@statelyai/flow 0.10.0 → 0.11.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
@@ -83,31 +83,61 @@ const selectedBounds = flow.getSelectionBounds();
83
83
  Install only the engine you use:
84
84
 
85
85
  ```bash
86
- npm install @statelyai/flow elkjs
86
+ npm install @statelyai/flow @statelyai/layout
87
87
  ```
88
88
 
89
- Use `@dagrejs/dagre` instead of `elkjs` for dagre. Both are optional peer
90
- dependencies, so installing Flow alone does not install either engine.
89
+ `@statelyai/layout` is the first-class engine: both packages operate on
90
+ `@statelyai/graph`, so the adapter preserves graph-native nodes, ports, labels,
91
+ and complete edge routes. Layout engines are optional peer dependencies; use
92
+ `elkjs` or `@dagrejs/dagre` only for their compatibility adapters.
91
93
 
92
94
  ```ts
93
95
  import { createFlow } from '@statelyai/flow';
94
- import { elkLayout } from '@statelyai/flow/layout/elk';
96
+ import { statelyLayout } from '@statelyai/flow/layout';
95
97
 
96
- const flow = createFlow({ graph });
98
+ const flow = createFlow({
99
+ graph,
100
+ layout: statelyLayout({
101
+ direction: 'right',
102
+ spacing: { node: 80, layer: 120 },
103
+ }),
104
+ });
97
105
 
98
- await flow.layout.run(
99
- elkLayout({
100
- nodeSpacing: 80,
101
- rankSpacing: 120,
102
- })
103
- );
106
+ await flow.layout.run();
107
+ ```
108
+
109
+ <!-- adapter contracts from src/layout/stately.ts src/layout/elk.ts src/layout/dagre.ts and src/layout/shared.ts -->
110
+
111
+ `statelyLayout()` uses `@statelyai/layout`'s native layered algorithm. It
112
+ supports flat and compound graphs, ports, labels, cycles, four directions,
113
+ constraints, advanced layered settings, and replaceable layout phases. Flow
114
+ resolves measured node bounds before the run, converts parent-relative compound
115
+ geometry back to its absolute coordinate model, and applies complete routed
116
+ `points` as authoritative graph geometry. Factory and run scopes induce a
117
+ smaller graph before layout; fixed and pinned entities stay in the input but are
118
+ omitted from returned geometry.
119
+
120
+ ```ts
121
+ await flow.layout.run(statelyLayout({ scope: { ids: candidateIds } }), {
122
+ scope: { parentId: 'group', depth: 1 },
123
+ fixedEntityIds: new Set(['pinned-node']),
124
+ source: 'editor',
125
+ });
104
126
  ```
105
127
 
106
- <!-- adapter contracts from src/layout/elk.ts src/layout/dagre.ts and src/layout/shared.ts -->
128
+ The ELK adapter remains available for migration and comparison:
129
+
130
+ ```ts
131
+ import { elkLayout } from '@statelyai/flow/layout/elk';
132
+
133
+ await flow.layout.run(elkLayout({ nodeSpacing: 80, rankSpacing: 120 }));
134
+ ```
107
135
 
108
136
  `elkLayout()` supports compound nodes, ports, edge labels, graph direction,
109
137
  per-group child direction, measured bounds via `getBounds`, and scoped
110
- incremental layout with `scope: { ids }`.
138
+ incremental layout with `scope: { ids }`. If an explicit group direction needs a
139
+ local repair pass, it retains `elk.layered.cycleBreaking.strategy`: direct `node`
140
+ options take precedence over `node.layoutOptions`, then `graph` options.
111
141
  Results include computed node sizes and bounds, label bounds, routed interior
112
142
  waypoints, source metadata, and diagnostics. Hierarchical ELK runs repair
113
143
  invalid nested label positions by choosing the nearest node-free position, keep
@@ -123,14 +153,6 @@ child ranks without changing the root direction. Scoped passes send only
123
153
  the induced graph to ELK; fixed and pinned entities remain in the input but are
124
154
  omitted from returned geometry.
125
155
 
126
- ```ts
127
- await flow.layout.run(elkLayout({ scope: { ids: candidateIds } }), {
128
- scope: { parentId: 'group', depth: 1 },
129
- fixedEntityIds: new Set(['pinned-node']),
130
- source: 'editor',
131
- });
132
- ```
133
-
134
156
  `dagreLayout()` flattens hierarchy and rejects scoped layout. It returns node
135
157
  sizes, node bounds, and edge-label bounds without fabricating unsupported route
136
158
  waypoints.
@@ -148,7 +170,7 @@ The canonical data model is `VisualGraph` from `@statelyai/graph`. Flow extends
148
170
  <!-- flow entity types from src/types.ts -->
149
171
 
