@statelyai/flow 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,7 +14,7 @@ npm install @statelyai/flow @statelyai/graph @xstate/store
14
14
 
15
15
  `@statelyai/graph` is a peer dependency — you bring your own version.
16
16
 
17
- If you want DOM helpers such as `attachContainer()` and `createMeasurementObserver()`, also install `@statelyai/flow-dom`.
17
+ If you want DOM helpers such as `attachContainer()` and `createMeasurementObserver()`, install `@statelyai/flow-dom`; it installs and re-exports the core package.
18
18
 
19
19
  ## Quick start
20
20
 
@@ -39,13 +39,11 @@ const flow = createFlow({
39
39
  // Read state
40
40
  const { graph, viewport, selection } = flow.getContext();
41
41
 
42
- // Trigger events
43
- flow.trigger.select({ ids: ['a'], mode: 'single' });
44
- flow.trigger.panBy({ x: 100, y: 0 });
45
- flow.trigger.dragStart({ id: 'a' });
46
- flow.trigger.dragMove({ dx: 10, dy: 20 });
47
- flow.trigger.dragEnd();
48
- flow.trigger.commitDrag();
42
+ // Use the public controller namespaces
43
+ flow.selection.set(['a']);
44
+ flow.viewport.panBy({ x: 100, y: 0 });
45
+ flow.nodes.setData('a', { label: 'Selected' });
46
+ flow.view.setScope({ parentId: null, depth: 1 });
49
47
 
50
48
  // Query derived state through the engine-backed controller
51
49
  const selectedBounds = flow.getSelectionBounds();
@@ -60,12 +58,105 @@ The canonical data model is `VisualGraph` from `@statelyai/graph`. Flow extends
60
58
 
61
59
  <!-- flow entity types from src/types.ts -->
62
60
 
63
- - **`FlowNode`** — `VisualNode` + `{ dx, dy, style, ports, hidden, selectable, draggable, connectable, deletable, resizable }` for drag offsets, style overrides, and per-entity behavior
64
- - **`FlowEdge`** — `VisualEdge` + `{ label, sourcePort, targetPort, kind, style, labelAnchor }` for edge labels, port binding, and edge styling
61
+ - **`FlowNode`** — `VisualNode` + `{ kind, dx, dy, style, ports, autoSize, autoSizeAnchor, resize, hidden, selectable, draggable, connectable, deletable, resizable }` for application-defined rendering kinds, drag offsets, DOM-owned sizing, anchor policy, style overrides, resize constraints, and per-entity behavior. Keep the structural `type` equal to `"node"`; use `kind` for variants such as `state` or `annotation`.
62
+ - **`FlowEdge`** — `VisualEdge` + `{ label, waypoints, sourcePort, targetPort, kind, style, labelAnchor }` for edge labels, editable route points, port binding, and edge styling; `label.autoSize` makes rendered DOM own transient label dimensions without overwriting authored fallback `width`/`height`; inherited edge `x/y/width/height` are reserved, while positioned edge content belongs on `label`
65
63
  - **`FlowGraph`** — `VisualGraph` with `FlowNode[]` and `FlowEdge[]`
66
- - **`FlowAddressable`** — descriptor for a node, edge, port, or block resolved by id
64
+ - **`FlowEntityRef`** — descriptor for a node, edge, port, or block resolved by id. `FlowAddressable` is a deprecated alias.
67
65
 
68
- Positions use a two-layer system: `x/y` from layout, `dx/dy` from user drag. Visual position = `(x + dx, y + dy)`.
66
+ Positions use a two-layer system: `x/y` from layout, `dx/dy` from user drag. Visual position = `(x + dx, y + dy)`. Paint order uses hierarchy depth, per-entity `zIndex`, and selected elevation.
67
+
68
+ For DOM-owned nodes, `autoSizeAnchor` is `'top-left'` by default. Use
69
+ `'center'` to preserve the visual center, or `{ x: 0.5, y: 0 }` to preserve
70
+ only the horizontal center. Fractions must be finite and within `0..1`.
71
+ Node measurements, including their anchor correction, and `label.autoSize`
72
+ measurements remain derived session state: they emit no graph commit, create no
73
+ undo entry, and do not overwrite authored dimensions. Auto-size label
74
+ measurements drive routing, graph/selection bounds, hit testing, snapping,
75
+ culling, and toolbar anchors; surviving measurements remain stable across
76
+ `replaceGraph()` calls.
77
+
78
+ ## Graph projections
79
+
80
+ <!-- graph projection types from src/projections.ts -->
81
+
82
+ A projection is derived data addressed to graph entities; a mapper decorates nodes/edges from that data; Flow composes multiple active projections into final visual attrs.
83
+
84
+ - **`GraphProjection`** — `{ id, label?, nodes?, edges? }`, with `nodes`/`edges` keyed by existing entity ids
85
+ - **`GraphProjectionMapper`** — maps projected node/edge datum to visual attrs
86
+ - **`ActiveGraphProjection`** — `{ projection, mapper, priority? }`
87
+ - **`GraphNodeAttrs` / `GraphEdgeAttrs`** — visual attrs such as class, style, color, opacity, stroke width, labels, badges, and tooltips
88
+
89
+ Composition is deterministic: lower priority first, then array order. Attrs merge shallowly, `className` concatenates, `style` merges with later values winning, scalar attrs later-win, and badges/tooltips aggregate.
90
+
91
+ `createFlow({ projections })` can own the active projection list directly. Use `flow.projections.set()`, `flow.projections.add()`, `flow.projections.remove(id)`, `flow.projections.clear()`, `flow.projections.subscribe(listener)`, and `flow.projections.getAttrs()` when projections are application state rather than a render prop. Projection data for missing graph ids is ignored.
92
+
93
+ ## Graph traversal
94
+
95
+ <!-- graph traversal helpers from src/graph-index.ts and src/createFlow.ts -->
96
+
97
+ Use `getIncomers(graph, id)`, `getOutgoers(graph, id)`, `getConnectedEdges(graph, ids)`, and `getNeighbors(graph, id)` for common adjacency queries. The same helpers are available on `flow` for the current graph. Node-returning helpers skip dangling endpoints and return unique nodes in graph order. `flow.connections.get({ nodeId, port?, direction? })` returns endpoint addresses and edges in stable graph order.
98
+
99
+ ## Structural views
100
+
101
+ <!-- structural view API from src/view.ts and src/createFlow.ts -->
102
+
103
+ `flow.view` scopes the canonical graph without changing it or mixing structural
104
+ visibility with visual projections/highlights. The default scope is
105
+ `{ parentId: null, depth: null }`, preserving the full visible graph.
106
+
107
+ ```ts
108
+ flow.view.setScope(
109
+ { parentId: 'compound', depth: 1 },
110
+ { selection: 'prune' },
111
+ );
112
+
113
+ const { nodes, edges, boundaryEndpoints } = flow.view.getEntities();
114
+ ```
115
+
116
+ Depth `1` exposes direct children, `2` includes grandchildren, `0` is an empty
117
+ view, and `null` is unlimited. Edges owned by the exposed containers are
118
+ included. Endpoints below the depth boundary are lifted to their visible
119
+ ancestor; those returned edge objects are frozen clones, while the canonical
120
+ edge remains unchanged. `getBoundaryEndpoints(edgeId)` reports both original
121
+ and view endpoint ids.
122
+
123
+ Changing scope validates the parent/depth atomically and prunes selection to
124
+ the next view by default; use `{ selection: 'clear' }` to clear it. `selection.all()`
125
+ and `viewport.fit()` use the current view. Pass `{ includeHidden: true }` to
126
+ `view.getEntities()` or `selection.all()` when explicitly needed. Active graph
127
+ projections remain controller-owned and independent of the structural view.
128
+
129
+ ## Viewport fit frame
130
+
131
+ <!-- viewport fit-frame API from src/createFlow.ts and src/viewport/index.ts -->
132
+
133
+ Register the unobscured screen-space rectangle when persistent UI overlays
134
+ cover part of the canvas. Fit, center, and zoom commands with no explicit pivot
135
+ then target that frame. The default remains the full, current viewport.
136
+
137
+ ```ts
138
+ flow.viewport.setFitFrame({ x: 320, y: 0, width: 880, height: 800 });
139
+
140
+ flow.viewport.fit();
141
+ flow.viewport.fitBounds(bounds);
142
+ flow.viewport.centerOn({ x: 100, y: 50 });
143
+ flow.viewport.zoomTo(1.5);
144
+
145
+ flow.viewport.setFitFrame(null); // reset to the full viewport
146
+ ```
147
+
148
+ Frames require finite `x`/`y` and positive finite dimensions. A `frame` on
149
+ `fit()`, `fitBounds()`, or `centerOn()` overrides the registered frame for that
150
+ call. `fit()` still composes with the current structural view and its `nodes`
151
+ subset. Animation resolves the same frame-aware target before it begins.
152
+
153
+ Every viewport mutation (`set`, `panBy`, `zoomTo`, `zoomBy`, `fit`,
154
+ `fitBounds`, and `centerOn`) returns `ViewportAnimationControls` with `cancel()`
155
+ and a `done` promise. `done` resolves on completion or cancellation. Immediate
156
+ and targetless commands return already-resolved controls; a targetless command
157
+ also cancels any older animation, so no viewport writes continue after its
158
+ `done`. A newer viewport command or direct low-level viewport write cancels and
159
+ resolves the previous controls.
69
160
 
70
161
  ## Ports
71
162
 
@@ -79,6 +170,10 @@ Ports are based on the visual node port model from `@statelyai/graph`.
79
170
 
80
171
  At runtime, flow expects port rectangles to be available for routing and hit geometry: `x`, `y`, `width`, `height` relative to the node origin. In practice this means the port objects in flow are graph visual ports, with one extra flow-specific field: `side`.
81
172
 
173
+ Connection gestures snap to the nearest valid port inside `engine.connection.radius` (default `24` canvas pixels). In the default `loose` mode, node body targets remain valid fallback targets; `strict` mode requires port targets.
174
+
175
+ For controlled graphs, `reconnectMode({ commit: false, dragThreshold: true, preview: false })` keeps pointer capture, thresholding, auto-pan, target resolution, and lifecycle events in Flow while leaving domain mutation and temporary geometry to the controller. `connectionEnded.reconnectedEdgeId` identifies connected, invalid, and cancelled observer-owned reconnects.
176
+
82
177
  ```ts
83
178
  const graph = {
84
179
  nodes: [
@@ -113,6 +208,64 @@ const graph = {
113
208
  };
114
209
  ```
115
210
 
211
+ ## Selection commands
212
+
213
+ <!-- selection command API from src/createFlow.ts -->
214
+
215
+ `flow.selection.duplicate()` clones selected nodes, their descendants, and
216
+ internal edges through the content/ID remapping pipeline. It retains external
217
+ parents, selects all clones, offsets the duplicated subtree by `{ x: 24, y: 24 }`
218
+ by default, and creates one undo step. Pass `{ offset: { x, y } }` to override.
219
+
220
+ `flow.selection.align('left' | 'right' | 'top' | 'bottom' | 'center-x' |
221
+ 'center-y')` aligns two or more selected nodes. Use
222
+ `flow.selection.distribute('horizontal' | 'vertical')` to space three or more
223
+ nodes evenly while retaining deterministic outer endpoints. Both use exact
224
+ current visual bounds and return `false` without adding history when the
225
+ selection is ineligible or the geometry is already satisfied.
226
+
227
+ ## Layout contract
228
+
229
+ <!-- layout controller API from src/createFlow.ts -->
230
+
231
+ `flow.layout.run(algorithm, options?)` accepts `LayoutRunOptions`: cancellation
232
+ signal, stale-result `force`, structural `scope`, `previousResult`, fixed and
233
+ pinned entity ids, `source`, generic metadata, and optional `animation`.
234
+ Algorithms receive frozen clones of graph/options. The position `Map` shorthand
235
+ remains supported.
236
+
237
+ `LayoutResult` can additionally provide node sizes/bounds, edge-label
238
+ positions/bounds, edge routes, diagnostics, quality metadata, and source.
239
+ `flow.layout.apply(result, options?)` validates all ids and finite geometry
240
+ before mutation, then applies the result atomically as one history step. Fixed
241
+ or pinned entities remain unchanged unless listed in
242
+ `overrideFixedEntityIds`. Granular positions/sizes override matching axes from
243
+ aggregate bounds.
244
+
245
+ Pass `{ animation: { duration, easing? } }` to `run` or `apply` for a transient
246
+ visual transition. The final graph is committed once at the start; animation
247
+ frames never create graph commits or history entries. Both APIs provide
248
+ `animation: { cancel, done }` controls (`apply` returns the controls directly).
249
+ Canceling, replacing, or destroying an animation snaps visual geometry to the
250
+ durable final layout.
251
+
252
+ ## Persistence
253
+
254
+ <!-- serialization API from src/serialize.ts and src/createFlow.ts -->
255
+
256
+ `flow.toJSON()` returns `{ version: 1, graph, viewport, collapsedNodeIds }`. The graph is plain persisted intent: pending node and label drag offsets are folded into `x/y`, `dx/dy` and DOM `measured` sizes are stripped, and `style.customWidth/customHeight` are kept. Selection, hover, connection state, highlights, measurements, and undo history are session state and are not serialized.
257
+
258
+ Use `fromJSON(data, options?)` to create a new controller from saved data, or `flow.load(data)` to validate and replace an existing document atomically. `load()` returns `{ ok: true, value }` or `{ ok: false, error }`. User data is deep-cloned and must be JSON-safe; optional Standard Schema-compatible contracts can validate and migrate it.
259
+
260
+ Use `flow.replaceGraph(graph, options?)` when another model is authoritative and
261
+ continuously projects its graph into Flow. It validates atomically, returns the
262
+ applied `FlowChangeSet` (or `null` for an equal graph), preserves state addressed
263
+ to surviving entities by default, and clears Flow undo/redo history by default.
264
+ Set `retention: 'reset'` to clear graph-scoped session state, or set `history` to
265
+ `'ignore'` or `'record'` when the external synchronization contract requires it.
266
+ Pass `origin` and `transactionId` to suppress feedback loops through `commit`
267
+ events.
268
+
116
269
  ## Store events
117
270
 
118
271
  <!-- all store events from src/store/index.ts -->
@@ -123,14 +276,20 @@ const graph = {
123
276
  |---|---|---|
124
277
  | `createNode` | `{ node: FlowNode }` | Add a node |
125
278
  | `deleteNode` | `{ id }` | Remove node + cascade edges |
279
+ | `updateNode` | `{ id, patch? }` or `{ id, updater? }` | Patch/replace a node without changing id/type/parent |
126
280
  | `updateNodeData` | `{ id, data }` | Merge into node.data |
127
281
  | `createEdge` | `{ edge: FlowEdge }` | Add an edge |
128
282
  | `deleteEdge` | `{ id }` | Remove an edge |
283
+ | `deleteEntities` | `{ nodeIds?, edgeIds? }` | Low-level synchronous deletion of a known entity set |
284
+ | `updateEdge` | `{ id, patch? }` or `{ id, updater? }` | Patch/replace an edge without changing id/type/endpoints/ports |
129
285
  | `updateEdgeData` | `{ id, data }` | Merge into edge.data |
130
286
  | `deleteSelected` | — | Remove all selected nodes + edges |
131
287
  | `setGraph` | `{ graph: FlowGraph }` | Replace entire graph, reset interaction state |
288
+ | `replaceGraph` | `{ graph, retention?, history?, origin?, transactionId? }` | Replace through the external synchronization policy used by `flow.replaceGraph()` |
132
289
  | `reset` | — | Reset store to initial state (preserves viewport size) |
133
290
  | `reparentNode` | `{ id, parentId }` | Move node to new parent |
291
+ | `collapseNode` | `{ id }` | Hide descendants and derive folded boundary edges |
292
+ | `expandNode` | `{ id }` | Show descendants again |
134
293
  | `reconnectEdge` | `{ edgeId, newSourceId?, newTargetId?, newSourcePort?, newTargetPort? }` | Rewire edge endpoints |
135
294
 
136
295
  ### Drag lifecycle
@@ -166,6 +325,7 @@ const graph = {
166
325
  | Event | Payload | Description |
167
326
  |---|---|---|
168
327
  | `setViewport` | `{ x, y, zoom }` | Set viewport directly |
328
+ | `setFitFrame` | `{ frame: { x, y, width, height } \| null }` | Set or reset the persistent screen-space fit frame |
169
329
  | `panBy` | `{ x, y }` | Pan by offset |
170
330
  | `panStart` | `{ x, y }` | Begin pan gesture (screen coords) |
171
331
  | `pan` | `{ x, y }` | Continue pan gesture (screen coords) |
@@ -174,7 +334,7 @@ const graph = {
174
334
  | `setMinZoom` | `{ minZoom }` | Set minimum zoom level |
175
335
  | `setMaxZoom` | `{ maxZoom }` | Set maximum zoom level |
176
336
  | `updateViewportSize` | `{ width, height }` | Report container size |
177
- | `fitView` | `{ padding?, minZoom?, maxZoom?, nodes? }` | Fit all (or specific) nodes in view |
337
+ | `fitView` | `{ padding?, minZoom?, maxZoom?, nodes?, frame? }` | Fit all (or specific) nodes into a target frame |
178
338
  | `pushViewport` / `popViewport` | — | Viewport stack for drill-in/out |
179
339
  | `setTranslateExtent` | `{ extent: [Point, Point] \| null }` | Set pan boundary |
180
340
  | `setNodeExtent` | `{ extent: [Point, Point] \| null }` | Set node drag boundary |
@@ -184,8 +344,8 @@ const graph = {
184
344
  | Event | Payload | Description |
185
345
  |---|---|---|
186
346
  | `connectionStart` | `{ sourceId, sourcePort, position }` | Begin connection gesture |
187
- | `connectionMove` | `{ position, targetId?, targetPort?, isValid? }` | Update in-progress connection |
188
- | `connectionEnd` | `{ target?: ConnectEndTarget }` | End connection gesture (emits `connectionEnded`) |
347
+ | `connectionMove` | `{ position, targetId?, targetPort?, isValid?, invalidReason? }` | Update in-progress connection |
348
+ | `connectionEnd` | `{ target?: ConnectEndTarget }` | End connection gesture (emits `connectionEnded` with `status`) |
189
349
  | `cancelConnection` | — | Cancel connection without emitting |
190
350
  | `setConnectionClickStartHandle` | `{ nodeId, port } \| null` | Set/clear click-to-connect start handle |
191
351
 
@@ -211,10 +371,11 @@ const graph = {
211
371
 
212
372
  | Event | Payload | Description |
213
373
  |---|---|---|
214
- | `setCanvasState` | `{ state: CanvasState }` | Set interaction mode |
374
+ | `setCanvasState` | `{ state: CanvasState }` | Set low-level canvas gesture state |
215
375
  | `setMode` | `{ mode: string }` | Set active profile mode |
216
376
  | `setDragThreshold` | `{ dragThreshold }` | Set pixel threshold before drag starts |
217
377
  | `setAutoPanOptions` | `{ autoPanOnDrag?, autoPanThreshold?, autoPanSpeed? }` | Configure auto-pan behavior |
378
+ | `updateSettings` | `Partial<FlowRuntimeSettings>` | Update runtime store settings in one event |
218
379
  | `setSnapToGrid` | `{ enabled, grid? }` | Enable/disable grid snapping |
219
380
  | `setSnapLines` | `{ enabled, threshold?, spacing? }` | Enable/disable Figma-style alignment guides |
220
381
  | `setColorMode` | `{ colorMode: FlowColorMode }` | Set the preferred UI color mode (`'light'` \| `'dark'` \| `'system'`) |
@@ -224,18 +385,25 @@ const graph = {
224
385
  | Event | Payload | Description |
225
386
  |---|---|---|
226
387
  | `updateParentNodeId` | `{ parentNodeId }` | Drill into/out of nested node |
388
+ | `setViewScope` | `{ parentNodeId, depth, selection, visibleEntityIds }` | Low-level structural scope update; prefer `flow.view.setScope()` |
227
389
 
228
390
  ### Emitted events
229
391
 
230
- Subscribe with `flow.on(type, listener)` or `store.on(type, listener)`.
392
+ Subscribe with `flow.on(type, listener)` or, for the low-level escape hatch, `flow.internals.store.on(type, listener)`.
231
393
 
232
394
  | Event | Payload | Description |
233
395
  |---|---|---|
234
396
  | `graphChanged` | `{ graph, event }` | Graph changed after a mutation |
235
397
  | `viewportChanged` | `{ viewport, event }` | Viewport changed |
236
398
  | `selectionChanged` | `{ selection, event }` | Selection changed |
399
+ | `viewChanged` | `{ scope, event }` | Structural parent/depth changed |
237
400
  | `entitiesDeleted` | `{ ids, event }` | Entities were deleted |
238
- | `connectionEnded` | `ConnectionEndedEvent` | Connection gesture ended |
401
+ | `connectionEnded` | `ConnectionEndedEvent` | Connection gesture ended with `status: 'connected' \| 'cancelled' \| 'invalid'` |
402
+ | `dragStarted` / `dragMoved` / `dragEnded` | `FlowDrag*Event` | Drag gesture milestones; `dragMoved` fires per processed input event |
403
+ | `resizeStarted` / `resizeEnded` | `FlowResize*Event` | Resize gesture milestones |
404
+ | `connectStarted` / `connectMoved` | `FlowConnect*Event` | Connection gesture milestones; `connectMoved` fires per processed input event |
405
+ | `paneClicked` / `paneContextMenu` | `FlowPaneGestureEvent` | Pane click and context menu gestures |
406
+ | `entityClicked` / `entityDoubleClicked` / `entityContextMenu` | `FlowEntityGestureEvent` | Entity click, double-click, and context menu gestures |
239
407
  | `layoutRequested` | `LayoutRequestedEvent` | Layout was requested |
240
408
  | `error` | `{ error, event? }` | Flow error emitted |
241
409
 
@@ -243,7 +411,7 @@ Subscribe with `flow.on(type, listener)` or `store.on(type, listener)`.
243
411
 
244
412
  <!-- undo/redo config from src/store/index.ts UNDOABLE_EVENT_TYPES -->
245
413
 
246
- `@statelyai/flow` uses XState Store's `undoRedo()` extension with a whitelist of committed graph mutation events. Interaction-only events such as selection, panning, live drag updates, and connection hover state are intentionally skipped.
414
+ `@statelyai/flow` uses XState Store's `undoRedo()` extension with a whitelist of committed graph mutation events. Interaction-only events such as selection, panning, live drag updates, and connection hover state are intentionally skipped. Undo/redo restores graph and collapse history while preserving current viewport and valid session state. Cancelled drag/resize gestures create no history entry.
247
415
 
248
416
  ```ts
249
417
  import {
@@ -276,7 +444,7 @@ store.trigger.createNode({
276
444
  store.trigger.undo();
277
445
  ```
278
446
 
279
- Tracked events: `createNode`, `deleteNode`, `updateNodeData`, `createEdge`, `deleteEdge`, `updateEdgeData`, `deleteSelected`, `reparentNode`, `commitDrag`, `resizeEnd`, `reconnectEdge`, `applyLayoutResult`, `bakeLabelPositions`.
447
+ Tracked events: `createNode`, `deleteNode`, `updateNode`, `updateNodeData`, `createEdge`, `deleteEdge`, `updateEdge`, `updateEdgeData`, `deleteSelected`, `reparentNode`, `commitDrag`, `resizeEnd`, `reconnectEdge`, `applyLayoutResult`, `bakeLabelPositions`.
280
448
 
281
449
  ## Viewport utilities
282
450
 
@@ -291,9 +459,12 @@ import {
291
459
  canvasToScreen,
292
460
  getVisibleBounds,
293
461
  viewportForBounds,
462
+ viewportCenteredOn,
463
+ validateFitFrame,
294
464
  panBy,
295
465
  zoomTo,
296
466
  clampZoom,
467
+ animateViewport,
297
468
  } from '@statelyai/flow';
298
469
 
299
470
  const vp = createViewport(); // { x: 0, y: 0, zoom: 1 }
@@ -308,26 +479,45 @@ const screenPoint = canvasToScreen(vp, { x: 100, y: 50 });
308
479
 
309
480
  // Fit content
310
481
  const bounds = getVisibleBounds(vp, { width: 800, height: 600 });
311
- const fitted = viewportForBounds(contentRect, containerSize, { padding: 0.1 });
482
+ const frame = validateFitFrame({ x: 300, y: 0, width: 500, height: 600 });
483
+ const fitted = viewportForBounds(contentRect, containerSize, {
484
+ padding: 0.1,
485
+ frame,
486
+ });
487
+ const centered = viewportCenteredOn(canvasPoint, containerSize, 1, frame);
488
+
489
+ // Animation
490
+ const animation = animateViewport(store, fitted, { duration: 300 });
491
+ await animation.done;
312
492
  ```
313
493
 
314
494
  ## Edge routing
315
495
 
316
496
  <!-- edge routers from src/routing/index.ts -->
317
497
 
318
- Three built-in routers. All return `PathData` (points + source/target direction).
498
+ Four built-in routers. All return `PathData` (points + source/target direction). A custom router may also return `svgPath` to preserve rounded or otherwise custom SVG geometry; `points` remain required for bounds and endpoint handles, and exported `pathToSVG` safely prefers a finite, non-empty override. Edge `waypoints` are ordered interior canvas points passed through `EdgeRouterContext`; built-in routers honor them. Custom `EdgeRouter`s receive the full typed edge plus the exact canonical or projection `graph` currently being routed and a detached, read-only `getEntityBounds(id)` lookup for live node/edge-label geometry. The lookup never routes another edge. Use `configureBezierRouter(options)`, `configureStepRouter(options)`, and `configureAvoidRouter(options)` for customized built-in router variants. `avoidRouter` is opt-in and routes orthogonal polylines around sibling node obstacles.
319
499
 
320
500
  ```ts
321
- import { straightRouter, stepRouter, bezierRouter, pathToSVG } from '@statelyai/flow';
322
-
323
- const path = stepRouter({
324
- sourceRect: { x: 0, y: 0, width: 200, height: 80 },
325
- targetRect: { x: 300, y: 200, width: 200, height: 80 },
326
- sourceDirection: 'bottom',
327
- targetDirection: 'top',
328
- });
329
-
330
- const d = pathToSVG(path); // SVG path d attribute
501
+ import { configureStepRouter, type EdgeRouter } from '@statelyai/flow';
502
+
503
+ type StatechartEdgeData = { transitionType: 'external' | 'internal' };
504
+
505
+ const statechartRouter: EdgeRouter<StatechartEdgeData> = (edge, context) => {
506
+ const source = context.graph.nodes.find((node) => node.id === edge.sourceId);
507
+ const siblingBounds = source?.parentId
508
+ ? context.graph.nodes
509
+ .filter((node) => node.parentId === source.parentId)
510
+ .map((node) => context.getEntityBounds(node.id))
511
+ : [];
512
+
513
+ const offset =
514
+ edge.data.transitionType === 'internal'
515
+ ? 32
516
+ : siblingBounds.length
517
+ ? 64
518
+ : 48;
519
+ return configureStepRouter({ offset })(edge, context);
520
+ };
331
521
  ```
332
522
 
333
523
  When an edge uses ports, routing prefers the explicit port position. When no port is specified, routing uses the registered shape anchor for the node.
@@ -416,15 +606,32 @@ const store = createFlowStore(graph, {
416
606
  snapThreshold: 5,
417
607
  enableSpacingGuides: false,
418
608
  connectOnClick: false,
609
+ labelAnchor: 'fixed',
610
+ boxSelectionTest: null,
419
611
  selectionMode: 'partial', // 'partial' | 'full'
420
612
  historyLimit: 100,
421
613
  mode: 'interactive',
422
614
  profile: defaultFlowProfile,
423
- beforeDelete: ({ graph, reason, nodes, edges }) => { /* return false to cancel */ },
424
615
  onDeleteNodes: 'cascade', // 'cascade' | 'retarget' | custom function
425
616
  });
426
617
  ```
427
618
 
619
+ Use `flow.configure(patch)` for partial live updates. Use `flow.configure(current => completeNext)` for explicit full replacement and `flow.getConfiguration()` to capture a baseline. Store, engine, profile, mode, edge defaults, connection creation, and layout configuration share this path. Changing `historyLimit` after creation throws until XState exposes a supported live history-limit API.
620
+
621
+ `FlowProfile.resolvers`, `FlowProfile.policies`, and `FlowProfile.rules` are exported but experimental until the profile API settles.
622
+
623
+ Flow owns deterministic graph state and graph operations. Apps own intent, authorization, confirmation, persistence, and product policy. Async is valid where the domain is inherently async. For app-owned delete intent:
624
+
625
+ ```ts
626
+ if (await confirmDelete()) {
627
+ flow.selection.delete();
628
+ }
629
+ ```
630
+
631
+ Deletion itself is synchronous and returns whether anything was removed.
632
+
633
+ Engine `connection` options control connect-target magnet behavior: `{ radius?: number, mode?: 'loose' | 'strict' }`. Loose is the default/current behavior and falls back to node-body targets; strict only completes to ports.
634
+
428
635
  ## Edge labels
429
636
 
430
637
  Labels are first-class citizens — part of the edge data, positioned like nodes:
@@ -441,13 +648,14 @@ store.trigger.createEdge({
441
648
  label: {
442
649
  x: 150, y: 100,
443
650
  width: 80, height: 30,
651
+ autoSize: true, // optional: rendered DOM owns live width/height
444
652
  data: { text: 'yes' },
445
653
  },
446
654
  },
447
655
  });
448
656
  ```
449
657
 
450
- Selecting a label selects its edge (same ID). The renderer draws two path segments: source → label, label → target.
658
+ Selecting a label selects its edge (same ID). The renderer draws two path segments: source → label, label → target. With `autoSize: true`, authored dimensions are only the pre-measurement fallback; DOM measurements remain transient and never rewrite the label model.
451
659
 
452
660
  ## Factory functions
453
661
 
@@ -473,7 +681,7 @@ FlowEngine ← purely derived queries (no mutable state)
473
681
  renderer adapter (React, Vue, …) ← UI: components, DOM/SVG, event binding
474
682
  ```
475
683
 
476
- **Design principle: the engine is a pure projection over the store.** DOM-specific concerns such as element measurement and container observation are intentionally out of this package. All interaction state (pan, drag, selection, connection) lives in the store and is driven by `store.trigger.*` events. The engine provides computed queries (edge paths, resolved bounds, coordinate conversion, hit testing) derived from the current store snapshot.
684
+ **Design principle: the engine is a pure projection over the store.** DOM-specific concerns such as element measurement and container observation are intentionally out of this package. All interaction state (pan, drag, selection, connection) lives in the store and is driven by `store.trigger.*` events. The engine provides computed queries (edge paths, visual bounds, coordinate conversion, hit testing) derived from the current store snapshot.
477
685
 
478
686
  This means:
479
687
  - All state transitions are testable via `store.trigger.*` + snapshot assertions
@@ -493,7 +701,7 @@ store.trigger.dragEnd();
493
701
  store.trigger.zoomTo({ zoom: 1.5, center: { x: 400, y: 300 } });
494
702
 
495
703
  // Engine is purely derived:
496
- const bounds = engine.resolvedBounds('a'); // from store snapshot
704
+ const bounds = engine.getBounds('a'); // measured or model bounds
497
705
  const paths = engine.getAllEdgePaths(); // computed from graph state
498
706
  const canvas = engine.screenToCanvas({ x, y }); // from current viewport
499
707
  ```