@statelyai/flow 0.0.1 → 0.4.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
@@ -1,15 +1,503 @@
1
- # AgentFlow
1
+ # @statelyai/flow
2
2
 
3
- > **Work in progress** — a lightweight TypeScript library for defining composable, type-safe workflows with plain async functions.
3
+ Framework-agnostic flow visualization engine. Built on [`@statelyai/graph`](https://github.com/statelyai/graph) VisualGraph + [`@xstate/store`](https://github.com/statelyai/xstate) + [Immer](https://immerjs.github.io/immer/).
4
4
 
5
- **AgentFlow** lets you orchestrate multi-step flows by composing simple functions into declarative, testable flows. Think of it as a tiny state machine.
5
+ Render adapters (React, Vue, tldraw, etc.) sit on top. `@statelyai/flow` owns the pure state, layout, routing, and interaction logic. DOM-specific helpers such as `ResizeObserver` integration live in `@statelyai/flow-dom`.
6
6
 
7
- ---
7
+ ## Install
8
8
 
9
- ## ✨ Features
9
+ <!-- install command matching package.json#name and peerDependencies -->
10
10
 
11
- - ✅ **Composable steps** — each step is just an async function you can test in isolation
12
- - ✅ **Declarative orchestration** — define what happens after each step completes
13
- - ✅ **Type-safe transitions** — transitions between steps are fully inferred
14
- - ✅ **Lightweight** — no runtime dependencies
15
- - ✅ **Future integration** — designed to integrate naturally with [Vercel AI SDK](https://vercel.com/docs/ai/vercel-ai-sdk)
11
+ ```bash
12
+ npm install @statelyai/flow @statelyai/graph @xstate/store
13
+ ```
14
+
15
+ `@statelyai/graph` is a peer dependency — you bring your own version.
16
+
17
+ If you want DOM helpers such as `attachContainer()` and `createMeasurementObserver()`, also install `@statelyai/flow-dom`.
18
+
19
+ ## Quick start
20
+
21
+ <!-- primary controller quick start matching src/createFlow.ts and src/index.ts exports -->
22
+
23
+ ```ts
24
+ import { createFlow } from '@statelyai/flow';
25
+
26
+ const flow = createFlow({
27
+ graph: {
28
+ direction: 'down',
29
+ nodes: [
30
+ { type: 'node', id: 'a', x: 0, y: 0, width: 200, height: 80, data: { label: 'Start' } },
31
+ { type: 'node', id: 'b', x: 0, y: 150, width: 200, height: 80, data: { label: 'End' } },
32
+ ],
33
+ edges: [
34
+ { type: 'edge', id: 'e1', sourceId: 'a', targetId: 'b', x: 0, y: 0, width: 0, height: 0, data: {} },
35
+ ],
36
+ },
37
+ });
38
+
39
+ // Read state
40
+ const { graph, viewport, selection } = flow.getContext();
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();
49
+
50
+ // Query derived state through the engine-backed controller
51
+ const selectedBounds = flow.getSelectionBounds();
52
+ ```
53
+
54
+ `createFlow()` owns the store and engine together. Use `createFlowStore()` and
55
+ `createFlowEngine()` directly when you need lower-level control.
56
+
57
+ ## Data model
58
+
59
+ The canonical data model is `VisualGraph` from `@statelyai/graph`. Flow extends it with:
60
+
61
+ <!-- flow entity types from src/types.ts -->
62
+
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
65
+ - **`FlowGraph`** — `VisualGraph` with `FlowNode[]` and `FlowEdge[]`
66
+ - **`FlowAddressable`** — descriptor for a node, edge, port, or block resolved by id
67
+
68
+ Positions use a two-layer system: `x/y` from layout, `dx/dy` from user drag. Visual position = `(x + dx, y + dy)`.
69
+
70
+ ## Ports
71
+
72
+ Ports are based on the visual node port model from `@statelyai/graph`.
73
+
74
+ - `FlowNode` inherits `ports` from `VisualNode`
75
+ - `FlowPort` is `VisualPort` plus flow's `side` hint
76
+ - `sourcePort` / `targetPort` on `FlowEdge` reference those port names
77
+ - `'*'` means "choose the closest available port"
78
+ - `null` means "use the node shape anchor"
79
+
80
+ 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
+
82
+ ```ts
83
+ const graph = {
84
+ nodes: [
85
+ {
86
+ type: 'node',
87
+ id: 'a',
88
+ x: 0,
89
+ y: 0,
90
+ width: 160,
91
+ height: 60,
92
+ ports: [
93
+ { name: 'out', side: 'right', direction: 'out', x: 150, y: 25, width: 10, height: 10 },
94
+ ],
95
+ data: {},
96
+ },
97
+ ],
98
+ edges: [
99
+ {
100
+ type: 'edge',
101
+ id: 'e1',
102
+ sourceId: 'a',
103
+ targetId: 'b',
104
+ sourcePort: 'out',
105
+ targetPort: '*',
106
+ x: 0,
107
+ y: 0,
108
+ width: 0,
109
+ height: 0,
110
+ data: {},
111
+ },
112
+ ],
113
+ };
114
+ ```
115
+
116
+ ## Store events
117
+
118
+ <!-- all store events from src/store/index.ts -->
119
+
120
+ ### Graph mutations
121
+
122
+ | Event | Payload | Description |
123
+ |---|---|---|
124
+ | `createNode` | `{ node: FlowNode }` | Add a node |
125
+ | `deleteNode` | `{ id }` | Remove node + cascade edges |
126
+ | `updateNodeData` | `{ id, data }` | Merge into node.data |
127
+ | `createEdge` | `{ edge: FlowEdge }` | Add an edge |
128
+ | `deleteEdge` | `{ id }` | Remove an edge |
129
+ | `updateEdgeData` | `{ id, data }` | Merge into edge.data |
130
+ | `deleteSelected` | — | Remove all selected nodes + edges |
131
+ | `setGraph` | `{ graph: FlowGraph }` | Replace entire graph, reset interaction state |
132
+ | `reset` | — | Reset store to initial state (preserves viewport size) |
133
+ | `reparentNode` | `{ id, parentId }` | Move node to new parent |
134
+ | `reconnectEdge` | `{ edgeId, newSourceId?, newTargetId?, newSourcePort?, newTargetPort? }` | Rewire edge endpoints |
135
+
136
+ ### Drag lifecycle
137
+
138
+ | Event | Payload | Description |
139
+ |---|---|---|
140
+ | `dragStart` | `{ id }` | Begin dragging the selected entity |
141
+ | `dragMove` | `{ dx, dy }` | Apply in-progress drag delta |
142
+ | `dragEnd` | — | End drag gesture |
143
+ | `commitDrag` | — | Bake `dx/dy` into committed positions |
144
+ | `moveNodes` | `{ direction: Point, factor? }` | Move selected nodes by arrow key |
145
+
146
+ ### Selection & focus
147
+
148
+ | Event | Payload | Description |
149
+ |---|---|---|
150
+ | `select` | `{ ids, mode: 'single' \| 'multi' }` | Select entities (multi toggles) |
151
+ | `selectAll` | — | Select all nodes and edges |
152
+ | `clearSelection` | — | Deselect everything |
153
+ | `focus` | `{ entityId }` | Set keyboard/a11y focus |
154
+ | `clearFocus` | — | Clear focus |
155
+
156
+ ### Box selection
157
+
158
+ | Event | Payload | Description |
159
+ |---|---|---|
160
+ | `selectionBoxStart` | `{ point, mode? }` | Begin box-select gesture |
161
+ | `selectionBoxMove` | `{ point }` | Update box-select corner |
162
+ | `selectionBoxEnd` | — | Finalize: select intersecting entities |
163
+
164
+ ### Viewport
165
+
166
+ | Event | Payload | Description |
167
+ |---|---|---|
168
+ | `setViewport` | `{ x, y, zoom }` | Set viewport directly |
169
+ | `panBy` | `{ x, y }` | Pan by offset |
170
+ | `panStart` | `{ x, y }` | Begin pan gesture (screen coords) |
171
+ | `pan` | `{ x, y }` | Continue pan gesture (screen coords) |
172
+ | `panEnd` | — | End pan gesture |
173
+ | `zoomTo` | `{ zoom, center }` | Zoom to level around center point |
174
+ | `setMinZoom` | `{ minZoom }` | Set minimum zoom level |
175
+ | `setMaxZoom` | `{ maxZoom }` | Set maximum zoom level |
176
+ | `updateViewportSize` | `{ width, height }` | Report container size |
177
+ | `fitView` | `{ padding?, minZoom?, maxZoom?, nodes? }` | Fit all (or specific) nodes in view |
178
+ | `pushViewport` / `popViewport` | — | Viewport stack for drill-in/out |
179
+ | `setTranslateExtent` | `{ extent: [Point, Point] \| null }` | Set pan boundary |
180
+ | `setNodeExtent` | `{ extent: [Point, Point] \| null }` | Set node drag boundary |
181
+
182
+ ### Connection lifecycle
183
+
184
+ | Event | Payload | Description |
185
+ |---|---|---|
186
+ | `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`) |
189
+ | `cancelConnection` | — | Cancel connection without emitting |
190
+ | `setConnectionClickStartHandle` | `{ nodeId, port } \| null` | Set/clear click-to-connect start handle |
191
+
192
+ ### Resize lifecycle
193
+
194
+ | Event | Payload | Description |
195
+ |---|---|---|
196
+ | `resizeStart` | `{ id, handle: ResizeHandle }` | Begin resize gesture |
197
+ | `resizeMove` | `{ x, y }` | Update resize position |
198
+ | `resizeEnd` | — | Commit resize (bake position + custom dimensions) |
199
+ | `resizeCancel` | — | Cancel resize without committing |
200
+
201
+ ### Layout
202
+
203
+ | Event | Payload | Description |
204
+ |---|---|---|
205
+ | `requestLayout` | `{ algorithm? }` | Request auto-layout (blocked during drag) |
206
+ | `applyLayoutResult` | `{ positions: Map<id, {x,y}>, edgeLabelPositions? }` | Apply layout positions, reset dx/dy |
207
+ | `updateMeasurements` | `{ measurements: Array<{ id, rect: Rect }> }` | Renderer reports measured world-space rects |
208
+ | `bakeLabelPositions` | `{ positions: Map<edgeId, Point> }` | Bake computed label positions into edge data |
209
+
210
+ ### Configuration
211
+
212
+ | Event | Payload | Description |
213
+ |---|---|---|
214
+ | `setCanvasState` | `{ state: CanvasState }` | Set interaction mode |
215
+ | `setMode` | `{ mode: string }` | Set active profile mode |
216
+ | `setDragThreshold` | `{ dragThreshold }` | Set pixel threshold before drag starts |
217
+ | `setAutoPanOptions` | `{ autoPanOnDrag?, autoPanThreshold?, autoPanSpeed? }` | Configure auto-pan behavior |
218
+ | `setSnapToGrid` | `{ enabled, grid? }` | Enable/disable grid snapping |
219
+ | `setSnapLines` | `{ enabled, threshold?, spacing? }` | Enable/disable Figma-style alignment guides |
220
+ | `setColorMode` | `{ colorMode: FlowColorMode }` | Set the preferred UI color mode (`'light'` \| `'dark'` \| `'system'`) |
221
+
222
+ ### Navigation
223
+
224
+ | Event | Payload | Description |
225
+ |---|---|---|
226
+ | `updateParentNodeId` | `{ parentNodeId }` | Drill into/out of nested node |
227
+
228
+ ### Emitted events
229
+
230
+ Subscribe with `flow.on(type, listener)` or `store.on(type, listener)`.
231
+
232
+ | Event | Payload | Description |
233
+ |---|---|---|
234
+ | `graphChanged` | `{ graph, event }` | Graph changed after a mutation |
235
+ | `viewportChanged` | `{ viewport, event }` | Viewport changed |
236
+ | `selectionChanged` | `{ selection, event }` | Selection changed |
237
+ | `entitiesDeleted` | `{ ids, event }` | Entities were deleted |
238
+ | `connectionEnded` | `ConnectionEndedEvent` | Connection gesture ended |
239
+ | `layoutRequested` | `LayoutRequestedEvent` | Layout was requested |
240
+ | `error` | `{ error, event? }` | Flow error emitted |
241
+
242
+ ## Undo / redo
243
+
244
+ <!-- undo/redo config from src/store/index.ts UNDOABLE_EVENT_TYPES -->
245
+
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.
247
+
248
+ ```ts
249
+ import {
250
+ createFlowStore,
251
+ createNode,
252
+ } from '@statelyai/flow';
253
+
254
+ const store = createFlowStore(undefined, {
255
+ historyLimit: 200,
256
+ });
257
+
258
+ store.trigger.createNode({
259
+ node: createNode({ id: 'a', x: 0, y: 0 }),
260
+ });
261
+
262
+ store.trigger.undo();
263
+ store.trigger.redo();
264
+
265
+ const transactionId = 'create-node-pair';
266
+ store.trigger.createNode({
267
+ node: createNode({ id: 'b', x: 0, y: 100 }),
268
+ transactionId,
269
+ });
270
+ store.trigger.createNode({
271
+ node: createNode({ id: 'c', x: 180, y: 100 }),
272
+ transactionId,
273
+ });
274
+
275
+ // A single undo reverts both node creations.
276
+ store.trigger.undo();
277
+ ```
278
+
279
+ Tracked events: `createNode`, `deleteNode`, `updateNodeData`, `createEdge`, `deleteEdge`, `updateEdgeData`, `deleteSelected`, `reparentNode`, `commitDrag`, `resizeEnd`, `reconnectEdge`, `applyLayoutResult`, `bakeLabelPositions`.
280
+
281
+ ## Viewport utilities
282
+
283
+ <!-- viewport functions exported from src/viewport/index.ts -->
284
+
285
+ ```ts
286
+ import {
287
+ createViewport,
288
+ toSVGTransform,
289
+ toViewBox,
290
+ screenToCanvas,
291
+ canvasToScreen,
292
+ getVisibleBounds,
293
+ viewportForBounds,
294
+ panBy,
295
+ zoomTo,
296
+ clampZoom,
297
+ } from '@statelyai/flow';
298
+
299
+ const vp = createViewport(); // { x: 0, y: 0, zoom: 1 }
300
+
301
+ // SVG rendering
302
+ const transform = toSVGTransform(vp); // "translate(0, 0) scale(1)"
303
+ const viewBox = toViewBox(vp, { width: 800, height: 600 });
304
+
305
+ // Coordinate conversion
306
+ const canvasPoint = screenToCanvas(vp, { x: 400, y: 300 });
307
+ const screenPoint = canvasToScreen(vp, { x: 100, y: 50 });
308
+
309
+ // Fit content
310
+ const bounds = getVisibleBounds(vp, { width: 800, height: 600 });
311
+ const fitted = viewportForBounds(contentRect, containerSize, { padding: 0.1 });
312
+ ```
313
+
314
+ ## Edge routing
315
+
316
+ <!-- edge routers from src/routing/index.ts -->
317
+
318
+ Three built-in routers. All return `PathData` (points + source/target direction).
319
+
320
+ ```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
331
+ ```
332
+
333
+ 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.
334
+
335
+ ## Shapes
336
+
337
+ <!-- shape registry from src/shapes/index.ts -->
338
+
339
+ Shape handlers own hit testing and edge anchor calculation. Register custom shapes:
340
+
341
+ ```ts
342
+ import { registerShape, getShapeOrDefault } from '@statelyai/flow';
343
+
344
+ registerShape('hexagon', {
345
+ hitTest: (point, bounds) => { /* point-in-hexagon */ },
346
+ edgeAnchor: (bounds, direction) => { /* anchor point */ },
347
+ });
348
+
349
+ // Built-in: 'rect', 'rounded', 'ellipse', 'diamond'
350
+ const shape = getShapeOrDefault('hexagon');
351
+ ```
352
+
353
+ ## Snap lines
354
+
355
+ <!-- snap module exports from src/snap.ts -->
356
+
357
+ Figma-style alignment guides for drag operations. Exported:
358
+
359
+ ```ts
360
+ import { getSnapLines } from '@statelyai/flow';
361
+ import type { SnapLine, SpacingGuide, SnapResult, SnapOptions } from '@statelyai/flow';
362
+
363
+ const result: SnapResult = getSnapLines(movingRect, otherRects, {
364
+ threshold: 5,
365
+ enableSpacing: true,
366
+ });
367
+ // result.snapLines — alignment lines
368
+ // result.snapRect — snapped rectangle position
369
+ // result.spacingGuides — equal spacing indicators
370
+ ```
371
+
372
+ Enable via store: `store.trigger.setSnapLines({ enabled: true })`.
373
+
374
+ ## Config & behavior
375
+
376
+ <!-- behavior config from src/config.ts -->
377
+
378
+ Behavior is controlled by predicate functions, not boolean flags:
379
+
380
+ ```ts
381
+ import { defaultConfig, readonlyConfig, resolveBehavior } from '@statelyai/flow';
382
+
383
+ // Everything interactive
384
+ defaultConfig; // { selectable: () => true, draggable: () => true, connectable: () => true, ... }
385
+
386
+ // View-only (can still select)
387
+ readonlyConfig; // { draggable: false, connectable: false, reconnectable: false, deletable: false, resizable: false }
388
+
389
+ // Custom: nodes draggable, edges not
390
+ const config = {
391
+ ...defaultConfig,
392
+ draggable: (entity) => entity.type === 'node',
393
+ };
394
+
395
+ // Resolve for a specific entity
396
+ const canDrag = resolveBehavior(config.draggable, someNode, flowState);
397
+ ```
398
+
399
+ ## Store options
400
+
401
+ <!-- FlowStoreOptions from src/store/index.ts -->
402
+
403
+ ```ts
404
+ const store = createFlowStore(graph, {
405
+ minZoom: 0.1,
406
+ maxZoom: 4,
407
+ translateExtent: null, // [Point, Point] | null — pan boundary
408
+ nodeExtent: null, // [Point, Point] | null — node drag boundary
409
+ dragThreshold: 3, // px before drag starts
410
+ autoPanOnDrag: true,
411
+ autoPanThreshold: 40,
412
+ autoPanSpeed: 15,
413
+ snapToGrid: false,
414
+ snapGrid: [10, 10],
415
+ enableSnapLines: false,
416
+ snapThreshold: 5,
417
+ enableSpacingGuides: false,
418
+ connectOnClick: false,
419
+ selectionMode: 'partial', // 'partial' | 'full'
420
+ historyLimit: 100,
421
+ mode: 'interactive',
422
+ profile: defaultFlowProfile,
423
+ beforeDelete: ({ graph, reason, nodes, edges }) => { /* return false to cancel */ },
424
+ onDeleteNodes: 'cascade', // 'cascade' | 'retarget' | custom function
425
+ });
426
+ ```
427
+
428
+ ## Edge labels
429
+
430
+ Labels are first-class citizens — part of the edge data, positioned like nodes:
431
+
432
+ ```ts
433
+ store.trigger.createEdge({
434
+ edge: {
435
+ type: 'edge',
436
+ id: 'e1',
437
+ sourceId: 'a',
438
+ targetId: 'b',
439
+ x: 0, y: 0, width: 0, height: 0,
440
+ data: {},
441
+ label: {
442
+ x: 150, y: 100,
443
+ width: 80, height: 30,
444
+ data: { text: 'yes' },
445
+ },
446
+ },
447
+ });
448
+ ```
449
+
450
+ Selecting a label selects its edge (same ID). The renderer draws two path segments: source → label, label → target.
451
+
452
+ ## Factory functions
453
+
454
+ <!-- factory functions from src/factories.ts -->
455
+
456
+ ```ts
457
+ import { createNode, createEdge, createGraph } from '@statelyai/flow';
458
+
459
+ const node = createNode({ id: 'a', x: 0, y: 0 }); // defaults: width=150, height=50
460
+ const edge = createEdge({ id: 'e1', sourceId: 'a', targetId: 'b' });
461
+ const graph = createGraph({ nodes: [node], edges: [edge] }); // defaults: direction='down'
462
+ ```
463
+
464
+ ## Architecture
465
+
466
+ ```
467
+ @statelyai/graph (VisualGraph) ← canonical data model
468
+ ↓
469
+ FlowStore (@xstate/store) ← all state + transitions (pure, testable)
470
+ ↓
471
+ FlowEngine ← purely derived queries (no mutable state)
472
+ ↓
473
+ renderer adapter (React, Vue, …) ← UI: components, DOM/SVG, event binding
474
+ ```
475
+
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.
477
+
478
+ This means:
479
+ - All state transitions are testable via `store.trigger.*` + snapshot assertions
480
+ - The store is the single source of truth
481
+ - The engine can be reconstructed from any store snapshot
482
+ - Input handling (gestures, keyboard) is a separate concern — wire `store.trigger.*` to whatever input you want
483
+
484
+ ```ts
485
+ // All interaction goes through the store:
486
+ store.trigger.panStart({ x: e.clientX, y: e.clientY });
487
+ store.trigger.pan({ x: e.clientX, y: e.clientY });
488
+ store.trigger.panEnd();
489
+ store.trigger.select({ ids: ['a'], mode: 'single' });
490
+ store.trigger.dragStart({ id: 'a' });
491
+ store.trigger.dragMove({ dx: 10, dy: 5 });
492
+ store.trigger.dragEnd();
493
+ store.trigger.zoomTo({ zoom: 1.5, center: { x: 400, y: 300 } });
494
+
495
+ // Engine is purely derived:
496
+ const bounds = engine.resolvedBounds('a'); // from store snapshot
497
+ const paths = engine.getAllEdgePaths(); // computed from graph state
498
+ const canvas = engine.screenToCanvas({ x, y }); // from current viewport
499
+ ```
500
+
501
+ ## License
502
+
503
+ MIT