@umodeapporg/ui 0.23.1 → 0.24.1

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.
Files changed (57) hide show
  1. package/dist/assets/umode-ui.css +100 -0
  2. package/dist/components/UI/Flow/FlowBlockNode.d.ts +35 -0
  3. package/dist/components/UI/Flow/FlowBlockNode.js +84 -0
  4. package/dist/components/UI/Flow/FlowBlockNode.js.map +1 -0
  5. package/dist/components/UI/Flow/FlowCanvas.d.ts +21 -0
  6. package/dist/components/UI/Flow/FlowCanvas.js +252 -0
  7. package/dist/components/UI/Flow/FlowCanvas.js.map +1 -0
  8. package/dist/components/UI/Flow/FlowConnectionEdge.d.ts +18 -0
  9. package/dist/components/UI/Flow/FlowConnectionEdge.js +115 -0
  10. package/dist/components/UI/Flow/FlowConnectionEdge.js.map +1 -0
  11. package/dist/components/UI/Flow/FlowEditorProvider.d.ts +17 -0
  12. package/dist/components/UI/Flow/FlowEditorProvider.js +27 -0
  13. package/dist/components/UI/Flow/FlowEditorProvider.js.map +1 -0
  14. package/dist/components/UI/Flow/FlowInspector.d.ts +11 -0
  15. package/dist/components/UI/Flow/FlowInspector.js +127 -0
  16. package/dist/components/UI/Flow/FlowInspector.js.map +1 -0
  17. package/dist/components/UI/Flow/FlowIssueList.d.ts +8 -0
  18. package/dist/components/UI/Flow/FlowIssueList.js +55 -0
  19. package/dist/components/UI/Flow/FlowIssueList.js.map +1 -0
  20. package/dist/components/UI/Flow/FlowLaneMap.d.ts +30 -0
  21. package/dist/components/UI/Flow/FlowLaneMap.js +206 -0
  22. package/dist/components/UI/Flow/FlowLaneMap.js.map +1 -0
  23. package/dist/components/UI/Flow/FlowNodeShell.d.ts +20 -0
  24. package/dist/components/UI/Flow/FlowNodeShell.js +81 -0
  25. package/dist/components/UI/Flow/FlowNodeShell.js.map +1 -0
  26. package/dist/components/UI/Flow/FlowResizablePanel.d.ts +20 -0
  27. package/dist/components/UI/Flow/FlowResizablePanel.js +117 -0
  28. package/dist/components/UI/Flow/FlowResizablePanel.js.map +1 -0
  29. package/dist/components/UI/Flow/FlowZoomControls.d.ts +12 -0
  30. package/dist/components/UI/Flow/FlowZoomControls.js +53 -0
  31. package/dist/components/UI/Flow/FlowZoomControls.js.map +1 -0
  32. package/dist/components/UI/Flow/flowBlockRegistry.d.ts +12 -0
  33. package/dist/components/UI/Flow/flowBlockRegistry.js +20 -0
  34. package/dist/components/UI/Flow/flowBlockRegistry.js.map +1 -0
  35. package/dist/components/UI/Flow/flowEditorStore.d.ts +49 -0
  36. package/dist/components/UI/Flow/flowEditorStore.js +302 -0
  37. package/dist/components/UI/Flow/flowEditorStore.js.map +1 -0
  38. package/dist/components/UI/Flow/flowGraph.d.ts +32 -0
  39. package/dist/components/UI/Flow/flowGraph.js +157 -0
  40. package/dist/components/UI/Flow/flowGraph.js.map +1 -0
  41. package/dist/components/UI/Flow/flowTypes.d.ts +74 -0
  42. package/dist/components/UI/Flow/flowTypes.js +2 -0
  43. package/dist/components/UI/Flow/flowTypes.js.map +1 -0
  44. package/dist/components/UI/Flow/index.d.ts +12 -0
  45. package/dist/components/UI/Flow/index.js +40 -0
  46. package/dist/components/UI/Flow/index.js.map +1 -0
  47. package/dist/components/UI/Flow/useFlowLabels.d.ts +10 -0
  48. package/dist/components/UI/Flow/useFlowLabels.js +51 -0
  49. package/dist/components/UI/Flow/useFlowLabels.js.map +1 -0
  50. package/dist/locales/en/ui.json.d.ts +64 -0
  51. package/dist/locales/en/ui.json.js +3 -0
  52. package/dist/locales/en/ui.json.js.map +1 -1
  53. package/dist/locales/index.d.ts +128 -0
  54. package/dist/locales/pt/ui.json.d.ts +64 -0
  55. package/dist/locales/pt/ui.json.js +3 -0
  56. package/dist/locales/pt/ui.json.js.map +1 -1
  57. package/package.json +10 -1
