@statelyai/flow 0.12.0 → 0.13.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
@@ -117,6 +117,14 @@ geometry back to its absolute coordinate model, and applies complete routed
117
117
  smaller graph before layout; fixed and pinned entities stay in the input but are
118
118
  omitted from returned geometry.
119
119
 
120
+ <!-- finalized geometry policy from src/createFlow.ts applyLayout -->
121
+
122
+ `flow.layout.run()` and `flow.layout.apply()` round applied node positions,
123
+ edge-label positions, and route points to whole CSS pixels. Dimensions retain
124
+ subpixel precision. Fixed and untouched entities keep their authored coordinates;
125
+ manual graph edits and serialization do not round positions. The algorithm's
126
+ original precision remains available in `LayoutRunResult.result`.
127
+
120
128
  ```ts
121
129
  await flow.layout.run(statelyLayout({ scope: { ids: candidateIds } }), {
122
130
  scope: { parentId: 'group', depth: 1 },
@@ -188,6 +196,81 @@ culling, and toolbar anchors; surviving measurements remain stable across
188
196
  positions, so stale DOM measurements cannot move bounds or toolbar anchors back
189
197
  to a pre-drag location.
190
198
 
199
+ ## Renderer integration
200
+
201
+ <!-- renderer APIs from src/createFlow.ts, src/external-edit.ts and src/render-invalidation.ts -->
202
+
203
+ Keep observations separate from authored geometry:
204
+
205
+ ```ts
206
+ flow.measurements.update([
207
+ { id: 'node', rect: { x: 10, y: 20, width: 120.5, height: 60 } },
208
+ ]);
209
+ flow.measurements.get('node'); // detached last reported rect
210
+ flow.measurements.remove(['node']);
211
+
212
+ flow.nodes.move('node', { x: 40.2, y: 70.8 }); // settles to 40, 71
213
+ flow.nodes.resize('node', { x: 40, y: 71, width: 160, height: 90 });
214
+ flow.nodes.setContentSize('node', { width: 180.5, height: 110 });
215
+ ```
216
+
217
+ Measurements are world-space rectangles for existing node, edge-label, or port
218
+ IDs. They remain transient, work in readonly mode, and never author label, port,
219
+ or route geometry. Port observations follow their owner's subsequent movement.
220
+ `get()` returns the last report; `getBounds()` resolves current geometry. Removing
221
+ an observation restores authored fallback bounds. Deleting and recreating an
222
+ identity clears its observations, including within one transaction. Reports do
223
+ not alter authoritative saved route points.
224
+
225
+ `move` enforces dragging permission, grid/extent constraints, and core movement
226
+ policy. `resize` enforces resize permission and limits, including top/left edge
227
+ movement. `setContentSize` authors intrinsic content growth without requiring
228
+ manual resize or move permission; it still respects readonly and `canEdit`.
229
+ Its options can include `position` when text layout also shifts the origin.
230
+ Geometry options accept `positionPrecision` (default `0`, decimal digits `0..6`,
231
+ or `null` for exact positions). Dimensions retain precision. Low-level
232
+ `nodes.update()` remains an authored patch API and does not settle coordinates.
233
+
234
+ Native editors keep their own previews and submit semantic operations on release:
235
+
236
+ ```ts
237
+ const edit = flow.beginExternalEdit({ origin: 'canvas', history: 'ignore' });
238
+ // Native preview; concurrent Flow changes may arrive here.
239
+ const result = edit.commit([
240
+ { kind: 'node.move', id: 'node', position: { x: 120 } },
241
+ { kind: 'node.data', id: 'node', update: data => ({ ...data, text: 'Updated' }) },
242
+ ]);
243
+ if (!result.ok) console.error(result.error);
244
+ ```
245
+
246
+ A session compares supplied fields with its starting geometry/endpoints, merges
247
+ local changes into the latest graph, and preserves untouched concurrent fields.
248
+ Local changes win conflicts on the same field; returning a field to its baseline
249
+ preserves its latest concurrent value. Geometry fields returned to baseline are
250
+ omitted from the batch before staging. Data updaters read staged latest data.
251
+ Removed targets are skipped, including IDs deleted and recreated in separate
252
+ commits. An atomic delete/create with the same ID is treated as an update by
253
+ other sessions. Create nodes before edges referring to them. Batches also support
254
+ node resize/content size/delete and edge create/reconnect/data/delete operations.
255
+ Core validates new and reconnected edges once against the completed candidate
256
+ graph, including the candidate edge itself. Rejection rolls back the whole batch.
257
+ `commit()` returns a `FlowResult` and closes the session on success or failure;
258
+ `cancel()`/`dispose()` and controller destruction also close it.
259
+
260
+ All authored commands and transactions accept `history: 'record' | 'ignore'`
261
+ (default `'record'`). Ignored commits still notify persistence listeners.
262
+ `transactionId` groups recorded history entries; `origin` identifies their source.
263
+ Nested commands inherit outer ownership and reject conflicting options. Choose
264
+ one undo owner: Flow history stores graph snapshots and does not rebase older
265
+ recorded entries over later ignored edits.
266
+
267
+ For Canvas, `flow.subscribeRender(listener)` covers context, transient interaction,
268
+ measurement, projection, and commit changes. Notifications carry increasing
269
+ `revision`, `reason`, and conservative `all: true`. They are synchronous and may
270
+ occur more than once per commit; coalesce with your renderer's animation frame.
271
+ The returned function unsubscribes. `flow.on('destroy', listener)` supports host
272
+ cleanup; controller destruction also disposes sessions and render subscriptions.
273
+
191
274
  ## Entity appearances
192
275
 
193
276
  <!-- appearance references and resolution policy from src/appearances.ts, src/types.ts, src/engine.ts -->
@@ -371,17 +454,23 @@ resolves the previous controls.
371
454
 
372
455
  ## Ports
373
456
 
457
+ <!-- FlowPort and FlowNode port types from src/types.ts -->
458
+
374
459
  Ports are based on the visual node port model from `@statelyai/graph`.
375
460
 
376
- - `FlowNode` inherits `ports` from `VisualNode`
377
- - `FlowPort` is `VisualPort` plus flow's `side` hint
461
+ - `FlowNode` replaces `VisualNode.ports` with `FlowPort[]`, so array operations retain Flow-specific fields such as `side`
462
+ - `FlowPort` is `VisualPort` plus flow's `side` hint and optional explicit measurement `id`
378
463
  - `sourcePort` / `targetPort` on `FlowEdge` reference those port names
379
464
  - `'*'` means "choose the closest available port"
380
465
  - `null` means "use the node shape anchor"
381
466
 
382
467
  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`.