150
172
  - **`FlowNode`** — `VisualNode` + `{ kind, dx, dy, style, ports, autoSize, autoSizeAnchor, selectionBounds, resize, hidden, selectable, draggable, connectable, deletable, resizable }` for application-defined rendering kinds, drag offsets, DOM-owned sizing, anchor policy, optional marquee hit geometry, style overrides, resize constraints, and per-entity behavior. Keep the structural `type` equal to `"node"`; use `kind` for variants such as `state` or `annotation`.
151
- - **`FlowEdge`** — `VisualEdge` + `{ label, waypoints, svgPath, sourcePort, targetPort, kind, style, labelAnchor }` for edge labels, editable router via-points, exact SVG geometry, port binding, and edge styling. Canonical `VisualEdge.points` plus `routing` are an authoritative precomputed route and bypass Flow routers; an optional `svgPath` controls exact SVG paint while points remain authoritative for interaction geometry. Reconnects, node geometry updates, committed drags, and layout application clear stale precomputed routes; layout-provided edge routes replace them with router waypoints. `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`.
173
+ - **`FlowEdge`** — `VisualEdge` + `{ label, waypoints, svgPath, sourcePort, targetPort, kind, style, labelAnchor }` for edge labels, editable router via-points, exact SVG geometry, port binding, and edge styling. Canonical `VisualEdge.points` plus `routing` are an authoritative precomputed route and bypass Flow routers; an optional `svgPath` controls exact SVG paint while points remain authoritative for interaction geometry. Reconnects, node geometry updates, committed drags, and layout application clear stale precomputed routes; layout results may provide either interior router waypoints or a complete authoritative route. `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`.
152
174
  - **`FlowGraph`** — `VisualGraph` with `FlowNode[]` and `FlowEdge[]`
153
175
  - **`FlowEntityRef`** — descriptor for a node, edge, port, or block resolved by id. `FlowAddressable` is a deprecated alias.
154
176
 
@@ -626,7 +648,7 @@ await animation.done;
626
648
 
627
649
  <!-- edge routers from src/routing/index.ts -->
628
650
 
629
- 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 override containing only SVG path commands and numeric parameters. Canonical graph `edge.points` are different from `waypoints`: they are a complete authoritative endpoint-to-endpoint route, interpreted by `edge.routing` (`polyline`, `orthogonal`, or chained `splines`) and never sent through a Flow router or split around a label. An optional edge `svgPath` preserves exact SVG paint while the authoritative points drive endpoints, bounds, hit testing, culling, transient DOM updates, and export. Core endpoint-geometry mutations invalidate precomputed route fields; layout-provided edge routes replace them with router waypoints, while consumers can apply a fresh authoritative graph to restore exact geometry. Edge `waypoints` remain ordered interior router inputs 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. Set `engine.edgeRouterDependencies: 'endpoints'` only when a custom router does not inspect unrelated graph entities, bounds, or obstacles; Flow can then retain unaffected routes after local geometry changes. The safe default is `'graph'`.
651
+ 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 override containing only SVG path commands and numeric parameters. Canonical graph `edge.points` are different from `waypoints`: they are a complete authoritative endpoint-to-endpoint route, interpreted by `edge.routing` (`polyline`, `orthogonal`, or chained `splines`) and never sent through a Flow router or split around a label. An optional edge `svgPath` preserves exact SVG paint while the authoritative points drive endpoints, bounds, hit testing, culling, transient DOM updates, and export. Core endpoint-geometry mutations invalidate precomputed route fields; layout results may atomically replace them with either interior router waypoints or complete `points` plus `routing`. Edge `waypoints` remain ordered interior router inputs 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. Set `engine.edgeRouterDependencies: 'endpoints'` only when a custom router does not inspect unrelated graph entities, bounds, or obstacles; Flow can then retain unaffected routes after local geometry changes. The safe default is `'graph'`.
630
652
 
631
653
  Router obstacles exclude the source, target, and their ancestor groups, so an
632
654
  edge crossing a hierarchy boundary can pass through its endpoint container.
@@ -2825,9 +2825,14 @@ type LayoutDiagnostic = {
2825
2825
  severity?: 'info' | 'warning' | 'error';
2826
2826
  code?: string;
2827
2827
  entityId?: string;
2828
+ entityIds?: readonly string[];
2829
+ phase?: string;
2828
2830
  };
2829
2831
  type LayoutEdgeRoute = {
2830
2832
  waypoints: readonly Point[];
2833
+ } | {
2834
+ points: readonly Point[];
2835
+ routing?: EdgeRouting;
2831
2836
  };