@@ -0,0 +1,49 @@
1
+ import { StoreApi } from 'zustand/vanilla';
2
+ import { IFlowBlockRegistry } from './flowBlockRegistry';
3
+ import { IFlowGraph, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';
4
+ export interface IFlowEditorState {
5
+ graph: IFlowGraph;
6
+ selectedNodeIds: Array<string>;
7
+ selectedEdgeIds: Array<string>;
8
+ past: Array<IFlowGraph>;
9
+ future: Array<IFlowGraph>;
10
+ clipboard: Array<IFlowNode>;
11
+ isDirty: boolean;
12
+ replaceGraph: (graph: IFlowGraph, options?: {
13
+ keepHistory?: boolean;
14
+ }) => void;
15
+ markClean: () => void;
16
+ /** Snapshot before a gesture that changes the graph in many small steps (a drag). */
17
+ recordHistory: () => void;
18
+ addNode: (type: string) => string | null;
19
+ /** Adds a block right of `sourceNodeId` and wires `sourcePort` to it in one undo step. */
20
+ addNodeFromPort: (type: string, sourceNodeId: string, sourcePort: TFlowPortId) => string | null;
21
+ /**
22
+ * Puts a block in the middle of an edge: the edge now ends at the new block, whose first output
23
+ * leads to the old target. The old target and everything after it move one column right, so the
24
+ * new block takes the place it left. One undo step.
25
+ */
26
+ insertNodeOnEdge: (type: string, edgeId: string) => string | null;
27
+ updateNodeConfig: (nodeId: string, config: unknown) => void;
28
+ updateNodeLabel: (nodeId: string, label: string) => void;
29
+ moveNodes: (positions: Record<string, IFlowPosition>) => void;
30
+ connect: (source: string, sourcePort: TFlowPortId, target: string) => boolean;
31
+ removeSelected: () => void;
32
+ duplicateSelected: () => void;
33
+ copySelected: () => void;
34
+ paste: () => void;
35
+ setSelection: (selection: {
36
+ nodeIds?: Array<string>;
37
+ edgeIds?: Array<string>;
38
+ }) => void;
39
+ undo: () => void;
40
+ redo: () => void;
41
+ /** The host may rebuild its registry (labels after a language switch); gestures always read the latest. */
42
+ setRegistry: (registry: IFlowBlockRegistry) => void;
43
+ }
44
+ export type TFlowEditorStore = StoreApi<IFlowEditorState>;
45
+ /**
46
+ * One store per editor instance (two canvases on a page never share state). The graph
47
+ * is the source of truth; the canvas only renders it and reports gestures back.
48
+ */
49
+ export declare const createFlowEditorStore: (initialGraph: IFlowGraph, registry: IFlowBlockRegistry) => TFlowEditorStore;
@@ -0,0 +1,302 @@
1
+ import { createStore } from "zustand/vanilla";
2
+ import { generateUUID } from "../../../helpers/utilityHelpers.js";
3
+ import { flowOutputsOf } from "./flowBlockRegistry.js";
4
+ import { isFlowNodeRemovable, canConnect, reachableFrom, FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, layoutFlowByLevels } from "./flowGraph.js";
5
+ const HISTORY_LIMIT = 50;
6
+ const PASTE_OFFSET = 32;
7
+ const COALESCE_WINDOW_MS = 1e3;
8
+ const isPosition = (position) => typeof position?.x === "number" && typeof position?.y === "number";
9
+ const normalizeGraph = (graph, registry) => {
10
+ const normalized = {
11
+ nodes: Array.isArray(graph?.nodes) ? graph.nodes : [],
12
+ edges: Array.isArray(graph?.edges) ? graph.edges : []
13
+ };
14
+ if (normalized.nodes.every((node) => isPosition(node.position))) return normalized;
15
+ const layout = layoutFlowByLevels(normalized, registry);
16
+ return {
17
+ ...normalized,
18
+ nodes: normalized.nodes.map(
19
+ (node) => isPosition(node.position) ? node : { ...node, position: layout[node.nodeId] ?? { x: 0, y: 0 } }
20
+ )
21
+ };
22
+ };
23
+ const withoutNodes = (graph, nodeIds) => ({
24
+ nodes: graph.nodes.filter((node) => !nodeIds.has(node.nodeId)),
25
+ edges: graph.edges.filter((edge) => !nodeIds.has(edge.source) && !nodeIds.has(edge.target))
26
+ });
27
+ const isPositionTaken = (graph, position) => graph.nodes.some(
28
+ (node) => Math.abs(node.position.x - position.x) < FLOW_LEVEL_GAP && Math.abs(node.position.y - position.y) < FLOW_SIBLING_GAP
29
+ );
30
+ const nextFreePosition = (graph, selectedNodeIds) => {
31
+ if (graph.nodes.length === 0) return { x: 0, y: 0 };
32
+ const anchor = graph.nodes.find((node) => node.nodeId === selectedNodeIds[0]) ?? graph.nodes.reduce((current, node) => node.position.x > current.position.x ? node : current);
33
+ let candidate = { x: anchor.position.x + FLOW_LEVEL_GAP, y: anchor.position.y };
34
+ while (isPositionTaken(graph, candidate)) candidate = { x: candidate.x, y: candidate.y + FLOW_SIBLING_GAP };
35
+ return candidate;
36
+ };
37
+ const createFlowEditorStore = (initialGraph, registry) => createStore()((set, get) => {
38
+ let currentRegistry = registry;
39
+ let lastCoalesce = null;
40
+ const commit = (next, selection, coalesceKey) => {
41
+ const { graph, past } = get();
42
+ const now = Date.now();
43
+ const extendsLastStep = coalesceKey !== void 0 && lastCoalesce?.key === coalesceKey && now - lastCoalesce.at < COALESCE_WINDOW_MS;
44
+ lastCoalesce = coalesceKey === void 0 ? null : { key: coalesceKey, at: now };
45
+ set({
46
+ graph: next,
47
+ past: extendsLastStep ? past : [...past, graph].slice(-HISTORY_LIMIT),
48
+ future: [],
49
+ isDirty: true,
50
+ ...selection?.nodeIds ? { selectedNodeIds: selection.nodeIds } : {},
51
+ ...selection?.edgeIds ? { selectedEdgeIds: selection.edgeIds } : {}
52
+ });
53
+ };
54
+ const cloneNodes = (nodes, offset) => {
55
+ const instancesByType = /* @__PURE__ */ new Map();
56
+ get().graph.nodes.forEach((node) => instancesByType.set(node.type, (instancesByType.get(node.type) ?? 0) + 1));
57
+ return nodes.filter((node) => {
58
+ const definition = currentRegistry.get(node.type);
59
+ if (!definition || definition.category === "trigger") return false;
60
+ const instances = instancesByType.get(node.type) ?? 0;
61
+ if (definition.maxInstances !== void 0 && instances >= definition.maxInstances) return false;
62
+ instancesByType.set(node.type, instances + 1);
63
+ return true;
64
+ }).map((node) => ({
65
+ ...node,
66
+ nodeId: generateUUID(),
67
+ config: structuredClone(node.config),
68
+ position: { x: node.position.x + offset, y: node.position.y + offset }
69
+ }));
70
+ };
71
+ return {
72
+ graph: normalizeGraph(initialGraph, registry),
73
+ selectedNodeIds: [],
74
+ selectedEdgeIds: [],
75
+ past: [],
76
+ future: [],
77
+ clipboard: [],
78
+ isDirty: false,
79
+ replaceGraph: (graph, options) => {
80
+ set((state) => ({
81
+ graph: normalizeGraph(graph, currentRegistry),
82
+ past: options?.keepHistory ? [...state.past, state.graph].slice(-HISTORY_LIMIT) : [],
83
+ future: [],
84
+ selectedNodeIds: [],
85
+ selectedEdgeIds: [],
86
+ isDirty: Boolean(options?.keepHistory)
87
+ }));
88
+ },
89
+ markClean: () => set({ isDirty: false }),
90
+ recordHistory: () => {
91
+ const { graph, past } = get();
92
+ set({ past: [...past, graph].slice(-HISTORY_LIMIT), future: [] });
93
+ },
94
+ addNode: (type) => {
95
+ const definition = currentRegistry.get(type);
96
+ if (!definition) return null;
97
+ const { graph, selectedNodeIds } = get();
98
+ const instances = graph.nodes.filter((node2) => node2.type === type).length;
99
+ if (definition.maxInstances !== void 0 && instances >= definition.maxInstances) return null;
100
+ const node = {
101
+ nodeId: generateUUID(),
102
+ type,
103
+ typeVersion: definition.typeVersion,
104
+ config: definition.createDefaultConfig(),
105
+ position: nextFreePosition(graph, selectedNodeIds)
106
+ };
107
+ commit({ ...graph, nodes: [...graph.nodes, node] }, { nodeIds: [node.nodeId], edgeIds: [] });
108
+ return node.nodeId;
109
+ },
110
+ addNodeFromPort: (type, sourceNodeId, sourcePort) => {
111
+ const definition = currentRegistry.get(type);
112
+ const { graph } = get();
113
+ const source = graph.nodes.find((node2) => node2.nodeId === sourceNodeId);
114
+ if (!definition || !source) return null;
115
+ const instances = graph.nodes.filter((node2) => node2.type === type).length;
116
+ if (definition.maxInstances !== void 0 && instances >= definition.maxInstances) return null;
117
+ if (graph.edges.some((edge) => edge.source === sourceNodeId && edge.sourcePort === sourcePort)) return null;
118
+ const outputs = flowOutputsOf(currentRegistry.get(source.type), source.config);
119
+ if (!outputs.includes(sourcePort)) return null;
120
+ const portIndex = outputs.indexOf(sourcePort);
121
+ let position = {
122
+ x: source.position.x + FLOW_LEVEL_GAP,
123
+ y: source.position.y + (portIndex - (outputs.length - 1) / 2) * FLOW_SIBLING_GAP
124
+ };
125
+ while (isPositionTaken(graph, position)) position = { x: position.x, y: position.y + FLOW_SIBLING_GAP };
126
+ const node = {
127
+ nodeId: generateUUID(),
128
+ type,
129
+ typeVersion: definition.typeVersion,
130
+ config: definition.createDefaultConfig(),
131
+ position
132
+ };
133
+ const nodes = [...graph.nodes, node];
134
+ const wires = canConnect({ ...graph, nodes }, currentRegistry, {
135
+ source: sourceNodeId,
136
+ sourcePort,
137
+ target: node.nodeId
138
+ });
139
+ const edges = wires ? [...graph.edges, { edgeId: generateUUID(), source: sourceNodeId, sourcePort, target: node.nodeId }] : graph.edges;
140
+ commit({ nodes, edges }, { nodeIds: [node.nodeId], edgeIds: [] });
141
+ return node.nodeId;
142
+ },
143
+ insertNodeOnEdge: (type, edgeId) => {
144
+ const definition = currentRegistry.get(type);
145
+ const { graph } = get();
146
+ const edge = graph.edges.find((candidate) => candidate.edgeId === edgeId);
147
+ const target = edge ? graph.nodes.find((node2) => node2.nodeId === edge.target) : void 0;
148
+ const config = definition?.createDefaultConfig();
149
+ const continuationPort = definition ? flowOutputsOf(definition, config)[0] : void 0;
150
+ if (!definition || !edge || !target || !continuationPort || definition.category === "trigger") return null;
151
+ const instances = graph.nodes.filter((node2) => node2.type === type).length;
152
+ if (definition.maxInstances !== void 0 && instances >= definition.maxInstances) return null;
153
+ const shifted = reachableFrom(graph, target.nodeId);
154
+ const node = {
155
+ nodeId: generateUUID(),
156
+ type,
157
+ typeVersion: definition.typeVersion,
158
+ config,
159
+ position: { ...target.position }
160
+ };
161
+ const nodes = [
162
+ ...graph.nodes.map(
163
+ (current) => shifted.has(current.nodeId) ? { ...current, position: { x: current.position.x + FLOW_LEVEL_GAP, y: current.position.y } } : current
164
+ ),
165
+ node
166
+ ];
167
+ const withoutEdge = graph.edges.filter((current) => current.edgeId !== edgeId);
168
+ const incoming = { ...edge, target: node.nodeId };
169
+ const outgoing = {
170
+ edgeId: generateUUID(),
171
+ source: node.nodeId,
172
+ sourcePort: continuationPort,
173
+ target: target.nodeId
174
+ };
175
+ const wiresIn = canConnect({ nodes, edges: withoutEdge }, currentRegistry, incoming);
176
+ const wiresOut = canConnect({ nodes, edges: [...withoutEdge, incoming] }, currentRegistry, outgoing);
177
+ if (!wiresIn || !wiresOut) return null;
178
+ commit({ nodes, edges: [...withoutEdge, incoming, outgoing] }, { nodeIds: [node.nodeId], edgeIds: [] });
179
+ return node.nodeId;
180
+ },
181
+ updateNodeConfig: (nodeId, config) => {
182
+ const { graph } = get();
183
+ const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);
184
+ const outputs = node ? flowOutputsOf(currentRegistry.get(node.type), config) : [];
185
+ commit(
186
+ {
187
+ nodes: graph.nodes.map((current) => current.nodeId === nodeId ? { ...current, config } : current),
188
+ edges: graph.edges.filter((edge) => edge.source !== nodeId || outputs.includes(edge.sourcePort))
189
+ },
190
+ void 0,
191
+ `config:${nodeId}`
192
+ );
193
+ },
194
+ updateNodeLabel: (nodeId, label) => {
195
+ const { graph } = get();
196
+ const hasText = label.trim().length > 0;
197
+ commit(
198
+ {
199
+ ...graph,
200
+ nodes: graph.nodes.map(
201
+ (node) => node.nodeId === nodeId ? { ...node, label: hasText ? label : void 0 } : node
202
+ )
203
+ },
204
+ void 0,
205
+ `label:${nodeId}`
206
+ );
207
+ },
208
+ moveNodes: (positions) => {
209
+ const { graph } = get();
210
+ set({
211
+ graph: {
212
+ ...graph,
213
+ nodes: graph.nodes.map(
214
+ (node) => positions[node.nodeId] ? { ...node, position: positions[node.nodeId] } : node
215
+ )
216
+ },
217
+ isDirty: true
218
+ });
219
+ },
220
+ connect: (source, sourcePort, target) => {
221
+ const { graph } = get();
222
+ if (!canConnect(graph, currentRegistry, { source, sourcePort, target })) return false;
223
+ const edge = { edgeId: generateUUID(), source, sourcePort, target };
224
+ commit({ ...graph, edges: [...graph.edges, edge] });
225
+ return true;
226
+ },
227
+ removeSelected: () => {
228
+ const { graph, selectedNodeIds, selectedEdgeIds } = get();
229
+ const removableNodeIds = graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId) && isFlowNodeRemovable(node, currentRegistry)).map((node) => node.nodeId);
230
+ if (removableNodeIds.length === 0 && selectedEdgeIds.length === 0) return;
231
+ const removedEdges = new Set(selectedEdgeIds);
232
+ const next = withoutNodes(
233
+ { ...graph, edges: graph.edges.filter((edge) => !removedEdges.has(edge.edgeId)) },
234
+ new Set(removableNodeIds)
235
+ );
236
+ commit(next, { nodeIds: [], edgeIds: [] });
237
+ },
238
+ duplicateSelected: () => {
239
+ const { graph, selectedNodeIds } = get();
240
+ const selected = graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId));
241
+ const copies = cloneNodes(selected, PASTE_OFFSET);
242
+ if (copies.length === 0) return;
243
+ commit(
244
+ { ...graph, nodes: [...graph.nodes, ...copies] },
245
+ { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] }
246
+ );
247
+ },
248
+ copySelected: () => {
249
+ const { graph, selectedNodeIds } = get();
250
+ set({ clipboard: graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId)) });
251
+ },
252
+ paste: () => {
253
+ const { graph, clipboard } = get();
254
+ const copies = cloneNodes(clipboard, PASTE_OFFSET);
255
+ if (copies.length === 0) return;
256
+ commit(
257
+ { ...graph, nodes: [...graph.nodes, ...copies] },
258
+ { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] }
259
+ );
260
+ set({ clipboard: copies });
261
+ },
262
+ setSelection: ({ nodeIds, edgeIds }) => {
263
+ set((state) => ({
264
+ selectedNodeIds: nodeIds ?? state.selectedNodeIds,
265
+ selectedEdgeIds: edgeIds ?? state.selectedEdgeIds
266
+ }));
267
+ },
268
+ undo: () => {
269
+ const { graph, past, future } = get();
270
+ const previous = past[past.length - 1];
271
+ if (!previous) return;
272
+ set({
273
+ graph: previous,
274
+ past: past.slice(0, -1),
275
+ future: [graph, ...future].slice(0, HISTORY_LIMIT),
276
+ selectedNodeIds: [],
277
+ selectedEdgeIds: [],
278
+ isDirty: true
279
+ });
280
+ },
281
+ redo: () => {
282
+ const { graph, past, future } = get();
283
+ const following = future[0];
284
+ if (!following) return;
285
+ set({
286
+ graph: following,
287
+ past: [...past, graph].slice(-HISTORY_LIMIT),
288
+ future: future.slice(1),
289
+ selectedNodeIds: [],
290
+ selectedEdgeIds: [],
291
+ isDirty: true
292
+ });
293
+ },
294
+ setRegistry: (nextRegistry) => {
295
+ currentRegistry = nextRegistry;
296
+ }
297
+ };
298
+ });
299
+ export {
300
+ createFlowEditorStore
301
+ };
302
+ //# sourceMappingURL=flowEditorStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flowEditorStore.js","sources":["../../../../src/components/UI/Flow/flowEditorStore.ts"],"sourcesContent":["import { createStore, type StoreApi } from 'zustand/vanilla';\n\nimport { generateUUID } from '@/helpers/utilityHelpers';\n\nimport { flowOutputsOf, type IFlowBlockRegistry } from './flowBlockRegistry';\nimport {\n canConnect,\n FLOW_LEVEL_GAP,\n FLOW_SIBLING_GAP,\n isFlowNodeRemovable,\n layoutFlowByLevels,\n reachableFrom,\n} from './flowGraph';\nimport type { IFlowEdge, IFlowGraph, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';\n\nconst HISTORY_LIMIT = 50;\nconst PASTE_OFFSET = 32;\n/** Edits to the same field within this window share one undo step (typing a name is one change). */\nconst COALESCE_WINDOW_MS = 1000;\n\nexport interface IFlowEditorState {\n graph: IFlowGraph;\n selectedNodeIds: Array<string>;\n selectedEdgeIds: Array<string>;\n past: Array<IFlowGraph>;\n future: Array<IFlowGraph>;\n clipboard: Array<IFlowNode>;\n isDirty: boolean;\n\n replaceGraph: (graph: IFlowGraph, options?: { keepHistory?: boolean }) => void;\n markClean: () => void;\n /** Snapshot before a gesture that changes the graph in many small steps (a drag). */\n recordHistory: () => void;\n addNode: (type: string) => string | null;\n /** Adds a block right of `sourceNodeId` and wires `sourcePort` to it in one undo step. */\n addNodeFromPort: (type: string, sourceNodeId: string, sourcePort: TFlowPortId) => string | null;\n /**\n * Puts a block in the middle of an edge: the edge now ends at the new block, whose first output\n * leads to the old target. The old target and everything after it move one column right, so the\n * new block takes the place it left. One undo step.\n */\n insertNodeOnEdge: (type: string, edgeId: string) => string | null;\n updateNodeConfig: (nodeId: string, config: unknown) => void;\n updateNodeLabel: (nodeId: string, label: string) => void;\n moveNodes: (positions: Record<string, IFlowPosition>) => void;\n connect: (source: string, sourcePort: TFlowPortId, target: string) => boolean;\n removeSelected: () => void;\n duplicateSelected: () => void;\n copySelected: () => void;\n paste: () => void;\n setSelection: (selection: { nodeIds?: Array<string>; edgeIds?: Array<string> }) => void;\n undo: () => void;\n redo: () => void;\n /** The host may rebuild its registry (labels after a language switch); gestures always read the latest. */\n setRegistry: (registry: IFlowBlockRegistry) => void;\n}\n\nexport type TFlowEditorStore = StoreApi<IFlowEditorState>;\n\nconst isPosition = (position: unknown): position is IFlowPosition =>\n typeof (position as IFlowPosition | undefined)?.x === 'number' &&\n typeof (position as IFlowPosition | undefined)?.y === 'number';\n\n/** Coerces a stored graph; a block saved without a position is placed by the automatic layout. */\nconst normalizeGraph = (graph: IFlowGraph | null | undefined, registry: IFlowBlockRegistry): IFlowGraph => {\n const normalized: IFlowGraph = {\n nodes: Array.isArray(graph?.nodes) ? graph.nodes : [],\n edges: Array.isArray(graph?.edges) ? graph.edges : [],\n };\n if (normalized.nodes.every((node) => isPosition(node.position))) return normalized;\n\n const layout = layoutFlowByLevels(normalized, registry);\n return {\n ...normalized,\n nodes: normalized.nodes.map((node) =>\n isPosition(node.position) ? node : { ...node, position: layout[node.nodeId] ?? { x: 0, y: 0 } },\n ),\n };\n};\n\nconst withoutNodes = (graph: IFlowGraph, nodeIds: Set<string>): IFlowGraph => ({\n nodes: graph.nodes.filter((node) => !nodeIds.has(node.nodeId)),\n edges: graph.edges.filter((edge) => !nodeIds.has(edge.source) && !nodeIds.has(edge.target)),\n});\n\nconst isPositionTaken = (graph: IFlowGraph, position: IFlowPosition): boolean =>\n graph.nodes.some(\n (node) =>\n Math.abs(node.position.x - position.x) < FLOW_LEVEL_GAP &&\n Math.abs(node.position.y - position.y) < FLOW_SIBLING_GAP,\n );\n\n/** Right of the selected block (or the rightmost one), stepping down the column until the slot is free. */\nconst nextFreePosition = (graph: IFlowGraph, selectedNodeIds: Array<string>): IFlowPosition => {\n if (graph.nodes.length === 0) return { x: 0, y: 0 };\n const anchor =\n graph.nodes.find((node) => node.nodeId === selectedNodeIds[0]) ??\n graph.nodes.reduce((current, node) => (node.position.x > current.position.x ? node : current));\n let candidate = { x: anchor.position.x + FLOW_LEVEL_GAP, y: anchor.position.y };\n while (isPositionTaken(graph, candidate)) candidate = { x: candidate.x, y: candidate.y + FLOW_SIBLING_GAP };\n return candidate;\n};\n\n/**\n * One store per editor instance (two canvases on a page never share state). The graph\n * is the source of truth; the canvas only renders it and reports gestures back.\n */\nexport const createFlowEditorStore = (initialGraph: IFlowGraph, registry: IFlowBlockRegistry): TFlowEditorStore =>\n createStore<IFlowEditorState>()((set, get) => {\n let currentRegistry = registry;\n let lastCoalesce: { key: string; at: number } | null = null;\n\n const commit = (\n next: IFlowGraph,\n selection?: { nodeIds?: Array<string>; edgeIds?: Array<string> },\n coalesceKey?: string,\n ) => {\n const { graph, past } = get();\n const now = Date.now();\n const extendsLastStep =\n coalesceKey !== undefined && lastCoalesce?.key === coalesceKey && now - lastCoalesce.at < COALESCE_WINDOW_MS;\n lastCoalesce = coalesceKey === undefined ? null : { key: coalesceKey, at: now };\n set({\n graph: next,\n past: extendsLastStep ? past : [...past, graph].slice(-HISTORY_LIMIT),\n future: [],\n isDirty: true,\n ...(selection?.nodeIds ? { selectedNodeIds: selection.nodeIds } : {}),\n ...(selection?.edgeIds ? { selectedEdgeIds: selection.edgeIds } : {}),\n });\n };\n\n const cloneNodes = (nodes: Array<IFlowNode>, offset: number): Array<IFlowNode> => {\n const instancesByType = new Map<string, number>();\n get().graph.nodes.forEach((node) => instancesByType.set(node.type, (instancesByType.get(node.type) ?? 0) + 1));\n return nodes\n .filter((node) => {\n const definition = currentRegistry.get(node.type);\n if (!definition || definition.category === 'trigger') return false;\n const instances = instancesByType.get(node.type) ?? 0;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return false;\n instancesByType.set(node.type, instances + 1);\n return true;\n })\n .map((node) => ({\n ...node,\n nodeId: generateUUID(),\n config: structuredClone(node.config),\n position: { x: node.position.x + offset, y: node.position.y + offset },\n }));\n };\n\n return {\n graph: normalizeGraph(initialGraph, registry),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n past: [],\n future: [],\n clipboard: [],\n isDirty: false,\n\n replaceGraph: (graph, options) => {\n set((state) => ({\n graph: normalizeGraph(graph, currentRegistry),\n past: options?.keepHistory ? [...state.past, state.graph].slice(-HISTORY_LIMIT) : [],\n future: [],\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: Boolean(options?.keepHistory),\n }));\n },\n\n markClean: () => set({ isDirty: false }),\n\n recordHistory: () => {\n const { graph, past } = get();\n set({ past: [...past, graph].slice(-HISTORY_LIMIT), future: [] });\n },\n\n addNode: (type) => {\n const definition = currentRegistry.get(type);\n if (!definition) return null;\n\n const { graph, selectedNodeIds } = get();\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config: definition.createDefaultConfig(),\n position: nextFreePosition(graph, selectedNodeIds),\n };\n commit({ ...graph, nodes: [...graph.nodes, node] }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n addNodeFromPort: (type, sourceNodeId, sourcePort) => {\n const definition = currentRegistry.get(type);\n const { graph } = get();\n const source = graph.nodes.find((node) => node.nodeId === sourceNodeId);\n if (!definition || !source) return null;\n\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n if (graph.edges.some((edge) => edge.source === sourceNodeId && edge.sourcePort === sourcePort)) return null;\n\n const outputs = flowOutputsOf(currentRegistry.get(source.type), source.config);\n if (!outputs.includes(sourcePort)) return null;\n const portIndex = outputs.indexOf(sourcePort);\n let position = {\n x: source.position.x + FLOW_LEVEL_GAP,\n y: source.position.y + (portIndex - (outputs.length - 1) / 2) * FLOW_SIBLING_GAP,\n };\n while (isPositionTaken(graph, position)) position = { x: position.x, y: position.y + FLOW_SIBLING_GAP };\n\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config: definition.createDefaultConfig(),\n position,\n };\n const nodes = [...graph.nodes, node];\n const wires = canConnect({ ...graph, nodes }, currentRegistry, {\n source: sourceNodeId,\n sourcePort,\n target: node.nodeId,\n });\n const edges = wires\n ? [...graph.edges, { edgeId: generateUUID(), source: sourceNodeId, sourcePort, target: node.nodeId }]\n : graph.edges;\n commit({ nodes, edges }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n insertNodeOnEdge: (type, edgeId) => {\n const definition = currentRegistry.get(type);\n const { graph } = get();\n const edge = graph.edges.find((candidate) => candidate.edgeId === edgeId);\n const target = edge ? graph.nodes.find((node) => node.nodeId === edge.target) : undefined;\n const config = definition?.createDefaultConfig();\n const continuationPort = definition ? flowOutputsOf(definition, config)[0] : undefined;\n if (!definition || !edge || !target || !continuationPort || definition.category === 'trigger') return null;\n\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n\n const shifted = reachableFrom(graph, target.nodeId);\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config,\n position: { ...target.position },\n };\n const nodes = [\n ...graph.nodes.map((current) =>\n shifted.has(current.nodeId)\n ? { ...current, position: { x: current.position.x + FLOW_LEVEL_GAP, y: current.position.y } }\n : current,\n ),\n node,\n ];\n const withoutEdge = graph.edges.filter((current) => current.edgeId !== edgeId);\n const incoming: IFlowEdge = { ...edge, target: node.nodeId };\n const outgoing: IFlowEdge = {\n edgeId: generateUUID(),\n source: node.nodeId,\n sourcePort: continuationPort,\n target: target.nodeId,\n };\n\n const wiresIn = canConnect({ nodes, edges: withoutEdge }, currentRegistry, incoming);\n const wiresOut = canConnect({ nodes, edges: [...withoutEdge, incoming] }, currentRegistry, outgoing);\n if (!wiresIn || !wiresOut) return null;\n\n commit({ nodes, edges: [...withoutEdge, incoming, outgoing] }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n updateNodeConfig: (nodeId, config) => {\n const { graph } = get();\n const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);\n const outputs = node ? flowOutputsOf(currentRegistry.get(node.type), config) : [];\n commit(\n {\n nodes: graph.nodes.map((current) => (current.nodeId === nodeId ? { ...current, config } : current)),\n edges: graph.edges.filter((edge) => edge.source !== nodeId || outputs.includes(edge.sourcePort)),\n },\n undefined,\n `config:${nodeId}`,\n );\n },\n\n updateNodeLabel: (nodeId, label) => {\n const { graph } = get();\n const hasText = label.trim().length > 0;\n commit(\n {\n ...graph,\n nodes: graph.nodes.map((node) =>\n node.nodeId === nodeId ? { ...node, label: hasText ? label : undefined } : node,\n ),\n },\n undefined,\n `label:${nodeId}`,\n );\n },\n\n moveNodes: (positions) => {\n const { graph } = get();\n set({\n graph: {\n ...graph,\n nodes: graph.nodes.map((node) =>\n positions[node.nodeId] ? { ...node, position: positions[node.nodeId] } : node,\n ),\n },\n isDirty: true,\n });\n },\n\n connect: (source, sourcePort, target) => {\n const { graph } = get();\n if (!canConnect(graph, currentRegistry, { source, sourcePort, target })) return false;\n const edge: IFlowEdge = { edgeId: generateUUID(), source, sourcePort, target };\n commit({ ...graph, edges: [...graph.edges, edge] });\n return true;\n },\n\n removeSelected: () => {\n const { graph, selectedNodeIds, selectedEdgeIds } = get();\n const removableNodeIds = graph.nodes\n .filter((node) => selectedNodeIds.includes(node.nodeId) && isFlowNodeRemovable(node, currentRegistry))\n .map((node) => node.nodeId);\n if (removableNodeIds.length === 0 && selectedEdgeIds.length === 0) return;\n const removedEdges = new Set(selectedEdgeIds);\n const next = withoutNodes(\n { ...graph, edges: graph.edges.filter((edge) => !removedEdges.has(edge.edgeId)) },\n new Set(removableNodeIds),\n );\n commit(next, { nodeIds: [], edgeIds: [] });\n },\n\n duplicateSelected: () => {\n const { graph, selectedNodeIds } = get();\n const selected = graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId));\n const copies = cloneNodes(selected, PASTE_OFFSET);\n if (copies.length === 0) return;\n commit(\n { ...graph, nodes: [...graph.nodes, ...copies] },\n { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] },\n );\n },\n\n copySelected: () => {\n const { graph, selectedNodeIds } = get();\n set({ clipboard: graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId)) });\n },\n\n paste: () => {\n const { graph, clipboard } = get();\n const copies = cloneNodes(clipboard, PASTE_OFFSET);\n if (copies.length === 0) return;\n commit(\n { ...graph, nodes: [...graph.nodes, ...copies] },\n { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] },\n );\n set({ clipboard: copies });\n },\n\n setSelection: ({ nodeIds, edgeIds }) => {\n set((state) => ({\n selectedNodeIds: nodeIds ?? state.selectedNodeIds,\n selectedEdgeIds: edgeIds ?? state.selectedEdgeIds,\n }));\n },\n\n undo: () => {\n const { graph, past, future } = get();\n const previous = past[past.length - 1];\n if (!previous) return;\n set({\n graph: previous,\n past: past.slice(0, -1),\n future: [graph, ...future].slice(0, HISTORY_LIMIT),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: true,\n });\n },\n\n redo: () => {\n const { graph, past, future } = get();\n const following = future[0];\n if (!following) return;\n set({\n graph: following,\n past: [...past, graph].slice(-HISTORY_LIMIT),\n future: future.slice(1),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: true,\n });\n },\n\n setRegistry: (nextRegistry) => {\n currentRegistry = nextRegistry;\n },\n };\n });\n"],"names":["node"],"mappings":";;;;AAeA,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAErB,MAAM,qBAAqB;AAyC3B,MAAM,aAAa,CAAC,aAClB,OAAQ,UAAwC,MAAM,YACtD,OAAQ,UAAwC,MAAM;AAGxD,MAAM,iBAAiB,CAAC,O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A,CACV;AAAA,IACH;AAAA,IAEA,aAAa,CAAC,iBAAiB;AAC7B,wBAAkB;AAAA,IACpB;AAAA,EAAA;AAEJ,CAAC;"}
@@ -0,0 +1,32 @@
1
+ import { IFlowBlockRegistry } from './flowBlockRegistry';
2
+ import { IFlowGraph, IFlowIssue, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';
3
+ /** The flow reads left to right: one level per column, siblings stacked in the column. */
4
+ export declare const FLOW_LEVEL_GAP = 336;
5
+ export declare const FLOW_SIBLING_GAP = 176;
6
+ export declare const triggerNodesOf: (graph: IFlowGraph, registry: IFlowBlockRegistry) => Array<IFlowNode>;
7
+ export declare const isFlowNodeRemovable: (node: IFlowNode, registry: IFlowBlockRegistry) => boolean;
8
+ /** Node ids reachable from `startNodeId` following edges, the start included. */
9
+ export declare const reachableFrom: (graph: IFlowGraph, startNodeId: string) => Set<string>;
10
+ /** The node ids of the first cycle found, in order, or null when the graph has none. */
11
+ export declare const findCycle: (graph: IFlowGraph) => Array<string> | null;
12
+ export interface IFlowConnectionCandidate {
13
+ source: string;
14
+ sourcePort: TFlowPortId;
15
+ target: string;
16
+ }
17
+ /**
18
+ * The V0 shape is a tree with no fan-out: one input per block, one edge per output
19
+ * port, no edge into a trigger and no cycle. Keeping this rule here lets the canvas
20
+ * refuse a bad connection while it is being drawn, not only when publishing.
21
+ */
22
+ export declare const canConnect: (graph: IFlowGraph, registry: IFlowBlockRegistry, candidate: IFlowConnectionCandidate) => boolean;
23
+ /** The structural rules of the V0 shape, plus each block's own `validate`. */
24
+ export declare const validateFlowGraph: (graph: IFlowGraph, registry: IFlowBlockRegistry) => Array<IFlowIssue>;
25
+ export declare const hasBlockingIssues: (issues: Array<IFlowIssue>) => boolean;
26
+ /**
27
+ * Lays the tree out by levels from the trigger: each level one column to the right,
28
+ * siblings stacked in the column. Used only for a flow with no saved positions (one born from a rule) or when
29
+ * the user asks for it; a position the user arranged is data and is never overwritten
30
+ * implicitly.
31
+ */
32
+ export declare const layoutFlowByLevels: (graph: IFlowGraph, registry: IFlowBlockRegistry) => Record<string, IFlowPosition>;
@@ -0,0 +1,157 @@
1
+ import { flowOutputsOf } from "./flowBlockRegistry.js";
2
+ const FLOW_LEVEL_GAP = 336;
3
+ const FLOW_SIBLING_GAP = 176;
4
+ const nodesOf = (graph) => Array.isArray(graph?.nodes) ? graph.nodes : [];
5
+ const edgesOf = (graph) => Array.isArray(graph?.edges) ? graph.edges : [];
6
+ const outgoingByNode = (graph) => {
7
+ const outgoing = /* @__PURE__ */ new Map();
8
+ for (const edge of edgesOf(graph)) {
9
+ outgoing.set(edge.source, [...outgoing.get(edge.source) ?? [], edge]);
10
+ }
11
+ return outgoing;
12
+ };
13
+ const triggerNodesOf = (graph, registry) => nodesOf(graph).filter((node) => registry.get(node.type)?.category === "trigger");
14
+ const isFlowNodeRemovable = (node, registry) => registry.get(node.type)?.removable !== false;
15
+ const reachableFrom = (graph, startNodeId) => {
16
+ const outgoing = outgoingByNode(graph);
17
+ const visited = /* @__PURE__ */ new Set();
18
+ const pending = [startNodeId];
19
+ while (pending.length > 0) {
20
+ const nodeId = pending.pop();
21
+ if (nodeId === void 0 || visited.has(nodeId)) continue;
22
+ visited.add(nodeId);
23
+ for (const edge of outgoing.get(nodeId) ?? []) pending.push(edge.target);
24
+ }
25
+ return visited;
26
+ };
27
+ const findCycle = (graph) => {
28
+ const outgoing = outgoingByNode(graph);
29
+ const state = /* @__PURE__ */ new Map();
30
+ const path = [];
31
+ const visit = (nodeId) => {
32
+ state.set(nodeId, "visiting");
33
+ path.push(nodeId);
34
+ for (const edge of outgoing.get(nodeId) ?? []) {
35
+ const targetState = state.get(edge.target);
36
+ if (targetState === "visiting") return path.slice(path.indexOf(edge.target));
37
+ if (targetState === void 0) {
38
+ const cycle = visit(edge.target);
39
+ if (cycle) return cycle;
40
+ }
41
+ }
42
+ path.pop();
43
+ state.set(nodeId, "done");
44
+ return null;
45
+ };
46
+ for (const node of nodesOf(graph)) {
47
+ if (state.has(node.nodeId)) continue;
48
+ const cycle = visit(node.nodeId);
49
+ if (cycle) return cycle;
50
+ }
51
+ return null;
52
+ };
53
+ const canConnect = (graph, registry, candidate) => {
54
+ const { source, sourcePort, target } = candidate;
55
+ if (!source || !target || source === target) return false;
56
+ const nodes = nodesOf(graph);
57
+ const sourceNode = nodes.find((node) => node.nodeId === source);
58
+ const targetNode = nodes.find((node) => node.nodeId === target);
59
+ if (!sourceNode || !targetNode) return false;
60
+ const sourceDefinition = registry.get(sourceNode.type);
61
+ const targetDefinition = registry.get(targetNode.type);
62
+ if (!flowOutputsOf(sourceDefinition, sourceNode.config).includes(sourcePort)) return false;
63
+ if (!targetDefinition || targetDefinition.category === "trigger") return false;
64
+ const edges = edgesOf(graph);
65
+ if (edges.some((edge) => edge.source === source && edge.sourcePort === sourcePort)) return false;
66
+ if (edges.some((edge) => edge.target === target)) return false;
67
+ return !reachableFrom(graph, target).has(source);
68
+ };
69
+ const validateFlowGraph = (graph, registry) => {
70
+ const issues = [];
71
+ const nodes = nodesOf(graph);
72
+ const edges = edgesOf(graph);
73
+ for (const node of nodes) {
74
+ const definition = registry.get(node.type);
75
+ if (!definition) {
76
+ issues.push({ code: "unknownBlock", severity: "error", nodeId: node.nodeId });
77
+ continue;
78
+ }
79
+ for (const blockIssue of definition.validate(node.config) ?? []) {
80
+ issues.push({ ...blockIssue, nodeId: node.nodeId });
81
+ }
82
+ }
83
+ const triggers = triggerNodesOf(graph, registry);
84
+ if (triggers.length === 0) issues.push({ code: "missingTrigger", severity: "error" });
85
+ triggers.slice(1).forEach((trigger) => {
86
+ issues.push({ code: "multipleTriggers", severity: "error", nodeId: trigger.nodeId });
87
+ });
88
+ const firstTrigger = triggers[0];
89
+ if (firstTrigger) {
90
+ const reachable = reachableFrom(graph, firstTrigger.nodeId);
91
+ nodes.filter((node) => !reachable.has(node.nodeId) && registry.get(node.type)?.category !== "trigger").forEach((node) => issues.push({ code: "unreachableNode", severity: "error", nodeId: node.nodeId }));
92
+ }
93
+ const inputCount = /* @__PURE__ */ new Map();
94
+ const portCount = /* @__PURE__ */ new Map();
95
+ for (const edge of edges) {
96
+ inputCount.set(edge.target, (inputCount.get(edge.target) ?? 0) + 1);
97
+ const portKey = `${edge.source}|${edge.sourcePort}`;
98
+ portCount.set(portKey, (portCount.get(portKey) ?? 0) + 1);
99
+ }
100
+ inputCount.forEach((count, nodeId) => {
101
+ if (count > 1) issues.push({ code: "multipleInputs", severity: "error", nodeId });
102
+ });
103
+ edges.filter((edge) => (portCount.get(`${edge.source}|${edge.sourcePort}`) ?? 0) > 1).forEach(
104
+ (edge) => issues.push({ code: "portFanOut", severity: "error", edgeId: edge.edgeId, nodeId: edge.source })
105
+ );
106
+ const cycle = findCycle(graph);
107
+ if (cycle) cycle.forEach((nodeId) => issues.push({ code: "cycle", severity: "error", nodeId }));
108
+ nodes.filter((node) => flowOutputsOf(registry.get(node.type), node.config).includes("true")).filter((node) => !edges.some((edge) => edge.source === node.nodeId && edge.sourcePort === "true")).forEach((node) => issues.push({ code: "missingTrueBranch", severity: "warning", nodeId: node.nodeId }));
109
+ return issues;
110
+ };
111
+ const hasBlockingIssues = (issues) => (issues ?? []).some((issue) => issue.severity === "error");
112
+ const layoutFlowByLevels = (graph, registry) => {
113
+ const nodes = nodesOf(graph);
114
+ const outgoing = outgoingByNode(graph);
115
+ const levelOf = /* @__PURE__ */ new Map();
116
+ const roots = triggerNodesOf(graph, registry);
117
+ const queue = roots.map((root) => root.nodeId);
118
+ roots.forEach((root) => levelOf.set(root.nodeId, 0));
119
+ while (queue.length > 0) {
120
+ const nodeId = queue.shift();
121
+ if (nodeId === void 0) continue;
122
+ const level = levelOf.get(nodeId) ?? 0;
123
+ for (const edge of outgoing.get(nodeId) ?? []) {
124
+ if (levelOf.has(edge.target)) continue;
125
+ levelOf.set(edge.target, level + 1);
126
+ queue.push(edge.target);
127
+ }
128
+ }
129
+ const deepestLevel = Math.max(-1, ...Array.from(levelOf.values()));
130
+ nodes.filter((node) => !levelOf.has(node.nodeId)).forEach((node) => levelOf.set(node.nodeId, deepestLevel + 1));
131
+ const nodesByLevel = /* @__PURE__ */ new Map();
132
+ nodes.forEach((node) => {
133
+ const level = levelOf.get(node.nodeId) ?? 0;
134
+ nodesByLevel.set(level, [...nodesByLevel.get(level) ?? [], node.nodeId]);
135
+ });
136
+ const positions = {};
137
+ nodesByLevel.forEach((nodeIds, level) => {
138
+ const columnHeight = (nodeIds.length - 1) * FLOW_SIBLING_GAP;
139
+ nodeIds.forEach((nodeId, index) => {
140
+ positions[nodeId] = { x: level * FLOW_LEVEL_GAP, y: index * FLOW_SIBLING_GAP - columnHeight / 2 };
141
+ });
142
+ });
143
+ return positions;
144
+ };
145
+ export {
146
+ FLOW_LEVEL_GAP,
147
+ FLOW_SIBLING_GAP,
148
+ canConnect,
149
+ findCycle,
150
+ hasBlockingIssues,
151
+ isFlowNodeRemovable,
152
+ layoutFlowByLevels,
153
+ reachableFrom,
154
+ triggerNodesOf,
155
+ validateFlowGraph
156
+ };
157
+ //# sourceMappingURL=flowGraph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flowGraph.js","sources":["../../../../src/components/UI/Flow/flowGraph.ts"],"sourcesContent":["import { flowOutputsOf, type IFlowBlockRegistry } from './flowBlockRegistry';\nimport type { IFlowEdge, IFlowGraph, IFlowIssue, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';\n\n/** The flow reads left to right: one level per column, siblings stacked in the column. */\nexport const FLOW_LEVEL_GAP = 336;\nexport const FLOW_SIBLING_GAP = 176;\n\nconst nodesOf = (graph: IFlowGraph): Array<IFlowNode> => (Array.isArray(graph?.nodes) ? graph.nodes : []);\nconst edgesOf = (graph: IFlowGraph): Array<IFlowEdge> => (Array.isArray(graph?.edges) ? graph.edges : []);\n\nconst outgoingByNode = (graph: IFlowGraph): Map<string, Array<IFlowEdge>> => {\n const outgoing = new Map<string, Array<IFlowEdge>>();\n for (const edge of edgesOf(graph)) {\n outgoing.set(edge.source, [...(outgoing.get(edge.source) ?? []), edge]);\n }\n return outgoing;\n};\n\nexport const triggerNodesOf = (graph: IFlowGraph, registry: IFlowBlockRegistry): Array<IFlowNode> =>\n nodesOf(graph).filter((node) => registry.get(node.type)?.category === 'trigger');\n\nexport const isFlowNodeRemovable = (node: IFlowNode, registry: IFlowBlockRegistry): boolean =>\n registry.get(node.type)?.removable !== false;\n\n/** Node ids reachable from `startNodeId` following edges, the start included. */\nexport const reachableFrom = (graph: IFlowGraph, startNodeId: string): Set<string> => {\n const outgoing = outgoingByNode(graph);\n const visited = new Set<string>();\n const pending = [startNodeId];\n while (pending.length > 0) {\n const nodeId = pending.pop();\n if (nodeId === undefined || visited.has(nodeId)) continue;\n visited.add(nodeId);\n for (const edge of outgoing.get(nodeId) ?? []) pending.push(edge.target);\n }\n return visited;\n};\n\n/** The node ids of the first cycle found, in order, or null when the graph has none. */\nexport const findCycle = (graph: IFlowGraph): Array<string> | null => {\n const outgoing = outgoingByNode(graph);\n const state = new Map<string, 'visiting' | 'done'>();\n const path: Array<string> = [];\n\n const visit = (nodeId: string): Array<string> | null => {\n state.set(nodeId, 'visiting');\n path.push(nodeId);\n for (const edge of outgoing.get(nodeId) ?? []) {\n const targetState = state.get(edge.target);\n if (targetState === 'visiting') return path.slice(path.indexOf(edge.target));\n if (targetState === undefined) {\n const cycle = visit(edge.target);\n if (cycle) return cycle;\n }\n }\n path.pop();\n state.set(nodeId, 'done');\n return null;\n };\n\n for (const node of nodesOf(graph)) {\n if (state.has(node.nodeId)) continue;\n const cycle = visit(node.nodeId);\n if (cycle) return cycle;\n }\n return null;\n};\n\nexport interface IFlowConnectionCandidate {\n source: string;\n sourcePort: TFlowPortId;\n target: string;\n}\n\n/**\n * The V0 shape is a tree with no fan-out: one input per block, one edge per output\n * port, no edge into a trigger and no cycle. Keeping this rule here lets the canvas\n * refuse a bad connection while it is being drawn, not only when publishing.\n */\nexport const canConnect = (\n graph: IFlowGraph,\n registry: IFlowBlockRegistry,\n candidate: IFlowConnectionCandidate,\n): boolean => {\n const { source, sourcePort, target } = candidate;\n if (!source || !target || source === target) return false;\n\n const nodes = nodesOf(graph);\n const sourceNode = nodes.find((node) => node.nodeId === source);\n const targetNode = nodes.find((node) => node.nodeId === target);\n if (!sourceNode || !targetNode) return false;\n\n const sourceDefinition = registry.get(sourceNode.type);\n const targetDefinition = registry.get(targetNode.type);\n if (!flowOutputsOf(sourceDefinition, sourceNode.config).includes(sourcePort)) return false;\n if (!targetDefinition || targetDefinition.category === 'trigger') return false;\n\n const edges = edgesOf(graph);\n if (edges.some((edge) => edge.source === source && edge.sourcePort === sourcePort)) return false;\n if (edges.some((edge) => edge.target === target)) return false;\n\n return !reachableFrom(graph, target).has(source);\n};\n\n/** The structural rules of the V0 shape, plus each block's own `validate`. */\nexport const validateFlowGraph = (graph: IFlowGraph, registry: IFlowBlockRegistry): Array<IFlowIssue> => {\n const issues: Array<IFlowIssue> = [];\n const nodes = nodesOf(graph);\n const edges = edgesOf(graph);\n\n for (const node of nodes) {\n const definition = registry.get(node.type);\n if (!definition) {\n issues.push({ code: 'unknownBlock', severity: 'error', nodeId: node.nodeId });\n continue;\n }\n for (const blockIssue of definition.validate(node.config) ?? []) {\n issues.push({ ...blockIssue, nodeId: node.nodeId });\n }\n }\n\n const triggers = triggerNodesOf(graph, registry);\n if (triggers.length === 0) issues.push({ code: 'missingTrigger', severity: 'error' });\n triggers.slice(1).forEach((trigger) => {\n issues.push({ code: 'multipleTriggers', severity: 'error', nodeId: trigger.nodeId });\n });\n\n const firstTrigger = triggers[0];\n if (firstTrigger) {\n const reachable = reachableFrom(graph, firstTrigger.nodeId);\n nodes\n .filter((node) => !reachable.has(node.nodeId) && registry.get(node.type)?.category !== 'trigger')\n .forEach((node) => issues.push({ code: 'unreachableNode', severity: 'error', nodeId: node.nodeId }));\n }\n\n const inputCount = new Map<string, number>();\n const portCount = new Map<string, number>();\n for (const edge of edges) {\n inputCount.set(edge.target, (inputCount.get(edge.target) ?? 0) + 1);\n const portKey = `${edge.source}|${edge.sourcePort}`;\n portCount.set(portKey, (portCount.get(portKey) ?? 0) + 1);\n }\n inputCount.forEach((count, nodeId) => {\n if (count > 1) issues.push({ code: 'multipleInputs', severity: 'error', nodeId });\n });\n edges\n .filter((edge) => (portCount.get(`${edge.source}|${edge.sourcePort}`) ?? 0) > 1)\n .forEach((edge) =>\n issues.push({ code: 'portFanOut', severity: 'error', edgeId: edge.edgeId, nodeId: edge.source }),\n );\n\n const cycle = findCycle(graph);\n if (cycle) cycle.forEach((nodeId) => issues.push({ code: 'cycle', severity: 'error', nodeId }));\n\n nodes\n .filter((node) => flowOutputsOf(registry.get(node.type), node.config).includes('true'))\n .filter((node) => !edges.some((edge) => edge.source === node.nodeId && edge.sourcePort === 'true'))\n .forEach((node) => issues.push({ code: 'missingTrueBranch', severity: 'warning', nodeId: node.nodeId }));\n\n return issues;\n};\n\nexport const hasBlockingIssues = (issues: Array<IFlowIssue>): boolean =>\n (issues ?? []).some((issue) => issue.severity === 'error');\n\n/**\n * Lays the tree out by levels from the trigger: each level one column to the right,\n * siblings stacked in the column. Used only for a flow with no saved positions (one born from a rule) or when\n * the user asks for it; a position the user arranged is data and is never overwritten\n * implicitly.\n */\nexport const layoutFlowByLevels = (graph: IFlowGraph, registry: IFlowBlockRegistry): Record<string, IFlowPosition> => {\n const nodes = nodesOf(graph);\n const outgoing = outgoingByNode(graph);\n const levelOf = new Map<string, number>();\n const roots = triggerNodesOf(graph, registry);\n const queue: Array<string> = roots.map((root) => root.nodeId);\n roots.forEach((root) => levelOf.set(root.nodeId, 0));\n\n while (queue.length > 0) {\n const nodeId = queue.shift();\n if (nodeId === undefined) continue;\n const level = levelOf.get(nodeId) ?? 0;\n for (const edge of outgoing.get(nodeId) ?? []) {\n if (levelOf.has(edge.target)) continue;\n levelOf.set(edge.target, level + 1);\n queue.push(edge.target);\n }\n }\n\n const deepestLevel = Math.max(-1, ...Array.from(levelOf.values()));\n nodes.filter((node) => !levelOf.has(node.nodeId)).forEach((node) => levelOf.set(node.nodeId, deepestLevel + 1));\n\n const nodesByLevel = new Map<number, Array<string>>();\n nodes.forEach((node) => {\n const level = levelOf.get(node.nodeId) ?? 0;\n nodesByLevel.set(level, [...(nodesByLevel.get(level) ?? []), node.nodeId]);\n });\n\n const positions: Record<string, IFlowPosition> = {};\n nodesByLevel.forEach((nodeIds, level) => {\n const columnHeight = (nodeIds.length - 1) * FLOW_SIBLING_GAP;\n nodeIds.forEach((nodeId, index) => {\n positions[nodeId] = { x: level * FLOW_LEVEL_GAP, y: index * FLOW_SIBLING_GAP - columnHeight / 2 };\n });\n });\n return positions;\n};\n"],"names":[],"mappings":";AAIO,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AAEhC,MAAM,UAAU,CAAC,UAAyC,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AACtG,MAAM,UAAU,CAAC,UAAyC,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AAEtG,MAAM,iBAAiB,CAAC,UAAqD;AAC3E,QAAM,+BAAe,IAAA;AACrB,aAAW,QAAQ,QAAQ,KAAK,GAAG;AACjC,aAAS,IAAI,KAAK,QAAQ,CAAC,GAAI,SAAS,IAAI,KAAK,MAAM,KAAK,CAAA,GAAK,IAAI,CAAC;AAAA,EACxE;AACA,SAAO;AACT;AAEO,MAAM,iBAAiB,CAAC,OAAmB,aAChD,QAAQ,KAAK,EAAE,OAAO,CAAC,SAAS,SAAS,IAAI,KAAK,IAAI,GAAG,aAAa,SAAS;AAE1E,MAAM,sBAAsB,CAAC,MAAiB,aACnD,SAAS,IAAI,KAAK,IAAI,GAAG,cAAc;AAGlC,MAAM,gBAAgB,CAAC,OAAmB,gBAAqC;AACpF,QAAM,WAAW,eAAe,KAAK;AACrC,QAAM,8BAAc,IAAA;AACpB,QAAM,UAAU,CAAC,WAAW;AAC5B,SAAO,QAAQ,SAAS,GAAG;AACzB,UAAM,SAAS,QAAQ,IAAA;AACvB,QAAI,W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