383
468
 
384
- 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.
469
+ <!-- connection gesture policy from src/input/modes.ts and src/engine.ts -->
470
+
471
+ 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. An explicitly targeted invalid port does not fall back to the node body.
472
+
473
+ With `store: { connectOnClick: true }`, `connectMode()` supports click, move, then click to complete. Drag connections remain available. Both paths validate the release target and share preview and cancellation behavior, including loose node-body targets. `connectionDragThreshold` measures pointer travel in screen pixels, so zoom does not change click sensitivity. A valid gesture that starts at an input port creates an output-to-input edge. `connectionEnded.source` still identifies the port where the gesture began. Public engine validation remains directed.
385
474
 
386
475
  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. Exact DOM node/port targets take priority, then reconnection falls back to Flow's spatial candidate. Groups are fully targetable by default; `group.connectionBoundaryWidth` limits spatial body targeting to the content block and an inset child-surface boundary, leaving its interior as canvas. `connectionEnded.reconnectedEdgeId` identifies connected, invalid, and cancelled observer-owned reconnects.
387
476
 
@@ -822,6 +911,57 @@ const config = {
822
911
  const canDrag = resolveBehavior(config.draggable, someNode, flowState);
823
912
  ```
824
913
 
914
+ ## Input policies
915
+
916
+ <!-- keyboardMode, keyboardNavMode, and pinchMode from src/input/modes.ts -->
917
+
918
+ `keyboardNavMode(options?)` configures focused activation and selection movement.
919
+
920
+ | Option | Default | Behavior |
921
+ | --- | --- | --- |
922
+ | `activationKeys` | `['Enter', ' ', 'Spacebar']` | Literal `KeyboardEvent.key` values. `null` or `[]` disables focused activation. |
923
+ | `preventDefault` | `true` | Prevents the browser default for activation keys. Arrow movement still prevents its browser default. |
924
+ | `selectionBehavior` | `'replace'` | `'preserve'` retains the current selection when the focused entity is already selected. |
925
+ | `nudge` | `'selection'` | `'focused-selection'` requires a focused, selected node before moving the selection. |
926
+ | `allowMove` | `true` | Enables selection movement with the configured arrow shortcuts. |
927
+ | `step` | `5` | Normal movement distance. Grid snapping uses grid increments. |
928
+ | `shiftStep` | `20` | Movement factor with `keymap.nudgeLargeModifier`. |
929
+ | `keymap` | Default keymap | Overrides shortcuts and the shared pointer/keyboard multiselect modifier. |
930
+
931
+ With the multiselect modifier, activation toggles the focused entity's membership in the selection. `selectionBehavior: 'preserve'` does not suppress that toggle.
932
+
933
+ `keyboardMode({ escapeSelection })` controls idle cancellation. `'all'` clears selection and focus. `'focused'` removes the focused entity from selection and clears focus. `'none'` preserves both. Active connection or resize cancellation takes priority over the idle selection policy. The default is `'all'`.
934
+
935
+ Replace the corresponding factories in the default mode list to configure these policies.
936
+
937
+ ```ts
938
+ import {
939
+ defaultInputModesForKeymap,
940
+ keyboardMode,
941
+ keyboardNavMode,
942
+ } from '@statelyai/flow';
943
+
944
+ const keymap = { multiSelectModifier: 'meta' as const };
945
+ const inputModes = [
946
+ ...defaultInputModesForKeymap(keymap).filter(
947
+ (mode) => mode.id !== 'keyboard' && mode.id !== 'keyboard-nav',
948
+ ),
949
+ keyboardMode({ keymap, escapeSelection: 'focused' }),
950
+ keyboardNavMode({
951
+ keymap,
952
+ activationKeys: ['Enter'],
953
+ selectionBehavior: 'preserve',
954
+ nudge: 'focused-selection',
955
+ }),
956
+ ];
957
+ ```
958
+
959
+ Pass `inputModes` to the input runtime or `<StatelyFlow inputModes={inputModes} />`. `pinchMode()` calculates zoom from the gesture's initial distance and keeps its original canvas anchor under the moving touch center. Zoom limits and independent pan/zoom permissions apply throughout the gesture.
960
+
961
+ For a dynamic input-mode resolver, call `runtime.reconcileModes()` after changing
962
+ the mode set. It clears a pending click connection if connect mode was removed,
963
+ while leaving an active pointer gesture in progress.
964
+
825
965
  ## Store options
826
966
 
827
967
  <!-- FlowStoreOptions from src/store/index.ts -->