@statelyai/flow 0.5.0 → 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 CHANGED
@@ -52,6 +52,58 @@ const selectedBounds = flow.getSelectionBounds();
52
52
  `createFlow()` owns the store and engine together. Use `createFlowStore()` and
53
53
  `createFlowEngine()` directly when you need lower-level control.
54
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
+
55
107
  ## Data model
56
108
 
57
109
  The canonical data model is `VisualGraph` from `@statelyai/graph`. Flow extends it with:
@@ -0,0 +1,6 @@
1
+ import { n as FlowLayoutFactory, r as FlowLayoutOptions } from "../shared.js";
2
+ //#region src/layout/dagre.d.ts
3
+ type DagreLayoutOptions<TNodeData = any, TEdgeData = any, TLabelData = any> = FlowLayoutOptions<TNodeData, TEdgeData, TLabelData>;
4
+ declare const dagreLayout: FlowLayoutFactory;
5
+ //#endregion
6
+ export { DagreLayoutOptions, dagreLayout };
@@ -0,0 +1,106 @@
1
+ import { i as layoutRunContext, n as edgeLabelPositionsFromNodePositions, o as rankDirection, s as throwIfAborted, t as boundsOf } from "../shared.js";
2
+ import * as dagre from "@dagrejs/dagre";
3
+ //#region src/layout/dagre.ts
4
+ const dagreLayout = (options = {}) => {
5
+ return async (graph, runOptions = {}) => {
6
+ throwIfAborted(runOptions);
7
+ if (options.scope || runOptions.scope) throw new Error("dagreLayout does not support scope/incremental layout.");
8
+ const mutableGraph = graph;
9
+ const context = layoutRunContext(mutableGraph, options, runOptions, "dagre");
10
+ if (graph.nodes.some((node) => node.parentId)) {
11
+ const message = "dagreLayout flattens parentId hierarchy; use elkLayout for compound layout.";
12
+ options.onWarning?.(message);
13
+ context.diagnostics.push({
14
+ severity: "warning",
15
+ code: "flattened-hierarchy",
16
+ message
17
+ });
18
+ }
19
+ const g = new dagre.graphlib.Graph({ multigraph: true });
20
+ g.setGraph({
21
+ rankdir: rankDirection(options.direction ?? graph.direction),
22
+ nodesep: options.nodeSpacing ?? 60,
23
+ ranksep: options.rankSpacing ?? 90,
24
+ ...options.graph
25
+ });
26
+ g.setDefaultEdgeLabel(() => ({}));
27
+ for (const node of graph.nodes) {
28
+ const bounds = boundsOf(node, options.getBounds);
29
+ g.setNode(node.id, {
30
+ width: bounds.width,
31
+ height: bounds.height,
32
+ ...options.node
33
+ });
34
+ }
35
+ for (const edge of graph.edges) g.setEdge(edge.sourceId, edge.targetId, {
36
+ width: edge.label?.width ?? 0,
37
+ height: edge.label?.height ?? 0,
38
+ ...options.edge
39
+ }, edge.id);
40
+ dagre.layout(g);
41
+ throwIfAborted(runOptions);
42
+ const positions = /* @__PURE__ */ new Map();
43
+ const nodeSizes = /* @__PURE__ */ new Map();
44
+ const nodeBounds = /* @__PURE__ */ new Map();
45
+ for (const node of graph.nodes) {
46
+ if (context.fixedIds.has(node.id)) continue;
47
+ const laidOut = g.node(node.id);
48
+ if (!laidOut) continue;
49
+ const position = {
50
+ x: laidOut.x - laidOut.width / 2,
51
+ y: laidOut.y - laidOut.height / 2
52
+ };
53
+ const size = {
54
+ width: laidOut.width,
55
+ height: laidOut.height
56
+ };
57
+ positions.set(node.id, position);
58
+ nodeSizes.set(node.id, size);
59
+ nodeBounds.set(node.id, {
60
+ ...position,
61
+ ...size
62
+ });
63
+ }
64
+ const edgeLabelPositions = dagreEdgeLabelPositions(mutableGraph, g) ?? edgeLabelPositionsFromNodePositions(mutableGraph, positions, options.getBounds);
65
+ const edgeLabelBounds = /* @__PURE__ */ new Map();
66
+ for (const edge of graph.edges) {
67
+ if (!edge.label || context.fixedIds.has(edge.id)) continue;
68
+ const position = edgeLabelPositions?.get(edge.id);
69
+ if (!position) continue;
70
+ edgeLabelBounds.set(edge.id, {
71
+ ...position,
72
+ width: edge.label.width,
73
+ height: edge.label.height
74
+ });
75
+ }
76
+ return {
77
+ positions,
78
+ nodeSizes,
79
+ nodeBounds,
80
+ ...edgeLabelPositions ? { edgeLabelPositions: new Map([...edgeLabelPositions].filter(([id]) => !context.fixedIds.has(id))) } : {},
81
+ ...edgeLabelBounds.size > 0 ? { edgeLabelBounds } : {},
82
+ ...context.diagnostics.length > 0 ? { diagnostics: context.diagnostics } : {},
83
+ source: context.source,
84
+ metadata: context.metadata
85
+ };
86
+ };
87
+ };
88
+ function dagreEdgeLabelPositions(graph, g) {
89
+ const labels = /* @__PURE__ */ new Map();
90
+ for (const edge of graph.edges) {
91
+ if (!edge.label) continue;
92
+ const laidOut = g.edge({
93
+ v: edge.sourceId,
94
+ w: edge.targetId,
95
+ name: edge.id
96
+ });
97
+ if (!laidOut || typeof laidOut.x !== "number" || typeof laidOut.y !== "number") continue;
98
+ labels.set(edge.id, {
99
+ x: laidOut.x - edge.label.width / 2,
100
+ y: laidOut.y - edge.label.height / 2
101
+ });
102
+ }
103
+ return labels.size > 0 ? labels : void 0;
104
+ }
105
+ //#endregion
106
+ export { dagreLayout };
@@ -0,0 +1,9 @@
1
+ import { n as FlowLayoutFactory, r as FlowLayoutOptions } from "../shared.js";
2
+ import { FlowGraph } from "@statelyai/flow";
3
+ import { ElkNode } from "elkjs/lib/elk-api";
4
+ //#region src/layout/elk.d.ts
5
+ type ElkLayoutOptions<TNodeData = any, TEdgeData = any, TLabelData = any> = FlowLayoutOptions<TNodeData, TEdgeData, TLabelData>;
6
+ declare const elkLayout: FlowLayoutFactory;
7
+ declare function toElkGraph(graph: FlowGraph, options: FlowLayoutOptions): ElkNode;
8
+ //#endregion
9
+ export { ElkLayoutOptions, elkLayout, toElkGraph };
@@ -0,0 +1,237 @@
1
+ import { a as mergedLayoutScope, i as layoutRunContext, n as edgeLabelPositionsFromNodePositions, o as rankDirection, r as graphForLayoutScope, s as throwIfAborted, t as boundsOf } from "../shared.js";
2
+ import { isGroup, resolveGroupPadding } from "@statelyai/flow";
3
+ import ELK from "elkjs/lib/elk.bundled.js";
4
+ //#region src/layout/elk.ts
5
+ const elkLayout = (options = {}) => {
6
+ const elk = new ELK();
7
+ return async (graph, runOptions = {}) => {
8
+ throwIfAborted(runOptions);
9
+ const mutableGraph = graph;
10
+ const scope = mergedLayoutScope(mutableGraph, options.scope, runOptions);
11
+ const layoutGraph = graphForLayoutScope(mutableGraph, scope);
12
+ const context = layoutRunContext(mutableGraph, options, runOptions, "elk");
13
+ const result = await elk.layout(toElkGraph(layoutGraph, {
14
+ ...options,
15
+ scope
16
+ }));
17
+ throwIfAborted(runOptions);
18
+ const positions = /* @__PURE__ */ new Map();
19
+ const nodeSizes = /* @__PURE__ */ new Map();
20
+ const nodeBounds = /* @__PURE__ */ new Map();
21
+ const edgeLabelBounds = /* @__PURE__ */ new Map();
22
+ const edgeRoutes = /* @__PURE__ */ new Map();
23
+ collectElkGeometry(result, {
24
+ positions,
25
+ nodeSizes,
26
+ nodeBounds,
27
+ edgeLabelBounds,
28
+ edgeRoutes,
29
+ fixedIds: context.fixedIds
30
+ });
31
+ const edgeLabelPositions = new Map([...edgeLabelBounds].map(([id, bounds]) => [id, {
32
+ x: bounds.x,
33
+ y: bounds.y
34
+ }]));
35
+ const fallbackLabels = edgeLabelPositionsFromNodePositions(layoutGraph, positions, options.getBounds);
36
+ for (const [id, position] of fallbackLabels ?? []) if (!edgeLabelPositions.has(id) && !context.fixedIds.has(id)) edgeLabelPositions.set(id, position);
37
+ const missingNodes = layoutGraph.nodes.map((node) => node.id).filter((id) => !context.fixedIds.has(id) && !positions.has(id)).sort();
38
+ if (missingNodes.length > 0) {
39
+ const message = `ELK omitted node geometry: ${missingNodes.join(", ")}`;
40
+ context.diagnostics.push({
41
+ severity: "warning",
42
+ code: "missing-node",
43
+ message
44
+ });
45
+ options.onWarning?.(message);
46
+ }
47
+ return {
48
+ positions,
49
+ nodeSizes,
50
+ nodeBounds,
51
+ ...edgeLabelPositions.size > 0 ? { edgeLabelPositions } : {},
52
+ ...edgeLabelBounds.size > 0 ? { edgeLabelBounds } : {},
53
+ ...edgeRoutes.size > 0 ? { edgeRoutes } : {},
54
+ ...context.diagnostics.length > 0 ? { diagnostics: context.diagnostics } : {},
55
+ source: context.source,
56
+ metadata: context.metadata
57
+ };
58
+ };
59
+ };
60
+ const SIDE_TO_ELK = {
61
+ top: "NORTH",
62
+ bottom: "SOUTH",
63
+ left: "WEST",
64
+ right: "EAST"
65
+ };
66
+ function toElkGraph(graph, options) {
67
+ const childIdsByParent = /* @__PURE__ */ new Map();
68
+ for (const node of graph.nodes) {
69
+ const parentId = node.parentId ?? void 0;
70
+ const siblings = childIdsByParent.get(parentId) ?? [];
71
+ siblings.push(node.id);
72
+ childIdsByParent.set(parentId, siblings);
73
+ }
74
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
75
+ const edgesByContainer = /* @__PURE__ */ new Map();
76
+ for (const edge of graph.edges) {
77
+ const containerId = edgeContainerId(edge, nodesById);
78
+ const bucket = edgesByContainer.get(containerId) ?? [];
79
+ bucket.push(toElkEdge(edge, options));
80
+ edgesByContainer.set(containerId, bucket);
81
+ }
82
+ return {
83
+ id: "root",
84
+ layoutOptions: {
85
+ "elk.algorithm": "layered",
86
+ "elk.direction": rankDirection(options.direction ?? graph.direction),
87
+ "elk.spacing.nodeNode": String(options.nodeSpacing ?? 60),
88
+ "elk.layered.spacing.nodeNodeBetweenLayers": String(options.rankSpacing ?? 90),
89
+ ...options.scope ? { "elk.interactive": "true" } : {},
90
+ ...stringOptions(options.graph)
91
+ },
92
+ children: (childIdsByParent.get(void 0) ?? []).map((id) => toElkNode(nodesById.get(id), childIdsByParent, nodesById, edgesByContainer, options)),
93
+ edges: edgesByContainer.get(void 0) ?? []
94
+ };
95
+ }
96
+ function toElkEdge(edge, options) {
97
+ return {
98
+ id: edge.id,
99
+ sources: [edge.sourcePort ? `${edge.sourceId}:${edge.sourcePort}` : edge.sourceId],
100
+ targets: [edge.targetPort ? `${edge.targetId}:${edge.targetPort}` : edge.targetId],
101
+ labels: edge.label ? [{
102
+ id: `${edge.id}:label`,
103
+ width: edge.label.width,
104
+ height: edge.label.height
105
+ }] : void 0,
106
+ ...options.edge
107
+ };
108
+ }
109
+ /**
110
+ * The container node an edge belongs in for ELK hierarchy: the Lowest Common
111
+ * Ancestor group of its source & target (undefined = root). Walk the source's
112
+ * ancestor chain (including the source itself) into a set, then walk the
113
+ * target's chain up until it hits a member of that set. An edge whose
114
+ * endpoints are both children of group G resolves to G; a cross-boundary edge
115
+ * resolves to the shared ancestor (often root/undefined).
116
+ */
117
+ function edgeContainerId(edge, nodesById) {
118
+ const source = nodesById.get(edge.sourceId);
119
+ const target = edge.targetId ? nodesById.get(edge.targetId) : void 0;
120
+ if (!source) return void 0;
121
+ if (!target || source === target) return source.parentId ?? void 0;
122
+ const ancestors = /* @__PURE__ */ new Set([source.id]);
123
+ let marker = source.parentId ? nodesById.get(source.parentId) : void 0;
124
+ while (marker) {
125
+ ancestors.add(marker.id);
126
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
127
+ }
128
+ marker = target;
129
+ while (marker) {
130
+ if (ancestors.has(marker.id)) return marker.id;
131
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
132
+ }
133
+ }
134
+ function toElkNode(node, childIdsByParent, nodesById, edgesByContainer, options) {
135
+ const bounds = boundsOf(node, options.getBounds);
136
+ const children = (childIdsByParent.get(node.id) ?? []).map((id) => toElkNode(nodesById.get(id), childIdsByParent, nodesById, edgesByContainer, options));
137
+ const ports = (node.ports ?? []).map((port) => ({
138
+ id: `${node.id}:${port.name}`,
139
+ x: port.x,
140
+ y: port.y,
141
+ width: port.width,
142
+ height: port.height,
143
+ layoutOptions: { "elk.port.side": SIDE_TO_ELK[port.side ?? "right"] ?? "EAST" }
144
+ }));
145
+ const isCompound = children.length > 0 && isGroup(node);
146
+ const layoutOptions = {};
147
+ if (ports.length > 0) layoutOptions["elk.portConstraints"] = "FIXED_SIDE";
148
+ if (isCompound) {
149
+ layoutOptions["elk.hierarchyHandling"] = "INCLUDE_CHILDREN";
150
+ layoutOptions["elk.padding"] = elkPadding(groupInsets(node.group, {
151
+ width: bounds.width,
152
+ height: bounds.height
153
+ }));
154
+ layoutOptions["elk.nodeSize.constraints"] = "NODE_LABELS PORTS MINIMUM_SIZE";
155
+ }
156
+ const nestedEdges = edgesByContainer.get(node.id);
157
+ const elkNode = {
158
+ id: node.id,
159
+ x: node.x,
160
+ y: node.y,
161
+ ports,
162
+ layoutOptions: Object.keys(layoutOptions).length > 0 ? layoutOptions : void 0,
163
+ children: children.length > 0 ? children : void 0,
164
+ edges: nestedEdges && nestedEdges.length > 0 ? nestedEdges : void 0,
165
+ ...options.node
166
+ };
167
+ if (!isCompound) {
168
+ elkNode.width = bounds.width;
169
+ elkNode.height = bounds.height;
170
+ }
171
+ return elkNode;
172
+ }
173
+ /**
174
+ * The inset ELK must leave inside a compound so children clear the group's
175
+ * content block (header) and honor its padding. The content block occupies
176
+ * one side at `contentSize` (fixed groups) or the node's own size (derived
177
+ * groups); every side also carries the group's padding.
178
+ */
179
+ function groupInsets(group, bounds) {
180
+ const padding = resolveGroupPadding(group.padding);
181
+ const side = group.content ?? "top";
182
+ const contentSize = group.type === "fixed" ? group.contentSize ?? {
183
+ width: 0,
184
+ height: 0
185
+ } : bounds;
186
+ const insets = { ...padding };
187
+ if (side === "top") insets.top += contentSize.height;
188
+ else if (side === "bottom") insets.bottom += contentSize.height;
189
+ else if (side === "left") insets.left += contentSize.width;
190
+ else insets.right += contentSize.width;
191
+ return insets;
192
+ }
193
+ function elkPadding(insets) {
194
+ return `[top=${insets.top},left=${insets.left},bottom=${insets.bottom},right=${insets.right}]`;
195
+ }
196
+ function collectElkGeometry(node, output, offsetX = 0, offsetY = 0) {
197
+ const x = offsetX + (node.x ?? 0);
198
+ const y = offsetY + (node.y ?? 0);
199
+ if (node.id !== "root" && !output.fixedIds.has(node.id) && Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(node.width) && Number.isFinite(node.height)) {
200
+ const size = {
201
+ width: node.width,
202
+ height: node.height
203
+ };
204
+ output.positions.set(node.id, {
205
+ x,
206
+ y
207
+ });
208
+ output.nodeSizes.set(node.id, size);
209
+ output.nodeBounds.set(node.id, {
210
+ x,
211
+ y,
212
+ ...size
213
+ });
214
+ }
215
+ for (const edge of node.edges ?? []) {
216
+ if (output.fixedIds.has(edge.id)) continue;
217
+ const label = edge.labels?.[0];
218
+ if (label && Number.isFinite(label.x) && Number.isFinite(label.y) && Number.isFinite(label.width) && Number.isFinite(label.height)) output.edgeLabelBounds.set(edge.id, {
219
+ x: x + label.x,
220
+ y: y + label.y,
221
+ width: label.width,
222
+ height: label.height
223
+ });
224
+ const sections = edge.sections ?? [];
225
+ if (sections.length === 1) output.edgeRoutes.set(edge.id, { waypoints: (sections[0].bendPoints ?? []).map((point) => ({
226
+ x: x + point.x,
227
+ y: y + point.y
228
+ })) });
229
+ }
230
+ for (const child of node.children ?? []) collectElkGeometry(child, output, x, y);
231
+ }
232
+ function stringOptions(options) {
233
+ if (!options) return {};
234
+ return Object.fromEntries(Object.entries(options).map(([key, value]) => [key, String(value)]));
235
+ }
236
+ //#endregion
237
+ export { elkLayout, toElkGraph };
@@ -0,0 +1,4 @@
1
+ import { i as FlowLayoutScope, n as FlowLayoutFactory, r as FlowLayoutOptions, t as FlowLayoutAlgorithm } from "../shared.js";
2
+ import { DagreLayoutOptions, dagreLayout } from "./dagre.js";
3
+ import { ElkLayoutOptions, elkLayout } from "./elk.js";
4
+ export { type DagreLayoutOptions, type ElkLayoutOptions, type FlowLayoutAlgorithm, type FlowLayoutFactory, type FlowLayoutOptions, type FlowLayoutScope, dagreLayout, elkLayout };
@@ -0,0 +1,3 @@
1
+ import { dagreLayout } from "./dagre.js";
2
+ import { elkLayout } from "./elk.js";
3
+ export { dagreLayout, elkLayout };
@@ -0,0 +1,28 @@
1
+ import { FlowGraph, FlowNode, LayoutPositions, LayoutResult, LayoutRunOptions, Rect } from "@statelyai/flow";
2
+ //#region src/layout/shared.d.ts
3
+ type FlowLayoutScope = {
4
+ ids: string[];
5
+ };
6
+ type FlowLayoutOptions<TNodeData = any, TEdgeData = any, TLabelData = any> = {
7
+ getBounds?: (node: FlowNode<TNodeData>) => Rect;
8
+ scope?: FlowLayoutScope;
9
+ onWarning?: (message: string) => void;
10
+ nodeSpacing?: number;
11
+ rankSpacing?: number;
12
+ direction?: 'down' | 'right' | 'up' | 'left';
13
+ graph?: Record<string, unknown>;
14
+ node?: Record<string, unknown>;
15
+ edge?: Record<string, unknown>;
16
+ label?: Record<string, unknown>;
17
+ source?: string;
18
+ metadata?: Readonly<Record<string, unknown>>;
19
+ _types?: {
20
+ node?: TNodeData;
21
+ edge?: TEdgeData;
22
+ label?: TLabelData;
23
+ };
24
+ };
25
+ type FlowLayoutFactory<TNodeData = any, TEdgeData = any, TLabelData = any> = (options?: FlowLayoutOptions<TNodeData, TEdgeData, TLabelData>) => FlowLayoutAlgorithm<TNodeData, TEdgeData, TLabelData>;
26
+ type FlowLayoutAlgorithm<TNodeData = any, TEdgeData = any, TLabelData = any> = (graph: Readonly<FlowGraph<TNodeData, TEdgeData, TLabelData>>, options?: LayoutRunOptions) => Promise<LayoutResult | LayoutPositions>;
27
+ //#endregion
28
+ export { FlowLayoutScope as i, FlowLayoutFactory as n, FlowLayoutOptions as r, FlowLayoutAlgorithm as t };
@@ -0,0 +1,91 @@
1
+ import { deriveFlowView, resolvedBounds } from "@statelyai/flow";
2
+ //#region src/layout/shared.ts
3
+ function boundsOf(node, getBounds) {
4
+ const bounds = getBounds?.(node) ?? resolvedBounds(node);
5
+ if (!Number.isFinite(bounds.x) || !Number.isFinite(bounds.y) || !Number.isFinite(bounds.width) || !Number.isFinite(bounds.height) || bounds.width < 0 || bounds.height < 0) throw new TypeError(`Layout bounds for node "${node.id}" must be finite with non-negative size.`);
6
+ return bounds;
7
+ }
8
+ /**
9
+ * Build the induced graph used by a scoped layout. Out-of-scope nodes never
10
+ * reach the engine; scoped nodes with an excluded parent become roots.
11
+ */
12
+ function graphForLayoutScope(graph, scope) {
13
+ if (!scope) return graph;
14
+ const ids = new Set(scope.ids);
15
+ const knownIds = new Set(graph.nodes.map((node) => node.id));
16
+ const unknownIds = [...ids].filter((id) => !knownIds.has(id)).sort();
17
+ if (unknownIds.length > 0) throw new TypeError(`Layout scope contains unknown node ids: ${unknownIds.join(", ")}`);
18
+ return {
19
+ ...graph,
20
+ nodes: graph.nodes.filter((node) => ids.has(node.id)).map((node) => node.parentId && !ids.has(node.parentId) ? {
21
+ ...node,
22
+ parentId: void 0
23
+ } : node),
24
+ edges: graph.edges.filter((edge) => ids.has(edge.sourceId) && ids.has(edge.targetId))
25
+ };
26
+ }
27
+ function mergedLayoutScope(graph, factoryScope, runOptions) {
28
+ if (!factoryScope && !runOptions.scope) return void 0;
29
+ const knownIds = new Set(graph.nodes.map((node) => node.id));
30
+ if (runOptions.scope?.parentId && !knownIds.has(runOptions.scope.parentId)) throw new TypeError(`Layout scope contains unknown parent id: ${runOptions.scope.parentId}`);
31
+ const unknownFactoryIds = (factoryScope?.ids ?? []).filter((id) => !knownIds.has(id)).sort();
32
+ if (unknownFactoryIds.length > 0) throw new TypeError(`Layout scope contains unknown node ids: ${unknownFactoryIds.join(", ")}`);
33
+ const factoryIds = factoryScope ? new Set(factoryScope.ids) : null;
34
+ const structuralIds = runOptions.scope ? new Set(deriveFlowView(graph, runOptions.scope, {
35
+ nodes: graph.nodes,
36
+ edges: graph.edges
37
+ }).nodes.map((node) => node.id)) : null;
38
+ return { ids: graph.nodes.map((node) => node.id).filter((id) => (!factoryIds || factoryIds.has(id)) && (!structuralIds || structuralIds.has(id))) };
39
+ }
40
+ function layoutRunContext(graph, factoryOptions, runOptions, adapter) {
41
+ const knownIds = /* @__PURE__ */ new Set([...graph.nodes.map((node) => node.id), ...graph.edges.map((edge) => edge.id)]);
42
+ const fixedIds = /* @__PURE__ */ new Set([...runOptions.fixedEntityIds ?? [], ...runOptions.pinnedEntityIds ?? []]);
43
+ const unknown = [...fixedIds].filter((id) => !knownIds.has(id)).sort();
44
+ if (unknown.length > 0) throw new TypeError(`Layout fixed/pinned ids are unknown: ${unknown.join(", ")}`);
45
+ return {
46
+ fixedIds,
47
+ source: runOptions.source ?? factoryOptions.source ?? adapter,
48
+ metadata: {
49
+ ...runOptions.previousResult?.metadata ?? {},
50
+ ...factoryOptions.metadata ?? {},
51
+ ...runOptions.metadata ?? {},
52
+ adapter
53
+ },
54
+ diagnostics: []
55
+ };
56
+ }
57
+ function throwIfAborted(options) {
58
+ if (!options.signal?.aborted) return;
59
+ const error = /* @__PURE__ */ new Error("Layout aborted.");
60
+ error.name = "AbortError";
61
+ throw error;
62
+ }
63
+ function edgeLabelPositionsFromNodePositions(graph, positions, getBounds) {
64
+ const labels = /* @__PURE__ */ new Map();
65
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node]));
66
+ for (const edge of graph.edges) {
67
+ if (!edge.label) continue;
68
+ const source = nodes.get(edge.sourceId);
69
+ const target = nodes.get(edge.targetId);
70
+ if (!source || !target) continue;
71
+ const sourceBounds = boundsOf(source, getBounds);
72
+ const targetBounds = boundsOf(target, getBounds);
73
+ const sourcePosition = positions.get(source.id) ?? sourceBounds;
74
+ const targetPosition = positions.get(target.id) ?? targetBounds;
75
+ labels.set(edge.id, {
76
+ x: (sourcePosition.x + targetPosition.x + targetBounds.width) / 2 - edge.label.width / 2,
77
+ y: (sourcePosition.y + targetPosition.y + targetBounds.height) / 2 - edge.label.height / 2
78
+ });
79
+ }
80
+ return labels.size > 0 ? labels : void 0;
81
+ }
82
+ function rankDirection(direction) {
83
+ switch (direction) {
84
+ case "right": return "LR";
85
+ case "up": return "BT";
86
+ case "left": return "RL";
87
+ default: return "TB";
88
+ }
89
+ }
90
+ //#endregion
91
+ export { mergedLayoutScope as a, layoutRunContext as i, edgeLabelPositionsFromNodePositions as n, rankDirection as o, graphForLayoutScope as r, throwIfAborted as s, boundsOf as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statelyai/flow",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Framework-agnostic flow visualization engine. Builds on @statelyai/graph.",
5
5
  "type": "module",
6
6
  "sideEffects": true,
@@ -26,6 +26,24 @@
26
26
  "types": "./dist/esm/index.d.ts",
27
27
  "import": "./dist/esm/index.js",
28
28
  "default": "./dist/esm/index.js"
29
+ },
30
+ "./layout": {
31
+ "source": "./src/layout/index.ts",
32
+ "types": "./dist/esm/layout/index.d.ts",
33
+ "import": "./dist/esm/layout/index.js",
34
+ "default": "./dist/esm/layout/index.js"
35
+ },
36
+ "./layout/elk": {
37
+ "source": "./src/layout/elk.ts",
38
+ "types": "./dist/esm/layout/elk.d.ts",
39
+ "import": "./dist/esm/layout/elk.js",
40
+ "default": "./dist/esm/layout/elk.js"
41
+ },
42
+ "./layout/dagre": {
43
+ "source": "./src/layout/dagre.ts",
44
+ "types": "./dist/esm/layout/dagre.d.ts",
45
+ "import": "./dist/esm/layout/dagre.js",
46
+ "default": "./dist/esm/layout/dagre.js"
29
47
  }
30
48
  },
31
49
  "dependencies": {
@@ -33,9 +51,20 @@
33
51
  "immer": "^10.0.0"
34
52
  },
35
53
  "peerDependencies": {
36
- "@statelyai/graph": ">=2.1.0"
54
+ "@dagrejs/dagre": ">=3.0.0",
55
+ "@statelyai/graph": ">=2.1.0",
56
+ "elkjs": ">=0.11.0"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "@dagrejs/dagre": {
60
+ "optional": true
61
+ },
62
+ "elkjs": {
63
+ "optional": true
64
+ }
37
65
  },
38
66
  "devDependencies": {
67
+ "@dagrejs/dagre": "^3.0.0",
39
68
  "@statelyai/graph": "^2.1.0",
40
69
  "@vitest/coverage-v8": "^4.1.0",
41
70
  "elkjs": "^0.11.1",