@invana/canvas 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/events/EventEmitter.ts","../src/events/CanvasEvent.ts","../src/events/assertSerialisable.ts","../src/events/CanvasEventBus.ts","../src/events/SourceEmitter.ts","../src/state/Store.ts","../src/state/ColumnStore.ts","../src/state/DirtyBatcher.ts","../src/camera/Camera.ts","../src/layers/Layer.ts","../src/layers/WorldLayer.ts","../src/layers/ScreenLayer.ts","../src/layers/DevInfoLayer.ts","../src/layers/BackgroundLayer.ts","../src/layers/ThemedBackgroundLayer.ts","../src/layers/LayersPanelLayer.ts","../src/behaviours/Behaviour.ts","../src/behaviours/DragPanBehaviour.ts","../src/behaviours/DragShapeBehaviour.ts","../src/behaviours/WheelZoomBehaviour.ts","../src/behaviours/PinchZoomBehaviour.ts","../src/behaviours/KeyboardCameraInputBehaviour.ts","../src/behaviours/ElementSizeLODBehaviour.ts","../src/layouts/Layout.ts","../src/registries/LayerRegistry.ts","../src/registries/BehaviourRegistry.ts","../src/engine/Canvas.ts","../src/textures/TextureRegistry.ts","../src/hit/HitIndex.ts","../src/instancing/ShapeInstance.ts","../src/instancing/ConnectorInstance.ts","../src/primitives/base/PrimitiveBase.ts","../src/primitives/paint/insetContentLayer.ts","../src/primitives/base/ShapeBase.ts","../src/primitives/paint/applyFillStroke.ts","../src/primitives/paint/dashedStroke.ts","../src/primitives/shapes/CircleShape.ts","../src/primitives/shapes/RectShape.ts","../src/primitives/shapes/_polyUtils.ts","../src/primitives/shapes/PolygonShape.ts","../src/primitives/shapes/RegularPolygonShape.ts","../src/primitives/shapes/StarShape.ts","../src/primitives/shapes/ArcShape.ts","../src/primitives/paint/labelContent.ts","../src/primitives/shapes/CompositeShape.ts","../src/primitives/connectors/pathSampling.ts","../src/primitives/base/ConnectorBase.ts","../src/primitives/connectors/Connector.ts","../src/primitives/connectors/routers/straight.ts","../src/primitives/connectors/routers/orth.ts","../src/primitives/connectors/routers/_obstacleGrid.ts","../src/primitives/connectors/routers/_aStar.ts","../src/primitives/connectors/routers/manhattan.ts","../src/primitives/connectors/routers/metro.ts","../src/primitives/connectors/routers/er.ts","../src/primitives/connectors/routers/oneSide.ts","../src/primitives/connectors/pathStyles/normal.ts","../src/primitives/connectors/pathStyles/rounded.ts","../src/primitives/connectors/pathStyles/bezier.ts","../src/primitives/connectors/pathStyles/bumpRadial.ts","../src/primitives/connectors/pathStyles/bumpHorizontal.ts","../src/primitives/connectors/pathStyles/bundle.ts","../src/primitives/connectors/pathStyles/stepRadial.ts","../src/primitives/connectors/pathStyles/smooth.ts","../src/primitives/connectors/pathStyles/quadratic.ts","../src/primitives/connectors/pathStyles/loopCurve.ts","../src/primitives/connectors/pathStyles/loopPolyline.ts","../src/primitives/connectors/anchors/center.ts","../src/primitives/connectors/anchors/boundary.ts","../src/primitives/connectors/anchors/perpendicular.ts","../src/primitives/connectors/anchors/edgePort.ts","../src/primitives/connectors/anchors/silhouettePort.ts","../src/primitives/markers/ArrowMarker.ts","../src/primitives/base/ShapeDecorationBase.ts","../src/primitives/decorations/shape/GlowDecoration.ts","../src/primitives/decorations/shape/PulseRingDecoration.ts","../src/primitives/decorations/shape/LiquidFillDecoration.ts","../src/primitives/decorations/shape/MarchingAntsDecoration.ts","../src/primitives/decorations/shape/RingDecoration.ts","../src/primitives/base/ConnectorDecorationBase.ts","../src/primitives/decorations/connector/MarchingAntsConnectorDecoration.ts","../src/primitives/decorations/connector/FlyMarkerConnectorDecoration.ts","../src/primitives/decorations/connector/FlowParticlesConnectorDecoration.ts","../src/primitives/decorations/connector/GlowConnectorDecoration.ts","../src/primitives/decorations/connector/RippleConnectorDecoration.ts","../src/primitives/animation/easings.ts","../src/primitives/animation/Tween.ts","../src/primitives/decorations/connector/RevealConnectorDecoration.ts","../src/primitives/decorations/connector/RingConnectorDecoration.ts","../src/primitives/paint/labelBackground.ts","../src/primitives/decorations/shape/LabelDecoration.ts","../src/primitives/decorations/shape/ToggleDecoration.ts","../src/primitives/decorations/shape/ResizeHandleDecoration.ts","../src/primitives/decorations/shape/SelectionFrameDecoration.ts","../src/primitives/decorations/connector/LabelConnectorDecoration.ts","../src/primitives/base/EffectBase.ts","../src/primitives/effects/shape/ShakeEffect.ts","../src/primitives/effects/shape/BreathingEffect.ts","../src/primitives/base/ConnectorEffectBase.ts","../src/primitives/effects/connector/BreathingConnectorEffect.ts","../src/primitives/effects/connector/FadeInConnectorEffect.ts","../src/primitives/badges/placement.ts","../src/primitives/badges/connectorPlacement.ts","../src/primitives/PrimitivesRenderer.ts","../src/fonts/loadIconFont.ts"],"names":["sub","createZustandStore","Container","Graphics","resolveKind","DEFAULT_OPTIONS","g","n","len","tracePolygon","computeVertices","display","Text","a","b","DEFAULT_INFLATE","DEFAULT_STUB_LENGTH","DEFAULT_TENSION","DEFAULT_RADIUS","DEFAULT_SIDE","DEFAULT_BASE_OFFSET","sideToAngle","sx","sy","resolveAutoSide","width","clamp01","dx","dy","reversed","HIT_PADDING_PX","inflateRect","handleCentre","effectiveScale","resolveEasing","inst","distSq","exact"],"mappings":";;;;;;;;;AAsBO,IAAM,eAAN,MAAkD;AAAA;AAAA;AAAA,EAGtC,QAAA,uBAAyD,GAAA,EAAI;AAAA;AAAA;AAAA;AAAA,EAK9E,EAAA,CAAsB,OAAU,OAAA,EAAyC;AACvE,IAAA,IAAI,GAAA,GAAM,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,KAAK,CAAA;AACjC,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,GAAA,uBAAU,GAAA,EAAI;AACd,MAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,KAAA,EAAO,GAAG,CAAA;AAAA,IAC9B;AACA,IAAA,GAAA,CAAI,IAAI,OAAgC,CAAA;AACxC,IAAA,OAAO,MAAM,IAAA,CAAK,GAAA,CAAI,KAAA,EAAO,OAAO,CAAA;AAAA,EACtC;AAA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AAS,IAAA,CAAK,YAAY,IAAI,CAAA;AAAA,EAChC,CAAC,CAAA;AACH;AAEA,SAAS,UAAU,CAAA,EAAmB;AACpC,EAAA,IAAI,OAAO,GAAA,KAAQ,WAAA,IAAe,OAAO,GAAA,CAAI,WAAW,UAAA,EAAY,OAAO,GAAA,CAAI,MAAA,CAAO,CAAC,CAAA;AACvF,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,iBAAA,EAAmB,MAAM,CAAA;AAC5C","file":"index.js","sourcesContent":["/**\n * Typed event emitter — generic over an event-map shape.\n *\n * Used by `Canvas`, every `Layer`, every `Behaviour`, and the `ShapesRenderer`.\n * Hard-wired to play nicely with `CanvasEventBus.tap()` (see `events/CanvasEventBus.ts`)\n * but functions standalone.\n *\n * @example\n * type GraphLayerEvents = {\n * 'node:hover': { id: string };\n * 'selection:changed': { ids: ReadonlySet<string> };\n * };\n * const events = new EventEmitter<GraphLayerEvents>();\n * const off = events.on('node:hover', ({ id }) => console.log(id));\n * events.emit('node:hover', { id: 'n-42' });\n * off();\n */\n\nexport type EventMap = Record<string, unknown>;\n\nexport type EventHandler<TPayload> = (payload: TPayload) => void;\n\nexport class EventEmitter<E extends EventMap = EventMap> {\n // Map of event name → Set of handlers. Set keeps insertion order and\n // gives O(1) add/remove. Sets are reused across emit calls; never reallocated.\n private readonly handlers: Map<keyof E, Set<EventHandler<unknown>>> = new Map();\n\n /**\n * Subscribe to an event. Returns an unsubscribe function for ergonomic cleanup.\n */\n on<K extends keyof E>(event: K, handler: EventHandler<E[K]>): () => void {\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(handler as EventHandler<unknown>);\n return () => this.off(event, handler);\n }\n\n /**\n * Subscribe once. The handler fires at most once and auto-removes itself.\n * Returns an unsubscribe function in case you want to cancel before it fires.\n */\n once<K extends keyof E>(event: K, handler: EventHandler<E[K]>): () => void {\n const wrapped: EventHandler<E[K]> = (payload) => {\n this.off(event, wrapped);\n handler(payload);\n };\n return this.on(event, wrapped);\n }\n\n /**\n * Unsubscribe a specific handler.\n * No-op if the handler wasn't registered.\n */\n off<K extends keyof E>(event: K, handler: EventHandler<E[K]>): void {\n const set = this.handlers.get(event);\n if (!set) return;\n set.delete(handler as EventHandler<unknown>);\n if (set.size === 0) this.handlers.delete(event);\n }\n\n /**\n * Emit an event. Each registered handler is called synchronously in registration order.\n *\n * If a handler throws, the error is logged via `console.error` and subsequent\n * handlers still run. This prevents one buggy subscriber from breaking the\n * whole event chain. Errors are not re-thrown: subscribers should not be able\n * to crash unrelated code paths through the event bus.\n */\n emit<K extends keyof E>(event: K, payload: E[K]): void {\n const set = this.handlers.get(event);\n if (!set || set.size === 0) return;\n\n // Snapshot the handlers so a handler that mutates the set during iteration\n // (off/on inside a handler) doesn't break the loop.\n // Set iteration is otherwise mutation-safe in practice, but the spec is\n // permissive enough that a snapshot is the conservative choice.\n const snapshot = Array.from(set);\n for (const handler of snapshot) {\n try {\n (handler as EventHandler<E[K]>)(payload);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(`[EventEmitter] handler for event \"${String(event)}\" threw:`, err);\n }\n }\n }\n\n /**\n * Remove all listeners for one event, or all events if no event is given.\n */\n removeAllListeners(event?: keyof E): void {\n if (event === undefined) {\n this.handlers.clear();\n } else {\n this.handlers.delete(event);\n }\n }\n\n /**\n * Number of handlers registered for an event. Useful in tests.\n */\n listenerCount(event: keyof E): number {\n return this.handlers.get(event)?.size ?? 0;\n }\n}\n","/**\n * Telemetry envelope for events crossing into the canvas-wide tap channel.\n *\n * Architecture: see `architecture-proposal.md` §2.5.\n *\n * Two channels coexist:\n * - **Typed events** — clean payloads on the emitter you care about\n * (`canvas.events.on('camera:zoom', ...)`, `graphLayer.events.on('node:click', ...)`).\n * - **Tap channel** — a single firehose receiving an envelope for every event\n * emitted system-wide (`canvas.events.tap(handler)`). Telemetry sinks subscribe here.\n *\n * App code uses the first; observability uses the second.\n *\n * Type strings follow `<source-kind>:<source-id>:<event-name>` so a tap subscriber\n * can filter without inspecting `source` (e.g. `'layer:graph:node:click'`).\n */\n\nexport type EventSourceKind = 'canvas' | 'layer' | 'behaviour' | 'layout' | 'store';\n\nexport interface EventSource {\n readonly kind: EventSourceKind;\n readonly id: string;\n}\n\nexport interface CanvasEvent<TPayload = unknown> {\n readonly type: string; // e.g. 'layer:graph:node:click'\n readonly timestamp: number; // performance.now()\n readonly source: EventSource;\n readonly payload: TPayload;\n}\n\n/**\n * Build a `<source-kind>:<source-id>:<event-name>` envelope-type string.\n * Centralised so the convention can't drift.\n */\nexport function makeEventType(source: EventSource, name: string): string {\n return `${source.kind}:${source.id}:${name}`;\n}\n\n/**\n * Construct a CanvasEvent envelope. The source is captured by reference, but the\n * caller is expected to honour the rule that source ids are immutable for the\n * lifetime of the source — so reading the envelope's `source.id` later is safe.\n */\nexport function makeCanvasEvent<TPayload>(\n source: EventSource,\n name: string,\n payload: TPayload,\n): CanvasEvent<TPayload> {\n return {\n type: makeEventType(source, name),\n timestamp: performance.now(),\n source,\n payload,\n };\n}\n\n/**\n * Default exclude list for the tap channel.\n *\n * High-frequency events that would flood telemetry without adding signal.\n * Consumers can override per `tap()` registration:\n * `canvas.events.tap(fn, { exclude: [] })` — see everything.\n * `canvas.events.tap(fn, { exclude: ['canvas:camera:zoom'] })` — explicit override.\n *\n * The strings are matched as **suffixes** of the envelope `type` so we don't\n * have to enumerate every layer instance. `'pointermove'` excludes\n * `'layer:graph-1:shape:pointermove'`, `'layer:er-7:shape:pointermove'`, …\n */\nexport const DEFAULT_TAP_EXCLUDE: readonly string[] = Object.freeze([\n 'pointermove',\n 'render:tick',\n 'shape:pointermove',\n 'connector:pointermove',\n 'state:dirty-flush',\n]);\n\n/**\n * Returns true if the given envelope type should be excluded from the tap\n * channel under the supplied exclude list. Exclusion is suffix-based so\n * source-id variations don't require enumerating every emitter.\n */\nexport function isExcludedFromTap(\n type: string,\n exclude: readonly string[] = DEFAULT_TAP_EXCLUDE,\n): boolean {\n for (const pattern of exclude) {\n if (type.endsWith(pattern)) return true;\n }\n return false;\n}\n","/**\n * Dev-mode walker that asserts an event payload is serialisable.\n *\n * Architecture: see `architecture-proposal.md` §2.5 (Serialisability discipline).\n *\n * Once the canvas advertises `tap()` as telemetry-ready, payloads must be\n * serialisable: only ids, numbers, strings, plain objects, arrays, and\n * `Map`/`Set` containing the same. PixiJS objects, DOM nodes, function refs,\n * and class instances must NOT appear in payloads — they break:\n *\n * - JSON-based telemetry sinks (Datadog, log shippers)\n * - structured-clone-based sinks (BroadcastChannel, postMessage to workers)\n * - devtools time-travel\n * - test snapshots\n *\n * The walker is **dev-only**. The exported `assertSerialisable` is\n * unconditionally callable, but `assertSerialisableInDev` is the public\n * entry point that the bus uses — it inlines a build-time NODE_ENV check\n * so production bundlers tree-shake the entire walker out.\n *\n * @example violation log\n * [canvas] payload at 'node.shape' is not serialisable: BaseShape (class instance)\n */\n\nconst ALLOWED_CLASS_TAGS = new Set(['Object', 'Array', 'Map', 'Set']);\n\n/**\n * Walk `value`, returning a list of human-readable violation messages.\n * Empty array means \"fully serialisable\".\n *\n * The walker is iterative-ish: it uses recursion but with explicit cycle\n * detection so a self-referencing payload doesn't blow the stack.\n */\nexport function findSerialisationViolations(\n value: unknown,\n rootPath = '',\n): string[] {\n const violations: string[] = [];\n const seen = new WeakSet<object>();\n\n function walk(v: unknown, path: string): void {\n if (v === null || v === undefined) return;\n\n const t = typeof v;\n if (t === 'string' || t === 'number' || t === 'boolean') return;\n\n if (t === 'function') {\n violations.push(`${path || '<root>'} — function reference`);\n return;\n }\n\n if (t === 'symbol' || t === 'bigint') {\n violations.push(`${path || '<root>'} — ${t}`);\n return;\n }\n\n // Object-like from here on.\n const obj = v as object;\n\n if (seen.has(obj)) return; // cycle — already reported (or ignored)\n seen.add(obj);\n\n if (Array.isArray(obj)) {\n for (let i = 0; i < obj.length; i++) {\n walk(obj[i], `${path}[${i}]`);\n }\n return;\n }\n\n if (obj instanceof Map) {\n let i = 0;\n for (const [k, vv] of obj) {\n if (typeof k !== 'string' && typeof k !== 'number') {\n violations.push(`${path}.<map key #${i}> — non-primitive key (${typeof k})`);\n }\n walk(vv, `${path}.<map[${formatMapKey(k)}]>`);\n i++;\n }\n return;\n }\n\n if (obj instanceof Set) {\n let i = 0;\n for (const item of obj) {\n walk(item, `${path}.<set[${i}]>`);\n i++;\n }\n return;\n }\n\n // Detect specific non-serialisable kinds first for friendlier messages.\n const ctorName = obj.constructor?.name ?? '<anonymous>';\n if (\n typeof Element !== 'undefined' && obj instanceof Element\n ) {\n violations.push(`${path || '<root>'} — DOM Element (${ctorName})`);\n return;\n }\n if (typeof Node !== 'undefined' && obj instanceof Node) {\n violations.push(`${path || '<root>'} — DOM Node (${ctorName})`);\n return;\n }\n\n // A plain object (constructor === Object, or Object-tag) is serialisable.\n // Anything else (a class instance) is NOT — but we still walk its enumerable\n // own properties so a partially-bad payload still surfaces the bad branches.\n if (!ALLOWED_CLASS_TAGS.has(ctorName)) {\n violations.push(\n `${path || '<root>'} — class instance (${ctorName})`,\n );\n // fall through and walk own enumerable properties for completeness\n }\n\n for (const [k, vv] of Object.entries(obj)) {\n walk(vv, path ? `${path}.${k}` : k);\n }\n }\n\n walk(value, rootPath);\n return violations;\n}\n\nfunction formatMapKey(k: unknown): string {\n if (typeof k === 'string') return JSON.stringify(k);\n if (typeof k === 'number') return String(k);\n return `<${typeof k}>`;\n}\n\n/**\n * Convenience: assert a payload is serialisable. In dev, logs warnings via\n * `console.warn` for each violation (with offending path). In production,\n * compiles to a no-op via `process.env.NODE_ENV` substitution.\n *\n * Pass a `context` string so the warning includes which event triggered it,\n * e.g. `assertSerialisableInDev(payload, \"emit('node:click')\")`.\n */\nexport function assertSerialisableInDev(value: unknown, context: string): void {\n const proc = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process;\n if (proc?.env?.NODE_ENV === 'production') return;\n\n const violations = findSerialisationViolations(value);\n if (violations.length === 0) return;\n\n for (const v of violations) {\n // eslint-disable-next-line no-console\n console.warn(`[canvas] ${context}.payload.${v}`);\n }\n}\n","/**\n * `CanvasEventBus` — canvas-wide event hub with two channels:\n *\n * 1. **Typed canvas-wide events** (`on / emit`) — for things that genuinely\n * live at the canvas level: `layer:added`, `behaviour:enabled`,\n * `camera:zoom`, `renderer:initialised`, `background:click`, …\n *\n * 2. **Tap channel** (`tap`) — a single firehose subscription that receives\n * a `CanvasEvent` envelope for every event emitted system-wide\n * (canvas + every layer + every behaviour). Telemetry sinks register here\n * and see everything.\n *\n * Architecture: see `architecture-proposal.md` §2.5.\n *\n * **Why a tap channel and not bubbling?**\n *\n * | Aspect | Tap | Bubbling |\n * |---|---|---|\n * | App subscriptions | Clean — only what you ask for | Noisy — every layer's events at canvas |\n * | Telemetry hookup | One line, sees everything | Must enumerate every emitter |\n * | Sampling/filtering | At the tap, one place | Per-subscriber boilerplate |\n * | Payload shape | Plain payload + envelope | One shape for both audiences |\n *\n * **Forwarding pattern**\n *\n * Per-source emitters (`SourceEmitter`) hold an optional reference to the bus.\n * When they `emit(name, payload)`, they additionally call `bus.publish(envelope)`\n * which fan-outs to every tap subscriber (after exclude/sampleRate filtering).\n * Local subscribers see the plain payload; tap subscribers see the envelope.\n *\n * @example\n * const bus = new CanvasEventBus();\n *\n * // Telemetry sink — sees everything except the default high-frequency exclude list.\n * bus.tap((event) => sendToDatadog(event));\n *\n * // Dev-mode timeline — sees everything including pointermove.\n * bus.tap((event) => devLog.push(event), { exclude: [] });\n *\n * // Sampled sink — 10% of events.\n * bus.tap((event) => costlyAnalytics(event), { sampleRate: 0.1 });\n */\n\nimport { EventEmitter } from './EventEmitter';\nimport type { EventMap } from './EventEmitter';\nimport type { CanvasEvent, EventSource } from './CanvasEvent';\nimport { isExcludedFromTap, DEFAULT_TAP_EXCLUDE, makeCanvasEvent } from './CanvasEvent';\nimport { assertSerialisableInDev } from './assertSerialisable';\n\n/**\n * Default canvas-wide event map. Domain packages or the canvas implementation\n * can extend it via TypeScript module augmentation; for now we keep it open.\n *\n * Listed here are events that the canvas itself or its built-in primitives\n * emit. Additional event names get added as their producers land.\n */\nexport interface CanvasGlobalEvents extends EventMap {\n 'renderer:initialised': {\n backend: 'webgpu' | 'webgl' | 'canvas';\n capabilities?: Record<string, unknown>;\n };\n 'layer:added': { id: string };\n 'layer:removed': { id: string };\n 'behaviour:registered': { id: string };\n 'behaviour:enabled': { id: string };\n 'behaviour:disabled': { id: string };\n 'camera:zoom': { scale: number; centerX: number; centerY: number };\n 'camera:pan': { x: number; y: number };\n 'background:click': { worldX: number; worldY: number };\n 'tap:dropped': { type: string; reason: 'excluded' | 'sampled' };\n}\n\nexport type TapHandler = (event: CanvasEvent) => void;\n\nexport interface TapOptions {\n /**\n * Suffix-matched event-type strings to exclude. Defaults to\n * `DEFAULT_TAP_EXCLUDE` (high-frequency noise like `pointermove`,\n * `render:tick`). Pass `[]` to see everything.\n */\n exclude?: readonly string[];\n /**\n * 0..1. Probability that any given (non-excluded) event is delivered to\n * this tap. Default `1` (no sampling). Use for high-volume sinks.\n */\n sampleRate?: number;\n}\n\ninterface TapSubscription {\n handler: TapHandler;\n exclude: readonly string[];\n sampleRate: number;\n}\n\nexport interface CanvasEventBusOptions {\n /** Source identity for envelopes the bus publishes via its own `emit()`.\n * Default: `{ kind: 'canvas', id: 'canvas' }`. Override per Canvas instance. */\n source?: EventSource;\n}\n\nexport class CanvasEventBus extends EventEmitter<CanvasGlobalEvents> {\n private readonly taps: Set<TapSubscription> = new Set();\n private readonly source: EventSource;\n\n constructor(opts: CanvasEventBusOptions = {}) {\n super();\n this.source = opts.source ?? { kind: 'canvas', id: 'canvas' };\n }\n\n /**\n * Override of `EventEmitter.emit` so canvas-wide events ALSO reach the tap\n * channel (per `architecture-proposal.md` §2.5: \"every emitter — canvas,\n * layer, behaviour — auto-forwards an envelope to the tap\").\n *\n * Order: dev-mode serialisability check → local subscribers → tap publish.\n * A throwing local handler is isolated by `EventEmitter.emit`; a throwing\n * tap handler is isolated by `publish()`.\n */\n emit<K extends keyof CanvasGlobalEvents>(\n event: K,\n payload: CanvasGlobalEvents[K],\n ): void {\n assertSerialisableInDev(payload, `canvas.events.emit('${String(event)}')`);\n super.emit(event, payload);\n this.publish(makeCanvasEvent(this.source, String(event), payload));\n }\n\n /**\n * Subscribe to the tap channel. Returns an unsubscribe function.\n *\n * Default exclude: `DEFAULT_TAP_EXCLUDE` (high-frequency noise).\n * Default sampleRate: `1` (no sampling).\n *\n * Errors thrown by tap handlers are caught and logged via `console.error`,\n * just like local emitter handlers — one bad sink can't break the rest.\n */\n tap(handler: TapHandler, opts: TapOptions = {}): () => void {\n const sub: TapSubscription = {\n handler,\n exclude: opts.exclude ?? DEFAULT_TAP_EXCLUDE,\n sampleRate: opts.sampleRate ?? 1,\n };\n this.taps.add(sub);\n return () => {\n this.taps.delete(sub);\n };\n }\n\n /**\n * Publish an envelope to all tap subscribers. Called by `SourceEmitter`\n * (and by canvas-internal code that emits envelopes directly).\n *\n * Filtering applies per-tap:\n * - exclude list (suffix-match against event type)\n * - sampleRate\n *\n * No allocation per call other than what the handlers themselves do.\n */\n publish(event: CanvasEvent): void {\n if (this.taps.size === 0) return;\n\n for (const sub of this.taps) {\n if (isExcludedFromTap(event.type, sub.exclude)) continue;\n if (sub.sampleRate < 1 && Math.random() >= sub.sampleRate) continue;\n try {\n sub.handler(event);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(`[CanvasEventBus] tap handler threw on event \"${event.type}\":`, err);\n }\n }\n }\n\n /** Number of currently registered tap subscribers. Useful in tests. */\n tapCount(): number {\n return this.taps.size;\n }\n\n /** Drop all tap subscribers. Used on canvas teardown. */\n clearTaps(): void {\n this.taps.clear();\n }\n}\n","/**\n * `SourceEmitter` — typed event emitter that auto-forwards every emit to a\n * `CanvasEventBus.tap()` channel as a structured envelope.\n *\n * Architecture: see `architecture-proposal.md` §2.5.\n *\n * Each source (a `Layer`, a `Behaviour`, a `Layout`, the `Canvas` itself)\n * holds one of these. Local subscribers see the plain payload (`on(name, fn)`);\n * the bus's tap subscribers see the envelope (`{ type, timestamp, source, payload }`).\n *\n * The forward path is a single method call (`bus.publish(envelope)`). Tap\n * filtering (exclude / sampleRate) lives in the bus, not here, so the emit\n * cost stays constant whether 0 or 100 taps are subscribed.\n *\n * In dev, payloads are run through `assertSerialisableInDev` so violations\n * surface immediately with the offending path.\n *\n * @example\n * class GraphLayer {\n * readonly events: SourceEmitter<{ 'node:click': { id: string } }>;\n *\n * constructor(id: string, ctx: CanvasContext) {\n * this.events = new SourceEmitter({ kind: 'layer', id }, ctx.events);\n * }\n *\n * onShapeClick(id: string) {\n * // local handlers + bus tap, both fired:\n * this.events.emit('node:click', { id });\n * }\n * }\n */\n\nimport { EventEmitter } from './EventEmitter';\nimport type { EventHandler, EventMap } from './EventEmitter';\nimport type { CanvasEventBus } from './CanvasEventBus';\nimport type { EventSource } from './CanvasEvent';\nimport { makeCanvasEvent } from './CanvasEvent';\nimport { assertSerialisableInDev } from './assertSerialisable';\n\nexport class SourceEmitter<E extends EventMap = EventMap> extends EventEmitter<E> {\n /**\n * @param source — `{ kind: 'layer' | 'behaviour' | 'layout' | 'canvas' | 'store', id }`.\n * Identity of this emitter; used as the `source` field of each envelope.\n * @param bus — Optional. When present, every `emit()` also publishes a\n * `CanvasEvent` envelope to this bus's tap channel. Pass `undefined`\n * for emitters that should be local-only (rare; mostly tests).\n */\n private bus?: CanvasEventBus;\n\n constructor(private readonly source: EventSource, bus?: CanvasEventBus) {\n super();\n this.bus = bus;\n }\n\n /**\n * Attach (or detach) the bus this emitter forwards to.\n *\n * Use case: a `Layer` is constructed before it knows which `Canvas` it'll be\n * mounted on. The Layer creates its `SourceEmitter` upfront with no bus,\n * then `mount(ctx)` calls `events.setBus(ctx.events)` to start forwarding.\n * Pass `undefined` to detach (e.g. on unmount).\n */\n setBus(bus: CanvasEventBus | undefined): void {\n this.bus = bus;\n }\n\n /**\n * Emit to local subscribers AND publish to the bus's tap channel.\n * Order: local handlers run first (synchronous, in registration order),\n * then the envelope is published. A throwing local handler is caught\n * (logged via `console.error` per `EventEmitter`) and does not block the\n * tap publish.\n */\n emit<K extends keyof E>(event: K, payload: E[K]): void {\n // Dev-mode serialisability check. Stripped in production builds.\n assertSerialisableInDev(payload, `emit('${String(event)}')`);\n\n // Local subscribers — clean payload.\n super.emit(event, payload);\n\n // Bus tap — envelope.\n if (this.bus !== undefined) {\n this.bus.publish(makeCanvasEvent(this.source, String(event), payload));\n }\n }\n\n /** Convenience: source identity (read-only). */\n get sourceInfo(): EventSource {\n return this.source;\n }\n}\n\n// Re-export types so consumers can import in one line.\nexport type { EventHandler, EventMap };\n","/**\n * `Store<T>` — typed alias of `zustand/vanilla` `StoreApi<T>` plus a thin\n * factory that pre-composes the middleware stack we use everywhere.\n *\n * Architecture: see `architecture-proposal.md` §2.1 (state vs. data — bifurcated).\n *\n * **Use this only for small, observable interaction state** — hover, selection,\n * drag intent, decoration overrides, view modes. The cardinality should stay\n * comfortably below a few thousand items per slice; typical state size is\n * tens of fields, not megabytes.\n *\n * For bulk hot data (positions, attributes for tens of thousands or millions\n * of items), use `ColumnStore` instead. Immer + Map at 500k entries clones the\n * whole Map on every mutation (5–50 ms each); typed-array columns are 10 ns.\n *\n * Middleware stack (outer → inner):\n *\n * devtools → subscribeWithSelector → immer → state creator\n *\n * - **immer** lets recipes mutate a draft; the produced state is structurally\n * shared with the previous state (untouched branches kept by reference).\n * - **subscribeWithSelector** adds the `subscribe(selector, listener, opts?)`\n * overload so consumers can subscribe to a slice instead of the whole state.\n * - **devtools** is enabled only in non-production builds (Redux DevTools\n * extension). Tree-shaken / no-op in production.\n *\n * @example\n * type GraphLayerState = {\n * hoveredId: string | null;\n * selectedIds: ReadonlySet<string>;\n * haloIds: ReadonlySet<string>;\n * };\n *\n * const store = createLayerStore<GraphLayerState>(\n * { hoveredId: null, selectedIds: new Set(), haloIds: new Set() },\n * { name: 'GraphLayer:graph-1' }\n * );\n *\n * // immer-style mutation\n * store.setState((draft) => { draft.hoveredId = 'n-42'; });\n *\n * // selector subscription — fires only when haloIds changes\n * const off = store.subscribe(\n * (s) => s.haloIds,\n * (curr, prev) => { ... },\n * { equalityFn: Object.is }\n * );\n */\n\nimport { createStore as createZustandStore, type StoreApi } from 'zustand/vanilla';\nimport { subscribeWithSelector } from 'zustand/middleware';\nimport { immer } from 'zustand/middleware/immer';\nimport { devtools } from 'zustand/middleware';\nimport { enableMapSet } from 'immer';\n\n// Opt immer into drafting Map and Set values. UI state slices commonly carry\n// `selectedIds: Set<string>`, `haloStyles: Map<string, HaloStyle>`, etc.\n// Without this, immer throws on first Map/Set mutation. Idempotent.\nenableMapSet();\n\n/**\n * The store API surface exposed to consumers.\n *\n * After middleware composition, the runtime store has:\n * - `setState(recipe)` — immer recipe that mutates a draft (immer middleware).\n * - `setState(partial)` and `setState(updater)` — vanilla forms (still work).\n * - `subscribe(listener)` — vanilla zustand API.\n * - `subscribe(selector, listener, opts?)` — added by `subscribeWithSelector`.\n *\n * The `setState` overload union mirrors what the immer middleware produces at\n * runtime; `Store<T>` is what `createLayerStore<T>()` returns.\n */\nexport type Store<T> = Omit<StoreApi<T>, 'setState' | 'subscribe'> & {\n setState: {\n /** Immer recipe form — mutate the draft, return nothing. Preferred. */\n (recipe: (draft: T) => void): void;\n /** Direct partial / replacement / updater forms — also accepted. */\n (\n partial:\n | T\n | Partial<T>\n | ((state: T) => T | Partial<T> | void),\n replace?: false,\n ): void;\n /** Replace-state form (second arg = true). */\n (state: T, replace: true): void;\n };\n subscribe: StoreApi<T>['subscribe'] & {\n <U>(\n selector: (state: T) => U,\n listener: (selectedState: U, previousSelectedState: U) => void,\n options?: {\n equalityFn?: (a: U, b: U) => boolean;\n fireImmediately?: boolean;\n },\n ): () => void;\n };\n};\n\nexport interface CreateLayerStoreOptions {\n /**\n * Devtools display name. Used as the \"store\" name in Redux DevTools.\n * Convention: `<ClassName>:<id>` (e.g. `'GraphLayer:graph-1'`).\n */\n name?: string;\n\n /**\n * Force devtools on/off. Default: enabled when `process.env.NODE_ENV !== 'production'`.\n * High-frequency mutation sites can pass `enableDevtools: false` per-store\n * to avoid devtools serialisation cost in dev too.\n */\n enableDevtools?: boolean;\n}\n\n/**\n * Detect whether we're in a production build. Tree-shakers (esbuild, tsup,\n * Vite, webpack) replace `process.env.NODE_ENV` with the literal string at\n * build time, so this evaluates to a constant and the dev-only branches\n * are eliminated entirely.\n *\n * Accessed via `globalThis` to avoid requiring `@types/node` in this\n * browser-targeted package; in unbuilt Node contexts (vitest) the global\n * `process` is present.\n */\nfunction isProductionBuild(): boolean {\n const proc = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process;\n return proc?.env?.NODE_ENV === 'production';\n}\n\n/**\n * Create a `Store<T>` with our standard middleware stack.\n *\n * Pass either an initial state object, or a creator function that takes the\n * zustand `set` / `get` (already wrapped with immer) and returns initial state.\n * The creator form is useful when initial state needs to reference itself or\n * close over imperative setup; the object form is the common case.\n */\nexport function createLayerStore<T extends object>(\n initial: T,\n opts?: CreateLayerStoreOptions,\n): Store<T>;\nexport function createLayerStore<T extends object>(\n // The set / get types after immer middleware are intentionally loose here —\n // consumers rarely use the creator form, and a tighter signature would\n // require importing immer's mutator types.\n creator: (set: (recipe: (draft: T) => void) => void, get: () => T) => T,\n opts?: CreateLayerStoreOptions,\n): Store<T>;\nexport function createLayerStore<T extends object>(\n initialOrCreator:\n | T\n | ((set: (recipe: (draft: T) => void) => void, get: () => T) => T),\n opts: CreateLayerStoreOptions = {},\n): Store<T> {\n const initFn =\n typeof initialOrCreator === 'function'\n ? (initialOrCreator as (set: never, get: never) => T)\n : (() => initialOrCreator as T);\n\n // Cast through `any` here — composing zustand middleware preserves runtime\n // behaviour but the chained generic types become unwieldy. The publicly\n // returned type (`Store<T>`) is what consumers observe.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let creator: any = (set: never, get: never) => initFn(set, get);\n\n // Inner-to-outer middleware composition.\n creator = immer(creator);\n creator = subscribeWithSelector(creator);\n\n const wantDevtools = opts.enableDevtools ?? !isProductionBuild();\n if (wantDevtools) {\n creator = devtools(creator, { name: opts.name ?? 'CanvasStore' });\n }\n\n return createZustandStore(creator) as unknown as Store<T>;\n}\n\n/**\n * Re-export `StoreApi` for consumers who want the bare zustand type\n * (e.g. in third-party utility wrappers).\n */\nexport type { StoreApi };\n","/**\n * `ColumnStore<TSchema>` — typed-array column store for **bulk hot data**.\n *\n * Architecture: see `architecture-proposal.md` §2.1.\n *\n * Designed to scale to millions of items at machine-rate mutation (1000s/sec\n * from external feeds). Where `Store<T>` (zustand+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.\n *\n * **Mental model**\n *\n * One id-keyed object would be: `{ id: 'n-42', x: 100, y: 50, color: 0x... }`\n * In a ColumnStore that's: slot 17 across N parallel typed-array columns.\n *\n * Lookup goes id → slot (`Map<string, number>`), then any number of columns\n * are read/written by indexing slot. Slots are recycled when items are removed,\n * so the column buffers stay compact under churn.\n *\n * **Performance characteristics at 500k items**\n *\n * | Op | Cost |\n * |---|---|\n * | `add(id, row)` | ~100 ns (Map.set + N TypedArray writes) |\n * | `set(id, col, value)` | ~50 ns (Map.get + TypedArray write) |\n * | `column(name)[slot] = value` (fast-path) | ~10 ns (single TypedArray write) |\n * | `addBulk(rows)` for 500k | ~5–20 ms |\n * | Memory for 500k × 5 columns × 4 bytes | ~10 MB |\n *\n * Compare immer + Map<string, object> at 500k: ~5–50 ms per single-field\n * mutation (clones the entire 500k Map every time), ~150–250 MB memory.\n *\n * @example\n * type NodeSchema = { x: 'f32'; y: 'f32'; color: 'u32'; size: 'f32' };\n *\n * class GraphNodeStore extends ColumnStore<NodeSchema> {\n * constructor() {\n * super({ x: 'f32', y: 'f32', color: 'u32', size: 'f32' }, { initialCapacity: 1024 });\n * }\n * }\n *\n * const nodes = new GraphNodeStore();\n * nodes.add('n-1', { x: 10, y: 20, color: 0x3b82f6, size: 8 });\n * nodes.set('n-1', 'x', 30); // typesafe per-field setter\n *\n * // Renderer fast path — hold refs once, write directly:\n * const xCol = nodes.column('x');\n * const slot = nodes.slot('n-1')!;\n * xCol[slot] = 40; // ~10 ns per write\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 *\n * - `i8 / u8` — small integers (1 byte). Use for booleans, bitfields, packed enums.\n * - `i16 / u16` — medium integers (2 bytes). Use for short integer ids, type-tags.\n * - `i32 / u32` — large integers (4 bytes). Use for slot refs, packed colors, hashes.\n * - `f32` — single-precision floats (4 bytes). Default for coordinates, weights.\n * - `f64` — double-precision floats (8 bytes). Use only when precision matters.\n */\nexport type ColumnType =\n | 'i8'\n | 'u8'\n | 'i16'\n | 'u16'\n | 'i32'\n | 'u32'\n | 'f32'\n | 'f64';\n\nexport type ColumnSchema = Record<string, ColumnType>;\n\n// Map a `ColumnType` tag to the JS value type stored in that column.\n// All TypedArray slots round-trip as `number`.\nexport type ColumnValue<T extends ColumnType> = T extends 'f32' | 'f64'\n ? number\n : number;\n\n// Map a `ColumnType` tag to the 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 this.columns = {} as Record<keyof TSchema, unknown> as Record<\n keyof TSchema,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >;\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\n * the column is grown** (then the underlying buffer is replaced).\n *\n * Use the version field to detect grow events:\n * const v = store.version; const col = store.column('x');\n * // if (store.version !== v) the col reference may be stale\n *\n * Renderer fast path: cache `column(name)` and `slot(id)` once per frame\n * and write directly. Bump `touch()` after batched fast-path writes so\n * subscribers know.\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 /**\n * Add a new item. Throws if `id` already exists.\n * Reuses a recycled slot when available; otherwise extends (and grows).\n */\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 /**\n * Bulk add. Grows once if needed (cheaper than N individual grows).\n * Throws if any id already exists.\n */\n addBulk(items: ReadonlyArray<{ id: string; row: RowOf<TSchema> }>): void {\n if (items.length === 0) return;\n // Pre-grow to fit. We may end up with extra free slots if we recycle some;\n // worst case we over-allocate by `items.length`, which is fine.\n const projected = this.idIndex.size + items.length;\n if (projected > this._capacity) {\n this.grow(projected);\n }\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 /**\n * Set a single field. ~50 ns: Map.get + TypedArray write.\n * No-op if id doesn't exist.\n */\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 /**\n * Update multiple fields of one item in one call. Avoids N version bumps.\n */\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 /**\n * Remove an item. Recycles the slot. No-op if id doesn't exist.\n */\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 // Don't zero the column data — recycled slots overwrite on next add().\n // Saves a per-remove iteration over all columns.\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 actually changing anything via the API.\n * Use this after batches of fast-path writes via `column(...)[slot] = ...`\n * so version-bump-driven subscribers know to re-read.\n */\n touch(): void {\n this._version++;\n }\n\n /**\n * Drop all items and recycled slots. Keeps the current capacity (no shrink).\n * Cheap reset for repopulating from a feed.\n */\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 // Column data left in place; will be overwritten on next add().\n }\n\n // ─── Iteration ──────────────────────────────────────────────────────────\n\n /**\n * Iterate over (id, slot) pairs in insertion order of currently-live ids.\n * O(idIndex.size) — does NOT walk holes.\n */\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\n if (this._highWater >= this._capacity) {\n this.grow(this._capacity * 2);\n }\n return this._highWater++;\n }\n\n /**\n * Grow each column's TypedArray to at least `target` capacity.\n * Doubles past target until met (so we don't grow once per add in a tight loop).\n */\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(\n `ColumnStore: requested capacity ${target} exceeds max ${this.maxCapacity}`,\n );\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 * `DirtyBatcher<TBucket>` — accumulates \"this id changed\" signals between\n * frames, deduplicates them, and hands a per-frame snapshot to a flush callback.\n *\n * Architecture: see `architecture-proposal.md` §2.1 (Render projection).\n *\n * **Single responsibility:** absorb high-frequency dirty signals; nothing else.\n * No rendering, no PixiJS knowledge, no `requestAnimationFrame` of its own.\n * Canvas owns the single RAF (proposal §2.1) and calls `flush()` once per tick.\n *\n * **Performance properties (the contract that makes the architecture work)**\n *\n * - `mark(bucket, id)`: O(1) — Map.get + Set.add. No allocation in steady state.\n * - `markAll(bucket)`: O(1) — sets a flag.\n * - `flush()`: O(1) — Map swap, no copy.\n * - Per-frame work for the consumer is proportional to `changed` ids,\n * never total scene size.\n * - Sets are reused across frames (cleared after swap-out, not reallocated).\n * Zero GC pressure in steady state.\n *\n * **Double buffering & mid-flush mutations**\n *\n * `flush()` returns a snapshot whose Sets are the previous frame's accumulated\n * marks. The \"active\" Sets are swapped to the empty buffer, so any `mark()`\n * call made *during* the consumer's flush handler lands in the next frame's\n * bucket — never corrupts the iteration in flight, never loops.\n *\n * @example\n * type GraphDirty = 'shape' | 'halo' | 'edge';\n * const dirty = new DirtyBatcher<GraphDirty>();\n *\n * // anywhere — mutation site\n * dirty.mark('shape', 'n-42');\n *\n * // canvas tick\n * if (dirty.hasPending()) {\n * const snap = dirty.flush();\n * for (const id of snap.buckets.shape) renderer.updateShape(id, ...);\n * for (const id of snap.buckets.halo) renderer.setDecoration(id, 'halo', ...);\n * }\n */\n\n/**\n * The frozen snapshot handed to the flush handler.\n *\n * `buckets` is a ReadonlyMap keyed by bucket name; each value is the Set of\n * dirty ids for that bucket this frame. Buckets that have never been touched\n * are absent (use `snap.buckets.get(bucket) ?? EMPTY_SET` to handle missing).\n *\n * `rebuildAll` is the Set of buckets the consumer marked with `markAll()`.\n * For those buckets, the consumer should iterate the underlying data\n * (not the per-id Set) — usually meaning \"rebuild everything in this category.\"\n */\nexport interface DirtySnapshot<TBucket extends string = string> {\n readonly buckets: ReadonlyMap<TBucket, ReadonlySet<string>>;\n readonly rebuildAll: ReadonlySet<TBucket>;\n}\n\n/**\n * One side of the double buffer. Internal.\n */\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 // The currently-accumulating frame.\n private active: BatcherFrame<TBucket> = makeFrame<TBucket>();\n // The other half of the double buffer. Repurposed for the next frame\n // after `flush()` swaps and clears it.\n private buffer: BatcherFrame<TBucket> = makeFrame<TBucket>();\n\n /** True iff at least one mark has landed since the last flush. */\n private _dirty = false;\n\n /**\n * Mark a single id as dirty in a bucket. O(1), no allocation in steady state.\n *\n * Bucket Sets are created lazily on first mark and reused thereafter.\n * If the bucket is currently flagged `markAll`, this call is redundant\n * (consumer will iterate all data anyway) but cheap and harmless.\n */\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 /**\n * Flag a whole bucket as needing rebuild. The consumer's flush handler\n * should iterate its full data set for this bucket, ignoring the per-id Set.\n *\n * Use for bulk events: theme change, LOD swap, \"everything moved\",\n * data feed wholesale replace.\n */\n markAll(bucket: TBucket): void {\n this.active.rebuildAll.add(bucket);\n this._dirty = true;\n }\n\n /** Cheap check the canvas tick uses to decide whether to call `flush()`. */\n hasPending(): boolean {\n return this._dirty;\n }\n\n /**\n * Swap buffers and return the previous frame's snapshot. After this call:\n * - The returned snapshot is stable for the duration of the consumer's\n * handler (any new marks land in the freshly-cleared other buffer).\n * - `hasPending()` returns false until the next mark.\n *\n * The handed-out Sets are still owned by the batcher — the consumer must\n * **not retain references past the flush call**. The next `flush()` will\n * reuse and clear them.\n */\n flush(): DirtySnapshot<TBucket> {\n // Swap: outgoing snapshot = active; new active = buffer (which is empty).\n const outgoing = this.active;\n this.active = this.buffer;\n this.buffer = outgoing;\n this._dirty = false;\n\n // Pre-clear the new active frame so the next `mark()` finds it empty.\n // Note: we DON'T clear `outgoing` here — we hand it to the consumer first.\n // It gets cleared on the next `flush()` (when it returns to active service)\n // or right now if we want eager cleanup. We do eager cleanup AFTER returning\n // (no — actually we must do it before, since we return outgoing as-is).\n // Compromise: pre-clear new active *before* returning the snapshot. The\n // outgoing buffer is cleared on the FOLLOWING flush, when it cycles back.\n\n for (const set of this.active.buckets.values()) set.clear();\n this.active.rebuildAll.clear();\n\n return outgoing as unknown as DirtySnapshot<TBucket>;\n }\n\n /**\n * Drop both buffers. Call on layer unmount. After reset(), the batcher is\n * usable again from a clean state.\n */\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 // ─── Test/debug helpers ─────────────────────────────────────────────────\n\n /** Number of dirty ids in a bucket. Returns 0 if bucket has never been touched. */\n bucketSize(bucket: TBucket): number {\n return this.active.buckets.get(bucket)?.size ?? 0;\n }\n\n /** True iff the bucket has been flagged for rebuild this frame. */\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 * `Camera` — pan/zoom/projection facade over a `pixi-viewport` `Viewport`.\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 * - The Camera owns no input gestures — those live in opt-in camera-input\n * `Behaviour`s (proposal §2.6) which reach for `viewport.drag()`,\n * `viewport.wheel()`, etc. via the `viewport` accessor on this class.\n * - All transform math delegates to the underlying `Viewport`. Position/scale\n * on the Viewport `Container` is the single source of truth, so Camera\n * methods and Viewport plugins stay in sync automatically.\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 type { Viewport } from 'pixi-viewport';\nimport type { CanvasEventBus } from '../events/CanvasEventBus';\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface CameraOptions {\n /**\n * The `Viewport` instance the camera transforms. Created by `Canvas` and\n * attached to `app.stage` as the world root. Camera mutates its\n * `position` / `scale` directly via Viewport's typed methods.\n */\n viewport: Viewport;\n /** Initial viewport size in CSS pixels. Mirrors the Viewport's own `screenWidth`/`screenHeight` for projection math. */\n screenWidth: number;\n screenHeight: number;\n /** Optional bus for `camera:zoom` / `camera:pan` events. */\n bus?: CanvasEventBus;\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 underlying `pixi-viewport` `Viewport`. Public for engine internals\n * (camera-input behaviours that need `viewport.drag()` / `viewport.snap()`\n * / `viewport.animate()` etc.). Domain code should go through Camera's\n * typed methods (`pan`, `setZoom`, `toWorld`, ...) rather than touching\n * Viewport directly.\n */\n readonly viewport: Viewport;\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 constructor(opts: CameraOptions) {\n this.viewport = opts.viewport;\n this.bus = opts.bus;\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 const initialScale = this.clampScale(opts.initialScale ?? 1);\n this.viewport.scale.set(initialScale);\n this.viewport.position.set(opts.initialX ?? 0, opts.initialY ?? 0);\n\n // Bridge pixi-viewport's plugin-driven events to the canvas bus. Without\n // this, interactive pan/zoom (drag, wheel, pinch — all driven via\n // `viewport.drag()` / `viewport.wheel()` / etc. inside camera-input\n // behaviours) never reaches `camera:pan` / `camera:zoom` listeners,\n // because plugin-driven mutations bypass Camera's typed mutators.\n // Direct `.position.set` / `.scale.set` calls from this class don't\n // trigger viewport's 'moved' / 'zoomed', so we don't double-emit.\n this.viewport.on('moved', () => {\n this.bus?.emit('camera:pan', { x: this.viewport.position.x, y: this.viewport.position.y });\n });\n this.viewport.on('zoomed', () => {\n this.bus?.emit('camera:zoom', {\n scale: this.viewport.scale.x,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('camera:pan', { x: this.viewport.position.x, y: this.viewport.position.y });\n });\n }\n\n // ─── Read accessors ──────────────────────────────────────────────────────\n\n /** Current uniform scale. */\n get scale(): number {\n return this.viewport.scale.x;\n }\n\n /** Current world-container x in screen pixels. (Where world (0,0) sits.) */\n get x(): number {\n return this.viewport.position.x;\n }\n\n get y(): number {\n return this.viewport.position.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 if (x === this.x && y === this.y) return;\n this.viewport.position.set(x, y);\n this.bus?.emit('camera:pan', { x, y });\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 * 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 const next = this.clampScale(scale);\n if (next === this.scale) return;\n // `setZoom(scale, true)` keeps the world centre under the screen centre.\n this.viewport.setZoom(next, true);\n this.bus?.emit('camera:zoom', {\n scale: next,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('camera:pan', { x: this.x, y: this.y });\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 * Viewport has no built-in arbitrary-anchor zoom, so we do the math here:\n * project the anchor to world, change scale, then translate so the same\n * 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 const before = this.toWorld(centerX, centerY);\n const nextScale = this.clampScale(this.scale * factor);\n if (nextScale === this.scale) return;\n this.viewport.scale.set(nextScale);\n this.viewport.position.set(\n centerX - before.x * nextScale,\n centerY - before.y * nextScale,\n );\n this.bus?.emit('camera:zoom', { scale: nextScale, centerX, centerY });\n this.bus?.emit('camera:pan', { x: this.x, y: this.y });\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, padding = 24): void {\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.viewport.scale.set(next);\n this.viewport.position.set(tx, ty);\n\n this.bus?.emit('camera:zoom', {\n scale: next,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('camera:pan', { x: tx, y: ty });\n }\n\n /** Update on viewport resize. Forwards to Viewport so its hit-area + plugin math stays correct. */\n resize(screenWidth: number, screenHeight: number): void {\n this._screenWidth = screenWidth;\n this._screenHeight = screenHeight;\n this.viewport.resize(screenWidth, screenHeight);\n }\n\n // ─── Projection ──────────────────────────────────────────────────────────\n\n /** Screen → world. */\n toWorld(screenX: number, screenY: number): Point {\n const p = this.viewport.toWorld<Point>(screenX, screenY);\n return { x: p.x, y: p.y };\n }\n\n /** World → screen. */\n toScreen(worldX: number, worldY: number): Point {\n const p = this.viewport.toScreen<Point>(worldX, worldY);\n return { x: p.x, y: p.y };\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 const r = this.viewport.getVisibleBounds();\n return { x: r.x, y: r.y, width: r.width, height: r.height };\n }\n\n // ─── Internal ────────────────────────────────────────────────────────────\n\n /**\n * Advance viewport plugins that animate over time (decelerate, snap, etc.).\n * Called by `Canvas.tickOnce()` every frame. No-op until a camera-input\n * behaviour enables a plugin that uses `update()`.\n */\n tick(dt: number): void {\n this.viewport.update(dt);\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 * `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 (`Store<T>` zustand+immer; small, observable).\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 '../context/CanvasContext';\nimport type { EventMap } from '../events/EventEmitter';\nimport { SourceEmitter } from '../events/SourceEmitter';\nimport { createLayerStore, type Store } from '../state/Store';\nimport { DirtyBatcher, type DirtySnapshot } from '../state/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 mount(ctx: CanvasContext): void;\n unmount(): void;\n flush(): void;\n hasPending(): boolean;\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 /** Optional: name shown in devtools. Default `'<ClassName>:<id>'`. */\n devtoolsName?: string;\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 readonly options: TOptions;\n readonly state: Store<TState>;\n readonly events: SourceEmitter<TEvents>;\n readonly dirty: DirtyBatcher<TDirtyBucket>;\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 /** 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 lives on the layer for its full lifetime. Created via the\n // `createState()` hook so subclass generic types flow through cleanly.\n this.state = createLayerStore<TState>(this.createState(), {\n name: opts.devtoolsName ?? `${this.constructor.name}:${opts.id}`,\n });\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 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(undefined);\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 // ─── 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 * `WorldLayer` — abstract base for layers that live in **world coordinate space**.\n *\n * Architecture: see `architecture-proposal.md` §2.1.\n *\n * - Camera-affected: pans / zooms with the camera.\n * - Owns a root pixi `Container` (RenderGroup) attached to `surfaces.world`.\n * - `hitTest(worldX, worldY)` — input is in world coordinates.\n *\n * Subclasses call `this.createGraphics(label?)` or `this.createContainer(label?)`\n * to add pixi display objects, and override `onMount(ctx)` to wire up renderers.\n * For stacked draw-order (e.g. edges below nodes), use separate Layer instances.\n *\n * The type-distinct `hitTest` signature (vs. `ScreenLayer`'s) is what stops\n * consumers passing screen coords to a world layer or vice versa.\n */\n\nimport { Container, Graphics } from 'pixi.js';\nimport type { CanvasContext } from '../context/CanvasContext';\nimport type { EventMap } from '../events/EventEmitter';\nimport { Layer, type LayerOptions } from './Layer';\n\nexport interface WorldLayerHit {\n /** Whatever the subclass chooses to return — a node id, a sub-region, etc. */\n readonly id: string;\n readonly subId?: string;\n readonly kind?: string;\n}\n\nexport abstract class WorldLayer<\n TOptions = unknown,\n TState extends object = object,\n TEvents extends EventMap = EventMap,\n TDirtyBucket extends string = string,\n THit extends WorldLayerHit = WorldLayerHit,\n> extends Layer<TOptions, TState, TEvents, TDirtyBucket> {\n /** Backing field — assigned in `mount`, cleared in `unmount`. */\n protected _container?: Container;\n\n /**\n * Root pixi `Container` (RenderGroup) for this layer. Available from\n * `onMount(ctx)` for the layer's lifetime. Throws before mount / after unmount.\n *\n * Pass to `ShapesRenderer` as the `container` option when wiring up a renderer\n * inside `onMount`. Subclass-only — not part of the external layer API.\n */\n protected get container(): Container {\n if (!this._container) {\n throw new Error(`WorldLayer \"${this.id}\" container accessed before mount`);\n }\n return this._container;\n }\n\n constructor(opts: LayerOptions<TOptions>) {\n super(opts);\n }\n\n override mount(ctx: CanvasContext): void {\n // Build the root container BEFORE calling `super.mount(ctx)` so that\n // `onMount(ctx)` (invoked by `Layer.mount`) can rely on `this.container`.\n const root = new Container({ isRenderGroup: true });\n root.label = this.id;\n if (this.zIndex !== 0) {\n root.zIndex = this.zIndex;\n ctx.world.sortableChildren = true;\n }\n root.visible = this.visible;\n ctx.world.addChild(root);\n this._container = root;\n super.mount(ctx);\n }\n\n /** Keep the pixi container in sync when `layer.visible` is toggled. */\n protected override onVisibleChange(value: boolean): void {\n if (this._container) this._container.visible = value;\n }\n\n override unmount(): void {\n if (!this.mounted) return;\n super.unmount();\n this._container?.destroy({ children: true });\n this._container = undefined;\n }\n\n /**\n * Create a pixi `Graphics` attached to this layer's root container. The\n * sanctioned way for layer authors to obtain a `Graphics` for direct\n * painting via `@invana/canvas/draw` primitives — keeps pixi internal\n * (no `new Graphics()` in user code).\n */\n createGraphics(label?: string): Graphics {\n const g = new Graphics();\n if (label) g.label = label;\n this.container.addChild(g);\n return g;\n }\n\n /**\n * Create a plain pixi `Container` attached to this layer's root container.\n * Useful as a parent for mounted display objects (e.g. text sprites).\n */\n createContainer(label?: string): Container {\n const c = new Container();\n if (label) c.label = label;\n this.container.addChild(c);\n return c;\n }\n\n /**\n * Update this layer's z-order relative to its peers. Keeps the iteration\n * field (`this.zIndex`, used by `LayerRegistry.byZOrder()`) and the pixi\n * container's `zIndex` in sync, and flips `surfaces.world` into sorted mode\n * so the change renders.\n */\n setZIndex(z: number): void {\n this.zIndex = z;\n if (this._container) {\n this._container.zIndex = z;\n const parent = this._container.parent;\n if (parent) parent.sortableChildren = true;\n }\n }\n\n /**\n * Return the world-space AABB of everything currently rendered on this layer.\n * Delegates to Pixi's `getLocalBounds()` — a one-shot scene-graph traversal.\n * Suitable for \"fit to content\" calls; do not call every frame.\n */\n getBounds(): { x: number; y: number; width: number; height: number } {\n const b = this.container.getLocalBounds();\n return { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY };\n }\n\n /**\n * Hit-test in world coordinates. Returns the topmost hit or `null`.\n * Concrete layers implement this against their own data + spatial index.\n *\n * The `Canvas`-level hit-test orchestration (top-down by z-order, stop on\n * first hit, screen-layers-before-world per proposal Q6) calls this.\n */\n abstract hitTest(worldX: number, worldY: number): THit | null;\n}\n","/**\n * `ScreenLayer` — abstract base for layers that live in **screen / viewport coordinate space**.\n *\n * Architecture: see `architecture-proposal.md` §2.1.\n *\n * - Viewport-fixed: NOT camera-affected. Pans / zooms do not transform it.\n * - Owns a root pixi `Container` attached directly to `ctx.stage`.\n * Plain `Container` (not a RenderGroup) — screen-space content is typically\n * lightweight HUD-style rendering that doesn't need its own GPU batch boundary.\n * - `hitTest(screenX, screenY)` — input is in screen pixels.\n *\n * Examples: `MiniMapLayer`, `DevInfoLayer`, HUD, tool palettes.\n *\n * The type-distinct `hitTest` signature (vs. `WorldLayer`'s) is what stops\n * consumers passing world coords to a screen layer or vice versa.\n */\n\nimport { Container, Graphics } from 'pixi.js';\nimport type { CanvasContext } from '../context/CanvasContext';\nimport type { EventMap } from '../events/EventEmitter';\nimport { Layer, type LayerOptions } from './Layer';\n\nexport interface ScreenLayerHit {\n readonly id: string;\n readonly subId?: string;\n readonly kind?: string;\n}\n\nexport abstract class ScreenLayer<\n TOptions = unknown,\n TState extends object = object,\n TEvents extends EventMap = EventMap,\n TDirtyBucket extends string = string,\n THit extends ScreenLayerHit = ScreenLayerHit,\n> extends Layer<TOptions, TState, TEvents, TDirtyBucket> {\n /** Backing field — assigned in `mount`, cleared in `unmount`. */\n protected _container?: Container;\n\n /**\n * Root pixi `Container` for this screen-space layer. Available from\n * `onMount(ctx)` for the layer's lifetime. Throws before mount / after unmount.\n *\n * Subclass-only — not part of the external layer API.\n */\n protected get container(): Container {\n if (!this._container) {\n throw new Error(`ScreenLayer \"${this.id}\" container accessed before mount`);\n }\n return this._container;\n }\n\n constructor(opts: LayerOptions<TOptions>) {\n super(opts);\n }\n\n override mount(ctx: CanvasContext): void {\n // Build the root container BEFORE calling `super.mount(ctx)` so that\n // `onMount(ctx)` can rely on `this.container`.\n const root = new Container();\n root.label = this.id;\n if (this.zIndex !== 0) {\n root.zIndex = this.zIndex;\n ctx.stage.sortableChildren = true;\n }\n root.visible = this.visible;\n ctx.stage.addChild(root);\n this._container = root;\n super.mount(ctx);\n }\n\n /** Keep the pixi container in sync when `layer.visible` is toggled. */\n protected override onVisibleChange(value: boolean): void {\n if (this._container) this._container.visible = value;\n }\n\n override unmount(): void {\n if (!this.mounted) return;\n super.unmount();\n this._container?.destroy({ children: true });\n this._container = undefined;\n }\n\n /**\n * Create a pixi `Graphics` attached to this layer's root container. The\n * sanctioned way for layer authors to obtain a `Graphics` for direct\n * painting via `@invana/canvas/draw` primitives.\n */\n createGraphics(label?: string): Graphics {\n const g = new Graphics();\n if (label) g.label = label;\n this.container.addChild(g);\n return g;\n }\n\n /**\n * Create a plain pixi `Container` attached to this layer's root container.\n * Useful as a parent for mounted display objects.\n */\n createContainer(label?: string): Container {\n const c = new Container();\n if (label) c.label = label;\n this.container.addChild(c);\n return c;\n }\n\n /**\n * Update this layer's z-order relative to its peers. Keeps the iteration\n * field (`this.zIndex`) and the pixi container's `zIndex` in sync, and\n * flips `ctx.stage` into sorted mode so the change renders.\n */\n setZIndex(z: number): void {\n this.zIndex = z;\n if (this._container) {\n this._container.zIndex = z;\n const parent = this._container.parent;\n if (parent) parent.sortableChildren = true;\n }\n }\n\n /** Hit-test in screen / viewport coordinates. Top-most hit or `null`. */\n abstract hitTest(screenX: number, screenY: number): THit | null;\n}\n","/**\n * `DevInfoLayer` — developer overlay that continuously displays:\n * - Canvas display size\n * - Camera position (x, y) and zoom scale\n * - Visible world bounds\n * - Pointer position (screen and world coords)\n * - Frame rate (FPS)\n *\n * Implemented as a `ScreenLayer` whose visible artifact is a plain\n * absolutely-positioned HTML `<div>` layered above the canvas (so it never\n * interferes with pointer events on the scene). The pixi `container` from\n * `ScreenLayer` is unused — overlay rendering is pure DOM.\n *\n * Headless / offscreen mode: when `ctx.canvasElement` is undefined (i.e.\n * `Canvas.initWithStage`), the layer mounts cleanly but renders nothing.\n *\n * @example\n * ```ts\n * import { DevInfoLayer } from '@invana/canvas/toolkit';\n *\n * const devInfo = new DevInfoLayer({ corner: 'top-right' });\n * canvas.layers.add(devInfo);\n *\n * // Toggle at runtime\n * devInfo.setEnabled(false);\n * ```\n */\n\nimport { ScreenLayer, type ScreenLayerHit } from './ScreenLayer';\n\n// ─── Public types ────────────────────────────────────────────────────────────\n\nexport type DevInfoCorner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\nexport interface DevInfoLayerOptions {\n /** Which corner to anchor the overlay. Default: 'bottom-left' */\n corner?: DevInfoCorner;\n /** Show the overlay. Can be toggled at runtime via setEnabled(). Default: true */\n enabled?: boolean;\n /** Font size in px. Default: 11 */\n fontSize?: number;\n /** Panel opacity 0–1. Default: 0.92 */\n opacity?: number;\n /** Overlay background CSS color. Default: 'rgba(10,10,10,0.82)' */\n backgroundColor?: string;\n /** Text color. Default: '#c8d3e0' */\n textColor?: string;\n /** Accent / header color. Default: '#4fc3f7' */\n accentColor?: string;\n}\n\nexport interface DevInfoLayerCtorOptions extends DevInfoLayerOptions {\n /** Layer id. Default: 'dev-info'. */\n id?: string;\n /** Pixi z-index inside the screen stage. Default: 9999 (top). */\n zIndex?: number;\n}\n\n// ─── Defaults ────────────────────────────────────────────────────────────────\n\nconst DEFAULT_OPTIONS: Required<DevInfoLayerOptions> = {\n corner: 'bottom-left',\n enabled: true,\n fontSize: 11,\n opacity: 0.92,\n backgroundColor: 'rgba(10,10,10,0.82)',\n textColor: '#c8d3e0',\n accentColor: '#4fc3f7',\n};\n\n// ─── Implementation ──────────────────────────────────────────────────────────\n\ninterface DevInfoState {\n enabled: boolean;\n}\n\nexport class DevInfoLayer extends ScreenLayer<DevInfoLayerOptions, DevInfoState> {\n private _opts: Required<DevInfoLayerOptions>;\n private _overlay: HTMLDivElement | null = null;\n\n // Tracked state — updated by events\n private _pointerScreen = { x: 0, y: 0 };\n private _pointerWorld = { x: 0, y: 0 };\n private _onPointerMove: ((e: PointerEvent) => void) | null = null;\n\n // Unsubscribers for ctx.events listeners\n private _unsubs: Array<() => void> = [];\n\n // FPS tracking\n private _rafId: number | null = null;\n private _fps = 0;\n private _frameCount = 0;\n private _lastFpsTimestamp = 0;\n\n constructor(opts: DevInfoLayerCtorOptions = {}) {\n const { id, zIndex, ...rest } = opts;\n super({\n id: id ?? 'dev-info',\n options: rest,\n zIndex: zIndex ?? 9999,\n hittable: false,\n cullable: false,\n });\n this._opts = { ...DEFAULT_OPTIONS, ...rest };\n }\n\n protected override createState(): DevInfoState {\n return { enabled: true };\n }\n\n // ── ScreenLayer hit-testing ────────────────────────────────────────────────\n\n /** Overlay is DOM with `pointer-events:none` — never participates in hit-testing. */\n override hitTest(_screenX: number, _screenY: number): ScreenLayerHit | null {\n return null;\n }\n\n // ── Lifecycle ──────────────────────────────────────────────────────────────\n\n protected override onMount(): void {\n if (this._opts.enabled) {\n this._mountOverlay();\n }\n }\n\n protected override onUnmount(): void {\n this._stopFpsTicker();\n this._unmountOverlay();\n }\n\n // ── Public API ─────────────────────────────────────────────────────────────\n\n /** Show or hide the overlay at runtime without removing the layer. */\n setEnabled(enabled: boolean): void {\n if (enabled) this.enable();\n else this.disable();\n }\n\n enable(): void {\n this._opts.enabled = true;\n if (this.mounted && !this._overlay) this._mountOverlay();\n }\n\n disable(): void {\n this._opts.enabled = false;\n this._stopFpsTicker();\n this._unmountOverlay();\n }\n\n /** Update display options (corner, colors, font size, …) at runtime. */\n setOptions(partial: Partial<DevInfoLayerOptions>): void {\n this._opts = { ...this._opts, ...partial };\n if (this._overlay) {\n this._applyStyles();\n this._update();\n }\n }\n\n // ── Mount / unmount the DOM overlay ────────────────────────────────────────\n\n private _mountOverlay(): void {\n const ctx = this.context;\n const canvasEl = ctx.canvasElement;\n if (!canvasEl) return; // headless / initWithStage\n\n const parent = canvasEl.parentElement;\n if (!parent) return;\n\n // Ensure the parent is a positioning context for absolute children.\n if (window.getComputedStyle(parent).position === 'static') {\n parent.style.position = 'relative';\n }\n\n const div = document.createElement('div');\n div.dataset['devInfoLayer'] = this.id;\n this._overlay = div;\n this._applyStyles();\n parent.appendChild(div);\n\n // Camera updates → repaint overlay.\n this._unsubs.push(ctx.events.on('camera:pan', () => this._update()));\n this._unsubs.push(ctx.events.on('camera:zoom', () => this._update()));\n\n // Native pointermove — engine doesn't emit a typed `pointermove` event,\n // so read DOM coords directly and convert via camera.\n this._onPointerMove = (e: PointerEvent) => {\n const rect = canvasEl.getBoundingClientRect();\n const sx = e.clientX - rect.left;\n const sy = e.clientY - rect.top;\n this._pointerScreen = { x: sx, y: sy };\n this._pointerWorld = ctx.camera.toWorld(sx, sy);\n this._update();\n };\n canvasEl.addEventListener('pointermove', this._onPointerMove);\n\n // FPS counter — 500ms bucket.\n this._lastFpsTimestamp = performance.now();\n this._startFpsTicker();\n\n this._update();\n }\n\n private _unmountOverlay(): void {\n for (const unsub of this._unsubs) unsub();\n this._unsubs = [];\n\n if (this._onPointerMove && this.ctx?.canvasElement) {\n this.ctx.canvasElement.removeEventListener('pointermove', this._onPointerMove);\n }\n this._onPointerMove = null;\n\n this._overlay?.remove();\n this._overlay = null;\n }\n\n // ── Styles ─────────────────────────────────────────────────────────────────\n\n private _applyStyles(): void {\n if (!this._overlay) return;\n const { corner, fontSize, opacity, backgroundColor, textColor } = this._opts;\n\n const position: Record<DevInfoCorner, string> = {\n 'top-left': 'top:10px; left:10px;',\n 'top-right': 'top:10px; right:10px;',\n 'bottom-left': 'bottom:10px; left:10px;',\n 'bottom-right': 'bottom:10px; right:10px;',\n };\n\n this._overlay.style.cssText = [\n 'position:absolute;',\n position[corner],\n `font-size:${fontSize}px;`,\n `opacity:${opacity};`,\n `background:${backgroundColor};`,\n `color:${textColor};`,\n 'font-family:\"SF Mono\",\"Fira Code\",\"Cascadia Code\",\"Courier New\",monospace;',\n 'padding:8px 12px;',\n 'border-radius:6px;',\n 'line-height:1.65;',\n 'pointer-events:none;',\n 'z-index:9999;',\n 'white-space:pre;',\n 'min-width:230px;',\n 'border:1px solid rgba(255,255,255,0.08);',\n 'box-shadow:0 4px 16px rgba(0,0,0,0.5);',\n 'user-select:none;',\n ].join('');\n }\n\n // ── FPS ticker ─────────────────────────────────────────────────────────────\n\n private _startFpsTicker(): void {\n const tick = (now: number) => {\n this._frameCount++;\n const elapsed = now - this._lastFpsTimestamp;\n if (elapsed >= 500) {\n this._fps = Math.round((this._frameCount / elapsed) * 1000);\n this._frameCount = 0;\n this._lastFpsTimestamp = now;\n this._update();\n }\n this._rafId = requestAnimationFrame(tick);\n };\n this._rafId = requestAnimationFrame(tick);\n }\n\n private _stopFpsTicker(): void {\n if (this._rafId !== null) {\n cancelAnimationFrame(this._rafId);\n this._rafId = null;\n }\n }\n\n // ── Render ─────────────────────────────────────────────────────────────────\n\n private _update(): void {\n if (!this._overlay || !this.ctx) return;\n const ctx = this.ctx;\n const canvasEl = ctx.canvasElement;\n if (!canvasEl) return;\n\n const { accentColor } = this._opts;\n const cam = ctx.camera;\n const bounds = cam.getVisibleBounds();\n\n const w = canvasEl.clientWidth || canvasEl.width;\n const h = canvasEl.clientHeight || canvasEl.height;\n\n const sep = `<span style=\"color:${accentColor};opacity:0.5\">${'─'.repeat(28)}</span>`;\n const header = (label: string) =>\n `<span style=\"color:${accentColor};font-weight:bold\"> ${label}</span>`;\n const row = (label: string, value: string) =>\n ` <span style=\"opacity:0.6\">${label.padEnd(12)}</span>${value}`;\n\n const lines = [\n header('DEV INFO'),\n sep,\n header('Canvas'),\n row('size', `${w} × ${h} px`),\n sep,\n header('Camera'),\n row('x', n(cam.x)),\n row('y', n(cam.y)),\n row('zoom', `${cam.scale.toFixed(3)}×`),\n sep,\n header('World Bounds'),\n row('x (left)', n(bounds.x)),\n row('y (top)', n(bounds.y)),\n row('right', n(bounds.x + bounds.width)),\n row('bottom', n(bounds.y + bounds.height)),\n row('width', n(bounds.width)),\n row('height', n(bounds.height)),\n sep,\n header('Pointer'),\n row('screen', `${n(this._pointerScreen.x)}, ${n(this._pointerScreen.y)}`),\n row('world', `${n(this._pointerWorld.x)}, ${n(this._pointerWorld.y)}`),\n sep,\n header('Performance'),\n row('fps', String(this._fps)),\n ];\n\n this._overlay.innerHTML = lines.join('\\n');\n }\n}\n\n// ─── helpers ─────────────────────────────────────────────────────────────────\n\n/** Format a number to 1 decimal place, right-aligned in 9 chars. */\nfunction n(value: number): string {\n return value.toFixed(1).padStart(9);\n}\n","/**\n * `BackgroundLayer` — solid colour or tiled pattern fill behind the world.\n *\n * Architecture: see `architecture-proposal.md` §2.1.\n *\n * Implemented as a `ScreenLayer` for two practical reasons:\n *\n * 1. The pattern needs to cover the *viewport*, not the world bounds. A\n * WorldLayer would require sizing an infinite rectangle.\n * 2. `TilingSprite` lets us mimic camera-following cheaply by adjusting\n * `tileScale` + `tilePosition` on each pan/zoom — no per-frame geometry\n * rebuild needed.\n *\n * When `followCamera` is `true` (default), the pattern shifts and scales with\n * the camera so the background feels like part of the world (\"graph paper\").\n * When `false`, the pattern is fixed to the screen.\n *\n * @example\n * ```ts\n * canvas.layers.add(new BackgroundLayer({\n * id: 'bg',\n * options: { type: 'pattern', patternType: 'dots', backgroundColor: 0x0f172a },\n * }));\n * ```\n */\n\nimport { Graphics, Texture, TilingSprite } from 'pixi.js';\n\nimport type { CanvasContext } from '../context/CanvasContext';\nimport { ScreenLayer, type ScreenLayerHit } from './ScreenLayer';\nimport type { LayerOptions } from './Layer';\n\n/** Top-level background style. `'solid'` skips the pattern texture entirely. */\nexport type BackgroundType = 'solid' | 'pattern';\n\n/** Pattern texture kind. */\nexport type BackgroundPatternType = 'dots' | 'grid' | 'lines';\n\n/**\n * Mode selector for light/dark colour resolution. `'auto'` follows the host's\n * `prefers-color-scheme` media query; `'light'` / `'dark'` pin explicitly.\n */\nexport type BackgroundMode = 'auto' | 'light' | 'dark';\n\n/** The concrete kind currently being rendered after mode resolution. */\nexport type BackgroundKind = 'light' | 'dark';\n\n/**\n * A colour input. Pass a `number` / CSS string for a single colour, or a\n * `{ light, dark }` pair to swap based on the layer's `mode`.\n */\nexport type BackgroundColor =\n | number\n | string\n | { light: number | string; dark: number | string };\n\n/** Construction-time options for `BackgroundLayer`. */\nexport interface BackgroundLayerOptions {\n /** `'solid'` paints a flat fill; `'pattern'` overlays a tiled texture. Default `'solid'`. */\n type?: BackgroundType;\n /** Tile texture kind when `type === 'pattern'`. Default `'dots'`. */\n patternType?: BackgroundPatternType;\n /**\n * Pattern foreground colour (dot / line / grid colour). Accepts `0xRRGGBB`,\n * a CSS string, or a `{ light, dark }` pair resolved against `mode`.\n */\n color?: BackgroundColor;\n /** Solid-fill colour painted behind the pattern. Same accepted forms as `color`. */\n backgroundColor?: BackgroundColor;\n /** Dot radius / line thickness, in *texture pixels*. Default `1`. */\n size?: number;\n /** Tile cell spacing, in *texture pixels*. Default `12`. */\n spacing?: number;\n /** Pattern alpha 0–1. Default `0.6`. */\n alpha?: number;\n /**\n * `true` (default): pattern shifts + scales with the camera. `false`: pattern\n * stays fixed to the screen regardless of camera state.\n */\n followCamera?: boolean;\n /**\n * How `{ light, dark }` colour variants are resolved. `'auto'` (default)\n * follows `prefers-color-scheme`; `'light'` / `'dark'` pin explicitly. Has\n * no effect when both colours are plain scalars.\n */\n mode?: BackgroundMode;\n}\n\nconst DEFAULTS: Required<BackgroundLayerOptions> = {\n type: 'solid',\n patternType: 'dots',\n color: '#6f7b8b',\n backgroundColor: '#f8fafc',\n size: 1,\n spacing: 12,\n alpha: 0.6,\n followCamera: true,\n mode: 'auto',\n};\n\ninterface BackgroundLayerState {\n readonly _placeholder?: never;\n}\n\n/** Normalise a colour input into a hex string suitable for the canvas 2D ctx. */\nfunction colorToCss(c: number | string): string {\n if (typeof c === 'number') return `#${c.toString(16).padStart(6, '0')}`;\n return c;\n}\n\nexport class BackgroundLayer extends ScreenLayer<\n BackgroundLayerOptions,\n BackgroundLayerState,\n Record<string, never>,\n never,\n ScreenLayerHit\n> {\n private opts: Required<BackgroundLayerOptions>;\n private tiling: TilingSprite | null = null;\n private patternTexture: Texture | null = null;\n /** DPR baked into the current pattern texture — used to compensate `tileScale`. */\n private textureDpr = window.devicePixelRatio || 1;\n private resizeObserver: ResizeObserver | null = null;\n private offCameraPan: (() => void) | null = null;\n private offCameraZoom: (() => void) | null = null;\n private modeMediaQuery: MediaQueryList | null = null;\n private modeMediaListener: ((e: MediaQueryListEvent) => void) | null = null;\n\n // Cached camera state used by tile-transform sync.\n private camX = 0;\n private camY = 0;\n private camScale = 1;\n\n constructor(opts: LayerOptions<BackgroundLayerOptions>) {\n super({\n ...opts,\n // Background sits below everything by default. Caller can override.\n zIndex: opts.zIndex ?? -1000,\n // Always render — viewport-culling is meaningless for a full-screen background.\n cullable: opts.cullable ?? false,\n // Not hittable by default; the world's `background:click` already covers it.\n hittable: opts.hittable ?? false,\n });\n this.opts = { ...DEFAULTS, ...opts.options };\n }\n\n protected createState(): BackgroundLayerState {\n return {};\n }\n\n protected override onMount(ctx: CanvasContext): void {\n // Seed cached camera state — events may not have fired yet if the camera\n // is at a non-default initial position when this layer mounts.\n this.camX = ctx.camera.x;\n this.camY = ctx.camera.y;\n this.camScale = ctx.camera.scale;\n\n this.render();\n this.wireModeMediaQuery();\n\n this.offCameraPan = ctx.events.on('camera:pan', ({ x, y }) => {\n this.camX = x;\n this.camY = y;\n this.syncTileTransform();\n });\n this.offCameraZoom = ctx.events.on('camera:zoom', ({ scale }) => {\n // `centerX/centerY` is the screen-space zoom anchor — *not* the\n // world-origin screen position — so we only consume the new scale here.\n // The accompanying `camera:pan` emission (always paired with zoom)\n // updates `camX/camY` to the post-zoom origin offset.\n this.camScale = scale;\n this.syncTileTransform();\n });\n\n if (typeof ResizeObserver !== 'undefined' && ctx.canvasElement) {\n this.resizeObserver = new ResizeObserver(() => this.render());\n this.resizeObserver.observe(ctx.canvasElement);\n }\n }\n\n protected override onUnmount(): void {\n this.detachModeMediaQuery();\n this.offCameraPan?.();\n this.offCameraZoom?.();\n this.offCameraPan = null;\n this.offCameraZoom = null;\n this.resizeObserver?.disconnect();\n this.resizeObserver = null;\n this.patternTexture?.destroy(true);\n this.patternTexture = null;\n this.tiling = null;\n }\n\n /**\n * Hit tests on the background always miss — clicks fall through to the\n * world layer beneath, which is what users expect for a bg.\n */\n hitTest(): ScreenLayerHit | null {\n return null;\n }\n\n // ─── Public API ─────────────────────────────────────────────────────────\n\n /** Merge-update options + re-render. */\n setOptions(changes: Partial<BackgroundLayerOptions>): void {\n this.opts = { ...this.opts, ...changes };\n if (this.mounted) {\n this.wireModeMediaQuery();\n this.render();\n }\n }\n\n /** Snapshot of the resolved options. */\n getOptions(): Required<BackgroundLayerOptions> {\n return { ...this.opts };\n }\n\n /**\n * Set the colour-resolution mode. `'auto'` re-arms the system listener;\n * `'light'` / `'dark'` pin explicitly. No-op when mode is unchanged.\n */\n setMode(mode: BackgroundMode): void {\n if (this.opts.mode === mode) return;\n this.opts = { ...this.opts, mode };\n if (this.mounted) {\n this.wireModeMediaQuery();\n this.render();\n }\n }\n\n /** Current mode setting. */\n getMode(): BackgroundMode {\n return this.opts.mode;\n }\n\n /** Concrete kind currently being rendered after mode resolution. */\n getResolvedKind(): BackgroundKind {\n return resolveKind(this.opts.mode);\n }\n\n // ─── Internals ──────────────────────────────────────────────────────────\n\n private viewportSize(): { width: number; height: number } {\n const el = this.context.canvasElement;\n if (el) return { width: el.clientWidth || 800, height: el.clientHeight || 600 };\n return { width: 800, height: 600 };\n }\n\n private render(): void {\n // Drop previous render contents.\n this.container.removeChildren();\n this.tiling = null;\n this.patternTexture?.destroy(true);\n this.patternTexture = null;\n\n const { width, height } = this.viewportSize();\n\n const bg = new Graphics();\n bg.rect(0, 0, width, height).fill(this.resolveColor(this.opts.backgroundColor));\n this.container.addChild(bg);\n\n if (this.opts.type === 'solid') return;\n\n const texture = this.createPatternTexture();\n const tiling = new TilingSprite({ texture, width, height });\n tiling.alpha = this.opts.alpha;\n this.container.addChild(tiling);\n this.patternTexture = texture;\n this.tiling = tiling;\n this.syncTileTransform();\n }\n\n private syncTileTransform(): void {\n if (!this.tiling) return;\n // Texture is rasterised at `textureDpr` device pixels per CSS pixel; we\n // divide `tileScale` by it so on-screen pattern size stays in CSS-pixel\n // units regardless of display density.\n const dpr = this.textureDpr;\n if (!this.opts.followCamera) {\n this.tiling.tileScale.set(1 / dpr, 1 / dpr);\n this.tiling.tilePosition.set(0, 0);\n return;\n }\n const s = this.camScale;\n this.tiling.tileScale.set(s / dpr, s / dpr);\n // Modulo keeps the offset small so we don't accumulate float drift over\n // long pans. The pattern is periodic at `spacing * scale` px (in screen\n // pixels — independent of DPR, since the period is texture_size * tileScale).\n const period = this.opts.spacing * s;\n this.tiling.tilePosition.set(this.camX % period, this.camY % period);\n }\n\n private createPatternTexture(): Texture {\n const { patternType, color, size, spacing } = this.opts;\n // Rasterise the tile at device-pixel density so dots / lines stay crisp on\n // retina / scaled displays. `tileScale` compensates so the on-screen size\n // is still expressed in CSS pixels.\n const dpr =\n typeof window !== 'undefined' && typeof window.devicePixelRatio === 'number'\n ? Math.max(1, window.devicePixelRatio)\n : 1;\n this.textureDpr = dpr;\n\n const off = document.createElement('canvas');\n off.width = Math.round(spacing * dpr);\n off.height = Math.round(spacing * dpr);\n const ctx2d = off.getContext('2d')!;\n ctx2d.scale(dpr, dpr);\n ctx2d.fillStyle = colorToCss(this.resolveColor(color));\n\n switch (patternType) {\n case 'dots':\n ctx2d.beginPath();\n ctx2d.arc(spacing / 2, spacing / 2, size, 0, Math.PI * 2);\n ctx2d.fill();\n break;\n case 'grid':\n ctx2d.fillRect(0, 0, spacing, size);\n ctx2d.fillRect(0, 0, size, spacing);\n break;\n case 'lines':\n ctx2d.fillRect(0, 0, spacing, size);\n break;\n }\n\n return Texture.from(off);\n }\n\n private resolveColor(c: BackgroundColor): number | string {\n if (typeof c === 'number' || typeof c === 'string') return c;\n return this.getResolvedKind() === 'dark' ? c.dark : c.light;\n }\n\n private hasVariantColor(): boolean {\n return isVariant(this.opts.color) || isVariant(this.opts.backgroundColor);\n }\n\n private wireModeMediaQuery(): void {\n // Only listen when we're actually following the system AND at least one\n // colour has a `{ light, dark }` shape — avoids wasted listeners.\n if (this.opts.mode !== 'auto' || !this.hasVariantColor()) {\n this.detachModeMediaQuery();\n return;\n }\n if (this.modeMediaQuery) return;\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;\n this.modeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n this.modeMediaListener = () => {\n if (this.mounted) this.render();\n };\n this.modeMediaQuery.addEventListener('change', this.modeMediaListener);\n }\n\n private detachModeMediaQuery(): void {\n if (this.modeMediaQuery && this.modeMediaListener) {\n this.modeMediaQuery.removeEventListener('change', this.modeMediaListener);\n }\n this.modeMediaQuery = null;\n this.modeMediaListener = null;\n }\n}\n\nfunction isVariant(\n c: BackgroundColor,\n): c is { light: number | string; dark: number | string } {\n return typeof c === 'object' && c !== null;\n}\n\nfunction resolveKind(mode: BackgroundMode): BackgroundKind {\n if (mode === 'light' || mode === 'dark') return mode;\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return 'light';\n return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n}\n","/**\n * `ThemedBackgroundLayer` — `BackgroundLayer` extended with named themes and\n * a light / dark / auto mode.\n *\n * Each theme bundles both a `light` and `dark` variant. The layer's `mode`\n * picks which variant renders: `'light'` and `'dark'` pin explicitly, while\n * `'auto'` follows the host's `prefers-color-scheme` media query.\n *\n * Theme switches and mode flips fire layer-scoped events so app-level UI\n * (theme picker, mode toggle) can react.\n *\n * @example\n * ```ts\n * canvas.layers.add(new ThemedBackgroundLayer({\n * id: 'bg',\n * options: {\n * themes: [\n * {\n * id: 'graph-paper',\n * light: { type: 'pattern', patternType: 'dots', backgroundColor: '#f8fafc', color: '#94a3b8' },\n * dark: { type: 'pattern', patternType: 'dots', backgroundColor: '#0f172a', color: '#475569' },\n * },\n * ],\n * mode: 'auto',\n * },\n * }));\n * ```\n */\n\nimport type { CanvasContext } from '../context/CanvasContext';\nimport type { LayerOptions } from './Layer';\nimport { BackgroundLayer, type BackgroundLayerOptions } from './BackgroundLayer';\n\n/**\n * Mode selector. `'auto'` follows `prefers-color-scheme`; `'light'` / `'dark'`\n * pin explicitly.\n */\nexport type ThemedBackgroundMode = 'auto' | 'light' | 'dark';\n\n/** The concrete variant currently being rendered after mode resolution. */\nexport type ThemedBackgroundKind = 'light' | 'dark';\n\n/** A named look bundling both a light and dark variant. */\nexport interface ThemedBackgroundTheme {\n /** Stable identifier — referenced by `setTheme(id)` and `defaultTheme`. */\n id: string;\n /** Optional human-friendly label for UIs. */\n label?: string;\n /** Style applied when the resolved kind is `'light'`. */\n light: BackgroundLayerOptions;\n /** Style applied when the resolved kind is `'dark'`. */\n dark: BackgroundLayerOptions;\n}\n\n/** Construction-time options for `ThemedBackgroundLayer`. */\nexport interface ThemedBackgroundLayerOptions {\n /** Named themes. Must contain at least one entry. */\n themes: ThemedBackgroundTheme[];\n /** Id of the theme to start with. Defaults to `themes[0].id`. */\n defaultTheme?: string;\n /** Initial mode. Defaults to `'auto'`. */\n mode?: ThemedBackgroundMode;\n}\n\n/** Layer-event map fired by `ThemedBackgroundLayer.events`. */\nexport interface ThemedBackgroundLayerEvents {\n 'theme:switched': {\n theme: ThemedBackgroundTheme;\n resolvedKind: ThemedBackgroundKind;\n source: 'initial' | 'manual';\n };\n 'mode:updated': {\n mode: ThemedBackgroundMode;\n previousMode: ThemedBackgroundMode;\n resolvedKind: ThemedBackgroundKind;\n source: 'manual' | 'system';\n };\n [event: string]: unknown;\n}\n\ninterface ThemedBackgroundLayerState {\n readonly _placeholder?: never;\n}\n\nexport class ThemedBackgroundLayer extends BackgroundLayer {\n private readonly themes: ThemedBackgroundTheme[];\n private activeId: string;\n private currentMode: ThemedBackgroundMode;\n\n private mediaQuery: MediaQueryList | null = null;\n private mediaListener: ((e: MediaQueryListEvent) => void) | null = null;\n\n // We override the base typed-events surface with one that carries the\n // themed-specific names. The base ScreenLayer narrows EventMap = never;\n // we re-type via cast since EventEmitter is generic-erased at runtime.\n declare readonly events: import('../events/EventEmitter').EventEmitter<ThemedBackgroundLayerEvents> &\n BackgroundLayer['events'];\n\n constructor(opts: LayerOptions<ThemedBackgroundLayerOptions>) {\n const { themes, defaultTheme, mode } = opts.options;\n\n if (!themes || themes.length === 0) {\n throw new Error(\n `ThemedBackgroundLayer \"${opts.id}\": 'themes' must contain at least one entry.`,\n );\n }\n for (const t of themes) {\n if (!t.light || !t.dark) {\n throw new Error(\n `ThemedBackgroundLayer \"${opts.id}\": theme '${t.id}' must define both 'light' and 'dark' variants.`,\n );\n }\n }\n const startId = defaultTheme ?? themes[0]!.id;\n if (!themes.some((t) => t.id === startId)) {\n throw new Error(\n `ThemedBackgroundLayer \"${opts.id}\": unknown defaultTheme id '${startId}'.`,\n );\n }\n\n // Seed the base BackgroundLayer with the resolved variant so the very\n // first render matches the active theme + mode.\n const initialMode = mode ?? 'auto';\n const initialTheme = themes.find((t) => t.id === startId)!;\n const initialKind = resolveKind(initialMode);\n const initialVariant = initialKind === 'dark' ? initialTheme.dark : initialTheme.light;\n\n super({\n id: opts.id,\n options: initialVariant,\n visible: opts.visible,\n hittable: opts.hittable,\n zIndex: opts.zIndex,\n cullable: opts.cullable,\n devtoolsName: opts.devtoolsName,\n });\n\n this.themes = themes;\n this.activeId = startId;\n this.currentMode = initialMode;\n }\n\n protected override createState(): ThemedBackgroundLayerState {\n return {};\n }\n\n protected override onMount(ctx: CanvasContext): void {\n super.onMount(ctx);\n this.wireMediaQuery();\n this.emitThemeSwitched('initial');\n }\n\n protected override onUnmount(): void {\n this.detachMediaQuery();\n super.onUnmount();\n }\n\n // ─── Public API ─────────────────────────────────────────────────────────\n\n /**\n * Switch to a theme by id. Mode is preserved. Throws on unknown id.\n * Emits `'theme:switched'`.\n */\n setTheme(id: string): void {\n if (!this.themes.some((t) => t.id === id)) {\n throw new Error(`ThemedBackgroundLayer \"${this.id}\": unknown theme id '${id}'.`);\n }\n if (id === this.activeId) return;\n this.activeId = id;\n this.applyResolved();\n this.emitThemeSwitched('manual');\n }\n\n /**\n * Set the mode. `'auto'` re-arms the system listener; `'light'` / `'dark'`\n * pin explicitly. Emits `'mode:updated'` when the mode actually changes.\n */\n setMode(mode: ThemedBackgroundMode): void {\n if (mode === this.currentMode) return;\n const previous = this.currentMode;\n this.currentMode = mode;\n if (mode === 'auto') this.wireMediaQuery();\n else this.detachMediaQuery();\n this.applyResolved();\n this.emitModeUpdated(previous, 'manual');\n }\n\n /** Currently active theme. */\n getActiveTheme(): ThemedBackgroundTheme {\n return this.themes.find((t) => t.id === this.activeId)!;\n }\n\n /** Current mode setting. */\n getMode(): ThemedBackgroundMode {\n return this.currentMode;\n }\n\n /** Concrete kind currently being rendered. */\n getResolvedKind(): ThemedBackgroundKind {\n return resolveKind(this.currentMode);\n }\n\n /** Snapshot of the configured themes. */\n getThemes(): readonly ThemedBackgroundTheme[] {\n return this.themes;\n }\n\n // ─── Internals ──────────────────────────────────────────────────────────\n\n private applyResolved(): void {\n const theme = this.getActiveTheme();\n const variant = this.getResolvedKind() === 'dark' ? theme.dark : theme.light;\n this.setOptions(variant);\n }\n\n private emitThemeSwitched(source: 'initial' | 'manual'): void {\n this.events.emit('theme:switched', {\n theme: this.getActiveTheme(),\n resolvedKind: this.getResolvedKind(),\n source,\n });\n }\n\n private emitModeUpdated(\n previousMode: ThemedBackgroundMode,\n source: 'manual' | 'system',\n ): void {\n this.events.emit('mode:updated', {\n mode: this.currentMode,\n previousMode,\n resolvedKind: this.getResolvedKind(),\n source,\n });\n }\n\n private wireMediaQuery(): void {\n if (this.currentMode !== 'auto') {\n this.detachMediaQuery();\n return;\n }\n if (this.mediaQuery) return;\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;\n\n this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n this.mediaListener = () => {\n if (this.currentMode !== 'auto') return;\n // System flip: rendered variant changes, `mode` itself is unchanged.\n // Still emit so listeners that watch `resolvedKind` get the signal.\n this.applyResolved();\n this.emitModeUpdated(this.currentMode, 'system');\n };\n this.mediaQuery.addEventListener('change', this.mediaListener);\n }\n\n private detachMediaQuery(): void {\n if (this.mediaQuery && this.mediaListener) {\n this.mediaQuery.removeEventListener('change', this.mediaListener);\n }\n this.mediaQuery = null;\n this.mediaListener = null;\n }\n}\n\n/** Standalone kind resolver — shared between constructor seed + runtime. */\nfunction resolveKind(mode: ThemedBackgroundMode): ThemedBackgroundKind {\n if (mode === 'light' || mode === 'dark') return mode;\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return 'light';\n return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n}\n","/**\n * `LayersPanelLayer` — developer overlay that lists every layer currently\n * mounted on the canvas and exposes a checkbox per row to toggle that\n * layer's `visible` flag.\n *\n * Implemented as a `ScreenLayer` whose visible artifact is a plain\n * absolutely-positioned HTML `<div>` layered above the canvas — same pattern\n * as `DevInfoLayer`. Unlike `DevInfoLayer`, the overlay receives pointer\n * events (so the checkboxes are clickable); the layer itself still opts out\n * of engine hit-testing via `hittable: false`.\n *\n * The panel re-renders on `'layer:added'` / `'layer:removed'`. The panel's\n * own row is filtered out so the user can't hide it via itself.\n *\n * Headless / offscreen mode: when `ctx.canvasElement` is undefined (i.e.\n * `Canvas.initWithStage`), the layer mounts cleanly but renders nothing.\n *\n * @example\n * ```ts\n * import { LayersPanelLayer } from '@invana/canvas';\n *\n * const panel = new LayersPanelLayer({ corner: 'top-right' });\n * canvas.layers.add(panel);\n *\n * // Toggle the panel itself at runtime\n * panel.setEnabled(false);\n * ```\n */\n\nimport { ScreenLayer, type ScreenLayerHit } from './ScreenLayer';\n\n// ─── Public types ────────────────────────────────────────────────────────────\n\nexport type LayersPanelCorner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\nexport interface LayersPanelLayerOptions {\n /** Which corner to anchor the overlay. Default: 'top-right' */\n corner?: LayersPanelCorner;\n /** Show the overlay. Toggle at runtime via setEnabled(). Default: true */\n enabled?: boolean;\n /** Font size in px. Default: 11 */\n fontSize?: number;\n /** Panel opacity 0–1. Default: 0.92 */\n opacity?: number;\n /** Overlay background CSS color. Default: 'rgba(10,10,10,0.82)' */\n backgroundColor?: string;\n /** Text color. Default: '#c8d3e0' */\n textColor?: string;\n /** Accent / header color. Default: '#4fc3f7' */\n accentColor?: string;\n /**\n * Layer ids to hide from the list. The panel's own id is always hidden\n * regardless of this option.\n */\n hideIds?: readonly string[];\n}\n\nexport interface LayersPanelLayerCtorOptions extends LayersPanelLayerOptions {\n /** Layer id. Default: 'layers-panel'. */\n id?: string;\n /** Pixi z-index inside the screen stage. Default: 9998 (just below DevInfoLayer). */\n zIndex?: number;\n}\n\n// ─── Defaults ────────────────────────────────────────────────────────────────\n\nconst DEFAULT_OPTIONS: Required<Omit<LayersPanelLayerOptions, 'hideIds'>> & {\n hideIds: readonly string[];\n} = {\n corner: 'top-right',\n enabled: true,\n fontSize: 11,\n opacity: 0.92,\n backgroundColor: 'rgba(10,10,10,0.82)',\n textColor: '#c8d3e0',\n accentColor: '#4fc3f7',\n hideIds: [],\n};\n\n// ─── Implementation ──────────────────────────────────────────────────────────\n\ninterface LayersPanelState {\n enabled: boolean;\n}\n\nexport class LayersPanelLayer extends ScreenLayer<LayersPanelLayerOptions, LayersPanelState> {\n private _opts: typeof DEFAULT_OPTIONS;\n private _overlay: HTMLDivElement | null = null;\n private _onChange: ((e: Event) => void) | null = null;\n\n // Unsubscribers for ctx.events listeners.\n private _unsubs: Array<() => void> = [];\n\n constructor(opts: LayersPanelLayerCtorOptions = {}) {\n const { id, zIndex, ...rest } = opts;\n super({\n id: id ?? 'layers-panel',\n options: rest,\n zIndex: zIndex ?? 9998,\n hittable: false,\n cullable: false,\n });\n this._opts = { ...DEFAULT_OPTIONS, ...rest };\n }\n\n protected override createState(): LayersPanelState {\n return { enabled: true };\n }\n\n // ── ScreenLayer hit-testing ────────────────────────────────────────────────\n\n /** Overlay is DOM — never participates in the engine's hit-testing. */\n override hitTest(_screenX: number, _screenY: number): ScreenLayerHit | null {\n return null;\n }\n\n // ── Lifecycle ──────────────────────────────────────────────────────────────\n\n protected override onMount(): void {\n if (this._opts.enabled) {\n this._mountOverlay();\n }\n }\n\n protected override onUnmount(): void {\n this._unmountOverlay();\n }\n\n // ── Public API ─────────────────────────────────────────────────────────────\n\n /** Show or hide the panel at runtime without removing the layer. */\n setEnabled(enabled: boolean): void {\n if (enabled) this.enable();\n else this.disable();\n }\n\n enable(): void {\n this._opts.enabled = true;\n if (this.mounted && !this._overlay) this._mountOverlay();\n }\n\n disable(): void {\n this._opts.enabled = false;\n this._unmountOverlay();\n }\n\n /** Update display options (corner, colors, font size, …) at runtime. */\n setOptions(partial: Partial<LayersPanelLayerOptions>): void {\n this._opts = { ...this._opts, ...partial };\n if (this._overlay) {\n this._applyStyles();\n this._render();\n }\n }\n\n /**\n * Force a re-render of the panel. Call this if external code mutates\n * `layer.visible` on a registered layer and you want the checkboxes to\n * reflect the new state. (The engine does not emit an event for visibility\n * mutations.)\n */\n refresh(): void {\n if (this._overlay) this._render();\n }\n\n // ── Mount / unmount the DOM overlay ────────────────────────────────────────\n\n private _mountOverlay(): void {\n const ctx = this.context;\n const canvasEl = ctx.canvasElement;\n if (!canvasEl) return; // headless / initWithStage\n\n const parent = canvasEl.parentElement;\n if (!parent) return;\n\n if (window.getComputedStyle(parent).position === 'static') {\n parent.style.position = 'relative';\n }\n\n const div = document.createElement('div');\n div.dataset['layersPanelLayer'] = this.id;\n this._overlay = div;\n this._applyStyles();\n parent.appendChild(div);\n\n // Re-render when the layer set changes.\n this._unsubs.push(ctx.events.on('layer:added', () => this._render()));\n this._unsubs.push(ctx.events.on('layer:removed', () => this._render()));\n\n // Single delegated change listener for all checkboxes.\n this._onChange = (e: Event) => {\n const target = e.target as HTMLElement | null;\n if (!target || target.tagName !== 'INPUT') return;\n const input = target as HTMLInputElement;\n const layerId = input.dataset['layerId'];\n if (!layerId || !this.ctx) return;\n const layer = this.ctx.layers.get(layerId);\n if (layer) layer.visible = input.checked;\n };\n div.addEventListener('change', this._onChange);\n\n this._render();\n }\n\n private _unmountOverlay(): void {\n for (const unsub of this._unsubs) unsub();\n this._unsubs = [];\n\n if (this._onChange && this._overlay) {\n this._overlay.removeEventListener('change', this._onChange);\n }\n this._onChange = null;\n\n this._overlay?.remove();\n this._overlay = null;\n }\n\n // ── Styles ─────────────────────────────────────────────────────────────────\n\n private _applyStyles(): void {\n if (!this._overlay) return;\n const { corner, fontSize, opacity, backgroundColor, textColor } = this._opts;\n\n const position: Record<LayersPanelCorner, string> = {\n 'top-left': 'top:10px; left:10px;',\n 'top-right': 'top:10px; right:10px;',\n 'bottom-left': 'bottom:10px; left:10px;',\n 'bottom-right': 'bottom:10px; right:10px;',\n };\n\n this._overlay.style.cssText = [\n 'position:absolute;',\n position[corner],\n `font-size:${fontSize}px;`,\n `opacity:${opacity};`,\n `background:${backgroundColor};`,\n `color:${textColor};`,\n 'font-family:\"SF Mono\",\"Fira Code\",\"Cascadia Code\",\"Courier New\",monospace;',\n 'padding:8px 12px;',\n 'border-radius:6px;',\n 'line-height:1.5;',\n 'pointer-events:auto;',\n 'z-index:9998;',\n 'width:260px;',\n 'max-width:320px;',\n 'box-sizing:border-box;',\n 'border:1px solid rgba(255,255,255,0.08);',\n 'box-shadow:0 4px 16px rgba(0,0,0,0.5);',\n 'user-select:none;',\n ].join('');\n }\n\n // ── Render ─────────────────────────────────────────────────────────────────\n\n private _render(): void {\n if (!this._overlay || !this.ctx) return;\n const { accentColor, hideIds } = this._opts;\n\n const all = this.ctx.layers.list().filter((l) => {\n if (l.id === this.id) return false;\n if (hideIds.includes(l.id)) return false;\n return true;\n });\n\n const headerHtml =\n `<div style=\"color:${accentColor};font-weight:bold;margin-bottom:6px;\">` +\n ` LAYERS (${all.length})` +\n `</div>`;\n\n if (all.length === 0) {\n this._overlay.innerHTML =\n headerHtml +\n `<div style=\"opacity:0.5;font-style:italic;padding:2px 0;\">no other layers</div>`;\n return;\n }\n\n const headerCellStyle =\n `text-align:left;padding:2px 6px 4px 0;color:${accentColor};` +\n `border-bottom:1px solid rgba(255,255,255,0.12);font-weight:600;`;\n const cellStyle =\n 'padding:2px 6px 2px 0;vertical-align:middle;' +\n 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';\n\n const tableHead =\n `<thead><tr>` +\n `<th style=\"${headerCellStyle}width:16px;\"></th>` +\n `<th style=\"${headerCellStyle}\">id</th>` +\n `<th style=\"${headerCellStyle}\">class</th>` +\n `<th style=\"${headerCellStyle}text-align:right;padding-right:0;width:46px;\">z</th>` +\n `</tr></thead>`;\n\n const rows = all\n .map((l) => {\n const checked = l.visible ? 'checked' : '';\n const className = l.constructor?.name ?? '';\n const idHtml = escapeHtml(l.id);\n const classHtml = escapeHtml(className);\n return (\n `<tr>` +\n `<td style=\"${cellStyle}width:16px;\">` +\n `<input type=\"checkbox\" data-layer-id=\"${escapeAttr(l.id)}\" ${checked}` +\n ` style=\"cursor:pointer;margin:0;display:block;\" />` +\n `</td>` +\n `<td style=\"${cellStyle}\" title=\"${idHtml}\">${idHtml}</td>` +\n `<td style=\"${cellStyle}opacity:0.75;\" title=\"${classHtml}\">${classHtml}</td>` +\n `<td style=\"${cellStyle}text-align:right;padding-right:0;opacity:0.75;width:46px;\">` +\n `${escapeHtml(String(l.zIndex))}</td>` +\n `</tr>`\n );\n })\n .join('');\n\n this._overlay.innerHTML =\n headerHtml +\n `<table style=\"border-collapse:collapse;width:100%;table-layout:fixed;font-size:inherit;font-family:inherit;color:inherit;\">` +\n tableHead +\n `<tbody>${rows}</tbody>` +\n `</table>`;\n }\n}\n\n// ─── helpers ─────────────────────────────────────────────────────────────────\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\nfunction escapeAttr(s: string): string {\n return escapeHtml(s);\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\nimport type { CanvasContext } from '../context/CanvasContext';\n\n/** What `BehaviourRegistry` sees. */\nexport interface IBehaviour {\n readonly id: string;\n readonly enabled: boolean;\n readonly scope: 'layer' | 'canvas';\n readonly layerId?: string;\n readonly shortcuts?: readonly string[];\n register(ctx: CanvasContext): void;\n destroy(): void;\n enable(): void;\n disable(): 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 `layerId` and `scope: 'canvas'`.\n */\n layerId?: 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\nexport abstract class Behaviour implements IBehaviour {\n readonly id: string;\n readonly layerId?: string;\n readonly shortcuts?: readonly string[];\n\n /**\n * `'layer'` if `layerId` 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 protected _enabled: boolean;\n protected ctx?: CanvasContext;\n\n constructor(opts: BehaviourOptions) {\n this.id = opts.id;\n this.layerId = opts.layerId;\n this.scope = opts.layerId !== undefined ? 'layer' : 'canvas';\n this.shortcuts = opts.shortcuts;\n this._enabled = opts.enabled ?? false;\n }\n\n get enabled(): boolean {\n return this._enabled;\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 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.onDestroy(ctx);\n this.ctx = undefined;\n }\n\n enable(): void {\n if (this._enabled) return;\n this._enabled = true;\n this.onEnable();\n }\n\n disable(): void {\n if (!this._enabled) return;\n this._enabled = false;\n this.onDisable();\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 * Convenience `if (!enabled) return;` for use inside event handlers\n * (without rebinding `this` cost).\n */\n protected get isEnabled(): boolean {\n return this._enabled;\n }\n}\n","/**\n * `DragPanBehaviour` — pointer-drag panning via the pixi-viewport `drag` plugin.\n *\n * An optional `modifier` key restricts the gesture so you can reserve plain\n * drag for other behaviours (e.g. lasso, rubber-band select):\n *\n * - `'none'` (default) — any left-button drag pans.\n * - `'space'` — Space + drag (Figma / Sketch style).\n * - `'shift'` — Shift + drag.\n * - `'alt'` — Alt/Option + drag.\n *\n * A decelerate plugin is added alongside by default, giving momentum after\n * the pointer lifts. Disable with `decelerate: false`.\n *\n * The canvas cursor swaps to `dragCursor` (`'grabbing'` by default) the moment\n * a qualifying pointer is pressed — so it reads as \"holding the canvas, ready\n * to drag\" before any movement happens — and restores on release. The press is\n * matched against the configured `mouseButtons` and `modifier`; the `space`\n * modifier can't be read off a pointer event, so for that mode the swap falls\n * back to pixi-viewport's `drag-start` (fires once the gesture actually moves).\n * The idle cursor is left untouched, so this never fights the renderer's hover\n * cursor.\n */\n\nimport { Behaviour, type BehaviourOptions } from './Behaviour';\nimport type { CanvasContext } from '../context/CanvasContext';\n\nexport type DragModifier = 'none' | 'space' | 'shift' | 'alt';\n\nexport interface DragPanBehaviourOptions extends BehaviourOptions {\n /** Which modifier key must be held during drag. Default `'none'`. */\n modifier?: DragModifier;\n /** Allowed mouse buttons. Default `'left'`. Forwarded to pixi-viewport. */\n mouseButtons?: 'all' | 'left' | 'right' | 'middle';\n /** Add momentum deceleration after pointer lift. Default `true`. */\n decelerate?: boolean;\n /**\n * Cursor applied to the canvas while the pan pointer is held. Set on\n * pointer-press (matching `mouseButtons` / `modifier`), restored to the\n * previous value on release. Default `'grabbing'`.\n */\n dragCursor?: string;\n}\n\nfunction modifierToKeys(modifier: DragModifier): string[] | null {\n switch (modifier) {\n case 'space': return ['Space'];\n case 'shift': return ['ShiftLeft', 'ShiftRight'];\n case 'alt': return ['AltLeft', 'AltRight'];\n default: return null;\n }\n}\n\nexport class DragPanBehaviour extends Behaviour {\n private readonly modifier: DragModifier;\n private readonly mouseButtons: string;\n private readonly withDecelerate: boolean;\n private readonly dragCursor: string;\n\n /** Canvas the cursor swap targets; `null` on headless / custom stages. */\n private canvasEl: HTMLCanvasElement | null = null;\n /** Cursor saved when the pan pointer is pressed, restored on release. */\n private prevCursor: string | null = null;\n\n constructor(opts: DragPanBehaviourOptions) {\n const modifier = opts.modifier ?? 'none';\n const gesture = modifier === 'none' ? 'drag' : `${modifier}+drag`;\n super({ ...opts, shortcuts: opts.shortcuts ?? [gesture] });\n this.modifier = modifier;\n this.mouseButtons = opts.mouseButtons ?? 'left';\n this.withDecelerate = opts.decelerate ?? true;\n this.dragCursor = opts.dragCursor ?? 'grabbing';\n }\n\n protected onRegister(ctx: CanvasContext): void {\n this.canvasEl = ctx.canvasElement ?? null;\n }\n\n protected onEnable(): void {\n const vp = this.ctx!.camera.viewport;\n vp.drag({ mouseButtons: this.mouseButtons, keyToPress: modifierToKeys(this.modifier) ?? undefined });\n if (this.withDecelerate) vp.decelerate();\n // Eager grab on press for the immediate \"holding the canvas\" feel.\n this.canvasEl?.addEventListener('pointerdown', this.onPointerDown);\n // Fallback for the `space` modifier, which can't be read off a pointer\n // event: pixi-viewport fires `drag-start` only once the gesture moves.\n vp.on('drag-start', this.armCursor);\n }\n\n protected onDisable(): void {\n const vp = this.ctx!.camera.viewport;\n this.canvasEl?.removeEventListener('pointerdown', this.onPointerDown);\n vp.off('drag-start', this.armCursor);\n this.restoreCursor(); // restore + drop window listeners if disabled mid-gesture\n vp.plugins.remove('drag');\n if (this.withDecelerate) vp.plugins.remove('decelerate');\n }\n\n private readonly onPointerDown = (e: PointerEvent): void => {\n if (!this._enabled) return;\n if (!this.buttonAllowed(e.button)) return;\n if (!this.modifierHeld(e)) return;\n this.armCursor();\n // Release can land outside the canvas, so listen at the window.\n window.addEventListener('pointerup', this.restoreCursor);\n window.addEventListener('pointercancel', this.restoreCursor);\n };\n\n /** Swap to the drag cursor, saving the prior value. No-op if already armed. */\n private readonly armCursor = (): void => {\n if (!this.canvasEl || this.prevCursor !== null) return;\n this.prevCursor = this.canvasEl.style.cursor;\n this.canvasEl.style.cursor = this.dragCursor;\n };\n\n /** Restore the saved cursor and detach the release listeners. */\n private readonly restoreCursor = (): void => {\n window.removeEventListener('pointerup', this.restoreCursor);\n window.removeEventListener('pointercancel', this.restoreCursor);\n if (this.prevCursor === null || !this.canvasEl) return;\n this.canvasEl.style.cursor = this.prevCursor;\n this.prevCursor = null;\n };\n\n /** Does this pointer button match the configured `mouseButtons`? */\n private buttonAllowed(button: number): boolean {\n switch (this.mouseButtons) {\n case 'all': return true;\n case 'middle': return button === 1;\n case 'right': return button === 2;\n default: return button === 0; // 'left'\n }\n }\n\n /**\n * Is the configured modifier satisfied for this press? `shift` / `alt` read\n * off the event; `none` is always true; `space` returns `false` here (not\n * detectable on a pointer event) and is handled by the `drag-start` fallback.\n */\n private modifierHeld(e: PointerEvent): boolean {\n switch (this.modifier) {\n case 'shift': return e.shiftKey;\n case 'alt': return e.altKey;\n case 'space': return false;\n default: return true; // 'none'\n }\n }\n}\n","/**\n * `DragShapeBehaviour` — pointer-drag move for individual shapes managed by\n * a `PrimitivesRenderer`. Layer-scoped: constructed with a specific renderer\n * reference; the same canvas can host multiple layers, each with its own\n * drag behaviour.\n *\n * Default `enabled: false` — register, then explicitly enable. Matches the\n * project rule that no behaviour auto-activates.\n *\n * What happens on drag:\n * 1. `shape:pointerdown` from the renderer → drag start. Records the\n * pointer's world position and the shape's current `(spec.x, spec.y)`.\n * 2. The viewport's pan plugin is paused so the camera doesn't pan while\n * you're moving a shape.\n * 3. Window-level `pointermove` updates the shape via\n * `renderer.updateShape(id, { x, y })` so the click point stays under\n * the cursor. Window events are used (rather than pixi container events)\n * so the drag continues smoothly even when the pointer slides off the\n * original shape or off the canvas momentarily.\n * 4. When `reRouteConnectors` is `true` (default), every connector is\n * re-routed after each move — useful when the moved shape is an\n * obstacle for an obstacle-aware router. Set `false` if you're moving\n * a node whose edges should re-route via a smarter graph-level signal\n * (or if you have thousands of edges and the cost matters).\n * 5. `pointerup` / `pointercancel` → drag end. Viewport pan resumes.\n *\n * The behaviour observes the renderer's public surface only: subscribes to\n * `shape:pointerdown`, calls `getShapePosition` / `updateShape` /\n * `reRouteAllConnectors`. No private access.\n */\n\nimport { Behaviour, type BehaviourOptions } from './Behaviour';\nimport type { CanvasContext } from '../context/CanvasContext';\nimport type { PrimitivesRenderer } from '../primitives/PrimitivesRenderer';\n\nexport interface DragShapeBehaviourOptions extends BehaviourOptions {\n /** The renderer whose shapes this behaviour can drag. */\n readonly renderer: PrimitivesRenderer;\n /**\n * Optional predicate to restrict which shape ids are draggable. Returning\n * `false` ignores the pointerdown. Default = every shape is draggable.\n */\n readonly filter?: (id: string) => boolean;\n /**\n * Re-route every connector after each move. Default `true` — needed for\n * obstacle-aware routers (`manhattan` etc.) so they recompute when\n * obstacles move. Set `false` to avoid the per-move re-route cost.\n */\n readonly reRouteConnectors?: boolean;\n /**\n * Optional cursor while dragging. Applied on drag start and cleared on\n * drag end. Default `'grabbing'`.\n */\n readonly dragCursor?: string;\n}\n\ninterface DragState {\n readonly id: string;\n readonly pointerWorldStart: { x: number; y: number };\n readonly shapePosStart: { x: number; y: number };\n}\n\nexport class DragShapeBehaviour extends Behaviour {\n private readonly renderer: PrimitivesRenderer;\n private readonly filter?: (id: string) => boolean;\n private readonly reRouteConnectors: boolean;\n private readonly dragCursor: string;\n\n private state: DragState | null = null;\n private offShapeDown?: () => void;\n private viewport?: CanvasContext['camera']['viewport'];\n private canvasEl: HTMLCanvasElement | null = null;\n private prevCursor: string | null = null;\n\n constructor(opts: DragShapeBehaviourOptions) {\n super({ ...opts, shortcuts: opts.shortcuts ?? ['shape+drag'] });\n this.renderer = opts.renderer;\n this.filter = opts.filter;\n this.reRouteConnectors = opts.reRouteConnectors ?? true;\n this.dragCursor = opts.dragCursor ?? 'grabbing';\n }\n\n protected override onRegister(ctx: CanvasContext): void {\n this.viewport = ctx.camera.viewport;\n\n // Pixi-viewport's Viewport stores the `EventSystem` it was constructed\n // with, and the EventSystem exposes `.domElement` — the actual HTMLCanvas\n // pixi renders into. We use this canvas for `getBoundingClientRect()`\n // when converting window pointer coords to screen coords during drag.\n this.canvasEl = readCanvasElement(this.viewport);\n\n const onShapeDown = (e: { id: string; worldX: number; worldY: number }): void => {\n if (!this._enabled) return;\n if (this.filter && !this.filter(e.id)) return;\n const pos = this.renderer.getShapePosition(e.id);\n if (!pos) return;\n this.startDrag(e.id, e.worldX, e.worldY, pos);\n };\n this.renderer.events.on('shape:pointerdown', onShapeDown);\n this.offShapeDown = () => this.renderer.events.off('shape:pointerdown', onShapeDown);\n }\n\n protected override onDestroy(_ctx: CanvasContext): void {\n this.endDrag();\n this.offShapeDown?.();\n this.offShapeDown = undefined;\n }\n\n protected override onDisable(): void {\n if (this.state) this.endDrag();\n }\n\n private startDrag(id: string, worldX: number, worldY: number, shapePos: { x: number; y: number }): void {\n this.state = {\n id,\n pointerWorldStart: { x: worldX, y: worldY },\n shapePosStart: shapePos,\n };\n\n // Pause the viewport's pan plugin so we don't pan while moving a shape.\n this.viewport?.plugins.pause('drag');\n\n // Window-level move/up listeners. DOM events are the most reliable\n // source for drag flows — they fire regardless of which pixi target is\n // currently hit and continue working when the pointer briefly leaves\n // the canvas.\n window.addEventListener('pointermove', this.onWindowPointerMove);\n window.addEventListener('pointerup', this.onWindowPointerUp);\n window.addEventListener('pointercancel', this.onWindowPointerUp);\n\n // Swap the canvas cursor for visual feedback.\n if (this.canvasEl) {\n this.prevCursor = this.canvasEl.style.cursor;\n this.canvasEl.style.cursor = this.dragCursor;\n }\n }\n\n private endDrag(): void {\n if (!this.state) return;\n\n window.removeEventListener('pointermove', this.onWindowPointerMove);\n window.removeEventListener('pointerup', this.onWindowPointerUp);\n window.removeEventListener('pointercancel', this.onWindowPointerUp);\n\n if (this.prevCursor !== null && this.canvasEl) {\n this.canvasEl.style.cursor = this.prevCursor;\n this.prevCursor = null;\n }\n\n this.viewport?.plugins.resume('drag');\n this.state = null;\n }\n\n private readonly onWindowPointerMove = (e: PointerEvent): void => {\n if (!this.state || !this.ctx) return;\n const { screenX, screenY } = this.clientToScreen(e.clientX, e.clientY);\n const world = this.ctx.camera.toWorld(screenX, screenY);\n const dx = world.x - this.state.pointerWorldStart.x;\n const dy = world.y - this.state.pointerWorldStart.y;\n const nextX = this.state.shapePosStart.x + dx;\n const nextY = this.state.shapePosStart.y + dy;\n this.renderer.updateShape(this.state.id, { x: nextX, y: nextY });\n if (this.reRouteConnectors) this.renderer.reRouteAllConnectors();\n };\n\n private readonly onWindowPointerUp = (): void => {\n this.endDrag();\n };\n\n /** Convert a window-level `(clientX, clientY)` to canvas-relative screen coords. */\n private clientToScreen(clientX: number, clientY: number): { screenX: number; screenY: number } {\n if (!this.canvasEl) return { screenX: clientX, screenY: clientY };\n const rect = this.canvasEl.getBoundingClientRect();\n return { screenX: clientX - rect.left, screenY: clientY - rect.top };\n }\n}\n\n/**\n * Best-effort recovery of the `HTMLCanvasElement` pixi is rendering into.\n * Pixi-viewport's Viewport receives an `EventSystem` in its constructor\n * options and stores it on `.options.events`; the EventSystem exposes the\n * canvas via `.domElement`. Falls back to `null` when the structure differs\n * (headless test stages, custom Canvas wiring, etc.) — the drag still works,\n * just without cursor swap or perfectly accurate coord conversion when the\n * canvas is offset from the window origin.\n */\nfunction readCanvasElement(\n viewport: CanvasContext['camera']['viewport'] | undefined,\n): HTMLCanvasElement | null {\n if (!viewport) return null;\n const events = (viewport as unknown as {\n options?: { events?: { domElement?: HTMLCanvasElement } };\n }).options?.events;\n const el = events?.domElement;\n return el instanceof HTMLCanvasElement ? el : null;\n}\n","/**\n * `WheelZoomBehaviour` — scroll-wheel zooming via the pixi-viewport `wheel` plugin.\n *\n * By default, any scroll wheel event zooms. Set `requireCtrl: true` to\n * restrict to Ctrl+scroll (frees plain scroll for page scrolling — good\n * for accessibility contexts where the canvas is inline on a scrollable page).\n *\n * `trackpadPinch: true` is enabled so two-finger trackpad pinches zoom\n * instead of scroll. Pair with `PinchZoomBehaviour` for touch devices.\n */\n\nimport { Behaviour, type BehaviourOptions } from './Behaviour';\nimport type { CanvasContext } from '../context/CanvasContext';\n\nexport interface WheelZoomBehaviourOptions extends BehaviourOptions {\n /**\n * If `true`, only Ctrl+scroll triggers zoom; plain scroll falls through\n * to the browser. Good for inline canvas embeds. Default `false`.\n */\n requireCtrl?: boolean;\n /** Zoom speed per wheel tick, as a fraction. Default `0.1` (10%). */\n percent?: number;\n /**\n * Smooth-scroll frame count. `false` = instant snap. Default `false`.\n * Set to e.g. `8` for an ease-out feel.\n */\n smooth?: false | number;\n}\n\nexport class WheelZoomBehaviour extends Behaviour {\n private readonly requireCtrl: boolean;\n private readonly percent: number;\n private readonly smooth: false | number;\n\n constructor(opts: WheelZoomBehaviourOptions) {\n const requireCtrl = opts.requireCtrl ?? false;\n const gesture = requireCtrl ? 'ctrl+wheel' : 'wheel';\n super({ ...opts, shortcuts: opts.shortcuts ?? [gesture] });\n this.requireCtrl = requireCtrl;\n this.percent = opts.percent ?? 0.1;\n this.smooth = opts.smooth ?? false;\n }\n\n protected onRegister(_ctx: CanvasContext): void { /* wired on enable */ }\n\n protected onEnable(): void {\n this.ctx!.camera.viewport.wheel({\n percent: this.percent,\n smooth: this.smooth,\n keyToPress: this.requireCtrl ? ['ControlLeft', 'ControlRight'] : undefined,\n trackpadPinch: true,\n });\n }\n\n protected onDisable(): void {\n this.ctx!.camera.viewport.plugins.remove('wheel');\n }\n}\n","/**\n * `PinchZoomBehaviour` — two-finger pinch-to-zoom via the pixi-viewport `pinch` plugin.\n *\n * Designed for touch screens and trackpads. Works alongside\n * `WheelZoomBehaviour` (which handles trackpad pinch-as-scroll separately via\n * its `trackpadPinch` flag); this behaviour handles native touch pinch events.\n *\n * Set `noDrag: true` if you want pinch to only zoom, not also pan (useful\n * when you have a separate `DragPanBehaviour` and don't want conflicts).\n */\n\nimport { Behaviour, type BehaviourOptions } from './Behaviour';\nimport type { CanvasContext } from '../context/CanvasContext';\n\nexport interface PinchZoomBehaviourOptions extends BehaviourOptions {\n /**\n * If `true`, suppress the implicit pan that accompanies a pinch gesture.\n * Default `false` — pinch both zooms and centres the viewport on the\n * midpoint between the two fingers.\n */\n noDrag?: boolean;\n /** Zoom speed multiplier. Default `0.1`. */\n percent?: number;\n}\n\nexport class PinchZoomBehaviour extends Behaviour {\n private readonly noDrag: boolean;\n private readonly percent: number;\n\n constructor(opts: PinchZoomBehaviourOptions) {\n super({ ...opts, shortcuts: opts.shortcuts ?? ['pinch'] });\n this.noDrag = opts.noDrag ?? false;\n this.percent = opts.percent ?? 0.1;\n }\n\n protected onRegister(_ctx: CanvasContext): void { /* wired on enable */ }\n\n protected onEnable(): void {\n this.ctx!.camera.viewport.pinch({ noDrag: this.noDrag, percent: this.percent });\n }\n\n protected onDisable(): void {\n this.ctx!.camera.viewport.plugins.remove('pinch');\n }\n}\n","/**\n * `KeyboardCameraInputBehaviour` — keyboard pan and zoom for accessibility.\n *\n * Default keymap (all configurable via `keymap` option):\n *\n * Pan up/down/left/right → Arrow keys\n * Zoom in → `+` / `=` / `NumpadAdd`\n * Zoom out → `-` / `NumpadSubtract`\n * Reset zoom to 1:1 → `0` / `Numpad0`\n *\n * Events attach to `document` so the canvas does not need to be\n * individually focused. Input fields, textareas, and selects are\n * excluded automatically — keyboard events whose `target` is an editable\n * element fall through unhandled.\n *\n * Arrow key direction follows the \"scroll\" metaphor: ArrowUp pans the\n * viewport so you see content *above* the current view.\n */\n\nimport { Behaviour, type BehaviourOptions } from './Behaviour';\nimport type { CanvasContext } from '../context/CanvasContext';\n\nexport interface KeyboardCameraKeymap {\n panUp: string[];\n panDown: string[];\n panLeft: string[];\n panRight: string[];\n zoomIn: string[];\n zoomOut: string[];\n resetZoom: string[];\n}\n\nconst DEFAULT_KEYMAP: KeyboardCameraKeymap = {\n panUp: ['ArrowUp'],\n panDown: ['ArrowDown'],\n panLeft: ['ArrowLeft'],\n panRight: ['ArrowRight'],\n zoomIn: ['+', '=', 'NumpadAdd'],\n zoomOut: ['-', 'NumpadSubtract'],\n resetZoom: ['0', 'Numpad0'],\n};\n\nexport interface KeyboardCameraInputBehaviourOptions extends BehaviourOptions {\n /** Pan distance per key press in screen pixels. Default `40`. */\n panStep?: number;\n /**\n * Zoom multiplier per key press. `1.1` = 10% in/out per press.\n * Default `1.1`.\n */\n zoomFactor?: number;\n /** Override individual key groups. Merged with the defaults. */\n keymap?: Partial<KeyboardCameraKeymap>;\n}\n\nexport class KeyboardCameraInputBehaviour extends Behaviour {\n private readonly panStep: number;\n private readonly zoomFactor: number;\n private readonly keymap: KeyboardCameraKeymap;\n private _handler?: (e: KeyboardEvent) => void;\n\n constructor(opts: KeyboardCameraInputBehaviourOptions) {\n const keymap: KeyboardCameraKeymap = { ...DEFAULT_KEYMAP, ...opts.keymap };\n const allKeys = [...new Set(Object.values(keymap).flat())];\n super({ ...opts, shortcuts: opts.shortcuts ?? allKeys });\n this.panStep = opts.panStep ?? 40;\n this.zoomFactor = opts.zoomFactor ?? 1.1;\n this.keymap = keymap;\n }\n\n protected onRegister(_ctx: CanvasContext): void { /* wired on enable */ }\n\n protected onEnable(): void {\n this._handler = (e: KeyboardEvent) => this._onKeyDown(e);\n document.addEventListener('keydown', this._handler);\n }\n\n protected onDisable(): void {\n if (this._handler) {\n document.removeEventListener('keydown', this._handler);\n this._handler = undefined;\n }\n }\n\n private _onKeyDown(e: KeyboardEvent): void {\n const tag = (e.target as HTMLElement | null)?.tagName?.toUpperCase();\n if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;\n\n const camera = this.ctx!.camera;\n const key = e.key;\n const code = e.code;\n\n // ArrowUp/Down/Left/Right use scroll metaphor: ArrowUp = see content above.\n if (this._match(key, code, this.keymap.panUp)) {\n e.preventDefault();\n camera.pan(0, this.panStep);\n } else if (this._match(key, code, this.keymap.panDown)) {\n e.preventDefault();\n camera.pan(0, -this.panStep);\n } else if (this._match(key, code, this.keymap.panLeft)) {\n e.preventDefault();\n camera.pan(this.panStep, 0);\n } else if (this._match(key, code, this.keymap.panRight)) {\n e.preventDefault();\n camera.pan(-this.panStep, 0);\n } else if (this._match(key, code, this.keymap.zoomIn)) {\n e.preventDefault();\n camera.zoomAt(this.zoomFactor);\n } else if (this._match(key, code, this.keymap.zoomOut)) {\n e.preventDefault();\n camera.zoomAt(1 / this.zoomFactor);\n } else if (this._match(key, code, this.keymap.resetZoom)) {\n e.preventDefault();\n camera.setZoom(1);\n }\n }\n\n private _match(key: string, code: string, candidates: string[]): boolean {\n return candidates.includes(key) || candidates.includes(code);\n }\n}\n","/**\n * `ElementSizeLODBehaviour` — abstract base for zoom-driven \"keep this\n * element at a fixed screen-pixel size\" behaviours.\n *\n * Sits in the same family as `LabelResolutionLODBehaviour`: both react\n * to `camera:zoom`, both adapt how some kind of entity renders as the\n * camera scale changes. This base owns the shared plumbing — event\n * subscription, RAF coalescing of bursts, enable/disable lifecycle —\n * and leaves the *what to rescale* to concrete subclasses.\n *\n * ## Why a base + subclass split\n *\n * The \"screen-constant size\" need shows up across domains: graph nodes\n * and edges today; swimlane lane headers, annotation pins, ER table\n * decorations tomorrow. Putting the camera-zoom plumbing in canvas (which\n * already owns the camera and the behaviour base) and the per-element\n * rescaling in domain packages means:\n *\n * - Each domain ships its own subclass next to its data model. No need\n * to modify an upstream \"knows about everything\" class to add a new\n * element kind.\n * - The browser RAF callback batches every behaviour's scheduled\n * callback into the same frame, so registering multiple subclasses\n * has effectively the same per-frame cost as one monolith doing N\n * passes.\n *\n * ## Concrete subclass contract\n *\n * Override `onResolveTargets(ctx)` once at register to resolve layer\n * references. Override `apply(scale)` to walk those targets and write\n * the rescaled geometry through the renderer's fast paths\n * (`updateShape`, `setConnectorStroke`, etc.).\n *\n * `disable()` calls `apply(1)` — your apply function should be\n * idempotent at scale 1 (which is what \"restore to world-unit sizing\"\n * means).\n *\n * ## MapLibre note\n *\n * `MapLayer` writes the pixi-viewport transform directly to mirror\n * MapLibre's camera. It re-emits `camera:zoom` on the canvas event bus\n * after each move so subclasses of this behaviour react under MapLibre\n * gestures the same as under `WheelZoomBehaviour`. Without that bridge\n * these behaviours would silently no-op under MapLibre.\n */\n\nimport type { CanvasContext } from '../context/CanvasContext';\nimport { Behaviour, type BehaviourOptions } from './Behaviour';\n\n/** A static value or a getter — getters are re-read on every `apply`. */\nexport type NumberOrGetter = number | (() => number);\n\n/** Coerce a {@link NumberOrGetter} to its current numeric value, or `undefined`. */\nexport function resolveNumberOrGetter(v: NumberOrGetter | undefined): number | undefined {\n if (v === undefined) return undefined;\n return typeof v === 'function' ? v() : v;\n}\n\nexport interface ElementSizeLODBehaviourOptions extends BehaviourOptions {\n /**\n * Skip `apply` when the relative scale change since the last applied\n * frame is below this threshold (`|scale - lastScale| / lastScale`).\n * Set to `0` to disable the skip. Default `0.005` (0.5%) — sub-pixel\n * stroke / size deltas at typical screen DPIs, which the user can't\n * perceive but a wheel-zoom gesture fires 60×/sec of.\n */\n scaleEpsilon?: number;\n /**\n * When `> 0`, switch from per-frame RAF apply to a trailing-edge\n * debounce: skip work during a continuous gesture and run one final\n * `apply` after `settleMs` of zoom silence. Useful for expensive\n * passes (e.g. thousands of connector redraws) where mid-gesture\n * visual drift is preferable to a frame-rate collapse. Default `0`\n * (RAF mode).\n */\n settleMs?: number;\n}\n\nexport abstract class ElementSizeLODBehaviour extends Behaviour {\n private readonly subs: Array<() => void> = [];\n /**\n * Pending `requestAnimationFrame` handle. Non-null while a reflow is\n * scheduled but hasn't fired yet — collapses bursts of `camera:zoom`\n * events (the wheel-zoom gesture fires 100+/sec) into one `apply`\n * call per animation frame. Critical for keeping fps above 60 during\n * a continuous zoom over thousands of entities.\n */\n private rafHandle: number | null = null;\n /**\n * Settle timer (debounce) handle. Used instead of `rafHandle` when\n * `settleMs > 0`. Re-armed on every `camera:zoom`; firing triggers a\n * single `apply` at the latest scale.\n */\n private settleTimer: ReturnType<typeof setTimeout> | null = null;\n /**\n * Scale at the last `apply` call. Drives the `scaleEpsilon` skip:\n * the next scheduled apply bails if the current scale is within\n * epsilon of this value. `null` means \"no prior apply, never skip\".\n */\n private lastAppliedScale: number | null = null;\n private readonly scaleEpsilon: number;\n private readonly settleMs: number;\n\n constructor(opts: ElementSizeLODBehaviourOptions) {\n super({ ...opts, shortcuts: opts.shortcuts ?? [] });\n this.scaleEpsilon = opts.scaleEpsilon ?? 0.005;\n this.settleMs = opts.settleMs ?? 0;\n }\n\n protected override onRegister(ctx: CanvasContext): void {\n this.onResolveTargets(ctx);\n this.subs.push(ctx.events.on('camera:zoom', () => this.scheduleReflow()));\n // Pre-enabled register → apply once now so the first painted frame\n // already shows the rescaled sizes; we don't wait for the next zoom.\n if (this.isEnabled) this.applyAndRemember(ctx.camera.scale);\n }\n\n protected override onDestroy(): void {\n this.cancelScheduledReflow();\n for (const off of this.subs) off();\n this.subs.length = 0;\n this.onReleaseTargets();\n }\n\n protected override onEnable(): void {\n if (!this.ctx) return;\n // Drop the prior epsilon baseline — the first scheduled apply after\n // (re-)enable must run regardless of how close the current scale is\n // to whatever was applied before the disable.\n this.lastAppliedScale = null;\n this.applyAndRemember(this.ctx.camera.scale);\n }\n\n protected override onDisable(): void {\n // Disable is reversible — cancel any pending reflow and \"restore\"\n // by applying at scale 1 (world-unit sizing). `apply` must be\n // idempotent there.\n this.cancelScheduledReflow();\n this.apply(1);\n // Don't remember `1` as the baseline — we'd then skip the post-enable\n // apply if the camera happened to be at scale ≈ 1.\n this.lastAppliedScale = null;\n }\n\n /**\n * Force an immediate reflow at the current camera scale. Useful after\n * tuning a config knob (e.g. moving a GUI slider that a `NumberOrGetter`\n * reads from) — push the new sizes without waiting for the next zoom.\n *\n * Bypasses the epsilon skip and the settle debounce — explicit calls\n * are always treated as \"apply now.\"\n */\n reflow(): void {\n this.cancelScheduledReflow();\n if (!this.isEnabled || !this.ctx) return;\n this.applyAndRemember(this.ctx.camera.scale);\n }\n\n // ─── Subclass hooks ──────────────────────────────────────────────────────\n\n /**\n * Called once on register. Resolve layer references from `ctx.layers`\n * and stash them on `this` for later `apply` calls. Throw a descriptive\n * error if a required layer isn't present — the canvas guarantees\n * `ctx.layers` is fully populated before behaviours register.\n */\n protected abstract onResolveTargets(ctx: CanvasContext): void;\n\n /** Optional teardown hook — drop layer refs / caches. Default no-op. */\n protected onReleaseTargets(): void {\n /* default no-op */\n }\n\n /**\n * Apply rescaling at the given camera scale. Called by `onEnable`,\n * each `camera:zoom` (RAF coalesced), and by `onDisable` with\n * `scale = 1` to restore world-unit sizing.\n *\n * Implementations should be idempotent — calling twice with the same\n * scale is a no-op visually.\n */\n protected abstract apply(scale: number): void;\n\n // ─── Internals ───────────────────────────────────────────────────────────\n\n /**\n * Route a `camera:zoom` to either the RAF path (default) or the\n * trailing-edge debounce path (`settleMs > 0`). Both eventually call\n * {@link tryApply}, which honours the epsilon skip.\n */\n private scheduleReflow(): void {\n if (this.settleMs > 0) {\n // Debounce: every zoom event re-arms the timer. The timer firing\n // is the only thing that calls apply — during a continuous gesture\n // we do *no* work; we only catch up on settle.\n if (this.settleTimer !== null) clearTimeout(this.settleTimer);\n this.settleTimer = setTimeout(() => {\n this.settleTimer = null;\n this.tryApply();\n }, this.settleMs);\n return;\n }\n if (this.rafHandle !== null) return;\n this.rafHandle = requestAnimationFrame(() => {\n this.rafHandle = null;\n this.tryApply();\n });\n }\n\n /**\n * Apply at the current camera scale if (a) still enabled, (b) the\n * scale has moved by more than `scaleEpsilon` since the last apply.\n * Updates {@link lastAppliedScale} only on a real apply, so cumulative\n * sub-epsilon drift is eventually caught.\n */\n private tryApply(): void {\n if (!this.isEnabled || !this.ctx) return;\n const scale = this.ctx.camera.scale;\n const last = this.lastAppliedScale;\n if (\n last !== null &&\n last > 0 &&\n this.scaleEpsilon > 0 &&\n Math.abs(scale - last) / last < this.scaleEpsilon\n ) {\n return;\n }\n this.applyAndRemember(scale);\n }\n\n private applyAndRemember(scale: number): void {\n this.apply(scale);\n this.lastAppliedScale = scale;\n }\n\n private cancelScheduledReflow(): void {\n if (this.rafHandle !== null) {\n cancelAnimationFrame(this.rafHandle);\n this.rafHandle = null;\n }\n if (this.settleTimer !== null) {\n clearTimeout(this.settleTimer);\n this.settleTimer = null;\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 '../events/EventEmitter';\nimport type { Layer } from '../layers/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 start: Record<string, never>;\n tick: Record<string, never>;\n end: { reason: LayoutEndReason };\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 /**\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 * 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.\n */\n abstract apply(layer: TLayer): Promise<void>;\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 `'layer:added'` / `'layer:removed'` 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 '../context/CanvasContext';\nimport type { CanvasEventBus } from '../events/CanvasEventBus';\nimport type { ILayer } from '../layers/Layer';\n\nexport interface LayerRegistryOptions {\n /**\n * Resolves the `CanvasContext` at the moment of mount. The Canvas creates\n * its registries before the context object exists, so this thunk lets the\n * registry defer the context lookup.\n */\n getContext: () => CanvasContext;\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;\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. Calls `layer.mount(ctx)` and fires `layer:added`.\n * 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 layer.mount(this.getContext());\n this.layers.set(layer.id, layer);\n this.zOrderCache = null;\n this.bus.emit('layer:added', { id: layer.id });\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('layer:removed', { 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).\n * - `setEnabled(id, enabled)` — toggles + fires `'behaviour:enabled'` /\n * `'behaviour:disabled'`.\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 '../context/CanvasContext';\nimport type { CanvasEventBus } from '../events/CanvasEventBus';\nimport type { IBehaviour } from '../behaviours/Behaviour';\n\nexport interface BehaviourRegistryOptions {\n getContext: () => CanvasContext;\n bus: CanvasEventBus;\n}\n\nexport class BehaviourRegistry {\n private readonly behaviours: Map<string, IBehaviour> = new Map();\n private readonly getContext: () => CanvasContext;\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. Calls `behaviour.register(ctx)` + fires\n * `'behaviour:registered'`. If `behaviour.enabled` is `true` at construction\n * time (the developer opted in via `enabled: true` option), also fires\n * `'behaviour:enabled'` and runs the conflict-warning check.\n *\n * Throws on duplicate id.\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 behaviour.register(this.getContext());\n this.behaviours.set(behaviour.id, behaviour);\n this.bus.emit('behaviour:registered', { id: behaviour.id });\n\n if (behaviour.enabled) {\n this.bus.emit('behaviour:enabled', { id: behaviour.id });\n this.warnOnShortcutConflict(behaviour);\n }\n }\n\n /** Remove a behaviour. Calls `destroy()`. No-op if not registered. */\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('behaviour:disabled', { id });\n }\n this.behaviours.delete(id);\n b.destroy();\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('behaviour:enabled', { id });\n this.warnOnShortcutConflict(b);\n } else {\n b.disable();\n this.bus.emit('behaviour:disabled', { 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 * `Canvas` — the engine root.\n *\n * Architecture: see `architecture-proposal.md` (whole document) and\n * `decorations-plan.md` §11.9 (RenderGroups + Ticker integration).\n *\n * **What it owns**\n * - The pixi `Application` (created by `init`) and its `Ticker`.\n * - The `CanvasEventBus` (typed canvas-wide events + tap channel).\n * - The `SurfaceManager` (world + screen RenderGroups).\n * - The `Camera` (pan/zoom/projection).\n * - The `LayerRegistry` and `BehaviourRegistry`.\n * - The `CanvasContext` object handed to every Layer / Behaviour.\n *\n * **What it does per tick** (single RAF, delegated to pixi `Ticker`):\n * 1. Walk layers in z-order.\n * 2. Skip invisible layers.\n * 3. If a layer has pending dirty work, call `layer.flush()`.\n * 4. Pixi auto-renders the stage at end of tick.\n *\n * Animation runner (Tweens) and per-renderer animation ticks land in later\n * steps; this Canvas implementation has the hook points but doesn't yet\n * orchestrate them.\n *\n * **Two init paths**\n * - `init(opts)` — the production path. Creates a pixi `Application`,\n * mounts its canvas into the DOM container, hooks the ticker.\n * - `initWithStage(stage, sw, sh)` — the test / headless path. Skips pixi\n * `Application` entirely. Caller provides a `Container` (which can be\n * a freshly-constructed pixi `Container()`) and viewport dimensions.\n * Useful for unit tests that want to exercise the layer pipeline without\n * standing up a renderer.\n */\n\nimport { Application, Container, type EventSystem, type Ticker } from 'pixi.js';\nimport { Viewport } from 'pixi-viewport';\n\nimport { CanvasEventBus } from '../events/CanvasEventBus';\nimport { Camera } from '../camera/Camera';\nimport { LayerRegistry } from '../registries/LayerRegistry';\nimport { BehaviourRegistry } from '../registries/BehaviourRegistry';\nimport type { CanvasContext } from '../context/CanvasContext';\n\n// ─── Options ───────────────────────────────────────────────────────────────\n\nexport interface CanvasOptions {\n /**\n * Stable identifier for this Canvas instance. Used as the source id on\n * envelopes published by the bus's own `emit()`. Default: `'canvas'`.\n * Override when running multiple Canvas instances in one document.\n */\n id?: string;\n\n /** DOM element pixi mounts its `<canvas>` into. Required by `init()`. */\n container?: HTMLElement;\n\n /** Preferred backend. Default `'webgpu'`. Pixi falls back via its own logic. */\n preference?: 'webgpu' | 'webgl' | 'canvas';\n\n /** Viewport width in CSS pixels. Default = `container.clientWidth`. */\n width?: number;\n /** Viewport height in CSS pixels. Default = `container.clientHeight`. */\n height?: number;\n\n /** Device pixel ratio. Default `window.devicePixelRatio`. */\n resolution?: number;\n\n /** GPU MSAA. Default `true`. Auto-disabled on the Canvas backend. */\n antialias?: boolean;\n\n /** `true` → opaque scene, `backgroundAlpha = 1` (skips per-frame blend). */\n opaque?: boolean;\n\n /** Background colour. Default `0` (black, but only visible when `opaque: true`). */\n backgroundColor?: number;\n\n /** GPU power preference. Default `'high-performance'`. */\n powerPreference?: 'high-performance' | 'low-power';\n\n /** Suppress pixi's \"PixiJS X.X.X\" startup log. Default `true`. */\n hello?: boolean;\n\n /**\n * Automatically resize the renderer and camera when the container element\n * changes size. Covers both window resize and programmatic expand/collapse.\n * Uses `ResizeObserver` internally. Default `false`.\n */\n autoResize?: boolean;\n\n /**\n * Suppress the browser's native right-click context menu on the canvas\n * element. Diagram apps typically want to show their own menu UI via the\n * `shape:contextmenu` / `connector:contextmenu` events. Default `true`.\n *\n * Set to `false` if the app wants the OS context menu (e.g. for\n * accessibility / dev tooling on right-click).\n */\n suppressBrowserContextMenu?: boolean;\n}\n\n// ─── Canvas ────────────────────────────────────────────────────────────────\n\nexport class Canvas {\n readonly id: string;\n readonly options: CanvasOptions;\n\n /**\n * Public surface — populated by `init()` / `initWithStage()`. Accessing\n * before init throws (definite-assignment via `!`). Use `isInitialised`\n * to guard if needed.\n */\n readonly events: CanvasEventBus;\n /**\n * The world container — a `pixi-viewport` `Viewport` instance attached to\n * `app.stage`. Camera-transformed; `WorldLayer`s mount their roots here.\n * Typed as `Container` so consumers don't depend on `pixi-viewport`; reach\n * for the `Viewport`-specific API via `camera.viewport`.\n */\n world!: Container;\n\n /**\n * The pixi `Application.stage` (or, for `initWithStage`, the caller-\n * provided stage). `ScreenLayer`s mount their roots directly here, as\n * siblings of `world` — `world` is added first (bottom), each ScreenLayer\n * after (above). No \"screen\" wrapper container.\n */\n stage!: Container;\n camera!: Camera;\n layers!: LayerRegistry;\n behaviours!: BehaviourRegistry;\n context!: CanvasContext;\n\n private app?: Application;\n private _isInitialised = false;\n private _onRendererResize?: (w: number, h: number) => void;\n\n constructor(opts: CanvasOptions = {}) {\n this.id = opts.id ?? 'canvas';\n this.options = opts;\n this.events = new CanvasEventBus({ source: { kind: 'canvas', id: this.id } });\n }\n\n get isInitialised(): boolean {\n return this._isInitialised;\n }\n\n /** Pixi `Application`, available after `init()` (not `initWithStage`). */\n get application(): Application | undefined {\n return this.app;\n }\n\n // ─── Init paths ──────────────────────────────────────────────────────────\n\n /**\n * Production init: create a pixi `Application`, mount its canvas into the\n * supplied DOM container, wire the ticker, and emit\n * `'renderer:initialised'` on the bus.\n *\n * The selected backend (and capabilities) flows through the bus event so\n * consumers see which renderer pixi resolved.\n */\n async init(opts: CanvasOptions): Promise<void> {\n if (this._isInitialised) {\n throw new Error(`Canvas \"${this.id}\" already initialised`);\n }\n\n const container = opts.container;\n if (!container) throw new Error(`Canvas \"${this.id}\": init() requires a container element`);\n\n const width = opts.width ?? container.clientWidth;\n const height = opts.height ?? container.clientHeight;\n const dpr =\n opts.resolution ??\n (typeof window !== 'undefined' ? window.devicePixelRatio : 1);\n\n this.app = new Application();\n await this.app.init({\n preference: opts.preference ?? 'webgpu',\n width,\n height,\n resolution: dpr,\n autoDensity: true,\n antialias: opts.antialias ?? true,\n backgroundAlpha: opts.opaque ? 1 : 0,\n backgroundColor: opts.backgroundColor ?? 0,\n powerPreference: opts.powerPreference ?? 'high-performance',\n hello: opts.hello ?? false,\n // When `autoResize` is on, let pixi own the resize loop. It polls\n // `container` on its ticker and calls `renderer.resize()` itself,\n // which is naturally frame-paced and handles `autoDensity` / DPR.\n // We just hook the renderer's `resize` event to keep camera in sync.\n ...(opts.autoResize ? { resizeTo: container } : {}),\n });\n\n this.app.canvas.style.display = 'block';\n container.appendChild(this.app.canvas);\n\n if (opts.suppressBrowserContextMenu ?? true) {\n this.app.canvas.addEventListener('contextmenu', (e) => e.preventDefault());\n }\n\n this._wireScene(this.app.stage, width, height, this.app.renderer.events);\n this.app.ticker.add(this.tick, this);\n\n if (opts.autoResize) {\n this._onRendererResize = (w, h) => {\n this.camera.resize(w, h);\n };\n this.app.renderer.on('resize', this._onRendererResize);\n }\n\n this._isInitialised = true;\n\n this.events.emit('renderer:initialised', {\n backend: this._detectBackend(),\n capabilities: this._capabilities(),\n });\n }\n\n /**\n * Headless / test init. Caller provides a pre-built stage `Container`\n * and viewport dimensions; we skip pixi's `Application` setup entirely.\n *\n * Use case: unit tests of the layer / behaviour / dirty / state pipeline\n * that don't need an actual GPU renderer.\n */\n initWithStage(stage: Container, screenWidth: number, screenHeight: number): void {\n if (this._isInitialised) {\n throw new Error(`Canvas \"${this.id}\" already initialised`);\n }\n this._wireScene(stage, screenWidth, screenHeight);\n this._isInitialised = true;\n this.events.emit('renderer:initialised', {\n backend: 'canvas', // headless == no GPU backend\n capabilities: { headless: true },\n });\n }\n\n // ─── Tick ────────────────────────────────────────────────────────────────\n\n /**\n * Run one tick manually with a fixed delta. Useful in tests; in production\n * pixi's ticker calls `tick` automatically.\n */\n tickOnce(deltaMs = 16): void {\n if (!this._isInitialised) return;\n // Advance pixi-viewport plugins (decelerate, snap, etc.).\n this.camera.tick(deltaMs);\n for (const layer of this.layers.byZOrder()) {\n if (!layer.visible) continue;\n if (layer.hasPending()) layer.flush();\n // Per architecture-proposal §2.7 + decorations-plan §3: animated\n // decorations (and any other per-frame primitive animation a Layer's\n // renderer owns) advance via a duck-typed `tickAnimations(dt)` hook.\n // The base `Layer` class doesn't declare it — Layers compose\n // renderers internally and may expose this hook conditionally.\n const ticker = (\n layer as unknown as {\n tickAnimations?: (dt: number) => void;\n renderer?: { tickAnimations?: (dt: number) => void };\n }\n );\n if (ticker.tickAnimations) {\n ticker.tickAnimations(deltaMs);\n } else if (ticker.renderer?.tickAnimations) {\n ticker.renderer.tickAnimations(deltaMs);\n }\n }\n }\n\n /** Pixi ticker callback. Bound via `add(this.tick, this)`. */\n private tick(ticker: Ticker): void {\n this.tickOnce(ticker.deltaMS);\n }\n\n // ─── Lifecycle ───────────────────────────────────────────────────────────\n\n /**\n * Tear down everything: ticker callback, registries (which unmount their\n * Layers / destroy their Behaviours and any ScreenLayer roots they own),\n * the world subtree, bus subscriptions, pixi Application. Idempotent.\n */\n destroy(): void {\n if (!this._isInitialised) return;\n\n if (this._onRendererResize && this.app) {\n this.app.renderer.off('resize', this._onRendererResize);\n }\n this._onRendererResize = undefined;\n this.app?.ticker.remove(this.tick, this);\n this.layers?.clear();\n this.behaviours?.clear();\n this.world?.destroy({ children: true });\n this.events.clearTaps();\n this.events.removeAllListeners();\n\n if (this.app) {\n // Pixi destroys the renderer + canvas + ticker.\n this.app.destroy(true, { children: true });\n this.app = undefined;\n }\n this._isInitialised = false;\n }\n\n // ─── Internals ───────────────────────────────────────────────────────────\n\n private _wireScene(\n stage: Container,\n screenWidth: number,\n screenHeight: number,\n events?: EventSystem,\n ): void {\n // The world container is always a `Viewport` instance — its position /\n // scale is what `Camera` mutates. In headless tests no real `EventSystem`\n // is available, so we pass a minimal stub. Viewport stores `events` but\n // doesn't actively use `events.domElement` unless an input plugin is\n // enabled (which we don't do in headless).\n const eventsForViewport: EventSystem =\n events ??\n ({\n domElement:\n typeof document !== 'undefined'\n ? document.createElement('canvas')\n : ({} as HTMLCanvasElement),\n } as unknown as EventSystem);\n\n const viewport = new Viewport({\n events: eventsForViewport,\n screenWidth,\n screenHeight,\n // Canvas owns the tick loop (`this.tick`); don't auto-register on the\n // global pixi Ticker. We'll forward `deltaMS` into `viewport.update()`\n // when camera-input behaviours that animate (decelerate, snap, etc.)\n // land in a follow-up.\n noTicker: true,\n });\n viewport.label = 'world';\n this.world = viewport;\n this.stage = stage;\n\n // World goes in first → bottom. ScreenLayers attach themselves to `stage`\n // directly later, so they're added after world and draw on top.\n stage.addChild(this.world);\n\n this.camera = new Camera({\n viewport,\n screenWidth,\n screenHeight,\n bus: this.events,\n });\n\n // Default the camera so world (0, 0) sits at the centre of the screen.\n // Most diagram / graph content positions itself around the origin\n // (e.g. d3-force's `forceCenter` defaults to 0, 0), so a top-left\n // anchor leaves content drifting in from the corner on boot. Callers\n // who want top-left semantics can `camera.setPosition(0, 0)` after init.\n this.camera.setPosition(screenWidth / 2, screenHeight / 2);\n\n this.layers = new LayerRegistry({\n getContext: () => this.context,\n bus: this.events,\n });\n this.behaviours = new BehaviourRegistry({\n getContext: () => this.context,\n bus: this.events,\n });\n\n // Build the context object now that all dependencies exist.\n this.context = {\n events: this.events,\n world: this.world,\n stage: this.stage,\n camera: this.camera,\n layers: this.layers,\n behaviours: this.behaviours,\n canvasElement: this.app?.canvas,\n };\n }\n\n private _detectBackend(): 'webgpu' | 'webgl' | 'canvas' {\n if (!this.app) return 'canvas';\n // Pixi v8 renderers expose a `name` string.\n const name = (this.app.renderer as { name?: string }).name;\n if (name === 'webgpu' || name === 'webgl' || name === 'canvas') return name;\n const ctor = this.app.renderer.constructor.name.toLowerCase();\n if (ctor.includes('webgpu')) return 'webgpu';\n if (ctor.includes('webgl')) return 'webgl';\n return 'canvas';\n }\n\n private _capabilities(): Record<string, unknown> {\n if (!this.app) return { headless: true };\n return {\n backend: this._detectBackend(),\n resolution: this.app.renderer.resolution,\n width: this.app.renderer.width,\n height: this.app.renderer.height,\n };\n }\n}\n","/**\n * `TextureRegistry` — user-facing texture preload and cache.\n *\n * Designed to be created once (e.g. in `GraphLayer.onMount`) and passed to\n * one or more `PrimitivesRenderer` instances via `ShapeHostInfo.textureRegistry`.\n * The renderer uses the registry internally when resolving image-fill specs —\n * callers never need to reference texture keys directly.\n *\n * If no registry is provided to `PrimitivesRenderer`, the renderer creates an\n * internal one so that URL-based loading still works (lazy, per shape).\n *\n * Lifecycle:\n * - Textures loaded via `load` / `preload` / `loadAtlas` are owned by\n * this registry and destroyed in `destroy()`.\n * - Textures registered via `register(url, texture)` are external — the\n * caller owns the lifecycle; `destroy()` does not touch them.\n */\n\nimport { Assets, type Texture } from 'pixi.js';\n\nexport class TextureRegistry {\n /** Textures we loaded — we own the lifecycle. */\n private readonly owned = new Map<string, Texture>();\n /** Textures registered externally — caller owns the lifecycle. */\n private readonly external = new Map<string, Texture>();\n\n /** Look up a cached texture by URL or atlas frame name. */\n get(url: string): Texture | undefined {\n return this.owned.get(url) ?? this.external.get(url);\n }\n\n has(url: string): boolean {\n return this.owned.has(url) || this.external.has(url);\n }\n\n /**\n * Register a pre-built texture. Useful for programmatically generated or\n * SVG-constructed textures. The caller retains ownership — `destroy()` will\n * not unload this texture.\n */\n register(url: string, texture: Texture): void {\n this.external.set(url, texture);\n }\n\n /**\n * Load a single URL and cache it. Returns the cached texture on subsequent\n * calls (synchronous fast path). Uses pixi's `Assets` pipeline so the\n * result integrates with the global asset manager.\n *\n * For URLs without a recognised image extension (e.g. picsum.photos,\n * signed CDN URLs, API endpoints) the `loadTextures` parser is explicitly\n * requested so PixiJS doesn't skip loading due to an unknown file type.\n */\n async load(url: string): Promise<Texture> {\n const existing = this.owned.get(url) ?? this.external.get(url);\n if (existing) return existing;\n if (!hasImageExtension(url)) {\n // Pre-register with a parser hint so Assets.load(url) resolves correctly\n Assets.add({ alias: url, src: url, loadParser: 'loadTextures' });\n }\n const texture = await Assets.load<Texture>(url);\n this.owned.set(url, texture);\n return texture;\n }\n\n /** Batch-preload a list of URLs in parallel. Await before first render to avoid mid-frame async loads. */\n async preload(urls: string[]): Promise<void> {\n await Promise.all(urls.map((url) => this.load(url)));\n }\n\n /**\n * Load a PixiJS spritesheet atlas JSON. After this resolves, individual\n * frame textures are accessible via `get(frameName)` where `frameName`\n * matches the keys declared in the atlas JSON.\n *\n * All 1k-icon atlases packed into a single PNG → one GPU upload, one\n * draw call for every sprite sharing that atlas page.\n */\n async loadAtlas(jsonUrl: string): Promise<void> {\n const result = await Assets.load(jsonUrl);\n if (result && typeof result === 'object' && 'textures' in result) {\n for (const [name, tex] of Object.entries(result.textures as Record<string, Texture>)) {\n this.owned.set(name, tex);\n }\n }\n }\n\n /**\n * Unload and destroy all textures owned by this registry. External textures\n * (registered via `register`) are not touched. Call when the host Layer\n * unmounts.\n */\n destroy(): void {\n for (const url of this.owned.keys()) {\n Assets.unload(url).catch(() => {});\n }\n this.owned.clear();\n this.external.clear();\n }\n}\n\n// ─── Internal helpers ──────────────────────────────────────────────────────\n\nconst IMAGE_EXT_RE = /\\.(png|jpe?g|gif|webp|avif|svg|bmp)(\\?|$)/i;\n\n/** True when the URL path ends with a recognised image extension. */\nfunction hasImageExtension(url: string): boolean {\n return IMAGE_EXT_RE.test(url);\n}\n","/**\n * `HitIndex` — thin wrapper around `rbush` for spatial hit-testing.\n *\n * Stays generic over kind ('shape' | 'connector') so a single index serves\n * both. Hit-testing returns candidates in indeterminate order; the renderer\n * resolves topmost-by-zIndex.\n *\n * Per-id slot map keeps `update(id, ...)` O(log n) — we hold onto the\n * inserted entry so we can remove it before re-inserting the new bbox.\n */\n\nimport RBush from 'rbush';\nimport type { Rect } from '../primitives/types';\n\nexport interface HitEntry {\n readonly id: string;\n readonly kind: 'shape' | 'connector';\n /** zIndex from the spec; used by `PrimitivesRenderer` to pick topmost. */\n readonly zIndex: number;\n // rbush indexes by these four fields:\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\nexport class HitIndex {\n private readonly tree = new RBush<HitEntry>();\n private readonly entries = new Map<string, HitEntry>();\n\n insert(id: string, kind: HitEntry['kind'], rect: Rect, zIndex: number): void {\n this.remove(id);\n const entry: HitEntry = {\n id,\n kind,\n zIndex,\n minX: rect.x,\n minY: rect.y,\n maxX: rect.x + rect.width,\n maxY: rect.y + rect.height,\n };\n this.tree.insert(entry);\n this.entries.set(id, entry);\n }\n\n /** Update the bbox + zIndex for an existing entry. No-op if unknown. */\n update(id: string, rect: Rect, zIndex: number): void {\n const prev = this.entries.get(id);\n if (!prev) return;\n this.insert(id, prev.kind, rect, zIndex);\n }\n\n remove(id: string): void {\n const prev = this.entries.get(id);\n if (!prev) return;\n this.tree.remove(prev);\n this.entries.delete(id);\n }\n\n /**\n * Query candidates whose bbox intersects a `padWorld`-padded box around\n * `(x, y)`. With `padWorld = 0` (default), this matches the classic\n * \"point in bbox\" search.\n *\n * The pad exists for the renderer's **screen-pixel hit floor**:\n * `PrimitivesRenderer.hitTest` passes `MIN_HIT_PX / camera.scale` so a\n * shape whose bbox is smaller than the floor (e.g. a node collapsed to\n * sub-pixel size at low zoom) is still in the candidate set. The\n * subsequent `containsWithFloor` / precise check applies the same floor\n * in local coords. Without this pad, rbush would prune the tiny shape\n * before the floor could rescue it.\n *\n * Caller is responsible for the precise per-shape hit-test if the bbox\n * isn't the final answer (e.g. a circle inside its bbox).\n */\n query(x: number, y: number, padWorld: number = 0): HitEntry[] {\n return this.tree.search({\n minX: x - padWorld,\n minY: y - padWorld,\n maxX: x + padWorld,\n maxY: y + padWorld,\n });\n }\n\n clear(): void {\n this.tree.clear();\n this.entries.clear();\n }\n\n /**\n * Bulk replace bboxes for many existing entries in one O(N log N) pass.\n *\n * Per-id `update(...)` does `remove + insert`, and rbush's `remove(item)`\n * is a linear tree walk — so updating thousands of entries one at a time\n * is O(N²). When a behaviour like `NodeSizeLODBehaviour` rescales every\n * node on each camera-zoom frame, the per-id path floors fps even at\n * modest graph sizes.\n *\n * This path swaps the cached entry's bbox in place (the tree still holds\n * the same reference, so we can mutate the four bbox fields directly),\n * then rebuilds the tree once via `clear + load`. Bulk-loading is\n * `O(N log N)` total — for 3k entries, ~10× faster than the per-id\n * variant. zIndex is left untouched.\n *\n * Use when many entries change in the same logical tick (zoom settle,\n * bulk position update). For single-shape edits, prefer {@link update}.\n */\n bulkUpdateBoxes(updates: Iterable<{ id: string; rect: Rect }>): void {\n let touched = false;\n for (const u of updates) {\n const entry = this.entries.get(u.id);\n if (!entry) continue;\n entry.minX = u.rect.x;\n entry.minY = u.rect.y;\n entry.maxX = u.rect.x + u.rect.width;\n entry.maxY = u.rect.y + u.rect.height;\n touched = true;\n }\n if (!touched) return;\n this.tree.clear();\n this.tree.load([...this.entries.values()]);\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n","/**\n * `ShapeInstance` — internal record the renderer keeps per added shape.\n *\n * Holds the spec, the pixi-backed `IShape`, and the active decoration map\n * keyed by slot. Not exported from the package — purely an internal binding\n * between caller spec and rendered output.\n */\n\nimport type {\n BaseShapeSpec,\n IShape,\n IShapeDecoration,\n IShapeEffect,\n} from '../primitives/types';\n\nexport class ShapeInstance<TSpec extends BaseShapeSpec = BaseShapeSpec> {\n readonly decorations = new Map<string, IShapeDecoration>();\n /**\n * Active effects keyed by slot. Effects modulate the host's transform\n * and/or style each frame; the renderer aggregates contributions from\n * every entry and writes the result onto `shape.gfx`.\n */\n readonly effects = new Map<string, IShapeEffect>();\n\n /**\n * Uniform gfx-transform scale most recently written by\n * `PrimitivesRenderer.scaleShape`. Defaults to `1` (no extra scale).\n *\n * The spec's geometry (`radius` / `width` / `height`) describes the\n * shape in unscaled local units; `gfxScale` is the *visual* multiplier\n * the renderer applies on top, used by behaviours like\n * `NodeSizeLODBehaviour` to keep shapes pixel-constant across camera\n * zoom without rebuilding geometry every frame.\n *\n * Anchor / obstacle / endpoint-centre computations multiply the local\n * bounds by this factor so connectors stay glued to the *visible*\n * silhouette — without it, edges anchor to the pre-scaled bounds and\n * visibly fall short of the smaller shape.\n */\n gfxScale: number = 1;\n\n constructor(\n readonly id: string,\n /** Mutable; the renderer merges partial updates onto this in place. */\n public spec: TSpec,\n readonly shape: IShape<TSpec>,\n ) {}\n}\n","/**\n * `ConnectorInstance` — internal record the renderer keeps per added connector.\n *\n * Holds the spec, the pixi-backed `IConnector`, the cached routed `Path`, and\n * the active decoration map keyed by slot. Markers are painted inline by the\n * connector itself via `ShapeCtor.paintInto`. Not exported.\n */\n\nimport type {\n BaseConnectorSpec,\n IConnector,\n IConnectorDecoration,\n IConnectorEffect,\n Path,\n} from '../primitives/types';\n\nexport class ConnectorInstance<TSpec extends BaseConnectorSpec = BaseConnectorSpec> {\n readonly decorations = new Map<string, IConnectorDecoration>();\n /**\n * Active effects keyed by slot. Effects modulate the host connector's\n * style each frame; the renderer aggregates contributions from every\n * entry and writes the result onto `connector.gfx`.\n */\n readonly effects = new Map<string, IConnectorEffect>();\n /** Last router-resolved path. Reused by decoration update + hit-testing. */\n path: Path = [];\n\n /**\n * Render-time multiplier applied to `spec.stroke.width` at draw time.\n * Defaults to `1` (no extra scale). Written by `EdgeSizeLODBehaviour`\n * to `1 / cameraScale` so spec stroke widths render as pixel-constant\n * regardless of camera zoom — symmetric with `ShapeInstance.gfxScale`.\n *\n * The multiplier lives outside `spec` so `setConnectorStroke` /\n * `updateConnector` callers (and the state-config-driven full-spec\n * replacement in `GraphLayer.rerenderEdge`) can rewrite `spec.stroke`\n * without clobbering the LOD intent. The renderer's draw helper reads\n * this field on every draw and applies the multiplication on a\n * shallow-cloned spec, so the canonical `inst.spec` always carries the\n * caller-authored width.\n */\n strokeWidthScale: number = 1;\n\n constructor(\n readonly id: string,\n public spec: TSpec,\n readonly connector: IConnector<TSpec>,\n ) {}\n}\n","import { Container } from 'pixi.js';\n\n/**\n * Common base for every rendered primitive — shapes, connectors, decorations.\n * Owns the root `gfx` Container and a default `destroy` that tears it down\n * along with all children (Pixi removes the destroyed container from its\n * parent automatically).\n *\n * Subclasses add Graphics or other display objects as children of `gfx`.\n */\nexport abstract class PrimitiveBase {\n readonly gfx: Container;\n\n constructor() {\n this.gfx = new Container();\n }\n\n destroy(): void {\n this.gfx.destroy({ children: true });\n }\n}\n","/**\n * Inset-content mount / update / destroy for `glyph`, `svg`, and `svg-url`\n * fill layers. Each inset layer becomes a sibling Container parented to the\n * shape's `gfx`, sized as a fraction of the shape's bounds (`sizeRatio`)\n * and positioned by the layer's `anchor`.\n *\n * Image fills are NOT handled here — they paint into the silhouette via\n * `applyFillStroke.ts` with CSS-`cover` semantics. The engine does not\n * expose an inset-Sprite mode for raster images; reach for a `glyph` /\n * `svg` / `svg-url` layer when a small vector inset is what's wanted.\n *\n * Text labels are NOT handled here either. Multi-character labels\n * (centred-inside, outside-side, or along-path) are rendered by\n * `LabelDecoration` / `LabelConnectorDecoration` via\n * `setDecoration(id, 'label', ...)` — they support backgrounds, wrap /\n * ellipsis, rich (HTML) text, and 13 placements including the\n * inside-centre case the legacy `kind: 'text'` fill layer used to cover.\n *\n * Decorations operate on the silhouette only (via `paintInto`) — they never\n * see inset content. Animated decorations like glow / pulse paint a halo\n * around the silhouette; the inset content sits unaffected on top.\n *\n * `svg-url` layers fetch their SVG asynchronously. The Graphics child is\n * created empty and added to the scene immediately; once the fetch resolves,\n * the path is populated and `positionAndScale` is re-run so the now-non-empty\n * bounds drive the correct scale. Results are cached globally per URL.\n */\n\nimport {\n Container,\n Graphics,\n GraphicsPath,\n Text,\n type TextStyleOptions,\n} from 'pixi.js';\nimport type {\n InsetAnchor,\n Point,\n Rect,\n ShapeFillLayer,\n} from '../types';\n\nexport type InsetLayer = Extract<\n ShapeFillLayer,\n { kind: 'glyph' | 'svg' | 'svg-url' }\n>;\n\nexport interface InsetContentView {\n readonly gfx: Container;\n child: Text | Graphics;\n key: string;\n}\n\nexport function isInsetLayer(layer: ShapeFillLayer): layer is InsetLayer {\n return layer.kind === 'glyph' || layer.kind === 'svg' || layer.kind === 'svg-url';\n}\n\nexport function mountInsetContent(\n parent: Container,\n layer: InsetLayer,\n bounds: Rect,\n visualCenter?: Point,\n): InsetContentView {\n const gfx = new Container();\n gfx.label = `inset:${layer.kind}`;\n gfx.zIndex = 10;\n const reposition = () => positionAndScale(gfx, view.child, layer, bounds, visualCenter);\n const child = renderChild(layer, reposition);\n gfx.addChild(child);\n parent.addChild(gfx);\n const view: InsetContentView = { gfx, child, key: layerKey(layer) };\n positionAndScale(gfx, child, layer, bounds, visualCenter);\n return view;\n}\n\nexport function updateInsetContent(\n view: InsetContentView,\n layer: InsetLayer,\n bounds: Rect,\n visualCenter?: Point,\n): void {\n const key = layerKey(layer);\n if (key !== view.key) {\n view.child.destroy();\n const reposition = () => positionAndScale(view.gfx, view.child, layer, bounds, visualCenter);\n const fresh = renderChild(layer, reposition);\n view.gfx.removeChildren();\n view.gfx.addChild(fresh);\n view.child = fresh;\n view.key = key;\n }\n positionAndScale(view.gfx, view.child, layer, bounds, visualCenter);\n}\n\nexport function destroyInsetContent(view: InsetContentView): void {\n view.gfx.destroy({ children: true });\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\nfunction renderChild(\n layer: InsetLayer,\n onAsyncReady: () => void,\n): Text | Graphics {\n const color = layer.color ?? 0xffffff;\n const alpha = layer.alpha ?? 1;\n\n if (layer.kind === 'glyph') {\n const style: TextStyleOptions = {\n fontFamily: layer.fontFamily ?? 'sans-serif',\n fontSize: 100, // baseline; positionAndScale rescales\n fill: color,\n align: 'center',\n };\n if (layer.fontWeight !== undefined) style.fontWeight = layer.fontWeight as never;\n if (layer.fontStyle !== undefined) style.fontStyle = layer.fontStyle;\n const t = new Text({ text: layer.char, style });\n t.alpha = alpha;\n return t;\n }\n\n if (layer.kind === 'svg') {\n const g = new Graphics();\n g.path(new GraphicsPath(layer.pathD));\n g.stroke({\n color,\n alpha,\n width: layer.strokeWidth ?? 2,\n });\n return g;\n }\n\n // layer.kind === 'svg-url'\n const g = new Graphics();\n void fetchSvgPathD(layer.url)\n .then((pathD) => {\n if (g.destroyed) return;\n g.path(new GraphicsPath(pathD));\n g.stroke({\n color,\n alpha,\n width: layer.strokeWidth ?? 2,\n });\n onAsyncReady();\n })\n .catch((err: unknown) => {\n // Stay quiet on programmatic destroys; surface real errors.\n if (g.destroyed) return;\n // eslint-disable-next-line no-console\n console.warn(`[insetContentLayer] svg-url fetch failed for ${layer.url}:`, err);\n });\n return g;\n}\n\nfunction positionAndScale(\n host: Container,\n child: Text | Graphics,\n layer: InsetLayer,\n bounds: Rect,\n visualCenter?: Point,\n): void {\n // svg-url Graphics start out empty until the fetch resolves.\n if (layer.kind === 'svg-url') {\n const lb = child.getLocalBounds();\n if (lb.width === 0 && lb.height === 0) return;\n }\n\n const local = child.getLocalBounds();\n const scale = resolveScale(layer, bounds, local);\n child.scale.set(scale);\n\n // Position the host container at the anchor point on the shape's bounds.\n // `visualCenter` overrides the AABB midpoint for the `center` anchor only\n // — corner anchors stay bounds-relative.\n const anchor = layer.anchor ?? 'center';\n const [ax, ay] = anchorPoint(anchor, bounds, visualCenter);\n host.position.set(ax, ay);\n\n // Centre the child within the host container — `getLocalBounds` may not be\n // origin-aligned (Text / Graphics path-d both have offsets).\n child.position.set(\n -(local.x + local.width / 2) * scale,\n -(local.y + local.height / 2) * scale,\n );\n host.alpha = layer.alpha ?? 1;\n}\n\n/**\n * Inset kinds (`glyph`, `svg`, `svg-url`) all scale to fit a fraction\n * (`sizeRatio`) of the shape's smaller bounds dimension — the\n * bounds-fraction-square rule. Text labels live on `LabelDecoration` and\n * handle their own sizing.\n */\nfunction resolveScale(layer: InsetLayer, bounds: Rect, local: Rect): number {\n const ratio = layer.sizeRatio ?? 0.6;\n const targetSize = Math.min(bounds.width, bounds.height) * ratio;\n const naturalSize = Math.max(local.width, local.height) || 1;\n return targetSize / naturalSize;\n}\n\nfunction anchorPoint(\n anchor: InsetAnchor,\n b: Rect,\n visualCenter?: Point,\n): [number, number] {\n const inset = Math.min(b.width, b.height) * 0.15;\n switch (anchor) {\n case 'top-left': return [b.x + inset, b.y + inset];\n case 'top-right': return [b.x + b.width - inset, b.y + inset];\n case 'bottom-left': return [b.x + inset, b.y + b.height - inset];\n case 'bottom-right': return [b.x + b.width - inset, b.y + b.height - inset];\n case 'center':\n default:\n return visualCenter\n ? [visualCenter.x, visualCenter.y]\n : [b.x + b.width / 2, b.y + b.height / 2];\n }\n}\n\n/**\n * Identity key for change detection — same shape ⇒ same key. Field-by-field\n * concatenation keeps it cheap; SVG `pathD` is hashed because it can be\n * arbitrarily long.\n */\nfunction layerKey(layer: InsetLayer): string {\n if (layer.kind === 'glyph') {\n return `g:${layer.char}:${layer.fontFamily ?? ''}:${layer.fontWeight ?? ''}:${layer.fontStyle ?? ''}:${layer.color ?? 0xffffff}:${layer.alpha ?? 1}`;\n }\n if (layer.kind === 'svg') {\n return `s:${layer.pathD.length}:${hashString(layer.pathD)}:${layer.strokeWidth ?? 2}:${layer.color ?? 0xffffff}:${layer.alpha ?? 1}`;\n }\n // layer.kind === 'svg-url'\n return `u:${layer.url}:${layer.strokeWidth ?? 2}:${layer.color ?? 0xffffff}:${layer.alpha ?? 1}`;\n}\n\nfunction hashString(s: string): number {\n let h = 5381;\n for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n return h;\n}\n\n// ─── svg-url fetch + parse ─────────────────────────────────────────────────\n\n/**\n * Module-level promise cache keyed by URL. Subsequent shapes using the same\n * URL get the cached path-d immediately (no repeat fetch).\n */\nconst svgCache = new Map<string, Promise<string>>();\n\nfunction fetchSvgPathD(url: string): Promise<string> {\n let pending = svgCache.get(url);\n if (!pending) {\n pending = (async () => {\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`svg-url HTTP ${res.status}: ${url}`);\n }\n const text = await res.text();\n return svgMarkupToPathD(text);\n })();\n svgCache.set(url, pending);\n }\n return pending;\n}\n\n/**\n * Walk an SVG document and concatenate every drawing primitive into a single\n * `pathD` string. Handles `path`, `ellipse`, `circle`, `rect`, `line`,\n * `polyline`, `polygon`. Stroke / fill attributes are dropped — colour and\n * stroke width come from the fill-layer spec.\n */\nfunction svgMarkupToPathD(svg: string): string {\n const doc = new DOMParser().parseFromString(svg, 'image/svg+xml');\n const num = (el: Element, attr: string) => Number(el.getAttribute(attr) ?? 0);\n const pointsToPath = (pts: string, close: boolean): string => {\n const c = pts.trim().split(/[\\s,]+/).map(Number);\n if (c.length < 4) return '';\n let d = `M${c[0]},${c[1]}`;\n for (let i = 2; i < c.length; i += 2) d += ` L${c[i]},${c[i + 1]}`;\n return close ? `${d} Z` : d;\n };\n const ds: string[] = [];\n for (const el of doc.querySelectorAll(\n 'path, ellipse, circle, rect, line, polyline, polygon',\n )) {\n switch (el.tagName.toLowerCase()) {\n case 'path': {\n const d = el.getAttribute('d');\n if (d) ds.push(d);\n break;\n }\n case 'ellipse': {\n const cx = num(el, 'cx'), cy = num(el, 'cy');\n const rx = num(el, 'rx'), ry = num(el, 'ry');\n ds.push(`M${cx - rx},${cy} a${rx},${ry} 0 1,0 ${rx * 2},0 a${rx},${ry} 0 1,0 ${-rx * 2},0 Z`);\n break;\n }\n case 'circle': {\n const cx = num(el, 'cx'), cy = num(el, 'cy'), r = num(el, 'r');\n ds.push(`M${cx - r},${cy} a${r},${r} 0 1,0 ${r * 2},0 a${r},${r} 0 1,0 ${-r * 2},0 Z`);\n break;\n }\n case 'rect': {\n const x = num(el, 'x'), y = num(el, 'y');\n const w = num(el, 'width'), h = num(el, 'height');\n ds.push(`M${x},${y} h${w} v${h} h${-w} Z`);\n break;\n }\n case 'line': {\n ds.push(`M${num(el, 'x1')},${num(el, 'y1')} L${num(el, 'x2')},${num(el, 'y2')}`);\n break;\n }\n case 'polyline': {\n const d = pointsToPath(el.getAttribute('points') ?? '', false);\n if (d) ds.push(d);\n break;\n }\n case 'polygon': {\n const d = pointsToPath(el.getAttribute('points') ?? '', true);\n if (d) ds.push(d);\n break;\n }\n }\n }\n return ds.join(' ');\n}\n","import { Graphics, type IHitArea } from 'pixi.js';\nimport { PrimitiveBase } from './PrimitiveBase';\nimport type {\n BaseShapeSpec,\n IShape,\n Point,\n Rect,\n ShapeFill,\n ShapeFillLayer,\n ShapeHostInfo,\n ShapePaintStyle,\n} from '../types';\nimport {\n destroyInsetContent,\n isInsetLayer,\n mountInsetContent,\n updateInsetContent,\n type InsetLayer,\n type InsetContentView,\n} from '../paint/insetContentLayer';\n\n/**\n * Base for shapes whose `draw` and `paintInto` share a single silhouette\n * trace. Subclasses implement `drawGeometry` (trace path + apply fill +\n * apply stroke) and `bounds`. They get `draw` and `paintInto` for free.\n *\n * The shape's root `gfx` Container holds:\n * - `bodyGfx` — Graphics drawing the silhouette + silhouette-filler\n * fill layers (`solid` / `image`) + border.\n * - inset views — sibling Containers, one per inset-content fill layer\n * (`glyph` / `svg` / `svg-url`), keyed by layer index\n * in `spec.fill`.\n *\n * Decorations operate against `paintInto` — a callback into the silhouette\n * only, never into inset content. This means a glow on a shape with an icon\n * halos the silhouette but leaves the glyph alone.\n */\nexport abstract class ShapeBase<TSpec extends BaseShapeSpec>\n extends PrimitiveBase\n implements IShape<TSpec>\n{\n protected readonly bodyGfx: Graphics;\n protected readonly insetViews = new Map<number, InsetContentView>();\n protected spec!: TSpec;\n\n constructor(protected readonly host: ShapeHostInfo) {\n super();\n this.gfx.sortableChildren = true;\n this.bodyGfx = new Graphics();\n this.bodyGfx.zIndex = 0;\n this.gfx.addChild(this.bodyGfx);\n\n // Hit-test geometry is part of the shape's identity, not the renderer's\n // bookkeeping. Wire `hitArea` once from `getHitArea()` — the default\n // implementation returns an object that delegates to\n // `bodyGfx.containsPoint`, which Pixi answers against the silhouette\n // that `drawGeometry` paints there on every `draw()`. So every shape\n // (graph nodes, ER columns, badges, future composite hosts) gets exact\n // silhouette + stroke-tolerant hit-testing for free, derived from the\n // single source of truth: the geometry trace itself.\n this.gfx.eventMode = 'static';\n this.gfx.cursor = 'pointer';\n this.gfx.hitArea = this.getHitArea();\n }\n\n /**\n * Hit-test region for this shape, derived from {@link drawGeometry}.\n *\n * Default behaviour: the returned `IHitArea`'s `contains(x, y)` delegates\n * to `bodyGfx.containsPoint({ x, y })`. Because `drawGeometry` is the\n * single function that paints the silhouette into `bodyGfx` (see\n * {@link draw}), the hit region tracks the rendered silhouette exactly —\n * including any stroke (Pixi's `containsPoint` uses `strokeContains` for\n * stroke instructions, with a half-stroke-width tolerance).\n *\n * The returned object is stable across `draw()` calls: the closure reads\n * `bodyGfx` by reference, so subsequent `drawGeometry` repaints\n * automatically update the hit region. No re-wiring of `gfx.hitArea`.\n *\n * Subclasses with cheap analytical hit tests — `CircleShape`\n * (`x² + y² ≤ r²`), `RectShape` (AABB) — may override to skip Pixi's\n * path-walk on hot paths. Keep the contract: input is shape-local\n * coordinates; `true` iff the point is inside the silhouette.\n */\n getHitArea(): IHitArea {\n return {\n contains: (x: number, y: number): boolean =>\n this.bodyGfx.containsPoint({ x, y }),\n };\n }\n\n /**\n * Trace the silhouette into `g`, then apply fill + stroke. When `style`\n * is supplied, it overrides the spec's fill/stroke (decoration use).\n */\n protected abstract drawGeometry(\n g: Graphics,\n spec: TSpec,\n style?: ShapePaintStyle,\n ): void;\n\n abstract bounds(): Rect;\n\n draw(spec: TSpec): void {\n this.spec = spec;\n this.gfx.position.set(spec.x, spec.y);\n this.gfx.rotation = spec.rotation ?? 0;\n this.gfx.alpha = spec.alpha ?? 1;\n this.gfx.visible = spec.visible ?? true;\n this.gfx.zIndex = spec.zIndex ?? 0;\n this.bodyGfx.clear();\n this.drawGeometry(this.bodyGfx, spec);\n this.syncInsetLayers(spec);\n }\n\n paintInto(g: Graphics, style?: ShapePaintStyle): void {\n this.drawGeometry(g, this.spec, style);\n }\n\n /**\n * Default boundary intersection: ray from the shape's geometric centre\n * `(0, 0)` toward `localFromCenter`, intersected with a centred AABB\n * derived from `this.bounds()`. Correct for `RectShape` (anchored\n * top-left) and any shape whose silhouette can be approximated by its\n * bounding box.\n *\n * Geometric shapes with non-rectangular silhouettes (`CircleShape`,\n * `EllipseShape`, `PolygonShape`) should override this for pixel-accurate\n * perimeter snapping. Input and output are both centre-relative.\n */\n boundaryIntersect(localFromCenter: Point): Point | null {\n const b = this.bounds();\n const centred: Rect = {\n x: -b.width / 2,\n y: -b.height / 2,\n width: b.width,\n height: b.height,\n };\n return aabbRayExit(localFromCenter, centred);\n }\n\n override destroy(): void {\n for (const view of this.insetViews.values()) destroyInsetContent(view);\n this.insetViews.clear();\n super.destroy();\n }\n\n /**\n * Visual centre — the point inset content with `anchor: 'center'` snaps\n * to. Default is the AABB midpoint of `bounds()`, which is correct for\n * `CircleShape` (bounds is centred on origin) and `RectShape` (bounds is\n * the rect itself). Shapes whose silhouette doesn't fill its AABB —\n * triangle, hexagon, star, free-form polygon — override to return the\n * geometric centroid so a glyph drawn on a triangle sits on the visual\n * centroid instead of floating above it.\n */\n visualCenter(): Point {\n const b = this.bounds();\n return { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n }\n\n /**\n * Diff the spec's inset-content fill layers (`glyph` / `svg` / `svg-url`)\n * against the current `insetViews` map, keyed by layer index. Mounts new\n * layers, updates existing ones, destroys removed ones.\n */\n private syncInsetLayers(spec: TSpec): void {\n const layers = insetLayersByIndex(spec.fill);\n const bounds = this.bounds();\n const centre = this.visualCenter();\n\n // Mount or update layers present in the new spec.\n for (const [index, layer] of layers) {\n const existing = this.insetViews.get(index);\n if (existing) {\n updateInsetContent(existing, layer, bounds, centre);\n } else {\n const view = mountInsetContent(this.gfx, layer, bounds, centre);\n this.insetViews.set(index, view);\n }\n }\n\n // Destroy layers that the new spec no longer has at those indices.\n for (const [index, view] of this.insetViews) {\n if (!layers.has(index)) {\n destroyInsetContent(view);\n this.insetViews.delete(index);\n }\n }\n }\n}\n\n/**\n * Ray from `(0, 0)` toward `localFrom`, parametrised `P(t) = t * localFrom`\n * for `t ≥ 0`. Returns the smallest positive `t` at which `P(t)` exits the\n * AABB `bounds`. When `localFrom` is at the origin the ray is degenerate and\n * we return the bounds origin as a sentinel; callers using this as a\n * `boundary` anchor should ensure the two endpoints differ.\n */\nfunction aabbRayExit(localFrom: Point, bounds: Rect): Point {\n const x = localFrom.x;\n const y = localFrom.y;\n if (x === 0 && y === 0) return { x: bounds.x, y: bounds.y };\n let tMin = Infinity;\n if (x !== 0) {\n const tx = (x > 0 ? bounds.x + bounds.width : bounds.x) / x;\n if (tx > 0 && tx < tMin) tMin = tx;\n }\n if (y !== 0) {\n const ty = (y > 0 ? bounds.y + bounds.height : bounds.y) / y;\n if (ty > 0 && ty < tMin) tMin = ty;\n }\n if (!isFinite(tMin)) return { x: 0, y: 0 };\n return { x: x * tMin, y: y * tMin };\n}\n\n/** Walk a `ShapeFill` and return inset-content layers keyed by their index. */\nfunction insetLayersByIndex(fill: ShapeFill | undefined): Map<number, InsetLayer> {\n const out = new Map<number, InsetLayer>();\n if (fill === undefined || typeof fill === 'number') return out;\n const arr: ReadonlyArray<ShapeFillLayer> = Array.isArray(fill)\n ? fill\n : [fill as ShapeFillLayer];\n for (let i = 0; i < arr.length; i++) {\n const layer = arr[i]!;\n if (isInsetLayer(layer)) out.set(i, layer);\n }\n return out;\n}\n","/**\n * Fill + stroke resolution for `ShapeBase` subclasses.\n *\n * `drawGeometry` traces the silhouette into a `Graphics` once (the initial\n * trace), then calls `applyFill(g, spec, style, host, retrace)` followed by\n * a re-trace and `applyStroke(g, spec, style)`. When `style` is supplied\n * (decoration override) it takes precedence over `spec.fill` / `spec.stroke`.\n *\n * Layered fills: `spec.fill` may be a single layer or an array. This module\n * iterates only **silhouette-filler** layer kinds — `solid` and `image` —\n * painting each into the silhouette via `g.fill()`. Image layers honour\n * two CSS-aligned knobs: `fit` (`'cover'` default, or `'contain'`) and\n * `padding` (pixel inset on the silhouette for *this layer only*, so the\n * gap between the full silhouette and the inset silhouette paints from\n * the layer underneath — typically a `solid` plate). The `retrace`\n * callback supplied by the shape accepts the requested inset and\n * re-traces its silhouette accordingly; every built-in shape's\n * `drawGeometry` already honours `style.inset`, so per-layer padding\n * works uniformly across `circle` / `rect` / `polygon` / `regular-polygon`\n * / `star` / `arc`. Multiple silhouette layers are supported — each is\n * re-traced before painting (Pixi's `fill` consumes the most recent\n * path). **Inset-content** layers (`glyph`, `svg`, `svg-url`) are handled\n * separately by `ShapeBase.syncInsetLayers` / `insetContentLayer.ts` —\n * they're skipped here.\n */\n\nimport { Matrix, type Graphics, type Texture } from 'pixi.js';\nimport type {\n BaseShapeSpec,\n Rect,\n ShapeFill,\n ShapeFillLayer,\n ShapeHostInfo,\n ShapePaintStyle,\n ShapeStroke,\n} from '../types';\n\ntype SilhouetteLayer = Extract<ShapeFillLayer, { kind: 'solid' | 'image' }>;\n\nexport function applyFill(\n g: Graphics,\n spec: BaseShapeSpec,\n style: ShapePaintStyle | undefined,\n host: ShapeHostInfo,\n bounds: Rect,\n retrace: (inset?: number) => void,\n): void {\n if (style) {\n if (style.fill === false) return;\n if (style.color === undefined) return;\n g.fill({ color: style.color, alpha: style.alpha ?? 1 });\n return;\n }\n\n if (spec.fill === undefined) return;\n\n const layers = silhouetteLayersOf(spec.fill);\n for (let i = 0; i < layers.length; i++) {\n const layer = layers[i]!;\n const inset = layerInset(layer);\n // Retrace when we're past the first layer (its silhouette was already\n // consumed) or when this layer wants a non-zero inset (the pre-applyFill\n // trace is at inset 0). Otherwise the first layer can reuse the trace\n // the shape made before calling applyFill.\n if (i > 0 || inset > 0) retrace(inset);\n paintSilhouetteLayer(g, layer, host, insetBounds(bounds, inset));\n }\n}\n\nexport function applyStroke(\n g: Graphics,\n spec: BaseShapeSpec,\n style: ShapePaintStyle | undefined,\n): void {\n if (style?.strokeWidth !== undefined) {\n // Decorations default to `'outside'` alignment so their stroke lives\n // wholly past the silhouette instead of bleeding inward (Pixi's\n // built-in default is center-aligned, which makes a halo's inner band\n // cover the host body — see the `selected` ring + glow regression).\n g.stroke({\n color: style.color ?? 0x000000,\n alpha: style.alpha ?? 1,\n width: style.strokeWidth,\n alignment: alignmentFor(style.alignment ?? 'outside'),\n });\n return;\n }\n\n const s = spec.stroke;\n if (!s) return;\n const width = s.width ?? 1;\n if (width <= 0) return;\n g.stroke({\n color: s.color,\n alpha: s.alpha ?? 1,\n width,\n alignment: alignmentFor(s.alignment),\n cap: s.cap,\n join: s.join,\n });\n}\n\n/**\n * Static-`paintInto` helper for marker shapes. Markers are drawn into a\n * connector's `Graphics` by static methods that have no `host`, so image\n * fills aren't supported here — only `solid` (and the `number` shorthand)\n * apply. The first solid layer in `fill` is used; remaining layers are\n * ignored. Decoration `style` takes precedence.\n */\nexport function applyMarkerFill(\n g: Graphics,\n fill: ShapeFill | undefined,\n style: ShapePaintStyle | undefined,\n): void {\n if (style?.fill !== false && style?.color !== undefined) {\n g.fill({ color: style.color, alpha: style.alpha ?? 1 });\n return;\n }\n if (fill === undefined) return;\n if (typeof fill === 'number') {\n g.fill({ color: fill });\n return;\n }\n for (const layer of toLayerArray(fill)) {\n if (layer.kind === 'solid') {\n g.fill({ color: layer.color, alpha: layer.alpha ?? 1 });\n return;\n }\n }\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\nfunction silhouetteLayersOf(fill: ShapeFill): ReadonlyArray<SilhouetteLayer | { kind: 'shorthand'; color: number }> {\n if (typeof fill === 'number') return [{ kind: 'shorthand', color: fill }];\n return toLayerArray(fill).filter(isSilhouetteLayer);\n}\n\nfunction toLayerArray(fill: Exclude<ShapeFill, number>): ReadonlyArray<ShapeFillLayer> {\n return Array.isArray(fill) ? fill : [fill as ShapeFillLayer];\n}\n\nfunction isSilhouetteLayer(layer: ShapeFillLayer): layer is SilhouetteLayer {\n return layer.kind === 'solid' || layer.kind === 'image';\n}\n\nfunction paintSilhouetteLayer(\n g: Graphics,\n layer: SilhouetteLayer | { kind: 'shorthand'; color: number },\n host: ShapeHostInfo,\n bounds: Rect,\n): void {\n if (layer.kind === 'shorthand') {\n g.fill({ color: layer.color });\n return;\n }\n if (layer.kind === 'solid') {\n g.fill({ color: layer.color, alpha: layer.alpha ?? 1 });\n return;\n }\n const tex = host.textureRegistry.get(layer.url);\n if (!tex) {\n void host.textureRegistry\n .load(layer.url)\n .then(() => host.requestRedraw())\n .catch((err: unknown) => {\n // eslint-disable-next-line no-console\n console.warn(`[applyFill] image load failed for ${layer.url}:`, err);\n });\n return;\n }\n // Force clamp-to-edge on the texture's sampler so UV outside [0, 1]\n // reads the boundary pixel instead of tiling. Pixi v8 reads the wrap\n // mode from `source.style.addressModeU` / `addressModeV`; assignment\n // alone is not enough — `TextureStyle` caches the GPU sampler resource\n // ID on `_sharedResourceId`, and reuses the previously-built sampler\n // (default `'repeat'`) until `style.update()` invalidates the cache\n // and re-emits `'change'`. Without the explicit `update()` you see\n // tiled copies of the texture across the silhouette for `fit:\n // 'contain'` (and any other case where the matrix maps UV outside\n // [0, 1]). For PNG sources with transparent edges, clamp-to-edge\n // yields a transparent margin (the underlying `bgFill` reads\n // through); for opaque sources it smears the edge pixel as a\n // 1px-stretched border.\n const style = tex.source.style;\n if (style.addressModeU !== 'clamp-to-edge' || style.addressModeV !== 'clamp-to-edge') {\n style.addressMode = 'clamp-to-edge';\n style.update();\n }\n const matrix = textureFitMatrix(layer.fit ?? 'cover', tex, bounds);\n // `textureSpace: 'global'` — interpret our `matrix` as texture→world\n // (forward mapping) without Pixi's default local-bounds auto-fit. Without\n // this, Pixi pre-normalises UV to the shape's bounds and our custom\n // scaling stacks on top of the already-fitted UV.\n g.fill({ texture: tex, alpha: layer.alpha ?? 1, matrix, textureSpace: 'global' });\n}\n\n/**\n * Forward texture→world matrix sizing `tex` into `bounds` per the chosen\n * fit mode. Uniform scale either way; the only difference is `max(...)` vs\n * `min(...)` for the cover-vs-contain decision. The result is centred on\n * the cross-axis. With `textureSpace: 'global'` on the `fill` call, Pixi\n * inverts this and uses it directly for the UV-from-position transform.\n *\n * - `'cover'` — texture fully covers `bounds`; may crop on the\n * cross-axis but never leaves transparent edges.\n * - `'contain'` — texture fully fits inside `bounds`; may letterbox.\n * The letterbox area still samples the texture, but\n * sits outside [0,1] UV → tiles via Pixi's repeat\n * addressMode. For a clean transparent letterbox,\n * pair the image layer with `padding > 0` so the\n * silhouette is shrunk to match the texture's\n * aspect-fit rect.\n */\nfunction textureFitMatrix(\n fit: 'cover' | 'contain',\n tex: Texture,\n bounds: Rect,\n): Matrix {\n const tw = tex.width || 1;\n const th = tex.height || 1;\n const sx = bounds.width / tw;\n const sy = bounds.height / th;\n const s = fit === 'cover' ? Math.max(sx, sy) : Math.min(sx, sy);\n const mappedW = tw * s;\n const mappedH = th * s;\n const tx = bounds.x + (bounds.width - mappedW) / 2;\n const ty = bounds.y + (bounds.height - mappedH) / 2;\n return new Matrix().set(s, 0, 0, s, tx, ty);\n}\n\nfunction layerInset(\n layer: SilhouetteLayer | { kind: 'shorthand'; color: number },\n): number {\n return layer.kind === 'image' ? layer.padding ?? 0 : 0;\n}\n\nfunction insetBounds(bounds: Rect, inset: number): Rect {\n if (inset <= 0) return bounds;\n return {\n x: bounds.x + inset,\n y: bounds.y + inset,\n width: Math.max(0, bounds.width - inset * 2),\n height: Math.max(0, bounds.height - inset * 2),\n };\n}\n\nfunction alignmentFor(a: ShapeStroke['alignment']): number {\n return a === 'inside' ? 1 : a === 'outside' ? 0 : 0.5;\n}\n","/**\n * Dashed-stroke emitter. PixiJS v8's `g.stroke()` has no native dashed\n * support, so any shape / connector that needs a dashed silhouette routes\n * through here. The emitter walks a polyline cumulatively by arc length,\n * alternating dash / gap intervals; each in-dash segment is emitted as a\n * `moveTo` + `lineTo` pair. A single `g.stroke({...})` at the end paints\n * every dash uniformly.\n *\n * Callers:\n * - `ShapeBase` subclasses sample their silhouette into points and call\n * `emitDashedStroke(g, points, { closed: true, ... })`.\n * - `Connector` densifies its routed `Path` via `samplePath(...)` and\n * calls `emitDashedStroke(g, points, { closed: false, ... })`.\n *\n * `dashOffset` semantics: at arc length `s`, the position in the dash\n * cycle is `(s + dashOffset) mod (dash + gap)`. Negative `dashOffset`\n * shifts the pattern backward — which visually moves dashes forward along\n * the path, producing the \"marching ants\" effect for a continuously\n * decreasing offset.\n */\n\nimport type { Graphics } from 'pixi.js';\nimport type { Point } from '../types';\n\nexport interface DashedStrokeOptions {\n readonly color: number;\n readonly alpha?: number;\n readonly width: number;\n readonly dashArray: readonly [number, number];\n readonly dashOffset?: number;\n /** When `true`, an implicit closing segment joins last → first. */\n readonly closed?: boolean;\n readonly cap?: 'butt' | 'round' | 'square';\n readonly join?: 'miter' | 'round' | 'bevel';\n}\n\nexport function emitDashedStroke(\n g: Graphics,\n points: ReadonlyArray<Point>,\n opts: DashedStrokeOptions,\n): void {\n const [dash, gap] = opts.dashArray;\n const period = dash + gap;\n if (points.length < 2 || dash <= 0 || period <= 0 || opts.width <= 0) return;\n\n // Normalize offset into [0, period). `dashOffset` shifts the pattern: at\n // arc-length 0 the cycle phase is `dashOffset mod period`. Phase < dash\n // → currently inside a dash; otherwise inside a gap.\n const rawOffset = opts.dashOffset ?? 0;\n let phase = rawOffset % period;\n if (phase < 0) phase += period;\n\n let inDash = phase < dash;\n let remaining = inDash ? dash - phase : period - phase;\n let penX = points[0]!.x;\n let penY = points[0]!.y;\n let segIdx = 0;\n\n const segmentCount = opts.closed ? points.length : points.length - 1;\n\n while (segIdx < segmentCount) {\n const a = points[segIdx]!;\n const b = points[(segIdx + 1) % points.length]!;\n const dx = b.x - penX;\n const dy = b.y - penY;\n const segLen = Math.hypot(dx, dy);\n\n if (segLen <= 0) {\n segIdx++;\n if (segIdx < segmentCount) {\n const next = points[segIdx]!;\n penX = next.x;\n penY = next.y;\n }\n continue;\n }\n\n if (remaining >= segLen) {\n // Entire remaining segment fits inside the current dash/gap interval.\n if (inDash) {\n g.moveTo(penX, penY);\n g.lineTo(b.x, b.y);\n }\n remaining -= segLen;\n penX = b.x;\n penY = b.y;\n segIdx++;\n } else {\n // Boundary crossing partway through the segment.\n const t = remaining / segLen;\n const cx = penX + dx * t;\n const cy = penY + dy * t;\n if (inDash) {\n g.moveTo(penX, penY);\n g.lineTo(cx, cy);\n }\n penX = cx;\n penY = cy;\n inDash = !inDash;\n remaining = inDash ? dash : gap;\n }\n // Avoid using `a` after consumption (suppresses unused-var on tight loops).\n void a;\n }\n\n g.stroke({\n color: opts.color,\n alpha: opts.alpha ?? 1,\n width: opts.width,\n cap: opts.cap,\n join: opts.join,\n });\n}\n","import type { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport { applyFill, applyMarkerFill, applyStroke } from '../paint/applyFillStroke';\nimport { emitDashedStroke } from '../paint/dashedStroke';\nimport type {\n CircleSpec,\n Point,\n Rect,\n ShapeHostInfo,\n ShapePaintStyle,\n} from '../types';\n\n/**\n * Filled / stroked circle. Centered at `(spec.x, spec.y)`; the silhouette\n * is traced in shape-local space (origin at the center). Inset-content fill\n * layers (glyph / svg / svg-url) are mounted as sibling Containers by\n * `ShapeBase` — they appear centred (or anchored) inside the circle.\n */\nexport class CircleShape extends ShapeBase<CircleSpec> {\n static readonly kind = 'circle';\n\n constructor(spec: CircleSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: CircleSpec, style?: ShapePaintStyle): void {\n const baseInset = style?.inset ?? 0;\n const r = Math.max(0, spec.radius - baseInset);\n\n const dashArray = style?.dashArray ?? spec.stroke?.dashArray;\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n emitDashedStroke(g, sampleCircleOutline(r), {\n color: style?.color ?? spec.stroke?.color ?? 0x000000,\n alpha: style?.alpha ?? spec.stroke?.alpha ?? 1,\n width: style?.strokeWidth ?? spec.stroke?.width ?? 1,\n dashArray,\n dashOffset: style?.dashOffset ?? spec.stroke?.dashOffset,\n closed: true,\n });\n return;\n }\n\n // Pixi's `g.circle(...)` chooses segment count from the world-coord\n // radius — at very small radii (e.g. when `ScreenSizeBehaviour` shrinks\n // a screen-constant node's world radius to ~0.01 at high camera zoom)\n // it falls to 4–6 segments and the result reads as a diamond / octagon.\n // We trace through `regularPoly` with a floor of 32 sides, which is\n // visually indistinguishable from a true circle at any reasonable\n // effective size while staying cheap on the vertex budget.\n const trace = (extra = 0) => {\n const rr = Math.max(0, spec.radius - baseInset - extra);\n const segments = Math.max(32, Math.ceil((Math.PI * 2 * rr) / 4));\n g.regularPoly(0, 0, rr, segments);\n };\n trace();\n applyFill(g, spec, style, this.host, this.bounds(), trace);\n trace();\n applyStroke(g, spec, style);\n }\n\n bounds(): Rect {\n return CircleShape.boundsOf(this.spec);\n }\n\n static boundsOf(spec: Omit<CircleSpec, 'x' | 'y'>): Rect {\n const r = spec.radius;\n return { x: -r, y: -r, width: r * 2, height: r * 2 };\n }\n\n static scaleSpec(spec: Omit<CircleSpec, 'x' | 'y'>, factor: number): Partial<CircleSpec> {\n return { radius: spec.radius * factor };\n }\n\n contains(localX: number, localY: number): boolean {\n const r = this.spec.radius;\n return localX * localX + localY * localY <= r * r;\n }\n\n /**\n * Analytical perimeter intersection. `CircleShape` is centred at its\n * origin, so \"centre-relative\" and \"origin-relative\" local coords are the\n * same here. The boundary point along the ray from `(0, 0)` toward\n * `localFromCenter` is just the unit vector scaled by the radius.\n * When `localFromCenter` coincides with the centre the ray is degenerate;\n * we return `(r, 0)` as a stable sentinel.\n */\n override boundaryIntersect(localFromCenter: Point): Point {\n const d = Math.hypot(localFromCenter.x, localFromCenter.y);\n const r = this.spec.radius;\n if (d === 0) return { x: r, y: 0 };\n return { x: (localFromCenter.x / d) * r, y: (localFromCenter.y / d) * r };\n }\n\n /**\n * Silhouette obstacle-test for routers. Returns a closure over the\n * circle's current `(centre, radius)` that tests world points against\n * the inflated disc — pixel-tight, not the AABB-square. Routes hug the\n * circle's tangent instead of avoiding its bounding box corners.\n */\n obstacleTest(): (worldX: number, worldY: number, inflate: number) => boolean {\n const cx = this.spec.x;\n const cy = this.spec.y;\n const r = this.spec.radius;\n return (worldX, worldY, inflate) => {\n const dx = worldX - cx;\n const dy = worldY - cy;\n const limit = r + inflate;\n return dx * dx + dy * dy <= limit * limit;\n };\n }\n\n /**\n * Static paint surface for marker rendering. Connectors call this when\n * a circle is used as a source/target marker (no instantiation, just a\n * paint into someone else's Graphics). Only the first solid layer of\n * `spec.fill` is honoured here — markers don't support image fills or\n * inset content.\n */\n static paintInto(\n g: Graphics,\n spec: Omit<CircleSpec, 'x' | 'y'>,\n anchor: Point,\n _angleRad: number,\n style?: ShapePaintStyle,\n ): void {\n const r = Math.max(0, spec.radius - (style?.inset ?? 0));\n // Same fixed-segment trace as the instance path — see comment in\n // `draw()` above. Markers occasionally render at small effective\n // sizes (high-zoom edge tips), so the floor matters here too.\n const segments = Math.max(32, Math.ceil((Math.PI * 2 * r) / 4));\n g.regularPoly(anchor.x, anchor.y, r, segments);\n applyMarkerFill(g, spec.fill, style);\n }\n}\n\n/**\n * Densify the circle outline into a polyline for dashed-stroke emission.\n * Step count is proportional to perimeter (≈ 1 vertex per 4 px), clamped\n * to a minimum that keeps small circles smooth. Output is centred at the\n * origin and traverses counter-clockwise from `(r, 0)`.\n */\nfunction sampleCircleOutline(r: number): Point[] {\n if (r <= 0) return [];\n const n = Math.max(24, Math.ceil((Math.PI * 2 * r) / 4));\n const out: Point[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const a = (i / n) * Math.PI * 2;\n out[i] = { x: Math.cos(a) * r, y: Math.sin(a) * r };\n }\n return out;\n}\n","import type { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport { applyFill, applyMarkerFill, applyStroke } from '../paint/applyFillStroke';\nimport { emitDashedStroke } from '../paint/dashedStroke';\nimport type {\n Point,\n Rect,\n RectSpec,\n ShapeHostInfo,\n ShapePaintStyle,\n} from '../types';\n\n/**\n * Axis-aligned rectangle with optional `cornerRadius`. Anchored at its\n * top-left corner in shape-local space; `(spec.x, spec.y)` is the world\n * position of that corner. A \"square\" is just `RectShape` with\n * `width === height` and no `cornerRadius`.\n */\nexport class RectShape extends ShapeBase<RectSpec> {\n static readonly kind = 'rect';\n\n constructor(spec: RectSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: RectSpec, style?: ShapePaintStyle): void {\n const baseInset = style?.inset ?? 0;\n const w0 = Math.max(0, spec.width - baseInset * 2);\n const h0 = Math.max(0, spec.height - baseInset * 2);\n const cr0 = Math.max(0, (spec.cornerRadius ?? 0) - baseInset);\n\n const dashArray = style?.dashArray ?? spec.stroke?.dashArray;\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n emitDashedStroke(g, sampleRectOutline(baseInset, baseInset, w0, h0, cr0), {\n color: style?.color ?? spec.stroke?.color ?? 0x000000,\n alpha: style?.alpha ?? spec.stroke?.alpha ?? 1,\n width: style?.strokeWidth ?? spec.stroke?.width ?? 1,\n dashArray,\n dashOffset: style?.dashOffset ?? spec.stroke?.dashOffset,\n closed: true,\n });\n return;\n }\n\n const trace = (extra = 0) => {\n const i = baseInset + extra;\n const w = Math.max(0, spec.width - i * 2);\n const h = Math.max(0, spec.height - i * 2);\n const cr = Math.max(0, (spec.cornerRadius ?? 0) - i);\n if (cr > 0) g.roundRect(i, i, w, h, cr);\n else g.rect(i, i, w, h);\n };\n trace();\n applyFill(g, spec, style, this.host, this.bounds(), trace);\n trace();\n applyStroke(g, spec, style);\n }\n\n bounds(): Rect {\n return RectShape.boundsOf(this.spec);\n }\n\n static boundsOf(spec: Omit<RectSpec, 'x' | 'y'>): Rect {\n return { x: 0, y: 0, width: spec.width, height: spec.height };\n }\n\n static scaleSpec(spec: Omit<RectSpec, 'x' | 'y'>, factor: number): 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 contains(localX: number, localY: number): boolean {\n return (\n localX >= 0 && localY >= 0 &&\n localX <= this.spec.width && localY <= this.spec.height\n );\n }\n\n /**\n * Silhouette-aware ray exit. For `cornerRadius > 0` the AABB face isn't\n * the actual outline — the rendered rect rounds inward at each corner.\n * Take the AABB exit first; if it falls in one of the four corner zones\n * (within `R` of a corner in both axes), re-cast the ray against that\n * corner's quarter-circle so the returned point sits on the visible\n * silhouette. For sharp rects this is unchanged from the AABB fallback.\n */\n override boundaryIntersect(localFromCenter: Point): Point | null {\n const cr = this.spec.cornerRadius ?? 0;\n if (cr <= 0) return super.boundaryIntersect(localFromCenter);\n\n const halfW = this.spec.width / 2;\n const halfH = this.spec.height / 2;\n const R = Math.min(cr, halfW, halfH);\n\n const aabb = super.boundaryIntersect(localFromCenter);\n if (!aabb) return null;\n\n const onRight = aabb.x > halfW - R;\n const onLeft = aabb.x < -halfW + R;\n const onTop = aabb.y < -halfH + R;\n const onBot = aabb.y > halfH - R;\n let cornerX: number;\n let cornerY: number;\n if (onRight && onTop) { cornerX = halfW - R; cornerY = -halfH + R; }\n else if (onRight && onBot) { cornerX = halfW - R; cornerY = halfH - R; }\n else if (onLeft && onTop) { cornerX = -halfW + R; cornerY = -halfH + R; }\n else if (onLeft && onBot) { cornerX = -halfW + R; cornerY = halfH - R; }\n else return aabb;\n\n const len = Math.hypot(localFromCenter.x, localFromCenter.y);\n if (len === 0) return aabb;\n const ux = localFromCenter.x / len;\n const uy = localFromCenter.y / len;\n // Solve |t·(ux,uy) − C|² = R² with unit direction → quadratic in t:\n // t² − 2·dot·t + (Cx² + Cy² − R²) = 0\n // The rect interior in a corner zone is inside the arc circle (the\n // arc centre sits inside the body), so the ray exits the rect where\n // it crosses *out* of the circle — the larger positive root.\n const dot = ux * cornerX + uy * cornerY;\n const c = cornerX * cornerX + cornerY * cornerY - R * R;\n const disc = dot * dot - c;\n if (disc < 0) return aabb;\n const t = dot + Math.sqrt(disc);\n return { x: ux * t, y: uy * t };\n }\n\n static paintInto(\n g: Graphics,\n spec: Omit<RectSpec, 'x' | 'y'>,\n anchor: Point,\n _angleRad: number,\n style?: ShapePaintStyle,\n ): void {\n const cr = spec.cornerRadius ?? 0;\n const x = anchor.x - spec.width / 2;\n const y = anchor.y - spec.height / 2;\n if (cr > 0) g.roundRect(x, y, spec.width, spec.height, cr);\n else g.rect(x, y, spec.width, spec.height);\n applyMarkerFill(g, spec.fill, style);\n }\n}\n\n/**\n * Densify the rect outline into a polyline. For `cornerRadius > 0` each\n * corner arc is sampled with vertex count proportional to the radius\n * (~1 vertex per 2 px of arc, min 4). Output traverses clockwise from the\n * top-left corner (or, with rounded corners, from the start of the top\n * edge — the post-corner point on the top).\n */\nfunction sampleRectOutline(\n x: number,\n y: number,\n w: number,\n h: number,\n cr: number,\n): Point[] {\n if (w <= 0 || h <= 0) return [];\n const r = Math.min(cr, w / 2, h / 2);\n if (r <= 0) {\n return [\n { x, y },\n { x: x + w, y },\n { x: x + w, y: y + h },\n { x, y: y + h },\n ];\n }\n\n const arcSteps = Math.max(4, Math.ceil((Math.PI * 0.5 * r) / 2));\n const out: Point[] = [];\n // Quadrant centres (clockwise from top-left).\n const corners: ReadonlyArray<{ cx: number; cy: number; a0: number }> = [\n { cx: x + r, cy: y + r, a0: Math.PI }, // TL: π → 1.5π\n { cx: x + w - r, cy: y + r, a0: Math.PI * 1.5 }, // TR: 1.5π → 2π\n { cx: x + w - r, cy: y + h - r, a0: 0 }, // BR: 0 → 0.5π\n { cx: x + r, cy: y + h - r, a0: Math.PI * 0.5 }, // BL: 0.5π → π\n ];\n for (const c of corners) {\n for (let i = 0; i <= arcSteps; i++) {\n const t = i / arcSteps;\n const a = c.a0 + t * (Math.PI * 0.5);\n out.push({ x: c.cx + Math.cos(a) * r, y: c.cy + Math.sin(a) * r });\n }\n }\n return out;\n}\n","/**\n * Polygon math helpers shared by `PolygonShape`, `RegularPolygonShape`, and\n * `StarShape`. Pure functions, no `pixi.js` imports — everything operates on\n * plain `{x, y}` vertex arrays in shape-local space.\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.\n */\n\nimport type { Point, Rect } from '../types';\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/**\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 `PolygonShape` insets are best-effort and may\n * self-intersect at 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// ─── 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","import type { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport { applyFill, applyMarkerFill, applyStroke } from '../paint/applyFillStroke';\nimport { emitDashedStroke } from '../paint/dashedStroke';\nimport {\n offsetPolygon,\n pointInPolygon,\n polygonBounds,\n rayPolygonIntersection,\n} from './_polyUtils';\nimport type {\n Point,\n PolygonSpec,\n Rect,\n ShapeHostInfo,\n ShapePaintStyle,\n} from '../types';\n\n/**\n * Free-form polygon. Vertices are centre-relative — the silhouette is traced\n * around the origin in shape-local space and the `gfx` Container translates\n * the result to `(spec.x, spec.y)`. The polygon is treated as closed: the\n * trace returns to the first vertex automatically.\n */\nexport class PolygonShape extends ShapeBase<PolygonSpec> {\n static readonly kind = 'polygon';\n\n constructor(spec: PolygonSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: PolygonSpec, style?: ShapePaintStyle): void {\n const baseInset = style?.inset ?? 0;\n const verts = resolveVertices(spec.vertices, baseInset);\n if (verts.length < 3) return;\n\n const dashArray = style?.dashArray ?? spec.stroke?.dashArray;\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n emitDashedStroke(g, verts, {\n color: style?.color ?? spec.stroke?.color ?? 0x000000,\n alpha: style?.alpha ?? spec.stroke?.alpha ?? 1,\n width: style?.strokeWidth ?? spec.stroke?.width ?? 1,\n dashArray,\n dashOffset: style?.dashOffset ?? spec.stroke?.dashOffset,\n closed: true,\n });\n return;\n }\n\n const trace = (extra = 0) => {\n const v = extra > 0 ? resolveVertices(spec.vertices, baseInset + extra) : verts;\n if (v.length >= 3) tracePolygon(g, v);\n };\n trace();\n applyFill(g, spec, style, this.host, this.bounds(), trace);\n trace();\n applyStroke(g, spec, style);\n }\n\n bounds(): Rect {\n return PolygonShape.boundsOf(this.spec);\n }\n\n static boundsOf(spec: Omit<PolygonSpec, 'x' | 'y'>): Rect {\n return polygonBounds(spec.vertices);\n }\n\n static scaleSpec(spec: Omit<PolygonSpec, 'x' | 'y'>, factor: number): Partial<PolygonSpec> {\n return { vertices: spec.vertices.map((v) => ({ x: v.x * factor, y: v.y * factor })) };\n }\n\n /**\n * Vertices are authored centre-relative, so the local origin is the\n * natural visual centre. Returning `(0, 0)` instead of the AABB midpoint\n * keeps inset glyphs / icons sitting where the user expects when the\n * polygon's silhouette doesn't fill its AABB (e.g. the chevron's notch\n * leaves empty space on the left of the box).\n */\n override visualCenter(): Point {\n return { x: 0, y: 0 };\n }\n\n contains(localX: number, localY: number): boolean {\n return pointInPolygon(localX, localY, this.spec.vertices);\n }\n\n /**\n * Analytical ray-to-edge intersection. Polygon vertices are already\n * centre-relative, so `localFromCenter` shares the same frame as the\n * stored vertices.\n */\n override boundaryIntersect(localFromCenter: Point): Point | null {\n return rayPolygonIntersection(localFromCenter, this.spec.vertices);\n }\n\n /**\n * Silhouette obstacle-test for routers. Translates the world point into\n * shape-local space and runs an even-odd point-in-polygon test against the\n * polygon expanded by `inflate`. Tight against the actual silhouette\n * instead of the AABB, so routes hug concave / angular outlines.\n */\n obstacleTest(): (worldX: number, worldY: number, inflate: number) => boolean {\n const cx = this.spec.x;\n const cy = this.spec.y;\n const baseVerts = this.spec.vertices;\n let cachedInflate = Number.NaN;\n let cachedVerts: ReadonlyArray<Point> = baseVerts;\n return (worldX, worldY, inflate) => {\n if (inflate !== cachedInflate) {\n cachedInflate = inflate;\n cachedVerts = inflate === 0 ? baseVerts : offsetPolygon(baseVerts, -inflate);\n }\n return pointInPolygon(worldX - cx, worldY - cy, cachedVerts);\n };\n }\n\n /**\n * Marker paint surface. Rotates the vertex list by `angleRad`, translates\n * to `anchor`, then traces + fills. Only the first solid layer of\n * `spec.fill` is honoured (markers don't support image / inset fills).\n */\n static paintInto(\n g: Graphics,\n spec: Omit<PolygonSpec, 'x' | 'y'>,\n anchor: Point,\n angleRad: number,\n style?: ShapePaintStyle,\n ): void {\n const verts = resolveVertices(spec.vertices, style?.inset ?? 0);\n if (verts.length < 3) return;\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const placed: Point[] = verts.map((v) => ({\n x: anchor.x + v.x * cos - v.y * sin,\n y: anchor.y + v.x * sin + v.y * cos,\n }));\n tracePolygon(g, placed);\n applyMarkerFill(g, spec.fill, style);\n }\n}\n\nfunction resolveVertices(\n vertices: ReadonlyArray<Point>,\n inset: number,\n): ReadonlyArray<Point> {\n if (inset === 0) return vertices;\n return offsetPolygon(vertices, inset);\n}\n\nfunction tracePolygon(g: Graphics, vertices: ReadonlyArray<Point>): void {\n const first = vertices[0]!;\n g.moveTo(first.x, first.y);\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i]!;\n g.lineTo(v.x, v.y);\n }\n g.closePath();\n}\n","import type { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport { applyFill, applyMarkerFill, applyStroke } from '../paint/applyFillStroke';\nimport { emitDashedStroke } from '../paint/dashedStroke';\nimport {\n offsetPolygon,\n pointInPolygon,\n polygonBounds,\n rayPolygonIntersection,\n regularPolygonVertices,\n} from './_polyUtils';\nimport type {\n Point,\n Rect,\n RegularPolygonSpec,\n ShapeHostInfo,\n ShapePaintStyle,\n} from '../types';\n\n/**\n * Regular n-gon centred at `(spec.x, spec.y)` with circum-radius\n * `spec.radius`. With `rotation = 0` the first vertex points straight up, so\n * a triangle / pentagon / heptagon points up by default and a hexagon is\n * pointy-top. Pass `rotation: Math.PI / 6` for a flat-top hexagon.\n *\n * Vertices are recomputed on every `draw`. For hot paths consider caching at\n * the spec level — but a regular polygon's vertex count is small so the cost\n * is dominated by Pixi's path emission, not the trig.\n */\nexport class RegularPolygonShape extends ShapeBase<RegularPolygonSpec> {\n static readonly kind = 'regular-polygon';\n\n constructor(spec: RegularPolygonSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: RegularPolygonSpec, style?: ShapePaintStyle): void {\n const baseInset = style?.inset ?? 0;\n const verts = computeVertices(spec, baseInset);\n if (verts.length < 3) return;\n\n const dashArray = style?.dashArray ?? spec.stroke?.dashArray;\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n emitDashedStroke(g, verts, {\n color: style?.color ?? spec.stroke?.color ?? 0x000000,\n alpha: style?.alpha ?? spec.stroke?.alpha ?? 1,\n width: style?.strokeWidth ?? spec.stroke?.width ?? 1,\n dashArray,\n dashOffset: style?.dashOffset ?? spec.stroke?.dashOffset,\n closed: true,\n });\n return;\n }\n\n const trace = (extra = 0) => {\n const v = extra > 0 ? computeVertices(spec, baseInset + extra) : verts;\n if (v.length >= 3) tracePolygon(g, v);\n };\n trace();\n applyFill(g, spec, style, this.host, this.bounds(), trace);\n trace();\n applyStroke(g, spec, style);\n }\n\n bounds(): Rect {\n return RegularPolygonShape.boundsOf(this.spec);\n }\n\n static boundsOf(spec: Omit<RegularPolygonSpec, 'x' | 'y'>): Rect {\n return polygonBounds(regularPolygonVertices(spec.sides, spec.radius, spec.rotation ?? 0));\n }\n\n static scaleSpec(\n spec: Omit<RegularPolygonSpec, 'x' | 'y'>,\n factor: number,\n ): Partial<RegularPolygonSpec> {\n return { radius: spec.radius * factor };\n }\n\n /**\n * Vertices are placed symmetrically around the origin by\n * `regularPolygonVertices`, so the local origin is the centroid. The AABB\n * midpoint is offset for odd-sided polygons (triangle / pentagon /\n * heptagon) — using the origin instead keeps an inset glyph centred on\n * the visual mass rather than floating toward the apex.\n */\n override visualCenter(): Point {\n return { x: 0, y: 0 };\n }\n\n contains(localX: number, localY: number): boolean {\n return pointInPolygon(localX, localY, computeVertices(this.spec, 0));\n }\n\n override boundaryIntersect(localFromCenter: Point): Point | null {\n return rayPolygonIntersection(localFromCenter, computeVertices(this.spec, 0));\n }\n\n obstacleTest(): (worldX: number, worldY: number, inflate: number) => boolean {\n const cx = this.spec.x;\n const cy = this.spec.y;\n const baseVerts = computeVertices(this.spec, 0);\n let cachedInflate = Number.NaN;\n let cachedVerts: ReadonlyArray<Point> = baseVerts;\n return (worldX, worldY, inflate) => {\n if (inflate !== cachedInflate) {\n cachedInflate = inflate;\n cachedVerts = inflate === 0 ? baseVerts : offsetPolygon(baseVerts, -inflate);\n }\n return pointInPolygon(worldX - cx, worldY - cy, cachedVerts);\n };\n }\n\n static paintInto(\n g: Graphics,\n spec: Omit<RegularPolygonSpec, 'x' | 'y'>,\n anchor: Point,\n angleRad: number,\n style?: ShapePaintStyle,\n ): void {\n const base = regularPolygonVertices(\n spec.sides,\n Math.max(0, spec.radius - (style?.inset ?? 0)),\n spec.rotation ?? 0,\n );\n if (base.length < 3) return;\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const placed: Point[] = base.map((v) => ({\n x: anchor.x + v.x * cos - v.y * sin,\n y: anchor.y + v.x * sin + v.y * cos,\n }));\n tracePolygon(g, placed);\n applyMarkerFill(g, spec.fill, style);\n }\n}\n\nfunction computeVertices(spec: RegularPolygonSpec, inset: number): Point[] {\n const r = Math.max(0, spec.radius - inset);\n return regularPolygonVertices(spec.sides, r, spec.rotation ?? 0);\n}\n\nfunction tracePolygon(g: Graphics, vertices: ReadonlyArray<Point>): void {\n const first = vertices[0]!;\n g.moveTo(first.x, first.y);\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i]!;\n g.lineTo(v.x, v.y);\n }\n g.closePath();\n}\n","import type { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport { applyFill, applyMarkerFill, applyStroke } from '../paint/applyFillStroke';\nimport { emitDashedStroke } from '../paint/dashedStroke';\nimport {\n offsetPolygon,\n pointInPolygon,\n polygonBounds,\n rayPolygonIntersection,\n starVertices,\n} from './_polyUtils';\nimport type {\n Point,\n Rect,\n ShapeHostInfo,\n ShapePaintStyle,\n StarSpec,\n} from '../types';\n\n/**\n * N-pointed star centred at `(spec.x, spec.y)`. `points` controls the number\n * of outer tips; vertices alternate between `outerRadius` and `innerRadius`.\n * With `rotation = 0` the first outer tip points straight up. The silhouette\n * is concave by construction — the bisector-based `offsetPolygon` inset is\n * an approximation for thin / decorative insets only; deep insets may\n * self-intersect.\n */\nexport class StarShape extends ShapeBase<StarSpec> {\n static readonly kind = 'star';\n\n constructor(spec: StarSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: StarSpec, style?: ShapePaintStyle): void {\n const baseInset = style?.inset ?? 0;\n const verts = computeVertices(spec, baseInset);\n if (verts.length < 3) return;\n\n const dashArray = style?.dashArray ?? spec.stroke?.dashArray;\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n emitDashedStroke(g, verts, {\n color: style?.color ?? spec.stroke?.color ?? 0x000000,\n alpha: style?.alpha ?? spec.stroke?.alpha ?? 1,\n width: style?.strokeWidth ?? spec.stroke?.width ?? 1,\n dashArray,\n dashOffset: style?.dashOffset ?? spec.stroke?.dashOffset,\n closed: true,\n });\n return;\n }\n\n const trace = (extra = 0) => {\n const v = extra > 0 ? computeVertices(spec, baseInset + extra) : verts;\n if (v.length >= 3) tracePolygon(g, v);\n };\n trace();\n applyFill(g, spec, style, this.host, this.bounds(), trace);\n trace();\n applyStroke(g, spec, style);\n }\n\n bounds(): Rect {\n return StarShape.boundsOf(this.spec);\n }\n\n static boundsOf(spec: Omit<StarSpec, 'x' | 'y'>): Rect {\n return polygonBounds(\n starVertices(spec.points, spec.innerRadius, spec.outerRadius, spec.rotation ?? 0),\n );\n }\n\n static scaleSpec(spec: Omit<StarSpec, 'x' | 'y'>, factor: number): Partial<StarSpec> {\n return {\n innerRadius: spec.innerRadius * factor,\n outerRadius: spec.outerRadius * factor,\n };\n }\n\n /**\n * Star vertices are placed symmetrically around the origin by\n * `starVertices`, so the local origin is the centroid. For odd-pointed\n * stars (5-point being the canonical case) the AABB midpoint is offset\n * from the visual mass — using the origin instead keeps an inset glyph\n * sitting where the eye reads as \"centre\".\n */\n override visualCenter(): Point {\n return { x: 0, y: 0 };\n }\n\n contains(localX: number, localY: number): boolean {\n return pointInPolygon(localX, localY, computeVertices(this.spec, 0));\n }\n\n override boundaryIntersect(localFromCenter: Point): Point | null {\n return rayPolygonIntersection(localFromCenter, computeVertices(this.spec, 0));\n }\n\n obstacleTest(): (worldX: number, worldY: number, inflate: number) => boolean {\n const cx = this.spec.x;\n const cy = this.spec.y;\n const baseVerts = computeVertices(this.spec, 0);\n let cachedInflate = Number.NaN;\n let cachedVerts: ReadonlyArray<Point> = baseVerts;\n return (worldX, worldY, inflate) => {\n if (inflate !== cachedInflate) {\n cachedInflate = inflate;\n cachedVerts = inflate === 0 ? baseVerts : offsetPolygon(baseVerts, -inflate);\n }\n return pointInPolygon(worldX - cx, worldY - cy, cachedVerts);\n };\n }\n\n static paintInto(\n g: Graphics,\n spec: Omit<StarSpec, 'x' | 'y'>,\n anchor: Point,\n angleRad: number,\n style?: ShapePaintStyle,\n ): void {\n const inset = style?.inset ?? 0;\n const base = starVertices(\n spec.points,\n Math.max(0, spec.innerRadius - inset),\n Math.max(0, spec.outerRadius - inset),\n spec.rotation ?? 0,\n );\n if (base.length < 3) return;\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n const placed: Point[] = base.map((v) => ({\n x: anchor.x + v.x * cos - v.y * sin,\n y: anchor.y + v.x * sin + v.y * cos,\n }));\n tracePolygon(g, placed);\n applyMarkerFill(g, spec.fill, style);\n }\n}\n\nfunction computeVertices(spec: StarSpec, inset: number): Point[] {\n const inner = Math.max(0, spec.innerRadius - inset);\n const outer = Math.max(0, spec.outerRadius - inset);\n return starVertices(spec.points, inner, outer, spec.rotation ?? 0);\n}\n\nfunction tracePolygon(g: Graphics, vertices: ReadonlyArray<Point>): void {\n const first = vertices[0]!;\n g.moveTo(first.x, first.y);\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i]!;\n g.lineTo(v.x, v.y);\n }\n g.closePath();\n}\n","import type { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport { applyFill, applyStroke } from '../paint/applyFillStroke';\nimport { emitDashedStroke } from '../paint/dashedStroke';\nimport type {\n ArcSpec,\n Point,\n Rect,\n ShapeHostInfo,\n ShapePaintStyle,\n} from '../types';\n\nconst TAU = Math.PI * 2;\n/** Target angular step between sampled outline vertices for AABB / dashed-stroke\n * fallback paths — ~3° gives a smooth silhouette at typical zoom levels. */\nconst ARC_SAMPLE_STEP = Math.PI / 60;\n\n/**\n * Annular sector centred at `(spec.x, spec.y)` between two radii\n * (`innerR`, `outerR`) and two angles (`startAngle`, `endAngle`). Angles are\n * in radians with the standard screen convention — `0` points along `+x`\n * (3 o'clock) and increasing values sweep clockwise on screen (because the\n * canvas y-axis grows downward). For a d3-style sunburst projection, subtract\n * `π/2` from d3's `x0`/`x1` to align \"0 = 12 o'clock\" with this convention.\n *\n * Degenerate shapes:\n * - `innerR === 0` → pie slice (no inner cut-out).\n * - `endAngle - startAngle >= 2π` and `innerR > 0` → full annulus (ring).\n * - `endAngle - startAngle >= 2π` and `innerR === 0` → full disk; prefer\n * `CircleShape` for that case unless you need the arc spec for animation.\n *\n * The silhouette is traced with Pixi's native `arc()` for smoothness; bounds,\n * containment, and dashed-stroke fall back to a discretised polyline sampled\n * at `ARC_SAMPLE_STEP`.\n */\nexport class ArcShape extends ShapeBase<ArcSpec> {\n static readonly kind = 'arc';\n\n constructor(spec: ArcSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: ArcSpec, style?: ShapePaintStyle): void {\n const baseInset = style?.inset ?? 0;\n // Inset shrinks the silhouette uniformly along its inward normal — for an\n // annular sector that means growing the inner radius and shrinking the\n // outer. The angle endpoints don't move; the wedge gets narrower radially.\n if (spec.endAngle <= spec.startAngle) return;\n const innerR0 = Math.max(0, spec.innerR + baseInset);\n const outerR0 = Math.max(innerR0, spec.outerR - baseInset);\n if (outerR0 <= 0) return;\n\n const dashArray = style?.dashArray ?? spec.stroke?.dashArray;\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n emitDashedStroke(g, sampleArcOutline(innerR0, outerR0, spec.startAngle, spec.endAngle), {\n color: style?.color ?? spec.stroke?.color ?? 0x000000,\n alpha: style?.alpha ?? spec.stroke?.alpha ?? 1,\n width: style?.strokeWidth ?? spec.stroke?.width ?? 1,\n dashArray,\n dashOffset: style?.dashOffset ?? spec.stroke?.dashOffset,\n closed: true,\n });\n return;\n }\n\n const trace = (extra = 0): void => {\n const i = baseInset + extra;\n const inner = Math.max(0, spec.innerR + i);\n const outer = Math.max(inner, spec.outerR - i);\n if (outer <= 0) return;\n traceArc(g, inner, outer, spec.startAngle, spec.endAngle);\n };\n trace();\n applyFill(g, spec, style, this.host, this.bounds(), trace);\n trace();\n applyStroke(g, spec, style);\n }\n\n bounds(): Rect {\n return ArcShape.boundsOf(this.spec);\n }\n\n static boundsOf(spec: Omit<ArcSpec, 'x' | 'y'>): Rect {\n return arcBounds(spec.innerR, spec.outerR, spec.startAngle, spec.endAngle);\n }\n\n static scaleSpec(spec: Omit<ArcSpec, 'x' | 'y'>, factor: number): Partial<ArcSpec> {\n return { innerR: spec.innerR * factor, outerR: spec.outerR * factor };\n }\n\n /**\n * Visual centre of an annular sector — half-angle direction, midradius\n * distance. Used by inset-content labels (`placement: 'center'`); good\n * enough for visual centring without the (more expensive) area-weighted\n * centroid integral.\n */\n override visualCenter(): Point {\n const a0 = this.spec.startAngle;\n const a1 = this.spec.endAngle;\n if (a1 <= a0) return { x: 0, y: 0 };\n const mid = (a0 + a1) / 2;\n const r = (this.spec.innerR + this.spec.outerR) / 2;\n return { x: Math.cos(mid) * r, y: Math.sin(mid) * r };\n }\n\n contains(localX: number, localY: number): boolean {\n return pointInArc(\n localX,\n localY,\n this.spec.innerR,\n this.spec.outerR,\n this.spec.startAngle,\n this.spec.endAngle,\n );\n }\n}\n\n// ─── Geometry helpers ──────────────────────────────────────────────────────\n\n/** Trace the silhouette of an annular sector using Pixi's native arc() so the\n * rendered curve stays smooth at any zoom (unlike a polyline approximation). */\nfunction traceArc(\n g: Graphics,\n innerR: number,\n outerR: number,\n a0: number,\n a1: number,\n): void {\n const isFullSweep = a1 - a0 >= TAU - 1e-6;\n\n if (isFullSweep) {\n // Full circle / annulus. Trace the outer disc, then punch the inner disc\n // back out (Pixi uses non-zero fill rule by default → opposite winding\n // creates a hole). When innerR is 0 this degenerates to a plain disc.\n g.moveTo(outerR, 0);\n g.arc(0, 0, outerR, 0, TAU);\n g.closePath();\n if (innerR > 0) {\n g.moveTo(innerR, 0);\n g.arc(0, 0, innerR, 0, TAU, true);\n g.closePath();\n }\n return;\n }\n\n const cos0 = Math.cos(a0);\n const sin0 = Math.sin(a0);\n const cos1 = Math.cos(a1);\n const sin1 = Math.sin(a1);\n\n if (innerR <= 0) {\n // Pie slice: origin → outer-start → outer arc → origin.\n g.moveTo(0, 0);\n g.lineTo(outerR * cos0, outerR * sin0);\n g.arc(0, 0, outerR, a0, a1);\n g.lineTo(0, 0);\n g.closePath();\n return;\n }\n\n // Proper annular sector: inner-start → outer-start → outer arc forward →\n // inner-end → inner arc backward → close.\n g.moveTo(innerR * cos0, innerR * sin0);\n g.lineTo(outerR * cos0, outerR * sin0);\n g.arc(0, 0, outerR, a0, a1);\n g.lineTo(innerR * cos1, innerR * sin1);\n g.arc(0, 0, innerR, a1, a0, true);\n g.closePath();\n}\n\n/**\n * Sample the silhouette of an annular sector as a flat closed polyline.\n * Used by the dashed-stroke emitter (which only consumes polylines) and by\n * `applyFill`'s fallback redraw path. Walks the outer arc forward, then the\n * inner arc backward (or back to the origin for pie slices).\n */\nfunction sampleArcOutline(\n innerR: number,\n outerR: number,\n a0: number,\n a1: number,\n): Point[] {\n const out: Point[] = [];\n const sweep = a1 - a0;\n if (sweep <= 0 || outerR <= 0) return out;\n const steps = Math.max(2, Math.ceil(sweep / ARC_SAMPLE_STEP));\n\n // Outer arc, a0 → a1.\n for (let i = 0; i <= steps; i++) {\n const a = a0 + (sweep * i) / steps;\n out.push({ x: Math.cos(a) * outerR, y: Math.sin(a) * outerR });\n }\n\n if (innerR > 0) {\n // Inner arc, a1 → a0 (reverse) to close the annular sector.\n for (let i = 0; i <= steps; i++) {\n const a = a1 - (sweep * i) / steps;\n out.push({ x: Math.cos(a) * innerR, y: Math.sin(a) * innerR });\n }\n } else {\n // Pie slice: close through the origin.\n out.push({ x: 0, y: 0 });\n }\n return out;\n}\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 */\nfunction arcBounds(innerR: number, outerR: number, a0: number, a1: number): Rect {\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 let minX = corners[0]!.x;\n let maxX = minX;\n let minY = corners[0]!.y;\n let maxY = minY;\n for (let i = 1; i < corners.length; i++) {\n const p = corners[i]!;\n if (p.x < minX) minX = p.x;\n else if (p.x > maxX) maxX = p.x;\n if (p.y < minY) minY = p.y;\n else if (p.y > maxY) maxY = p.y;\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/**\n * Exact analytical point-in-annular-sector test. Splits the test into a\n * radial check (innerR ≤ r ≤ outerR) and an angular check (θ falls within\n * the sweep, modulo 2π). Cheap and pixel-tight — preferred over a polygon\n * approximation when the sweep is large.\n */\nfunction pointInArc(\n localX: number,\n localY: number,\n innerR: number,\n outerR: number,\n a0: number,\n a1: number,\n): boolean {\n const r2 = localX * localX + localY * localY;\n if (r2 < innerR * innerR || r2 > outerR * outerR) return false;\n if (a1 - a0 >= TAU) return true;\n\n // Bring θ into the same revolution as a0 so the comparison is unambiguous\n // across the 2π wrap (e.g. sweep from 3π/2 to 5π/2 hitting θ ≈ 0.1).\n const theta = Math.atan2(localY, localX);\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 * Builds and updates the inner visual of a `LabelDecoration` — a `Text`\n * (plain) or `HTMLText` (rich), with wrap / maxLines / ellipsis applied.\n *\n * Decorations call `mountLabelContent` once on mount, then `updateLabelContent`\n * to mutate the existing Pixi object on style change (cheap — no allocation).\n * Mutation-over-recreation is critical: each Pixi `Text` owns a texture, and\n * a graph with 2 000 labels would burn that many texture uploads per frame\n * if we recreated on every update.\n */\n\nimport { Text, HTMLText, type TextStyleOptions } from 'pixi.js';\nimport type { LabelContent, LabelWrap } from '../types';\n\nexport type LabelTextDisplay = Text | HTMLText;\n\nexport interface LabelContentView {\n display: LabelTextDisplay;\n kind: LabelContent['kind'];\n}\n\n/** Build a fresh Pixi text display from a `LabelContent` + optional wrap. */\nexport function mountLabelContent(\n content: LabelContent,\n wrap: LabelWrap | undefined,\n): LabelContentView {\n if (content.kind === 'text') {\n const effectiveWrap = withDerivedMaxLines(wrap);\n const display = new Text({ text: content.text, style: textStyleFor(content, effectiveWrap) });\n display.alpha = content.alpha ?? 1;\n applyMaxLines(display, content, effectiveWrap);\n return { display, kind: 'text' };\n }\n const display = new HTMLText({ text: htmlBodyFor(content), style: htmlStyleFor(content, wrap) });\n display.alpha = content.alpha ?? 1;\n return { display, kind: 'html-text' };\n}\n\n/**\n * Mutate `view` to reflect `content` + `wrap`. Recreates the Pixi instance\n * only when the content kind switches (`text` ↔ `html-text`); otherwise\n * updates `.text` and `.style` in place.\n *\n * Returns the (possibly new) display object so callers can re-parent it on\n * a kind switch.\n */\nexport function updateLabelContent(\n view: LabelContentView,\n content: LabelContent,\n wrap: LabelWrap | undefined,\n): LabelContentView {\n if (view.kind !== content.kind) {\n view.display.destroy();\n return mountLabelContent(content, wrap);\n }\n\n if (content.kind === 'text') {\n const t = view.display as Text;\n const effectiveWrap = withDerivedMaxLines(wrap);\n t.style = textStyleFor(content, effectiveWrap) as never;\n t.text = content.text;\n t.alpha = content.alpha ?? 1;\n applyMaxLines(t, content, effectiveWrap);\n } else {\n const h = view.display as HTMLText;\n h.style = htmlStyleFor(content, wrap) as never;\n h.text = htmlBodyFor(content);\n h.alpha = content.alpha ?? 1;\n }\n return view;\n}\n\n/**\n * Set the rasterisation resolution of the underlying Pixi text. Higher\n * resolution = sharper glyphs when the camera is zoomed in, at the cost of\n * a larger glyph texture. Setting the same value twice is a no-op in Pixi\n * (it short-circuits the re-rasterise), so callers can re-invoke freely.\n */\nexport function applyLabelResolution(view: LabelContentView, resolution: number): void {\n if (resolution <= 0 || !Number.isFinite(resolution)) return;\n (view.display as unknown as { resolution: number }).resolution = resolution;\n}\n\n// ─── Style builders ────────────────────────────────────────────────────────\n\nfunction textStyleFor(\n content: Extract<LabelContent, { kind: 'text' }>,\n wrap: LabelWrap | undefined,\n): TextStyleOptions {\n const wantsWrap = wrap?.wordWrap === true || (wrap?.maxWidth !== undefined);\n const style: TextStyleOptions = {\n fontFamily: content.fontFamily ?? 'sans-serif',\n fontSize: content.fontSize ?? 12,\n fill: content.fill ?? 0x111827,\n align: content.align ?? 'center',\n };\n if (content.fontWeight !== undefined) style.fontWeight = content.fontWeight as never;\n if (content.fontStyle !== undefined) style.fontStyle = content.fontStyle;\n if (content.fontVariant !== undefined) style.fontVariant = content.fontVariant as never;\n if (content.letterSpacing !== undefined) style.letterSpacing = content.letterSpacing;\n if (content.lineHeight !== undefined) style.lineHeight = content.lineHeight;\n if (wantsWrap) {\n style.wordWrap = true;\n if (wrap?.maxWidth !== undefined) style.wordWrapWidth = wrap.maxWidth;\n }\n if (content.stroke) {\n style.stroke = { color: content.stroke.color, width: content.stroke.width };\n }\n if (content.shadow) {\n style.dropShadow = {\n color: content.shadow.color,\n blur: content.shadow.blur ?? 0,\n distance: Math.hypot(content.shadow.offsetX ?? 0, content.shadow.offsetY ?? 2),\n angle: Math.atan2(content.shadow.offsetY ?? 2, content.shadow.offsetX ?? 0),\n alpha: content.shadow.alpha ?? 0.5,\n };\n }\n return style;\n}\n\nfunction htmlStyleFor(\n content: Extract<LabelContent, { kind: 'html-text' }>,\n wrap: LabelWrap | undefined,\n): Record<string, unknown> {\n const style: Record<string, unknown> = {\n fontFamily: content.defaultFontFamily ?? 'sans-serif',\n fontSize: content.defaultFontSize ?? 12,\n fill: content.defaultFill ?? 0x111827,\n };\n if (content.defaultFontWeight !== undefined) style.fontWeight = content.defaultFontWeight;\n if (content.width !== undefined) style.wordWrapWidth = content.width;\n if (wrap?.maxWidth !== undefined && style.wordWrapWidth === undefined) {\n style.wordWrapWidth = wrap.maxWidth;\n }\n if (style.wordWrapWidth !== undefined) style.wordWrap = true;\n if (content.tagStyles) style.tagStyles = content.tagStyles;\n if (content.cssOverrides) style.cssOverrides = content.cssOverrides;\n return style;\n}\n\nfunction htmlBodyFor(content: Extract<LabelContent, { kind: 'html-text' }>): string {\n return content.html;\n}\n\n// ─── Wrap / ellipsis truncation pass ───────────────────────────────────────\n\n/**\n * Enforce `wrap.maxLines` by truncating the text and re-rendering until the\n * line count fits. Only used for plain `Text`; `HTMLText` doesn't expose an\n * easy line-count probe and is documented to support `maxLines` natively via\n * the host's CSS (`-webkit-line-clamp`) — out of scope for v0.\n */\nfunction applyMaxLines(\n display: Text,\n content: Extract<LabelContent, { kind: 'text' }>,\n wrap: LabelWrap | undefined,\n): void {\n if (!wrap || !wrap.maxLines || wrap.maxLines < 1) return;\n const overflow = wrap.overflow ?? 'ellipsis';\n\n const lineHeight = effectiveLineHeight(display);\n if (lineHeight <= 0) return;\n\n if (currentLineCount(display, lineHeight) <= wrap.maxLines) return;\n\n const original = content.text;\n let lo = 0;\n let hi = original.length;\n // Binary search the longest character prefix that fits in maxLines (with\n // ellipsis appended when overflow === 'ellipsis').\n while (lo < hi) {\n const mid = (lo + hi + 1) >>> 1;\n const candidate = overflow === 'ellipsis'\n ? original.slice(0, mid).replace(/\\s+$/, '') + '…'\n : original.slice(0, mid);\n display.text = candidate;\n if (currentLineCount(display, lineHeight) <= wrap.maxLines) lo = mid;\n else hi = mid - 1;\n }\n\n display.text = overflow === 'ellipsis'\n ? original.slice(0, lo).replace(/\\s+$/, '') + '…'\n : original.slice(0, lo);\n}\n\n/**\n * If `wrap.maxHeight` is set, derive a `maxLines` cap from it by dividing by\n * the line height that would render at the configured `fontSize`. The result\n * is min-combined with any caller-provided `maxLines` so the smaller wins.\n *\n * Returns the same `wrap` object (with a possibly tightened `maxLines`).\n */\nfunction withDerivedMaxLines(wrap: LabelWrap | undefined): LabelWrap | undefined {\n if (!wrap || wrap.maxHeight === undefined || wrap.maxHeight <= 0) return wrap;\n // The line height used here is a coarse estimate (we don't have the rendered\n // Text yet). It's refined once the display is mounted; the value here just\n // sets an upper bound on `maxLines` for the initial mount. A line height of\n // ~14.4 (`12 * 1.2`) for the default font is the worst-case ascent.\n const approxLineHeight = 14.4;\n const derivedMaxLines = Math.max(1, Math.floor(wrap.maxHeight / approxLineHeight));\n const combinedMaxLines = wrap.maxLines !== undefined\n ? Math.min(wrap.maxLines, derivedMaxLines)\n : derivedMaxLines;\n return { ...wrap, maxLines: combinedMaxLines };\n}\n\n/**\n * Constrain the label's rendered geometry to fit inside `box`. Applies a\n * three-step cascade and mutates the underlying Pixi `Text` in place:\n *\n * 1. **Shrink** — binary-search the largest `fontSize ∈ [minFontSize, configured]`\n * such that the wrapped text fits both `box.width` and `box.height`.\n * 2. **Truncate** — at `minFontSize`, derive `maxLines = floor(box.height / lineHeight)`\n * and re-run the existing ellipsis truncation pass on top.\n * 3. **Hide** — if even the truncated label still overflows, return `hidden: true`\n * so the caller can set `alpha = 0`.\n *\n * Inside-placement decorations call this after `mountLabelContent` /\n * `updateLabelContent` and before measuring the display for positioning.\n * HTMLText is currently a no-op (no line-count probe available in v0).\n */\nexport function fitInsideBox(\n view: LabelContentView,\n content: LabelContent,\n wrap: LabelWrap | undefined,\n box: { width: number; height: number },\n minFontSize: number,\n): { hidden: boolean } {\n if (box.width <= 0 || box.height <= 0) return { hidden: true };\n if (content.kind !== 'text') return { hidden: false };\n const display = view.display as Text;\n const configuredFontSize = content.fontSize ?? 12;\n const floor = Math.max(1, minFontSize);\n\n // Effective wrap forces wordWrap to box width so multi-word labels can break\n // across lines, and caps maxHeight at the box.\n const widthBudget = Math.max(1, box.width);\n const heightBudget = Math.max(1, box.height);\n const baseWrap: LabelWrap = {\n ...(wrap ?? {}),\n maxWidth: Math.min(wrap?.maxWidth ?? Infinity, widthBudget),\n maxHeight: Math.min(wrap?.maxHeight ?? Infinity, heightBudget),\n wordWrap: true,\n };\n\n const applyAt = (fontSize: number): void => {\n const sizedContent = { ...content, fontSize } as Extract<LabelContent, { kind: 'text' }>;\n display.style = textStyleFor(sizedContent, baseWrap) as never;\n display.text = content.text;\n };\n\n applyAt(configuredFontSize);\n if (display.width <= widthBudget + 0.5 && display.height <= heightBudget + 0.5) {\n return { hidden: false };\n }\n\n // Step 1: binary-search font size down to floor.\n let lo = floor;\n let hi = configuredFontSize;\n let bestFit = -1;\n // Step size of 0.5 px is enough; Pixi rounds to integer subpixels anyway.\n while (hi - lo >= 0.5) {\n const mid = (lo + hi) / 2;\n applyAt(mid);\n if (display.width <= widthBudget + 0.5 && display.height <= heightBudget + 0.5) {\n bestFit = mid;\n lo = mid;\n } else {\n hi = mid;\n }\n }\n if (bestFit > 0) {\n applyAt(bestFit);\n return { hidden: false };\n }\n\n // Step 2: at floor font size, derive maxLines from box height and let\n // applyMaxLines truncate with ellipsis.\n applyAt(floor);\n const lineHeight = effectiveLineHeight(display);\n if (lineHeight <= 0) return { hidden: true };\n const derivedMaxLines = Math.max(1, Math.floor(heightBudget / lineHeight));\n applyMaxLines(display, content, { ...baseWrap, maxLines: derivedMaxLines, overflow: 'ellipsis' });\n\n // After truncation, the text may still be wider than the box if Pixi's\n // wordWrap couldn't break a single long word. In that case, prefix-shrink\n // the text on width directly.\n if (display.width > widthBudget + 0.5) {\n truncateToWidth(display, widthBudget);\n }\n\n // Step 3: if it still doesn't fit, hide.\n if (display.width > widthBudget + 0.5 || display.height > heightBudget + 0.5) {\n return { hidden: true };\n }\n return { hidden: false };\n}\n\n/**\n * Prefix-binary-search the text on `display` down to the longest prefix that\n * fits within `widthBudget` after appending an ellipsis. Used as a last resort\n * inside `fitInsideBox` when Pixi's wordWrap can't break a long single token.\n */\nfunction truncateToWidth(display: Text, widthBudget: number): void {\n const original = display.text;\n let lo = 0;\n let hi = original.length;\n while (lo < hi) {\n const mid = (lo + hi + 1) >>> 1;\n display.text = original.slice(0, mid).replace(/\\s+$/, '') + '…';\n if (display.width <= widthBudget + 0.5) lo = mid;\n else hi = mid - 1;\n }\n if (lo <= 0) {\n // Not even an ellipsis fits — leave the text empty so width collapses;\n // caller will hide via the post-check.\n display.text = '';\n } else {\n display.text = original.slice(0, lo).replace(/\\s+$/, '') + '…';\n }\n}\n\nfunction effectiveLineHeight(display: Text): number {\n const style = display.style as unknown as {\n lineHeight?: number;\n fontSize?: number;\n leading?: number;\n };\n const ascent = style.fontSize ?? 12;\n return style.lineHeight && style.lineHeight > 0 ? style.lineHeight : ascent * 1.2;\n}\n\nfunction currentLineCount(display: Text, lineHeight: number): number {\n // Pixi v8 exposes height after layout. Round to nearest integer line count.\n // Tolerance avoids off-by-one when height ≈ N * lineHeight + ε.\n const lines = display.height / lineHeight;\n return Math.max(1, Math.round(lines + 0.001));\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport {\n mountLabelContent,\n updateLabelContent,\n type LabelContentView,\n} from '../paint/labelContent';\nimport type { BaseShapeSpec, Rect, ShapeHostInfo } from '../types';\n\n/** Solid stroke for a {@link CompositePart}. */\ninterface PartStroke {\n readonly color: number;\n readonly width?: number;\n readonly alpha?: number;\n}\n\n/** Solid fill + optional stroke shared by the geometric part kinds. */\ninterface PartFill {\n readonly fill?: number;\n readonly fillAlpha?: number;\n readonly stroke?: PartStroke;\n}\n\n/**\n * A child element of a {@link CompositeShape}, positioned at a coordinate\n * relative to the composite's top-left origin.\n *\n * - `'rect'` / `'circle'` / `'line'` — geometry traced into the shared body\n * `Graphics`. Fill/stroke are solid colours (the simple sugar fields here);\n * for gradient / image / dashed paint, compose dedicated shapes instead.\n * - `'label'` — a text block mounted as a Pixi text child. `anchor` picks\n * which horizontal edge of the measured block lands at `x` (default left);\n * `maxWidth` enables word-wrap, `maxLines` + `overflow` drive ellipsis.\n */\nexport type CompositePart =\n | ({\n readonly part: 'rect';\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly cornerRadius?: number;\n } & PartFill)\n | ({\n readonly part: 'circle';\n readonly x: number;\n readonly y: number;\n readonly radius: number;\n } & PartFill)\n | {\n readonly part: 'line';\n readonly x: number;\n readonly y: number;\n readonly x2: number;\n readonly y2: number;\n readonly stroke: PartStroke;\n }\n | {\n readonly part: 'label';\n readonly x: number;\n readonly y: number;\n readonly text: string;\n /** Horizontal anchor of the text block at `(x, y)`. Default `'left'`. */\n readonly anchor?: 'left' | 'center' | 'right';\n readonly fontSize?: number;\n readonly fontWeight?: number | string;\n readonly fontStyle?: 'normal' | 'italic';\n readonly fontVariant?: 'normal' | 'small-caps';\n readonly fill?: number;\n readonly lineHeight?: number;\n readonly align?: 'left' | 'center' | 'right';\n readonly maxWidth?: number;\n readonly maxLines?: number;\n readonly overflow?: 'clip' | 'ellipsis';\n };\n\n/**\n * Spec for a {@link CompositeShape}. The outer frame is a rounded rect sized\n * `width` × `height`, painted from the inherited `fill` / `stroke`. `parts`\n * declares ordered child geometry + labels at coordinates relative to the\n * composite's top-left origin.\n */\nexport interface CompositeSpec extends BaseShapeSpec {\n readonly kind: 'composite';\n readonly width: number;\n readonly height: number;\n /** Outer frame corner radius. Default `0` (sharp). */\n readonly cornerRadius?: number;\n /** Ordered child parts; geometry traced into the body, labels mounted as text. */\n readonly parts: readonly CompositePart[];\n}\n\n/**\n * A container shape: an outer rounded-rect frame plus an ordered list of child\n * {@link CompositePart}s — `rect` / `circle` / `line` geometry traced into the\n * shared body `Graphics`, and `label` text blocks mounted as Pixi text children\n * — each positioned at a coordinate relative to the composite's top-left origin\n * (so `(spec.x, spec.y)` places the whole composite, like {@link RectShape}).\n *\n * Mounting text children mirrors how {@link ShapeBase} mounts glyph / svg /\n * image insets onto the shape's root container; labels here are diffed by\n * their index in `parts` (mount / update-in-place / destroy).\n */\nexport class CompositeShape extends ShapeBase<CompositeSpec> {\n static readonly kind = 'composite';\n\n /** Mounted label displays keyed by their index in `spec.parts`. */\n private readonly labelViews = new Map<number, LabelContentView>();\n\n constructor(spec: CompositeSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: CompositeSpec): void {\n // Outer frame.\n const r = spec.cornerRadius ?? 0;\n if (r > 0) g.roundRect(0, 0, spec.width, spec.height, r);\n else g.rect(0, 0, spec.width, spec.height);\n if (typeof spec.fill === 'number') g.fill({ color: spec.fill, alpha: spec.alpha ?? 1 });\n if (spec.stroke) {\n g.stroke({\n color: spec.stroke.color,\n width: spec.stroke.width ?? 1,\n alpha: spec.stroke.alpha ?? 1,\n });\n }\n\n // Geometric sub-parts — each traces its own path, then fills / strokes it.\n for (const p of spec.parts) {\n if (p.part === 'rect') {\n if (p.cornerRadius) g.roundRect(p.x, p.y, p.width, p.height, p.cornerRadius);\n else g.rect(p.x, p.y, p.width, p.height);\n if (p.fill !== undefined) g.fill({ color: p.fill, alpha: p.fillAlpha ?? 1 });\n if (p.stroke) g.stroke({ color: p.stroke.color, width: p.stroke.width ?? 1, alpha: p.stroke.alpha ?? 1 });\n } else if (p.part === 'circle') {\n g.circle(p.x, p.y, p.radius);\n if (p.fill !== undefined) g.fill({ color: p.fill, alpha: p.fillAlpha ?? 1 });\n if (p.stroke) g.stroke({ color: p.stroke.color, width: p.stroke.width ?? 1, alpha: p.stroke.alpha ?? 1 });\n } else if (p.part === 'line') {\n g.moveTo(p.x, p.y);\n g.lineTo(p.x2, p.y2);\n g.stroke({ color: p.stroke.color, width: p.stroke.width ?? 1, alpha: p.stroke.alpha ?? 1 });\n }\n // 'label' is text, not geometry — handled in syncLabels.\n }\n }\n\n /** Geometry via the base `draw`, then reconcile the text-label children. */\n override draw(spec: CompositeSpec): void {\n super.draw(spec); // transform + bodyGfx(drawGeometry) + inset layers\n this.syncLabels(spec);\n }\n\n /**\n * Diff the `label` parts against the mounted `labelViews` map, keyed by part\n * index: mount new labels, update existing ones in place, destroy removed\n * ones. Each label is positioned at its relative `(x, y)` with the requested\n * horizontal anchor (measured against the rendered block width).\n */\n private syncLabels(spec: CompositeSpec): void {\n const seen = new Set<number>();\n spec.parts.forEach((p, i) => {\n if (p.part !== 'label') return;\n seen.add(i);\n\n const content = {\n kind: 'text' as const,\n text: p.text,\n fontSize: p.fontSize,\n fontWeight: p.fontWeight,\n fontStyle: p.fontStyle,\n fontVariant: p.fontVariant,\n lineHeight: p.lineHeight,\n fill: p.fill ?? 0xffffff,\n align: p.align,\n };\n const wrap =\n p.maxWidth !== undefined\n ? { maxWidth: p.maxWidth, maxLines: p.maxLines, overflow: p.overflow ?? 'ellipsis' }\n : undefined;\n\n let view = this.labelViews.get(i);\n if (!view) {\n view = mountLabelContent(content, wrap);\n this.gfx.addChild(view.display);\n this.labelViews.set(i, view);\n } else {\n const next = updateLabelContent(view, content, wrap);\n if (next !== view) {\n this.gfx.addChild(next.display);\n view = next;\n this.labelViews.set(i, next);\n }\n }\n\n // Place the (measured) text block at the relative coordinate.\n const w = view.display.width;\n const dx = p.anchor === 'right' ? -w : p.anchor === 'center' ? -w / 2 : 0;\n view.display.position.set(p.x + dx, p.y);\n });\n\n // Destroy labels no longer present in the spec.\n for (const [i, view] of this.labelViews) {\n if (!seen.has(i)) {\n view.display.destroy();\n this.labelViews.delete(i);\n }\n }\n }\n\n bounds(): Rect {\n return { x: 0, y: 0, width: this.spec.width, height: this.spec.height };\n }\n\n override destroy(): void {\n for (const view of this.labelViews.values()) view.display.destroy();\n this.labelViews.clear();\n super.destroy();\n }\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 '../types';\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 return normalize(next.x - m.x, next.y - m.y);\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 return normalize(last.x - prevAnchor.x, last.y - prevAnchor.y);\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\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","import { Graphics } from 'pixi.js';\nimport { PrimitiveBase } from './PrimitiveBase';\nimport {\n distanceToPolylineSq,\n samplePath,\n tangentAt,\n trimPathEnds,\n} from '../connectors/pathSampling';\nimport type {\n BaseConnectorSpec,\n ConnectorHostInfo,\n ConnectorPaintStyle,\n IConnector,\n MarkerShapeSpec,\n Path,\n Point,\n ShapeCtor,\n ShapePaintStyle,\n} from '../types';\n\n/**\n * Base for the single concrete `Connector` class (and any future custom\n * subclasses). Subclasses implement `drawGeometry` to render a `Path` onto a\n * `Graphics`. Marker placement is handled by `paintMarkers` — wired in step 9\n * once `pathSampling.tangentAt` and the shape registry resolution land.\n *\n * v0 ships only one concrete subclass (`Connector`); custom rendering styles\n * (double-line strokes, gradient strokes, \"noodle\" wiggles) are introduced\n * later by extending `ConnectorBase` directly. See the v0 plan's \"What's NOT\n * in v0\" section.\n */\nexport abstract class ConnectorBase<TSpec extends BaseConnectorSpec>\n extends PrimitiveBase\n implements IConnector<TSpec>\n{\n protected readonly bodyGfx: Graphics;\n protected readonly sourceMarkerGfx: Graphics;\n protected readonly targetMarkerGfx: Graphics;\n protected spec!: TSpec;\n protected path: Path = [];\n\n constructor(protected readonly host: ConnectorHostInfo) {\n super();\n // Three siblings under `gfx` so decorations can hide each piece\n // independently. A reveal animation, for example, hides the body line\n // and the \"ending\" marker (the one the reveal is sweeping toward),\n // leaves the \"starting\" marker visible, and pops the ending marker in\n // when the line reaches it.\n this.bodyGfx = new Graphics();\n this.sourceMarkerGfx = new Graphics();\n this.targetMarkerGfx = new Graphics();\n this.gfx.addChild(this.bodyGfx);\n this.gfx.addChild(this.sourceMarkerGfx);\n this.gfx.addChild(this.targetMarkerGfx);\n\n // Hit-test geometry is part of the connector's identity, not the\n // renderer's bookkeeping. The closure reads `this.path` and\n // `this.spec.stroke.width` at call time, so route changes (router rerun)\n // and stroke changes (`setConnectorStroke` / spec rewrite) automatically\n // flow into the hit area — no re-wiring needed.\n //\n // Before the first `draw()`, `this.path` is empty and `this.spec` is\n // undefined; the early return makes hit-tests return `false` until the\n // connector is mounted with data. Pixi calls `hitArea.contains` only on\n // pointer events, by which time the connector has been drawn.\n this.gfx.eventMode = 'static';\n this.gfx.cursor = 'pointer';\n this.gfx.hitArea = {\n contains: (x: number, y: number): boolean => {\n if (this.path.length < 2 || !this.spec) return false;\n const sw = this.spec.stroke?.width ?? 1;\n const tol = sw / 2 + 4;\n return distanceToPolylineSq(samplePath(this.path), x, y) <= tol * tol;\n },\n };\n }\n\n /**\n * Render the path natively via Pixi commands (`moveTo` / `lineTo` /\n * `quadraticCurveTo` / `bezierCurveTo`) plus the spec's stroke (or `style`\n * override). Subclasses focus only on stroke style — markers are handled\n * by the base via `paintMarkers`.\n */\n protected abstract drawGeometry(\n g: Graphics,\n spec: TSpec,\n path: Path,\n style?: ConnectorPaintStyle,\n ): void;\n\n draw(spec: TSpec, path: Path): void {\n this.spec = spec;\n this.path = path;\n this.gfx.alpha = spec.alpha ?? 1;\n this.gfx.visible = spec.visible ?? true;\n this.gfx.zIndex = spec.zIndex ?? 0;\n this.bodyGfx.clear();\n this.sourceMarkerGfx.clear();\n this.targetMarkerGfx.clear();\n const strokeWidth = resolveStrokeWidth(spec);\n const bodyPath = this.trimPathForMarkers(spec, path, strokeWidth);\n this.drawGeometry(this.bodyGfx, spec, bodyPath);\n this.paintSourceMarker(this.sourceMarkerGfx, spec, path, undefined, strokeWidth);\n this.paintTargetMarker(this.targetMarkerGfx, spec, path, undefined, strokeWidth);\n }\n\n paintInto(g: Graphics, spec: TSpec, path: Path, style?: ConnectorPaintStyle): void {\n // Body uses the (possibly overridden) stroke width — decorations like\n // glow legitimately widen it for halo coverage. Markers always size off\n // the spec's stroke width: their geometry is `strokeWidth × *Scale`, so\n // a 16-px halo override would render a 96-px arrowhead on a 2-px line.\n // Path trimming also uses the spec width so the body stops where the\n // host's actual marker base lands.\n const bodyStrokeWidth = resolveStrokeWidth(spec, style);\n const markerStrokeWidth = resolveStrokeWidth(spec);\n const bodyPath = this.trimPathForMarkers(spec, path, markerStrokeWidth);\n this.drawGeometry(g, spec, bodyPath, style);\n if (!style?.skipMarkers) {\n this.paintMarkers(g, spec, path, style, markerStrokeWidth, bodyStrokeWidth);\n }\n }\n\n /**\n * Path trimmed by the source / target marker insets at the *spec* stroke\n * width — i.e. the visible body of the connector. Decorations call this\n * when they need to parameterise along the segment markers actually\n * cover. Identity when no markers are configured.\n */\n getVisiblePath(spec: TSpec, path: Path): Path {\n return this.trimPathForMarkers(spec, path, resolveStrokeWidth(spec));\n }\n\n /**\n * Toggle the body stroke without affecting markers or decoration children.\n * Body, source marker, and target marker live in three sibling Graphics\n * under `gfx`, so each can be hidden independently. The next `draw()`\n * re-strokes the body but preserves the hidden state.\n */\n setBodyVisible(visible: boolean): void {\n this.bodyGfx.visible = visible;\n }\n\n /** Toggle just the source-endpoint marker. See `setBodyVisible`. */\n setSourceMarkerVisible(visible: boolean): void {\n this.sourceMarkerGfx.visible = visible;\n }\n\n /** Toggle just the target-endpoint marker. See `setBodyVisible`. */\n setTargetMarkerVisible(visible: boolean): void {\n this.targetMarkerGfx.visible = visible;\n }\n\n /**\n * Resolve source/target marker insets via each marker's\n * `ShapeCtor.markerInset` and shorten the path's start / end so the body\n * stops at the marker's back edge. Markers themselves still paint at the\n * untrimmed endpoints, so the marker tip lands exactly on the path\n * endpoint (e.g. the arrow's tip touches the target).\n */\n private trimPathForMarkers(spec: TSpec, path: Path, strokeWidth: number): Path {\n if (path.length < 2) return path;\n const startInset = spec.sourceMarker\n ? markerInsetFor(this.host.shapeRegistry, spec.sourceMarker, strokeWidth)\n : 0;\n const endInset = spec.targetMarker\n ? markerInsetFor(this.host.shapeRegistry, spec.targetMarker, strokeWidth)\n : 0;\n if (startInset <= 0 && endInset <= 0) return path;\n return trimPathEnds(path, startInset, endInset);\n }\n\n /**\n * Paint source/target markers anchored at the path endpoints, oriented\n * along the local tangent. Looks up each marker's class via\n * `host.shapeRegistry` and dispatches to its `static paintInto`.\n *\n * Source angle is the **reversed** tangent so an arrow placed at the\n * source faces back toward it. Target angle is the forward tangent so an\n * arrow placed at the target points into it.\n *\n * When the connector style sets `tintMarkers`, markers paint with the\n * connector's color/alpha (used by glow / halo for unified silhouette\n * coverage). Otherwise markers use their own spec colors.\n */\n protected paintMarkers(\n g: Graphics,\n spec: TSpec,\n path: Path,\n style?: ConnectorPaintStyle,\n strokeWidth: number = resolveStrokeWidth(spec),\n /**\n * Halo stroke thickness used when `style.markerHalo` is set. Decoupled\n * from `strokeWidth` (which sizes marker geometry) so a glow can outline\n * the marker at its halo width without scaling the marker itself.\n */\n haloStrokeWidth: number = strokeWidth,\n ): void {\n this.paintSourceMarker(g, spec, path, style, strokeWidth, haloStrokeWidth);\n this.paintTargetMarker(g, spec, path, style, strokeWidth, haloStrokeWidth);\n }\n\n protected paintSourceMarker(\n g: Graphics,\n spec: TSpec,\n path: Path,\n style?: ConnectorPaintStyle,\n strokeWidth: number = resolveStrokeWidth(spec),\n haloStrokeWidth: number = strokeWidth,\n ): void {\n if (!spec.sourceMarker || path.length < 2) return;\n const m = path[0]!;\n const last = path[path.length - 1]!;\n if (m.kind !== 'M' || last.kind === 'M') return;\n const markerStyle = resolveMarkerStyle(style, haloStrokeWidth);\n const t = tangentAt(path, 0);\n const angleRad = Math.atan2(-t.y, -t.x);\n paintMarkerAt(\n g,\n this.host.shapeRegistry,\n spec.sourceMarker,\n { x: m.x, y: m.y },\n angleRad,\n markerStyle,\n strokeWidth,\n );\n }\n\n protected paintTargetMarker(\n g: Graphics,\n spec: TSpec,\n path: Path,\n style?: ConnectorPaintStyle,\n strokeWidth: number = resolveStrokeWidth(spec),\n haloStrokeWidth: number = strokeWidth,\n ): void {\n if (!spec.targetMarker || path.length < 2) return;\n const m = path[0]!;\n const last = path[path.length - 1]!;\n if (m.kind !== 'M' || last.kind === 'M') return;\n const markerStyle = resolveMarkerStyle(style, haloStrokeWidth);\n const t = tangentAt(path, 1);\n const angleRad = Math.atan2(t.y, t.x);\n paintMarkerAt(\n g,\n this.host.shapeRegistry,\n spec.targetMarker,\n { x: last.x, y: last.y },\n angleRad,\n markerStyle,\n strokeWidth,\n );\n }\n}\n\nfunction resolveMarkerStyle(\n style: ConnectorPaintStyle | undefined,\n haloStrokeWidth: number,\n): ShapePaintStyle | undefined {\n if (!style?.tintMarkers) return undefined;\n if (style.markerHalo) {\n return {\n color: style.color ?? 0x000000,\n alpha: style.alpha,\n fill: false,\n strokeWidth: haloStrokeWidth,\n };\n }\n return {\n color: style.color ?? 0x000000,\n alpha: style.alpha,\n fill: true,\n };\n}\n\n/**\n * Single source of truth for the stroke width used by both line and markers.\n * A `style` override (decoration-level repaint) wins over the spec's stroke;\n * if neither resolves to a positive number we fall back to 1 so markers stay\n * visible.\n */\nfunction resolveStrokeWidth(\n spec: BaseConnectorSpec,\n style?: ConnectorPaintStyle,\n): number {\n const w = style?.strokeWidth ?? spec.stroke?.width ?? 1;\n return w > 0 ? w : 1;\n}\n\nfunction paintMarkerAt(\n g: Graphics,\n shapeRegistry: ReadonlyMap<string, ShapeCtor>,\n marker: MarkerShapeSpec,\n anchor: Point,\n angleRad: number,\n style: ShapePaintStyle | undefined,\n strokeWidth: number,\n): void {\n const Ctor = shapeRegistry.get(marker.kind);\n if (!Ctor || typeof Ctor.paintInto !== 'function') return;\n Ctor.paintInto(g, marker, anchor, angleRad, style, strokeWidth);\n}\n\n/**\n * Resolve the tangent-extent of a marker spec — how far past the path's\n * untrimmed endpoint the marker visually extends. Looks up the marker's\n * `static markerInset` on the shape registry and clamps to a positive\n * finite value (`0` for markers that don't declare an inset).\n *\n * Exported so `PrimitivesRenderer` can compute clearance for\n * endpoint-anchored badges (the badge needs to sit past the *whole*\n * marker, not just the trimmed path endpoint).\n */\nexport function markerInsetFor(\n shapeRegistry: ReadonlyMap<string, ShapeCtor>,\n marker: MarkerShapeSpec,\n strokeWidth: number,\n): number {\n const Ctor = shapeRegistry.get(marker.kind);\n if (!Ctor || typeof Ctor.markerInset !== 'function') return 0;\n const inset = Ctor.markerInset(marker, strokeWidth);\n return Number.isFinite(inset) && inset > 0 ? inset : 0;\n}\n","import type { Graphics } from 'pixi.js';\nimport { ConnectorBase } from '../base/ConnectorBase';\nimport { emitDashedStroke } from '../paint/dashedStroke';\nimport type {\n BaseConnectorSpec,\n ConnectorPaintStyle,\n Path,\n} from '../types';\nimport { samplePath } from './pathSampling';\n\n/**\n * The single concrete connector class. Renders any `Path` natively via\n * Pixi commands (`moveTo` / `lineTo` / `quadraticCurveTo` / `bezierCurveTo`),\n * then strokes once with the spec's stroke or the decoration `style` override.\n *\n * Visual variation comes from the `router` (which produces the path), not\n * from connector subclasses. Custom rendering styles (double-line, gradient,\n * wiggle) are added later by extending `ConnectorBase` directly.\n */\nexport class Connector extends ConnectorBase<BaseConnectorSpec> {\n protected drawGeometry(\n g: Graphics,\n spec: BaseConnectorSpec,\n path: Path,\n style?: ConnectorPaintStyle,\n ): void {\n if (path.length < 2) return;\n\n // Decoration overlays take precedence; otherwise honour the spec's own\n // dash. `[0, 0]` (and any tuple with a non-positive endpoint) reads as\n // \"no dash pattern\" — fall through to the solid stroke so the line\n // doesn't disappear when a slider parks at zero.\n const dashArray = style?.dashArray ?? spec.stroke?.dashArray;\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n emitDashedStroke(g, samplePath(path), {\n color: style?.color ?? spec.stroke?.color ?? 0x000000,\n alpha: style?.alpha ?? spec.stroke?.alpha ?? 1,\n width: style?.strokeWidth ?? spec.stroke?.width ?? 1,\n dashArray,\n dashOffset: style?.dashOffset ?? spec.stroke?.dashOffset,\n closed: false,\n // Inherit cap / join from the spec when the override doesn't\n // specify them — decorations that only widen the stroke (glow,\n // ripple) should match the host's silhouette ends instead of\n // forcing butt/miter back on.\n cap: style?.cap ?? spec.stroke?.cap,\n join: style?.join ?? spec.stroke?.join,\n });\n return;\n }\n\n for (const cmd of path) {\n switch (cmd.kind) {\n case 'M':\n g.moveTo(cmd.x, cmd.y);\n break;\n case 'L':\n g.lineTo(cmd.x, cmd.y);\n break;\n case 'Q':\n g.quadraticCurveTo(cmd.cx, cmd.cy, cmd.x, cmd.y);\n break;\n case 'C':\n g.bezierCurveTo(cmd.c1x, cmd.c1y, cmd.c2x, cmd.c2y, cmd.x, cmd.y);\n break;\n }\n }\n\n if (style?.strokeWidth !== undefined) {\n g.stroke({\n color: style.color ?? 0x000000,\n alpha: style.alpha ?? 1,\n width: style.strokeWidth,\n cap: style.cap ?? spec.stroke?.cap,\n join: style.join ?? spec.stroke?.join,\n });\n return;\n }\n\n const s = spec.stroke;\n const width = s?.width ?? 1;\n if (width <= 0) return;\n g.stroke({\n color: s?.color ?? 0x000000,\n alpha: s?.alpha ?? 1,\n width,\n cap: s?.cap,\n join: s?.join,\n });\n }\n}\n","import type { IRouter } from '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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, PathCommand } from '../../types';\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, Point } from '../../types';\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 '../../types';\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 '../../types';\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","import type { IPathStyle } from '../../types';\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 { IAnchor } from '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 '../../types';\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 { Graphics } from 'pixi.js';\nimport { ShapeBase } from '../base/ShapeBase';\nimport { applyMarkerFill } from '../paint/applyFillStroke';\nimport type {\n BaseShapeSpec,\n Point,\n Rect,\n ShapeHostInfo,\n ShapePaintStyle,\n} from '../types';\n\n/**\n * Arrowhead marker. Drawn as a triangle whose tip lies at the anchor; the\n * base extends `lengthScale × strokeWidth` pixels back along the negative\n * tangent direction with a perpendicular spread of `widthScale × strokeWidth`\n * (clamped so the base is never narrower than the line).\n *\n * Sizing is **always proportional to the host connector's stroke width** —\n * a 1px line gets a 4×3 arrow (with the default scales), a 7px line gets a\n * 28×21 arrow. The base width is additionally clamped to ≥ strokeWidth so a\n * thick line never feeds into a narrower arrow base.\n *\n * Two paint surfaces:\n * - **instance**: used as a regular shape via `addShape` — the arrow tip\n * anchors at `(spec.x, spec.y)` and points along +X (angle = 0). Useful\n * for stand-alone arrowheads or directional badges. With no host\n * connector, sizing assumes `strokeWidth = 1`.\n * - **static**: used as a connector marker via `connectorSpec.sourceMarker\n * = arrowMarkerSpec(...)` — the connector calls `ArrowMarker.paintInto`\n * with the polyline endpoint, tangent angle, and resolved strokeWidth.\n */\n\nexport interface ArrowMarkerSpec extends BaseShapeSpec {\n readonly kind: 'arrow';\n /**\n * Multiplier on the connector's stroke width that yields the tip-to-base\n * distance. Default `4` (so a 2px stroke produces an 8px-long arrow).\n */\n readonly lengthScale?: number;\n /**\n * Multiplier on the connector's stroke width that yields the perpendicular\n * base width. Final width is clamped to `≥ strokeWidth` so the arrow base\n * is never narrower than the line. Default `3`.\n */\n readonly widthScale?: number;\n}\n\nconst DEFAULT_LENGTH_SCALE = 4;\nconst DEFAULT_WIDTH_SCALE = 3;\n\n/**\n * Convenience builder for connector marker specs (no `x` / `y`).\n * Usage: `connectorSpec.targetMarker = arrowMarkerSpec({ fill: 0x000000 })`.\n */\nexport function arrowMarkerSpec(\n spec: Omit<ArrowMarkerSpec, 'kind' | 'x' | 'y'> = {},\n): Omit<ArrowMarkerSpec, 'x' | 'y'> {\n return { kind: 'arrow', ...spec };\n}\n\nfunction resolveLength(spec: Omit<ArrowMarkerSpec, 'x' | 'y'>, strokeWidth: number): number {\n return (spec.lengthScale ?? DEFAULT_LENGTH_SCALE) * strokeWidth;\n}\n\nfunction resolveWidth(spec: Omit<ArrowMarkerSpec, 'x' | 'y'>, strokeWidth: number): number {\n const raw = (spec.widthScale ?? DEFAULT_WIDTH_SCALE) * strokeWidth;\n return raw < strokeWidth ? strokeWidth : raw;\n}\n\nexport class ArrowMarker extends ShapeBase<ArrowMarkerSpec> {\n static readonly kind = 'arrow';\n\n constructor(spec: ArrowMarkerSpec, host: ShapeHostInfo) {\n super(host);\n this.draw(spec);\n }\n\n protected drawGeometry(g: Graphics, spec: ArrowMarkerSpec, style?: ShapePaintStyle): void {\n // Instance shapes have no host connector — assume stroke width 1 so the\n // default scales (4, 3) yield a 4×3 arrow, matching the visual the spec\n // multipliers promise relative to a unit line.\n ArrowMarker.paintInto(g, spec, { x: 0, y: 0 }, 0, style, 1);\n }\n\n bounds(): Rect {\n // Mirrors `drawGeometry` — instance bounds use strokeWidth = 1.\n const len = resolveLength(this.spec, 1);\n const wid = resolveWidth(this.spec, 1);\n return { x: -len, y: -wid / 2, width: len, height: wid };\n }\n\n /**\n * Distance from the arrow tip back to the base along the negative tangent.\n * The connector trims its body by this amount so the line stops at the\n * marker's base — the marker triangle then visually starts where the line\n * ends and its tip reaches the original anchor (target endpoint).\n */\n static markerInset(\n spec: Omit<ArrowMarkerSpec, 'x' | 'y'>,\n strokeWidth: number = 1,\n ): number {\n return resolveLength(spec, strokeWidth);\n }\n\n static paintInto(\n g: Graphics,\n spec: Omit<ArrowMarkerSpec, 'x' | 'y'>,\n anchor: Point,\n angleRad: number,\n style?: ShapePaintStyle,\n strokeWidth: number = 1,\n ): void {\n const len = resolveLength(spec, strokeWidth);\n const wid = resolveWidth(spec, strokeWidth);\n const cos = Math.cos(angleRad);\n const sin = Math.sin(angleRad);\n\n // Base center: anchor stepped backward (opposite tangent) by `len`.\n const baseX = anchor.x - cos * len;\n const baseY = anchor.y - sin * len;\n // Perpendicular unit vector (90° CCW from tangent).\n const perpX = -sin;\n const perpY = cos;\n const halfW = wid / 2;\n\n g.poly([\n anchor.x, anchor.y, // tip\n baseX + perpX * halfW, baseY + perpY * halfW, // wing 1\n baseX - perpX * halfW, baseY - perpY * halfW, // wing 2\n ]);\n\n if (style?.fill === false) {\n // Halo / outline mode: stroke the marker silhouette at the requested\n // width. Geometry size still comes from `strokeWidth × *Scale` (above),\n // so the halo widens without scaling the marker.\n if (style.color !== undefined && (style.strokeWidth ?? 0) > 0) {\n g.stroke({\n width: style.strokeWidth!,\n color: style.color,\n alpha: style.alpha ?? 1,\n });\n }\n return;\n }\n if (style?.color !== undefined) {\n g.fill({ color: style.color, alpha: style.alpha ?? 1 });\n return;\n }\n if (spec.fill !== undefined) {\n applyMarkerFill(g, spec.fill, style);\n return;\n }\n // Default: black-filled arrow.\n g.fill({ color: 0x000000 });\n }\n}\n","import { PrimitiveBase } from './PrimitiveBase';\nimport type { IShapeDecoration, ShapeDecorationHostInfo } from '../types';\n\n/**\n * Base for decorations that target shape primitives. Subclass implements\n * `repaint`; this base handles the `mount` / `update` lifecycle (attach gfx\n * to the host's surface, set the slot z-index, cache the host, repaint).\n *\n * Animation: subclass adds `tick(deltaMs)` if it wants to be advanced per\n * frame. The renderer registers any decoration with a `tick` method into\n * its animation set; a falsy return retires the decoration.\n */\nexport abstract class ShapeDecorationBase<TStyle>\n extends PrimitiveBase\n implements IShapeDecoration<TStyle>\n{\n readonly style: TStyle;\n protected host: ShapeDecorationHostInfo | null = null;\n\n constructor(style: TStyle) {\n super();\n this.style = style;\n this.gfx.label = `deco:${this.constructor.name}`;\n }\n\n mount(host: ShapeDecorationHostInfo): void {\n this.host = host;\n this.gfx.zIndex = host.slotZIndex;\n host.surface.addChild(this.gfx);\n this.repaint();\n }\n\n update(host: ShapeDecorationHostInfo): void {\n this.host = host;\n this.repaint();\n }\n\n /** Render the decoration based on the current `host`. */\n protected abstract repaint(): void;\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\n\n/**\n * Halo / outer glow. Repaints the host's silhouette N times with widening\n * stroke and quadratic alpha falloff, producing a soft glow that hugs\n * whatever silhouette the host paints. Works on every shape that\n * implements `paintInto` (everything extending `ShapeBase`).\n *\n * Static by default. Supply `pulse` to animate brightness sinusoidally —\n * the renderer will register `tick` and advance the phase each frame.\n */\nexport interface GlowDecorationStyle {\n readonly color: number;\n /**\n * Outermost feather layer's stroke width, px. The outermost stroke\n * extends this many pixels past the host silhouette (`paintInto`'s\n * default alignment is `'outside'`), so the visual outer reach of the\n * glow matches this value. Inner layers taper linearly to `1` px.\n * Default `12`.\n *\n * Not a circle radius — the glow traces whatever silhouette the host\n * draws (rect / polygon / star / ...). The name reflects the underlying\n * stroke geometry, not the shape kind.\n */\n readonly strokeWidth?: number;\n /** Number of feather layers (more = smoother + more expensive). Default `6`. */\n readonly layers?: number;\n /** Innermost (brightest) layer alpha. Default `0.55`. */\n readonly innerAlpha?: number;\n /**\n * Optional brightness pulse. When omitted, the glow is static. When set,\n * the decoration alpha-multiplies between `1` and `1 - amplitude` on a\n * sinusoidal cycle of `periodMs` milliseconds.\n */\n readonly pulse?: {\n /** Cycle length in ms. Default `1200`. */\n readonly periodMs?: number;\n /** How far below full brightness the dim phase reaches, `[0, 1]`. Default `0.5`. */\n readonly amplitude?: number;\n };\n}\n\nexport class GlowDecoration extends ShapeDecorationBase<GlowDecorationStyle> {\n private layerGfx: Graphics[] = [];\n private pulseElapsed = 0;\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n\n const maxStroke = this.style.strokeWidth ?? 12;\n const layers = Math.max(1, this.style.layers ?? 6);\n const innerAlpha = this.style.innerAlpha ?? 0.55;\n const color = this.style.color;\n\n this.syncLayerCount(layers);\n\n const shape = host.shape;\n if (!shape.paintInto) {\n // Host shape doesn't support paintInto (e.g. text labels). Silently\n // clear all layers and skip — no glow on this shape kind.\n for (const g of this.layerGfx) g.clear();\n return;\n }\n\n // Outermost first (i=0), brightest last (i=layers-1).\n for (let i = 0; i < layers; i++) {\n const t = i / (layers - 1 || 1); // 0 (outer) .. 1 (inner)\n const strokeWidth = maxStroke * (1 - t) + 1; // wide outside, thin inside\n const alpha = innerAlpha * (t * t); // quadratic falloff\n const g = this.layerGfx[i]!;\n g.clear();\n shape.paintInto(g, { color, alpha, strokeWidth, fill: false });\n }\n }\n\n /**\n * Advance the optional pulse phase. Geometry is repainted once at mount\n * (cheap) and never again — only `this.gfx.alpha` is touched per frame,\n * so animated pulse is essentially free.\n */\n tick(deltaMs: number): boolean {\n if (!this.style.pulse) return false;\n this.pulseElapsed += deltaMs;\n const period = this.style.pulse.periodMs ?? 1200;\n const amplitude = this.style.pulse.amplitude ?? 0.5;\n const phase = (this.pulseElapsed / period) * Math.PI * 2;\n // Map sin from [-1, 1] to [1 - amplitude, 1].\n this.gfx.alpha = 1 - amplitude * (0.5 - 0.5 * Math.sin(phase));\n return true;\n }\n\n /**\n * Outer edge of the halo — the widest stroke layer paints at roughly\n * `strokeWidth` past the silhouette (`paintInto` defaults to `'outside'`\n * alignment, so the full stroke sits outward). Reported so\n * `LabelDecoration` can push outside-placement labels past the glow.\n * The optional `pulse` only modulates alpha, not geometry, so the\n * resting extent is the only one worth reporting.\n */\n getOuterExtent(): number {\n return this.style.strokeWidth ?? 12;\n }\n\n private syncLayerCount(n: number): void {\n while (this.layerGfx.length < n) {\n const g = new Graphics();\n this.gfx.addChild(g);\n this.layerGfx.push(g);\n }\n while (this.layerGfx.length > n) {\n this.layerGfx.pop()!.destroy();\n }\n }\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\n\n/**\n * Concentric rings that expand outward from the host's silhouette and fade\n * as they grow. A canonical \"attention\" decoration — pings, notifications,\n * \"new arrival\" indicators, sonar effects.\n *\n * Each ring traces the host silhouette via `paintInto` with a growing\n * `inset` (negative = outside) and shrinking alpha. Multiple concurrent\n * rings are scheduled by phase-offset across one period — so a `rings: 3`\n * decoration always shows three rings at different stages of expansion,\n * giving a steady visual rhythm.\n */\nexport interface PulseRingDecorationStyle {\n readonly color: number;\n /** Peak expansion distance from the host silhouette, px. Default `24`. */\n readonly maxRadius?: number;\n /** Cycle length in ms. Default `1400`. */\n readonly periodMs?: number;\n /** Number of concurrent rings (phase-distributed). Default `2`. */\n readonly rings?: number;\n /** Stroke width of each ring, px. Default `2`. */\n readonly strokeWidth?: number;\n /** Initial (full-brightness) alpha at radius 0. Default `0.7`. */\n readonly innerAlpha?: number;\n}\n\nexport class PulseRingDecoration extends ShapeDecorationBase<PulseRingDecorationStyle> {\n private ringGfx: Graphics[] = [];\n private elapsed = 0;\n\n protected repaint(): void {\n // Pulse geometry is purely a function of phase, so any host-bounds\n // change re-applies on the next tick. We only ensure the right number\n // of ring Graphics exist here.\n const rings = Math.max(1, this.style.rings ?? 2);\n this.syncRingCount(rings);\n }\n\n tick(deltaMs: number): boolean {\n const host = this.host;\n if (!host || !host.shape.paintInto) return true;\n\n this.elapsed += deltaMs;\n const period = this.style.periodMs ?? 1400;\n const maxRadius = this.style.maxRadius ?? 24;\n const rings = Math.max(1, this.style.rings ?? 2);\n const strokeWidth = this.style.strokeWidth ?? 2;\n const innerAlpha = this.style.innerAlpha ?? 0.7;\n const color = this.style.color;\n\n // Phase-distribute rings: each ring leads the next by `1/rings` of period.\n for (let i = 0; i < rings; i++) {\n const phase = ((this.elapsed / period) + i / rings) % 1; // [0, 1)\n const radius = maxRadius * phase; // grows outward\n const alpha = innerAlpha * (1 - phase); // fades as it grows\n const g = this.ringGfx[i]!;\n g.clear();\n // Negative inset draws the silhouette OUTSIDE the shape by `radius` px.\n host.shape.paintInto(g, {\n color,\n alpha,\n strokeWidth,\n fill: false,\n inset: -radius,\n });\n }\n return true;\n }\n\n private syncRingCount(n: number): void {\n while (this.ringGfx.length < n) {\n const g = new Graphics();\n this.gfx.addChild(g);\n this.ringGfx.push(g);\n }\n while (this.ringGfx.length > n) {\n this.ringGfx.pop()!.destroy();\n }\n }\n}\n","import { Container, FillGradient, Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\n\n/**\n * Liquid fill — paints a fluid level inside the host's silhouette, with a\n * vertical gradient and an optional wavy surface. Achieved without a \"fill\n * provider\" hook on shapes: the decoration paints a fluid polygon into its\n * own Graphics and masks the whole thing with the host silhouette via\n * `host.shape.paintInto({ fill: true })`.\n *\n * **Stroke compatibility.** When the host shape's stroke alignment is\n * `'outside'`, the stroke sits outside the silhouette and the mask leaves it\n * fully visible. For `'center'` / `'inside'`, the liquid covers the inside\n * portion of the stroke. Prefer `'outside'` for tank / pill diagrams.\n *\n * **Animation.** When `wave` is omitted the surface is a flat horizontal\n * line and `tick` returns `false` — the renderer retires the decoration\n * from its animation set, so still-water mode costs zero per frame after\n * `mount`. Supply `wave` to animate the meniscus.\n */\nexport interface LiquidFillDecorationStyle {\n /** Surface height as a fraction of host bounds height. `0` empty, `1` full. Default `0.6`. */\n readonly fillLevel?: number;\n /** Gradient colour at the surface. Default light blue (`0x9bbedb`). */\n readonly colorTop?: number;\n /** Gradient colour at the bottom. Default dark blue (`0x2d4d6e`). */\n readonly colorBottom?: number;\n /** Overall opacity of the fluid. Default `1`. */\n readonly alpha?: number;\n /**\n * Wave configuration. Omit (or pass `undefined`) for a flat still surface.\n * Provide for an animated meniscus — phase advances every frame.\n */\n readonly wave?: {\n /** Peak vertical displacement of the surface, px. Default `3`. */\n readonly amplitude?: number;\n /** Distance between wave crests, px. Default `80`. */\n readonly wavelength?: number;\n /** Time for one full phase cycle, ms. Default `1800`. */\n readonly periodMs?: number;\n /** Sample points per wavelength. Higher = smoother + more expensive. Default `12`. */\n readonly resolution?: number;\n };\n /**\n * Optional thin highlight band stroked along the surface (gloss / meniscus\n * effect). Opt-in: omit the field to skip drawing the highlight entirely.\n */\n readonly surfaceHighlight?: {\n /** Default `0xffffff`. */\n readonly color?: number;\n /** Default `0.35`. */\n readonly alpha?: number;\n /** Stroke width in px. Default `3`. */\n readonly thickness?: number;\n };\n}\n\nexport class LiquidFillDecoration extends ShapeDecorationBase<LiquidFillDecorationStyle> {\n private maskGfx: Graphics | null = null;\n private fluidContainer: Container | null = null;\n private fluidGfx: Graphics | null = null;\n private highlightGfx: Graphics | null = null;\n private gradient: FillGradient | null = null;\n private wavePhase = 0;\n\n protected repaint(): void {\n const host = this.host;\n if (!host || !host.shape.paintInto) return;\n\n if (!this.maskGfx) {\n this.maskGfx = new Graphics();\n this.gfx.addChild(this.maskGfx);\n }\n if (!this.fluidContainer) {\n this.fluidContainer = new Container();\n this.gfx.addChild(this.fluidContainer);\n }\n if (!this.fluidGfx) {\n this.fluidGfx = new Graphics();\n this.fluidContainer.addChild(this.fluidGfx);\n }\n if (!this.highlightGfx) {\n this.highlightGfx = new Graphics();\n this.fluidContainer.addChild(this.highlightGfx);\n }\n this.fluidContainer.mask = this.maskGfx;\n\n // Repaint silhouette mask — any non-transparent fill works as a mask.\n this.maskGfx.clear();\n host.shape.paintInto(this.maskGfx, {\n color: 0xffffff,\n alpha: 1,\n strokeWidth: 0,\n fill: true,\n });\n\n // (Re)build gradient when colours change. Local-space gradient auto-fits\n // its bounding box to the fill shape — top → surface, bottom → bottom.\n const colorTop = this.style.colorTop ?? 0x9bbedb;\n const colorBottom = this.style.colorBottom ?? 0x2d4d6e;\n this.gradient?.destroy();\n this.gradient = new FillGradient({\n type: 'linear',\n start: { x: 0, y: 0 },\n end: { x: 0, y: 1 },\n colorStops: [\n { offset: 0, color: colorTop },\n { offset: 1, color: colorBottom },\n ],\n textureSpace: 'local',\n });\n\n this.gfx.alpha = this.style.alpha ?? 1;\n this.drawFluid();\n }\n\n tick(deltaMs: number): boolean {\n if (!this.style.wave) {\n // Still water — no animation needed; renderer retires us.\n return false;\n }\n const period = this.style.wave.periodMs ?? 1800;\n this.wavePhase += (deltaMs / period) * Math.PI * 2;\n this.drawFluid();\n return true;\n }\n\n destroy(): void {\n this.gradient?.destroy();\n this.gradient = null;\n super.destroy();\n }\n\n private drawFluid(): void {\n const host = this.host;\n const fluid = this.fluidGfx;\n const highlight = this.highlightGfx;\n const gradient = this.gradient;\n if (!host || !fluid || !highlight || !gradient) return;\n\n const bounds = host.bounds;\n const fillLevel = Math.min(1, Math.max(0, this.style.fillLevel ?? 0.6));\n const wave = this.style.wave;\n\n const surfaceY = bounds.y + bounds.height * (1 - fillLevel);\n const left = bounds.x;\n const right = bounds.x + bounds.width;\n const bottom = bounds.y + bounds.height;\n const width = right - left;\n\n // Sample the surface polyline. Flat for still water; sinusoidal otherwise.\n const surfacePts: { x: number; y: number }[] = [];\n if (wave) {\n const amplitude = wave.amplitude ?? 3;\n const wavelength = Math.max(1, wave.wavelength ?? 80);\n const resolution = Math.max(2, wave.resolution ?? 12);\n const samples = Math.max(4, Math.ceil((width / wavelength) * resolution));\n for (let i = 0; i <= samples; i++) {\n const x = left + (width * i) / samples;\n const y = surfaceY + Math.sin((x / wavelength) * Math.PI * 2 + this.wavePhase) * amplitude;\n surfacePts.push({ x, y });\n }\n } else {\n surfacePts.push({ x: left, y: surfaceY }, { x: right, y: surfaceY });\n }\n\n // Body polygon: bottom-left → up to surface-left → wavy top → down to bottom-right → close.\n fluid.clear();\n fluid.moveTo(left, bottom);\n fluid.lineTo(surfacePts[0]!.x, surfacePts[0]!.y);\n for (let i = 1; i < surfacePts.length; i++) {\n fluid.lineTo(surfacePts[i]!.x, surfacePts[i]!.y);\n }\n fluid.lineTo(right, bottom);\n fluid.closePath();\n fluid.fill(gradient);\n\n // Optional highlight band along the surface — opt-in via style.\n highlight.clear();\n const hl = this.style.surfaceHighlight;\n if (hl) {\n const color = hl.color ?? 0xffffff;\n const alpha = hl.alpha ?? 0.35;\n const width = hl.thickness ?? 3;\n highlight.moveTo(surfacePts[0]!.x, surfacePts[0]!.y);\n for (let i = 1; i < surfacePts.length; i++) {\n highlight.lineTo(surfacePts[i]!.x, surfacePts[i]!.y);\n }\n highlight.stroke({ color, alpha, width });\n }\n }\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\n\n/**\n * Classic \"marching ants\" selection outline. Strokes the host silhouette\n * with a dashed border whose `dashOffset` advances each frame, producing\n * the characteristic crawling-along-the-edge animation seen in selection\n * marquees (Photoshop, Figma, etc.).\n *\n * Geometry is delegated to `host.shape.paintInto` with `dashArray` /\n * `dashOffset` overrides — the shape primitive itself does the\n * silhouette tessellation. Works on every shape that implements\n * `paintInto` (anything extending `ShapeBase`).\n */\nexport interface MarchingAntsDecorationStyle {\n readonly color: number;\n /** Stroke width in px. Default `1.5`. */\n readonly strokeWidth?: number;\n /** Dash length in px. Default `6`. */\n readonly dashLength?: number;\n /** Gap length in px. Default `4`. */\n readonly gapLength?: number;\n /**\n * March speed in px/sec along the perimeter. Default `24`.\n * Negative values reverse the march direction.\n */\n readonly speedPxPerSec?: number;\n /**\n * Distance from the host silhouette. Positive = inside, negative =\n * outside. Default `0` (on the silhouette itself).\n */\n readonly inset?: number;\n /** Overall decoration alpha. Default `1`. */\n readonly alpha?: number;\n}\n\nexport class MarchingAntsDecoration extends ShapeDecorationBase<MarchingAntsDecorationStyle> {\n private antsGfx = new Graphics();\n private elapsedMs = 0;\n\n protected repaint(): void {\n // One-time attach; the tick loop redraws every frame so we don't need\n // to re-emit geometry here. Just ensure the Graphics child is mounted.\n if (this.antsGfx.parent !== this.gfx) {\n this.gfx.addChild(this.antsGfx);\n }\n }\n\n tick(deltaMs: number): boolean {\n const host = this.host;\n if (!host?.shape.paintInto) {\n this.antsGfx.clear();\n return true;\n }\n\n this.elapsedMs += deltaMs;\n const speed = this.style.speedPxPerSec ?? 24;\n const dashLen = Math.max(0.5, this.style.dashLength ?? 6);\n const gapLen = Math.max(0.5, this.style.gapLength ?? 4);\n // Negative offset → dashes appear to march in the direction the\n // shape's outline is traversed (counter-clockwise for circle, clockwise\n // for rect). Speed sign flips this.\n const dashOffset = -(this.elapsedMs / 1000) * speed;\n\n this.antsGfx.clear();\n host.shape.paintInto(this.antsGfx, {\n color: this.style.color,\n alpha: this.style.alpha ?? 1,\n strokeWidth: this.style.strokeWidth ?? 1.5,\n fill: false,\n dashArray: [dashLen, gapLen],\n dashOffset,\n inset: this.style.inset ?? 0,\n });\n return true;\n }\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\n\n/**\n * Static ring that traces the host silhouette at a fixed outward offset.\n *\n * Geometry: one `paintInto` call with a negative inset, so the ring sits\n * cleanly *outside* the body — independent from the host's own stroke.\n * Multiple rings (e.g. inner + outer) compose by attaching multiple Ring\n * decorations with different `gap` values; this class itself paints one\n * band per instance.\n *\n * Works on every shape that implements `paintInto` (everything extending\n * `ShapeBase`). On shape kinds without `paintInto` (e.g. plain text) the\n * decoration silently clears — same fallback as `GlowDecoration`.\n */\nexport interface RingDecorationStyle {\n readonly color: number;\n /** Ring stroke thickness, px. Default `2`. */\n readonly width?: number;\n /**\n * Gap between the host silhouette and the ring's inner edge, px.\n * Default `4`. Zero hugs the body; larger values produce a detached ring.\n */\n readonly gap?: number;\n /** Ring alpha, `[0, 1]`. Default `1`. */\n readonly alpha?: number;\n /** Dashed ring — `[dashLength, gapLength]` in px. Default solid. */\n readonly dashArray?: readonly [number, number];\n}\n\nexport class RingDecoration extends ShapeDecorationBase<RingDecorationStyle> {\n private readonly band = new Graphics();\n\n constructor(style: RingDecorationStyle) {\n super(style);\n this.gfx.addChild(this.band);\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n\n const width = this.style.width ?? 2;\n const gap = this.style.gap ?? 4;\n const alpha = this.style.alpha ?? 1;\n const color = this.style.color;\n const dashArray = this.style.dashArray;\n\n this.band.clear();\n\n const shape = host.shape;\n if (!shape.paintInto) {\n // Host shape doesn't support paintInto (e.g. plain text labels) —\n // silently skip, matching GlowDecoration's behaviour.\n return;\n }\n\n // Paint a stroke at `inset = -gap` (the silhouette pushed `gap` outward)\n // and let alignment: 'outside' place the entire `width`-thick band on\n // the *outside* of that path. Net result: visible ring sits at\n // [gap, gap + width] outside the body, with no bleed into the fill.\n shape.paintInto(this.band, {\n color,\n alpha,\n strokeWidth: width,\n alignment: 'outside',\n fill: false,\n inset: -gap,\n ...(dashArray ? { dashArray } : {}),\n });\n }\n\n /**\n * Outer edge of the band: `gap` pushes the silhouette outward, then the\n * full stroke width sits past that. Reported so `LabelDecoration` can\n * offset outside-placement labels past the ring.\n */\n getOuterExtent(): number {\n const width = this.style.width ?? 2;\n const gap = this.style.gap ?? 4;\n return gap + width;\n }\n}\n","import { PrimitiveBase } from './PrimitiveBase';\nimport type { ConnectorDecorationHostInfo, IConnectorDecoration } from '../types';\n\n/**\n * Base for decorations that target connector primitives. Mirrors\n * `ShapeDecorationBase` — subclass implements `repaint`, the base handles\n * `mount` / `update` lifecycle.\n *\n * Connector decorations receive the routed `Path` (not a polyline). When a\n * decoration needs uniform-arc-length sampling (rare — most decorations\n * call `connector.paintInto` for native dashed/styled strokes), it pulls\n * `samplePath(path, n)` from `primitives/connectors/pathSampling.ts`.\n */\nexport abstract class ConnectorDecorationBase<TStyle>\n extends PrimitiveBase\n implements IConnectorDecoration<TStyle>\n{\n readonly style: TStyle;\n protected host: ConnectorDecorationHostInfo | null = null;\n\n constructor(style: TStyle) {\n super();\n this.style = style;\n this.gfx.label = `deco:${this.constructor.name}`;\n }\n\n mount(host: ConnectorDecorationHostInfo): void {\n this.host = host;\n this.gfx.zIndex = host.slotZIndex;\n host.surface.addChild(this.gfx);\n this.repaint();\n }\n\n update(host: ConnectorDecorationHostInfo): void {\n this.host = host;\n this.repaint();\n }\n\n protected abstract repaint(): void;\n}\n","import { Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\n\n/**\n * Connector variant of marching-ants. Strokes the connector's routed path\n * with a dashed line whose `dashOffset` advances each frame, producing\n * a flowing/marching pattern along the line — useful for highlighting an\n * active edge, a route under consideration, a data flow, etc.\n *\n * Geometry is delegated to `host.connector.paintInto` with `dashArray` /\n * `dashOffset` overrides; the connector primitive samples the routed\n * path and emits dashes via the shared `dashedStroke` helper. Works on\n * every router / pathStyle (straight, orth, bezier, smooth — all produce\n * a `Path`).\n */\nexport interface MarchingAntsConnectorDecorationStyle {\n readonly color: number;\n /** Stroke width in px. Default `1.5`. */\n readonly strokeWidth?: number;\n /** Dash length in px. Default `6`. */\n readonly dashLength?: number;\n /** Gap length in px. Default `4`. */\n readonly gapLength?: number;\n /**\n * March speed in px/sec along the path. Default `24`.\n * Negative values reverse the march direction.\n */\n readonly speedPxPerSec?: number;\n /** Overall decoration alpha. Default `1`. */\n readonly alpha?: number;\n readonly cap?: 'butt' | 'round' | 'square';\n readonly join?: 'miter' | 'round' | 'bevel';\n}\n\nexport class MarchingAntsConnectorDecoration extends ConnectorDecorationBase<MarchingAntsConnectorDecorationStyle> {\n private antsGfx = new Graphics();\n private elapsedMs = 0;\n\n protected repaint(): void {\n if (this.antsGfx.parent !== this.gfx) {\n this.gfx.addChild(this.antsGfx);\n }\n }\n\n tick(deltaMs: number): boolean {\n const host = this.host;\n if (!host) {\n this.antsGfx.clear();\n return true;\n }\n\n this.elapsedMs += deltaMs;\n const speed = this.style.speedPxPerSec ?? 24;\n const dashLen = Math.max(0.5, this.style.dashLength ?? 6);\n const gapLen = Math.max(0.5, this.style.gapLength ?? 4);\n const dashOffset = -(this.elapsedMs / 1000) * speed;\n\n this.antsGfx.clear();\n host.connector.paintInto(this.antsGfx, host.connectorSpec, host.path, {\n color: this.style.color,\n alpha: this.style.alpha ?? 1,\n strokeWidth: this.style.strokeWidth ?? 1.5,\n dashArray: [dashLen, gapLen],\n dashOffset,\n cap: this.style.cap,\n join: this.style.join,\n });\n return true;\n }\n}\n","import { Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\nimport { samplePath } from '../../connectors/pathSampling';\nimport type { Path, Point } from '../../types';\n\n/**\n * Connector decoration that animates a single marker travelling along the\n * routed path of its host. Useful for visualising direction, data flow, or\n * an active \"in-flight\" state on an edge. Works on every router / pathStyle\n * because it consumes the resolved `Path` via `samplePath`.\n *\n * The marker's silhouette is drawn once into `markerGfx`; only its position\n * and rotation are updated each frame. Position is derived from a\n * cumulative arc-length table rebuilt on `repaint` (host or style change),\n * so per-frame work is a binary search + interpolation.\n */\nexport interface FlyMarkerConnectorDecorationStyle {\n readonly color: number;\n /** Marker silhouette. Default `'circle'`. */\n readonly markerKind?: 'circle' | 'arrow' | 'square';\n /** Marker size in px (diameter / arrow length / square side). Default `8`. */\n readonly size?: number;\n /**\n * Travel speed along the path in px/sec. Negative values reverse direction.\n * Default `80`.\n */\n readonly speedPxPerSec?: number;\n /**\n * When `true` (default) the marker wraps back to the start after reaching\n * the end (or vice versa for negative speed). When `false` the marker\n * stops at the end of the path until the decoration is removed.\n */\n readonly loop?: boolean;\n /** Initial position along the path in `[0, 1]`. Default `0`. */\n readonly phase?: number;\n /**\n * Rotate the marker so its local +x axis points along the local tangent.\n * Default `true` for `'arrow'`, `false` for `'circle'` and `'square'`.\n */\n readonly orientToPath?: boolean;\n /** Overall decoration alpha. Default `1`. */\n readonly alpha?: number;\n}\n\nexport class FlyMarkerConnectorDecoration extends ConnectorDecorationBase<FlyMarkerConnectorDecorationStyle> {\n private markerGfx = new Graphics();\n private elapsedMs = 0;\n\n /** Densified polyline of the current host path. */\n private samples: Point[] = [];\n /** Cumulative arc-length at each sample. `cumLen[i]` = distance from samples[0] to samples[i]. */\n private cumLen: number[] = [];\n /** Total arc length of the sampled polyline. */\n private totalLen = 0;\n\n protected repaint(): void {\n if (this.markerGfx.parent !== this.gfx) {\n this.gfx.addChild(this.markerGfx);\n }\n this.gfx.alpha = this.style.alpha ?? 1;\n\n const host = this.host;\n if (!host) {\n this.markerGfx.clear();\n this.samples = [];\n this.cumLen = [];\n this.totalLen = 0;\n return;\n }\n\n this.rebuildArcTable(host.path);\n this.drawMarkerSilhouette();\n }\n\n tick(deltaMs: number): boolean {\n if (!this.host || this.totalLen <= 0) return true;\n\n this.elapsedMs += deltaMs;\n const speed = this.style.speedPxPerSec ?? 80;\n const phase = clamp01(this.style.phase ?? 0);\n const loop = this.style.loop ?? true;\n\n let dist = phase * this.totalLen + (this.elapsedMs / 1000) * speed;\n if (loop) {\n dist = ((dist % this.totalLen) + this.totalLen) % this.totalLen;\n } else if (dist < 0) {\n dist = 0;\n } else if (dist > this.totalLen) {\n dist = this.totalLen;\n }\n\n const { x, y, tx, ty } = this.sampleAt(dist);\n this.markerGfx.position.set(x, y);\n\n const orientToPath =\n this.style.orientToPath ?? (this.style.markerKind ?? 'circle') === 'arrow';\n this.markerGfx.rotation = orientToPath ? Math.atan2(ty, tx) : 0;\n\n return true;\n }\n\n private rebuildArcTable(path: Path): void {\n const samples = samplePath(path);\n this.samples = samples;\n const cum: number[] = new Array(samples.length);\n let total = 0;\n if (samples.length > 0) {\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 this.cumLen = cum;\n this.totalLen = total;\n }\n\n /** Position + unit tangent at arc-length `dist` along the sampled polyline. */\n private sampleAt(dist: number): { x: number; y: number; tx: number; ty: number } {\n const n = this.samples.length;\n if (n === 0) return { x: 0, y: 0, tx: 1, ty: 0 };\n if (n === 1) return { x: this.samples[0]!.x, y: this.samples[0]!.y, tx: 1, ty: 0 };\n\n const last = this.samples[n - 1]!;\n if (dist >= this.totalLen) {\n const prev = this.samples[n - 2]!;\n const dx = last.x - prev.x;\n const dy = last.y - prev.y;\n const len = Math.hypot(dx, dy) || 1;\n return { x: last.x, y: last.y, tx: dx / len, ty: dy / len };\n }\n\n // Binary-search for the segment containing `dist`.\n let lo = 0;\n let hi = n - 1;\n while (lo < hi - 1) {\n const mid = (lo + hi) >>> 1;\n if (this.cumLen[mid]! <= dist) lo = mid;\n else hi = mid;\n }\n const a = this.samples[lo]!;\n const b = this.samples[lo + 1]!;\n const segStart = this.cumLen[lo]!;\n const segEnd = this.cumLen[lo + 1]!;\n const segLen = segEnd - segStart;\n const u = segLen > 0 ? (dist - segStart) / segLen : 0;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const tLen = Math.hypot(dx, dy) || 1;\n return {\n x: a.x + dx * u,\n y: a.y + dy * u,\n tx: dx / tLen,\n ty: dy / tLen,\n };\n }\n\n private drawMarkerSilhouette(): void {\n const g = this.markerGfx;\n g.clear();\n const color = this.style.color;\n const size = Math.max(1, this.style.size ?? 8);\n const kind = this.style.markerKind ?? 'circle';\n\n switch (kind) {\n case 'circle': {\n g.circle(0, 0, size / 2).fill({ color });\n break;\n }\n case 'square': {\n const h = size / 2;\n g.rect(-h, -h, size, size).fill({ color });\n break;\n }\n case 'arrow': {\n // Isoceles triangle pointing along +x. Tip at (size/2, 0), base width = size.\n const tip = size / 2;\n const base = -size / 2;\n const half = size / 2;\n g.poly([tip, 0, base, -half, base, half]).fill({ color });\n break;\n }\n }\n }\n}\n\nfunction clamp01(v: number): number {\n if (v < 0) return 0;\n if (v > 1) return 1;\n return v;\n}\n","import { Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\nimport { samplePath } from '../../connectors/pathSampling';\nimport type { Path, Point } from '../../types';\n\n/**\n * Connector decoration that animates `count` markers travelling along the\n * routed path at the same speed, evenly spread in phase. Useful for\n * visualising sustained flow / throughput on an edge (e.g. data streaming,\n * traffic).\n *\n * Same engine as `FlyMarkerConnectorDecoration` extended to N markers; one\n * arc-length table is built per repaint and shared across all particles.\n */\nexport interface FlowParticlesConnectorDecorationStyle {\n readonly color: number;\n /** Marker silhouette. Default `'circle'`. */\n readonly markerKind?: 'circle' | 'arrow' | 'square';\n /** Number of particles. Clamped to `>= 1`. Default `5`. */\n readonly count?: number;\n /** Marker size in px. Default `6`. */\n readonly size?: number;\n /**\n * Travel speed along the path in px/sec. Negative values reverse direction.\n * Default `60`.\n */\n readonly speedPxPerSec?: number;\n /**\n * When `true` (default) particles wrap back to the start after reaching\n * the end. Setting this to `false` makes all particles stall at the end\n * once they arrive — usually only useful with `count: 1`.\n */\n readonly loop?: boolean;\n /** Phase offset applied to every particle in `[0, 1]`. Default `0`. */\n readonly phase?: number;\n /**\n * Rotate each marker so its local +x axis points along the local tangent.\n * Default `true` for `'arrow'`, `false` for `'circle'` and `'square'`.\n */\n readonly orientToPath?: boolean;\n /** Overall decoration alpha. Default `1`. */\n readonly alpha?: number;\n}\n\nexport class FlowParticlesConnectorDecoration extends ConnectorDecorationBase<FlowParticlesConnectorDecorationStyle> {\n private particles: Graphics[] = [];\n private elapsedMs = 0;\n\n private samples: Point[] = [];\n private cumLen: number[] = [];\n private totalLen = 0;\n\n protected repaint(): void {\n this.gfx.alpha = this.style.alpha ?? 1;\n\n const host = this.host;\n if (!host) {\n for (const p of this.particles) p.clear();\n this.samples = [];\n this.cumLen = [];\n this.totalLen = 0;\n return;\n }\n\n this.rebuildArcTable(host.path);\n this.syncParticleCount();\n this.drawSilhouetteIntoEach();\n }\n\n tick(deltaMs: number): boolean {\n if (!this.host || this.totalLen <= 0 || this.particles.length === 0) return true;\n\n this.elapsedMs += deltaMs;\n const speed = this.style.speedPxPerSec ?? 60;\n const basePhase = clamp01(this.style.phase ?? 0);\n const loop = this.style.loop ?? true;\n const total = this.totalLen;\n const count = this.particles.length;\n\n const orientToPath =\n this.style.orientToPath ?? (this.style.markerKind ?? 'circle') === 'arrow';\n\n const travel = (this.elapsedMs / 1000) * speed;\n\n for (let i = 0; i < count; i++) {\n const particlePhase = basePhase + i / count;\n let dist = particlePhase * total + travel;\n if (loop) {\n dist = ((dist % total) + total) % total;\n } else if (dist < 0) {\n dist = 0;\n } else if (dist > total) {\n dist = total;\n }\n const { x, y, tx, ty } = this.sampleAt(dist);\n const g = this.particles[i]!;\n g.position.set(x, y);\n g.rotation = orientToPath ? Math.atan2(ty, tx) : 0;\n }\n\n return true;\n }\n\n private syncParticleCount(): void {\n const target = Math.max(1, Math.floor(this.style.count ?? 5));\n while (this.particles.length < target) {\n const g = new Graphics();\n this.gfx.addChild(g);\n this.particles.push(g);\n }\n while (this.particles.length > target) {\n const g = this.particles.pop()!;\n g.destroy();\n }\n }\n\n private drawSilhouetteIntoEach(): void {\n const color = this.style.color;\n const size = Math.max(1, this.style.size ?? 6);\n const kind = this.style.markerKind ?? 'circle';\n for (const g of this.particles) {\n g.clear();\n switch (kind) {\n case 'circle': {\n g.circle(0, 0, size / 2).fill({ color });\n break;\n }\n case 'square': {\n const h = size / 2;\n g.rect(-h, -h, size, size).fill({ color });\n break;\n }\n case 'arrow': {\n const tip = size / 2;\n const base = -size / 2;\n const half = size / 2;\n g.poly([tip, 0, base, -half, base, half]).fill({ color });\n break;\n }\n }\n }\n }\n\n private rebuildArcTable(path: Path): void {\n const samples = samplePath(path);\n this.samples = samples;\n const cum: number[] = new Array(samples.length);\n let total = 0;\n if (samples.length > 0) {\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 this.cumLen = cum;\n this.totalLen = total;\n }\n\n private sampleAt(dist: number): { x: number; y: number; tx: number; ty: number } {\n const n = this.samples.length;\n if (n === 0) return { x: 0, y: 0, tx: 1, ty: 0 };\n if (n === 1) return { x: this.samples[0]!.x, y: this.samples[0]!.y, tx: 1, ty: 0 };\n\n const last = this.samples[n - 1]!;\n if (dist >= this.totalLen) {\n const prev = this.samples[n - 2]!;\n const dx = last.x - prev.x;\n const dy = last.y - prev.y;\n const len = Math.hypot(dx, dy) || 1;\n return { x: last.x, y: last.y, tx: dx / len, ty: dy / len };\n }\n\n let lo = 0;\n let hi = n - 1;\n while (lo < hi - 1) {\n const mid = (lo + hi) >>> 1;\n if (this.cumLen[mid]! <= dist) lo = mid;\n else hi = mid;\n }\n const a = this.samples[lo]!;\n const b = this.samples[lo + 1]!;\n const segStart = this.cumLen[lo]!;\n const segEnd = this.cumLen[lo + 1]!;\n const segLen = segEnd - segStart;\n const u = segLen > 0 ? (dist - segStart) / segLen : 0;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const tLen = Math.hypot(dx, dy) || 1;\n return {\n x: a.x + dx * u,\n y: a.y + dy * u,\n tx: dx / tLen,\n ty: dy / tLen,\n };\n }\n}\n\nfunction clamp01(v: number): number {\n if (v < 0) return 0;\n if (v > 1) return 1;\n return v;\n}\n","import { Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\n\n/**\n * Soft halo around the routed path of a connector. Repaints the path N\n * times with widening stroke and quadratic alpha falloff, producing a\n * glow that hugs whatever curve the path resolves to. Works on every\n * router / pathStyle because geometry is delegated to\n * `host.connector.paintInto`.\n *\n * Static by default. Supply `pulse` to animate brightness sinusoidally —\n * geometry is only repainted on `repaint`; per-frame work touches\n * `this.gfx.alpha` and nothing else, so the pulse is essentially free.\n */\nexport interface GlowConnectorDecorationStyle {\n readonly color: number;\n /** Outermost glow extent in px (widest stroke). Default `12`. */\n readonly radius?: number;\n /** Number of feather layers (more = smoother + more expensive). Default `6`. */\n readonly layers?: number;\n /** Innermost (brightest) layer alpha. Default `0.55`. */\n readonly innerAlpha?: number;\n /**\n * Optional brightness pulse. When omitted, the glow is static. When set,\n * the decoration alpha-multiplies between `1` and `1 - amplitude` on a\n * sinusoidal cycle of `periodMs` milliseconds.\n */\n readonly pulse?: {\n /** Cycle length in ms. Default `1200`. */\n readonly periodMs?: number;\n /** How far below full brightness the dim phase reaches, `[0, 1]`. Default `0.5`. */\n readonly amplitude?: number;\n };\n}\n\nexport class GlowConnectorDecoration extends ConnectorDecorationBase<GlowConnectorDecorationStyle> {\n private layerGfx: Graphics[] = [];\n private pulseElapsed = 0;\n\n /**\n * Halo extends `radius` px past each path endpoint (the outermost layer's\n * stroke is centered on the path and `radius` wide). Returning that as\n * end-padding asks the renderer to inset both ends by `radius` — so the\n * halo's outer edge lands at the anchor instead of overshooting.\n */\n getEndPadding(): { source: number; target: number } {\n const radius = this.style.radius ?? 12;\n return { source: radius, target: radius };\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n\n const radius = this.style.radius ?? 12;\n const layers = Math.max(1, this.style.layers ?? 6);\n const innerAlpha = this.style.innerAlpha ?? 0.55;\n const color = this.style.color;\n\n this.syncLayerCount(layers);\n\n // Outermost first (i=0), brightest last (i=layers-1).\n for (let i = 0; i < layers; i++) {\n const t = i / (layers - 1 || 1); // 0 (outer) .. 1 (inner)\n const strokeWidth = radius * (1 - t) + 1; // wide outside, thin inside\n const alpha = innerAlpha * (t * t); // quadratic falloff\n const g = this.layerGfx[i]!;\n g.clear();\n // No `cap` / `join` override — Connector.drawGeometry inherits them\n // from `spec.stroke` when omitted, so the halo matches the host's\n // own end / corner shape (matters at non-marker ends, where a round\n // cap would push the halo past the anchor with no marker to hide it).\n host.connector.paintInto(g, host.connectorSpec, host.path, {\n color,\n alpha,\n strokeWidth,\n // Halo the markers too: outline (don't fill) at this layer's width\n // and alpha. Marker geometry stays at host-stroke size; only the\n // outline thickness grows. The host paints its own filled marker on\n // top, so the visible result is \"filled arrow inside a soft halo\".\n tintMarkers: true,\n markerHalo: true,\n });\n }\n }\n\n tick(deltaMs: number): boolean {\n if (!this.style.pulse) return false;\n this.pulseElapsed += deltaMs;\n const period = this.style.pulse.periodMs ?? 1200;\n const amplitude = this.style.pulse.amplitude ?? 0.5;\n const phase = (this.pulseElapsed / period) * Math.PI * 2;\n this.gfx.alpha = 1 - amplitude * (0.5 - 0.5 * Math.sin(phase));\n return true;\n }\n\n private syncLayerCount(n: number): void {\n while (this.layerGfx.length < n) {\n const g = new Graphics();\n this.gfx.addChild(g);\n this.layerGfx.push(g);\n }\n while (this.layerGfx.length > n) {\n this.layerGfx.pop()!.destroy();\n }\n }\n}\n","import { Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\n\n/**\n * Connector analogue of `PulseRingDecoration`. Each frame, every ring\n * strokes the host's body + markers at a width that grows outward over\n * one period and fades as it grows — so the wave inherits the connector's\n * silhouette (line shape, bends, arrowhead) instead of being a circular\n * pulse at a single point. Multiple concurrent rings are phase-\n * distributed across one period for a steady rhythm.\n *\n * Geometry is delegated to `connector.paintInto` with a widening\n * `strokeWidth` and `tintMarkers + markerHalo` (so the markers outline at\n * the ring's width, not scale up). The host's normal paint sits on top\n * (zIndex = 0; this decoration's slot z is typically < 0 for \"behind\"\n * rings, ≥ 0 for \"above\" rings — pick a slot name accordingly).\n */\nexport interface RippleConnectorDecorationStyle {\n readonly color: number;\n /**\n * Peak halo extent in px (half-width). Each ring's stroke widens from\n * `0` to `2 × maxRadius` over one period, so the silhouette appears to\n * push outward by up to `maxRadius` on each side. Default `16`.\n */\n readonly maxRadius?: number;\n /** Cycle length in ms. Default `1400`. */\n readonly periodMs?: number;\n /** Number of concurrent rings (phase-distributed). Default `2`. */\n readonly rings?: number;\n /** Initial (full-brightness) alpha at radius 0. Default `0.7`. */\n readonly innerAlpha?: number;\n}\n\nexport class RippleConnectorDecoration extends ConnectorDecorationBase<RippleConnectorDecorationStyle> {\n private ringGfx: Graphics[] = [];\n private elapsed = 0;\n\n /**\n * The peak wave extends `maxRadius` px past each path endpoint (the\n * widest ring's stroke is `2 × maxRadius` centered on the path). Asking\n * the renderer to inset both ends by `maxRadius` makes the peak wave's\n * outer edge land at the anchor — the body / markers sit back from the\n * anchor by `maxRadius` so they're enveloped as each wave grows.\n */\n getEndPadding(): { source: number; target: number } {\n const r = this.style.maxRadius ?? 16;\n return { source: r, target: r };\n }\n\n protected repaint(): void {\n const rings = Math.max(1, this.style.rings ?? 2);\n this.syncRingCount(rings);\n }\n\n tick(deltaMs: number): boolean {\n const host = this.host;\n if (!host) return true;\n\n this.elapsed += deltaMs;\n const period = this.style.periodMs ?? 1400;\n const maxRadius = this.style.maxRadius ?? 16;\n const rings = Math.max(1, this.style.rings ?? 2);\n const innerAlpha = this.style.innerAlpha ?? 0.7;\n const color = this.style.color;\n\n // Phase-distribute rings: each ring leads the next by `1/rings` of period.\n for (let i = 0; i < rings; i++) {\n const phase = ((this.elapsed / period) + i / rings) % 1; // [0, 1)\n const radius = maxRadius * phase; // grows outward\n const alpha = innerAlpha * (1 - phase); // fades as it grows\n const g = this.ringGfx[i]!;\n g.clear();\n if (radius <= 0 || alpha <= 0) continue;\n // Stroke the body at width = 2*radius (so it extends `radius` past\n // the line centerline on each side). The marker outlines at the same\n // width via `markerHalo`, so the whole silhouette pulses outward in\n // shape — line, bends, arrowhead alike.\n // No `cap` / `join` override here — Connector.drawGeometry falls back\n // to `spec.stroke.cap` / `join` when the style omits them, so the\n // ripple inherits whatever end / corner shape the host line uses.\n host.connector.paintInto(g, host.connectorSpec, host.path, {\n color,\n alpha,\n strokeWidth: 2 * radius,\n tintMarkers: true,\n markerHalo: true,\n });\n }\n return true;\n }\n\n private syncRingCount(n: number): void {\n while (this.ringGfx.length < n) {\n const g = new Graphics();\n this.gfx.addChild(g);\n this.ringGfx.push(g);\n }\n while (this.ringGfx.length > n) {\n this.ringGfx.pop()!.destroy();\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","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","import { Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\nimport { samplePath } from '../../connectors/pathSampling';\nimport { Tween } from '../../animation/Tween';\nimport {\n easeInOutCubic,\n easeInOutSine,\n easeOutCubic,\n linear,\n type Easing,\n} from '../../animation/easings';\nimport type { Path, Point } from '../../types';\n\n/** Named easings accepted by the reveal style payload. */\nexport type RevealEasingName = 'linear' | 'easeOutCubic' | 'easeInOutCubic' | 'easeInOutSine';\n\n/**\n * Direction the reveal grows along the connector path.\n *\n * - `'source-to-target'` — segment grows from the source endpoint toward the\n * target endpoint.\n * - `'target-to-source'` — segment grows from the target endpoint toward the\n * source endpoint.\n */\nexport type RevealDirection = 'source-to-target' | 'target-to-source';\n\n/**\n * How the underlying host connector should be treated during reveal.\n *\n * - `'hide'` — the host's gfx is set invisible while the decoration is\n * active; the decoration owns the only visible line. On one-shot\n * completion (with `holdAtFull`) the host is restored to visible and the\n * decoration clears its own gfx, so markers + native stroke take over.\n * - `'overlay'` — the host stays visible; the decoration paints a brighter\n * \"progress\" segment on top. Best for laser-sweep / data-flow visuals on\n * infinite loops.\n */\nexport type RevealHostStroke = 'hide' | 'overlay';\n\n/**\n * Repeat semantics for the reveal animation.\n *\n * - `false` — one-shot. Reveal runs once, then either settles fully drawn\n * (`holdAtFull: true`) or clears.\n * - `true` — infinite loop. Reveal restarts from 0 each cycle.\n * - `number` — finite cycle count (must be `>= 1`).\n */\nexport type RevealRepeat = boolean | number;\n\n/**\n * Connector decoration that progressively reveals the routed path from one\n * endpoint to the other — as if the line were being drawn in real time.\n * Useful as an entrance animation for new edges, a directional \"data-flow\"\n * pulse, or a laser-sweep effect for active routes.\n *\n * Implementation: the host `Path` is densified into a polyline on mount\n * (via `samplePath`); per-frame the decoration computes a cumulative-arc-\n * length cutoff from the driving `Tween` and emits a `lineTo` walk plus a\n * single `stroke()` for the revealed segment. Curves stay smooth because\n * the polyline already uses the engine-wide sampling step counts.\n *\n * Markers are intentionally not painted by this decoration. When\n * `hostStroke: 'hide'` and the animation completes with `holdAtFull: true`,\n * the host connector's gfx is re-shown so its native stroke + markers\n * take over the final display. For infinite loops the host stays hidden\n * for the lifetime of the decoration.\n */\nexport interface RevealConnectorDecorationStyle {\n /** Duration of one full source→target sweep in ms. Default `2000`. */\n readonly durationMs?: number;\n /** `false` = one-shot (default), `true` = infinite, or a positive integer cycle count. */\n readonly repeat?: RevealRepeat;\n /** Easing curve. Default `'linear'` — constant \"pen speed\" feels most natural for a drawing reveal. */\n readonly easing?: RevealEasingName;\n /** Sweep direction. Default `'source-to-target'`. */\n readonly direction?: RevealDirection;\n /** Treatment of the underlying host connector stroke. Default `'hide'`. */\n readonly hostStroke?: RevealHostStroke;\n /**\n * When `repeat` is `false`, hold the fully-drawn state after the cycle\n * completes (handing off to the host stroke when `hostStroke: 'hide'`).\n * Ignored for infinite / finite-repeat modes. Default `true`.\n */\n readonly holdAtFull?: boolean;\n /** Wait this many ms after mount before starting the reveal. Default `0`. */\n readonly delayMs?: number;\n}\n\nexport class RevealConnectorDecoration extends ConnectorDecorationBase<RevealConnectorDecorationStyle> {\n private revealGfx = new Graphics();\n private tween: Tween | null = null;\n private remainingDelayMs: number;\n private finished = false;\n private hostHiddenByUs = false;\n\n /** Densified polyline of the host path, oriented per `direction`. */\n private samples: Point[] = [];\n /** Cumulative arc length at each sample. */\n private cumLen: number[] = [];\n /** Total arc length. */\n private totalLen = 0;\n\n constructor(style: RevealConnectorDecorationStyle) {\n super(style);\n this.remainingDelayMs = Math.max(0, style.delayMs ?? 0);\n }\n\n protected repaint(): void {\n if (this.revealGfx.parent !== this.gfx) {\n this.gfx.addChild(this.revealGfx);\n }\n\n const host = this.host;\n if (!host) {\n this.revealGfx.clear();\n this.samples = [];\n this.cumLen = [];\n this.totalLen = 0;\n return;\n }\n\n this.rebuildArcTable(host.path, this.style.direction ?? 'source-to-target');\n\n // Lazily create the tween on the first repaint (mount). Subsequent\n // `update(host)` calls (e.g. routing change while node drags) keep the\n // tween — we only rebuild the geometry tables so progress maps onto\n // the new path proportionally.\n if (!this.tween) {\n this.tween = new Tween({\n from: 0,\n to: 1,\n duration: Math.max(1, this.style.durationMs ?? 2000),\n easing: resolveEasing(this.style.easing),\n repeat: resolveRepeat(this.style.repeat),\n });\n }\n\n // Re-apply on every repaint: the renderer calls `connector.draw(...)` in\n // `recomputeConnectorPath` (triggered by mount + by routing changes) which\n // re-strokes the body and re-paints the markers. Hide only the body line\n // and the *ending* marker (the one the reveal is sweeping toward). The\n // *starting* marker stays visible because the line begins from it.\n if ((this.style.hostStroke ?? 'hide') === 'hide' && !this.finished) {\n host.connector.setBodyVisible(false);\n this.applyEndingMarkerVisibility(this.tween.value);\n this.hostHiddenByUs = true;\n }\n\n // Paint the current frame's slice immediately so we don't show an empty\n // surface for one frame between mount and first tick.\n this.paintAt(this.tween.value);\n }\n\n /**\n * Show / hide the \"ending\" marker (the endpoint the reveal sweeps toward)\n * based on whether the line has reached it. The \"starting\" marker stays\n * visible at all times because the reveal originates from its endpoint.\n */\n private applyEndingMarkerVisibility(progress: number): void {\n if (!this.host) return;\n if ((this.style.hostStroke ?? 'hide') !== 'hide') return;\n // Pop the ending marker in slightly before the line fully reaches the\n // endpoint so it feels in-sync rather than late. `0.985` ≈ last 1.5%\n // of the path — visually indistinguishable from \"at the end\" but\n // hides the one-frame gap between line completion and tween retire.\n const reached = progress >= 0.985;\n const direction = this.style.direction ?? 'source-to-target';\n if (direction === 'source-to-target') {\n this.host.connector.setTargetMarkerVisible(reached);\n } else {\n this.host.connector.setSourceMarkerVisible(reached);\n }\n }\n\n tick(deltaMs: number): boolean {\n if (this.finished) return false;\n if (this.remainingDelayMs > 0) {\n this.remainingDelayMs -= deltaMs;\n // Hold at 0% while delayed; nothing visible yet.\n this.paintAt(0);\n return true;\n }\n const tween = this.tween;\n const host = this.host;\n if (!tween || !host) return true;\n\n const stillAnimating = tween.tick(deltaMs);\n this.paintAt(tween.value);\n this.applyEndingMarkerVisibility(tween.value);\n\n if (stillAnimating) return true;\n\n // Cycle complete and tween retired (one-shot / N-cycles exhausted).\n const repeat = resolveRepeat(this.style.repeat);\n const isOneShotLike = repeat !== 'forever';\n if (isOneShotLike) {\n const holdAtFull = this.style.holdAtFull ?? true;\n if (holdAtFull) {\n // Hand off to the host stroke + markers if we were hiding it.\n this.restoreHostVisibility();\n this.revealGfx.clear();\n } else {\n this.revealGfx.clear();\n // Leave host as-is: for `hostStroke: 'hide'` the connector stays\n // invisible because the developer asked for `!holdAtFull`. They\n // can clear by removing the decoration explicitly.\n }\n this.finished = true;\n return false;\n }\n return true;\n }\n\n destroy(): void {\n this.restoreHostVisibility();\n super.destroy();\n }\n\n private restoreHostVisibility(): void {\n if (this.hostHiddenByUs && this.host) {\n this.host.connector.setBodyVisible(true);\n this.host.connector.setSourceMarkerVisible(true);\n this.host.connector.setTargetMarkerVisible(true);\n }\n this.hostHiddenByUs = false;\n }\n\n private rebuildArcTable(path: Path, direction: RevealDirection): void {\n let samples = samplePath(path);\n if (direction === 'target-to-source') {\n samples = samples.slice().reverse();\n }\n this.samples = samples;\n const cum: number[] = new Array(samples.length);\n let total = 0;\n if (samples.length > 0) {\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 this.cumLen = cum;\n this.totalLen = total;\n }\n\n /**\n * Paint the polyline from `samples[0]` up to arc-length `progress × totalLen`.\n * Interpolates within the last partial segment so the head doesn't snap\n * between sample indices.\n */\n private paintAt(progress: number): void {\n const g = this.revealGfx;\n g.clear();\n const host = this.host;\n if (!host) return;\n const n = this.samples.length;\n if (n < 2 || this.totalLen <= 0) return;\n\n const cutoff = clamp01(progress) * this.totalLen;\n if (cutoff <= 0) return;\n\n const first = this.samples[0]!;\n g.moveTo(first.x, first.y);\n\n if (cutoff >= this.totalLen) {\n // Full path — straight walk through every sample.\n for (let i = 1; i < n; i++) {\n const p = this.samples[i]!;\n g.lineTo(p.x, p.y);\n }\n } else {\n // Walk until the cumulative length crosses the cutoff, then emit\n // a final interpolated point so the head lands exactly on cutoff.\n for (let i = 1; i < n; i++) {\n const len = this.cumLen[i]!;\n if (len < cutoff) {\n const p = this.samples[i]!;\n g.lineTo(p.x, p.y);\n continue;\n }\n const prevLen = this.cumLen[i - 1]!;\n const segLen = len - prevLen;\n const u = segLen > 0 ? (cutoff - prevLen) / segLen : 0;\n const a = this.samples[i - 1]!;\n const b = this.samples[i]!;\n g.lineTo(a.x + (b.x - a.x) * u, a.y + (b.y - a.y) * u);\n break;\n }\n }\n\n // Inherit stroke style from the host connector's spec verbatim — the\n // reveal is a progressive draw of the *same* line the host would paint,\n // not a separate decorative overlay.\n const s = host.connectorSpec.stroke;\n g.stroke({\n color: s?.color ?? 0x000000,\n alpha: s?.alpha ?? 1,\n width: s?.width ?? 1,\n cap: s?.cap,\n join: s?.join,\n });\n }\n}\n\nfunction resolveEasing(name: RevealEasingName | undefined): Easing {\n switch (name) {\n case 'easeOutCubic':\n return easeOutCubic;\n case 'easeInOutCubic':\n return easeInOutCubic;\n case 'easeInOutSine':\n return easeInOutSine;\n case 'linear':\n default:\n return linear;\n }\n}\n\nfunction resolveRepeat(repeat: RevealRepeat | undefined): number | 'forever' {\n if (repeat === true) return 'forever';\n if (typeof repeat === 'number' && repeat >= 1) {\n // `Tween.repeat` is the count of *additional* cycles after the first,\n // so subtract one for parity with \"N cycles total\".\n return Math.max(0, Math.floor(repeat) - 1);\n }\n return 0;\n}\n\nfunction clamp01(v: number): number {\n if (v < 0) return 0;\n if (v > 1) return 1;\n return v;\n}\n","import { Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\n\n/**\n * Static halo-style ring painted underneath a connector's path — a single\n * thick stroke tracing the host's routed geometry, behind the host stroke.\n *\n * Connectors are 1-D (no `inset`), so a true detached parallel-offset ring\n * would need separately routed geometry. This decoration takes the simpler\n * \"single wider stroke\" route: paint one band of `width` px behind the\n * host, optionally dashed, with `markerHalo` so the host's end markers\n * land inside the same band. Composes with `width` < host stroke for a\n * subtle outline or `width` > host stroke for a \"highlighted edge\" feel.\n *\n * For a thicker / softer feathered halo, use `GlowConnectorDecoration`\n * instead — it stacks multiple layers with alpha falloff.\n */\nexport interface RingConnectorDecorationStyle {\n readonly color: number;\n /** Halo band thickness in px. Default `6`. */\n readonly width?: number;\n /** Halo alpha, `[0, 1]`. Default `0.6`. */\n readonly alpha?: number;\n /** Dashed band — `[dashLength, gapLength]` in px. Default solid. */\n readonly dashArray?: readonly [number, number];\n}\n\nexport class RingConnectorDecoration extends ConnectorDecorationBase<RingConnectorDecorationStyle> {\n private readonly band = new Graphics();\n\n constructor(style: RingConnectorDecorationStyle) {\n super(style);\n this.gfx.addChild(this.band);\n }\n\n /**\n * The band extends `width / 2` past each path endpoint (a centered stroke\n * widens equally on both sides). Asking the renderer to inset both ends\n * by that amount keeps the halo's outer edge sitting at the anchor\n * instead of poking past it.\n */\n getEndPadding(): { source: number; target: number } {\n const half = (this.style.width ?? 6) / 2;\n return { source: half, target: half };\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n\n const width = this.style.width ?? 6;\n const alpha = this.style.alpha ?? 0.6;\n const color = this.style.color;\n const dashArray = this.style.dashArray;\n\n this.band.clear();\n host.connector.paintInto(this.band, host.connectorSpec, host.path, {\n color,\n alpha,\n strokeWidth: width,\n tintMarkers: true,\n markerHalo: true,\n ...(dashArray ? { dashArray } : {}),\n });\n }\n}\n","/**\n * Rounded-rect \"pill\" background drawn behind a label's text. Shared between\n * shape- and connector-anchored label decorations.\n *\n * The pill is a single `Graphics` cleared and re-drawn on each repaint —\n * cheap (one rect path), and avoids per-frame allocation when style changes.\n */\n\nimport { Graphics, Filter, type ColorMatrixFilter } from 'pixi.js';\nimport type { LabelBackground } from '../types';\n\nexport interface BackgroundDrawArgs {\n /** Inner content width in pixels (text bounds). */\n readonly width: number;\n /** Inner content height in pixels. */\n readonly height: number;\n}\n\n/** Resolved padding `[top, right, bottom, left]` from any of the shorthand forms. */\nexport function resolvePadding(\n pad: LabelBackground['padding'] | undefined,\n): readonly [number, number, number, number] {\n if (pad === undefined) return [4, 6, 4, 6];\n if (typeof pad === 'number') return [pad, pad, pad, pad];\n if (pad.length === 2) return [pad[0], pad[1], pad[0], pad[1]];\n return [pad[0], pad[1], pad[2], pad[3]];\n}\n\n/** Resolved radius `[tl, tr, br, bl]` from a number or the per-corner tuple. */\nexport function resolveRadius(\n r: LabelBackground['radius'] | undefined,\n): readonly [number, number, number, number] {\n if (r === undefined) return [4, 4, 4, 4];\n if (typeof r === 'number') return [r, r, r, r];\n return r;\n}\n\n/**\n * Draw the pill into `g`. `width` / `height` are the *content* dimensions —\n * padding is added on top of them so the pill encloses the text.\n *\n * Returns the outer pill size, useful for layout (e.g. positioning the text\n * inside it).\n */\nexport function drawLabelBackground(\n g: Graphics,\n bg: LabelBackground,\n args: BackgroundDrawArgs,\n): { width: number; height: number; padding: readonly [number, number, number, number] } {\n g.clear();\n const padding = resolvePadding(bg.padding);\n const [pt, pr, pb, pl] = padding;\n const outerW = args.width + pl + pr;\n const outerH = args.height + pt + pb;\n const radius = resolveRadius(bg.radius);\n\n // Pixi v8 has no per-corner radius shorthand on Graphics — emit a manual\n // rounded path so per-corner radii are honoured. When all four corners\n // share a radius, fall back to the built-in `roundRect` for simplicity.\n if (allEqual(radius)) {\n g.roundRect(-pl, -pt, outerW, outerH, radius[0]);\n } else {\n traceRoundedRect(g, -pl, -pt, outerW, outerH, radius);\n }\n\n if (bg.fill !== undefined) {\n g.fill({ color: bg.fill, alpha: bg.fillAlpha ?? 1 });\n }\n if (bg.stroke !== undefined) {\n g.stroke({\n color: bg.stroke,\n alpha: bg.strokeAlpha ?? 1,\n width: bg.strokeWidth ?? 1,\n });\n }\n\n // Pixi v8 filter-based shadow is heavy. For v0 we draw a cheap soft-shadow\n // approximation: a second pass of the same rect, offset, lower-alpha, no\n // stroke. Good enough for label pills; switch to a filter later if needed.\n if (bg.shadow) {\n const offX = bg.shadow.offsetX ?? 1;\n const offY = bg.shadow.offsetY ?? 2;\n const alpha = bg.shadow.alpha ?? 0.25;\n // We rendered the foreground pill first; for shadow we need it behind.\n // So we wipe and re-issue, shadow first then foreground.\n g.clear();\n if (allEqual(radius)) {\n g.roundRect(-pl + offX, -pt + offY, outerW, outerH, radius[0]);\n } else {\n traceRoundedRect(g, -pl + offX, -pt + offY, outerW, outerH, radius);\n }\n g.fill({ color: bg.shadow.color, alpha });\n // Foreground pass.\n if (allEqual(radius)) {\n g.roundRect(-pl, -pt, outerW, outerH, radius[0]);\n } else {\n traceRoundedRect(g, -pl, -pt, outerW, outerH, radius);\n }\n if (bg.fill !== undefined) g.fill({ color: bg.fill, alpha: bg.fillAlpha ?? 1 });\n if (bg.stroke !== undefined) {\n g.stroke({\n color: bg.stroke,\n alpha: bg.strokeAlpha ?? 1,\n width: bg.strokeWidth ?? 1,\n });\n }\n }\n\n return { width: outerW, height: outerH, padding };\n}\n\nfunction allEqual(r: readonly [number, number, number, number]): boolean {\n return r[0] === r[1] && r[1] === r[2] && r[2] === r[3];\n}\n\n/**\n * Trace a rounded rect with per-corner radii using arcTo. Order: top-left,\n * top-right, bottom-right, bottom-left. Each corner radius is clamped to\n * half of the shorter side so opposite corners don't overlap on tiny pills.\n */\nfunction traceRoundedRect(\n g: Graphics,\n x: number,\n y: number,\n w: number,\n h: number,\n r: readonly [number, number, number, number],\n): void {\n const maxR = Math.min(w, h) / 2;\n const tl = Math.min(r[0], maxR);\n const tr = Math.min(r[1], maxR);\n const br = Math.min(r[2], maxR);\n const bl = Math.min(r[3], maxR);\n\n g.moveTo(x + tl, y);\n g.lineTo(x + w - tr, y);\n g.arcTo(x + w, y, x + w, y + tr, tr);\n g.lineTo(x + w, y + h - br);\n g.arcTo(x + w, y + h, x + w - br, y + h, br);\n g.lineTo(x + bl, y + h);\n g.arcTo(x, y + h, x, y + h - bl, bl);\n g.lineTo(x, y + tl);\n g.arcTo(x, y, x + tl, y, tl);\n g.closePath();\n}\n\n// Pixi types referenced for compatibility; not used in the cheap-shadow path.\n// Kept here so future filter-based shadows have a clear import surface.\nexport type _FilterTypes = Filter | ColorMatrixFilter;\n","/**\n * Shape-anchored `LabelDecoration` — positions a text (or HTML text) block\n * relative to the host shape's bounding box, with optional background pill\n * and per-zoom LOD.\n *\n * Placement covers the 13 standard slots: `center` (inside the silhouette),\n * 8 outside sides (`top` / `top-right` / `right` / ... / `top-left`), and 4\n * inside corners (`inside-top-left` / ...). For `center` this decoration\n * subsumes the legacy `kind: 'text'` fill layer.\n *\n * Performance: text and background are mutated in place on update; no\n * allocation per frame. LOD removes the decoration's gfx from the scene\n * (not just `visible = false`) when outside the zoom band so Pixi skips the\n * transform pass entirely.\n */\n\nimport { Container, Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\nimport {\n applyLabelResolution,\n fitInsideBox,\n mountLabelContent,\n updateLabelContent,\n type LabelContentView,\n} from '../../paint/labelContent';\nimport { drawLabelBackground } from '../../paint/labelBackground';\nimport type { Rect, ShapeLabelPlacement, ShapeLabelStyle } from '../../types';\n\n/** Default inset for inside-corner placements as a fraction of min(w, h). */\nconst INSIDE_CORNER_INSET_RATIO = 0.15;\n\nexport class LabelDecoration extends ShapeDecorationBase<ShapeLabelStyle> {\n private contentView: LabelContentView | null = null;\n private contentLayer: Container | null = null;\n private bgGfx: Graphics | null = null;\n /** Whether `gfx` is currently parented to host surface (false when LOD-hidden). */\n private attached = true;\n /** Cached host surface for re-attach on LOD show. */\n private hostSurface: Container | null = null;\n /**\n * Cached rasterisation resolution applied to the inner text. Survives\n * `repaint()` so a renderer-level zoom-LOD push isn't lost when style\n * changes trigger a fresh `updateLabelContent`.\n */\n private resolution: number | null = null;\n\n /**\n * Pixi rasterises `Text` to a glyph texture once and re-uses it across\n * frames. The default resolution is the renderer's DPR, so when the\n * camera zooms in the texture is sampled up and labels get fuzzy.\n * Bumping `resolution` re-rasterises at higher fidelity. Idempotent\n * with the same value (Pixi short-circuits internally).\n */\n setResolution(resolution: number): void {\n this.resolution = resolution;\n if (this.contentView) applyLabelResolution(this.contentView, resolution);\n }\n\n /**\n * Last-applied rasterisation resolution, or `null` if `setResolution`\n * has never been called. The renderer's viewport sweep uses this to\n * skip labels already at the target so a converged scene costs nothing\n * past one bounds check per label per frame.\n */\n getResolution(): number | null {\n return this.resolution;\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n this.hostSurface = host.surface;\n\n // Build inner layout: optional background pill + text content.\n if (!this.contentLayer) {\n this.contentLayer = new Container();\n this.contentLayer.label = 'label:content';\n this.gfx.addChild(this.contentLayer);\n }\n if (this.style.background && !this.bgGfx) {\n this.bgGfx = new Graphics();\n this.bgGfx.label = 'label:bg';\n // Background sits behind text inside the content layer.\n this.contentLayer.addChildAt(this.bgGfx, 0);\n } else if (!this.style.background && this.bgGfx) {\n this.bgGfx.destroy();\n this.bgGfx = null;\n }\n\n if (!this.contentView) {\n this.contentView = mountLabelContent(this.style.content, this.style.wrap);\n this.contentLayer.addChild(this.contentView.display);\n } else {\n const next = updateLabelContent(this.contentView, this.style.content, this.style.wrap);\n if (next !== this.contentView) {\n this.contentLayer.addChild(next.display);\n this.contentView = next;\n }\n }\n // Re-apply the renderer-pushed rasterisation resolution. `mountLabelContent`\n // / kind-switch in `updateLabelContent` creates a fresh Pixi `Text` whose\n // resolution defaults back to renderer DPR; without this re-apply the\n // label would silently revert to base sharpness on the next style change.\n if (this.resolution !== null) applyLabelResolution(this.contentView, this.resolution);\n\n // For `inside-*` placements, the label carries a containment contract —\n // it must fit inside the host shape's inner box. Run the shrink → truncate\n // → hide cascade against the placement-specific inner-box budget before\n // measuring. Outside placements and `'center'` skip this and size freely.\n const placement = this.style.placement ?? 'bottom';\n let hidden = false;\n if (isInsidePlacement(placement)) {\n const box = innerBoxFor(placement, host.bounds);\n const minFontSize = this.style.minFontSize ?? 9;\n const result = fitInsideBox(this.contentView, this.style.content, this.style.wrap, box, minFontSize);\n hidden = result.hidden;\n }\n\n // Measure text after style update; Pixi computes width/height on access.\n const textW = this.contentView.display.width;\n const textH = this.contentView.display.height;\n\n // Lay out content + background. Origin (0, 0) of contentLayer is the\n // label's geometric center; text is offset so its centroid sits there.\n let outerW = textW;\n let outerH = textH;\n if (this.style.background && this.bgGfx) {\n const result = drawLabelBackground(this.bgGfx, this.style.background, {\n width: textW,\n height: textH,\n });\n outerW = result.width;\n outerH = result.height;\n // Background was traced from (-padL, -padT); shift it so its centroid\n // lines up with the label's centroid.\n this.bgGfx.position.set(-textW / 2, -textH / 2);\n }\n // Center text inside the content layer (and background).\n this.contentView.display.position.set(-textW / 2, -textH / 2);\n\n // Compute the host-bounds-relative anchor for this placement. For the\n // `'center'` and `'inside-center'` placements, prefer the shape's\n // `visualCenter()` over the AABB midpoint when the shape provides it —\n // non-rectangular silhouettes (arc / polygon / star / ...) have AABB\n // centres that can sit outside their actual interior, which would\n // visibly mis-place a centred label.\n const offsetX = this.style.offset?.x ?? 0;\n const offsetY = this.style.offset?.y ?? 0;\n const visualCenter =\n (placement === 'center' || placement === 'inside-center') && host.shape.visualCenter\n ? host.shape.visualCenter()\n : undefined;\n // For outside placements (top / bottom / left / right / corners), inflate\n // the anchor rect by the host's `outerDecorationExtent` so the label\n // sits past the outermost ring / halo on the host instead of overlapping\n // it. Inside placements and the centred placements operate against the\n // raw silhouette bounds — pushing them outward would walk the label off\n // the shape it's meant to sit inside.\n const anchorBounds =\n host.outerDecorationExtent > 0 && isOutsidePlacement(placement)\n ? inflateRect(host.bounds, host.outerDecorationExtent)\n : host.bounds;\n const { ax, ay, alignDx, alignDy } = anchorAndAlign(\n anchorBounds,\n placement,\n outerW,\n outerH,\n visualCenter,\n );\n\n this.gfx.position.set(ax + alignDx + offsetX, ay + alignDy + offsetY);\n this.gfx.rotation = this.style.rotation ?? 0;\n // Fit cascade may have produced a \"hide\" result for inside-* placements\n // that couldn't fit even after shrink + truncate; clamp alpha to 0 in\n // that case. Otherwise honour the style's configured alpha.\n this.gfx.alpha = hidden ? 0 : (this.style.alpha ?? 1);\n this.gfx.cursor = this.style.cursor ?? 'default';\n this.gfx.eventMode = this.style.interactive ? 'static' : 'none';\n }\n\n /**\n * Per-frame check for LOD — when the camera-zoom (effective world scale)\n * leaves the `visibility` range, detach `gfx` from the surface so Pixi\n * skips it entirely. Re-attach when zoom re-enters the range.\n *\n * Without `visibility` set this hook is a no-op and the renderer never\n * registers it as animated (we return `false`).\n */\n tick(_deltaMs: number): boolean {\n const v = this.style.visibility;\n if (!v || (v.minZoom === undefined && v.maxZoom === undefined)) return false;\n const z = effectiveScale(this.gfx);\n const shouldShow =\n (v.minZoom === undefined || z >= v.minZoom) &&\n (v.maxZoom === undefined || z <= v.maxZoom);\n if (shouldShow && !this.attached && this.hostSurface) {\n this.hostSurface.addChild(this.gfx);\n this.attached = true;\n } else if (!shouldShow && this.attached) {\n this.gfx.parent?.removeChild(this.gfx);\n this.attached = false;\n }\n return true;\n }\n}\n\n// ─── Placement math ────────────────────────────────────────────────────────\n\n/**\n * Resolve the anchor point on / inside the host bounds for `placement`, and\n * the alignment delta that shifts the label's centroid relative to that\n * anchor so the label \"hugs\" the host correctly.\n *\n * Convention: the label's gfx origin is at the label's centroid. For outside\n * placements (`bottom`, `top-right`, ...) we shift the centroid past the\n * anchor by half the label's outer extent so the label sits next to the\n * shape, not on top of it. For inside placements (`center`,\n * `inside-top-left`, ...) we don't shift (the centroid stays on the anchor).\n */\nfunction anchorAndAlign(\n bounds: Rect,\n placement: ShapeLabelPlacement,\n outerW: number,\n outerH: number,\n visualCenter: { x: number; y: number } | undefined,\n): { ax: number; ay: number; alignDx: number; alignDy: number } {\n const cx = visualCenter ? visualCenter.x : bounds.x + bounds.width / 2;\n const cy = visualCenter ? visualCenter.y : bounds.y + bounds.height / 2;\n const left = bounds.x;\n const right = bounds.x + bounds.width;\n const top = bounds.y;\n const bottom = bounds.y + bounds.height;\n const inside = Math.min(bounds.width, bounds.height) * INSIDE_CORNER_INSET_RATIO;\n\n switch (placement) {\n case 'center':\n return { ax: cx, ay: cy, alignDx: 0, alignDy: 0 };\n\n case 'top':\n return { ax: cx, ay: top, alignDx: 0, alignDy: -outerH / 2 };\n case 'bottom':\n return { ax: cx, ay: bottom, alignDx: 0, alignDy: outerH / 2 };\n case 'left':\n return { ax: left, ay: cy, alignDx: -outerW / 2, alignDy: 0 };\n case 'right':\n return { ax: right, ay: cy, alignDx: outerW / 2, alignDy: 0 };\n\n case 'top-left':\n return { ax: left, ay: top, alignDx: -outerW / 2, alignDy: -outerH / 2 };\n case 'top-right':\n return { ax: right, ay: top, alignDx: outerW / 2, alignDy: -outerH / 2 };\n case 'bottom-left':\n return { ax: left, ay: bottom, alignDx: -outerW / 2, alignDy: outerH / 2 };\n case 'bottom-right':\n return { ax: right, ay: bottom, alignDx: outerW / 2, alignDy: outerH / 2 };\n\n case 'inside-top-left':\n return { ax: left + inside, ay: top + inside, alignDx: outerW / 2, alignDy: outerH / 2 };\n case 'inside-top-right':\n return { ax: right - inside, ay: top + inside, alignDx: -outerW / 2, alignDy: outerH / 2 };\n case 'inside-bottom-left':\n return { ax: left + inside, ay: bottom - inside, alignDx: outerW / 2, alignDy: -outerH / 2 };\n case 'inside-bottom-right':\n return { ax: right - inside, ay: bottom - inside, alignDx: -outerW / 2, alignDy: -outerH / 2 };\n\n case 'inside-top':\n return { ax: cx, ay: top + inside, alignDx: 0, alignDy: outerH / 2 };\n case 'inside-bottom':\n return { ax: cx, ay: bottom - inside, alignDx: 0, alignDy: -outerH / 2 };\n case 'inside-left':\n return { ax: left + inside, ay: cy, alignDx: outerW / 2, alignDy: 0 };\n case 'inside-right':\n return { ax: right - inside, ay: cy, alignDx: -outerW / 2, alignDy: 0 };\n case 'inside-center':\n return { ax: cx, ay: cy, alignDx: 0, alignDy: 0 };\n }\n}\n\n/**\n * Whether `placement` carries the \"label must stay inside the shape\"\n * containment contract — true for any `inside-*` value, false for the 8\n * outside sides/corners and bare `'center'`. The fit cascade (shrink →\n * truncate → hide) only runs for inside placements.\n */\nexport function isInsidePlacement(placement: ShapeLabelPlacement): boolean {\n return placement.startsWith('inside-');\n}\n\n/**\n * Whether `placement` anchors the label *outside* the host silhouette —\n * one of the 8 cardinal / diagonal slots (`top`, `top-right`, `right`,\n * `bottom-right`, `bottom`, `bottom-left`, `left`, `top-left`).\n *\n * `'center'` is intentionally excluded: the label sits *on* the host's\n * geometric centre, so the host's outer decorations don't push it.\n */\nfunction isOutsidePlacement(placement: ShapeLabelPlacement): boolean {\n return (\n placement === 'top' ||\n placement === 'bottom' ||\n placement === 'left' ||\n placement === 'right' ||\n placement === 'top-left' ||\n placement === 'top-right' ||\n placement === 'bottom-left' ||\n placement === 'bottom-right'\n );\n}\n\n/** Expand `r` by `pad` on every side. */\nfunction inflateRect(r: Rect, pad: number): Rect {\n return {\n x: r.x - pad,\n y: r.y - pad,\n width: r.width + pad * 2,\n height: r.height + pad * 2,\n };\n}\n\n/**\n * Inner-box budget the label is allowed to occupy for an `inside-*` placement,\n * expressed relative to the host shape's AABB. All inside placements share the\n * same uniform inset `INSIDE_CORNER_INSET_RATIO * min(w, h)` so the visual\n * rhythm matches the existing inside-corners. Width/height halves correspond\n * to which axis the placement subdivides:\n *\n * - `inside-center` — full box minus 2× inset on both axes\n * - `inside-top`/`-bottom` — full width, half height\n * - `inside-left`/`-right` — half width, full height\n * - `inside-*-corner` — half width, half height\n */\nexport function innerBoxFor(\n placement: ShapeLabelPlacement,\n bounds: Rect,\n): { width: number; height: number } {\n const inset = Math.min(bounds.width, bounds.height) * INSIDE_CORNER_INSET_RATIO;\n const fullW = Math.max(0, bounds.width - 2 * inset);\n const fullH = Math.max(0, bounds.height - 2 * inset);\n const halfW = Math.max(0, bounds.width / 2 - inset);\n const halfH = Math.max(0, bounds.height / 2 - inset);\n switch (placement) {\n case 'inside-center':\n return { width: fullW, height: fullH };\n case 'inside-top':\n case 'inside-bottom':\n return { width: fullW, height: halfH };\n case 'inside-left':\n case 'inside-right':\n return { width: halfW, height: fullH };\n case 'inside-top-left':\n case 'inside-top-right':\n case 'inside-bottom-left':\n case 'inside-bottom-right':\n return { width: halfW, height: halfH };\n default:\n // Not an inside placement — caller should not invoke; return zero box\n // so any incidental use is harmless.\n return { width: 0, height: 0 };\n }\n}\n\n/**\n * Effective world-space scale of `gfx` — product of `scale.x` walking up\n * parent chain. The camera applies its zoom as a scale on the world layer,\n * so the product reflects current effective zoom for LOD decisions.\n */\nfunction effectiveScale(gfx: Container): number {\n let s = 1;\n let p: Container | null = gfx;\n while (p) {\n s *= p.scale.x;\n p = p.parent;\n }\n return s;\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\nimport type { Rect } from '../../types';\n\n/**\n * Placement of a `ToggleDecoration` relative to the host shape's AABB.\n *\n * - Cardinal sides (`top` / `right` / `bottom` / `left`) sit centred on the\n * midpoint of that side.\n * - Corners (`top-left` / ... / `bottom-right`) sit on the corner itself.\n * - `inside-*` variants mirror the cardinal sides but pull inward by\n * `radius + 4 px` so the toggle nests inside the silhouette (useful for\n * circle groups where an outside toggle would float well past the rim).\n *\n * The toggle's gfx is positioned by its centre, so it half-overlaps the\n * silhouette edge in the outside variants — a touch-friendly hit target\n * that visually reads as \"attached to the host\".\n */\nexport type TogglePlacement =\n | 'top'\n | 'right'\n | 'bottom'\n | 'left'\n | 'top-left'\n | 'top-right'\n | 'bottom-left'\n | 'bottom-right'\n | 'inside-top'\n | 'inside-right'\n | 'inside-bottom'\n | 'inside-left';\n\n/**\n * Visual style of a `ToggleDecoration` — the small `+` / `−` button used to\n * collapse / expand compound groups, and by extension any \"open this\" /\n * \"close this\" affordance a domain layer wants to put on a shape.\n *\n * The decoration is pure-visual: it paints itself, exposes a shape-local\n * hit-geometry (`getLocalHitGeometry`), and emits no events. Domain\n * behaviours (e.g. `CollapseExpandBehaviour` in `@invana/graph`) read the\n * geometry and do the click-distance math against the host's\n * `shape:pointerdown` payload — keeps the decoration domain-free and\n * sidesteps Pixi event-bubbling through the shape gfx.\n */\nexport interface ToggleDecorationStyle {\n /**\n * Which glyph the button shows. Domain layers flip this through\n * `setDecoration` whenever the underlying collapsed-state changes.\n * Default `'plus'`.\n */\n readonly state?: 'plus' | 'minus';\n /** Where on the host AABB the toggle sits. Default `'bottom'`. */\n readonly placement?: TogglePlacement;\n /** Button outer radius, px. Default `10`. */\n readonly radius?: number;\n /** Button fill colour. Default `0xffffff` (white). */\n readonly bgFill?: number;\n /** Button fill alpha. Default `1`. */\n readonly bgAlpha?: number;\n /** Button outline colour. Default `0x6b7fff` (theme blue). */\n readonly strokeColor?: number;\n /** Button outline width, px. Default `1.5`. */\n readonly strokeWidth?: number;\n /** Glyph stroke colour. Default = `strokeColor`. */\n readonly glyphColor?: number;\n /** Glyph stroke width, px. Default `1.5`. */\n readonly glyphWidth?: number;\n /**\n * Extra offset applied after placement resolution, in shape-local px.\n * Use to nudge the toggle off a default placement without writing a\n * custom placement (e.g. push a `bottom-right` toggle further out\n * past a thick stroke).\n */\n readonly offsetX?: number;\n readonly offsetY?: number;\n /**\n * Override the keyword-based `placement` resolution with raw shape-local\n * coordinates. When set, `placement`, `offsetX`, and `offsetY` are all\n * ignored — the toggle's centre is placed at exactly `(x, y)` in the\n * host shape's local frame (centre-relative for centred shapes like\n * `CircleShape`, top-left-relative for `RectShape`).\n *\n * Use when none of the 12 named placements lands where you want it\n * (e.g. floating the toggle along a diagonal, or matching a specific\n * UI mock that doesn't snap to AABB anchors).\n */\n readonly position?: { readonly x: number; readonly y: number };\n}\n\n/**\n * Shape-local hit geometry exposed by a `ToggleDecoration` instance. The\n * `cx` / `cy` coordinates are in the host shape's local frame (i.e. add\n * the host's spec `x` / `y` to convert to world). `radius` is the touch\n * radius — typically a touch larger than the visual radius so the button\n * stays easy to hit on coarse pointers.\n *\n * Domain behaviours read this and check `Math.hypot(worldX − host.x − cx,\n * worldY − host.y − cy) ≤ radius` in their `shape:pointerdown` handler.\n */\nexport interface ToggleHitGeometry {\n readonly cx: number;\n readonly cy: number;\n readonly radius: number;\n}\n\n/**\n * Default touch padding added to the visual radius when reporting the hit\n * geometry. Keeps a 10 px visual button hittable at ~14 px — comfortable on\n * a desktop pointer and just acceptable on touch (which the layout-style\n * apps that use this generally aren't optimised for anyway).\n */\nconst HIT_PADDING_PX = 4;\n\n/**\n * Small circular `+` / `−` button drawn at a configurable anchor on the\n * host shape. Pure visual; emits no events.\n *\n * Geometry: one filled + stroked circle, plus one or two glyph strokes\n * (`+` draws a horizontal and vertical stroke; `−` draws only the\n * horizontal). Repainted on every `update()` so a `setDecoration` that\n * flips `state` from `'plus'` to `'minus'` redraws in place without\n * remounting.\n */\nexport class ToggleDecoration extends ShapeDecorationBase<ToggleDecorationStyle> {\n private readonly button = new Graphics();\n private readonly glyph = new Graphics();\n /**\n * Cached hit geometry, refreshed on every `repaint()`. Stale read between\n * a host bounds change and the next `update()` is acceptable — the\n * renderer always calls `update` after bounds change, and the resulting\n * \"missed by a pixel\" hit just means the user clicked an extra time.\n */\n private hit: ToggleHitGeometry = { cx: 0, cy: 0, radius: 0 };\n\n constructor(style: ToggleDecorationStyle) {\n super(style);\n this.gfx.addChild(this.button);\n this.gfx.addChild(this.glyph);\n }\n\n /**\n * Most-recently-computed shape-local hit geometry. Returns `{0, 0, 0}`\n * before the first `mount` / `update` — callers should still defend\n * against a zero radius as a \"not laid out yet\" signal.\n */\n getLocalHitGeometry(): ToggleHitGeometry {\n return this.hit;\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n\n const radius = this.style.radius ?? 10;\n const placement = this.style.placement ?? 'bottom';\n // Offsets are ignored when `position` overrides the placement — the\n // caller has supplied exact coordinates and shouldn't be surprised by\n // an extra shift.\n const offsetX = this.style.position ? 0 : (this.style.offsetX ?? 0);\n const offsetY = this.style.position ? 0 : (this.style.offsetY ?? 0);\n const bgFill = this.style.bgFill ?? 0xffffff;\n const bgAlpha = this.style.bgAlpha ?? 1;\n const strokeColor = this.style.strokeColor ?? 0x6b7fff;\n const strokeWidth = this.style.strokeWidth ?? 1.5;\n const glyphColor = this.style.glyphColor ?? strokeColor;\n const glyphWidth = this.style.glyphWidth ?? 1.5;\n const state = this.style.state ?? 'plus';\n\n // `position` overrides the keyword-based placement entirely — pure\n // raw shape-local coordinates. Falls back to the AABB anchor resolver\n // when not set.\n const { cx, cy } = this.style.position\n ? { cx: this.style.position.x, cy: this.style.position.y }\n : anchorOnBounds(host.bounds, placement, radius);\n\n this.button.clear();\n this.button.circle(0, 0, radius);\n this.button.fill({ color: bgFill, alpha: bgAlpha });\n if (strokeWidth > 0) {\n this.button.stroke({ color: strokeColor, width: strokeWidth });\n }\n\n this.glyph.clear();\n const armLength = radius * 0.55;\n this.glyph\n .moveTo(-armLength, 0)\n .lineTo(armLength, 0)\n .stroke({ color: glyphColor, width: glyphWidth, cap: 'round' });\n if (state === 'plus') {\n this.glyph\n .moveTo(0, -armLength)\n .lineTo(0, armLength)\n .stroke({ color: glyphColor, width: glyphWidth, cap: 'round' });\n }\n\n this.gfx.position.set(cx + offsetX, cy + offsetY);\n this.hit = { cx: cx + offsetX, cy: cy + offsetY, radius: radius + HIT_PADDING_PX };\n }\n\n /**\n * Outer-extent contribution — outside-placed toggles bulge slightly\n * past the silhouette, but the bulge is small (one radius) and only on\n * one side. Reporting it would push `LabelDecoration` outward on all\n * four sides, which looks worse than letting an outside-bottom label\n * overlap the toggle. Returning `0` keeps the label flow stable; the\n * developer can offset the label manually if both fight for the same\n * slot.\n */\n getOuterExtent(): number {\n return 0;\n }\n}\n\n/**\n * Resolve the shape-local centre of the toggle from the host's AABB and\n * the configured placement. The `radius` budget pulls inward for\n * `inside-*` placements so the entire button nests inside the silhouette.\n *\n * Conventions:\n * - Outside cardinal placements (`top` / `bottom` / `left` / `right`)\n * sit centred on the midpoint of that AABB side.\n * - Corner placements sit on the corner itself (half the button outside,\n * half inside).\n * - Inside cardinals pull the centre inward by `radius + 4 px` so a 10 px\n * button hugs the rim without poking out.\n */\nfunction anchorOnBounds(\n bounds: Rect,\n placement: TogglePlacement,\n radius: number,\n): { cx: number; cy: number } {\n const left = bounds.x;\n const right = bounds.x + bounds.width;\n const top = bounds.y;\n const bottom = bounds.y + bounds.height;\n const midX = bounds.x + bounds.width / 2;\n const midY = bounds.y + bounds.height / 2;\n const insidePad = radius + 4;\n\n switch (placement) {\n case 'top': return { cx: midX, cy: top };\n case 'bottom': return { cx: midX, cy: bottom };\n case 'left': return { cx: left, cy: midY };\n case 'right': return { cx: right, cy: midY };\n case 'top-left': return { cx: left, cy: top };\n case 'top-right': return { cx: right, cy: top };\n case 'bottom-left': return { cx: left, cy: bottom };\n case 'bottom-right':return { cx: right, cy: bottom };\n case 'inside-top': return { cx: midX, cy: top + insidePad };\n case 'inside-bottom': return { cx: midX, cy: bottom - insidePad };\n case 'inside-left': return { cx: left + insidePad, cy: midY };\n case 'inside-right': return { cx: right - insidePad, cy: midY };\n }\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\nimport type { Rect } from '../../types';\n\n/**\n * Where on the host AABB a `ResizeHandleDecoration` sits. The eight cardinal\n * + corner positions cover every rectangular drag axis (horizontal / vertical\n * sides, diagonal corners). For radially-symmetric hosts (circle groups) use\n * any side — domain behaviours typically map all four sides to the same\n * radius-scaling drag.\n */\nexport type ResizeHandlePlacement =\n | 'top'\n | 'right'\n | 'bottom'\n | 'left'\n | 'top-left'\n | 'top-right'\n | 'bottom-left'\n | 'bottom-right';\n\nexport interface ResizeHandleDecorationStyle {\n /** Which AABB position the handle sits on. Default `'bottom-right'`. */\n readonly placement?: ResizeHandlePlacement;\n /** Side length of the square handle, px. Default `8`. */\n readonly size?: number;\n /** Handle fill colour. Default `0xffffff`. */\n readonly bgFill?: number;\n readonly bgAlpha?: number;\n /** Handle outline colour. Default `0x6b7fff`. */\n readonly strokeColor?: number;\n /** Handle outline width. Default `1.5`. */\n readonly strokeWidth?: number;\n /** Optional CSS-style cursor hint for the host renderer's hit pipeline. */\n readonly cursor?: string;\n /** Visible only when truthy. Domain behaviours flip this on hover/select. Default `true`. */\n readonly visible?: boolean;\n /**\n * Override the keyword-based `placement` resolution with raw shape-local\n * coordinates. When set, `placement` is ignored — the handle's centre is\n * placed at exactly `(x, y)` in the host shape's local frame. The\n * reported hit geometry's `placement` field still reflects the\n * configured `placement` (or `'bottom-right'` if omitted) so consumers\n * that switch on it for resize-direction math still work.\n */\n readonly position?: { readonly x: number; readonly y: number };\n}\n\n/**\n * Shape-local hit geometry for a `ResizeHandleDecoration`. Same coordinate\n * convention as the toggle's: add the host shape's spec `x` / `y` to convert\n * to world. The geometry is a square — a behaviour testing a pointer hit\n * compares against the AABB `[cx-half, cx+half] × [cy-half, cy+half]`.\n */\nexport interface ResizeHandleHitGeometry {\n readonly cx: number;\n readonly cy: number;\n /** Half side-length in shape-local px. */\n readonly half: number;\n readonly placement: ResizeHandlePlacement;\n}\n\nconst HIT_PADDING_PX = 3;\n\n/**\n * Small square handle drawn at a configurable anchor on the host shape's\n * AABB. Pure visual; emits no events. `GroupResizeBehaviour` (in\n * `@invana/graph`) reads `getLocalHitGeometry()` and resolves drags itself.\n *\n * Multiple handles per host are expected — register one decoration per\n * corner / side with distinct slot ids (`'resize-tl'`, `'resize-br'`, …)\n * and the renderer will mount each into its own slot.\n */\nexport class ResizeHandleDecoration extends ShapeDecorationBase<ResizeHandleDecorationStyle> {\n private readonly handle = new Graphics();\n private hit: ResizeHandleHitGeometry = { cx: 0, cy: 0, half: 0, placement: 'bottom-right' };\n\n constructor(style: ResizeHandleDecorationStyle) {\n super(style);\n this.gfx.addChild(this.handle);\n }\n\n /** See {@link ToggleDecoration.getLocalHitGeometry}. */\n getLocalHitGeometry(): ResizeHandleHitGeometry {\n return this.hit;\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n\n const placement = this.style.placement ?? 'bottom-right';\n const size = this.style.size ?? 8;\n const bgFill = this.style.bgFill ?? 0xffffff;\n const bgAlpha = this.style.bgAlpha ?? 1;\n const strokeColor = this.style.strokeColor ?? 0x6b7fff;\n const strokeWidth = this.style.strokeWidth ?? 1.5;\n const visible = this.style.visible ?? true;\n\n const { cx, cy } = this.style.position\n ? { cx: this.style.position.x, cy: this.style.position.y }\n : handleCentre(host.bounds, placement);\n const half = size / 2;\n\n this.handle.clear();\n this.handle.rect(-half, -half, size, size);\n this.handle.fill({ color: bgFill, alpha: bgAlpha });\n if (strokeWidth > 0) {\n this.handle.stroke({ color: strokeColor, width: strokeWidth });\n }\n this.handle.cursor = this.style.cursor ?? cursorFor(placement);\n\n this.gfx.position.set(cx, cy);\n this.gfx.visible = visible;\n this.hit = { cx, cy, half: half + HIT_PADDING_PX, placement };\n }\n\n getOuterExtent(): number {\n return 0;\n }\n}\n\nfunction handleCentre(bounds: Rect, placement: ResizeHandlePlacement): { cx: number; cy: number } {\n const left = bounds.x;\n const right = bounds.x + bounds.width;\n const top = bounds.y;\n const bottom = bounds.y + bounds.height;\n const midX = bounds.x + bounds.width / 2;\n const midY = bounds.y + bounds.height / 2;\n\n switch (placement) {\n case 'top': return { cx: midX, cy: top };\n case 'bottom': return { cx: midX, cy: bottom };\n case 'left': return { cx: left, cy: midY };\n case 'right': return { cx: right, cy: midY };\n case 'top-left': return { cx: left, cy: top };\n case 'top-right': return { cx: right, cy: top };\n case 'bottom-left': return { cx: left, cy: bottom };\n case 'bottom-right': return { cx: right, cy: bottom };\n }\n}\n\n/**\n * Default cursor hint per side. Domain layers can override via\n * `style.cursor` — useful when the handle should map to a non-resize gesture\n * (e.g. rotate from a corner). Returned as a CSS cursor string.\n */\nfunction cursorFor(placement: ResizeHandlePlacement): string {\n switch (placement) {\n case 'top':\n case 'bottom': return 'ns-resize';\n case 'left':\n case 'right': return 'ew-resize';\n case 'top-left':\n case 'bottom-right': return 'nwse-resize';\n case 'top-right':\n case 'bottom-left': return 'nesw-resize';\n }\n}\n","import { Graphics } from 'pixi.js';\nimport { ShapeDecorationBase } from '../../base/ShapeDecorationBase';\nimport { emitDashedStroke } from '../../paint/dashedStroke';\nimport type { Point, Rect } from '../../types';\n\n/**\n * One of the eight standard transform-frame anchors: corner (`top-left`,\n * `top-right`, `bottom-left`, `bottom-right`) or edge-midpoint (`top`,\n * `right`, `bottom`, `left`).\n *\n * Re-using `ResizeHandlePlacement`'s vocabulary so any behaviour that\n * already does direction-aware drag math (corner → diagonal resize,\n * `top` / `bottom` → vertical, `left` / `right` → horizontal) keeps\n * working without translation.\n */\nexport type SelectionFramePlacement =\n | 'top'\n | 'right'\n | 'bottom'\n | 'left'\n | 'top-left'\n | 'top-right'\n | 'bottom-left'\n | 'bottom-right';\n\n/**\n * Visual style of a `SelectionFrameDecoration` — the dashed AABB outline\n * plus a configurable subset of round drag handles. One decoration\n * replaces the 4–8 separate `ResizeHandleDecoration` mounts the resize\n * behaviour used to issue, so callers only manage one slot per host.\n *\n * The decoration is pure-visual: it paints itself and exposes per-handle\n * hit geometry via {@link SelectionFrameDecoration.getLocalHandleHits}.\n * Hit-test math lives in the behaviour, matching the `ToggleDecoration`\n * / `ResizeHandleDecoration` contract.\n */\n/**\n * Border line style. `'solid'` paints a continuous outline; `'dashed'` and\n * `'dotted'` paint a regular gap pattern via Pixi's dashed stroke. Both\n * dash variants pick sensible default dash/gap lengths — supply\n * {@link SelectionFrameDecorationStyle.dashArray} to override them\n * verbatim.\n */\nexport type SelectionFrameBorderStyle = 'solid' | 'dashed' | 'dotted';\n\n/**\n * Visual kind of a drag handle. Circles read as \"round nub\"; squares are\n * the classic CAD/Figma look. Both kinds use the same hit geometry (a\n * disk of radius `handleRadius + HIT_PADDING_PX`) so the resize behaviour\n * doesn't need to branch on shape.\n */\nexport type SelectionFrameHandleShape = 'circle' | 'square';\n\nexport interface SelectionFrameDecorationStyle {\n /** Border line colour. Default `0x6b7fff` (theme blue). */\n readonly borderColor?: number;\n /** Border line width, px. Default `1.5`. */\n readonly borderWidth?: number;\n /**\n * `'solid'` | `'dashed'` | `'dotted'`. Default `'dotted'` — reads as a\n * helper / annotation rather than the host's actual outline. When\n * {@link dashArray} is supplied it wins over this preset.\n */\n readonly borderStyle?: SelectionFrameBorderStyle;\n /**\n * Custom dash pattern `[dashLength, gapLength]` in px. Overrides\n * {@link borderStyle} entirely when set — use when the presets don't\n * land where you want them.\n */\n readonly dashArray?: readonly [number, number];\n /** Border alpha. Default `0.6` — ghosts the frame so the host silhouette reads as the real thing. */\n readonly borderAlpha?: number;\n /**\n * Outward inset between the host AABB and the dashed frame. Lets the\n * frame visually \"wrap\" the host without touching the silhouette.\n * Default `4`.\n */\n readonly padding?: number;\n\n // ─── Handles ──────────────────────────────────────────────────────────\n /** `'circle'` (default) paints round nubs; `'square'` paints squares. */\n readonly handleShape?: SelectionFrameHandleShape;\n /**\n * Half-extent of the handle in px. For circle handles this is the\n * outer radius; for square handles it's half the side length, so the\n * visible size matches a circle of the same value. Default `5`.\n */\n readonly handleRadius?: number;\n /**\n * Corner radius for square handles only. Default `1.5` for a subtly\n * rounded look; pass `0` for hard corners. Ignored when\n * `handleShape: 'circle'`.\n */\n readonly handleCornerRadius?: number;\n /** Handle fill colour. Default `0xffffff`. */\n readonly handleFill?: number;\n /** Handle fill alpha. Default `1`. */\n readonly handleFillAlpha?: number;\n /** Handle outline colour. Default = `borderColor`. */\n readonly handleStrokeColor?: number;\n /** Handle outline width in px. Default `1.5`. Pass `0` for no outline. */\n readonly handleStrokeWidth?: number;\n /** Handle outline alpha. Default `1`. */\n readonly handleStrokeAlpha?: number;\n /**\n * Which handles to render. Default = all eight. Pass a smaller array to\n * suppress edge midpoints (`['top-left', 'top-right', 'bottom-left',\n * 'bottom-right']`) or limit to a single axis (`['right']` for the\n * radial circle case).\n */\n readonly handles?: ReadonlyArray<SelectionFramePlacement>;\n /** Visible only when truthy. Default `true`. */\n readonly visible?: boolean;\n}\n\n/** Default touch padding around each handle's visual radius. */\nconst HIT_PADDING_PX = 4;\n\nconst ALL_PLACEMENTS: ReadonlyArray<SelectionFramePlacement> = [\n 'top-left',\n 'top',\n 'top-right',\n 'right',\n 'bottom-right',\n 'bottom',\n 'bottom-left',\n 'left',\n];\n\n/**\n * Per-handle hit geometry returned by {@link SelectionFrameDecoration.getLocalHandleHits}.\n * `cx` / `cy` are in the host shape's local frame (add the host's spec\n * `x` / `y` to convert to world). `radius` is the touch radius (visual\n * radius + a small floor for coarse pointers).\n */\nexport interface SelectionFrameHandleHit {\n readonly placement: SelectionFramePlacement;\n readonly cx: number;\n readonly cy: number;\n readonly radius: number;\n}\n\n/**\n * Selection / transform frame — dashed AABB outline plus round drag\n * handles at the four corners and four edge midpoints. Pure visual; the\n * resize behaviour reads `getLocalHandleHits()` and runs its own\n * pointer hit math against the returned per-handle disks.\n *\n * Repaints in place on style change so a behaviour can flip the\n * `visible` field, change the dash colour, or hide / show specific\n * handles via `handles` without remounting.\n */\nexport class SelectionFrameDecoration extends ShapeDecorationBase<SelectionFrameDecorationStyle> {\n private readonly border = new Graphics();\n private readonly handlesGfx = new Graphics();\n private hits: ReadonlyArray<SelectionFrameHandleHit> = [];\n\n constructor(style: SelectionFrameDecorationStyle) {\n super(style);\n this.gfx.addChild(this.border);\n this.gfx.addChild(this.handlesGfx);\n }\n\n /**\n * Most-recently-computed per-handle hit geometry, in shape-local\n * coordinates. Behaviours iterate this array on pointerdown and test\n * each disk against the world-space click.\n */\n getLocalHandleHits(): ReadonlyArray<SelectionFrameHandleHit> {\n return this.hits;\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n\n const borderColor = this.style.borderColor ?? 0x6b7fff;\n const borderWidth = this.style.borderWidth ?? 1.5;\n // Defaults chosen so the frame reads as a *helper* rather than the\n // host's actual outline: dotted (more obviously transient than dashed)\n // and partially transparent so the underlying silhouette stays\n // visible through and around the frame.\n const borderStyle = this.style.borderStyle ?? 'dotted';\n const borderAlpha = this.style.borderAlpha ?? 0.6;\n const padding = this.style.padding ?? 4;\n const handleShape = this.style.handleShape ?? 'circle';\n const handleRadius = this.style.handleRadius ?? 5;\n const handleCornerRadius = this.style.handleCornerRadius ?? 1.5;\n const handleFill = this.style.handleFill ?? 0xffffff;\n const handleFillAlpha = this.style.handleFillAlpha ?? 1;\n const handleStrokeColor = this.style.handleStrokeColor ?? borderColor;\n const handleStrokeWidth = this.style.handleStrokeWidth ?? 1.5;\n const handleStrokeAlpha = this.style.handleStrokeAlpha ?? 1;\n const handles = this.style.handles ?? ALL_PLACEMENTS;\n const visible = this.style.visible ?? true;\n\n // Resolve dash pattern. Explicit `dashArray` wins; otherwise pick a\n // preset based on `borderStyle`. `'solid'` returns `null` so we skip\n // the dash field on the stroke entirely.\n const dashArray =\n this.style.dashArray ?? dashArrayFor(borderStyle, borderWidth);\n\n const inflated = inflateRect(host.bounds, padding);\n\n this.border.clear();\n if (dashArray && dashArray[0] > 0 && dashArray[1] > 0) {\n // PixiJS v8's `stroke()` has no native dash support — emit the dash\n // segments ourselves via the project-wide `emitDashedStroke` helper\n // (same path every other shape uses for dashed silhouettes), then\n // run a single `stroke()` to paint them uniformly.\n emitDashedStroke(this.border, rectOutlinePoints(inflated), {\n color: borderColor,\n alpha: borderAlpha,\n width: borderWidth,\n dashArray: dashArray as readonly [number, number],\n closed: true,\n });\n this.border.stroke({\n color: borderColor,\n width: borderWidth,\n alpha: borderAlpha,\n });\n } else {\n this.border.rect(inflated.x, inflated.y, inflated.width, inflated.height);\n this.border.stroke({\n color: borderColor,\n width: borderWidth,\n alpha: borderAlpha,\n });\n }\n\n this.handlesGfx.clear();\n const nextHits: SelectionFrameHandleHit[] = [];\n for (const p of handles) {\n const { cx, cy } = handleCentre(inflated, p);\n if (handleShape === 'square') {\n // `handleRadius` is treated as half-extent so a square reads the\n // same visual size as a circle of the same radius.\n const side = handleRadius * 2;\n if (handleCornerRadius > 0) {\n this.handlesGfx.roundRect(\n cx - handleRadius,\n cy - handleRadius,\n side,\n side,\n handleCornerRadius,\n );\n } else {\n this.handlesGfx.rect(cx - handleRadius, cy - handleRadius, side, side);\n }\n } else {\n this.handlesGfx.circle(cx, cy, handleRadius);\n }\n this.handlesGfx.fill({ color: handleFill, alpha: handleFillAlpha });\n if (handleStrokeWidth > 0) {\n this.handlesGfx.stroke({\n color: handleStrokeColor,\n width: handleStrokeWidth,\n alpha: handleStrokeAlpha,\n });\n }\n nextHits.push({\n placement: p,\n cx,\n cy,\n radius: handleRadius + HIT_PADDING_PX,\n });\n }\n\n this.hits = nextHits;\n this.gfx.visible = visible;\n }\n\n getOuterExtent(): number {\n // The frame sits at `padding + borderWidth/2` outside the silhouette,\n // and the handles bulge one more `handleRadius` past that on the\n // outside corners. Report the resting peak so `LabelDecoration` can\n // push labels past the frame.\n const padding = this.style.padding ?? 4;\n const borderWidth = this.style.borderWidth ?? 1.5;\n const handleRadius = this.style.handleRadius ?? 5;\n return padding + borderWidth / 2 + handleRadius;\n }\n}\n\n/**\n * Compute the centre of a handle on the inflated AABB. Corner handles\n * sit exactly on the corner; edge-midpoint handles sit on the midpoint\n * of the named side.\n */\nfunction handleCentre(bounds: Rect, placement: SelectionFramePlacement): { cx: number; cy: number } {\n const left = bounds.x;\n const right = bounds.x + bounds.width;\n const top = bounds.y;\n const bottom = bounds.y + bounds.height;\n const midX = bounds.x + bounds.width / 2;\n const midY = bounds.y + bounds.height / 2;\n switch (placement) {\n case 'top': return { cx: midX, cy: top };\n case 'bottom': return { cx: midX, cy: bottom };\n case 'left': return { cx: left, cy: midY };\n case 'right': return { cx: right, cy: midY };\n case 'top-left': return { cx: left, cy: top };\n case 'top-right': return { cx: right, cy: top };\n case 'bottom-left': return { cx: left, cy: bottom };\n case 'bottom-right': return { cx: right, cy: bottom };\n }\n}\n\n/**\n * Map a `borderStyle` preset to a concrete `[dashLength, gapLength]` (or\n * `null` for solid). Picked to read well at the default `borderWidth` of\n * `1.5` px:\n *\n * - `'solid'` → `null` — no dash field at all.\n * - `'dashed'` → `[5, 4]` — visible chunks with a comfortable gap.\n * - `'dotted'` → `[borderWidth, borderWidth * 2]` — short dashes that\n * visually read as dots without depending on `lineCap: 'round'`.\n */\nfunction dashArrayFor(\n style: SelectionFrameBorderStyle,\n borderWidth: number,\n): readonly [number, number] | null {\n switch (style) {\n case 'solid':\n return null;\n case 'dotted': {\n const w = Math.max(1, borderWidth);\n return [w, w * 2] as const;\n }\n case 'dashed':\n default:\n return [5, 4] as const;\n }\n}\n\n/**\n * Sharp-corner rect outline — four clockwise points (`emitDashedStroke`\n * closes the loop via the `closed: true` option). The selection frame\n * never has rounded corners, so the curved-corner sampler used by\n * `RectShape` would be overkill.\n */\nfunction rectOutlinePoints(r: Rect): ReadonlyArray<Point> {\n return [\n { x: r.x, y: r.y },\n { x: r.x + r.width, y: r.y },\n { x: r.x + r.width, y: r.y + r.height },\n { x: r.x, y: r.y + r.height },\n ];\n}\n\nfunction inflateRect(r: Rect, pad: number): Rect {\n return {\n x: r.x - pad,\n y: r.y - pad,\n width: r.width + pad * 2,\n height: r.height + pad * 2,\n };\n}\n","/**\n * Connector-anchored `LabelDecoration` — positions a text (or HTML text)\n * block at a `t` along the host path, with optional `pathOffset` shift along\n * the local tangent, screen-space `offset` applied post-rotation, and\n * `autoRotate` to align the label's baseline with the path direction.\n *\n * Tangent sampling: uses `samplePathAt(path, t)` which densifies the path\n * to a polyline and arc-length-walks to the requested `t`. Works uniformly\n * for every router / pathStyle the engine produces — straight, bezier,\n * smooth, rounded, orth, manhattan, bump-radial — because they all reduce\n * to the same `Path` (M/L/Q/C) command set.\n *\n * Per-frame cost: `tick` only runs when `autoRotate: true` or `visibility`\n * is configured. Static labels (`autoRotate: false`, no `visibility`) mount\n * once and never re-evaluate.\n */\n\nimport { Container, Graphics } from 'pixi.js';\nimport { ConnectorDecorationBase } from '../../base/ConnectorDecorationBase';\nimport { samplePathAt } from '../../connectors/pathSampling';\nimport {\n applyLabelResolution,\n mountLabelContent,\n updateLabelContent,\n type LabelContentView,\n} from '../../paint/labelContent';\nimport { drawLabelBackground } from '../../paint/labelBackground';\nimport type { ConnectorLabelStyle } from '../../types';\n\nexport class LabelConnectorDecoration extends ConnectorDecorationBase<ConnectorLabelStyle> {\n private contentView: LabelContentView | null = null;\n private contentLayer: Container | null = null;\n private bgGfx: Graphics | null = null;\n private attached = true;\n private hostSurface: Container | null = null;\n /** See `LabelDecoration.resolution`. */\n private resolution: number | null = null;\n\n /** See `LabelDecoration.setResolution`. */\n setResolution(resolution: number): void {\n this.resolution = resolution;\n if (this.contentView) applyLabelResolution(this.contentView, resolution);\n }\n\n /** See `LabelDecoration.getResolution`. */\n getResolution(): number | null {\n return this.resolution;\n }\n\n protected repaint(): void {\n const host = this.host;\n if (!host) return;\n this.hostSurface = host.surface;\n\n if (!this.contentLayer) {\n this.contentLayer = new Container();\n this.contentLayer.label = 'label:content';\n this.gfx.addChild(this.contentLayer);\n }\n if (this.style.background && !this.bgGfx) {\n this.bgGfx = new Graphics();\n this.bgGfx.label = 'label:bg';\n this.contentLayer.addChildAt(this.bgGfx, 0);\n } else if (!this.style.background && this.bgGfx) {\n this.bgGfx.destroy();\n this.bgGfx = null;\n }\n\n if (!this.contentView) {\n this.contentView = mountLabelContent(this.style.content, this.style.wrap);\n this.contentLayer.addChild(this.contentView.display);\n } else {\n const next = updateLabelContent(this.contentView, this.style.content, this.style.wrap);\n if (next !== this.contentView) {\n this.contentLayer.addChild(next.display);\n this.contentView = next;\n }\n }\n if (this.resolution !== null) applyLabelResolution(this.contentView, this.resolution);\n\n const textW = this.contentView.display.width;\n const textH = this.contentView.display.height;\n if (this.style.background && this.bgGfx) {\n drawLabelBackground(this.bgGfx, this.style.background, { width: textW, height: textH });\n this.bgGfx.position.set(-textW / 2, -textH / 2);\n }\n this.contentView.display.position.set(-textW / 2, -textH / 2);\n\n this.gfx.alpha = this.style.alpha ?? 1;\n this.gfx.cursor = this.style.cursor ?? 'default';\n this.gfx.eventMode = this.style.interactive ? 'static' : 'none';\n\n this.positionOnPath();\n }\n\n /**\n * Re-position + re-rotate the label on the current host path. Called\n * during repaint and on every tick (cheap — one path sample + one\n * trigonometric op). Without `autoRotate` and `visibility` configured the\n * renderer never registers `tick` and this stays static.\n */\n private positionOnPath(): void {\n const host = this.host;\n if (!host) return;\n\n const placement = this.style.placement ?? 'center';\n const t = resolveT(placement);\n\n const sample = samplePathAt(host.path, t);\n let baseX = sample.point.x;\n let baseY = sample.point.y;\n\n // `pathOffset` shifts the anchor along the local tangent (positive =\n // toward target). Useful for \"pad N px from source\".\n const pathOffset = this.style.pathOffset ?? 0;\n if (pathOffset !== 0) {\n baseX += sample.tangent.x * pathOffset;\n baseY += sample.tangent.y * pathOffset;\n }\n\n let rotation = 0;\n if (this.style.autoRotate !== false) {\n let theta = Math.atan2(sample.tangent.y, sample.tangent.x);\n // Keep text upright: flip 180° when the tangent points \"backwards\" so\n // letters always read left-to-right.\n if (this.style.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 // Screen-space offset is applied *after* rotation — so `offset.y: -8`\n // always lifts the label perpendicular to the path direction, not in\n // raw world space.\n const offsetX = this.style.offset?.x ?? 0;\n const offsetY = this.style.offset?.y ?? 0;\n if (rotation !== 0 && (offsetX !== 0 || offsetY !== 0)) {\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n baseX += offsetX * cos - offsetY * sin;\n baseY += offsetX * sin + offsetY * cos;\n } else {\n baseX += offsetX;\n baseY += offsetY;\n }\n\n this.gfx.position.set(baseX, baseY);\n this.gfx.rotation = rotation;\n }\n\n tick(_deltaMs: number): boolean {\n const v = this.style.visibility;\n const wantsLOD = v && (v.minZoom !== undefined || v.maxZoom !== undefined);\n const wantsAutoRotate = this.style.autoRotate !== false;\n if (!wantsLOD && !wantsAutoRotate) return false;\n\n if (wantsLOD && v) {\n const z = effectiveScale(this.gfx);\n const shouldShow =\n (v.minZoom === undefined || z >= v.minZoom) &&\n (v.maxZoom === undefined || z <= v.maxZoom);\n if (shouldShow && !this.attached && this.hostSurface) {\n this.hostSurface.addChild(this.gfx);\n this.attached = true;\n } else if (!shouldShow && this.attached) {\n this.gfx.parent?.removeChild(this.gfx);\n this.attached = false;\n }\n }\n\n // Connector paths change shape whenever the host re-routes (e.g. an\n // endpoint moves). `update()` is invoked then with the fresh path and\n // repaint() re-positions us — but if `autoRotate` is on we also want\n // position to follow any per-frame visual changes (e.g. a layout that\n // tweens endpoints). Re-evaluate every tick.\n if (wantsAutoRotate) this.positionOnPath();\n\n return true;\n }\n}\n\nfunction resolveT(placement: NonNullable<ConnectorLabelStyle['placement']>): 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': return 0;\n case 'end': return 1;\n case 'center':\n default: return 0.5;\n }\n}\n\nfunction effectiveScale(gfx: Container): number {\n let s = 1;\n let p: Container | null = gfx;\n while (p) {\n s *= p.scale.x;\n p = p.parent;\n }\n return s;\n}\n","import type {\n EffectTarget,\n IShapeEffect,\n ShapeEffectHostInfo,\n StyleOverride,\n TransformDelta,\n} from '../types';\n\n/**\n * Base for effects that target shape primitives. An effect *modulates* the\n * host — wiggle its transform, override its tint/alpha — rather than adding\n * geometry alongside it (that's a decoration). The renderer reads each\n * effect's contribution every frame via `readTransform()` (transform effects)\n * or `readStyle()` (style effects), aggregates across all effects attached to\n * the same host, and applies the aggregate to the host's gfx.\n *\n * Subclasses:\n * - Declare `readonly target` as `'transform'` or `'style'`.\n * - Implement `readTransform()` (target='transform') OR `readStyle()`\n * (target='style'). The renderer calls only the one matching `target`.\n * - Optionally implement `tick(deltaMs)` for animated effects. Returning\n * `false` retires the effect from the renderer's per-frame set.\n *\n * Effects do not own a Pixi container — they have no gfx. That's the\n * structural difference from `PrimitiveBase` children: shapes / connectors /\n * decorations draw, effects modulate.\n */\nexport abstract class EffectBase<TStyle> implements IShapeEffect<TStyle> {\n abstract readonly target: EffectTarget;\n\n readonly style: TStyle;\n protected host: ShapeEffectHostInfo | null = null;\n\n constructor(style: TStyle) {\n this.style = style;\n }\n\n mount(host: ShapeEffectHostInfo): void {\n this.host = host;\n }\n\n update(host: ShapeEffectHostInfo): void {\n this.host = host;\n }\n\n destroy(): void {\n this.host = null;\n }\n\n /**\n * Optional per-frame advance. Subclasses override; the base no-ops. Return\n * `false` to retire the effect from the renderer's animation set.\n */\n tick?(deltaMs: number): boolean;\n\n /**\n * Required by transform-effects; the renderer ignores it for style-effects.\n * Subclasses with `target='transform'` must override.\n */\n readTransform?(): TransformDelta;\n\n /**\n * Required by style-effects; the renderer ignores it for transform-effects.\n * Subclasses with `target='style'` must override.\n */\n readStyle?(): StyleOverride;\n}\n","import { EffectBase } from '../../base/EffectBase';\nimport { Tween } from '../../animation/Tween';\nimport { linear } from '../../animation/easings';\nimport type { EffectTarget, TransformDelta } from '../../types';\n\n/**\n * Style options for `ShakeEffect`.\n *\n * - `amplitude` — peak jitter magnitude in world pixels, applied as a random\n * offset to both axes every frame. Default `4`.\n * - `axis` — `'both' | 'x' | 'y'`. Default `'both'`.\n * - `decayMs` — when set, amplitude tweens from full to zero over this many\n * milliseconds and the effect retires when complete. Use this for \"shake\n * on click\" gestures. Omit for a continuous shake.\n * - `seed` — optional starting offset into the PRNG. Effects are independent\n * by default (each constructs its own RNG state).\n */\nexport interface ShakeEffectStyle {\n readonly amplitude?: number;\n readonly axis?: 'both' | 'x' | 'y';\n readonly decayMs?: number;\n readonly seed?: number;\n}\n\n/**\n * Per-frame random jitter applied to the host's position. Pure transform\n * modulation — the host's spec is untouched; removing the effect (or letting\n * `decayMs` retire it) reverts the host to its baseline position on the next\n * frame.\n *\n * Uses `Tween` for the optional decay envelope so easing stays consistent\n * with other animated primitives.\n */\nexport class ShakeEffect extends EffectBase<ShakeEffectStyle> {\n readonly target: EffectTarget = 'transform';\n\n private readonly amplitude: number;\n private readonly axis: 'both' | 'x' | 'y';\n private readonly decay: Tween | null;\n private seed: number;\n private currentDx = 0;\n private currentDy = 0;\n\n constructor(style: ShakeEffectStyle) {\n super(style);\n this.amplitude = style.amplitude ?? 4;\n this.axis = style.axis ?? 'both';\n this.seed = style.seed ?? Math.floor(Math.random() * 0xffffffff);\n this.decay = style.decayMs\n ? new Tween({ from: 1, to: 0, duration: style.decayMs, easing: linear })\n : null;\n }\n\n tick(deltaMs: number): boolean {\n let envelope = 1;\n if (this.decay) {\n const alive = this.decay.tick(deltaMs);\n envelope = this.decay.value;\n if (!alive) {\n this.currentDx = 0;\n this.currentDy = 0;\n return false;\n }\n }\n const amp = this.amplitude * envelope;\n if (this.axis === 'both' || this.axis === 'x') {\n this.currentDx = (this.rand() * 2 - 1) * amp;\n }\n if (this.axis === 'both' || this.axis === 'y') {\n this.currentDy = (this.rand() * 2 - 1) * amp;\n }\n return true;\n }\n\n readTransform(): TransformDelta {\n return { dx: this.currentDx, dy: this.currentDy };\n }\n\n /** xorshift32 — deterministic per-effect PRNG, no global state. */\n private rand(): number {\n let x = this.seed | 0;\n x ^= x << 13;\n x ^= x >>> 17;\n x ^= x << 5;\n this.seed = x;\n // Convert to [0, 1).\n return ((x >>> 0) % 0xffffff) / 0xffffff;\n }\n}\n","import { EffectBase } from '../../base/EffectBase';\nimport type { EffectTarget, TransformDelta } from '../../types';\n\n/**\n * Style options for `BreathingEffect`.\n *\n * - `amplitude` — fractional scale swing. `0.05` means the host scales\n * between `0.95` and `1.05`. Default `0.05`.\n * - `periodMs` — duration of one full breath cycle. Default `1800`.\n * - `axis` — `'both' | 'x' | 'y'`. Default `'both'`.\n * - `phaseOffsetMs` — start time offset; lets multiple breathing hosts\n * desync visually. Default `0`.\n */\nexport interface BreathingEffectStyle {\n readonly amplitude?: number;\n readonly periodMs?: number;\n readonly axis?: 'both' | 'x' | 'y';\n readonly phaseOffsetMs?: number;\n}\n\n/**\n * Sinusoidal scale modulation around 1.0. Cycles forever — never retires on\n * its own; remove explicitly via `setEffect(id, slot, null)`. Uses a raw\n * sine accumulator rather than `Tween` because the motion is naturally\n * cyclical (no start / end / easing curve to compose).\n */\nexport class BreathingEffect extends EffectBase<BreathingEffectStyle> {\n readonly target: EffectTarget = 'transform';\n\n private readonly amplitude: number;\n private readonly periodMs: number;\n private readonly axis: 'both' | 'x' | 'y';\n private elapsed: number;\n private currentSx = 1;\n private currentSy = 1;\n\n constructor(style: BreathingEffectStyle) {\n super(style);\n this.amplitude = style.amplitude ?? 0.05;\n this.periodMs = style.periodMs ?? 1800;\n this.axis = style.axis ?? 'both';\n this.elapsed = style.phaseOffsetMs ?? 0;\n }\n\n tick(deltaMs: number): boolean {\n this.elapsed += deltaMs;\n const phase = (this.elapsed / this.periodMs) * Math.PI * 2;\n const factor = 1 + this.amplitude * Math.sin(phase);\n this.currentSx = this.axis === 'y' ? 1 : factor;\n this.currentSy = this.axis === 'x' ? 1 : factor;\n return true;\n }\n\n readTransform(): TransformDelta {\n return { sx: this.currentSx, sy: this.currentSy };\n }\n}\n","import type {\n ConnectorEffectHostInfo,\n EffectTarget,\n IConnectorEffect,\n StyleOverride,\n TransformDelta,\n} from '../types';\n\n/**\n * Base for effects that target connector primitives. Mirror of `EffectBase`\n * for shape effects — the effect modulates the host connector's style\n * (tint / alpha) rather than adding geometry alongside it.\n *\n * Subclasses:\n * - Declare `readonly target` as `'style'` (typical) or `'transform'`.\n * Note: the renderer ignores `'transform'` for connector hosts because\n * translating / rotating / scaling a path-resolved primitive has no\n * coherent meaning — effects that need to perturb endpoints should\n * mutate the input polyline upstream of routing, not modulate gfx.\n * - Implement `readStyle()`. The renderer aggregates contributions\n * across every effect attached to the same connector (`tint` is\n * last-writer-wins per channel; `alpha` multipliers compose).\n * - Optionally implement `tick(deltaMs)` for animated effects. Returning\n * `false` retires the effect from the renderer's per-frame set.\n *\n * Effects do not own a Pixi container — they have no gfx. The structural\n * difference from `ConnectorDecorationBase` is the same as for shapes:\n * decorations draw, effects modulate.\n */\nexport abstract class ConnectorEffectBase<TStyle> implements IConnectorEffect<TStyle> {\n abstract readonly target: EffectTarget;\n\n readonly style: TStyle;\n protected host: ConnectorEffectHostInfo | null = null;\n\n constructor(style: TStyle) {\n this.style = style;\n }\n\n mount(host: ConnectorEffectHostInfo): void {\n this.host = host;\n }\n\n update(host: ConnectorEffectHostInfo): void {\n this.host = host;\n }\n\n destroy(): void {\n this.host = null;\n }\n\n tick?(deltaMs: number): boolean;\n\n readTransform?(): TransformDelta;\n\n readStyle?(): StyleOverride;\n}\n","import { ConnectorEffectBase } from '../../base/ConnectorEffectBase';\nimport type { EffectTarget, StyleOverride } from '../../types';\n\n/**\n * Sinusoidal alpha modulation on the host connector. Cycles forever — never\n * retires on its own; remove explicitly via `setEffect(id, slot, null)`.\n *\n * Style channel only — connector effects don't have a coherent meaning\n * for transform deltas (translating / scaling a path-resolved primitive\n * would just shift its position offscreen relative to the endpoints),\n * so this effect modulates the host's gfx alpha instead. Pairs naturally\n * with a thin static `glow-connector` for \"active edge\" cues, or stands\n * alone for \"blinking\" / \"pulsing\" / \"in-flight\" visualisations.\n */\nexport interface BreathingConnectorEffectStyle {\n /**\n * How far below full brightness the dim phase reaches, `[0, 1]`.\n * `0.5` swings alpha between `0.5` and `1`. Default `0.5`.\n */\n readonly amplitude?: number;\n /** Duration of one full breath cycle in ms. Default `1800`. */\n readonly periodMs?: number;\n /** Start-time offset so multiple breathing hosts can desync. Default `0`. */\n readonly phaseOffsetMs?: number;\n}\n\nexport class BreathingConnectorEffect extends ConnectorEffectBase<BreathingConnectorEffectStyle> {\n readonly target: EffectTarget = 'style';\n\n private readonly amplitude: number;\n private readonly periodMs: number;\n private elapsed: number;\n private currentAlpha = 1;\n\n constructor(style: BreathingConnectorEffectStyle) {\n super(style);\n this.amplitude = clamp01(style.amplitude ?? 0.5);\n this.periodMs = style.periodMs ?? 1800;\n this.elapsed = style.phaseOffsetMs ?? 0;\n }\n\n tick(deltaMs: number): boolean {\n this.elapsed += deltaMs;\n const phase = (this.elapsed / this.periodMs) * Math.PI * 2;\n // Map sin from [-1, 1] to [1 - amplitude, 1].\n this.currentAlpha = 1 - this.amplitude * (0.5 - 0.5 * Math.sin(phase));\n return true;\n }\n\n readStyle(): StyleOverride {\n return { alpha: this.currentAlpha };\n }\n}\n\nfunction clamp01(v: number): number {\n if (v < 0) return 0;\n if (v > 1) return 1;\n return v;\n}\n","import { ConnectorEffectBase } from '../../base/ConnectorEffectBase';\nimport { Tween } from '../../animation/Tween';\nimport {\n easeInOutCubic,\n easeInOutSine,\n easeOutCubic,\n linear,\n type Easing,\n} from '../../animation/easings';\nimport type { EffectTarget, StyleOverride } from '../../types';\n\n/** Named easings accepted by the fade-in style payload. */\nexport type FadeInEasingName = 'linear' | 'easeOutCubic' | 'easeInOutCubic' | 'easeInOutSine';\n\n/**\n * One-shot opacity fade-in on the host connector. Drives the connector's\n * alpha from `fromAlpha` (default `0`) to `toAlpha` (default `1`) over\n * `durationMs` with the configured easing, then retires from the per-frame\n * tick set while continuing to contribute `toAlpha` to the effect aggregation\n * so the connector stays visible after the fade.\n *\n * Pairs naturally with the appearance of a \"new edge\" in a graph. For a\n * continuous pulse use `BreathingConnectorEffect` instead — this one is\n * deliberately one-shot.\n */\nexport interface FadeInConnectorEffectStyle {\n /** Duration of the fade in milliseconds. Default `600`. */\n readonly durationMs?: number;\n /** Start alpha. Default `0`. */\n readonly fromAlpha?: number;\n /** End alpha. Default `1`. */\n readonly toAlpha?: number;\n /** Easing curve. Default `'easeOutCubic'`. */\n readonly easing?: FadeInEasingName;\n /** Hold the effect at `fromAlpha` for this many ms before the fade starts. Default `0`. */\n readonly delayMs?: number;\n}\n\nexport class FadeInConnectorEffect extends ConnectorEffectBase<FadeInConnectorEffectStyle> {\n readonly target: EffectTarget = 'style';\n\n private readonly tween: Tween;\n private readonly fromAlpha: number;\n private readonly toAlpha: number;\n private remainingDelayMs: number;\n private currentAlpha: number;\n\n constructor(style: FadeInConnectorEffectStyle) {\n super(style);\n this.fromAlpha = style.fromAlpha ?? 0;\n this.toAlpha = style.toAlpha ?? 1;\n this.remainingDelayMs = Math.max(0, style.delayMs ?? 0);\n this.currentAlpha = this.fromAlpha;\n this.tween = new Tween({\n from: this.fromAlpha,\n to: this.toAlpha,\n duration: Math.max(1, style.durationMs ?? 600),\n easing: resolveEasing(style.easing),\n });\n }\n\n tick(deltaMs: number): boolean {\n if (this.remainingDelayMs > 0) {\n this.remainingDelayMs -= deltaMs;\n // While delayed, keep the host at `fromAlpha` and stay animated.\n return true;\n }\n const stillAnimating = this.tween.tick(deltaMs);\n this.currentAlpha = this.tween.value;\n // After the tween retires, settle at `toAlpha` and stop ticking.\n // The renderer keeps calling `readStyle()` every frame so the alpha\n // override persists for the lifetime of the effect.\n if (!stillAnimating) this.currentAlpha = this.toAlpha;\n return stillAnimating;\n }\n\n readStyle(): StyleOverride {\n return { alpha: this.currentAlpha };\n }\n}\n\nfunction resolveEasing(name: FadeInEasingName | undefined): Easing {\n switch (name) {\n case 'linear':\n return linear;\n case 'easeInOutCubic':\n return easeInOutCubic;\n case 'easeInOutSine':\n return easeInOutSine;\n case 'easeOutCubic':\n default:\n return easeOutCubic;\n }\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 '../types';\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 '../types';\nimport type { BadgeOptions, ConnectorBadgePlacement } from './types';\nimport { samplePathAt } from '../connectors/pathSampling';\nimport { originToBadgeLocal } from './placement';\nimport type { Rect } from '../types';\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","/**\n * `PrimitivesRenderer` — domain-free drawing API for shapes, connectors,\n * markers, routers, and decorations.\n *\n * A Layer composes a `PrimitivesRenderer` internally and projects its state\n * into `addShape` / `addConnector` / `setDecoration` / ... calls. The\n * renderer is not a Layer and is never registered on `canvas.layers`. It\n * knows about pixels, hit-testing, and a camera; it knows nothing about\n * data, semantics, interactions, LOD policy, or label policy.\n *\n * **Five extensible registries**\n * - shapes — `ShapeCtor` (built-ins: circle, rect, arrow)\n * - routers — `IRouter` (built-ins: straight, orth, orthogonal,\n * manhattan, metro, er, oneSide)\n * - pathStyles — `IPathStyle` (built-ins: normal, rounded, bezier, bump-radial, bump-horizontal, step-radial, smooth, bundle, loop-curve, loop-polyline)\n * - anchors — `IAnchor` (built-ins: center, boundary, perpendicular)\n * - decorations — shape / connector (built-ins: glow)\n *\n * **No connector registry** — there is one concrete `Connector` class.\n * Visual variation comes from the (anchor → router → pathStyle) pipeline:\n * anchors resolve shape-id endpoints to concrete points (center / boundary),\n * routers produce a `Polyline` (topology — where bends sit), pathStyles\n * produce the final `Path` (visual style — how segments between bends are\n * drawn).\n *\n * **Lifecycle**\n *\n * Constructed by the host Layer in `onMount(ctx)`. The Layer passes\n * `this.container` (its own root pixi Container) and the canvas `Camera`.\n * On Layer unmount call `destroy()` first to clear internal bookkeeping\n * before the Layer's container is destroyed.\n */\n\nimport { Container, type FederatedPointerEvent } from 'pixi.js';\nimport type { Camera } from '../camera/Camera';\nimport { EventEmitter } from '../events/EventEmitter';\nimport { TextureRegistry } from '../textures/TextureRegistry';\nimport { HitIndex } from '../hit/HitIndex';\nimport { ShapeInstance } from '../instancing/ShapeInstance';\nimport { ConnectorInstance } from '../instancing/ConnectorInstance';\nimport { CircleShape } from './shapes/CircleShape';\nimport { RectShape } from './shapes/RectShape';\nimport { PolygonShape } from './shapes/PolygonShape';\nimport { RegularPolygonShape } from './shapes/RegularPolygonShape';\nimport { StarShape } from './shapes/StarShape';\nimport { ArcShape } from './shapes/ArcShape';\nimport { CompositeShape } from './shapes/CompositeShape';\nimport { Connector } from './connectors/Connector';\nimport { straightRouter } from './connectors/routers/straight';\nimport { orthRouter } from './connectors/routers/orth';\nimport { manhattanRouter } from './connectors/routers/manhattan';\nimport { metroRouter } from './connectors/routers/metro';\nimport { erRouter } from './connectors/routers/er';\nimport { oneSideRouter } from './connectors/routers/oneSide';\nimport { normalPathStyle } from './connectors/pathStyles/normal';\nimport { roundedPathStyle } from './connectors/pathStyles/rounded';\nimport { bezierPathStyle } from './connectors/pathStyles/bezier';\nimport { bumpRadialPathStyle } from './connectors/pathStyles/bumpRadial';\nimport { bumpHorizontalPathStyle } from './connectors/pathStyles/bumpHorizontal';\nimport { bundlePathStyle } from './connectors/pathStyles/bundle';\nimport { stepRadialPathStyle } from './connectors/pathStyles/stepRadial';\nimport { smoothPathStyle } from './connectors/pathStyles/smooth';\nimport { quadraticPathStyle } from './connectors/pathStyles/quadratic';\nimport { loopCurvePathStyle } from './connectors/pathStyles/loopCurve';\nimport { loopPolylinePathStyle } from './connectors/pathStyles/loopPolyline';\nimport { centerAnchor } from './connectors/anchors/center';\nimport { boundaryAnchor } from './connectors/anchors/boundary';\nimport { perpendicularAnchor } from './connectors/anchors/perpendicular';\nimport { edgePortAnchor } from './connectors/anchors/edgePort';\nimport { silhouettePortAnchor } from './connectors/anchors/silhouettePort';\nimport { distanceToPolylineSq, pathBounds, samplePath, trimPathEnds } from './connectors/pathSampling';\nimport { ArrowMarker } from './markers/ArrowMarker';\nimport { GlowDecoration } from './decorations/shape/GlowDecoration';\nimport { PulseRingDecoration } from './decorations/shape/PulseRingDecoration';\nimport { LiquidFillDecoration } from './decorations/shape/LiquidFillDecoration';\nimport { MarchingAntsDecoration } from './decorations/shape/MarchingAntsDecoration';\nimport { RingDecoration } from './decorations/shape/RingDecoration';\nimport { MarchingAntsConnectorDecoration } from './decorations/connector/MarchingAntsConnectorDecoration';\nimport { FlyMarkerConnectorDecoration } from './decorations/connector/FlyMarkerConnectorDecoration';\nimport { FlowParticlesConnectorDecoration } from './decorations/connector/FlowParticlesConnectorDecoration';\nimport { GlowConnectorDecoration } from './decorations/connector/GlowConnectorDecoration';\nimport { RippleConnectorDecoration } from './decorations/connector/RippleConnectorDecoration';\nimport { RevealConnectorDecoration } from './decorations/connector/RevealConnectorDecoration';\nimport { RingConnectorDecoration } from './decorations/connector/RingConnectorDecoration';\nimport { LabelDecoration } from './decorations/shape/LabelDecoration';\nimport { ToggleDecoration } from './decorations/shape/ToggleDecoration';\nimport { ResizeHandleDecoration } from './decorations/shape/ResizeHandleDecoration';\nimport { SelectionFrameDecoration } from './decorations/shape/SelectionFrameDecoration';\nimport { LabelConnectorDecoration } from './decorations/connector/LabelConnectorDecoration';\nimport { ShakeEffect } from './effects/shape/ShakeEffect';\nimport { BreathingEffect } from './effects/shape/BreathingEffect';\nimport { BreathingConnectorEffect } from './effects/connector/BreathingConnectorEffect';\nimport { FadeInConnectorEffect } from './effects/connector/FadeInConnectorEffect';\nimport { resolveBadgePosition } from './badges/placement';\nimport {\n DEFAULT_ENDPOINT_BADGE_GAP_PX,\n resolveConnectorBadgePosition,\n} from './badges/connectorPlacement';\nimport type { BadgeOptions } from './badges/types';\nimport { markerInsetFor } from './base/ConnectorBase';\nimport type {\n AnchorCtx,\n AnchorShapeRef,\n AnchorSpec,\n BaseConnectorSpec,\n BaseShapeSpec,\n ConnectorDecorationCtor,\n ConnectorDecorationHostInfo,\n ConnectorEndpointSpec,\n ConnectorHostInfo,\n DecorationSpec,\n DecorationTarget,\n EffectSpec,\n EffectTargetKind,\n Endpoint,\n HitResult,\n IAnchor,\n IConnector,\n IConnectorDecoration,\n IDecorationBase,\n IPathStyle,\n IRouter,\n IShape,\n IShapeDecoration,\n IShapeEffect,\n IConnectorEffect,\n ConnectorEffectCtor,\n ConnectorEffectHostInfo,\n Obstacle,\n Path,\n Point,\n PrimitivesRendererEventMap,\n Rect,\n RegisterDecorationOptions,\n RegisterEffectOptions,\n RenderStats,\n RouterCtx,\n ShapeCtor,\n ShapeDecorationCtor,\n ShapeDecorationHostInfo,\n ShapeEffectCtor,\n ShapeEffectHostInfo,\n ShapeHostInfo,\n} from './types';\n\ninterface RegisteredDecoration {\n readonly ctor: ShapeDecorationCtor | ConnectorDecorationCtor;\n readonly target: DecorationTarget;\n}\n\ninterface RegisteredEffect {\n readonly ctor: ShapeEffectCtor | ConnectorEffectCtor;\n readonly target: EffectTargetKind;\n}\n\ntype AnimatedDecoration = { tick(deltaMs: number): boolean };\ntype AnimatedEffect = (IShapeEffect | IConnectorEffect) & { tick(deltaMs: number): boolean };\n\nexport interface PrimitivesRendererOptions {\n readonly container: Container;\n readonly camera: Camera;\n /**\n * Optional shared texture registry. When omitted, the renderer creates an\n * internal one — image fills still work (lazy-loaded), but textures are\n * not shared across renderer instances.\n */\n readonly textureRegistry?: TextureRegistry;\n /**\n * Optional DOM `<canvas>` element. Used by `hitMode: 'indexed'` to\n * apply `cursor: pointer` on shape/connector hover (Pixi's native\n * `gfx.cursor` auto-application is bypassed in indexed mode because\n * `eventMode = 'none'` skips the federated hit-test walk).\n *\n * When omitted in indexed mode, hover-cursor styling is a no-op —\n * shape/connector hits still emit `pointerover` / `pointerout` events\n * to behaviours, just without the cursor feedback. Most consumers\n * should pass this; `GraphLayer` forwards `CanvasContext.canvasElement`\n * automatically.\n */\n readonly canvasElement?: HTMLCanvasElement;\n /**\n * Minimum hover/click target in screen pixels — used as a *fallback*\n * by {@link hitTest}: exact geometric hits always win; only when no\n * shape contains the cursor does the dispatcher pick the closest\n * candidate within this many screen pixels of its origin. Exact\n * hits are never widened, so dense graphs don't suffer false\n * positives.\n *\n * Default `6` (cursor-friendly). Raise (`8`–`12`) for touch-friendly\n * stories; drop to `0` to forbid the fallback entirely.\n */\n readonly hitFloorPx?: number;\n}\n\n/**\n * Default for {@link PrimitivesRendererOptions.hitFloorPx} — overridable\n * per-renderer. See the option's TSDoc for the rationale on raising /\n * lowering it.\n */\nconst DEFAULT_HIT_FLOOR_PX = 6;\n\nexport class PrimitivesRenderer {\n private readonly shapeRegistry = new Map<string, ShapeCtor>();\n private readonly routerRegistry = new Map<string, IRouter>();\n private readonly pathStyleRegistry = new Map<string, IPathStyle>();\n private readonly anchorRegistry = new Map<string, IAnchor>();\n private readonly decorationRegistry = new Map<string, RegisteredDecoration>();\n private readonly effectRegistry = new Map<string, RegisteredEffect>();\n\n private readonly shapeInstances = new Map<string, ShapeInstance>();\n private readonly connectorInstances = new Map<string, ConnectorInstance>();\n private readonly animated = new Set<AnimatedDecoration>();\n private readonly animatedEffects = new Set<AnimatedEffect>();\n /**\n * Shape instances that currently have at least one effect attached. The\n * per-frame aggregation walks this set rather than every shape instance.\n */\n private readonly hostsWithEffects = new Set<ShapeInstance>();\n /**\n * Connector instances that currently have at least one effect attached.\n * Walked per frame to aggregate style modulations (tint + alpha) onto\n * `connector.gfx`. Transform deltas are ignored for connector hosts.\n */\n private readonly connectorHostsWithEffects = new Set<ConnectorInstance>();\n\n /**\n * Host → (slot → BadgeOptions). Each entry corresponds to a shape registered\n * under id `${hostId}:${slot}` and re-anchored on host updates.\n */\n private readonly badges = new Map<string, Map<string, BadgeOptions>>();\n\n private readonly hit = new HitIndex();\n\n /**\n * Most recently-pushed label rasterisation resolution. `null` until a\n * zoom-LOD behaviour (or the host app) calls `setLabelsResolution`. When\n * non-null, every newly-mounted label decoration inherits this value so\n * the user never sees a freshly-drawn label start at base fidelity and\n * snap up on the next zoom event.\n */\n private trackedLabelResolution: number | null = null;\n\n /**\n * Every decoration exposing the `setResolution` / `getResolution` hooks\n * (i.e. `LabelDecoration` / `LabelConnectorDecoration`). Maintained on\n * `setDecoration` / `disposeDecoration` so `tickAnimations` can sweep it\n * cheaply without re-scanning every shape and connector instance.\n *\n * The sweep applies the tracked resolution only to labels currently\n * inside the camera viewport — re-rastering an off-screen label burns a\n * GPU texture upload with no visible benefit. Off-screen labels catch\n * up the moment they pan in, since the sweep re-checks every frame.\n */\n private readonly labelBearingDecorations = new Set<IDecorationBase<unknown>>();\n /**\n * Per-frame budget on how many on-screen labels get re-rastered. Each\n * `setResolution(r)` write triggers one glyph-texture regen in Pixi's\n * next render pass. 64 keeps the regen cost inside frame budget for a\n * typical few-hundred-visible-label scene while finishing the transition\n * in under 5 frames; widen if your scenes have larger visible label\n * sets and tolerate a longer transition.\n */\n private static readonly LABEL_RASTER_PER_TICK = 64;\n\n readonly events = new EventEmitter<PrimitivesRendererEventMap>();\n\n private readonly _container: Container;\n /**\n * Connector sub-layer — added to `_container` first so it renders *below*\n * the shape layer. Connector decorations live inside `connector.gfx`\n * (children of this layer), so any decoration geometry that extends past\n * the path endpoints (e.g. a glow halo's radius, a ripple wave's\n * `maxRadius`) is naturally hidden by overlapping shapes on top —\n * matching the standard graph-viz \"nodes above edges\" convention.\n */\n private readonly connectorLayer: Container;\n /** Shape sub-layer — rendered above `connectorLayer`. */\n private readonly shapeLayer: Container;\n readonly camera: Camera;\n private readonly textureRegistry: TextureRegistry;\n private readonly hitFloorPx: number;\n /** DOM canvas element used by the router for cursor styling. */\n private readonly canvasElement: HTMLCanvasElement | null;\n\n /** Currently-hovered target. Tracks pointerover/out diffs. */\n private currentHover: { kind: 'shape' | 'connector'; id: string } | null = null;\n /** Target captured by a pointerdown — used to gate click emission. */\n private downHit: { kind: 'shape' | 'connector'; id: string; button: number } | null = null;\n /**\n * True while any pointer button is held down (regardless of where\n * the pointerdown landed). Used to suppress hover state-changes\n * during a drag — without this, dragging a node over neighbouring\n * shapes fires `pointerover` on each one and triggers\n * `HoverActivateBehaviour` mid-drag.\n */\n private pointerDown = false;\n /** Last left-click time + target — drives double-click detection. */\n private lastLeftClick: { kind: 'shape' | 'connector'; id: string; t: number } | null = null;\n /** Pointer-router subscriptions to clean up on `destroy`. */\n private pointerRouterUnsubs: Array<() => void> = [];\n /**\n * RAF handle + latest pointer-move event for the move-coalescing\n * throttle. Raw `globalpointermove` fires hundreds of times per\n * second on a fast mouse sweep; we only need to resolve the hit\n * once per animation frame.\n */\n private pendingPointerMove: FederatedPointerEvent | null = null;\n private pointerMoveRaf: number | null = null;\n\n constructor(opts: PrimitivesRendererOptions) {\n this._container = opts.container;\n this.camera = opts.camera;\n this.textureRegistry = opts.textureRegistry ?? new TextureRegistry();\n this.hitFloorPx = opts.hitFloorPx ?? DEFAULT_HIT_FLOOR_PX;\n this.canvasElement = opts.canvasElement ?? null;\n // Insertion order = render order in Pixi. Adding the connector layer\n // first then the shape layer puts shapes on top — so any connector\n // decoration that extends past a path endpoint (glow halo, ripple\n // wave) is clipped visually by the overlapping shape.\n this.connectorLayer = new Container();\n this.shapeLayer = new Container();\n // Sort each sub-layer's children by `gfx.zIndex` so a primitive can be\n // lifted above its peers within its own layer (see `raiseShape` /\n // `raiseConnector`). Default `zIndex` is 0, and JS `Array.sort` is stable,\n // so untouched primitives keep their natural insertion order. Sorting is\n // confined to each sub-layer — `_container` itself is NOT sortable, so the\n // connector-below-shape ordering of the two layers is preserved (a raised\n // edge still sits under every node).\n this.connectorLayer.sortableChildren = true;\n this.shapeLayer.sortableChildren = true;\n this._container.addChild(this.connectorLayer);\n this._container.addChild(this.shapeLayer);\n this.registerBuiltins();\n this.installPointerRouter();\n }\n\n private registerBuiltins(): void {\n this.registerShape('circle', CircleShape);\n this.registerShape('rect', RectShape);\n this.registerShape('polygon', PolygonShape);\n this.registerShape('regular-polygon', RegularPolygonShape);\n this.registerShape('star', StarShape);\n this.registerShape('arc', ArcShape);\n this.registerShape('composite', CompositeShape);\n // Markers are shapes — registered through the same shape registry so\n // they can also be added directly via `addShape` and so connectors can\n // resolve them by `kind` from the read-only registry.\n this.registerShape('arrow', ArrowMarker);\n\n this.registerRouter('straight', straightRouter);\n // `orth` is the simple H/V router (matches X6 / JointJS naming).\n // `orthogonal` is an alias kept for compatibility.\n this.registerRouter('orth', orthRouter);\n this.registerRouter('orthogonal', orthRouter);\n // `manhattan` is the obstacle-aware variant — routes around `RouterCtx.obstacles`\n // via A* on a coarse grid; falls back to `orth` when obstacles are empty\n // or A* fails. See `connectors/routers/manhattan.ts`.\n this.registerRouter('manhattan', manhattanRouter);\n this.registerRouter('metro', metroRouter);\n this.registerRouter('er', erRouter);\n this.registerRouter('oneSide', oneSideRouter);\n\n this.registerPathStyle('normal', normalPathStyle);\n this.registerPathStyle('rounded', roundedPathStyle);\n this.registerPathStyle('bezier', bezierPathStyle);\n this.registerPathStyle('quadratic', quadraticPathStyle);\n this.registerPathStyle('bump-radial', bumpRadialPathStyle);\n this.registerPathStyle('bump-horizontal', bumpHorizontalPathStyle);\n this.registerPathStyle('bundle', bundlePathStyle);\n this.registerPathStyle('step-radial', stepRadialPathStyle);\n this.registerPathStyle('smooth', smoothPathStyle);\n // Self-loop pathStyles — draw a petal / U-stub anchored at the first\n // polyline point. Pair with `router: 'straight'` and a connector whose\n // source and target reference the same shape.\n this.registerPathStyle('loop-curve', loopCurvePathStyle);\n this.registerPathStyle('loop-polyline', loopPolylinePathStyle);\n\n this.registerAnchor('center', centerAnchor);\n this.registerAnchor('boundary', boundaryAnchor);\n this.registerAnchor('perpendicular', perpendicularAnchor);\n this.registerAnchor('edge-port', edgePortAnchor);\n this.registerAnchor('silhouette-port', silhouettePortAnchor);\n\n this.registerDecoration('glow', GlowDecoration, { target: 'shape' });\n this.registerDecoration('pulse-ring', PulseRingDecoration, { target: 'shape' });\n this.registerDecoration('liquid-fill', LiquidFillDecoration, { target: 'shape' });\n this.registerDecoration('marching-ants', MarchingAntsDecoration, { target: 'shape' });\n this.registerDecoration('ring', RingDecoration, { target: 'shape' });\n this.registerDecoration('marching-ants-connector', MarchingAntsConnectorDecoration, { target: 'connector' });\n this.registerDecoration('fly-marker-connector', FlyMarkerConnectorDecoration, { target: 'connector' });\n this.registerDecoration('flow-particles-connector', FlowParticlesConnectorDecoration, { target: 'connector' });\n this.registerDecoration('glow-connector', GlowConnectorDecoration, { target: 'connector' });\n this.registerDecoration('ripple-connector', RippleConnectorDecoration, { target: 'connector' });\n this.registerDecoration('reveal-connector', RevealConnectorDecoration, { target: 'connector' });\n this.registerDecoration('ring-connector', RingConnectorDecoration, { target: 'connector' });\n this.registerDecoration('label', LabelDecoration, { target: 'shape' });\n this.registerDecoration('label-connector', LabelConnectorDecoration, { target: 'connector' });\n this.registerDecoration('toggle', ToggleDecoration, { target: 'shape' });\n this.registerDecoration('resize-handle', ResizeHandleDecoration, { target: 'shape' });\n this.registerDecoration('selection-frame', SelectionFrameDecoration, { target: 'shape' });\n\n this.registerEffect('shake', ShakeEffect, { target: 'shape' });\n this.registerEffect('breathing', BreathingEffect, { target: 'shape' });\n this.registerEffect('breathing-connector', BreathingConnectorEffect, { target: 'connector' });\n this.registerEffect('fade-in-connector', FadeInConnectorEffect, { target: 'connector' });\n }\n\n // ─── Registries ─────────────────────────────────────────────────────────\n\n registerShape<TSpec extends BaseShapeSpec>(kind: string, ctor: ShapeCtor<TSpec>): void {\n this.shapeRegistry.set(kind, ctor as ShapeCtor);\n }\n\n registerRouter(kind: string, fn: IRouter): void {\n this.routerRegistry.set(kind, fn);\n }\n\n registerPathStyle(kind: string, fn: IPathStyle): void {\n this.pathStyleRegistry.set(kind, fn);\n }\n\n registerAnchor(kind: string, fn: IAnchor): void {\n this.anchorRegistry.set(kind, fn);\n }\n\n registerDecoration<TStyle>(\n kind: string,\n ctor: new (style: TStyle) => IShapeDecoration<TStyle> | IConnectorDecoration<TStyle>,\n opts: RegisterDecorationOptions,\n ): void {\n this.decorationRegistry.set(kind, {\n ctor: ctor as unknown as ShapeDecorationCtor | ConnectorDecorationCtor,\n target: opts.target,\n });\n }\n\n /**\n * Register an effect under a string kind. Effects are domain-free primitives\n * that modulate the host shape's transform or style channels each frame\n * (shake, breathing, shimmer, …). The effect's constructor receives the\n * caller's `style` payload; `opts.target` constrains which host kinds the\n * effect may attach to (shape-only for v0).\n *\n * Throws on `setEffect` if the registered `target` doesn't include the\n * host kind being targeted.\n */\n registerEffect<TStyle>(\n kind: string,\n ctor: new (style: TStyle) => IShapeEffect<TStyle> | IConnectorEffect<TStyle>,\n opts: RegisterEffectOptions,\n ): void {\n this.effectRegistry.set(kind, {\n ctor: ctor as unknown as ShapeEffectCtor | ConnectorEffectCtor,\n target: opts.target,\n });\n }\n\n // ─── Mutation: shapes ───────────────────────────────────────────────────\n\n addShape<TSpec extends BaseShapeSpec>(id: string, spec: TSpec): void {\n if (this.shapeInstances.has(id)) {\n throw new Error(`PrimitivesRenderer.addShape: id \"${id}\" already exists`);\n }\n const Ctor = this.shapeRegistry.get(spec.kind);\n if (!Ctor) {\n throw new Error(`PrimitivesRenderer.addShape: unknown shape kind \"${spec.kind}\"`);\n }\n const host: ShapeHostInfo = {\n surface: this.shapeLayer,\n textureRegistry: this.textureRegistry,\n requestRedraw: () => {\n const cur = this.shapeInstances.get(id);\n if (cur) cur.shape.draw(cur.spec);\n },\n };\n const shape = new Ctor(spec, host) as IShape<TSpec>;\n this.shapeLayer.addChild(shape.gfx);\n const inst = new ShapeInstance<TSpec>(id, spec, shape);\n this.shapeInstances.set(id, inst as unknown as ShapeInstance);\n this.hit.insert(id, 'shape', this.shapeWorldBounds(inst), spec.zIndex ?? 0);\n // Per-shape Pixi event dispatch is bypassed — the renderer's global\n // pointer router (see `installPointerRouter`) handles hit-routing\n // via `hitTest`. Disabling `eventMode` on the gfx skips Pixi's\n // per-shape hit-test walk on every pointer event (the perf win on\n // dense graphs); the geometric `hitArea` set by `ShapeBase` is\n // left in place so `hitTest` can still consult it via\n // `inst.shape.getHitArea().contains(...)`.\n shape.gfx.eventMode = 'none';\n }\n\n updateShape<TSpec extends BaseShapeSpec>(id: string, partial: Partial<TSpec>): void {\n const inst = this.shapeInstances.get(id) as ShapeInstance<TSpec> | undefined;\n if (!inst) return;\n inst.spec = { ...inst.spec, ...partial };\n inst.shape.draw(inst.spec);\n this.hit.update(id, this.shapeWorldBounds(inst), inst.spec.zIndex ?? 0);\n if (inst.decorations.size > 0) this.refreshShapeDecorations(inst);\n if (this.badges.has(id)) this.reanchorBadges(id);\n }\n\n /**\n * Fast-path uniform rescale for a shape — writes the gfx transform\n * directly without touching the spec or rebuilding geometry.\n *\n * `updateShape` rebuilds the underlying Pixi geometry (Graphics.clear()\n * + retrace) on every call, which dominates the cost when something\n * like `NodeSizeLODBehaviour` rewrites thousands of node sizes per\n * camera-zoom frame. `scaleShape` skips all of that: the geometry on\n * the GPU is unchanged, only its transform changes.\n *\n * **Hit-test bounds are NOT updated here.** rbush's `remove(entry)` is\n * an O(N) tree walk, so per-id `hit.update` × N shapes is O(N²) per\n * zoom frame — pathological at a few thousand shapes. Call\n * {@link reindexScaledShapeHits} once *after* a batch (typically on\n * gesture settle) to bulk-reindex in O(N log N). The hit-bounds are\n * stale until you do — acceptable when the caller knows pointer\n * interaction is unlikely mid-gesture.\n *\n * **Other limitations** — decorations and badges attached to the host\n * are **not** re-anchored against the new visible bounds; if you have\n * either on a size-LOD'd node, prefer `updateShape` or accept the\n * stale anchor. Stroke width inside the geometry scales with the\n * transform (Pixi's stroke is in local units), which is usually the\n * intent for pixel-constant sizing but means you can't independently\n * target body size and stroke width via `scaleShape` alone.\n */\n scaleShape(id: string, scale: number): void {\n const inst = this.shapeInstances.get(id);\n if (!inst) return;\n inst.gfxScale = scale;\n inst.shape.gfx.scale.set(scale, scale);\n }\n\n /**\n * Restack a shape within the shape layer by writing its `gfx.zIndex`. The\n * shape layer renders with `sortableChildren`, so a higher `zIndex` paints\n * later (on top of peers with a lower one); `zIndex = 0` (the default)\n * restores natural insertion order. Use to lift a hovered / selected node\n * above the rest so unrelated nodes don't draw over it.\n *\n * Visual-only: this does NOT touch geometry, transform, or the hit index\n * (closest-wins hit resolution already consults the spec `zIndex` recorded\n * at insert). Restacking is confined to the shape layer, so a raised node\n * still renders above every connector.\n */\n raiseShape(id: string, zIndex: number): void {\n const inst = this.shapeInstances.get(id);\n if (!inst) return;\n inst.shape.gfx.zIndex = zIndex;\n }\n\n /**\n * Restack a connector within the connector layer by writing its `gfx.zIndex`\n * — the connector-side sibling of {@link raiseShape}. A higher `zIndex`\n * paints later (above peer edges); `zIndex = 0` restores insertion order.\n * Use to lift a hovered / selected edge above unrelated edges crossing it.\n *\n * Confined to the connector layer, which renders below the shape layer, so a\n * raised edge still sits under every node.\n */\n raiseConnector(id: string, zIndex: number): void {\n const inst = this.connectorInstances.get(id);\n if (!inst) return;\n inst.connector.gfx.zIndex = zIndex;\n }\n\n /**\n * Bulk re-index hit-test bboxes for shapes — pairs with\n * {@link scaleShape} (which intentionally skips per-call hit updates).\n *\n * Passing `ids` confines the reindex to those shapes. Omitting it\n * touches every shape instance. Either way the rbush tree is rebuilt\n * once via `clear + load` rather than N × `remove + insert`.\n *\n * Call on gesture settle (e.g. inside `NodeSizeLODBehaviour`'s\n * trailing-edge `flushReanchor`) so mid-gesture frames stay cheap and\n * hit-test accuracy snaps back the moment the user stops zooming.\n */\n reindexScaledShapeHits(ids?: Iterable<string>): void {\n const updates: Array<{ id: string; rect: Rect }> = [];\n const sourceIds: Iterable<string> = ids ?? this.shapeInstances.keys();\n for (const id of sourceIds) {\n const inst = this.shapeInstances.get(id);\n if (!inst) continue;\n updates.push({ id, rect: this.shapeWorldBounds(inst) });\n }\n this.hit.bulkUpdateBoxes(updates);\n }\n\n /**\n * Recompute the path of every connector. Use after a batch of\n * `scaleShape` calls (e.g. one `NodeSizeLODBehaviour` zoom tick) so\n * connectors re-anchor against the freshly-scaled silhouettes — without\n * this, edges remain anchored to the pre-scale bounds and visibly fall\n * short of the smaller shape.\n *\n * Cheap when paired with the lazy `obstacles` getter in `routePath`:\n * routers that don't read obstacles (e.g. `straight`) skip the\n * `O(shapes)` collection per connector. Routers that *do* read\n * obstacles (`manhattan`, `metro`, `er`) still pay it — pair them with\n * a debounce when re-anchoring on a continuous gesture.\n */\n reanchorAllConnectors(): void {\n for (const inst of this.connectorInstances.values()) {\n this.recomputeConnectorPath(inst);\n }\n }\n\n removeShape(id: string): void {\n const inst = this.shapeInstances.get(id);\n if (!inst) return;\n // Cascade-remove attached badges *before* removing the host so the badge\n // ids don't outlive the host in any consumer-visible state.\n const attached = this.badges.get(id);\n if (attached) {\n for (const slot of [...attached.keys()]) this.removeBadge(id, slot);\n this.badges.delete(id);\n }\n for (const deco of inst.decorations.values()) this.disposeDecoration(deco);\n inst.decorations.clear();\n for (const fx of inst.effects.values()) this.disposeEffect(fx);\n inst.effects.clear();\n this.hostsWithEffects.delete(inst);\n inst.shape.destroy();\n this.hit.remove(id);\n this.shapeInstances.delete(id);\n }\n\n // ─── Mutation: connectors ───────────────────────────────────────────────\n\n addConnector<TSpec extends BaseConnectorSpec>(id: string, spec: TSpec): void {\n if (this.connectorInstances.has(id)) {\n throw new Error(`PrimitivesRenderer.addConnector: id \"${id}\" already exists`);\n }\n const host: ConnectorHostInfo = {\n surface: this.connectorLayer,\n shapeRegistry: this.shapeRegistry,\n };\n const connector = new Connector(host) as unknown as IConnector<TSpec>;\n this.connectorLayer.addChild(connector.gfx);\n const inst = new ConnectorInstance<TSpec>(id, spec, connector);\n this.connectorInstances.set(id, inst as unknown as ConnectorInstance);\n // No decorations attached yet, so padding is zero — but funnel through\n // `recomputeConnectorPath` for a single code path that handles both\n // the no-decoration and with-decoration cases.\n this.recomputeConnectorPath(inst as unknown as ConnectorInstance);\n // See `addShape` for the rationale — per-connector Pixi event\n // dispatch is replaced by the global pointer router.\n connector.gfx.eventMode = 'none';\n }\n\n updateConnector<TSpec extends BaseConnectorSpec>(id: string, partial: Partial<TSpec>): void {\n const inst = this.connectorInstances.get(id) as ConnectorInstance<TSpec> | undefined;\n if (!inst) return;\n inst.spec = { ...inst.spec, ...partial };\n this.recomputeConnectorPath(inst as unknown as ConnectorInstance);\n }\n\n /**\n * Fast-path render update for connectors — patches the `stroke` spec\n * and redraws on the **existing cached path** without re-running the\n * router / pathStyle / obstacle calculation.\n *\n * `updateConnector` always calls `recomputeConnectorPath`, which builds\n * an obstacle list by iterating every shape in the renderer (line 1271).\n * For a `straight` router with thousands of connectors that's\n * `O(connectors × shapes)` per update — fine for one-off restyles, but\n * lethal during continuous camera-driven reflows (e.g. `ScreenSizeBehaviour`\n * keeping stroke widths pixel-constant across zoom).\n *\n * This skips all of that: the path is unchanged (scale doesn't move\n * any endpoint in world coords), so we just redraw the body on the\n * cached `inst.path` with the new stroke. Use when you know **only**\n * the stroke is changing.\n */\n setConnectorStroke(id: string, stroke: { color: number; width: number }): void {\n const inst = this.connectorInstances.get(id);\n if (!inst) return;\n inst.spec = { ...inst.spec, stroke };\n this.drawConnectorInstance(inst);\n }\n\n /**\n * Re-route the path for `inst`, trim by aggregated decoration end-padding,\n * redraw the connector body + markers on the trimmed path, and refresh\n * any attached decorations against the new path. Called whenever the\n * spec, decorations, or padding requirements change.\n */\n private recomputeConnectorPath(inst: ConnectorInstance): void {\n const rawPath = this.routePath(inst.spec);\n const padding = this.aggregateConnectorPadding(inst);\n // Padding only applies at endpoints that actually have a marker. Without\n // a marker, the body's stroke (and any decoration's body stroke) ends\n // sharp at the path endpoint (butt cap) — there's no \"outer extent\"\n // past the anchor to make room for. Inserting padding there would just\n // shorten the body and open a visible gap between it and the anchor.\n const srcPad = inst.spec.sourceMarker ? padding.source : 0;\n const tgtPad = inst.spec.targetMarker ? padding.target : 0;\n inst.path = srcPad > 0 || tgtPad > 0\n ? trimPathEnds(rawPath, srcPad, tgtPad)\n : rawPath;\n this.drawConnectorInstance(inst);\n this.indexConnector(inst);\n if (inst.decorations.size > 0) this.refreshConnectorDecorations(inst);\n if (this.badges.has(inst.id)) this.reanchorConnectorBadges(inst, inst.id);\n }\n\n /**\n * Fast-path render-time stroke multiplier for a connector — writes\n * `inst.strokeWidthScale` and redraws on the cached path.\n *\n * `EdgeSizeLODBehaviour` uses this each `camera:zoom` frame to keep\n * spec stroke widths pixel-constant across zoom. Critically, it does\n * **not** touch `spec.stroke.width`: the canonical spec stays as the\n * caller authored it, so a downstream `setConnectorStroke` (or a state-\n * config-driven `updateConnector` rebuild via `GraphLayer.rerenderEdge`)\n * supplies the new \"base\" width and the LOD multiplier applies on top\n * — no clobber, no inversion of caller intent.\n *\n * Path / obstacles / decorations are unchanged by a stroke-only\n * rescale, so this is the same shape as `setConnectorStroke`: skip\n * `recomputeConnectorPath`, just redraw on the cached path.\n */\n scaleConnectorStroke(id: string, scale: number): void {\n const inst = this.connectorInstances.get(id);\n if (!inst) return;\n inst.strokeWidthScale = scale;\n this.drawConnectorInstance(inst);\n }\n\n /**\n * Draw a connector with `inst.strokeWidthScale` baked into the spec's\n * stroke width. The original `inst.spec` is unchanged — only the spec\n * handed to `inst.connector.draw` carries the scaled width.\n *\n * The multiplication also flows through markers (sized off the stroke\n * width via `*Scale` multipliers) and the trimmed body path (computed\n * from stroke width), so the whole connector visual scales coherently.\n */\n private drawConnectorInstance(inst: ConnectorInstance): void {\n const k = inst.strokeWidthScale;\n const stroke = inst.spec.stroke;\n if (k === 1 || !stroke || stroke.width === undefined) {\n inst.connector.draw(inst.spec, inst.path);\n return;\n }\n const scaledSpec = {\n ...inst.spec,\n stroke: { ...stroke, width: stroke.width * k },\n };\n inst.connector.draw(scaledSpec, inst.path);\n }\n\n /**\n * Max end-padding across every decoration attached to `inst`. Decorations\n * declare their outer extent via `getEndPadding()`; we take the max per\n * endpoint so a glow with radius 16 and a ripple with maxRadius 24 on the\n * same edge result in a 24-px inset at each end (both reach the anchor;\n * the glow stops 8 px short, which is the intended \"smaller halo\" look).\n */\n private aggregateConnectorPadding(inst: ConnectorInstance): { source: number; target: number } {\n let src = 0;\n let tgt = 0;\n for (const deco of inst.decorations.values()) {\n if (typeof deco.getEndPadding !== 'function') continue;\n const p = deco.getEndPadding();\n if (p.source > src) src = p.source;\n if (p.target > tgt) tgt = p.target;\n }\n return { source: src, target: tgt };\n }\n\n /**\n * Max resting outer extent across every shape decoration attached to\n * `inst`. Read by `LabelDecoration` (via `ShapeDecorationHostInfo`) so\n * outside-placement labels offset past the outermost ring / halo on the\n * host. Decorations that don't paint past the silhouette (label,\n * marching-ants) omit `getOuterExtent` and contribute `0`; animated\n * transients (pulse-ring) deliberately report `0` so the label doesn't\n * yo-yo with the pulse.\n */\n private aggregateShapeOuterExtent(inst: ShapeInstance): number {\n let max = 0;\n for (const deco of inst.decorations.values()) {\n if (typeof deco.getOuterExtent !== 'function') continue;\n const v = deco.getOuterExtent();\n if (v > max) max = v;\n }\n return max;\n }\n\n removeConnector(id: string): void {\n const inst = this.connectorInstances.get(id);\n if (!inst) return;\n // Cascade-remove attached badges *before* destroying the host so the\n // badge ids don't outlive the host in any consumer-visible state.\n // Mirrors the symmetric path in `removeShape`.\n const attached = this.badges.get(id);\n if (attached) {\n for (const slot of [...attached.keys()]) this.removeBadge(id, slot);\n this.badges.delete(id);\n }\n for (const deco of inst.decorations.values()) this.disposeDecoration(deco);\n inst.decorations.clear();\n for (const fx of inst.effects.values()) this.disposeEffect(fx);\n inst.effects.clear();\n this.connectorHostsWithEffects.delete(inst);\n this.hit.remove(id);\n inst.connector.destroy();\n this.connectorInstances.delete(id);\n }\n\n // ─── Decorations ────────────────────────────────────────────────────────\n\n setDecoration<TStyle = unknown>(\n targetId: string,\n slot: string,\n decoration: DecorationSpec<TStyle> | null,\n ): void {\n const shape = this.shapeInstances.get(targetId);\n const connector = this.connectorInstances.get(targetId);\n if (!shape && !connector) {\n throw new Error(`PrimitivesRenderer.setDecoration: unknown target \"${targetId}\"`);\n }\n\n const decorations = (shape ?? connector!).decorations as Map<\n string,\n IDecorationBase<unknown>\n >;\n const prev = decorations.get(slot);\n if (prev) this.disposeDecoration(prev);\n\n if (decoration === null) {\n decorations.delete(slot);\n // Removing a decoration may shrink the aggregated padding for the\n // connector — re-route + redraw on the new (less-trimmed) path.\n if (connector) this.recomputeConnectorPath(connector);\n // Shape analogue: dropping a ring / halo shrinks the aggregated outer\n // extent, so any LabelDecoration on the same host needs to re-flow\n // back toward the silhouette.\n if (shape) this.refreshShapeDecorations(shape);\n return;\n }\n\n const entry = this.decorationRegistry.get(decoration.kind);\n if (!entry) {\n throw new Error(`PrimitivesRenderer.setDecoration: unknown kind \"${decoration.kind}\"`);\n }\n\n const targetKind: DecorationTarget = shape ? 'shape' : 'connector';\n if (entry.target !== 'both' && entry.target !== targetKind) {\n throw new Error(\n `PrimitivesRenderer.setDecoration: kind \"${decoration.kind}\" targets ` +\n `\"${entry.target}\" but host is a ${targetKind}`,\n );\n }\n\n const z = slotZIndex(slot);\n if (shape) {\n const ctor = entry.ctor as ShapeDecorationCtor;\n const deco = new ctor(decoration.style);\n shape.shape.gfx.sortableChildren = true;\n // Aggregate must include the new decoration's contribution — set it\n // into the map first so `aggregateShapeOuterExtent` picks it up, then\n // mount.\n decorations.set(slot, deco);\n const outerDecorationExtent = this.aggregateShapeOuterExtent(shape);\n const host: ShapeDecorationHostInfo = {\n hostId: targetId,\n slot,\n slotZIndex: z,\n bounds: shape.shape.bounds(),\n surface: shape.shape.gfx,\n shape: shape.shape,\n outerDecorationExtent,\n };\n deco.mount(host);\n if (typeof deco.tick === 'function') {\n this.animated.add(deco as AnimatedDecoration);\n }\n if (decoHasSetResolution(deco)) this.labelBearingDecorations.add(deco);\n this.applyTrackedLabelResolution(deco);\n // Refresh siblings so any LabelDecoration on this host re-flows past\n // the new ring / halo. Skip the just-mounted decoration — we already\n // gave it the up-to-date aggregate above.\n this.refreshShapeDecorations(shape, deco);\n } else {\n const ctor = entry.ctor as ConnectorDecorationCtor;\n const deco = new ctor(decoration.style);\n connector!.connector.gfx.sortableChildren = true;\n const host: ConnectorDecorationHostInfo = {\n hostId: targetId,\n slot,\n slotZIndex: z,\n path: connector!.path,\n surface: connector!.connector.gfx,\n connector: connector!.connector,\n connectorSpec: connector!.spec,\n };\n deco.mount(host);\n decorations.set(slot, deco);\n if (typeof deco.tick === 'function') {\n this.animated.add(deco as AnimatedDecoration);\n }\n if (decoHasSetResolution(deco)) this.labelBearingDecorations.add(deco);\n this.applyTrackedLabelResolution(deco);\n // Now that the decoration is in the map, re-aggregate padding and\n // re-route the path. `recomputeConnectorPath` redraws the body /\n // markers on the trimmed path and refreshes every decoration\n // (including the one we just mounted) with the new host info.\n this.recomputeConnectorPath(connector!);\n }\n }\n\n // ─── Effects ────────────────────────────────────────────────────────────\n\n /**\n * Attach (or detach with `null`) an effect to a shape at the given slot.\n * Effects don't draw — they modulate the host shape's transform and/or\n * style. Multiple effects per host stack: transform deltas compose\n * additively (translations + rotation) and multiplicatively (scale);\n * style channels are last-writer-wins per channel by insertion order.\n *\n * Connector effects are supported and modulate the host connector's\n * style channels (tint + alpha). Transform deltas on a path-resolved\n * primitive have no coherent meaning, so transform effects on connector\n * hosts are ignored at aggregation time.\n */\n setEffect<TStyle = unknown>(\n targetId: string,\n slot: string,\n effect: EffectSpec<TStyle> | null,\n ): void {\n const shape = this.shapeInstances.get(targetId);\n if (shape) {\n this.setShapeEffect(shape, targetId, slot, effect);\n return;\n }\n const connector = this.connectorInstances.get(targetId);\n if (connector) {\n this.setConnectorEffect(connector, targetId, slot, effect);\n return;\n }\n throw new Error(`PrimitivesRenderer.setEffect: unknown target \"${targetId}\"`);\n }\n\n private setShapeEffect<TStyle>(\n shape: ShapeInstance,\n targetId: string,\n slot: string,\n effect: EffectSpec<TStyle> | null,\n ): void {\n const prev = shape.effects.get(slot);\n if (prev) this.disposeEffect(prev);\n\n if (effect === null) {\n shape.effects.delete(slot);\n if (shape.effects.size === 0) {\n this.hostsWithEffects.delete(shape);\n this.resetHostToBaseline(shape);\n }\n return;\n }\n\n const entry = this.effectRegistry.get(effect.kind);\n if (!entry) {\n throw new Error(`PrimitivesRenderer.setEffect: unknown kind \"${effect.kind}\"`);\n }\n if (entry.target !== 'both' && entry.target !== 'shape') {\n throw new Error(\n `PrimitivesRenderer.setEffect: kind \"${effect.kind}\" targets \"${entry.target}\" but host is a shape`,\n );\n }\n\n const fx = new (entry.ctor as ShapeEffectCtor)(effect.style) as IShapeEffect;\n const host: ShapeEffectHostInfo = {\n hostId: targetId,\n slot,\n bounds: shape.shape.bounds(),\n shape: shape.shape,\n };\n fx.mount(host);\n shape.effects.set(slot, fx);\n this.hostsWithEffects.add(shape);\n if (typeof fx.tick === 'function') {\n this.animatedEffects.add(fx as AnimatedEffect);\n }\n this.applyEffectsToHost(shape);\n }\n\n private setConnectorEffect<TStyle>(\n connector: ConnectorInstance,\n targetId: string,\n slot: string,\n effect: EffectSpec<TStyle> | null,\n ): void {\n const prev = connector.effects.get(slot);\n if (prev) this.disposeEffect(prev);\n\n if (effect === null) {\n connector.effects.delete(slot);\n if (connector.effects.size === 0) {\n this.connectorHostsWithEffects.delete(connector);\n this.resetConnectorToBaseline(connector);\n }\n return;\n }\n\n const entry = this.effectRegistry.get(effect.kind);\n if (!entry) {\n throw new Error(`PrimitivesRenderer.setEffect: unknown kind \"${effect.kind}\"`);\n }\n if (entry.target !== 'both' && entry.target !== 'connector') {\n throw new Error(\n `PrimitivesRenderer.setEffect: kind \"${effect.kind}\" targets \"${entry.target}\" but host is a connector`,\n );\n }\n\n const fx = new (entry.ctor as ConnectorEffectCtor)(effect.style) as IConnectorEffect;\n const host: ConnectorEffectHostInfo = {\n hostId: targetId,\n slot,\n connector: connector.connector,\n };\n fx.mount(host);\n connector.effects.set(slot, fx);\n this.connectorHostsWithEffects.add(connector);\n if (typeof fx.tick === 'function') {\n this.animatedEffects.add(fx as AnimatedEffect);\n }\n this.applyEffectsToConnector(connector);\n }\n\n // ─── Badges ─────────────────────────────────────────────────────────────\n\n /**\n * Attach a badge to a host shape. The badge is registered as a real shape\n * under id `` `${hostId}:${slot}` `` so it inherits every shape capability —\n * any registered shape kind as the plate, any `ShapeFillLayer` as content\n * (solid / image / glyph / svg / svg-url), and any registered decoration\n * via the `decorations` field.\n *\n * On `updateShape(hostId, …)` every attached badge re-anchors automatically.\n * On `removeShape(hostId)` every attached badge is removed first.\n *\n * Calling `setBadge` with the same `(hostId, slot)` replaces the previous\n * badge (the old badge shape and any of its decorations are destroyed).\n */\n setBadge(hostId: string, slot: string, options: BadgeOptions): void {\n const shapeHost = this.shapeInstances.get(hostId);\n const connectorHost = shapeHost ? undefined : this.connectorInstances.get(hostId);\n if (!shapeHost && !connectorHost) {\n throw new Error(`PrimitivesRenderer.setBadge: unknown host \"${hostId}\"`);\n }\n\n const badgeId = badgeIdFor(hostId, slot);\n if (this.shapeInstances.has(badgeId)) this.removeShape(badgeId);\n\n // Instantiate at (0, 0); read `bounds()` from the live shape instance\n // (works for any registered shape kind without a separate bounds-from-spec\n // contract) and update to the resolved world position synchronously.\n // No render frame happens between the two calls, so the (0, 0) position\n // is never observed by the user.\n this.addShape(badgeId, { ...options.shape, x: 0, y: 0 } as unknown as BaseShapeSpec);\n const badge = this.shapeInstances.get(badgeId)!;\n\n if (shapeHost) {\n const pos = resolveBadgePosition(\n this.shapeWorldBounds(shapeHost),\n badge.shape.bounds(),\n options,\n );\n this.updateShape(badgeId, { x: pos.x, y: pos.y });\n } else {\n const clearance = this.connectorBadgeEndpointClearance(connectorHost!);\n const pos = resolveConnectorBadgePosition(\n connectorHost!.path,\n badge.shape.bounds(),\n options,\n clearance,\n );\n this.updateShape(badgeId, { x: pos.x, y: pos.y, rotation: pos.rotation });\n }\n\n if (options.decorations) {\n for (const [decoSlot, decoSpec] of Object.entries(options.decorations)) {\n this.setDecoration(badgeId, decoSlot, decoSpec);\n }\n }\n\n if (options.effects) {\n for (const [effectSlot, effectSpec] of Object.entries(options.effects)) {\n this.setEffect(badgeId, effectSlot, effectSpec);\n }\n }\n\n let map = this.badges.get(hostId);\n if (!map) {\n map = new Map();\n this.badges.set(hostId, map);\n }\n map.set(slot, options);\n }\n\n removeBadge(hostId: string, slot: string): void {\n const map = this.badges.get(hostId);\n if (!map || !map.has(slot)) return;\n const badgeId = badgeIdFor(hostId, slot);\n this.removeShape(badgeId);\n map.delete(slot);\n if (map.size === 0) this.badges.delete(hostId);\n }\n\n hasBadge(hostId: string, slot: string): boolean {\n return this.badges.get(hostId)?.has(slot) ?? false;\n }\n\n /**\n * Recompute every attached badge's `(x, y)` from the host's new bounds.\n * Called from `updateShape` when the host has badges; safe to no-op when\n * the badge map for `hostId` is empty. Shape-host flavour only; see\n * {@link reanchorConnectorBadges} for the connector-path flavour.\n */\n private reanchorBadges(hostId: string): void {\n const map = this.badges.get(hostId);\n if (!map) return;\n const host = this.shapeInstances.get(hostId);\n if (!host) return;\n const hostBounds = this.shapeWorldBounds(host);\n for (const [slot, options] of map) {\n const badge = this.shapeInstances.get(badgeIdFor(hostId, slot));\n if (!badge) continue;\n const pos = resolveBadgePosition(hostBounds, badge.shape.bounds(), options);\n this.updateShape(badgeIdFor(hostId, slot), { x: pos.x, y: pos.y });\n }\n }\n\n /**\n * Recompute every attached badge's `(x, y, rotation)` from the connector\n * host's new path. Called from {@link recomputeConnectorPath} whenever\n * the routed path changes (source / target shape moved, anchor / router /\n * waypoints reconfigured, marker insets adjusted).\n */\n private reanchorConnectorBadges(inst: ConnectorInstance, hostId: string): void {\n const map = this.badges.get(hostId);\n if (!map) return;\n const clearance = this.connectorBadgeEndpointClearance(inst);\n for (const [slot, options] of map) {\n const badge = this.shapeInstances.get(badgeIdFor(hostId, slot));\n if (!badge) continue;\n const pos = resolveConnectorBadgePosition(\n inst.path,\n badge.shape.bounds(),\n options,\n clearance,\n );\n this.updateShape(badgeIdFor(hostId, slot), {\n x: pos.x,\n y: pos.y,\n rotation: pos.rotation,\n });\n }\n }\n\n /**\n * Per-endpoint clearance to apply when an endpoint-anchored badge sits\n * on a connector — marker length (so the arrowhead isn't tucked under\n * the badge) plus {@link DEFAULT_ENDPOINT_BADGE_GAP_PX} of visual gap.\n *\n * Independent of decoration `getEndPadding()` (which feeds path-trim\n * for the body stroke); markers paint at the *untrimmed* endpoints, so\n * we have to look at the marker spec directly.\n */\n private connectorBadgeEndpointClearance(\n inst: ConnectorInstance,\n ): { source: number; target: number } {\n const strokeWidth = inst.spec.stroke?.width ?? 1;\n const sourceMarkerInset = inst.spec.sourceMarker\n ? markerInsetFor(this.shapeRegistry, inst.spec.sourceMarker, strokeWidth)\n : 0;\n const targetMarkerInset = inst.spec.targetMarker\n ? markerInsetFor(this.shapeRegistry, inst.spec.targetMarker, strokeWidth)\n : 0;\n return {\n source: sourceMarkerInset + DEFAULT_ENDPOINT_BADGE_GAP_PX,\n target: targetMarkerInset + DEFAULT_ENDPOINT_BADGE_GAP_PX,\n };\n }\n\n // ─── LOD / labels ───────────────────────────────────────────────────────\n\n setLODLevel(id: string, level: number): void {\n const inst = this.shapeInstances.get(id);\n if (!inst) return;\n if (inst.shape.setLODLevel) {\n inst.shape.setLODLevel(level);\n return;\n }\n inst.shape.gfx.visible = level > 0;\n }\n\n rasteriseLabel(id: string, resolution: number): void {\n const inst = this.shapeInstances.get(id);\n if (!inst) return;\n inst.shape.setLabelResolution?.(resolution);\n }\n\n /**\n * Push a rasterisation resolution to every label decoration (shape + edge)\n * currently attached, and remember it so labels mounted later inherit the\n * same fidelity. Driven by zoom-aware behaviours\n * (see `@invana/graph` / `LabelResolutionLODBehaviour`): when the camera\n * zooms past a threshold, push `dpr * zoom` to re-rasterise glyphs sharp.\n *\n * Idempotent: Pixi internally short-circuits `Text.resolution` writes when\n * the value matches, so calling this with the unchanged value every frame\n * is safe and cheap.\n */\n setLabelsResolution(resolution: number): void {\n if (!Number.isFinite(resolution) || resolution <= 0) return;\n // Identity short-circuit — keeps repeat pushes from churning the\n // viewport sweep below.\n if (this.trackedLabelResolution === resolution) return;\n this.trackedLabelResolution = resolution;\n // No iteration here. The frame-tick sweep (see `tickLabelRasterise`)\n // picks up the new target and re-rasters only on-screen labels, plus\n // any that scroll into view later. This bounds the per-frame texture-\n // regen cost to whatever's visible instead of the full dataset.\n }\n\n /**\n * Forward the tracked label resolution to `deco` when it exposes a\n * `setResolution` method. Called on every label mount (so a newly-added\n * label inherits the current resolution immediately, no waiting for the\n * next tier-change to populate it).\n */\n private applyTrackedLabelResolution(deco: IDecorationBase<unknown>): void {\n if (this.trackedLabelResolution === null) return;\n const withResolution = deco as unknown as { setResolution?: (r: number) => void };\n withResolution.setResolution?.(this.trackedLabelResolution);\n }\n\n // ─── Per-frame animation ────────────────────────────────────────────────\n\n tickAnimations(deltaMs: number): void {\n if (this.animated.size > 0) {\n for (const deco of this.animated) {\n const keep = deco.tick(deltaMs);\n if (!keep) this.animated.delete(deco);\n }\n }\n\n if (this.animatedEffects.size > 0) {\n for (const fx of this.animatedEffects) {\n const keep = fx.tick(deltaMs);\n if (!keep) this.animatedEffects.delete(fx);\n }\n }\n\n if (this.hostsWithEffects.size > 0) {\n for (const host of this.hostsWithEffects) {\n this.applyEffectsToHost(host);\n }\n }\n\n if (this.connectorHostsWithEffects.size > 0) {\n for (const host of this.connectorHostsWithEffects) {\n this.applyEffectsToConnector(host);\n }\n }\n\n if (this.trackedLabelResolution !== null && this.labelBearingDecorations.size > 0) {\n this.tickLabelRasterise();\n }\n }\n\n /**\n * Re-raster labels whose current resolution differs from the tracked\n * target, prioritising those currently inside the camera viewport so the\n * tier crossing reads as a fade-into-crispness on what the user is\n * looking at. Off-screen labels are deferred to subsequent ticks but\n * *not* skipped forever — once the in-view set converges, remaining\n * budget rolls over to off-screen labels so panning later lands on\n * already-crisp text. Bounds that come back degenerate (Infinity AABB\n * from a container that hasn't laid out yet) fall through to the second\n * pass and are treated as off-screen for this tick.\n *\n * Convergence: once every label matches the target, the loop is O(N)\n * `getResolution` checks per frame with zero texture work — negligible.\n */\n private tickLabelRasterise(): void {\n const target = this.trackedLabelResolution;\n if (target === null) return;\n const viewport = (this.camera.viewport as unknown as {\n getVisibleBounds: () => { x: number; y: number; width: number; height: number };\n }).getVisibleBounds();\n let budget = PrimitivesRenderer.LABEL_RASTER_PER_TICK;\n // First pass: in-viewport labels.\n const offscreen: Array<{ setResolution: (r: number) => void }> = [];\n for (const deco of this.labelBearingDecorations) {\n if (budget <= 0) break;\n const withRes = deco as unknown as {\n getResolution?: () => number | null;\n setResolution: (r: number) => void;\n gfx?: { getBounds?: () => { x: number; y: number; width: number; height: number } };\n };\n if (withRes.getResolution?.() === target) continue;\n const bounds = withRes.gfx?.getBounds?.();\n const inView = bounds !== undefined && isFiniteRect(bounds) && rectsIntersect(bounds, viewport);\n if (inView) {\n withRes.setResolution(target);\n budget--;\n } else {\n offscreen.push(withRes);\n }\n }\n // Second pass: spend the remaining budget on off-screen labels so they\n // converge in the background. Without this, a brand-new tier would\n // leave every off-screen label permanently stale (its bounds wouldn't\n // change until the camera pans past it).\n for (const deco of offscreen) {\n if (budget <= 0) break;\n deco.setResolution(target);\n budget--;\n }\n }\n\n /**\n * Aggregate every effect attached to `inst` and write the result onto the\n * host gfx. Resets to the spec baseline first so removing effects (or a\n * scale dropping to identity) cleanly reverts. Called every frame for\n * hosts with at least one effect, and synchronously on `setEffect` so\n * non-animated effects take effect immediately.\n */\n private applyEffectsToHost(inst: ShapeInstance): void {\n const { gfx } = inst.shape;\n const spec = inst.spec;\n const baseAlpha = spec.alpha ?? 1;\n const baseX = spec.x;\n const baseY = spec.y;\n\n let dx = 0;\n let dy = 0;\n let dRot = 0;\n let sx = 1;\n let sy = 1;\n let tint = 0xffffff;\n let alphaMul = 1;\n\n for (const fx of inst.effects.values()) {\n if (fx.target === 'transform' && fx.readTransform) {\n const d = fx.readTransform();\n if (d.dx) dx += d.dx;\n if (d.dy) dy += d.dy;\n if (d.dRot) dRot += d.dRot;\n if (d.sx !== undefined) sx *= d.sx;\n if (d.sy !== undefined) sy *= d.sy;\n } else if (fx.target === 'style' && fx.readStyle) {\n const s = fx.readStyle();\n if (s.tint !== undefined) tint = s.tint;\n if (s.alpha !== undefined) alphaMul *= s.alpha;\n }\n }\n\n // Pivot at the shape's local centre so scale and rotation deltas spin\n // around the visual centre (matters for shapes whose local origin isn't\n // the centre — e.g. RectShape is top-left). When scale and rotation are\n // identity, skip the pivot detour to keep the position math trivial.\n const needsCentredPivot = sx !== 1 || sy !== 1 || dRot !== 0;\n if (needsCentredPivot) {\n const b = inst.shape.bounds();\n const cx = b.x + b.width / 2;\n const cy = b.y + b.height / 2;\n gfx.pivot.set(cx, cy);\n gfx.position.set(baseX + dx + cx, baseY + dy + cy);\n } else {\n gfx.pivot.set(0, 0);\n gfx.position.set(baseX + dx, baseY + dy);\n }\n gfx.rotation = (spec.rotation ?? 0) + dRot;\n gfx.scale.set(sx, sy);\n gfx.alpha = baseAlpha * alphaMul;\n // Pixi v8 Container.tint is multiplicative; 0xffffff is identity.\n (gfx as unknown as { tint: number }).tint = tint;\n }\n\n /**\n * Aggregate every effect attached to a connector and write the result onto\n * `connector.gfx`. Resets to the spec baseline first so removing effects\n * cleanly reverts. Only style channels are honoured for connector hosts\n * (transform deltas on a path-resolved primitive have no coherent\n * meaning); transform effects on connectors contribute nothing.\n */\n private applyEffectsToConnector(inst: ConnectorInstance): void {\n const { gfx } = inst.connector;\n const baseAlpha = inst.spec.alpha ?? 1;\n\n let tint = 0xffffff;\n let alphaMul = 1;\n\n for (const fx of inst.effects.values()) {\n if (fx.target === 'style' && fx.readStyle) {\n const s = fx.readStyle();\n if (s.tint !== undefined) tint = s.tint;\n if (s.alpha !== undefined) alphaMul *= s.alpha;\n }\n }\n\n gfx.alpha = baseAlpha * alphaMul;\n (gfx as unknown as { tint: number }).tint = tint;\n }\n\n private resetConnectorToBaseline(inst: ConnectorInstance): void {\n const { gfx } = inst.connector;\n gfx.alpha = inst.spec.alpha ?? 1;\n (gfx as unknown as { tint: number }).tint = 0xffffff;\n }\n\n /** Restore the host gfx to its spec-derived baseline (used after the last effect is removed). */\n private resetHostToBaseline(inst: ShapeInstance): void {\n const { gfx } = inst.shape;\n const spec = inst.spec;\n gfx.pivot.set(0, 0);\n gfx.position.set(spec.x, spec.y);\n gfx.rotation = spec.rotation ?? 0;\n gfx.scale.set(1, 1);\n gfx.alpha = spec.alpha ?? 1;\n (gfx as unknown as { tint: number }).tint = 0xffffff;\n }\n\n // ─── Hit-testing + pointer router ────────────────────────────────────\n\n /**\n * Resolve the hit at a world point under render-order rules. Two\n * priority bands:\n *\n * 1. **Exact geometric hits** — any candidate whose\n * `IHitArea.contains` (shapes) or stroke-tolerance polyline\n * distance (connectors) covers the cursor. Ranked to match what\n * is drawn on top:\n * a. higher `zIndex` wins (mirrors visual stacking);\n * b. on equal `zIndex`, a shape (node) beats a connector (edge)\n * — shapes render above connectors;\n * c. on equal `zIndex` *and* same kind, the closest one to its\n * origin / polyline wins.\n * So a node sitting over an edge takes the hit even when the edge's\n * polyline passes nearer the cursor than the node's centre — and an\n * edge with an explicitly higher `zIndex` still wins.\n * 2. **Floor fallback** — if NO exact hit, return the closest\n * candidate whose origin sits within `hitFloorPx` screen pixels\n * of the cursor. Lets tiny pinpoints stay hoverable in sparse\n * regions without widening hit areas in dense ones.\n *\n * Returns `null` when nothing is hit.\n */\n hitTest(worldX: number, worldY: number, exclude?: ReadonlySet<string>): HitResult | null {\n const floorWorld = this.hitFloorWorld();\n const candidates = this.hit.query(worldX, worldY, floorWorld);\n if (candidates.length === 0) return null;\n\n let bestExact: { kind: 'shape' | 'connector'; id: string; distSq: number; zIndex: number } | null = null;\n let bestFloor: { kind: 'shape' | 'connector'; id: string; distSq: number } | null = null;\n const floorSq = floorWorld * floorWorld;\n\n for (const c of candidates) {\n // Skip excluded ids — e.g. a transient drag preview (rubber-band edge)\n // that sits under the cursor and would otherwise mask the real target.\n if (exclude?.has(c.id)) continue;\n const res = this.geometricHit(c.kind, c.id, worldX, worldY);\n if (!res) continue;\n if (res.exact) {\n // Rank to match render order: zIndex first (higher = on top), then\n // shape-over-connector on a tie (nodes draw above edges), then the\n // closest origin/polyline within the same kind.\n const kindRank = c.kind === 'shape' ? 1 : 0;\n const bestKindRank = bestExact && bestExact.kind === 'shape' ? 1 : 0;\n if (\n bestExact === null ||\n c.zIndex > bestExact.zIndex ||\n (c.zIndex === bestExact.zIndex &&\n (kindRank > bestKindRank ||\n (kindRank === bestKindRank && res.distSq < bestExact.distSq)))\n ) {\n bestExact = { kind: c.kind, id: c.id, distSq: res.distSq, zIndex: c.zIndex };\n }\n } else if (res.distSq <= floorSq) {\n if (bestFloor === null || res.distSq < bestFloor.distSq) {\n bestFloor = { kind: c.kind, id: c.id, distSq: res.distSq };\n }\n }\n }\n\n const winner = bestExact ?? bestFloor;\n return winner ? { kind: winner.kind, id: winner.id } : null;\n }\n\n /**\n * Squared tolerance (world units) for an *exact* connector hit:\n * `(strokeWidth / 2 + slop)²`. The slop adds 4 world units of\n * forgiveness on top of the stroke half-width since 1-px-stroke\n * lines are genuinely hard to click pixel-perfect.\n */\n private connectorHitToleranceSq(inst: ConnectorInstance): number {\n const sw = inst.spec.stroke?.width ?? 1;\n const slop = 4;\n const r = sw / 2 + slop;\n return r * r;\n }\n\n /**\n * Geometric test that returns *both* whether the cursor exactly\n * contains the shape/connector AND the squared distance to the\n * shape's origin (or to the connector's nearest polyline point) —\n * used together by {@link hitTest} for the two-band ranking.\n */\n private geometricHit(\n kind: 'shape' | 'connector',\n id: string,\n worldX: number,\n worldY: number,\n ): { exact: boolean; distSq: number } | null {\n if (kind === 'shape') {\n const inst = this.shapeInstances.get(id);\n if (!inst) return null;\n const dx = worldX - inst.spec.x;\n const dy = worldY - inst.spec.y;\n // World-space distance to the shape's origin — used for closest-\n // wins ranking + the floor-radius fallback. Independent of any\n // `gfx.scale` multiplier the shape carries (the visual centre\n // doesn't move under a uniform scale-about-origin).\n const distSq = dx * dx + dy * dy;\n // The shape's geometric `hitArea` operates in its *local* frame\n // — i.e. before `gfx.scale` is applied. `NodeSizeLODBehaviour`\n // (and `HoverActivateBehaviour.zoomedOutScale`) write `gfx.scale`\n // to inflate visuals without rebuilding geometry, so we must\n // divide world-space deltas by `gfxScale` before consulting\n // `contains` — otherwise a 5×-scaled shape whose visible\n // silhouette covers the cursor reports `false`.\n const s = inst.gfxScale || 1;\n const exact = inst.shape.getHitArea().contains(dx / s, dy / s);\n return { exact, distSq };\n }\n const inst = this.connectorInstances.get(id);\n if (!inst) return null;\n const poly = samplePath(inst.path);\n const distSq = distanceToPolylineSq(poly, worldX, worldY);\n const exact = distSq <= this.connectorHitToleranceSq(inst);\n return { exact, distSq };\n }\n\n /**\n * Attach a single `globalpointer*` listener trio to the renderer's\n * container. Pixi's *global* pointer events fire on every move /\n * down / up regardless of which DisplayObject is under the cursor —\n * so one listener handles the whole renderer's hit-routing.\n *\n * Setting `eventMode = 'static'` on the container is the standard\n * Pixi v8 idiom for opting into the event system; we don't set a\n * `hitArea` because the container itself is never the dispatch\n * target — we delegate to {@link hitTest} on every move/down/up.\n */\n private installPointerRouter(): void {\n this._container.eventMode = 'static';\n // Always-true `hitArea` so the container catches `pointerdown` /\n // `pointerup` for the whole canvas. Without this, Pixi can't find\n // an interactive target on press (every shape's `eventMode` is\n // `'none'` so the router can do its own hit-testing), and our\n // `pointerdown` / `pointerup` listeners below never fire —\n // breaking `DragNodeBehaviour` and anything else that listens for\n // `shape:pointerdown` / `connector:pointerdown`. The container's\n // own pointer events are then routed through `hitTest` exactly\n // like the move stream. `globalpointermove` doesn't need this\n // (the `global` variant fires regardless of hit) but the regular\n // down / up events do.\n this._container.hitArea = { contains: () => true };\n\n // Move events are RAF-coalesced — only the latest pointer position\n // is resolved per frame. Without this, a fast mouse sweep over a\n // dense graph fires hundreds of pickAtWorld + hover-state churns\n // per second, swamping the renderer.\n const onMove = (e: FederatedPointerEvent): void => {\n this.pendingPointerMove = e;\n if (this.pointerMoveRaf !== null) return;\n this.pointerMoveRaf = requestAnimationFrame(() => {\n this.pointerMoveRaf = null;\n const pending = this.pendingPointerMove;\n this.pendingPointerMove = null;\n if (pending) this.routePointerMove(pending);\n });\n };\n const onDown = (e: FederatedPointerEvent): void => this.routePointerDown(e);\n const onUp = (e: FederatedPointerEvent): void => this.routePointerUp(e);\n\n this._container.on('globalpointermove', onMove);\n this._container.on('pointerdown', onDown);\n this._container.on('pointerup', onUp);\n this._container.on('pointerupoutside', onUp);\n\n this.pointerRouterUnsubs.push(\n () => this._container.off('globalpointermove', onMove),\n () => this._container.off('pointerdown', onDown),\n () => this._container.off('pointerup', onUp),\n () => this._container.off('pointerupoutside', onUp),\n );\n }\n\n private routePointerMove(e: FederatedPointerEvent): void {\n // Suppress hover state-changes while a pointer button is held.\n // The currently-hovered target stays highlighted through the\n // drag; on release, the next move resolves the cursor's actual\n // target and fires `pointerover` / `pointerout` normally.\n if (this.pointerDown) return;\n const w = this.camera.toWorld(e.global.x, e.global.y);\n const hit = this.hitTest(w.x, w.y);\n const prev = this.currentHover;\n\n if (hit === null) {\n if (prev) {\n this.events.emit(`${prev.kind}:pointerout`, {\n id: prev.id, worldX: w.x, worldY: w.y,\n });\n this.currentHover = null;\n this.applyHoverCursor(null);\n }\n return;\n }\n\n if (prev && prev.kind === hit.kind && prev.id === hit.id) return;\n\n if (prev) {\n this.events.emit(`${prev.kind}:pointerout`, {\n id: prev.id, worldX: w.x, worldY: w.y,\n });\n }\n this.events.emit(`${hit.kind}:pointerover`, {\n id: hit.id, worldX: w.x, worldY: w.y,\n });\n this.currentHover = hit;\n this.applyHoverCursor(hit);\n }\n\n /**\n * Apply a hover cursor on the canvas DOM element. Skipped when a\n * pointer-capture interaction is in flight (`downHit != null`) so\n * behaviours like `DragNodeBehaviour` that own the cursor during a\n * drag (`'grabbing'`) aren't overridden mid-gesture.\n */\n private applyHoverCursor(hit: { kind: 'shape' | 'connector'; id: string } | null): void {\n if (!this.canvasElement) return;\n if (this.downHit) return;\n this.canvasElement.style.cursor = hit ? 'pointer' : '';\n }\n\n private routePointerDown(e: FederatedPointerEvent): void {\n this.pointerDown = true;\n const w = this.camera.toWorld(e.global.x, e.global.y);\n const hit = this.hitTest(w.x, w.y);\n if (!hit) {\n this.downHit = null;\n return;\n }\n this.events.emit(`${hit.kind}:pointerdown`, {\n id: hit.id, worldX: w.x, worldY: w.y, button: e.button, pointerId: e.pointerId,\n });\n this.downHit = { kind: hit.kind, id: hit.id, button: e.button };\n }\n\n private routePointerUp(e: FederatedPointerEvent): void {\n this.pointerDown = false;\n const w = this.camera.toWorld(e.global.x, e.global.y);\n const hit = this.hitTest(w.x, w.y);\n\n if (!hit) {\n // Right-button release on empty canvas → background context menu.\n // There's no shape/connector to attribute a pointerup/click to, so this\n // is the only event the renderer surfaces for an empty-canvas right-click.\n if (e.button === 2) {\n this.events.emit('background:contextmenu', { worldX: w.x, worldY: w.y });\n }\n this.downHit = null;\n return;\n }\n\n this.events.emit(`${hit.kind}:pointerup`, {\n id: hit.id, worldX: w.x, worldY: w.y, button: e.button, pointerId: e.pointerId,\n });\n\n const down = this.downHit;\n this.downHit = null;\n if (!down) return;\n if (down.kind !== hit.kind || down.id !== hit.id) return;\n if (down.button !== e.button) return;\n\n if (e.button === 0) {\n this.events.emit(`${hit.kind}:click`, {\n id: hit.id, worldX: w.x, worldY: w.y, button: 0,\n });\n // Manual double-click detection — Pixi's federated `e.detail`\n // counter isn't available on `globalpointer*` paths the same way,\n // so we track per-target click timestamps ourselves. 350ms matches\n // common OS double-click intervals; same target required.\n const now = performance.now();\n const last = this.lastLeftClick;\n if (last && last.kind === hit.kind && last.id === hit.id && now - last.t < 350) {\n this.events.emit(`${hit.kind}:doubleclick`, {\n id: hit.id, worldX: w.x, worldY: w.y, button: 0,\n });\n this.lastLeftClick = null;\n } else {\n this.lastLeftClick = { kind: hit.kind, id: hit.id, t: now };\n }\n } else if (e.button === 2) {\n this.events.emit(`${hit.kind}:contextmenu`, {\n id: hit.id, worldX: w.x, worldY: w.y,\n });\n }\n }\n\n /**\n * `hitFloorPx` translated into world units at the current camera scale.\n * The clamp guards against a zero/NaN scale from a misconfigured camera —\n * with a divide-by-zero, the floor would balloon to `Infinity` and every\n * pointer event would hit every shape.\n */\n private hitFloorWorld(): number {\n const scale = this.camera.scale;\n return this.hitFloorPx / Math.max(scale, 1e-6);\n }\n\n // ─── Diagnostics ────────────────────────────────────────────────────────\n\n getRenderStats(): RenderStats {\n return {\n shapes: this.shapeInstances.size,\n connectors: this.connectorInstances.size,\n animatedDecorations: this.animated.size,\n };\n }\n\n get shapeCount(): number {\n return this.shapeInstances.size;\n }\n\n get connectorCount(): number {\n return this.connectorInstances.size;\n }\n\n hasShape(id: string): boolean {\n return this.shapeInstances.has(id);\n }\n\n /**\n * Kind of the currently-installed shape with id `id`, or `undefined`\n * if no shape with that id exists.\n *\n * `GraphLayer.rerenderNode` / `updateNodeShape` use this to decide\n * between an instance-preserving `updateShape` (when the rebuilt spec\n * has the same kind — the common case) and a `removeShape + addShape`\n * fallback (when the kind changed, e.g. `circle` → `rect`, which\n * `updateShape` can't handle since the underlying `IShape` class is\n * fixed at construction time).\n */\n getShapeKind(id: string): string | undefined {\n return this.shapeInstances.get(id)?.spec.kind;\n }\n\n /**\n * Local AABB for the registered shape `kind`, derived from `spec` alone\n * without instantiating the shape's Pixi `Graphics`. Returns `undefined`\n * when the kind isn't registered, or when the registered ctor doesn't\n * implement `static boundsOf`.\n *\n * `spec.x` / `spec.y` are ignored — the returned rect is in the shape's\n * local (centre-relative) frame, so callers can reuse the same width /\n * height for every positioned instance of the kind. To get world-space\n * bounds for a mounted instance, use {@link getShapeWorldBounds}\n * instead.\n *\n * The argument's only required field is `kind`; pass either a full\n * positioned spec (with `x` / `y` / paint) or a bare shape-options\n * record (geometry only — `NodeStyle.shape` from `@invana/graph`).\n * Either way the shape's static `boundsOf` reads only its own\n * geometry params.\n *\n * Consumers (minimap footprint estimation, layouts that need node\n * sizes, label-collision pre-pass, the LOD behaviours) call this so\n * they don't have to switch over a closed kind enum — built-in shapes\n * and shapes registered at runtime via {@link registerShape} both\n * flow through the same hook.\n */\n boundsOfSpec(spec: { readonly kind: string }): Rect | undefined {\n const Ctor = this.shapeRegistry.get(spec.kind);\n return Ctor?.boundsOf?.(spec as never);\n }\n\n /**\n * Uniformly-scaled partial of the registered shape `kind`, with\n * geometry params multiplied by `factor`. Aspect ratio, angular\n * range, and vertex topology are preserved. Returns `undefined`\n * when the kind isn't registered or its ctor doesn't implement\n * `static scaleSpec`.\n *\n * The contract pairs with {@link boundsOfSpec}: scaling by `k`\n * scales the AABB exactly by `k`. Callers compose the returned\n * partial with paint channels (`fill` / `stroke`) and position\n * (`x` / `y`) themselves.\n *\n * Used by `NodeSizeLODBehaviour` to rewrite shape size as the\n * camera zooms, without switching over a closed kind enum. Shapes\n * that don't implement `scaleSpec` are simply skipped by the\n * LOD writer.\n */\n scaleShapeSpec(spec: { readonly kind: string }, factor: number): Record<string, unknown> | undefined {\n const Ctor = this.shapeRegistry.get(spec.kind);\n return Ctor?.scaleSpec?.(spec as never, factor) as Record<string, unknown> | undefined;\n }\n\n hasConnector(id: string): boolean {\n return this.connectorInstances.has(id);\n }\n\n /**\n * Currently-mounted decoration instance for shape (or connector) `id` at\n * `slot`, or `undefined` when no decoration is attached at that slot.\n *\n * Domain behaviours read this when they need to introspect a decoration's\n * exposed state — e.g. `CollapseExpandBehaviour` calls\n * `getDecoration(nodeId, 'collapse-toggle')` and reads the toggle's\n * cached hit geometry to test a pointer click against the button's\n * shape-local centre + radius.\n *\n * The returned object is the live `IDecorationBase` — callers should\n * treat it as read-only and not mutate the decoration's `style` directly\n * (use `setDecoration` to swap the style atomically).\n */\n getDecoration(id: string, slot: string): IDecorationBase<unknown> | undefined {\n const shape = this.shapeInstances.get(id);\n const connector = this.connectorInstances.get(id);\n if (!shape && !connector) return undefined;\n return (shape ?? connector!).decorations.get(slot) as IDecorationBase<unknown> | undefined;\n }\n\n /**\n * Densified polyline of the routed connector's path, in world coordinates,\n * or `null` when no connector with that id exists. Returns the same point\n * set used internally for hit-testing — so curved / orthogonal / bezier\n * connectors hand back their true visible silhouette, not the straight\n * source-to-target line.\n *\n * Domain-free read accessor for overview layers (e.g. `MiniMapLayer`) that\n * need to render the actual routed shape without re-running the router.\n * Cheap: only samples the cached `inst.path`; no router invocation.\n */\n getConnectorPolyline(id: string): readonly Point[] | null {\n const inst = this.connectorInstances.get(id);\n if (!inst) return null;\n return samplePath(inst.path);\n }\n\n /**\n * Local-space AABB of a decoration's gfx container in world coordinates\n * (origin offset by the host). Returns `null` when no host or slot exists.\n *\n * Cheaper to call than `getGlobalBounds` because we don't traverse the\n * scene; just take the decoration's local bounds and offset by its\n * position. Used by `LabelCollisionBehaviour` and any other behaviour\n * that needs per-decoration screen geometry.\n */\n getDecorationWorldBounds(targetId: string, slot: string): Rect | null {\n const host =\n this.shapeInstances.get(targetId) ?? this.connectorInstances.get(targetId);\n if (!host) return null;\n const deco = host.decorations.get(slot);\n if (!deco) return null;\n const g = (deco as { gfx?: Container }).gfx;\n if (!g) return null;\n const lb = g.getLocalBounds();\n // Decoration gfx is parented to the host's gfx. The host's gfx has the\n // host position applied (shape: spec.x/y, connector: 0). Combine to get\n // world-space.\n const hostX = (host as { spec?: { x?: number; y?: number } }).spec?.x ?? 0;\n const hostY = (host as { spec?: { x?: number; y?: number } }).spec?.y ?? 0;\n return {\n x: hostX + g.position.x + lb.x,\n y: hostY + g.position.y + lb.y,\n width: lb.width,\n height: lb.height,\n };\n }\n\n /**\n * Show / hide a decoration's gfx without destroying it. Used by\n * collision-style behaviours that want to suppress overlapping labels for a\n * frame without paying the cost of re-mounting on the next reveal.\n *\n * No-op when `targetId` / `slot` doesn't resolve.\n */\n setDecorationVisible(targetId: string, slot: string, visible: boolean): void {\n const host =\n this.shapeInstances.get(targetId) ?? this.connectorInstances.get(targetId);\n if (!host) return;\n const deco = host.decorations.get(slot);\n if (!deco) return;\n const g = (deco as { gfx?: Container }).gfx;\n if (g) g.visible = visible;\n }\n\n /**\n * World-space AABB of the registered shape, or `null` when no shape with\n * that id exists. Domain-free read accessor for layer code that needs to\n * query shape geometry without poking at private state — e.g. a graph\n * layer building an obstacle list for an edge's router, a behaviour that\n * wants to fit content to a selection, or a debug overlay.\n */\n getShapeWorldBounds(id: string): Rect | null {\n const inst = this.shapeInstances.get(id);\n return inst ? this.shapeWorldBounds(inst) : null;\n }\n\n /**\n * World-space origin `(spec.x, spec.y)` of the registered shape, or `null`\n * when no shape with that id exists. Counterpart to `getShapeWorldBounds`;\n * use this when a behaviour needs the shape's translation point (drag\n * offset baseline, anchor for an external overlay, etc.).\n */\n getShapePosition(id: string): Point | null {\n const inst = this.shapeInstances.get(id);\n return inst ? { x: inst.spec.x, y: inst.spec.y } : null;\n }\n\n /**\n * World-space geometric **centre** of the registered shape's bounding box,\n * or `null` when no shape with that id exists. Differs from\n * `getShapePosition` for shapes whose local origin isn't the centre\n * (`RectShape` is anchored top-left; `CircleShape` is already centred).\n *\n * This is the canonical \"anchor reference point\" for layer code that wants\n * a uniform centre regardless of shape kind — connector routing, badge\n * placement, fit-to-content, etc.\n */\n getShapeCenter(id: string): Point | null {\n const inst = this.shapeInstances.get(id);\n if (!inst) return null;\n const b = inst.shape.bounds();\n return {\n x: inst.spec.x + b.x + b.width / 2,\n y: inst.spec.y + b.y + b.height / 2,\n };\n }\n\n /**\n * Re-route every registered connector. Useful after a non-endpoint shape\n * moves (e.g. an obstacle) and you want connectors that auto-collect\n * obstacles to update their path.\n *\n * Each call re-runs `routePath` per connector and refreshes the hit index\n * and any connector decorations. Linear in `connectorInstances`; safe to\n * call from drag handlers in typical layouts. Heavy graphs with thousands\n * of edges should prefer a targeted re-route (future).\n */\n reRouteAllConnectors(): void {\n for (const inst of this.connectorInstances.values()) {\n inst.path = this.routePath(inst.spec);\n this.drawConnectorInstance(inst);\n this.indexConnector(inst);\n if (inst.decorations.size > 0) this.refreshConnectorDecorations(inst);\n }\n }\n\n // ─── Teardown ───────────────────────────────────────────────────────────\n\n destroy(): void {\n if (this.pointerMoveRaf !== null) {\n cancelAnimationFrame(this.pointerMoveRaf);\n this.pointerMoveRaf = null;\n }\n this.pendingPointerMove = null;\n for (const fn of this.pointerRouterUnsubs) fn();\n this.pointerRouterUnsubs = [];\n this.currentHover = null;\n this.downHit = null;\n this.lastLeftClick = null;\n this.pointerDown = false;\n for (const id of [...this.shapeInstances.keys()]) this.removeShape(id);\n for (const id of [...this.connectorInstances.keys()]) this.removeConnector(id);\n this.animated.clear();\n this.hit.clear();\n this.events.removeAllListeners();\n }\n\n // ─── Internals ──────────────────────────────────────────────────────────\n\n private shapeWorldBounds(inst: ShapeInstance): Rect {\n const local = inst.shape.bounds();\n const s = inst.gfxScale;\n return {\n x: inst.spec.x + local.x * s,\n y: inst.spec.y + local.y * s,\n width: local.width * s,\n height: local.height * s,\n };\n }\n\n private routePath(spec: BaseConnectorSpec): Path {\n const routerKind = spec.router ?? 'straight';\n const router = this.routerRegistry.get(routerKind);\n if (!router) {\n throw new Error(`PrimitivesRenderer: unknown router \"${routerKind}\"`);\n }\n const pathStyleKind = spec.pathStyle ?? 'normal';\n const pathStyle = this.pathStyleRegistry.get(pathStyleKind);\n if (!pathStyle) {\n throw new Error(`PrimitivesRenderer: unknown pathStyle \"${pathStyleKind}\"`);\n }\n\n // Pass 1: resolve both endpoints to a stable point (centre for shape\n // endpoints, literal for `kind: 'point'`). The pass-1 point of one\n // endpoint is the `fromPoint` for the other endpoint's anchor in pass 2.\n const sourceCenter = this.endpointCenter(spec.source);\n const targetCenter = this.endpointCenter(spec.target);\n\n // Pass 2: re-resolve each endpoint with its declared anchor.\n const source = this.resolveEndpoint(spec.source, targetCenter);\n const target = this.resolveEndpoint(spec.target, sourceCenter);\n\n // `obstacles` is a memoised getter — routers that don't read it (e.g.\n // `straight`, `orth`) avoid the O(shapes) per-connector cost. Critical\n // when `reanchorAllConnectors` re-routes thousands of straight edges\n // per zoom frame; without laziness the build is O(connectors × shapes).\n const resolveObstacles = (): ReadonlyArray<Obstacle> => this.resolveObstacles(spec);\n let obstaclesCache: ReadonlyArray<Obstacle> | null = null;\n const ctx: RouterCtx = {\n get obstacles(): ReadonlyArray<Obstacle> {\n if (obstaclesCache === null) obstaclesCache = resolveObstacles();\n return obstaclesCache;\n },\n };\n const polyline = router(source, target, spec.waypoints, spec.routerOpts, ctx);\n return pathStyle(polyline, spec.pathStyleOpts, { source, target });\n }\n\n /**\n * Build the obstacle list passed to the router. By default every shape in\n * the renderer except the source / target shapes (when those endpoints are\n * `kind: 'shape'`) is included. Each obstacle carries its AABB plus an\n * optional `containsInflated` silhouette test (when the shape exposes\n * `obstacleTest`) so routers can hug non-rect silhouettes tightly.\n *\n * Callers can override via `routerOpts.obstacles`:\n * - `'auto'` (default) — auto-collected as above.\n * - `'none'` — empty list; router runs as if no obstacles exist.\n * - `Obstacle[]` / `Rect[]` — verbatim list (used for testing or\n * layer-specific filtering). Plain `Rect` entries are valid because\n * `Obstacle extends Rect`; they fall back to AABB-only marking.\n */\n private resolveObstacles(spec: BaseConnectorSpec): ReadonlyArray<Obstacle> {\n const opt = (spec.routerOpts as\n | { obstacles?: 'auto' | 'none' | ReadonlyArray<Obstacle> }\n | undefined)?.obstacles;\n if (opt === 'none') return [];\n if (Array.isArray(opt)) return opt;\n const excludeIds = new Set<string>();\n if (spec.source.kind === 'shape') excludeIds.add(spec.source.shapeId);\n if (spec.target.kind === 'shape') excludeIds.add(spec.target.shapeId);\n const out: Obstacle[] = [];\n for (const [id, inst] of this.shapeInstances) {\n if (excludeIds.has(id)) continue;\n const bounds = this.shapeWorldBounds(inst);\n const containsInflated = inst.shape.obstacleTest?.();\n out.push({ ...bounds, containsInflated });\n }\n return out;\n }\n\n /**\n * Pass-1 endpoint resolution — stable, anchor-independent reference point.\n * Returns the shape's geometric bounding-box centre in world space (NOT\n * the raw `(spec.x, spec.y)` origin) so the anchor's pass-2 ray cast is\n * uniform across shape kinds.\n */\n private endpointCenter(spec: ConnectorEndpointSpec): Point {\n if (spec.kind === 'point') return { x: spec.x, y: spec.y };\n const inst = this.shapeInstances.get(spec.shapeId);\n if (!inst) {\n throw new Error(`PrimitivesRenderer: connector references unknown shape \"${spec.shapeId}\"`);\n }\n const b = inst.shape.bounds();\n const s = inst.gfxScale;\n return {\n x: inst.spec.x + (b.x + b.width / 2) * s,\n y: inst.spec.y + (b.y + b.height / 2) * s,\n };\n }\n\n /** Pass-2 endpoint resolution — applies the declared anchor for shape endpoints. */\n private resolveEndpoint(spec: ConnectorEndpointSpec, fromPoint: Point): Endpoint {\n if (spec.kind === 'point') {\n return { x: spec.x, y: spec.y, tangent: spec.tangent };\n }\n const inst = this.shapeInstances.get(spec.shapeId);\n if (!inst) {\n throw new Error(`PrimitivesRenderer: connector references unknown shape \"${spec.shapeId}\"`);\n }\n const { name, opts } = normalizeAnchorSpec(spec.anchor);\n const anchor = this.anchorRegistry.get(name);\n if (!anchor) {\n throw new Error(`PrimitivesRenderer: unknown anchor \"${name}\"`);\n }\n const ctx: AnchorCtx = { getShape: (id) => this.anchorShapeRef(id) };\n const result = anchor({ shapeId: spec.shapeId, opts }, fromPoint, ctx);\n\n // Optional outward `padding`: push the endpoint along the anchor's\n // tangent direction. Useful when a halo / glow decoration extends\n // beyond the silhouette and the connector should visibly start at\n // the halo's edge. No-op when the anchor returns no tangent.\n const padding = spec.padding ?? 0;\n if (padding === 0 || !result.tangent) return result;\n return {\n x: result.x + result.tangent.x * padding,\n y: result.y + result.tangent.y * padding,\n tangent: result.tangent,\n };\n }\n\n private anchorShapeRef(id: string): AnchorShapeRef | undefined {\n const inst = this.shapeInstances.get(id);\n if (!inst) return undefined;\n const localBounds = inst.shape.bounds();\n const s = inst.gfxScale;\n const bounds = s === 1\n ? localBounds\n : {\n x: localBounds.x * s,\n y: localBounds.y * s,\n width: localBounds.width * s,\n height: localBounds.height * s,\n };\n // When `gfxScale !== 1` the visible silhouette is a uniform scale of\n // the local geometry around the gfx origin. The anchor passes a\n // `localFromCenter` in *world units* relative to the (scaled) centre;\n // the shape's `boundaryIntersect` interprets its input in *unscaled*\n // local coords. Divide on the way in, multiply on the way out so the\n // returned point lands on the visible silhouette.\n const rawBoundary = inst.shape.boundaryIntersect?.bind(inst.shape);\n const boundaryIntersect = rawBoundary\n ? s === 1\n ? rawBoundary\n : (localFromCenter: Point): Point | null => {\n const p = rawBoundary({ x: localFromCenter.x / s, y: localFromCenter.y / s });\n return p === null ? null : { x: p.x * s, y: p.y * s };\n }\n : undefined;\n return {\n origin: { x: inst.spec.x, y: inst.spec.y },\n bounds,\n center: {\n x: inst.spec.x + bounds.x + bounds.width / 2,\n y: inst.spec.y + bounds.y + bounds.height / 2,\n },\n boundaryIntersect,\n };\n }\n\n private indexConnector(inst: ConnectorInstance): void {\n if (inst.path.length < 2) {\n this.hit.remove(inst.id);\n return;\n }\n const bb = pathBounds(inst.path);\n const sw = inst.spec.stroke?.width ?? 1;\n const slop = 4;\n const pad = sw / 2 + slop;\n this.hit.insert(\n inst.id,\n 'connector',\n {\n x: bb.x - pad,\n y: bb.y - pad,\n width: bb.width + pad * 2,\n height: bb.height + pad * 2,\n },\n inst.spec.zIndex ?? 0,\n );\n }\n\n private refreshShapeDecorations(\n inst: ShapeInstance,\n skip?: IDecorationBase<ShapeDecorationHostInfo>,\n ): void {\n const bounds = inst.shape.bounds();\n const outerDecorationExtent = this.aggregateShapeOuterExtent(inst);\n for (const [slot, deco] of inst.decorations) {\n if (deco === skip) continue;\n if (!deco.update) continue;\n const host: ShapeDecorationHostInfo = {\n hostId: inst.id,\n slot,\n slotZIndex: slotZIndex(slot),\n bounds,\n surface: inst.shape.gfx,\n shape: inst.shape,\n outerDecorationExtent,\n };\n deco.update(host);\n }\n }\n\n private refreshConnectorDecorations(inst: ConnectorInstance): void {\n for (const [slot, deco] of inst.decorations) {\n if (!deco.update) continue;\n const host: ConnectorDecorationHostInfo = {\n hostId: inst.id,\n slot,\n slotZIndex: slotZIndex(slot),\n path: inst.path,\n surface: inst.connector.gfx,\n connector: inst.connector,\n connectorSpec: inst.spec,\n };\n deco.update(host);\n }\n }\n\n private disposeDecoration(deco: IDecorationBase<unknown>): void {\n if ('tick' in deco && typeof deco.tick === 'function') {\n this.animated.delete(deco as AnimatedDecoration);\n }\n if (decoHasSetResolution(deco)) this.labelBearingDecorations.delete(deco);\n deco.destroy?.();\n }\n\n private disposeEffect(fx: IShapeEffect | IConnectorEffect): void {\n if (typeof fx.tick === 'function') {\n this.animatedEffects.delete(fx as AnimatedEffect);\n }\n fx.destroy?.();\n }\n}\n\n// ─── Slot z-band ────────────────────────────────────────────────────────────\n//\n// Decoration slots stack in a fixed visual order regardless of insertion order.\n// Built-in slot names get well-known z-indices; unrecognised names fall into\n// a default mid-band so callers can pick custom slot names without breaking\n// ordering.\n//\n// Layout (bottom → top):\n// glow −300\n// halo −200\n// breathing −150\n// pulse −100\n// pulse-ring −80\n// ring −50\n// <shape> 0\n// liquid 20 (fills inside silhouette, above shape body)\n// <other> 50 (mid-band)\n// badge 300\n// fx 400\n\nconst SLOT_Z_TABLE: Readonly<Record<string, number>> = {\n glow: -300,\n halo: -200,\n breathing: -150,\n pulse: -100,\n 'pulse-ring': -80,\n ring: -50,\n liquid: 20,\n label: 200,\n badge: 300,\n fx: 400,\n};\n\nconst SLOT_Z_DEFAULT = 50;\n\nfunction slotZIndex(slot: string): number {\n return SLOT_Z_TABLE[slot] ?? SLOT_Z_DEFAULT;\n}\n\n/** Stable id mapping `(hostId, slot)` → badge shape id. */\nfunction badgeIdFor(hostId: string, slot: string): string {\n return `${hostId}:${slot}`;\n}\n\n/** Resolve an `AnchorSpec` (string or object form) to a `(name, opts)` pair. */\nfunction normalizeAnchorSpec(\n spec: AnchorSpec | undefined,\n): { name: string; opts?: Readonly<Record<string, unknown>> } {\n if (spec === undefined) return { name: 'center' };\n if (typeof spec === 'string') return { name: spec };\n return { name: spec.name, opts: spec.opts };\n}\n\n/**\n * Duck-type check for the `setResolution` hook used by label decorations\n * (`LabelDecoration` / `LabelConnectorDecoration`). Other decoration kinds\n * don't implement it, so the viewport-clipped rasterisation sweep can\n * skip them cheaply.\n */\nfunction decoHasSetResolution(deco: IDecorationBase<unknown>): boolean {\n return typeof (deco as { setResolution?: unknown }).setResolution === 'function';\n}\n\n/** AABB intersection in screen / world coords. Half-open on the far edges. */\nfunction rectsIntersect(\n a: { x: number; y: number; width: number; height: number },\n b: { x: number; y: number; width: number; height: number },\n): boolean {\n return (\n a.x < b.x + b.width &&\n a.x + a.width > b.x &&\n a.y < b.y + b.height &&\n a.y + a.height > b.y\n );\n}\n\n/**\n * Pixi v8's `Container.getBounds()` returns an Infinity-AABB for containers\n * whose content hasn't been laid out yet (no children with renderable\n * geometry attached). Filter those out — the label decoration just got\n * mounted; its real bounds will resolve on the next tick.\n */\nfunction isFiniteRect(r: { x: number; y: number; width: number; height: number }): boolean {\n return (\n Number.isFinite(r.x) &&\n Number.isFinite(r.y) &&\n Number.isFinite(r.width) &&\n Number.isFinite(r.height)\n );\n}\n","/**\n * `loadIconFont` — inject an icon-font stylesheet at runtime, then await\n * font readiness so the very first paint rasterises against the real\n * webfont (not a fallback with the wrong metrics).\n *\n * The mechanic:\n *\n * 1. Attaching `<link rel=\"stylesheet\" href=…>` kicks off:\n * stylesheet download → CSS parse → `@font-face` registration → WOFF\n * fetch.\n * 2. The browser's `FontFaceSet` only knows about the family **after**\n * the `@font-face` declaration is parsed — calling\n * `document.fonts.load(…)` before that returns an empty result.\n * 3. So we wait for the link's `load` event first, then ask the\n * `FontFaceSet` to actually load the face.\n *\n * Vendor-agnostic: takes any stylesheet URL and any font-family name. The\n * canvas library does not know about Font Awesome / Material Symbols /\n * Phosphor / Heroicons / etc. — consumers point this at whichever icon\n * font (or regular webfont) they want.\n *\n * @example\n * ```ts\n * await loadIconFont(\n * 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css',\n * 'Font Awesome 6 Free',\n * );\n * // now safe to render `{ kind: 'glyph', char: '', fontFamily: 'Font Awesome 6 Free', fontWeight: 900 }`.\n * ```\n *\n * Idempotent: subsequent calls with the same `stylesheetUrl` reuse the\n * existing `<link>` element. Safe to call from N stories that all use the\n * same icon font.\n *\n * SSR-safe: a no-op when `document` is undefined.\n */\nexport async function loadIconFont(\n stylesheetUrl: string,\n fontFamilyToProbe?: string,\n fontWeightToProbe?: number | string,\n fontStyleToProbe?: 'normal' | 'italic',\n): Promise<void> {\n if (typeof document === 'undefined') return;\n\n const dedupeKey = encodeURIComponent(stylesheetUrl);\n await ensureStylesheet(stylesheetUrl, dedupeKey);\n\n if (fontFamilyToProbe && document.fonts) {\n // CSS font shorthand: [style] [weight] size family. Including the\n // weight matters for icon fonts that pack different glyph sets per\n // weight (e.g. Font Awesome 6 Free Solid = 900, Regular = 400).\n const style = fontStyleToProbe ?? '';\n const weight = fontWeightToProbe ?? '';\n const probe = `${style} ${weight} 16px \"${fontFamilyToProbe}\"`.trim().replace(/\\s+/g, ' ');\n await document.fonts.load(probe);\n }\n}\n\nfunction ensureStylesheet(href: string, dedupeKey: string): Promise<void> {\n const selector = `link[data-icon-font=\"${cssEscape(dedupeKey)}\"]`;\n const existing = document.querySelector<HTMLLinkElement>(selector);\n if (existing) {\n if (existing.sheet) return Promise.resolve();\n return new Promise((resolve, reject) => {\n existing.addEventListener('load', () => resolve(), { once: true });\n existing.addEventListener(\n 'error',\n () => reject(new Error(`loadIconFont: stylesheet load failed: ${href}`)),\n { once: true },\n );\n });\n }\n\n return new Promise((resolve, reject) => {\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = href;\n link.dataset.iconFont = dedupeKey;\n link.onload = () => resolve();\n link.onerror = () => reject(new Error(`loadIconFont: stylesheet load failed: ${href}`));\n document.head.appendChild(link);\n });\n}\n\nfunction cssEscape(s: string): string {\n if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(s);\n return s.replace(/[^a-zA-Z0-9_-]/g, '\\\\$&');\n}\n"]}