@statelyai/flow 0.4.2 → 0.6.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 +296 -36
- package/dist/esm/index.d.ts +1478 -199
- package/dist/esm/index.js +5758 -633
- package/dist/esm/layout/dagre.d.ts +6 -0
- package/dist/esm/layout/dagre.js +106 -0
- package/dist/esm/layout/elk.d.ts +9 -0
- package/dist/esm/layout/elk.js +237 -0
- package/dist/esm/layout/index.d.ts +4 -0
- package/dist/esm/layout/index.js +3 -0
- package/dist/esm/shared.d.ts +28 -0
- package/dist/esm/shared.js +91 -0
- package/package.json +38 -7
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()`,
|
|
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
|
-
//
|
|
43
|
-
flow.
|
|
44
|
-
flow.
|
|
45
|
-
flow.
|
|
46
|
-
flow.
|
|
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();
|
|
@@ -54,18 +52,163 @@ const selectedBounds = flow.getSelectionBounds();
|
|
|
54
52
|
`createFlow()` owns the store and engine together. Use `createFlowStore()` and
|
|
55
53
|
`createFlowEngine()` directly when you need lower-level control.
|
|
56
54
|
|
|
55
|
+
## Layout adapters
|
|
56
|
+
|
|
57
|
+
Install only the engine you use:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
npm install @statelyai/flow elkjs
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Use `@dagrejs/dagre` instead of `elkjs` for dagre. Both are optional peer
|
|
64
|
+
dependencies, so installing Flow alone does not install either engine.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { createFlow } from '@statelyai/flow';
|
|
68
|
+
import { elkLayout } from '@statelyai/flow/layout/elk';
|
|
69
|
+
|
|
70
|
+
const flow = createFlow({ graph });
|
|
71
|
+
|
|
72
|
+
await flow.layout.run(
|
|
73
|
+
elkLayout({
|
|
74
|
+
nodeSpacing: 80,
|
|
75
|
+
rankSpacing: 120,
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
<!-- adapter contracts from src/layout/elk.ts src/layout/dagre.ts and src/layout/shared.ts -->
|
|
81
|
+
|
|
82
|
+
`elkLayout()` supports compound nodes, ports, edge labels, direction, measured
|
|
83
|
+
bounds via `getBounds`, and scoped incremental layout with `scope: { ids }`.
|
|
84
|
+
Results include computed node sizes and bounds, actual ELK label bounds, routed
|
|
85
|
+
interior waypoints, source metadata, and diagnostics. Scoped passes send only
|
|
86
|
+
the induced graph to ELK; fixed and pinned entities remain in the input but are
|
|
87
|
+
omitted from returned geometry.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
await flow.layout.run(elkLayout({ scope: { ids: candidateIds } }), {
|
|
91
|
+
scope: { parentId: 'group', depth: 1 },
|
|
92
|
+
fixedEntityIds: new Set(['pinned-node']),
|
|
93
|
+
source: 'editor',
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`dagreLayout()` flattens hierarchy and rejects scoped layout. It returns node
|
|
98
|
+
sizes, node bounds, and edge-label bounds without fabricating unsupported route
|
|
99
|
+
waypoints.
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { dagreLayout } from '@statelyai/flow/layout/dagre';
|
|
103
|
+
|
|
104
|
+
await flow.layout.run(dagreLayout());
|
|
105
|
+
```
|
|
106
|
+
|
|
57
107
|
## Data model
|
|
58
108
|
|
|
59
109
|
The canonical data model is `VisualGraph` from `@statelyai/graph`. Flow extends it with:
|
|
60
110
|
|
|
61
111
|
<!-- flow entity types from src/types.ts -->
|
|
62
112
|
|
|
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
|
|
113
|
+
- **`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`.
|
|
114
|
+
- **`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
115
|
- **`FlowGraph`** — `VisualGraph` with `FlowNode[]` and `FlowEdge[]`
|
|
66
|
-
- **`
|
|
116
|
+
- **`FlowEntityRef`** — descriptor for a node, edge, port, or block resolved by id. `FlowAddressable` is a deprecated alias.
|
|
117
|
+
|
|
118
|
+
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.
|
|
119
|
+
|
|
120
|
+
For DOM-owned nodes, `autoSizeAnchor` is `'top-left'` by default. Use
|
|
121
|
+
`'center'` to preserve the visual center, or `{ x: 0.5, y: 0 }` to preserve
|
|
122
|
+
only the horizontal center. Fractions must be finite and within `0..1`.
|
|
123
|
+
Node measurements, including their anchor correction, and `label.autoSize`
|
|
124
|
+
measurements remain derived session state: they emit no graph commit, create no
|
|
125
|
+
undo entry, and do not overwrite authored dimensions. Auto-size label
|
|
126
|
+
measurements drive routing, graph/selection bounds, hit testing, snapping,
|
|
127
|
+
culling, and toolbar anchors; surviving measurements remain stable across
|
|
128
|
+
`replaceGraph()` calls.
|
|
129
|
+
|
|
130
|
+
## Graph projections
|
|
131
|
+
|
|
132
|
+
<!-- graph projection types from src/projections.ts -->
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
- **`GraphProjection`** — `{ id, label?, nodes?, edges? }`, with `nodes`/`edges` keyed by existing entity ids
|
|
137
|
+
- **`GraphProjectionMapper`** — maps projected node/edge datum to visual attrs
|
|
138
|
+
- **`ActiveGraphProjection`** — `{ projection, mapper, priority? }`
|
|
139
|
+
- **`GraphNodeAttrs` / `GraphEdgeAttrs`** — visual attrs such as class, style, color, opacity, stroke width, labels, badges, and tooltips
|
|
140
|
+
|
|
141
|
+
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.
|
|
142
|
+
|
|
143
|
+
`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.
|
|
144
|
+
|
|
145
|
+
## Graph traversal
|
|
146
|
+
|
|
147
|
+
<!-- graph traversal helpers from src/graph-index.ts and src/createFlow.ts -->
|
|
148
|
+
|
|
149
|
+
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.
|
|
150
|
+
|
|
151
|
+
## Structural views
|
|
152
|
+
|
|
153
|
+
<!-- structural view API from src/view.ts and src/createFlow.ts -->
|
|
154
|
+
|
|
155
|
+
`flow.view` scopes the canonical graph without changing it or mixing structural
|
|
156
|
+
visibility with visual projections/highlights. The default scope is
|
|
157
|
+
`{ parentId: null, depth: null }`, preserving the full visible graph.
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
flow.view.setScope(
|
|
161
|
+
{ parentId: 'compound', depth: 1 },
|
|
162
|
+
{ selection: 'prune' },
|
|
163
|
+
);
|
|
164
|
+
|
|
165
|
+
const { nodes, edges, boundaryEndpoints } = flow.view.getEntities();
|
|
166
|
+
```
|
|
67
167
|
|
|
68
|
-
|
|
168
|
+
Depth `1` exposes direct children, `2` includes grandchildren, `0` is an empty
|
|
169
|
+
view, and `null` is unlimited. Edges owned by the exposed containers are
|
|
170
|
+
included. Endpoints below the depth boundary are lifted to their visible
|
|
171
|
+
ancestor; those returned edge objects are frozen clones, while the canonical
|
|
172
|
+
edge remains unchanged. `getBoundaryEndpoints(edgeId)` reports both original
|
|
173
|
+
and view endpoint ids.
|
|
174
|
+
|
|
175
|
+
Changing scope validates the parent/depth atomically and prunes selection to
|
|
176
|
+
the next view by default; use `{ selection: 'clear' }` to clear it. `selection.all()`
|
|
177
|
+
and `viewport.fit()` use the current view. Pass `{ includeHidden: true }` to
|
|
178
|
+
`view.getEntities()` or `selection.all()` when explicitly needed. Active graph
|
|
179
|
+
projections remain controller-owned and independent of the structural view.
|
|
180
|
+
|
|
181
|
+
## Viewport fit frame
|
|
182
|
+
|
|
183
|
+
<!-- viewport fit-frame API from src/createFlow.ts and src/viewport/index.ts -->
|
|
184
|
+
|
|
185
|
+
Register the unobscured screen-space rectangle when persistent UI overlays
|
|
186
|
+
cover part of the canvas. Fit, center, and zoom commands with no explicit pivot
|
|
187
|
+
then target that frame. The default remains the full, current viewport.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
flow.viewport.setFitFrame({ x: 320, y: 0, width: 880, height: 800 });
|
|
191
|
+
|
|
192
|
+
flow.viewport.fit();
|
|
193
|
+
flow.viewport.fitBounds(bounds);
|
|
194
|
+
flow.viewport.centerOn({ x: 100, y: 50 });
|
|
195
|
+
flow.viewport.zoomTo(1.5);
|
|
196
|
+
|
|
197
|
+
flow.viewport.setFitFrame(null); // reset to the full viewport
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Frames require finite `x`/`y` and positive finite dimensions. A `frame` on
|
|
201
|
+
`fit()`, `fitBounds()`, or `centerOn()` overrides the registered frame for that
|
|
202
|
+
call. `fit()` still composes with the current structural view and its `nodes`
|
|
203
|
+
subset. Animation resolves the same frame-aware target before it begins.
|
|
204
|
+
|
|
205
|
+
Every viewport mutation (`set`, `panBy`, `zoomTo`, `zoomBy`, `fit`,
|
|
206
|
+
`fitBounds`, and `centerOn`) returns `ViewportAnimationControls` with `cancel()`
|
|
207
|
+
and a `done` promise. `done` resolves on completion or cancellation. Immediate
|
|
208
|
+
and targetless commands return already-resolved controls; a targetless command
|
|
209
|
+
also cancels any older animation, so no viewport writes continue after its
|
|
210
|
+
`done`. A newer viewport command or direct low-level viewport write cancels and
|
|
211
|
+
resolves the previous controls.
|
|
69
212
|
|
|
70
213
|
## Ports
|
|
71
214
|
|
|
@@ -79,6 +222,10 @@ Ports are based on the visual node port model from `@statelyai/graph`.
|
|
|
79
222
|
|
|
80
223
|
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
224
|
|
|
225
|
+
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.
|
|
226
|
+
|
|
227
|
+
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.
|
|
228
|
+
|
|
82
229
|
```ts
|
|
83
230
|
const graph = {
|
|
84
231
|
nodes: [
|
|
@@ -113,6 +260,64 @@ const graph = {
|
|
|
113
260
|
};
|
|
114
261
|
```
|
|
115
262
|
|
|
263
|
+
## Selection commands
|
|
264
|
+
|
|
265
|
+
<!-- selection command API from src/createFlow.ts -->
|
|
266
|
+
|
|
267
|
+
`flow.selection.duplicate()` clones selected nodes, their descendants, and
|
|
268
|
+
internal edges through the content/ID remapping pipeline. It retains external
|
|
269
|
+
parents, selects all clones, offsets the duplicated subtree by `{ x: 24, y: 24 }`
|
|
270
|
+
by default, and creates one undo step. Pass `{ offset: { x, y } }` to override.
|
|
271
|
+
|
|
272
|
+
`flow.selection.align('left' | 'right' | 'top' | 'bottom' | 'center-x' |
|
|
273
|
+
'center-y')` aligns two or more selected nodes. Use
|
|
274
|
+
`flow.selection.distribute('horizontal' | 'vertical')` to space three or more
|
|
275
|
+
nodes evenly while retaining deterministic outer endpoints. Both use exact
|
|
276
|
+
current visual bounds and return `false` without adding history when the
|
|
277
|
+
selection is ineligible or the geometry is already satisfied.
|
|
278
|
+
|
|
279
|
+
## Layout contract
|
|
280
|
+
|
|
281
|
+
<!-- layout controller API from src/createFlow.ts -->
|
|
282
|
+
|
|
283
|
+
`flow.layout.run(algorithm, options?)` accepts `LayoutRunOptions`: cancellation
|
|
284
|
+
signal, stale-result `force`, structural `scope`, `previousResult`, fixed and
|
|
285
|
+
pinned entity ids, `source`, generic metadata, and optional `animation`.
|
|
286
|
+
Algorithms receive frozen clones of graph/options. The position `Map` shorthand
|
|
287
|
+
remains supported.
|
|
288
|
+
|
|
289
|
+
`LayoutResult` can additionally provide node sizes/bounds, edge-label
|
|
290
|
+
positions/bounds, edge routes, diagnostics, quality metadata, and source.
|
|
291
|
+
`flow.layout.apply(result, options?)` validates all ids and finite geometry
|
|
292
|
+
before mutation, then applies the result atomically as one history step. Fixed
|
|
293
|
+
or pinned entities remain unchanged unless listed in
|
|
294
|
+
`overrideFixedEntityIds`. Granular positions/sizes override matching axes from
|
|
295
|
+
aggregate bounds.
|
|
296
|
+
|
|
297
|
+
Pass `{ animation: { duration, easing? } }` to `run` or `apply` for a transient
|
|
298
|
+
visual transition. The final graph is committed once at the start; animation
|
|
299
|
+
frames never create graph commits or history entries. Both APIs provide
|
|
300
|
+
`animation: { cancel, done }` controls (`apply` returns the controls directly).
|
|
301
|
+
Canceling, replacing, or destroying an animation snaps visual geometry to the
|
|
302
|
+
durable final layout.
|
|
303
|
+
|
|
304
|
+
## Persistence
|
|
305
|
+
|
|
306
|
+
<!-- serialization API from src/serialize.ts and src/createFlow.ts -->
|
|
307
|
+
|
|
308
|
+
`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.
|
|
309
|
+
|
|
310
|
+
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.
|
|
311
|
+
|
|
312
|
+
Use `flow.replaceGraph(graph, options?)` when another model is authoritative and
|
|
313
|
+
continuously projects its graph into Flow. It validates atomically, returns the
|
|
314
|
+
applied `FlowChangeSet` (or `null` for an equal graph), preserves state addressed
|
|
315
|
+
to surviving entities by default, and clears Flow undo/redo history by default.
|
|
316
|
+
Set `retention: 'reset'` to clear graph-scoped session state, or set `history` to
|
|
317
|
+
`'ignore'` or `'record'` when the external synchronization contract requires it.
|
|
318
|
+
Pass `origin` and `transactionId` to suppress feedback loops through `commit`
|
|
319
|
+
events.
|
|
320
|
+
|
|
116
321
|
## Store events
|
|
117
322
|
|
|
118
323
|
<!-- all store events from src/store/index.ts -->
|
|
@@ -123,14 +328,20 @@ const graph = {
|
|
|
123
328
|
|---|---|---|
|
|
124
329
|
| `createNode` | `{ node: FlowNode }` | Add a node |
|
|
125
330
|
| `deleteNode` | `{ id }` | Remove node + cascade edges |
|
|
331
|
+
| `updateNode` | `{ id, patch? }` or `{ id, updater? }` | Patch/replace a node without changing id/type/parent |
|
|
126
332
|
| `updateNodeData` | `{ id, data }` | Merge into node.data |
|
|
127
333
|
| `createEdge` | `{ edge: FlowEdge }` | Add an edge |
|
|
128
334
|
| `deleteEdge` | `{ id }` | Remove an edge |
|
|
335
|
+
| `deleteEntities` | `{ nodeIds?, edgeIds? }` | Low-level synchronous deletion of a known entity set |
|
|
336
|
+
| `updateEdge` | `{ id, patch? }` or `{ id, updater? }` | Patch/replace an edge without changing id/type/endpoints/ports |
|
|
129
337
|
| `updateEdgeData` | `{ id, data }` | Merge into edge.data |
|
|
130
338
|
| `deleteSelected` | — | Remove all selected nodes + edges |
|
|
131
339
|
| `setGraph` | `{ graph: FlowGraph }` | Replace entire graph, reset interaction state |
|
|
340
|
+
| `replaceGraph` | `{ graph, retention?, history?, origin?, transactionId? }` | Replace through the external synchronization policy used by `flow.replaceGraph()` |
|
|
132
341
|
| `reset` | — | Reset store to initial state (preserves viewport size) |
|
|
133
342
|
| `reparentNode` | `{ id, parentId }` | Move node to new parent |
|
|
343
|
+
| `collapseNode` | `{ id }` | Hide descendants and derive folded boundary edges |
|
|
344
|
+
| `expandNode` | `{ id }` | Show descendants again |
|
|
134
345
|
| `reconnectEdge` | `{ edgeId, newSourceId?, newTargetId?, newSourcePort?, newTargetPort? }` | Rewire edge endpoints |
|
|
135
346
|
|
|
136
347
|
### Drag lifecycle
|
|
@@ -166,6 +377,7 @@ const graph = {
|
|
|
166
377
|
| Event | Payload | Description |
|
|
167
378
|
|---|---|---|
|
|
168
379
|
| `setViewport` | `{ x, y, zoom }` | Set viewport directly |
|
|
380
|
+
| `setFitFrame` | `{ frame: { x, y, width, height } \| null }` | Set or reset the persistent screen-space fit frame |
|
|
169
381
|
| `panBy` | `{ x, y }` | Pan by offset |
|
|
170
382
|
| `panStart` | `{ x, y }` | Begin pan gesture (screen coords) |
|
|
171
383
|
| `pan` | `{ x, y }` | Continue pan gesture (screen coords) |
|
|
@@ -174,7 +386,7 @@ const graph = {
|
|
|
174
386
|
| `setMinZoom` | `{ minZoom }` | Set minimum zoom level |
|
|
175
387
|
| `setMaxZoom` | `{ maxZoom }` | Set maximum zoom level |
|
|
176
388
|
| `updateViewportSize` | `{ width, height }` | Report container size |
|
|
177
|
-
| `fitView` | `{ padding?, minZoom?, maxZoom?, nodes? }` | Fit all (or specific) nodes
|
|
389
|
+
| `fitView` | `{ padding?, minZoom?, maxZoom?, nodes?, frame? }` | Fit all (or specific) nodes into a target frame |
|
|
178
390
|
| `pushViewport` / `popViewport` | — | Viewport stack for drill-in/out |
|
|
179
391
|
| `setTranslateExtent` | `{ extent: [Point, Point] \| null }` | Set pan boundary |
|
|
180
392
|
| `setNodeExtent` | `{ extent: [Point, Point] \| null }` | Set node drag boundary |
|
|
@@ -184,8 +396,8 @@ const graph = {
|
|
|
184
396
|
| Event | Payload | Description |
|
|
185
397
|
|---|---|---|
|
|
186
398
|
| `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`) |
|
|
399
|
+
| `connectionMove` | `{ position, targetId?, targetPort?, isValid?, invalidReason? }` | Update in-progress connection |
|
|
400
|
+
| `connectionEnd` | `{ target?: ConnectEndTarget }` | End connection gesture (emits `connectionEnded` with `status`) |
|
|
189
401
|
| `cancelConnection` | — | Cancel connection without emitting |
|
|
190
402
|
| `setConnectionClickStartHandle` | `{ nodeId, port } \| null` | Set/clear click-to-connect start handle |
|
|
191
403
|
|
|
@@ -211,10 +423,11 @@ const graph = {
|
|
|
211
423
|
|
|
212
424
|
| Event | Payload | Description |
|
|
213
425
|
|---|---|---|
|
|
214
|
-
| `setCanvasState` | `{ state: CanvasState }` | Set
|
|
426
|
+
| `setCanvasState` | `{ state: CanvasState }` | Set low-level canvas gesture state |
|
|
215
427
|
| `setMode` | `{ mode: string }` | Set active profile mode |
|
|
216
428
|
| `setDragThreshold` | `{ dragThreshold }` | Set pixel threshold before drag starts |
|
|
217
429
|
| `setAutoPanOptions` | `{ autoPanOnDrag?, autoPanThreshold?, autoPanSpeed? }` | Configure auto-pan behavior |
|
|
430
|
+
| `updateSettings` | `Partial<FlowRuntimeSettings>` | Update runtime store settings in one event |
|
|
218
431
|
| `setSnapToGrid` | `{ enabled, grid? }` | Enable/disable grid snapping |
|
|
219
432
|
| `setSnapLines` | `{ enabled, threshold?, spacing? }` | Enable/disable Figma-style alignment guides |
|
|
220
433
|
| `setColorMode` | `{ colorMode: FlowColorMode }` | Set the preferred UI color mode (`'light'` \| `'dark'` \| `'system'`) |
|
|
@@ -224,18 +437,25 @@ const graph = {
|
|
|
224
437
|
| Event | Payload | Description |
|
|
225
438
|
|---|---|---|
|
|
226
439
|
| `updateParentNodeId` | `{ parentNodeId }` | Drill into/out of nested node |
|
|
440
|
+
| `setViewScope` | `{ parentNodeId, depth, selection, visibleEntityIds }` | Low-level structural scope update; prefer `flow.view.setScope()` |
|
|
227
441
|
|
|
228
442
|
### Emitted events
|
|
229
443
|
|
|
230
|
-
Subscribe with `flow.on(type, listener)` or `store.on(type, listener)`.
|
|
444
|
+
Subscribe with `flow.on(type, listener)` or, for the low-level escape hatch, `flow.internals.store.on(type, listener)`.
|
|
231
445
|
|
|
232
446
|
| Event | Payload | Description |
|
|
233
447
|
|---|---|---|
|
|
234
448
|
| `graphChanged` | `{ graph, event }` | Graph changed after a mutation |
|
|
235
449
|
| `viewportChanged` | `{ viewport, event }` | Viewport changed |
|
|
236
450
|
| `selectionChanged` | `{ selection, event }` | Selection changed |
|
|
451
|
+
| `viewChanged` | `{ scope, event }` | Structural parent/depth changed |
|
|
237
452
|
| `entitiesDeleted` | `{ ids, event }` | Entities were deleted |
|
|
238
|
-
| `connectionEnded` | `ConnectionEndedEvent` | Connection gesture ended |
|
|
453
|
+
| `connectionEnded` | `ConnectionEndedEvent` | Connection gesture ended with `status: 'connected' \| 'cancelled' \| 'invalid'` |
|
|
454
|
+
| `dragStarted` / `dragMoved` / `dragEnded` | `FlowDrag*Event` | Drag gesture milestones; `dragMoved` fires per processed input event |
|
|
455
|
+
| `resizeStarted` / `resizeEnded` | `FlowResize*Event` | Resize gesture milestones |
|
|
456
|
+
| `connectStarted` / `connectMoved` | `FlowConnect*Event` | Connection gesture milestones; `connectMoved` fires per processed input event |
|
|
457
|
+
| `paneClicked` / `paneContextMenu` | `FlowPaneGestureEvent` | Pane click and context menu gestures |
|
|
458
|
+
| `entityClicked` / `entityDoubleClicked` / `entityContextMenu` | `FlowEntityGestureEvent` | Entity click, double-click, and context menu gestures |
|
|
239
459
|
| `layoutRequested` | `LayoutRequestedEvent` | Layout was requested |
|
|
240
460
|
| `error` | `{ error, event? }` | Flow error emitted |
|
|
241
461
|
|
|
@@ -243,7 +463,7 @@ Subscribe with `flow.on(type, listener)` or `store.on(type, listener)`.
|
|
|
243
463
|
|
|
244
464
|
<!-- undo/redo config from src/store/index.ts UNDOABLE_EVENT_TYPES -->
|
|
245
465
|
|
|
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.
|
|
466
|
+
`@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
467
|
|
|
248
468
|
```ts
|
|
249
469
|
import {
|
|
@@ -276,7 +496,7 @@ store.trigger.createNode({
|
|
|
276
496
|
store.trigger.undo();
|
|
277
497
|
```
|
|
278
498
|
|
|
279
|
-
Tracked events: `createNode`, `deleteNode`, `updateNodeData`, `createEdge`, `deleteEdge`, `updateEdgeData`, `deleteSelected`, `reparentNode`, `commitDrag`, `resizeEnd`, `reconnectEdge`, `applyLayoutResult`, `bakeLabelPositions`.
|
|
499
|
+
Tracked events: `createNode`, `deleteNode`, `updateNode`, `updateNodeData`, `createEdge`, `deleteEdge`, `updateEdge`, `updateEdgeData`, `deleteSelected`, `reparentNode`, `commitDrag`, `resizeEnd`, `reconnectEdge`, `applyLayoutResult`, `bakeLabelPositions`.
|
|
280
500
|
|
|
281
501
|
## Viewport utilities
|
|
282
502
|
|
|
@@ -291,9 +511,12 @@ import {
|
|
|
291
511
|
canvasToScreen,
|
|
292
512
|
getVisibleBounds,
|
|
293
513
|
viewportForBounds,
|
|
514
|
+
viewportCenteredOn,
|
|
515
|
+
validateFitFrame,
|
|
294
516
|
panBy,
|
|
295
517
|
zoomTo,
|
|
296
518
|
clampZoom,
|
|
519
|
+
animateViewport,
|
|
297
520
|
} from '@statelyai/flow';
|
|
298
521
|
|
|
299
522
|
const vp = createViewport(); // { x: 0, y: 0, zoom: 1 }
|
|
@@ -308,26 +531,45 @@ const screenPoint = canvasToScreen(vp, { x: 100, y: 50 });
|
|
|
308
531
|
|
|
309
532
|
// Fit content
|
|
310
533
|
const bounds = getVisibleBounds(vp, { width: 800, height: 600 });
|
|
311
|
-
const
|
|
534
|
+
const frame = validateFitFrame({ x: 300, y: 0, width: 500, height: 600 });
|
|
535
|
+
const fitted = viewportForBounds(contentRect, containerSize, {
|
|
536
|
+
padding: 0.1,
|
|
537
|
+
frame,
|
|
538
|
+
});
|
|
539
|
+
const centered = viewportCenteredOn(canvasPoint, containerSize, 1, frame);
|
|
540
|
+
|
|
541
|
+
// Animation
|
|
542
|
+
const animation = animateViewport(store, fitted, { duration: 300 });
|
|
543
|
+
await animation.done;
|
|
312
544
|
```
|
|
313
545
|
|
|
314
546
|
## Edge routing
|
|
315
547
|
|
|
316
548
|
<!-- edge routers from src/routing/index.ts -->
|
|
317
549
|
|
|
318
|
-
|
|
550
|
+
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
551
|
|
|
320
552
|
```ts
|
|
321
|
-
import {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
553
|
+
import { configureStepRouter, type EdgeRouter } from '@statelyai/flow';
|
|
554
|
+
|
|
555
|
+
type StatechartEdgeData = { transitionType: 'external' | 'internal' };
|
|
556
|
+
|
|
557
|
+
const statechartRouter: EdgeRouter<StatechartEdgeData> = (edge, context) => {
|
|
558
|
+
const source = context.graph.nodes.find((node) => node.id === edge.sourceId);
|
|
559
|
+
const siblingBounds = source?.parentId
|
|
560
|
+
? context.graph.nodes
|
|
561
|
+
.filter((node) => node.parentId === source.parentId)
|
|
562
|
+
.map((node) => context.getEntityBounds(node.id))
|
|
563
|
+
: [];
|
|
564
|
+
|
|
565
|
+
const offset =
|
|
566
|
+
edge.data.transitionType === 'internal'
|
|
567
|
+
? 32
|
|
568
|
+
: siblingBounds.length
|
|
569
|
+
? 64
|
|
570
|
+
: 48;
|
|
571
|
+
return configureStepRouter({ offset })(edge, context);
|
|
572
|
+
};
|
|
331
573
|
```
|
|
332
574
|
|
|
333
575
|
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 +658,32 @@ const store = createFlowStore(graph, {
|
|
|
416
658
|
snapThreshold: 5,
|
|
417
659
|
enableSpacingGuides: false,
|
|
418
660
|
connectOnClick: false,
|
|
661
|
+
labelAnchor: 'fixed',
|
|
662
|
+
boxSelectionTest: null,
|
|
419
663
|
selectionMode: 'partial', // 'partial' | 'full'
|
|
420
664
|
historyLimit: 100,
|
|
421
665
|
mode: 'interactive',
|
|
422
666
|
profile: defaultFlowProfile,
|
|
423
|
-
beforeDelete: ({ graph, reason, nodes, edges }) => { /* return false to cancel */ },
|
|
424
667
|
onDeleteNodes: 'cascade', // 'cascade' | 'retarget' | custom function
|
|
425
668
|
});
|
|
426
669
|
```
|
|
427
670
|
|
|
671
|
+
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.
|
|
672
|
+
|
|
673
|
+
`FlowProfile.resolvers`, `FlowProfile.policies`, and `FlowProfile.rules` are exported but experimental until the profile API settles.
|
|
674
|
+
|
|
675
|
+
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:
|
|
676
|
+
|
|
677
|
+
```ts
|
|
678
|
+
if (await confirmDelete()) {
|
|
679
|
+
flow.selection.delete();
|
|
680
|
+
}
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
Deletion itself is synchronous and returns whether anything was removed.
|
|
684
|
+
|
|
685
|
+
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.
|
|
686
|
+
|
|
428
687
|
## Edge labels
|
|
429
688
|
|
|
430
689
|
Labels are first-class citizens — part of the edge data, positioned like nodes:
|
|
@@ -441,13 +700,14 @@ store.trigger.createEdge({
|
|
|
441
700
|
label: {
|
|
442
701
|
x: 150, y: 100,
|
|
443
702
|
width: 80, height: 30,
|
|
703
|
+
autoSize: true, // optional: rendered DOM owns live width/height
|
|
444
704
|
data: { text: 'yes' },
|
|
445
705
|
},
|
|
446
706
|
},
|
|
447
707
|
});
|
|
448
708
|
```
|
|
449
709
|
|
|
450
|
-
Selecting a label selects its edge (same ID). The renderer draws two path segments: source → label, label → target.
|
|
710
|
+
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
711
|
|
|
452
712
|
## Factory functions
|
|
453
713
|
|
|
@@ -473,7 +733,7 @@ FlowEngine ← purely derived queries (no mutable state)
|
|
|
473
733
|
renderer adapter (React, Vue, …) ← UI: components, DOM/SVG, event binding
|
|
474
734
|
```
|
|
475
735
|
|
|
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,
|
|
736
|
+
**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
737
|
|
|
478
738
|
This means:
|
|
479
739
|
- All state transitions are testable via `store.trigger.*` + snapshot assertions
|
|
@@ -493,7 +753,7 @@ store.trigger.dragEnd();
|
|
|
493
753
|
store.trigger.zoomTo({ zoom: 1.5, center: { x: 400, y: 300 } });
|
|
494
754
|
|
|
495
755
|
// Engine is purely derived:
|
|
496
|
-
const bounds = engine.
|
|
756
|
+
const bounds = engine.getBounds('a'); // measured or model bounds
|
|
497
757
|
const paths = engine.getAllEdgePaths(); // computed from graph state
|
|
498
758
|
const canvas = engine.screenToCanvas({ x, y }); // from current viewport
|
|
499
759
|
```
|