2832
2837
  type LayoutResult = {
2833
2838
  positions: ReadonlyMap<string, Point>;
package/dist/esm/index.js CHANGED
@@ -4712,8 +4712,9 @@ function createFlowStore(initialGraph = {
4712
4712
  const candidate = draft.graph.nodes[portTarget.nodeIndex];
4713
4713
  const port = candidate.ports?.[portTarget.portIndex];
4714
4714
  if (!port) continue;
4715
- port.x = measurement.rect.x - (candidate.x + (candidate.dx ?? 0));
4716
- port.y = measurement.rect.y - (candidate.y + (candidate.dy ?? 0));
4715
+ const origin = snappedBounds(candidate, draft.snapToGrid ? draft.snapGrid : null);
4716
+ port.x = measurement.rect.x - origin.x;
4717
+ port.y = measurement.rect.y - origin.y;
4717
4718
  port.width = measurement.rect.width;
4718
4719
  port.height = measurement.rect.height;
4719
4720
  }
@@ -7418,6 +7419,12 @@ function insertFlowContent(graph, content, options) {
7418
7419
  }
7419
7420
  //#endregion
7420
7421
  //#region src/createFlow.ts
7422
+ function hasAuthoritativeLayoutPoints(route) {
7423
+ return !Array.isArray(route) && "points" in route;
7424
+ }
7425
+ function layoutWaypoints(route) {
7426
+ return Array.isArray(route) ? route : route.waypoints;
7427
+ }
7421
7428
  function immutableConfiguration(configuration) {
7422
7429
  const seen = /* @__PURE__ */ new WeakMap();
7423
7430
  const clone = (value) => {
@@ -7580,10 +7587,19 @@ function createFlow(options = {}) {
7580
7587
  ...value.nodeBounds ? { nodeBounds: rects(value.nodeBounds) } : {},
7581
7588
  ...value.edgeLabelPositions ? { edgeLabelPositions: points(value.edgeLabelPositions) } : {},
7582
7589
  ...value.edgeLabelBounds ? { edgeLabelBounds: rects(value.edgeLabelBounds) } : {},
7583
- ...value.edgeRoutes ? { edgeRoutes: new Map([...value.edgeRoutes].map(([id, route]) => [id, { waypoints: ("waypoints" in route ? route.waypoints : route).map((point) => ({
7584
- x: point.x,
7585
- y: point.y
7586
- })) }])) } : {},
7590
+ ...value.edgeRoutes ? { edgeRoutes: new Map([...value.edgeRoutes].map(([id, route]) => {
7591
+ if (hasAuthoritativeLayoutPoints(route)) return [id, {
7592
+ points: route.points.map((point) => ({
7593
+ x: point.x,
7594
+ y: point.y
7595
+ })),
7596
+ ...route.routing ? { routing: route.routing } : {}
7597
+ }];
7598
+ return [id, { waypoints: layoutWaypoints(route).map((point) => ({
7599
+ x: point.x,
7600
+ y: point.y
7601
+ })) }];
7602
+ })) } : {},
7587
7603
  ...value.diagnostics ? { diagnostics: value.diagnostics.map((entry) => ({ ...entry })) } : {},
7588
7604
  ...value.quality ? { quality: cloneJsonSafe(value.quality, "$.layout.quality") } : {},
7589
7605
  ...value.metadata ? { metadata: cloneJsonSafe(value.metadata, "$.layout.metadata") } : {},
@@ -7839,7 +7855,7 @@ function createFlow(options = {}) {
7839
7855
  finiteSize(rect, path);
7840
7856
  });
7841
7857
  validateMap("edgeRoutes", result.edgeRoutes, edgeIds, (route, path) => {
7842
- ("waypoints" in route ? route.waypoints : route).forEach((point, index) => finitePoint(point, `${path}.waypoints[${index}]`));
7858
+ (hasAuthoritativeLayoutPoints(route) ? route.points : layoutWaypoints(route)).forEach((point, index) => finitePoint(point, `${path}.points[${index}]`));
7843
7859
  });
7844
7860
  for (const [field, ids] of [
7845
7861
  ["fixedEntityIds", applyOptions.fixedEntityIds],
@@ -7927,7 +7943,11 @@ function createFlow(options = {}) {
7927
7943
  delete edge.label.dx;
7928
7944
  delete edge.label.dy;
7929
7945
  }
7930
- if (route) edge.waypoints = ("waypoints" in route ? route.waypoints : route).map((point) => ({ ...point }));
7946
+ if (route) if (hasAuthoritativeLayoutPoints(route)) {
7947
+ edge.points = route.points.map((point) => ({ ...point }));
7948
+ edge.routing = route.routing ?? "polyline";
7949
+ delete edge.waypoints;
7950
+ } else edge.waypoints = layoutWaypoints(route).map((point) => ({ ...point }));
7931
7951
  }
7932
7952
  const initialOffsets = /* @__PURE__ */ new Map();
7933
7953
  if (animate) {
@@ -167,6 +167,9 @@ async function restoreExplicitCompoundDirections(elk, graph, positions, nodeSize
167
167
  "elk.spacing.nodeNode": String(options.nodeSpacing ?? 60)
168
168
  };
169
169
  applyCompoundLayeredOptions(localLayoutOptions, localEdges, direction, options);
170
+ const nestedNodeOptions = options.node?.layoutOptions;
171
+ const cycleBreakingStrategy = options.node?.["elk.layered.cycleBreaking.strategy"] ?? (nestedNodeOptions && typeof nestedNodeOptions === "object" ? nestedNodeOptions["elk.layered.cycleBreaking.strategy"] : void 0) ?? options.graph?.["elk.layered.cycleBreaking.strategy"];
172
+ if (cycleBreakingStrategy !== void 0) localLayoutOptions["elk.layered.cycleBreaking.strategy"] = String(cycleBreakingStrategy);
170
173
  const laidOutChildren = (await elk.layout({
171
174
  id: `direction:${group.id}`,
172
175
  layoutOptions: localLayoutOptions,
@@ -1,4 +1,5 @@
1
1
  import { i as FlowLayoutScope, n as FlowLayoutFactory, r as FlowLayoutOptions, t as FlowLayoutAlgorithm } from "../shared.js";
2
2
  import { DagreLayoutOptions, dagreLayout } from "./dagre.js";
3
3
  import { ElkLayoutOptions, elkLayout } from "./elk.js";
4
- export { type DagreLayoutOptions, type ElkLayoutOptions, type FlowLayoutAlgorithm, type FlowLayoutFactory, type FlowLayoutOptions, type FlowLayoutScope, dagreLayout, elkLayout };
4
+ import { StatelyLayoutOptions, statelyLayout } from "./stately.js";
5
+ export { type DagreLayoutOptions, type ElkLayoutOptions, type FlowLayoutAlgorithm, type FlowLayoutFactory, type FlowLayoutOptions, type FlowLayoutScope, type StatelyLayoutOptions, dagreLayout, elkLayout, statelyLayout };
@@ -1,3 +1,4 @@
1
1
  import { dagreLayout } from "./dagre.js";
2
2
  import { elkLayout } from "./elk.js";
3
- export { dagreLayout, elkLayout };
3
+ import { statelyLayout } from "./stately.js";
4
+ export { dagreLayout, elkLayout, statelyLayout };
@@ -0,0 +1,8 @@
1
+ import { r as FlowLayoutOptions, t as FlowLayoutAlgorithm } from "../shared.js";
2
+ import { LayeredLayoutOptions } from "@statelyai/layout/layered";
3
+ //#region src/layout/stately.d.ts
4
+ type StatelyLayoutOptions<TNodeData = any, TEdgeData = any, TLabelData = any> = Omit<LayeredLayoutOptions, 'measure'> & Pick<FlowLayoutOptions<TNodeData, TEdgeData, TLabelData>, 'getBounds' | 'scope' | 'source' | 'metadata' | '_types'>;
5
+ /** Graph-native layered layout powered by `@statelyai/layout`. */
6
+ declare const statelyLayout: <TNodeData = any, TEdgeData = any, TLabelData = any>(options?: StatelyLayoutOptions<TNodeData, TEdgeData, TLabelData>) => FlowLayoutAlgorithm<TNodeData, TEdgeData, TLabelData>;
7
+ //#endregion
8
+ export { StatelyLayoutOptions, statelyLayout };
@@ -0,0 +1,425 @@
1
+ import { a as mergedLayoutScope, i as layoutRunContext, r as graphForLayoutScope, s as throwIfAborted, t as boundsOf } from "../shared.js";
2
+ import { getLCA } from "@statelyai/graph";
3
+ import { deriveGroupGeometry, fixedGroupGeometry, isGroup, resolveGroupPadding } from "@statelyai/flow";
4
+ import { getLayeredLayout } from "@statelyai/layout/layered";
5
+ import { getLayout } from "@statelyai/layout";
6
+ //#region src/layout/stately.ts
7
+ /** Graph-native layered layout powered by `@statelyai/layout`. */
8
+ const statelyLayout = (options = {}) => {
9
+ return async (graph, runOptions = {}) => {
10
+ throwIfAborted(runOptions);
11
+ const mutableGraph = graph;
12
+ const layoutGraph = graphForLayoutScope(mutableGraph, mergedLayoutScope(mutableGraph, options.scope, runOptions));
13
+ const context = layoutRunContext(mutableGraph, options, runOptions, "stately");
14
+ const native = await getLayout({
15
+ graph: toStatelyGraph(layoutGraph, options.getBounds),
16
+ algorithm: "layered",
17
+ options: nativeOptions(options),
18
+ ...runOptions.signal ? { signal: runOptions.signal } : {}
19
+ });
20
+ context.diagnostics.push(...native.diagnostics.map((entry) => ({ ...entry })));
21
+ const output = applyFlowGroupContracts(native.graph, layoutGraph, nativeOptions(options), options.getBounds);
22
+ throwIfAborted(runOptions);
23
+ return fromStatelyGraph(output, layoutGraph, promotedRootOffsets(layoutGraph, mutableGraph, options.getBounds), context.fixedIds, options.getBounds, new Set(layoutGraph.edges.filter((edge) => edge.label).map((edge) => edge.id)), {
24
+ source: context.source,
25
+ metadata: {
26
+ ...context.metadata,
27
+ algorithm: "layered"
28
+ },
29
+ diagnostics: context.diagnostics
30
+ });
31
+ };
32
+ };
33
+ function nativeOptions(options) {
34
+ const { getBounds: _getBounds, scope: _scope, source: _source, metadata: _metadata, _types, ...native } = options;
35
+ return native;
36
+ }
37
+ function promotedRootOffsets(scoped, full, getBounds) {
38
+ if (scoped === full) return /* @__PURE__ */ new Map();
39
+ const scopedById = new Map(scoped.nodes.map((node) => [node.id, node]));
40
+ const fullById = new Map(full.nodes.map((node) => [node.id, node]));
41
+ return new Map(scoped.nodes.flatMap((node) => {
42
+ const original = fullById.get(node.id);
43
+ if (!original?.parentId || scopedById.has(original.parentId)) return [];
44
+ const parent = fullById.get(original.parentId);
45
+ return parent ? [[node.id, boundsOf(parent, getBounds)]] : [];
46
+ }));
47
+ }
48
+ function applyFlowGroupContracts(output, input, options, getBounds) {
49
+ const nodes = output.nodes.map((node) => ({ ...node }));
50
+ const edges = output.edges.map((edge) => ({ ...edge }));
51
+ const nodeById = new Map(nodes.map((node) => [node.id, node]));
52
+ const inputById = new Map(input.nodes.map((node) => [node.id, node]));
53
+ const edgeById = new Map(edges.map((edge) => [edge.id, edge]));
54
+ const depth = (id) => {
55
+ let value = 0;
56
+ let parentId = nodeById.get(id)?.parentId;
57
+ const seen = /* @__PURE__ */ new Set();
58
+ while (parentId && !seen.has(parentId)) {
59
+ seen.add(parentId);
60
+ value++;
61
+ parentId = nodeById.get(parentId)?.parentId;
62
+ }
63
+ return value;
64
+ };
65
+ const layoutSiblings = (parentId, direction, padding = 0) => {
66
+ const siblings = nodes.filter((node) => (node.parentId ?? void 0) === parentId);
67
+ if (siblings.length === 0) return;
68
+ const siblingIds = new Set(siblings.map((node) => node.id));
69
+ const owner = (id) => {
70
+ let node = nodeById.get(id);
71
+ const seen = /* @__PURE__ */ new Set();
72
+ while (node && !seen.has(node.id)) {
73
+ seen.add(node.id);
74
+ if (siblingIds.has(node.id)) return node.id;
75
+ node = node.parentId ? nodeById.get(node.parentId) : void 0;
76
+ }
77
+ };
78
+ const siblingEdges = edges.flatMap((edge) => {
79
+ const sourceId = owner(edge.sourceId);
80
+ const targetId = owner(edge.targetId);
81
+ if (!sourceId || !targetId || sourceId === targetId) return [];
82
+ if (sourceId === edge.sourceId && targetId === edge.targetId) return [edge];
83
+ return [{
84
+ ...edge,
85
+ id: `__flow_layout_proxy__${edge.id}`,
86
+ sourceId,
87
+ targetId,
88
+ x: 0,
89
+ y: 0,
90
+ width: 0,
91
+ height: 0,
92
+ points: void 0
93
+ }];
94
+ });
95
+ const laidOut = getLayeredLayout({
96
+ ...output,
97
+ direction,
98
+ nodes: siblings.map((node) => ({
99
+ ...node,
100
+ parentId: void 0
101
+ })),
102
+ edges: siblingEdges
103
+ }, {
104
+ ...options,
105
+ direction,
106
+ padding
107
+ });
108
+ for (const node of laidOut.nodes) Object.assign(nodeById.get(node.id), node, { parentId });
109
+ for (const edge of laidOut.edges) if (edgeById.has(edge.id)) edgeById.set(edge.id, edge);
110
+ };
111
+ const groups = input.nodes.filter(isGroup).sort((left, right) => depth(right.id) - depth(left.id));
112
+ for (const group of groups) {
113
+ const node = nodeById.get(group.id);
114
+ if (!node) continue;
115
+ const children = nodes.filter((child) => child.parentId === group.id);
116
+ if (children.length === 0) continue;
117
+ layoutSiblings(group.id, group.group.direction ?? input.direction);
118
+ const union = boundsUnion(children);
119
+ const original = boundsOf(inputById.get(group.id), getBounds);
120
+ const contentSize = group.group.type === "fixed" ? group.group.contentSize ?? {
121
+ width: 0,
122
+ height: 0
123
+ } : {
124
+ width: original.width,
125
+ height: original.height
126
+ };
127
+ const normalizedUnion = {
128
+ ...union,
129
+ x: 0,
130
+ y: 0
131
+ };
132
+ const geometry = group.group.type === "fixed" ? fixedGroupGeometry({
133
+ x: 0,
134
+ y: 0,
135
+ width: original.width,
136
+ height: original.height
137
+ }, contentSize, group.group) : deriveGroupGeometry(contentSize, normalizedUnion, group.group);
138
+ const derivedPadding = group.group.type === "derived" ? resolveGroupPadding(group.group.padding) : {
139
+ top: 0,
140
+ left: 0
141
+ };
142
+ const target = {
143
+ x: geometry.childArea.x - geometry.bounds.x + derivedPadding.left,
144
+ y: geometry.childArea.y - geometry.bounds.y + derivedPadding.top
145
+ };
146
+ shiftChildrenAndOwnedEdges(children, edgeById, target.x - union.x, target.y - union.y);
147
+ node.width = geometry.bounds.width;
148
+ node.height = geometry.bounds.height;
149
+ }
150
+ layoutSiblings(void 0, options.direction ?? input.direction, options.padding);
151
+ routeCrossBoundaryEdges({
152
+ ...output,
153
+ nodes,
154
+ edges: edges.map((edge) => edgeById.get(edge.id) ?? edge)
155
+ }, options.direction ?? input.direction ?? "down");
156
+ return {
157
+ ...output,
158
+ nodes,
159
+ edges: edges.map((edge) => edgeById.get(edge.id) ?? edge)
160
+ };
161
+ }
162
+ function routeCrossBoundaryEdges(graph, direction) {
163
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node]));
164
+ const absolute = (id) => {
165
+ const node = nodes.get(id);
166
+ if (!node) return {
167
+ x: 0,
168
+ y: 0
169
+ };
170
+ const parent = node.parentId ? absolute(node.parentId) : {
171
+ x: 0,
172
+ y: 0
173
+ };
174
+ return {
175
+ x: parent.x + node.x,
176
+ y: parent.y + node.y
177
+ };
178
+ };
179
+ const horizontal = direction === "left" || direction === "right";
180
+ const reverse = direction === "left" || direction === "up";
181
+ for (const edge of graph.edges) {
182
+ const sourceNode = nodes.get(edge.sourceId);
183
+ const targetNode = nodes.get(edge.targetId);
184
+ if (!sourceNode || !targetNode || sourceNode.parentId === targetNode.parentId) continue;
185
+ const source = {
186
+ ...absolute(sourceNode.id),
187
+ width: sourceNode.width,
188
+ height: sourceNode.height
189
+ };
190
+ const target = {
191
+ ...absolute(targetNode.id),
192
+ width: targetNode.width,
193
+ height: targetNode.height
194
+ };
195
+ const start = horizontal ? {
196
+ x: reverse ? source.x : source.x + source.width,
197
+ y: source.y + source.height / 2
198
+ } : {
199
+ x: source.x + source.width / 2,
200
+ y: reverse ? source.y : source.y + source.height
201
+ };
202
+ const end = horizontal ? {
203
+ x: reverse ? target.x + target.width : target.x,
204
+ y: target.y + target.height / 2
205
+ } : {
206
+ x: target.x + target.width / 2,
207
+ y: reverse ? target.y + target.height : target.y
208
+ };
209
+ const track = horizontal ? {
210
+ x: (start.x + end.x) / 2,
211
+ y: 0
212
+ } : {
213
+ x: 0,
214
+ y: (start.y + end.y) / 2
215
+ };
216
+ const container = getLCA(graph, edge.sourceId, edge.targetId);
217
+ const origin = container ? absolute(container.id) : {
218
+ x: 0,
219
+ y: 0
220
+ };
221
+ edge.points = (horizontal ? [
222
+ start,
223
+ {
224
+ x: track.x,
225
+ y: start.y
226
+ },
227
+ {
228
+ x: track.x,
229
+ y: end.y
230
+ },
231
+ end
232
+ ] : [
233
+ start,
234
+ {
235
+ x: start.x,
236
+ y: track.y
237
+ },
238
+ {
239
+ x: end.x,
240
+ y: track.y
241
+ },
242
+ end
243
+ ]).map((point) => ({
244
+ x: point.x - origin.x,
245
+ y: point.y - origin.y
246
+ }));
247
+ edge.routing = "orthogonal";
248
+ edge.x = (start.x + end.x) / 2 - origin.x - edge.width / 2;
249
+ edge.y = (start.y + end.y) / 2 - origin.y - edge.height / 2;
250
+ }
251
+ }
252
+ function boundsUnion(nodes) {
253
+ const left = Math.min(...nodes.map((node) => node.x));
254
+ const top = Math.min(...nodes.map((node) => node.y));
255
+ const right = Math.max(...nodes.map((node) => node.x + node.width));
256
+ const bottom = Math.max(...nodes.map((node) => node.y + node.height));
257
+ return {
258
+ x: left,
259
+ y: top,
260
+ width: right - left,
261
+ height: bottom - top
262
+ };
263
+ }
264
+ function shiftChildrenAndOwnedEdges(children, edges, dx, dy) {
265
+ const ids = new Set(children.map((node) => node.id));
266
+ for (const child of children) {
267
+ child.x += dx;
268
+ child.y += dy;
269
+ }
270
+ for (const edge of edges.values()) {
271
+ if (!ids.has(edge.sourceId) || !ids.has(edge.targetId)) continue;
272
+ edge.x += dx;
273
+ edge.y += dy;
274
+ if (edge.points) edge.points = edge.points.map((point) => ({
275
+ x: point.x + dx,
276
+ y: point.y + dy
277
+ }));
278
+ }
279
+ }
280
+ function toStatelyGraph(graph, getBounds) {
281
+ const boundsById = new Map(graph.nodes.map((node) => [node.id, boundsOf(node, getBounds)]));
282
+ return {
283
+ ...graph,
284
+ id: graph.id ?? "flow",
285
+ mode: graph.mode ?? "directed",
286
+ data: graph.data ?? {},
287
+ direction: graph.direction ?? "down",
288
+ nodes: graph.nodes.map((node) => {
289
+ const bounds = boundsById.get(node.id);
290
+ const parent = node.parentId ? boundsById.get(node.parentId) : void 0;
291
+ return {
292
+ ...node,
293
+ ...bounds,
294
+ x: bounds.x - (parent?.x ?? 0),
295
+ y: bounds.y - (parent?.y ?? 0)
296
+ };
297
+ }),
298
+ edges: graph.edges.map((edge) => {
299
+ const container = getLCA(graph, edge.sourceId, edge.targetId);
300
+ const origin = container ? boundsById.get(container.id) ?? {
301
+ x: 0,
302
+ y: 0
303
+ } : {
304
+ x: 0,
305
+ y: 0
306
+ };
307
+ return {
308
+ ...edge,
309
+ x: (edge.label?.x ?? edge.x ?? 0) - origin.x,
310
+ y: (edge.label?.y ?? edge.y ?? 0) - origin.y,
311
+ width: edge.label?.width ?? edge.width ?? 0,
312
+ height: edge.label?.height ?? edge.height ?? 0,
313
+ ...edge.points ? { points: edge.points.map((point) => ({
314
+ x: point.x - origin.x,
315
+ y: point.y - origin.y
316
+ })) } : {}
317
+ };
318
+ })
319
+ };
320
+ }
321
+ function fromStatelyGraph(graph, input, rootOffsets, fixedIds, getBounds, labelEdgeIds, details) {
322
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
323
+ const inputNodesById = new Map(input.nodes.map((node) => [node.id, node]));
324
+ const absolutePositions = /* @__PURE__ */ new Map();
325
+ const absolutePosition = (id, visiting = /* @__PURE__ */ new Set()) => {
326
+ const cached = absolutePositions.get(id);
327
+ if (cached) return cached;
328
+ const node = nodesById.get(id);
329
+ if (!node || visiting.has(id)) return {
330
+ x: 0,
331
+ y: 0
332
+ };
333
+ if (fixedIds.has(id)) {
334
+ const fixed = inputNodesById.get(id);
335
+ if (fixed) {
336
+ const position = boundsOf(fixed, getBounds);
337
+ absolutePositions.set(id, position);
338
+ return position;
339
+ }
340
+ }
341
+ visiting.add(id);
342
+ const parent = node.parentId ? absolutePosition(node.parentId, visiting) : rootOffsets.get(node.id) ?? {
343
+ x: 0,
344
+ y: 0
345
+ };
346
+ const position = {
347
+ x: parent.x + node.x,
348
+ y: parent.y + node.y
349
+ };
350
+ absolutePositions.set(id, position);
351
+ return position;
352
+ };
353
+ const rootAncestorId = (id) => {
354
+ let node = nodesById.get(id);
355
+ const seen = /* @__PURE__ */ new Set();
356
+ while (node?.parentId && !seen.has(node.id)) {
357
+ seen.add(node.id);
358
+ node = nodesById.get(node.parentId);
359
+ }
360
+ return node?.id ?? id;
361
+ };
362
+ const rootOffsetOf = (id) => rootOffsets.get(rootAncestorId(id)) ?? {
363
+ x: 0,
364
+ y: 0
365
+ };
366
+ const positions = /* @__PURE__ */ new Map();
367
+ const nodeSizes = /* @__PURE__ */ new Map();
368
+ const nodeBounds = /* @__PURE__ */ new Map();
369
+ for (const node of graph.nodes) {
370
+ if (fixedIds.has(node.id)) continue;
371
+ const position = absolutePosition(node.id);
372
+ const size = {
373
+ width: node.width,
374
+ height: node.height
375
+ };
376
+ positions.set(node.id, position);
377
+ nodeSizes.set(node.id, size);
378
+ nodeBounds.set(node.id, {
379
+ ...position,
380
+ ...size
381
+ });
382
+ }
383
+ const edgeLabelBounds = /* @__PURE__ */ new Map();
384
+ const edgeRoutes = /* @__PURE__ */ new Map();
385
+ for (const edge of graph.edges) {
386
+ if (fixedIds.has(edge.id)) continue;
387
+ if (fixedIds.has(edge.sourceId) || fixedIds.has(edge.targetId)) continue;
388
+ const container = getLCA(graph, edge.sourceId, edge.targetId);
389
+ const sourceOffset = rootOffsetOf(edge.sourceId);
390
+ const targetOffset = rootOffsetOf(edge.targetId);
391
+ if (!container && (sourceOffset.x !== targetOffset.x || sourceOffset.y !== targetOffset.y)) continue;
392
+ const origin = container ? absolutePosition(container.id) : sourceOffset;
393
+ if (labelEdgeIds.has(edge.id) && Number.isFinite(edge.x) && Number.isFinite(edge.y) && Number.isFinite(edge.width) && Number.isFinite(edge.height)) edgeLabelBounds.set(edge.id, {
394
+ x: origin.x + edge.x,
395
+ y: origin.y + edge.y,
396
+ width: edge.width,
397
+ height: edge.height
398
+ });
399
+ if (edge.points && edge.points.length >= 2) edgeRoutes.set(edge.id, {
400
+ points: edge.points.map((point) => ({
401
+ x: origin.x + point.x,
402
+ y: origin.y + point.y
403
+ })),
404
+ ...edge.routing ? { routing: edge.routing } : {}
405
+ });
406
+ }
407
+ return {
408
+ positions,
409
+ nodeSizes,
410
+ nodeBounds,
411
+ ...edgeLabelBounds.size > 0 ? {
412
+ edgeLabelBounds,
413
+ edgeLabelPositions: new Map([...edgeLabelBounds].map(([id, bounds]) => [id, {
414
+ x: bounds.x,
415
+ y: bounds.y
416
+ }]))
417
+ } : {},
418
+ ...edgeRoutes.size > 0 ? { edgeRoutes } : {},
419
+ ...details.diagnostics?.length ? { diagnostics: details.diagnostics } : {},
420
+ source: details.source,
421
+ metadata: details.metadata
422
+ };
423
+ }
424
+ //#endregion
425
+ export { statelyLayout };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statelyai/flow",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Framework-agnostic flow visualization engine. Builds on @statelyai/graph.",
5
5
  "type": "module",
6
6
  "sideEffects": true,
@@ -39,6 +39,12 @@
39
39
  "import": "./dist/esm/layout/elk.js",
40
40
  "default": "./dist/esm/layout/elk.js"
41
41
  },
42
+ "./layout/stately": {
43
+ "source": "./src/layout/stately.ts",
44
+ "types": "./dist/esm/layout/stately.d.ts",
45
+ "import": "./dist/esm/layout/stately.js",
46
+ "default": "./dist/esm/layout/stately.js"
47
+ },
42
48
  "./layout/dagre": {
43
49
  "source": "./src/layout/dagre.ts",
44
50
  "types": "./dist/esm/layout/dagre.d.ts",
@@ -53,12 +59,16 @@
53
59
  "peerDependencies": {
54
60
  "@dagrejs/dagre": ">=3.0.0",
55
61
  "@statelyai/graph": ">=2.1.0",
62
+ "@statelyai/layout": ">=0.0.5",
56
63
  "elkjs": ">=0.11.0"
57
64
  },
58
65
  "peerDependenciesMeta": {
59
66
  "@dagrejs/dagre": {
60
67
  "optional": true
61
68
  },
69
+ "@statelyai/layout": {
70
+ "optional": true
71
+ },
62
72
  "elkjs": {
63
73
  "optional": true
64
74
  }
@@ -66,6 +76,7 @@
66
76
  "devDependencies": {
67
77
  "@dagrejs/dagre": "^3.0.0",
68
78
  "@statelyai/graph": "^2.1.0",
79
+ "@statelyai/layout": "^0.0.5",
69
80
  "@vitest/coverage-v8": "^4.1.0",
70
81
  "elkjs": "^0.11.1",
71
82
  "tsdown": "^0.22.13",