@octaviaflow/core 3.0.18-beta.3 → 3.0.18-beta.30

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 (178) hide show
  1. package/dist/chunk-2NGC7AI3.js +2637 -0
  2. package/dist/chunk-2NGC7AI3.js.map +1 -0
  3. package/dist/chunk-2O6K5PLY.js +2637 -0
  4. package/dist/chunk-2O6K5PLY.js.map +1 -0
  5. package/dist/chunk-2ZIOFEIS.js +3001 -0
  6. package/dist/chunk-2ZIOFEIS.js.map +1 -0
  7. package/dist/chunk-3DWB2PUF.js +2991 -0
  8. package/dist/chunk-3DWB2PUF.js.map +1 -0
  9. package/dist/chunk-4ZALUTZS.js +2936 -0
  10. package/dist/chunk-4ZALUTZS.js.map +1 -0
  11. package/dist/chunk-5ARKSRED.js +2951 -0
  12. package/dist/chunk-5ARKSRED.js.map +1 -0
  13. package/dist/chunk-5OSGSJMM.js +2981 -0
  14. package/dist/chunk-5OSGSJMM.js.map +1 -0
  15. package/dist/chunk-5YQQMEF3.js +2981 -0
  16. package/dist/chunk-5YQQMEF3.js.map +1 -0
  17. package/dist/chunk-6QCJK7H7.js +2991 -0
  18. package/dist/chunk-6QCJK7H7.js.map +1 -0
  19. package/dist/chunk-6QDYERZD.js +2944 -0
  20. package/dist/chunk-6QDYERZD.js.map +1 -0
  21. package/dist/chunk-76TP67ED.js +2984 -0
  22. package/dist/chunk-76TP67ED.js.map +1 -0
  23. package/dist/chunk-A6KMO4JV.js +2949 -0
  24. package/dist/chunk-A6KMO4JV.js.map +1 -0
  25. package/dist/chunk-B7FTWSTM.js +2938 -0
  26. package/dist/chunk-B7FTWSTM.js.map +1 -0
  27. package/dist/chunk-BCO6M26F.js +2940 -0
  28. package/dist/chunk-BCO6M26F.js.map +1 -0
  29. package/dist/chunk-C3UD2AZ5.js +2637 -0
  30. package/dist/chunk-C3UD2AZ5.js.map +1 -0
  31. package/dist/chunk-CEUP4NK2.js +2850 -0
  32. package/dist/chunk-CEUP4NK2.js.map +1 -0
  33. package/dist/chunk-DBNSBJO7.js +2993 -0
  34. package/dist/chunk-DBNSBJO7.js.map +1 -0
  35. package/dist/chunk-ECIHUVU7.js +2986 -0
  36. package/dist/chunk-ECIHUVU7.js.map +1 -0
  37. package/dist/chunk-EERNYLFL.js +2860 -0
  38. package/dist/chunk-EERNYLFL.js.map +1 -0
  39. package/dist/chunk-EKFDJX4G.js +2872 -0
  40. package/dist/chunk-EKFDJX4G.js.map +1 -0
  41. package/dist/chunk-GJA3GJUZ.js +2844 -0
  42. package/dist/chunk-GJA3GJUZ.js.map +1 -0
  43. package/dist/chunk-HDOTOZNA.js +2936 -0
  44. package/dist/chunk-HDOTOZNA.js.map +1 -0
  45. package/dist/chunk-IOKUV7FD.js +2658 -0
  46. package/dist/chunk-IOKUV7FD.js.map +1 -0
  47. package/dist/chunk-IUIICQU5.js +2946 -0
  48. package/dist/chunk-IUIICQU5.js.map +1 -0
  49. package/dist/chunk-J2UYZI6D.js +2946 -0
  50. package/dist/chunk-J2UYZI6D.js.map +1 -0
  51. package/dist/chunk-J7YASALS.js +2859 -0
  52. package/dist/chunk-J7YASALS.js.map +1 -0
  53. package/dist/chunk-JIEUYBQT.js +2658 -0
  54. package/dist/chunk-JIEUYBQT.js.map +1 -0
  55. package/dist/chunk-K2H7JLQW.js +2952 -0
  56. package/dist/chunk-K2H7JLQW.js.map +1 -0
  57. package/dist/chunk-KUXYBP66.js +2953 -0
  58. package/dist/chunk-KUXYBP66.js.map +1 -0
  59. package/dist/chunk-KYMYNYFV.js +2656 -0
  60. package/dist/chunk-KYMYNYFV.js.map +1 -0
  61. package/dist/chunk-MMXL343D.js +2974 -0
  62. package/dist/chunk-MMXL343D.js.map +1 -0
  63. package/dist/chunk-MXJL3EPE.js +2986 -0
  64. package/dist/chunk-MXJL3EPE.js.map +1 -0
  65. package/dist/chunk-MYZ25B2R.js +2995 -0
  66. package/dist/chunk-MYZ25B2R.js.map +1 -0
  67. package/dist/chunk-NTMEYB7B.js +2949 -0
  68. package/dist/chunk-NTMEYB7B.js.map +1 -0
  69. package/dist/chunk-PVJXX6GP.js +2640 -0
  70. package/dist/chunk-PVJXX6GP.js.map +1 -0
  71. package/dist/chunk-Q6ERDPQR.js +2981 -0
  72. package/dist/chunk-Q6ERDPQR.js.map +1 -0
  73. package/dist/chunk-S2SSBMWJ.js +2658 -0
  74. package/dist/chunk-S2SSBMWJ.js.map +1 -0
  75. package/dist/chunk-SLVDAZSX.js +2946 -0
  76. package/dist/chunk-SLVDAZSX.js.map +1 -0
  77. package/dist/chunk-UQBPYONV.js +2991 -0
  78. package/dist/chunk-UQBPYONV.js.map +1 -0
  79. package/dist/chunk-UXMNBS22.js +2955 -0
  80. package/dist/chunk-UXMNBS22.js.map +1 -0
  81. package/dist/chunk-WEGED7TA.js +2991 -0
  82. package/dist/chunk-WEGED7TA.js.map +1 -0
  83. package/dist/chunk-WEPTBLWX.js +2847 -0
  84. package/dist/chunk-WEPTBLWX.js.map +1 -0
  85. package/dist/chunk-WG4ZQMPS.js +2844 -0
  86. package/dist/chunk-WG4ZQMPS.js.map +1 -0
  87. package/dist/chunk-XEPEBHAW.js +2808 -0
  88. package/dist/chunk-XEPEBHAW.js.map +1 -0
  89. package/dist/chunk-XG2OYFX6.js +2925 -0
  90. package/dist/chunk-XG2OYFX6.js.map +1 -0
  91. package/dist/chunk-ZAMJEU42.js +2992 -0
  92. package/dist/chunk-ZAMJEU42.js.map +1 -0
  93. package/dist/chunk-ZRAM6FXB.js +2949 -0
  94. package/dist/chunk-ZRAM6FXB.js.map +1 -0
  95. package/dist/components/CsvViewer/CsvViewer.d.ts +51 -0
  96. package/dist/components/CsvViewer/CsvViewer.d.ts.map +1 -0
  97. package/dist/components/CsvViewer/index.d.ts +2 -0
  98. package/dist/components/CsvViewer/index.d.ts.map +1 -0
  99. package/dist/components/DataTable/DataTable.d.ts +19 -1
  100. package/dist/components/DataTable/DataTable.d.ts.map +1 -1
  101. package/dist/components/DropdownMenu/DropdownMenu.d.ts +12 -2
  102. package/dist/components/DropdownMenu/DropdownMenu.d.ts.map +1 -1
  103. package/dist/components/ExecutionConsole/ExecutionConsole.d.ts +8 -2
  104. package/dist/components/ExecutionConsole/ExecutionConsole.d.ts.map +1 -1
  105. package/dist/components/FlowMinimap/FlowMinimap.d.ts +17 -1
  106. package/dist/components/FlowMinimap/FlowMinimap.d.ts.map +1 -1
  107. package/dist/components/FlowToolbar/FlowToolbar.d.ts +16 -10
  108. package/dist/components/FlowToolbar/FlowToolbar.d.ts.map +1 -1
  109. package/dist/components/JsonViewer/JsonViewer.d.ts +42 -7
  110. package/dist/components/JsonViewer/JsonViewer.d.ts.map +1 -1
  111. package/dist/components/JsonViewer/index.d.ts +1 -1
  112. package/dist/components/JsonViewer/index.d.ts.map +1 -1
  113. package/dist/components/Select/Select.d.ts.map +1 -1
  114. package/dist/components/WorkflowHeader/WorkflowHeader.d.ts +130 -0
  115. package/dist/components/WorkflowHeader/WorkflowHeader.d.ts.map +1 -0
  116. package/dist/components/WorkflowHeader/WorkflowHeaderExpanded.d.ts +69 -0
  117. package/dist/components/WorkflowHeader/WorkflowHeaderExpanded.d.ts.map +1 -0
  118. package/dist/components/WorkflowHeader/index.d.ts +3 -0
  119. package/dist/components/WorkflowHeader/index.d.ts.map +1 -0
  120. package/dist/components/WorkflowHeader/misc/WorkflowHeaderCentered.d.ts +40 -0
  121. package/dist/components/WorkflowHeader/misc/WorkflowHeaderCentered.d.ts.map +1 -0
  122. package/dist/components/WorkflowHeader/misc/WorkflowHeaderCommand.d.ts +39 -0
  123. package/dist/components/WorkflowHeader/misc/WorkflowHeaderCommand.d.ts.map +1 -0
  124. package/dist/components/WorkflowHeader/misc/WorkflowHeaderMinimal.d.ts +44 -0
  125. package/dist/components/WorkflowHeader/misc/WorkflowHeaderMinimal.d.ts.map +1 -0
  126. package/dist/components/WorkflowHeader/misc/WorkflowHeaderRail.d.ts +45 -0
  127. package/dist/components/WorkflowHeader/misc/WorkflowHeaderRail.d.ts.map +1 -0
  128. package/dist/components/WorkflowHeader/misc/WorkflowHeaderStudio.d.ts +48 -0
  129. package/dist/components/WorkflowHeader/misc/WorkflowHeaderStudio.d.ts.map +1 -0
  130. package/dist/components/WorkflowHeader/misc/WorkflowHeaderTiered.d.ts +52 -0
  131. package/dist/components/WorkflowHeader/misc/WorkflowHeaderTiered.d.ts.map +1 -0
  132. package/dist/components/XmlViewer/XmlViewer.d.ts +26 -1
  133. package/dist/components/XmlViewer/XmlViewer.d.ts.map +1 -1
  134. package/dist/components/XmlViewer/index.d.ts +1 -1
  135. package/dist/components/XmlViewer/index.d.ts.map +1 -1
  136. package/dist/components/YamlViewer/YamlViewer.d.ts +26 -1
  137. package/dist/components/YamlViewer/YamlViewer.d.ts.map +1 -1
  138. package/dist/components/YamlViewer/index.d.ts +1 -1
  139. package/dist/components/YamlViewer/index.d.ts.map +1 -1
  140. package/dist/hooks/useRelativeTime.d.ts +28 -0
  141. package/dist/hooks/useRelativeTime.d.ts.map +1 -0
  142. package/dist/hooks/useWorkflowRuntime.d.ts +20 -0
  143. package/dist/hooks/useWorkflowRuntime.d.ts.map +1 -0
  144. package/dist/index.cjs +4884 -3581
  145. package/dist/index.cjs.map +1 -1
  146. package/dist/index.d.ts +7 -3
  147. package/dist/index.d.ts.map +1 -1
  148. package/dist/index.js +4505 -3515
  149. package/dist/index.js.map +1 -1
  150. package/dist/styles.css +1 -1
  151. package/dist/workflow/components/ConfigPanel/ConfigPanel.d.ts +27 -9
  152. package/dist/workflow/components/ConfigPanel/ConfigPanel.d.ts.map +1 -1
  153. package/dist/workflow/components/FlowCanvas/FlowCanvas.d.ts +49 -1
  154. package/dist/workflow/components/FlowCanvas/FlowCanvas.d.ts.map +1 -1
  155. package/dist/workflow/components/FlowEdge/FlowEdge.d.ts.map +1 -1
  156. package/dist/workflow/components/FxPanel/DataRefButton.d.ts +9 -0
  157. package/dist/workflow/components/FxPanel/DataRefButton.d.ts.map +1 -0
  158. package/dist/workflow/components/FxPanel/FxPanel.d.ts +74 -0
  159. package/dist/workflow/components/FxPanel/FxPanel.d.ts.map +1 -0
  160. package/dist/workflow/components/FxPanel/FxToggleButton.d.ts +9 -0
  161. package/dist/workflow/components/FxPanel/FxToggleButton.d.ts.map +1 -0
  162. package/dist/workflow/components/Handle/Handle.d.ts +9 -1
  163. package/dist/workflow/components/Handle/Handle.d.ts.map +1 -1
  164. package/dist/workflow/components/Handle/handleRegistry.d.ts +19 -0
  165. package/dist/workflow/components/Handle/handleRegistry.d.ts.map +1 -1
  166. package/dist/workflow/components/kinds/index.d.ts +4 -0
  167. package/dist/workflow/components/kinds/index.d.ts.map +1 -1
  168. package/dist/workflow/index.d.ts +3 -1
  169. package/dist/workflow/index.d.ts.map +1 -1
  170. package/dist/workflow/store/selectors.d.ts +12 -0
  171. package/dist/workflow/store/selectors.d.ts.map +1 -1
  172. package/dist/workflow/utils/parenting.d.ts +5 -3
  173. package/dist/workflow/utils/parenting.d.ts.map +1 -1
  174. package/dist/workflow.cjs +1108 -471
  175. package/dist/workflow.cjs.map +1 -1
  176. package/dist/workflow.js +535 -250
  177. package/dist/workflow.js.map +1 -1
  178. package/package.json +8 -3
@@ -0,0 +1,2991 @@
1
+ import {
2
+ cn
3
+ } from "./chunk-ZAUUGK2Y.js";
4
+
5
+ // src/workflow/utils/paths.ts
6
+ function buildEdgePath(routing, start, startSide, end, endSide, options = {}) {
7
+ switch (routing) {
8
+ case "step":
9
+ return stepPath(start, startSide, end, endSide);
10
+ case "smoothstep":
11
+ return smoothStepPath(start, startSide, end, endSide, options.borderRadius ?? 8);
12
+ case "straight":
13
+ return straightPath(start, end);
14
+ default:
15
+ return bezierPath(start, startSide, end, endSide, options.curvature ?? 0.25);
16
+ }
17
+ }
18
+ function bezierPath(start, startSide, end, endSide, curvature = 0.25) {
19
+ const sourceOffset = calcControlOffset(start, startSide, end, curvature);
20
+ const targetOffset = calcControlOffset(end, endSide, start, curvature);
21
+ const c1 = offsetAlongSide(start, startSide, sourceOffset);
22
+ const c2 = offsetAlongSide(end, endSide, targetOffset);
23
+ const d = `M ${start.x},${start.y} C ${c1.x},${c1.y} ${c2.x},${c2.y} ${end.x},${end.y}`;
24
+ const midX = 0.125 * start.x + 0.375 * c1.x + 0.375 * c2.x + 0.125 * end.x;
25
+ const midY = 0.125 * start.y + 0.375 * c1.y + 0.375 * c2.y + 0.125 * end.y;
26
+ const tx = 3 * ((1 - 0.5) ** 2 * (c1.x - start.x) + 2 * (1 - 0.5) * 0.5 * (c2.x - c1.x) + 0.5 ** 2 * (end.x - c2.x));
27
+ const ty = 3 * ((1 - 0.5) ** 2 * (c1.y - start.y) + 2 * (1 - 0.5) * 0.5 * (c2.y - c1.y) + 0.5 ** 2 * (end.y - c2.y));
28
+ const midAngle = Math.atan2(ty, tx);
29
+ return { d, midX, midY, midAngle };
30
+ }
31
+ function axisDistance(from, side, to) {
32
+ switch (side) {
33
+ case "top":
34
+ return from.y - to.y;
35
+ case "bottom":
36
+ return to.y - from.y;
37
+ case "left":
38
+ return from.x - to.x;
39
+ case "right":
40
+ return to.x - from.x;
41
+ }
42
+ }
43
+ function calcControlOffset(from, side, to, curvature) {
44
+ const distance2 = axisDistance(from, side, to);
45
+ if (distance2 >= 0) {
46
+ return distance2 * 0.5 * (1 + curvature);
47
+ }
48
+ return curvature * 25 * Math.sqrt(-distance2);
49
+ }
50
+ function offsetAlongSide(p, side, magnitude) {
51
+ switch (side) {
52
+ case "top":
53
+ return { x: p.x, y: p.y - magnitude };
54
+ case "bottom":
55
+ return { x: p.x, y: p.y + magnitude };
56
+ case "left":
57
+ return { x: p.x - magnitude, y: p.y };
58
+ case "right":
59
+ return { x: p.x + magnitude, y: p.y };
60
+ }
61
+ }
62
+ function stepPath(start, startSide, end, endSide) {
63
+ const corners = computeStepCorners(start, startSide, end, endSide);
64
+ const pts = [start, ...corners, end];
65
+ const d = pts.map((p, i) => `${i === 0 ? "M" : "L"} ${p.x},${p.y}`).join(" ");
66
+ const { midX, midY, midAngle } = midpointOnPolyline(pts);
67
+ return { d, midX, midY, midAngle };
68
+ }
69
+ function smoothStepPath(start, startSide, end, endSide, borderRadius = 8) {
70
+ const corners = computeStepCorners(start, startSide, end, endSide);
71
+ const pts = [start, ...corners, end];
72
+ if (corners.length === 0) {
73
+ return straightPath(start, end);
74
+ }
75
+ const segments = [`M ${pts[0].x},${pts[0].y}`];
76
+ for (let i = 1; i < pts.length - 1; i++) {
77
+ const prev = pts[i - 1];
78
+ const here = pts[i];
79
+ const next = pts[i + 1];
80
+ const r = Math.min(borderRadius, distance(prev, here) / 2, distance(here, next) / 2);
81
+ const enter = pointTowards(here, prev, r);
82
+ const exit = pointTowards(here, next, r);
83
+ segments.push(`L ${enter.x},${enter.y}`);
84
+ segments.push(`Q ${here.x},${here.y} ${exit.x},${exit.y}`);
85
+ }
86
+ const last = pts[pts.length - 1];
87
+ segments.push(`L ${last.x},${last.y}`);
88
+ const d = segments.join(" ");
89
+ const { midX, midY, midAngle } = midpointOnPolyline(pts);
90
+ return { d, midX, midY, midAngle };
91
+ }
92
+ function straightPath(start, end) {
93
+ const d = `M ${start.x},${start.y} L ${end.x},${end.y}`;
94
+ return {
95
+ d,
96
+ midX: (start.x + end.x) / 2,
97
+ midY: (start.y + end.y) / 2,
98
+ midAngle: Math.atan2(end.y - start.y, end.x - start.x)
99
+ };
100
+ }
101
+ function computeStepCorners(start, startSide, end, endSide) {
102
+ const sourceVertical = startSide === "top" || startSide === "bottom";
103
+ const targetVertical = endSide === "top" || endSide === "bottom";
104
+ if (sourceVertical && targetVertical) {
105
+ const midY = (start.y + end.y) / 2;
106
+ return [
107
+ { x: start.x, y: midY },
108
+ { x: end.x, y: midY }
109
+ ];
110
+ }
111
+ if (!sourceVertical && !targetVertical) {
112
+ const midX = (start.x + end.x) / 2;
113
+ return [
114
+ { x: midX, y: start.y },
115
+ { x: midX, y: end.y }
116
+ ];
117
+ }
118
+ if (sourceVertical) {
119
+ return [{ x: end.x, y: start.y }];
120
+ }
121
+ return [{ x: start.x, y: end.y }];
122
+ }
123
+ function midpointOnPolyline(pts) {
124
+ if (pts.length === 2) {
125
+ return {
126
+ midX: (pts[0].x + pts[1].x) / 2,
127
+ midY: (pts[0].y + pts[1].y) / 2,
128
+ midAngle: Math.atan2(pts[1].y - pts[0].y, pts[1].x - pts[0].x)
129
+ };
130
+ }
131
+ let totalLen = 0;
132
+ const lens = [];
133
+ for (let i = 0; i < pts.length - 1; i++) {
134
+ const l = distance(pts[i], pts[i + 1]);
135
+ lens.push(l);
136
+ totalLen += l;
137
+ }
138
+ const half = totalLen / 2;
139
+ let acc = 0;
140
+ for (let i = 0; i < lens.length; i++) {
141
+ if (acc + lens[i] >= half) {
142
+ const seg = lens[i];
143
+ const remaining = half - acc;
144
+ const t = seg === 0 ? 0 : remaining / seg;
145
+ const a = pts[i];
146
+ const b = pts[i + 1];
147
+ return {
148
+ midX: a.x + (b.x - a.x) * t,
149
+ midY: a.y + (b.y - a.y) * t,
150
+ midAngle: Math.atan2(b.y - a.y, b.x - a.x)
151
+ };
152
+ }
153
+ acc += lens[i];
154
+ }
155
+ return { midX: pts[0].x, midY: pts[0].y, midAngle: 0 };
156
+ }
157
+ function distance(a, b) {
158
+ return Math.hypot(b.x - a.x, b.y - a.y);
159
+ }
160
+ function pointTowards(from, to, dist) {
161
+ const d = distance(from, to);
162
+ if (d === 0) return from;
163
+ const t = dist / d;
164
+ return { x: from.x + (to.x - from.x) * t, y: from.y + (to.y - from.y) * t };
165
+ }
166
+
167
+ // src/workflow/hooks/useFlow.ts
168
+ import { createContext, useContext } from "react";
169
+ var FlowInstanceContext = createContext(null);
170
+ function useFlow() {
171
+ const instance = useContext(FlowInstanceContext);
172
+ if (!instance) {
173
+ throw new Error("[@octaviaflow/core/workflow] useFlow() must be called inside <FlowCanvas>.");
174
+ }
175
+ return instance;
176
+ }
177
+
178
+ // src/workflow/store/selectors.ts
179
+ import { useContext as useContext3, useMemo, useSyncExternalStore } from "react";
180
+
181
+ // src/workflow/store/context.ts
182
+ import { createContext as createContext2, useContext as useContext2 } from "react";
183
+ var FlowStoreContext = createContext2(null);
184
+ function useFlowStore() {
185
+ const store = useContext2(FlowStoreContext);
186
+ if (!store) {
187
+ throw new Error(
188
+ "[@octaviaflow/core/workflow] useFlowStore must be called inside a <FlowCanvas>."
189
+ );
190
+ }
191
+ return store;
192
+ }
193
+
194
+ // src/workflow/store/selectors.ts
195
+ function useFlowSelector(selector, isEqual = Object.is) {
196
+ void isEqual;
197
+ const store = useFlowStore();
198
+ return useSyncExternalStore(
199
+ store.subscribe,
200
+ () => selector(store.getSnapshot()),
201
+ () => selector(store.getSnapshot())
202
+ );
203
+ }
204
+ function useNodes() {
205
+ return useFlowSelector((s) => s.nodes);
206
+ }
207
+ function useEdges() {
208
+ return useFlowSelector((s) => s.edges);
209
+ }
210
+ function useViewport() {
211
+ return useFlowSelector((s) => s.viewport);
212
+ }
213
+ var VIEWPORT_OR_NULL_NO_STORE_SUBSCRIBE = (_cb) => () => {
214
+ };
215
+ var VIEWPORT_OR_NULL_NO_STORE_SNAPSHOT = () => null;
216
+ function useViewportOrNull() {
217
+ const store = useContext3(FlowStoreContext);
218
+ const { sub, snap } = useMemo(
219
+ () => store ? {
220
+ sub: store.subscribe,
221
+ snap: () => store.getSnapshot().viewport
222
+ } : {
223
+ sub: VIEWPORT_OR_NULL_NO_STORE_SUBSCRIBE,
224
+ snap: VIEWPORT_OR_NULL_NO_STORE_SNAPSHOT
225
+ },
226
+ [store]
227
+ );
228
+ return useSyncExternalStore(sub, snap, snap);
229
+ }
230
+ function useNodeById(id) {
231
+ return useFlowSelector((s) => s.nodes.find((n) => n.id === id));
232
+ }
233
+ function useNodeData(id) {
234
+ return useFlowSelector(
235
+ (s) => s.nodes.find((n) => n.id === id)?.data ?? void 0
236
+ );
237
+ }
238
+ function useEdgeById(id) {
239
+ return useFlowSelector((s) => s.edges.find((e) => e.id === id));
240
+ }
241
+ function useIsNodeSelected(id) {
242
+ return useFlowSelector((s) => s.selectedNodeIds.has(id));
243
+ }
244
+ function useIsEdgeSelected(id) {
245
+ return useFlowSelector((s) => s.selectedEdgeIds.has(id));
246
+ }
247
+ function useConnection() {
248
+ return useFlowSelector((s) => s.connection);
249
+ }
250
+ function useSelection() {
251
+ const nodes = useNodes();
252
+ const edges = useEdges();
253
+ const selectedNodeIds = useFlowSelector((s) => s.selectedNodeIds);
254
+ const selectedEdgeIds = useFlowSelector((s) => s.selectedEdgeIds);
255
+ return useMemo(
256
+ () => ({
257
+ nodes: nodes.filter((n) => selectedNodeIds.has(n.id)),
258
+ edges: edges.filter((e) => selectedEdgeIds.has(e.id))
259
+ }),
260
+ [nodes, edges, selectedNodeIds, selectedEdgeIds]
261
+ );
262
+ }
263
+
264
+ // src/workflow/store/changes.ts
265
+ function applyNodeChanges(nodes, changes) {
266
+ if (changes.length === 0) return nodes;
267
+ const byId = /* @__PURE__ */ new Map();
268
+ const adds = [];
269
+ const removes = /* @__PURE__ */ new Set();
270
+ let touched = false;
271
+ for (const change2 of changes) {
272
+ switch (change2.type) {
273
+ case "add":
274
+ adds.push(change2.item);
275
+ touched = true;
276
+ break;
277
+ case "remove":
278
+ removes.add(change2.id);
279
+ touched = true;
280
+ break;
281
+ default: {
282
+ const id = change2.id;
283
+ const arr = byId.get(id);
284
+ if (arr) arr.push(change2);
285
+ else byId.set(id, [change2]);
286
+ touched = true;
287
+ break;
288
+ }
289
+ }
290
+ }
291
+ if (!touched) return nodes;
292
+ const next = [];
293
+ for (const node of nodes) {
294
+ if (removes.has(node.id)) continue;
295
+ const patches = byId.get(node.id);
296
+ if (!patches) {
297
+ next.push(node);
298
+ continue;
299
+ }
300
+ let n = node;
301
+ for (const patch of patches) {
302
+ switch (patch.type) {
303
+ case "position":
304
+ n = {
305
+ ...n,
306
+ position: patch.position,
307
+ dragging: patch.dragging
308
+ };
309
+ break;
310
+ case "dimensions":
311
+ n = {
312
+ ...n,
313
+ width: patch.dimensions.width,
314
+ height: patch.dimensions.height
315
+ };
316
+ break;
317
+ case "select":
318
+ if (n.selected === patch.selected) break;
319
+ n = { ...n, selected: patch.selected };
320
+ break;
321
+ case "replace":
322
+ n = patch.item;
323
+ break;
324
+ }
325
+ }
326
+ next.push(n);
327
+ }
328
+ for (const add of adds) next.push(add);
329
+ return next;
330
+ }
331
+ function applyEdgeChanges(edges, changes) {
332
+ if (changes.length === 0) return edges;
333
+ const byId = /* @__PURE__ */ new Map();
334
+ const adds = [];
335
+ const removes = /* @__PURE__ */ new Set();
336
+ let touched = false;
337
+ for (const change2 of changes) {
338
+ switch (change2.type) {
339
+ case "add":
340
+ adds.push(change2.item);
341
+ touched = true;
342
+ break;
343
+ case "remove":
344
+ removes.add(change2.id);
345
+ touched = true;
346
+ break;
347
+ default: {
348
+ const arr = byId.get(change2.id);
349
+ if (arr) arr.push(change2);
350
+ else byId.set(change2.id, [change2]);
351
+ touched = true;
352
+ break;
353
+ }
354
+ }
355
+ }
356
+ if (!touched) return edges;
357
+ const next = [];
358
+ for (const edge of edges) {
359
+ if (removes.has(edge.id)) continue;
360
+ const patches = byId.get(edge.id);
361
+ if (!patches) {
362
+ next.push(edge);
363
+ continue;
364
+ }
365
+ let e = edge;
366
+ for (const patch of patches) {
367
+ switch (patch.type) {
368
+ case "select":
369
+ if (e.selected === patch.selected) break;
370
+ e = { ...e, selected: patch.selected };
371
+ break;
372
+ case "replace":
373
+ e = patch.item;
374
+ break;
375
+ }
376
+ }
377
+ next.push(e);
378
+ }
379
+ for (const add of adds) next.push(add);
380
+ return next;
381
+ }
382
+ var change = {
383
+ node: {
384
+ add(item) {
385
+ return { type: "add", item };
386
+ },
387
+ remove(id) {
388
+ return { type: "remove", id };
389
+ },
390
+ position(id, position, dragging) {
391
+ return { type: "position", id, position, dragging };
392
+ },
393
+ dimensions(id, dimensions) {
394
+ return { type: "dimensions", id, dimensions };
395
+ },
396
+ select(id, selected) {
397
+ return { type: "select", id, selected };
398
+ },
399
+ replace(id, item) {
400
+ return { type: "replace", id, item };
401
+ }
402
+ },
403
+ edge: {
404
+ add(item) {
405
+ return { type: "add", item };
406
+ },
407
+ remove(id) {
408
+ return { type: "remove", id };
409
+ },
410
+ select(id, selected) {
411
+ return { type: "select", id, selected };
412
+ },
413
+ replace(id, item) {
414
+ return { type: "replace", id, item };
415
+ }
416
+ }
417
+ };
418
+
419
+ // src/workflow/utils/geometry.ts
420
+ var DEFAULT_NODE_WIDTH = 368;
421
+ var DEFAULT_NODE_HEIGHT = 96;
422
+ var COLLAPSED_GROUP_HEIGHT = 36;
423
+ var COLLAPSED_FOREACH_HEIGHT = 40;
424
+ function effectiveHeight(node) {
425
+ const data = node.data;
426
+ if (data?.collapsed) {
427
+ if (node.type === "group") return COLLAPSED_GROUP_HEIGHT;
428
+ if (node.type === "forEach") return COLLAPSED_FOREACH_HEIGHT;
429
+ }
430
+ return node.height ?? DEFAULT_NODE_HEIGHT;
431
+ }
432
+ function handleCentre(node, side, index, total) {
433
+ const w = node.width ?? DEFAULT_NODE_WIDTH;
434
+ const h = effectiveHeight(node);
435
+ const x0 = node.position.x;
436
+ const y0 = node.position.y;
437
+ const denom = total + 1;
438
+ const ratio = (index + 1) / denom;
439
+ switch (side) {
440
+ case "top":
441
+ return { x: x0 + w * ratio, y: y0 };
442
+ case "bottom":
443
+ return { x: x0 + w * ratio, y: y0 + h };
444
+ case "left":
445
+ return { x: x0, y: y0 + h * ratio };
446
+ case "right":
447
+ return { x: x0 + w, y: y0 + h * ratio };
448
+ }
449
+ }
450
+ function bezierPath2(start, startSide, end, endSide) {
451
+ const distance2 = Math.hypot(end.x - start.x, end.y - start.y);
452
+ const magnitude = Math.max(40, Math.min(160, distance2 * 0.45));
453
+ const c1 = offsetBySide(start, startSide, magnitude);
454
+ const c2 = offsetBySide(end, endSide, magnitude);
455
+ const d = `M ${start.x},${start.y} C ${c1.x},${c1.y} ${c2.x},${c2.y} ${end.x},${end.y}`;
456
+ const midX = 0.125 * start.x + 0.375 * c1.x + 0.375 * c2.x + 0.125 * end.x;
457
+ const midY = 0.125 * start.y + 0.375 * c1.y + 0.375 * c2.y + 0.125 * end.y;
458
+ return { d, midX, midY };
459
+ }
460
+ function offsetBySide(p, side, m) {
461
+ switch (side) {
462
+ case "top":
463
+ return { x: p.x, y: p.y - m };
464
+ case "bottom":
465
+ return { x: p.x, y: p.y + m };
466
+ case "left":
467
+ return { x: p.x - m, y: p.y };
468
+ case "right":
469
+ return { x: p.x + m, y: p.y };
470
+ }
471
+ }
472
+ function screenToFlow(p, vp) {
473
+ return {
474
+ x: (p.x - vp.x) / vp.zoom,
475
+ y: (p.y - vp.y) / vp.zoom
476
+ };
477
+ }
478
+ function flowToScreen(p, vp) {
479
+ return {
480
+ x: p.x * vp.zoom + vp.x,
481
+ y: p.y * vp.zoom + vp.y
482
+ };
483
+ }
484
+
485
+ // src/workflow/utils/parenting.ts
486
+ function descendantsOf(nodeId, nodes) {
487
+ const childrenByParent = /* @__PURE__ */ new Map();
488
+ for (const n of nodes) {
489
+ if (!n.parentId) continue;
490
+ const arr = childrenByParent.get(n.parentId);
491
+ if (arr) arr.push(n);
492
+ else childrenByParent.set(n.parentId, [n]);
493
+ }
494
+ const out = [];
495
+ const stack = [nodeId];
496
+ const visited = /* @__PURE__ */ new Set([nodeId]);
497
+ while (stack.length) {
498
+ const cur = stack.pop();
499
+ if (cur === void 0) break;
500
+ const list = childrenByParent.get(cur);
501
+ if (!list) continue;
502
+ for (const c of list) {
503
+ if (visited.has(c.id)) continue;
504
+ visited.add(c.id);
505
+ out.push(c);
506
+ stack.push(c.id);
507
+ }
508
+ }
509
+ return out;
510
+ }
511
+ function findAncestor(node, nodes, predicate) {
512
+ let cursor = node;
513
+ const seen = /* @__PURE__ */ new Set();
514
+ while (cursor?.parentId) {
515
+ if (seen.has(cursor.parentId)) return void 0;
516
+ seen.add(cursor.parentId);
517
+ const parent = nodes.find((n) => n.id === cursor.parentId);
518
+ if (!parent) return void 0;
519
+ if (predicate(parent)) return parent;
520
+ cursor = parent;
521
+ }
522
+ return void 0;
523
+ }
524
+ function clampToParentExtent(node, proposed, nodes) {
525
+ if (node.extent !== "parent" || !node.parentId) return proposed;
526
+ const parent = nodes.find((n) => n.id === node.parentId);
527
+ if (!parent) return proposed;
528
+ const pw = parent.width ?? DEFAULT_NODE_WIDTH;
529
+ const ph = effectiveHeight(parent);
530
+ const w = node.width ?? DEFAULT_NODE_WIDTH;
531
+ const h = effectiveHeight(node);
532
+ const minX = parent.position.x;
533
+ const minY = parent.position.y;
534
+ const maxX = parent.position.x + pw - w;
535
+ const maxY = parent.position.y + ph - h;
536
+ return {
537
+ x: Math.max(minX, Math.min(maxX, proposed.x)),
538
+ y: Math.max(minY, Math.min(maxY, proposed.y))
539
+ };
540
+ }
541
+ function findContainingGroup(point, nodes, exclude = []) {
542
+ for (let i = nodes.length - 1; i >= 0; i--) {
543
+ const n = nodes[i];
544
+ if (exclude.includes(n.id)) continue;
545
+ if (n.type !== "group" && n.type !== "forEach") continue;
546
+ if (n.data && typeof n.data === "object" && n.data.collapsed) {
547
+ continue;
548
+ }
549
+ const w = n.width ?? DEFAULT_NODE_WIDTH;
550
+ const h = effectiveHeight(n);
551
+ if (point.x >= n.position.x && point.y >= n.position.y && point.x <= n.position.x + w && point.y <= n.position.y + h) {
552
+ return n;
553
+ }
554
+ }
555
+ return void 0;
556
+ }
557
+
558
+ // src/workflow/components/FlowEdge/FlowEdge.tsx
559
+ import {
560
+ memo,
561
+ useEffect,
562
+ useId,
563
+ useRef,
564
+ useState
565
+ } from "react";
566
+
567
+ // src/workflow/components/Handle/handleRegistry.ts
568
+ import { createContext as createContext3, useContext as useContext4 } from "react";
569
+ var HandleRegistryContext = createContext3(null);
570
+ function useHandleRegistry() {
571
+ const r = useContext4(HandleRegistryContext);
572
+ if (!r) {
573
+ throw new Error("[@octaviaflow/core/workflow] Handle must be used inside <FlowCanvas>.");
574
+ }
575
+ return r;
576
+ }
577
+ function createHandleRegistry() {
578
+ const map = /* @__PURE__ */ new Map();
579
+ const key = (n, t, h) => `${n}::${t}::${h}`;
580
+ const listeners = /* @__PURE__ */ new Set();
581
+ const notify = () => {
582
+ for (const l of listeners) l();
583
+ };
584
+ return {
585
+ register(d) {
586
+ map.set(key(d.nodeId, d.type, d.handleId), d);
587
+ notify();
588
+ return () => {
589
+ const k = key(d.nodeId, d.type, d.handleId);
590
+ if (map.get(k) === d) {
591
+ map.delete(k);
592
+ notify();
593
+ }
594
+ };
595
+ },
596
+ resolve(nodeId, type, handleId) {
597
+ return map.get(key(nodeId, type, handleId));
598
+ },
599
+ all() {
600
+ return Array.from(map.values());
601
+ },
602
+ subscribe(listener) {
603
+ listeners.add(listener);
604
+ return () => {
605
+ listeners.delete(listener);
606
+ };
607
+ }
608
+ };
609
+ }
610
+
611
+ // src/workflow/components/FlowEdge/FlowEdge.tsx
612
+ import { jsx, jsxs } from "react/jsx-runtime";
613
+ function FlowEdgeImpl({
614
+ edge,
615
+ nodes,
616
+ onSelect,
617
+ onDelete,
618
+ onLabelChange,
619
+ showDelete = true,
620
+ curvature = 0.25,
621
+ borderRadius = 8
622
+ }) {
623
+ const uid = useId();
624
+ const markerId = `ods-flow-edge-arrow-${uid.replace(/:/g, "")}`;
625
+ const registry = useHandleRegistry();
626
+ const [hovered, setHovered] = useState(false);
627
+ const [editing, setEditing] = useState(false);
628
+ const [draftLabel, setDraftLabel] = useState(edge.label ?? "");
629
+ const inputRef = useRef(null);
630
+ useEffect(() => {
631
+ if (!editing) setDraftLabel(edge.label ?? "");
632
+ }, [edge.label, editing]);
633
+ const sourceNode = nodes.find((n) => n.id === edge.source);
634
+ const targetNode = nodes.find((n) => n.id === edge.target);
635
+ if (!sourceNode || !targetNode) return null;
636
+ const sourceHandleId = edge.sourceHandle ?? "default";
637
+ const targetHandleId = edge.targetHandle ?? "default";
638
+ const sourceDesc = registry.resolve(sourceNode.id, "source", sourceHandleId);
639
+ const targetDesc = registry.resolve(targetNode.id, "target", targetHandleId);
640
+ const sourceSide = sourceDesc?.side ?? sourceNode.sourcePosition ?? "bottom";
641
+ const targetSide = targetDesc?.side ?? targetNode.targetPosition ?? "top";
642
+ const sourceIndex = sourceDesc?.index ?? 0;
643
+ const sourceTotal = sourceDesc?.total ?? 1;
644
+ const targetIndex = targetDesc?.index ?? 0;
645
+ const targetTotal = targetDesc?.total ?? 1;
646
+ const rawStart = handleCentre(sourceNode, sourceSide, sourceIndex, sourceTotal);
647
+ const rawEnd = handleCentre(targetNode, targetSide, targetIndex, targetTotal);
648
+ const HANDLE_GAP = 8;
649
+ const start = offsetAlongSide2(rawStart, sourceSide, HANDLE_GAP);
650
+ const end = offsetAlongSide2(rawEnd, targetSide, HANDLE_GAP);
651
+ const routing = edge.routing ?? "bezier";
652
+ const { d, midX, midY } = buildEdgePath(routing, start, sourceSide, end, targetSide, {
653
+ curvature,
654
+ borderRadius
655
+ });
656
+ const { d: hitD } = buildEdgePath(routing, rawStart, sourceSide, rawEnd, targetSide, {
657
+ curvature,
658
+ borderRadius
659
+ });
660
+ const type = edge.type ?? "default";
661
+ const isHot = hovered || edge.selected;
662
+ const stroke = type === "error" ? "var(--ods-status-failed, #dc2626)" : isHot ? "var(--ods-accent, #4f46e5)" : "var(--ods-border-strong, #6b7280)";
663
+ const typeDash = type === "conditional" ? "6 4" : type === "loop" ? "4 4" : void 0;
664
+ const dash = edge.style?.strokeDasharray ?? typeDash;
665
+ const strokeWidth = edge.style?.strokeWidth ?? (isHot ? 2 : 1.4);
666
+ const animateDash = edge.animated === true;
667
+ const label = edge.label;
668
+ const hasDelete = showDelete && (isHot || edge.selected) && !!onDelete;
669
+ const showChrome = !!label || editing || hasDelete;
670
+ const commitLabel = (next) => {
671
+ setEditing(false);
672
+ if (next !== edge.label) onLabelChange?.(edge.id, next);
673
+ };
674
+ const onLabelKey = (e) => {
675
+ if (e.key === "Enter") {
676
+ e.preventDefault();
677
+ commitLabel(draftLabel);
678
+ } else if (e.key === "Escape") {
679
+ e.preventDefault();
680
+ setEditing(false);
681
+ setDraftLabel(edge.label ?? "");
682
+ }
683
+ };
684
+ return /* @__PURE__ */ jsxs(
685
+ "g",
686
+ {
687
+ className: cn(
688
+ "ods-flow-edge-v2",
689
+ `ods-flow-edge-v2--${type}`,
690
+ `ods-flow-edge-v2--routing-${routing}`,
691
+ edge.selected && "ods-flow-edge-v2--selected",
692
+ hovered && "ods-flow-edge-v2--hovered",
693
+ edge.className
694
+ ),
695
+ "data-edge-id": edge.id,
696
+ "data-edge-routing": routing,
697
+ onMouseEnter: () => setHovered(true),
698
+ onMouseLeave: () => setHovered(false),
699
+ onClick: (e) => {
700
+ e.stopPropagation();
701
+ onSelect?.(edge.id);
702
+ },
703
+ children: [
704
+ /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx(
705
+ "marker",
706
+ {
707
+ id: markerId,
708
+ viewBox: "0 0 10 10",
709
+ refX: "9",
710
+ refY: "5",
711
+ markerWidth: "7",
712
+ markerHeight: "7",
713
+ orient: "auto-start-reverse",
714
+ children: /* @__PURE__ */ jsx("path", { d: "M0 0L10 5L0 10z", fill: stroke })
715
+ }
716
+ ) }),
717
+ /* @__PURE__ */ jsx("path", { d: hitD, stroke: "transparent", strokeWidth: 20, fill: "none" }),
718
+ /* @__PURE__ */ jsx(
719
+ "path",
720
+ {
721
+ d,
722
+ stroke,
723
+ strokeWidth,
724
+ strokeDasharray: dash,
725
+ fill: "none",
726
+ markerEnd: `url(#${markerId})`,
727
+ style: animateDash ? {
728
+ strokeDasharray: dash ?? "6 4",
729
+ animation: "ods-flow-edge-flow 0.6s linear infinite"
730
+ } : void 0
731
+ }
732
+ ),
733
+ showChrome && /* @__PURE__ */ jsx(
734
+ "foreignObject",
735
+ {
736
+ x: midX - 140,
737
+ y: midY - 16,
738
+ width: 280,
739
+ height: 32,
740
+ style: { overflow: "visible", pointerEvents: "none" },
741
+ children: /* @__PURE__ */ jsxs("div", { className: "ods-flow-edge-v2__chrome", children: [
742
+ (label || editing) && (editing ? /* @__PURE__ */ jsx(
743
+ "input",
744
+ {
745
+ ref: inputRef,
746
+ className: "ods-flow-edge-v2__label-input",
747
+ value: draftLabel,
748
+ autoFocus: true,
749
+ onChange: (e) => setDraftLabel(e.target.value),
750
+ onBlur: () => commitLabel(draftLabel),
751
+ onKeyDown: onLabelKey,
752
+ onClick: (e) => e.stopPropagation(),
753
+ onMouseDown: (e) => e.stopPropagation(),
754
+ "aria-label": "Edit edge label"
755
+ }
756
+ ) : /* @__PURE__ */ jsx(
757
+ "button",
758
+ {
759
+ type: "button",
760
+ className: "ods-flow-edge-v2__label-chip",
761
+ onDoubleClick: (e) => {
762
+ if (!onLabelChange) return;
763
+ e.stopPropagation();
764
+ setDraftLabel(edge.label ?? "");
765
+ setEditing(true);
766
+ },
767
+ onClick: (e) => {
768
+ e.stopPropagation();
769
+ onSelect?.(edge.id);
770
+ },
771
+ title: onLabelChange ? "Double-click to edit" : void 0,
772
+ tabIndex: onLabelChange ? 0 : -1,
773
+ children: /* @__PURE__ */ jsx("span", { children: label })
774
+ }
775
+ )),
776
+ hasDelete && /* @__PURE__ */ jsx(
777
+ "button",
778
+ {
779
+ type: "button",
780
+ className: "ods-flow-edge-v2__delete-btn",
781
+ onClick: (e) => {
782
+ e.stopPropagation();
783
+ onDelete?.(edge.id);
784
+ },
785
+ "aria-label": "Delete edge",
786
+ children: /* @__PURE__ */ jsx("svg", { width: "10", height: "10", viewBox: "0 0 10 10", "aria-hidden": "true", children: /* @__PURE__ */ jsx(
787
+ "path",
788
+ {
789
+ d: "M2 2l6 6M8 2l-6 6",
790
+ stroke: "currentColor",
791
+ strokeWidth: 1.5,
792
+ strokeLinecap: "round"
793
+ }
794
+ ) })
795
+ }
796
+ )
797
+ ] })
798
+ }
799
+ )
800
+ ]
801
+ }
802
+ );
803
+ }
804
+ function offsetAlongSide2(p, side, gap) {
805
+ switch (side) {
806
+ case "top":
807
+ return { x: p.x, y: p.y - gap };
808
+ case "bottom":
809
+ return { x: p.x, y: p.y + gap };
810
+ case "left":
811
+ return { x: p.x - gap, y: p.y };
812
+ case "right":
813
+ return { x: p.x + gap, y: p.y };
814
+ }
815
+ }
816
+ var FlowEdge = memo(FlowEdgeImpl, (prev, next) => {
817
+ if (prev.edge !== next.edge) return false;
818
+ if (prev.onSelect !== next.onSelect || prev.onDelete !== next.onDelete) return false;
819
+ if (prev.onLabelChange !== next.onLabelChange) return false;
820
+ if (prev.showDelete !== next.showDelete) return false;
821
+ if (prev.curvature !== next.curvature || prev.borderRadius !== next.borderRadius) return false;
822
+ if (prev.handleVersion !== next.handleVersion) return false;
823
+ const ps = prev.nodes.find((n) => n.id === prev.edge.source);
824
+ const pt = prev.nodes.find((n) => n.id === prev.edge.target);
825
+ const ns = next.nodes.find((n) => n.id === next.edge.source);
826
+ const nt = next.nodes.find((n) => n.id === next.edge.target);
827
+ if (ps !== ns || pt !== nt) return false;
828
+ return true;
829
+ });
830
+
831
+ // src/workflow/components/FlowNode/FlowNodeContext.tsx
832
+ import { createContext as createContext4, useContext as useContext5 } from "react";
833
+ var FlowNodeContext = createContext4(null);
834
+ function useFlowNodeContext() {
835
+ const v = useContext5(FlowNodeContext);
836
+ if (!v) {
837
+ throw new Error(
838
+ "[@octaviaflow/core/workflow] Handle / NodeToolbar must be inside a node renderer."
839
+ );
840
+ }
841
+ return v;
842
+ }
843
+
844
+ // src/workflow/components/FlowNode/FlowNode.tsx
845
+ import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2 } from "react";
846
+
847
+ // src/workflow/components/FlowCanvas/FlowCanvasContext.tsx
848
+ import { createContext as createContext5, useContext as useContext6 } from "react";
849
+ var FlowDispatchContext = createContext5(null);
850
+ function useFlowDispatch() {
851
+ const dispatch = useContext6(FlowDispatchContext);
852
+ if (!dispatch) {
853
+ throw new Error(
854
+ "[@octaviaflow/core/workflow] useFlowDispatch must be called inside <FlowCanvas>."
855
+ );
856
+ }
857
+ return dispatch;
858
+ }
859
+ var FlowNodeBridgeContext = createContext5(null);
860
+ function useFlowNodeBridge() {
861
+ const b = useContext6(FlowNodeBridgeContext);
862
+ if (!b) {
863
+ throw new Error("[@octaviaflow/core/workflow] FlowNode must be a child of <FlowCanvas>.");
864
+ }
865
+ return b;
866
+ }
867
+
868
+ // src/workflow/components/FlowNode/FlowNode.tsx
869
+ import { jsx as jsx2 } from "react/jsx-runtime";
870
+ function FlowNode({
871
+ node,
872
+ selected,
873
+ dragging,
874
+ isConnecting,
875
+ Kind,
876
+ // Match the BaseNode body's fixed 368 px width so the wrapper bbox and
877
+ // the rendered card line up on the first paint — before the
878
+ // ResizeObserver has had a chance to write back the measured size.
879
+ // Container kinds (group / forEach) opt out by setting `node.width`.
880
+ defaultWidth = 368
881
+ }) {
882
+ const bridge = useFlowNodeBridge();
883
+ const wrapperRef = useRef2(null);
884
+ useEffect2(() => {
885
+ const el = wrapperRef.current;
886
+ if (!el || typeof ResizeObserver === "undefined") return;
887
+ if (node.type === "group" || node.type === "forEach") return;
888
+ const ro = new ResizeObserver(() => {
889
+ bridge.reportDimensions(node.id, el.offsetWidth, el.offsetHeight);
890
+ });
891
+ ro.observe(el);
892
+ return () => ro.disconnect();
893
+ }, [bridge, node.id, node.type]);
894
+ const ctx = useMemo2(
895
+ () => ({ id: node.id, node, selected }),
896
+ [node, selected]
897
+ );
898
+ const downPosRef = useRef2(null);
899
+ const draggedRef = useRef2(false);
900
+ const CLICK_VS_DRAG_PX = 5;
901
+ const handlePointerDown = (e) => {
902
+ if (e.target.closest("[data-handle-id]")) return;
903
+ if (e.target.closest("[data-flow-no-drag='true']")) return;
904
+ e.stopPropagation();
905
+ downPosRef.current = { x: e.clientX, y: e.clientY };
906
+ draggedRef.current = false;
907
+ bridge.beginNodeDrag(node.id, e.pointerId, e.clientX, e.clientY, e.altKey);
908
+ };
909
+ const handlePointerMove = (e) => {
910
+ const start = downPosRef.current;
911
+ if (!start || draggedRef.current) return;
912
+ if (Math.abs(e.clientX - start.x) > CLICK_VS_DRAG_PX || Math.abs(e.clientY - start.y) > CLICK_VS_DRAG_PX) {
913
+ draggedRef.current = true;
914
+ }
915
+ };
916
+ const handleClick = (e) => {
917
+ if (e.target.closest("[data-handle-id]")) return;
918
+ e.stopPropagation();
919
+ if (draggedRef.current) {
920
+ draggedRef.current = false;
921
+ downPosRef.current = null;
922
+ return;
923
+ }
924
+ downPosRef.current = null;
925
+ bridge.selectNode(node.id, e.metaKey || e.ctrlKey || e.shiftKey);
926
+ bridge.notifyNodeClick(node.id);
927
+ };
928
+ return /* @__PURE__ */ jsx2(
929
+ "div",
930
+ {
931
+ ref: wrapperRef,
932
+ "data-node-id": node.id,
933
+ "data-node-type": node.type,
934
+ "data-node-selected": selected ? "true" : "false",
935
+ className: cn(
936
+ "ods-flow-node-v2",
937
+ `ods-flow-node-v2--kind-${node.type}`,
938
+ selected && "ods-flow-node-v2--selected",
939
+ dragging && "ods-flow-node-v2--dragging",
940
+ isConnecting && "ods-flow-node-v2--connecting",
941
+ node.className
942
+ ),
943
+ style: {
944
+ position: "absolute",
945
+ left: node.position.x,
946
+ top: node.position.y,
947
+ width: node.width ?? defaultWidth,
948
+ // Z-stack (per architecture doc): groups (20) sit below normal
949
+ // nodes (30) so children render visually on top of their parent
950
+ // frame. Selection raises by 10. Consumer override wins.
951
+ zIndex: node.zIndex ?? (selected ? node.type === "group" ? 35 : 40 : node.type === "group" ? 20 : 30),
952
+ ...node.style
953
+ },
954
+ onPointerDown: handlePointerDown,
955
+ onPointerMove: handlePointerMove,
956
+ onClick: handleClick,
957
+ children: /* @__PURE__ */ jsx2(FlowNodeContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx2(Kind, { node, selected, dragging, isConnecting }) })
958
+ }
959
+ );
960
+ }
961
+
962
+ // src/workflow/components/FlowNode/nodeKinds.ts
963
+ function buildNodeKindRegistry(defaults, overrides) {
964
+ return Object.freeze({ ...defaults, ...overrides ?? {} });
965
+ }
966
+
967
+ // src/workflow/components/Handle/Handle.tsx
968
+ import { useEffect as useEffect3, useRef as useRef3 } from "react";
969
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
970
+ var DEFAULT_HANDLE_ID = "default";
971
+ function Handle({
972
+ type,
973
+ position,
974
+ id = DEFAULT_HANDLE_ID,
975
+ isConnectable = true,
976
+ isConnectableStart,
977
+ isConnectableEnd,
978
+ index = 0,
979
+ total = 1,
980
+ label,
981
+ className,
982
+ style
983
+ }) {
984
+ const registry = useHandleRegistry();
985
+ const node = useFlowNodeContext();
986
+ const dispatch = useFlowDispatch();
987
+ const ref = useRef3(null);
988
+ const canStart = isConnectableStart ?? isConnectable;
989
+ const canEnd = isConnectableEnd ?? isConnectable;
990
+ useEffect3(() => {
991
+ const dispose = registry.register({
992
+ nodeId: node.id,
993
+ handleId: id,
994
+ type,
995
+ side: position,
996
+ index,
997
+ total,
998
+ canStart,
999
+ canEnd
1000
+ });
1001
+ return dispose;
1002
+ }, [registry, node.id, id, type, position, index, total, canStart, canEnd]);
1003
+ const handlePointerDown = (e) => {
1004
+ if (!canStart) return;
1005
+ e.stopPropagation();
1006
+ e.preventDefault();
1007
+ dispatch({
1008
+ type: "connection/start",
1009
+ nodeId: node.id,
1010
+ handleId: id,
1011
+ handleType: type,
1012
+ pointerId: e.pointerId,
1013
+ clientX: e.clientX,
1014
+ clientY: e.clientY
1015
+ });
1016
+ };
1017
+ return /* @__PURE__ */ jsxs2(
1018
+ "div",
1019
+ {
1020
+ ref,
1021
+ "data-handle-id": id,
1022
+ "data-handle-node-id": node.id,
1023
+ "data-handle-type": type,
1024
+ "data-handle-side": position,
1025
+ "data-handle-connectable-end": canEnd ? "true" : "false",
1026
+ className: cn(
1027
+ "ods-flow-handle",
1028
+ `ods-flow-handle--${type}`,
1029
+ `ods-flow-handle--side-${position}`,
1030
+ !isConnectable && "ods-flow-handle--disabled",
1031
+ className
1032
+ ),
1033
+ style: {
1034
+ ...handleSideStyle(position, index, total),
1035
+ ...style
1036
+ },
1037
+ onPointerDown: handlePointerDown,
1038
+ children: [
1039
+ /* @__PURE__ */ jsx3("div", { className: "ods-flow-handle__dot" }),
1040
+ label && /* @__PURE__ */ jsx3("span", { className: "ods-flow-handle__label", children: label })
1041
+ ]
1042
+ }
1043
+ );
1044
+ }
1045
+ function handleSideStyle(side, index, total) {
1046
+ const ratio = (index + 1) / (total + 1) * 100;
1047
+ switch (side) {
1048
+ case "top":
1049
+ return { position: "absolute", top: -6, left: `${ratio}%`, transform: "translateX(-50%)" };
1050
+ case "bottom":
1051
+ return { position: "absolute", bottom: -6, left: `${ratio}%`, transform: "translateX(-50%)" };
1052
+ case "left":
1053
+ return { position: "absolute", left: -6, top: `${ratio}%`, transform: "translateY(-50%)" };
1054
+ case "right":
1055
+ return { position: "absolute", right: -6, top: `${ratio}%`, transform: "translateY(-50%)" };
1056
+ }
1057
+ }
1058
+
1059
+ // src/workflow/components/NodeResizer/NodeResizer.tsx
1060
+ import { useRef as useRef4 } from "react";
1061
+ import { jsx as jsx4 } from "react/jsx-runtime";
1062
+ function NodeResizer({
1063
+ isVisible,
1064
+ minWidth = 80,
1065
+ minHeight = 60,
1066
+ maxWidth,
1067
+ maxHeight,
1068
+ keepAspectRatio = false,
1069
+ onResize,
1070
+ onResizeEnd,
1071
+ color
1072
+ }) {
1073
+ const { node, selected } = useFlowNodeContext();
1074
+ const viewport = useViewport();
1075
+ const flow = useFlow();
1076
+ const dragRef = useRef4(null);
1077
+ const show = isVisible ?? selected;
1078
+ if (!show) return null;
1079
+ const beginResize = (e, corner) => {
1080
+ e.preventDefault();
1081
+ e.stopPropagation();
1082
+ e.target.setPointerCapture(e.pointerId);
1083
+ const w = node.width ?? DEFAULT_NODE_WIDTH;
1084
+ const h = node.height ?? DEFAULT_NODE_HEIGHT;
1085
+ dragRef.current = {
1086
+ pointerId: e.pointerId,
1087
+ corner,
1088
+ startClientX: e.clientX,
1089
+ startClientY: e.clientY,
1090
+ startWidth: w,
1091
+ startHeight: h,
1092
+ startX: node.position.x,
1093
+ startY: node.position.y,
1094
+ aspect: w / Math.max(1, h)
1095
+ };
1096
+ };
1097
+ const onMove = (e) => {
1098
+ const drag = dragRef.current;
1099
+ if (!drag || drag.pointerId !== e.pointerId) return;
1100
+ const dx = (e.clientX - drag.startClientX) / viewport.zoom;
1101
+ const dy = (e.clientY - drag.startClientY) / viewport.zoom;
1102
+ let nextW = drag.startWidth;
1103
+ let nextH = drag.startHeight;
1104
+ let nextX = drag.startX;
1105
+ let nextY = drag.startY;
1106
+ switch (drag.corner) {
1107
+ case "se":
1108
+ nextW = drag.startWidth + dx;
1109
+ nextH = drag.startHeight + dy;
1110
+ break;
1111
+ case "sw":
1112
+ nextW = drag.startWidth - dx;
1113
+ nextH = drag.startHeight + dy;
1114
+ nextX = drag.startX + dx;
1115
+ break;
1116
+ case "ne":
1117
+ nextW = drag.startWidth + dx;
1118
+ nextH = drag.startHeight - dy;
1119
+ nextY = drag.startY + dy;
1120
+ break;
1121
+ case "nw":
1122
+ nextW = drag.startWidth - dx;
1123
+ nextH = drag.startHeight - dy;
1124
+ nextX = drag.startX + dx;
1125
+ nextY = drag.startY + dy;
1126
+ break;
1127
+ }
1128
+ if (keepAspectRatio) {
1129
+ nextH = nextW / drag.aspect;
1130
+ if (drag.corner === "nw" || drag.corner === "ne") {
1131
+ nextY = drag.startY + (drag.startHeight - nextH);
1132
+ }
1133
+ }
1134
+ nextW = Math.max(minWidth, maxWidth ? Math.min(maxWidth, nextW) : nextW);
1135
+ nextH = Math.max(minHeight, maxHeight ? Math.min(maxHeight, nextH) : nextH);
1136
+ flow.updateNode(node.id, {
1137
+ width: nextW,
1138
+ height: nextH,
1139
+ position: { x: nextX, y: nextY }
1140
+ });
1141
+ onResize?.({ width: nextW, height: nextH });
1142
+ };
1143
+ const onUp = (e) => {
1144
+ if (dragRef.current?.pointerId === e.pointerId) {
1145
+ const cur = flow.getNode(node.id);
1146
+ if (cur) {
1147
+ onResizeEnd?.({
1148
+ width: cur.width ?? DEFAULT_NODE_WIDTH,
1149
+ height: cur.height ?? DEFAULT_NODE_HEIGHT
1150
+ });
1151
+ }
1152
+ dragRef.current = null;
1153
+ }
1154
+ };
1155
+ const handleColor = color ?? "var(--ods-accent)";
1156
+ const handleStyle = (corner) => {
1157
+ const base = {
1158
+ position: "absolute",
1159
+ width: 12,
1160
+ height: 12,
1161
+ background: "var(--ods-surface-canvas)",
1162
+ border: `2px solid ${handleColor}`,
1163
+ borderRadius: 2,
1164
+ cursor: cursorFor(corner),
1165
+ touchAction: "none",
1166
+ // Place each handle so its CENTRE sits on the corresponding corner.
1167
+ transform: "translate(-50%, -50%)"
1168
+ };
1169
+ switch (corner) {
1170
+ case "nw":
1171
+ return { ...base, top: 0, left: 0 };
1172
+ case "ne":
1173
+ return { ...base, top: 0, left: "100%" };
1174
+ case "sw":
1175
+ return { ...base, top: "100%", left: 0 };
1176
+ case "se":
1177
+ return { ...base, top: "100%", left: "100%" };
1178
+ }
1179
+ };
1180
+ return /* @__PURE__ */ jsx4("div", { className: cn("ods-node-resizer"), "data-flow-no-drag": "true", children: ["nw", "ne", "sw", "se"].map((corner) => /* @__PURE__ */ jsx4(
1181
+ "div",
1182
+ {
1183
+ style: handleStyle(corner),
1184
+ onPointerDown: (e) => beginResize(e, corner),
1185
+ onPointerMove: onMove,
1186
+ onPointerUp: onUp,
1187
+ onPointerCancel: onUp,
1188
+ "aria-label": `Resize ${corner}`
1189
+ },
1190
+ corner
1191
+ )) });
1192
+ }
1193
+ function cursorFor(corner) {
1194
+ switch (corner) {
1195
+ case "nw":
1196
+ case "se":
1197
+ return "nwse-resize";
1198
+ case "ne":
1199
+ case "sw":
1200
+ return "nesw-resize";
1201
+ }
1202
+ }
1203
+
1204
+ // src/workflow/components/kinds/BaseNode.tsx
1205
+ import { TrashCanIcon } from "@octaviaflow/icons";
1206
+ import { useContext as useContext7 } from "react";
1207
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
1208
+ function BaseNode({
1209
+ kind,
1210
+ kindIcon,
1211
+ icon,
1212
+ title,
1213
+ chip,
1214
+ description,
1215
+ valueChip,
1216
+ accent = "green",
1217
+ status,
1218
+ onDelete,
1219
+ footer,
1220
+ className,
1221
+ children
1222
+ }) {
1223
+ const ctx = useContext7(FlowNodeContext);
1224
+ const bridge = useContext7(FlowNodeBridgeContext);
1225
+ const deleteHandler = onDelete === false ? void 0 : onDelete ?? (ctx && bridge ? () => bridge.deleteNode(ctx.id) : void 0);
1226
+ return /* @__PURE__ */ jsxs3(
1227
+ "div",
1228
+ {
1229
+ className: cn(
1230
+ "ods-flow-base-node",
1231
+ `ods-flow-base-node--accent-${accent}`,
1232
+ status && `ods-flow-base-node--status-${status}`,
1233
+ className
1234
+ ),
1235
+ children: [
1236
+ /* @__PURE__ */ jsxs3("div", { className: "ods-flow-base-node__pill", children: [
1237
+ kindIcon && /* @__PURE__ */ jsx5("span", { className: "ods-flow-base-node__pill-icon", "aria-hidden": "true", children: kindIcon }),
1238
+ /* @__PURE__ */ jsx5("span", { className: "ods-flow-base-node__pill-label", children: kind })
1239
+ ] }),
1240
+ status && status !== "idle" && /* @__PURE__ */ jsx5(
1241
+ "span",
1242
+ {
1243
+ className: cn("ods-flow-base-node__status", `ods-flow-base-node__status--${status}`),
1244
+ "aria-hidden": "true"
1245
+ }
1246
+ ),
1247
+ /* @__PURE__ */ jsxs3("div", { className: "ods-flow-base-node__body", children: [
1248
+ /* @__PURE__ */ jsxs3("div", { className: "ods-flow-base-node__content", children: [
1249
+ /* @__PURE__ */ jsx5("div", { className: "ods-flow-base-node__bubble", "aria-hidden": "true", children: icon }),
1250
+ /* @__PURE__ */ jsxs3("div", { className: "ods-flow-base-node__content-text", children: [
1251
+ /* @__PURE__ */ jsx5("div", { className: "ods-flow-base-node__content-title", children: title }),
1252
+ (chip !== void 0 || description !== void 0 || valueChip !== void 0) && /* @__PURE__ */ jsxs3("div", { className: "ods-flow-base-node__content-info", children: [
1253
+ chip !== void 0 && /* @__PURE__ */ jsx5("span", { className: "ods-flow-base-node__chip", children: chip }),
1254
+ description !== void 0 && /* @__PURE__ */ jsx5("span", { className: "ods-flow-base-node__description", children: description }),
1255
+ valueChip !== void 0 && /* @__PURE__ */ jsx5("span", { className: "ods-flow-base-node__value-chip", children: valueChip })
1256
+ ] })
1257
+ ] })
1258
+ ] }),
1259
+ footer && /* @__PURE__ */ jsx5("div", { className: "ods-flow-base-node__footer", children: footer }),
1260
+ deleteHandler && /* @__PURE__ */ jsx5(
1261
+ "button",
1262
+ {
1263
+ type: "button",
1264
+ className: "ods-flow-base-node__delete",
1265
+ onClick: (e) => {
1266
+ e.stopPropagation();
1267
+ deleteHandler();
1268
+ },
1269
+ "aria-label": "Delete node",
1270
+ "data-flow-no-drag": "true",
1271
+ title: "Delete node",
1272
+ children: /* @__PURE__ */ jsx5(TrashCanIcon, { size: 16, "aria-hidden": true })
1273
+ }
1274
+ )
1275
+ ] }),
1276
+ children
1277
+ ]
1278
+ }
1279
+ );
1280
+ }
1281
+
1282
+ // src/workflow/components/kinds/index.tsx
1283
+ import { Fragment, jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
1284
+ var ActionNode = ({
1285
+ node
1286
+ }) => {
1287
+ const d = node.data ?? {};
1288
+ return /* @__PURE__ */ jsxs4(
1289
+ BaseNode,
1290
+ {
1291
+ kind: d.kind ?? "ACTION",
1292
+ icon: d.icon,
1293
+ title: d.title ?? "Action",
1294
+ chip: d.chip ?? d.badge,
1295
+ description: d.description ?? d.subtitle,
1296
+ valueChip: d.valueChip,
1297
+ status: d.status,
1298
+ accent: "green",
1299
+ children: [
1300
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top" }),
1301
+ /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom" })
1302
+ ]
1303
+ }
1304
+ );
1305
+ };
1306
+ var TriggerNode = ({
1307
+ node
1308
+ }) => {
1309
+ const d = node.data ?? {};
1310
+ return /* @__PURE__ */ jsx6(
1311
+ BaseNode,
1312
+ {
1313
+ kind: d.kind ?? "TRIGGER",
1314
+ icon: d.icon,
1315
+ title: d.title ?? "Trigger",
1316
+ chip: d.chip,
1317
+ description: d.description ?? "Manually triggered",
1318
+ valueChip: d.valueChip,
1319
+ status: d.status,
1320
+ accent: "green",
1321
+ children: /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom" })
1322
+ }
1323
+ );
1324
+ };
1325
+ var ConditionNode = ({
1326
+ node
1327
+ }) => {
1328
+ const d = node.data ?? {};
1329
+ const branches = d.branches ?? [
1330
+ { id: "true", label: "true" },
1331
+ { id: "false", label: "false" }
1332
+ ];
1333
+ return /* @__PURE__ */ jsxs4(
1334
+ BaseNode,
1335
+ {
1336
+ kind: d.kind ?? "CONDITION",
1337
+ icon: d.icon,
1338
+ title: d.title ?? "Condition",
1339
+ chip: d.chip ?? d.badge,
1340
+ description: d.description ?? d.subtitle,
1341
+ valueChip: d.valueChip,
1342
+ status: d.status,
1343
+ accent: "amber",
1344
+ children: [
1345
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top" }),
1346
+ branches.map((b, i) => /* @__PURE__ */ jsx6(
1347
+ Handle,
1348
+ {
1349
+ type: "source",
1350
+ position: "bottom",
1351
+ id: b.id,
1352
+ index: i,
1353
+ total: branches.length,
1354
+ label: b.label
1355
+ },
1356
+ b.id
1357
+ ))
1358
+ ]
1359
+ }
1360
+ );
1361
+ };
1362
+ var GroupNode = ({
1363
+ node
1364
+ }) => {
1365
+ const d = node.data ?? {};
1366
+ const collapsed = !!d.collapsed;
1367
+ const disabled = !!d.disabled;
1368
+ const hiddenCount = d.hiddenCount;
1369
+ const bridge = useFlowNodeBridge();
1370
+ const onChevronClick = (e) => {
1371
+ e.stopPropagation();
1372
+ bridge.toggleNodeCollapse(node.id);
1373
+ };
1374
+ return /* @__PURE__ */ jsxs4(
1375
+ "div",
1376
+ {
1377
+ className: "ods-flow-group",
1378
+ "data-collapsed": collapsed ? "true" : "false",
1379
+ "data-disabled": disabled ? "true" : void 0,
1380
+ style: {
1381
+ width: node.width ?? 360,
1382
+ height: collapsed ? 36 : node.height ?? 200
1383
+ },
1384
+ children: [
1385
+ !collapsed && /* @__PURE__ */ jsx6(NodeResizer, { minWidth: 240, minHeight: 120 }),
1386
+ /* @__PURE__ */ jsxs4("div", { className: "ods-flow-group__header", "data-flow-no-drag": "false", children: [
1387
+ /* @__PURE__ */ jsx6(
1388
+ "button",
1389
+ {
1390
+ type: "button",
1391
+ className: "ods-flow-group__chevron",
1392
+ "data-flow-no-drag": "true",
1393
+ "aria-label": collapsed ? "Expand group" : "Collapse group",
1394
+ "aria-expanded": !collapsed,
1395
+ onClick: onChevronClick,
1396
+ onPointerDown: (e) => e.stopPropagation(),
1397
+ children: collapsed ? "\u25B8" : "\u25BE"
1398
+ }
1399
+ ),
1400
+ /* @__PURE__ */ jsx6("span", { className: "ods-flow-group__title", children: d.title ?? "Group" }),
1401
+ d.subtitle && /* @__PURE__ */ jsx6("span", { className: "ods-flow-group__subtitle", children: d.subtitle }),
1402
+ disabled && /* @__PURE__ */ jsx6("span", { className: "ods-flow-group__disabled-badge", "aria-label": "Disabled subflow", children: "Disabled" }),
1403
+ collapsed && hiddenCount !== void 0 && hiddenCount > 0 && /* @__PURE__ */ jsxs4("span", { className: "ods-flow-group__count", "aria-label": `${hiddenCount} hidden steps`, children: [
1404
+ hiddenCount,
1405
+ " steps"
1406
+ ] })
1407
+ ] }),
1408
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top", id: "__group_in" }),
1409
+ /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom", id: "__group_out" })
1410
+ ]
1411
+ }
1412
+ );
1413
+ };
1414
+ var ForEachNode = ({
1415
+ node
1416
+ }) => {
1417
+ const d = node.data ?? {};
1418
+ const iteratorExpr = d.iterator ?? d.description ?? "items[]";
1419
+ const collapsed = !!d.collapsed;
1420
+ const disabled = !!d.disabled;
1421
+ const hiddenCount = d.hiddenCount;
1422
+ const bridge = useFlowNodeBridge();
1423
+ const onChevronClick = (e) => {
1424
+ e.stopPropagation();
1425
+ bridge.toggleNodeCollapse(node.id);
1426
+ };
1427
+ return /* @__PURE__ */ jsxs4(
1428
+ "div",
1429
+ {
1430
+ className: "ods-flow-foreach",
1431
+ "data-collapsed": collapsed ? "true" : "false",
1432
+ "data-disabled": disabled ? "true" : void 0,
1433
+ style: {
1434
+ width: node.width ?? 420,
1435
+ height: collapsed ? 40 : node.height ?? 260
1436
+ },
1437
+ children: [
1438
+ !collapsed && /* @__PURE__ */ jsx6(NodeResizer, { minWidth: 240, minHeight: 120 }),
1439
+ /* @__PURE__ */ jsxs4("div", { className: "ods-flow-foreach__header", children: [
1440
+ /* @__PURE__ */ jsx6(
1441
+ "button",
1442
+ {
1443
+ type: "button",
1444
+ className: "ods-flow-foreach__chevron",
1445
+ "data-flow-no-drag": "true",
1446
+ "aria-label": collapsed ? "Expand iterator" : "Collapse iterator",
1447
+ "aria-expanded": !collapsed,
1448
+ onClick: onChevronClick,
1449
+ onPointerDown: (e) => e.stopPropagation(),
1450
+ children: collapsed ? "\u25B8" : "\u25BE"
1451
+ }
1452
+ ),
1453
+ /* @__PURE__ */ jsx6("span", { className: "ods-flow-foreach__icon", "aria-hidden": "true", children: "\u21BB" }),
1454
+ /* @__PURE__ */ jsx6("span", { className: "ods-flow-foreach__title", children: d.title ?? "For each" }),
1455
+ /* @__PURE__ */ jsx6("code", { className: "ods-flow-foreach__iterator", children: iteratorExpr }),
1456
+ disabled && /* @__PURE__ */ jsx6(
1457
+ "span",
1458
+ {
1459
+ className: "ods-flow-foreach__disabled-badge",
1460
+ "aria-label": "Disabled subflow",
1461
+ children: "Disabled"
1462
+ }
1463
+ ),
1464
+ collapsed && hiddenCount !== void 0 && hiddenCount > 0 && /* @__PURE__ */ jsxs4("span", { className: "ods-flow-foreach__count", "aria-label": `${hiddenCount} hidden steps`, children: [
1465
+ hiddenCount,
1466
+ " steps"
1467
+ ] })
1468
+ ] }),
1469
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top", id: "__group_in", label: !collapsed ? "in" : void 0 }),
1470
+ collapsed ? (
1471
+ // Collapsed: single bottom exit so the container behaves like a
1472
+ // regular action in the chain.
1473
+ /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom", id: "__group_out" })
1474
+ ) : (
1475
+ // Expanded: two bottom outputs spread across the bottom edge.
1476
+ // Index/total tell the Handle to position them at 33% and 66%
1477
+ // along the edge (per `handleSideStyle`). `each` is left of
1478
+ // centre, `__group_out` (labelled "done") is right of centre.
1479
+ /* @__PURE__ */ jsxs4(Fragment, { children: [
1480
+ /* @__PURE__ */ jsx6(
1481
+ Handle,
1482
+ {
1483
+ type: "source",
1484
+ position: "bottom",
1485
+ id: "each",
1486
+ label: "each",
1487
+ index: 0,
1488
+ total: 2
1489
+ }
1490
+ ),
1491
+ /* @__PURE__ */ jsx6(
1492
+ Handle,
1493
+ {
1494
+ type: "source",
1495
+ position: "bottom",
1496
+ id: "__group_out",
1497
+ label: "done",
1498
+ index: 1,
1499
+ total: 2
1500
+ }
1501
+ )
1502
+ ] })
1503
+ )
1504
+ ]
1505
+ }
1506
+ );
1507
+ };
1508
+ var OutputNode = ({
1509
+ node
1510
+ }) => {
1511
+ const d = node.data ?? {};
1512
+ return /* @__PURE__ */ jsx6(
1513
+ BaseNode,
1514
+ {
1515
+ kind: d.kind ?? "OUTPUT",
1516
+ icon: d.icon,
1517
+ title: d.title ?? "Output",
1518
+ chip: d.chip ?? d.badge,
1519
+ description: d.description ?? d.subtitle,
1520
+ status: d.status,
1521
+ accent: "green",
1522
+ children: /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top" })
1523
+ }
1524
+ );
1525
+ };
1526
+ var ErrorNode = ({
1527
+ node
1528
+ }) => {
1529
+ const d = node.data ?? {};
1530
+ return /* @__PURE__ */ jsxs4(
1531
+ BaseNode,
1532
+ {
1533
+ kind: d.kind ?? "ERROR",
1534
+ icon: d.icon,
1535
+ title: d.title ?? "On error",
1536
+ chip: d.chip ?? d.badge,
1537
+ description: d.description ?? d.subtitle,
1538
+ status: d.status ?? "error",
1539
+ accent: "red",
1540
+ children: [
1541
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top" }),
1542
+ /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom" })
1543
+ ]
1544
+ }
1545
+ );
1546
+ };
1547
+ var WaitNode = ({
1548
+ node
1549
+ }) => {
1550
+ const d = node.data ?? {};
1551
+ const waitMs = d.waitMs;
1552
+ const durationChip = waitMs ? `${Math.round(waitMs / 100) / 10}s` : void 0;
1553
+ return /* @__PURE__ */ jsxs4(
1554
+ BaseNode,
1555
+ {
1556
+ kind: d.kind ?? "WAIT",
1557
+ icon: d.icon,
1558
+ title: d.title ?? "Wait",
1559
+ chip: d.chip ?? durationChip,
1560
+ description: d.description ?? (durationChip ? "Pause execution" : void 0),
1561
+ status: d.status,
1562
+ accent: "violet",
1563
+ children: [
1564
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top" }),
1565
+ /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom" })
1566
+ ]
1567
+ }
1568
+ );
1569
+ };
1570
+ var ParallelNode = ({
1571
+ node
1572
+ }) => {
1573
+ const d = node.data ?? {};
1574
+ const branches = d.branches ?? [
1575
+ { id: "a", label: "a" },
1576
+ { id: "b", label: "b" }
1577
+ ];
1578
+ return /* @__PURE__ */ jsxs4(
1579
+ BaseNode,
1580
+ {
1581
+ kind: d.kind ?? "PARALLEL",
1582
+ icon: d.icon,
1583
+ title: d.title ?? "Parallel",
1584
+ chip: d.chip ?? `${branches.length}\xD7`,
1585
+ description: d.description ?? "Fan-out branches",
1586
+ status: d.status,
1587
+ accent: "blue",
1588
+ children: [
1589
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top" }),
1590
+ branches.map((b, i) => /* @__PURE__ */ jsx6(
1591
+ Handle,
1592
+ {
1593
+ type: "source",
1594
+ position: "bottom",
1595
+ id: b.id,
1596
+ index: i,
1597
+ total: branches.length,
1598
+ label: b.label
1599
+ },
1600
+ b.id
1601
+ ))
1602
+ ]
1603
+ }
1604
+ );
1605
+ };
1606
+ var StickyNode = ({
1607
+ node
1608
+ }) => {
1609
+ const d = node.data ?? {};
1610
+ return /* @__PURE__ */ jsxs4(
1611
+ "div",
1612
+ {
1613
+ className: "ods-flow-sticky",
1614
+ style: {
1615
+ width: node.width ?? 240,
1616
+ minHeight: node.height ?? 120
1617
+ },
1618
+ children: [
1619
+ d.title && /* @__PURE__ */ jsx6("div", { className: "ods-flow-sticky__title", children: d.title }),
1620
+ d.description && /* @__PURE__ */ jsx6("div", { className: "ods-flow-sticky__body", children: d.description })
1621
+ ]
1622
+ }
1623
+ );
1624
+ };
1625
+ var WebhookNode = ({
1626
+ node
1627
+ }) => {
1628
+ const d = node.data ?? {};
1629
+ return /* @__PURE__ */ jsx6(
1630
+ BaseNode,
1631
+ {
1632
+ kind: d.kind ?? "WEBHOOK",
1633
+ icon: d.icon,
1634
+ title: d.title ?? "Webhook",
1635
+ chip: d.chip ?? d.method ?? "POST",
1636
+ description: d.description ?? d.path ?? "/hooks/incoming",
1637
+ valueChip: d.valueChip,
1638
+ status: d.status,
1639
+ accent: "blue",
1640
+ children: /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom" })
1641
+ }
1642
+ );
1643
+ };
1644
+ var HttpRequestNode = ({
1645
+ node
1646
+ }) => {
1647
+ const d = node.data ?? {};
1648
+ return /* @__PURE__ */ jsxs4(
1649
+ BaseNode,
1650
+ {
1651
+ kind: d.kind ?? "HTTP",
1652
+ icon: d.icon,
1653
+ title: d.title ?? "HTTP Request",
1654
+ chip: d.chip ?? d.method ?? "GET",
1655
+ description: d.description ?? d.url ?? "Call an API",
1656
+ valueChip: d.valueChip,
1657
+ status: d.status,
1658
+ accent: "blue",
1659
+ children: [
1660
+ /* @__PURE__ */ jsx6(Handle, { type: "target", position: "top" }),
1661
+ /* @__PURE__ */ jsx6(Handle, { type: "source", position: "bottom" })
1662
+ ]
1663
+ }
1664
+ );
1665
+ };
1666
+ var DEFAULT_NODE_KINDS = {
1667
+ action: ActionNode,
1668
+ trigger: TriggerNode,
1669
+ condition: ConditionNode,
1670
+ group: GroupNode,
1671
+ forEach: ForEachNode,
1672
+ output: OutputNode,
1673
+ error: ErrorNode,
1674
+ wait: WaitNode,
1675
+ parallel: ParallelNode,
1676
+ sticky: StickyNode,
1677
+ webhook: WebhookNode,
1678
+ httpRequest: HttpRequestNode
1679
+ };
1680
+
1681
+ // src/workflow/components/FlowCanvas/FlowCanvas.tsx
1682
+ import {
1683
+ memo as memo2,
1684
+ useCallback,
1685
+ useEffect as useEffect4,
1686
+ useMemo as useMemo3,
1687
+ useRef as useRef5,
1688
+ useState as useState2
1689
+ } from "react";
1690
+
1691
+ // src/workflow/store/createFlowStore.ts
1692
+ var DEFAULT_VIEWPORT = { x: 0, y: 0, zoom: 1 };
1693
+ function createFlowStore({
1694
+ initialNodes = [],
1695
+ initialEdges = [],
1696
+ initialViewport = DEFAULT_VIEWPORT
1697
+ } = {}) {
1698
+ let snapshot = {
1699
+ nodes: initialNodes,
1700
+ edges: initialEdges,
1701
+ viewport: initialViewport,
1702
+ selectedNodeIds: EMPTY_SET,
1703
+ selectedEdgeIds: EMPTY_SET,
1704
+ connection: null
1705
+ };
1706
+ const listeners = /* @__PURE__ */ new Set();
1707
+ const emit = () => {
1708
+ for (const l of listeners) l();
1709
+ };
1710
+ const subscribe = (listener) => {
1711
+ listeners.add(listener);
1712
+ return () => {
1713
+ listeners.delete(listener);
1714
+ };
1715
+ };
1716
+ const replace = (patch) => {
1717
+ snapshot = { ...snapshot, ...patch };
1718
+ emit();
1719
+ };
1720
+ return {
1721
+ subscribe,
1722
+ getSnapshot: () => snapshot,
1723
+ setNodes(nodes) {
1724
+ if (nodes === snapshot.nodes) return;
1725
+ replace({ nodes });
1726
+ },
1727
+ setEdges(edges) {
1728
+ if (edges === snapshot.edges) return;
1729
+ replace({ edges });
1730
+ },
1731
+ setViewport(viewport) {
1732
+ if (viewport.x === snapshot.viewport.x && viewport.y === snapshot.viewport.y && viewport.zoom === snapshot.viewport.zoom) {
1733
+ return;
1734
+ }
1735
+ replace({ viewport });
1736
+ },
1737
+ setSelection(selectedNodeIds, selectedEdgeIds) {
1738
+ replace({ selectedNodeIds, selectedEdgeIds });
1739
+ },
1740
+ setConnection(connection) {
1741
+ if (connection === snapshot.connection) return;
1742
+ replace({ connection });
1743
+ }
1744
+ };
1745
+ }
1746
+ var EMPTY_SET = /* @__PURE__ */ new Set();
1747
+
1748
+ // src/workflow/utils/collision.ts
1749
+ function resolveNodeCollisions(node, proposed, others, opts) {
1750
+ const { gap, maxIterations = 8, exclude, scopeToSiblings = true } = opts;
1751
+ if (gap < 0 || others.length === 0) return proposed;
1752
+ const w = node.width ?? DEFAULT_NODE_WIDTH;
1753
+ const h = effectiveHeight(node);
1754
+ const parentId = node.parentId;
1755
+ const candidates = others.filter((o) => {
1756
+ if (o.id === node.id) return false;
1757
+ if (o.hidden) return false;
1758
+ if (exclude?.has(o.id)) return false;
1759
+ if (scopeToSiblings && (o.parentId ?? void 0) !== (parentId ?? void 0)) {
1760
+ return false;
1761
+ }
1762
+ return true;
1763
+ });
1764
+ if (candidates.length === 0) return proposed;
1765
+ let cur = proposed;
1766
+ for (let iter = 0; iter < maxIterations; iter++) {
1767
+ let bestOverlap = Number.POSITIVE_INFINITY;
1768
+ let bestPushX = 0;
1769
+ let bestPushY = 0;
1770
+ let hit = false;
1771
+ const aLeft = cur.x - gap;
1772
+ const aRight = cur.x + w + gap;
1773
+ const aTop = cur.y - gap;
1774
+ const aBottom = cur.y + h + gap;
1775
+ for (const o of candidates) {
1776
+ const ow = o.width ?? DEFAULT_NODE_WIDTH;
1777
+ const oh = effectiveHeight(o);
1778
+ const bLeft = o.position.x;
1779
+ const bRight = o.position.x + ow;
1780
+ const bTop = o.position.y;
1781
+ const bBottom = o.position.y + oh;
1782
+ const overlapX = Math.min(aRight, bRight) - Math.max(aLeft, bLeft);
1783
+ const overlapY = Math.min(aBottom, bBottom) - Math.max(aTop, bTop);
1784
+ if (overlapX <= 0 || overlapY <= 0) continue;
1785
+ let pushX = 0;
1786
+ let pushY = 0;
1787
+ let overlap;
1788
+ if (overlapX < overlapY) {
1789
+ const aCx = cur.x + w / 2;
1790
+ const bCx = o.position.x + ow / 2;
1791
+ pushX = aCx < bCx ? -overlapX : overlapX;
1792
+ overlap = overlapX;
1793
+ } else {
1794
+ const aCy = cur.y + h / 2;
1795
+ const bCy = o.position.y + oh / 2;
1796
+ pushY = aCy < bCy ? -overlapY : overlapY;
1797
+ overlap = overlapY;
1798
+ }
1799
+ if (overlap < bestOverlap) {
1800
+ bestOverlap = overlap;
1801
+ bestPushX = pushX;
1802
+ bestPushY = pushY;
1803
+ hit = true;
1804
+ }
1805
+ }
1806
+ if (!hit) break;
1807
+ cur = { x: cur.x + bestPushX, y: cur.y + bestPushY };
1808
+ }
1809
+ return cur;
1810
+ }
1811
+
1812
+ // src/workflow/components/FlowCanvas/FlowCanvas.tsx
1813
+ import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
1814
+ var DEFAULT_VIEWPORT2 = { x: 0, y: 0, zoom: 1 };
1815
+ function FlowCanvas(props) {
1816
+ const viewportPropProvided = props.viewport !== void 0 || props.defaultViewport !== void 0;
1817
+ const {
1818
+ nodes,
1819
+ edges,
1820
+ onNodesChange,
1821
+ onEdgesChange,
1822
+ viewport: controlledViewport,
1823
+ defaultViewport = DEFAULT_VIEWPORT2,
1824
+ onViewportChange,
1825
+ minZoom = 0.25,
1826
+ maxZoom = 2,
1827
+ fitViewOnInit,
1828
+ nodeKinds,
1829
+ onConnect,
1830
+ onConnectStart,
1831
+ onConnectEnd,
1832
+ isValidConnection,
1833
+ onSelectionChange,
1834
+ onPaneClick,
1835
+ onNodeClick,
1836
+ onEdgeClick,
1837
+ onEdgeLabelChange,
1838
+ onInit,
1839
+ onBeforeDelete,
1840
+ onNodeContextMenu,
1841
+ onEdgeContextMenu,
1842
+ onPaneContextMenu,
1843
+ nodesDraggable = true,
1844
+ nodesConnectable = true,
1845
+ panOnDrag: panOnDragProp,
1846
+ zoomOnScroll: zoomOnScrollProp,
1847
+ preset = "mouse",
1848
+ paneClickDistance = 4,
1849
+ paneClickClearsSelection = true,
1850
+ background = "dots",
1851
+ gridSize = 20,
1852
+ snapToGrid = false,
1853
+ nodeCollisionGap = -1,
1854
+ subflowCollisionGap,
1855
+ reparentOnDrag = false,
1856
+ autoResizeContainers = false,
1857
+ containerAutoResizePadding = 32,
1858
+ containerMinWidth = 320,
1859
+ containerMinHeight = 200,
1860
+ height = "100%",
1861
+ width = "100%",
1862
+ className,
1863
+ style,
1864
+ children,
1865
+ emptyState
1866
+ } = props;
1867
+ const presetDefaults = {
1868
+ mouse: { panOnDrag: true, zoomOnScroll: true },
1869
+ trackpad: { panOnDrag: true, zoomOnScroll: true },
1870
+ touch: { panOnDrag: false, zoomOnScroll: true }
1871
+ };
1872
+ const panOnDrag = panOnDragProp ?? presetDefaults[preset].panOnDrag;
1873
+ const zoomOnScroll = zoomOnScrollProp ?? presetDefaults[preset].zoomOnScroll;
1874
+ const store = useState2(
1875
+ () => createFlowStore({
1876
+ initialNodes: nodes,
1877
+ initialEdges: edges,
1878
+ initialViewport: controlledViewport ?? defaultViewport
1879
+ })
1880
+ )[0];
1881
+ const handleRegistry = useState2(() => createHandleRegistry())[0];
1882
+ const [handleVersion, setHandleVersion] = useState2(0);
1883
+ useEffect4(() => {
1884
+ const unsub = handleRegistry.subscribe(() => {
1885
+ setHandleVersion((v) => v + 1);
1886
+ });
1887
+ return unsub;
1888
+ }, [handleRegistry]);
1889
+ const kinds = useMemo3(() => buildNodeKindRegistry(DEFAULT_NODE_KINDS, nodeKinds), [nodeKinds]);
1890
+ const containerRef = useRef5(null);
1891
+ useEffect4(() => store.setNodes(nodes), [store, nodes]);
1892
+ useEffect4(() => store.setEdges(edges), [store, edges]);
1893
+ const [uncontrolledVp, setUncontrolledVp] = useState2(controlledViewport ?? defaultViewport);
1894
+ const viewport = controlledViewport ?? uncontrolledVp;
1895
+ useEffect4(() => store.setViewport(viewport), [store, viewport]);
1896
+ const setViewport = useCallback(
1897
+ (next) => {
1898
+ if (controlledViewport === void 0) setUncontrolledVp(next);
1899
+ onViewportChange?.(next);
1900
+ },
1901
+ [controlledViewport, onViewportChange]
1902
+ );
1903
+ const selectedNodeIds = useMemo3(() => {
1904
+ const s = /* @__PURE__ */ new Set();
1905
+ for (const n of nodes) if (n.selected) s.add(n.id);
1906
+ return s;
1907
+ }, [nodes]);
1908
+ const selectedEdgeIds = useMemo3(() => {
1909
+ const s = /* @__PURE__ */ new Set();
1910
+ for (const e of edges) if (e.selected) s.add(e.id);
1911
+ return s;
1912
+ }, [edges]);
1913
+ useEffect4(() => {
1914
+ store.setSelection(selectedNodeIds, selectedEdgeIds);
1915
+ if (onSelectionChange) {
1916
+ onSelectionChange({
1917
+ nodes: nodes.filter((n) => selectedNodeIds.has(n.id)),
1918
+ edges: edges.filter((e) => selectedEdgeIds.has(e.id))
1919
+ });
1920
+ }
1921
+ }, [store, selectedNodeIds, selectedEdgeIds, nodes, edges, onSelectionChange]);
1922
+ const selectNode = useCallback(
1923
+ (id, additive) => {
1924
+ const next = [];
1925
+ const nextEdges = [];
1926
+ if (!additive) {
1927
+ for (const n of nodes) {
1928
+ if (n.selected && n.id !== id) next.push(change.node.select(n.id, false));
1929
+ }
1930
+ for (const e of edges) {
1931
+ if (e.selected) nextEdges.push(change.edge.select(e.id, false));
1932
+ }
1933
+ }
1934
+ const isSelected = selectedNodeIds.has(id);
1935
+ if (additive && isSelected) {
1936
+ next.push(change.node.select(id, false));
1937
+ } else if (!isSelected) {
1938
+ next.push(change.node.select(id, true));
1939
+ }
1940
+ if (next.length) onNodesChange?.(next);
1941
+ if (nextEdges.length) onEdgesChange?.(nextEdges);
1942
+ },
1943
+ [nodes, edges, selectedNodeIds, onNodesChange, onEdgesChange]
1944
+ );
1945
+ const notifyNodeClick = useCallback(
1946
+ (id) => {
1947
+ const node = nodes.find((n) => n.id === id);
1948
+ if (node) onNodeClick?.(node);
1949
+ },
1950
+ [nodes, onNodeClick]
1951
+ );
1952
+ const selectEdge = useCallback(
1953
+ (id, additive) => {
1954
+ const next = [];
1955
+ const nextNodes = [];
1956
+ if (!additive) {
1957
+ for (const e of edges) {
1958
+ if (e.selected && e.id !== id) next.push(change.edge.select(e.id, false));
1959
+ }
1960
+ for (const n of nodes) {
1961
+ if (n.selected) nextNodes.push(change.node.select(n.id, false));
1962
+ }
1963
+ }
1964
+ const isSelected = selectedEdgeIds.has(id);
1965
+ if (additive && isSelected) {
1966
+ next.push(change.edge.select(id, false));
1967
+ } else if (!isSelected) {
1968
+ next.push(change.edge.select(id, true));
1969
+ }
1970
+ if (next.length) onEdgesChange?.(next);
1971
+ if (nextNodes.length) onNodesChange?.(nextNodes);
1972
+ const edge = edges.find((e) => e.id === id);
1973
+ if (edge) onEdgeClick?.(edge);
1974
+ },
1975
+ [nodes, edges, selectedEdgeIds, onEdgesChange, onNodesChange, onEdgeClick]
1976
+ );
1977
+ const clearSelection = useCallback(() => {
1978
+ const ns = [];
1979
+ const es = [];
1980
+ for (const n of nodes) if (n.selected) ns.push(change.node.select(n.id, false));
1981
+ for (const e of edges) if (e.selected) es.push(change.edge.select(e.id, false));
1982
+ if (ns.length) onNodesChange?.(ns);
1983
+ if (es.length) onEdgesChange?.(es);
1984
+ }, [nodes, edges, onNodesChange, onEdgesChange]);
1985
+ const dragRef = useRef5(null);
1986
+ const [draggingId, setDraggingId] = useState2(null);
1987
+ const beginNodeDrag = useCallback(
1988
+ (nodeId, pointerId, clientX, clientY, altKey = false) => {
1989
+ if (!nodesDraggable) return;
1990
+ const node = nodes.find((n) => n.id === nodeId);
1991
+ if (!node) return;
1992
+ const kids = descendantsOf(nodeId, nodes).map((d) => ({
1993
+ id: d.id,
1994
+ startPosition: d.position
1995
+ }));
1996
+ const evaluateReparent = altKey || reparentOnDragRef.current;
1997
+ const hasParent = !!node.parentId;
1998
+ const skipClamp = altKey || reparentOnDragRef.current && !hasParent;
1999
+ dragRef.current = {
2000
+ pointerId,
2001
+ nodeId,
2002
+ startClientX: clientX,
2003
+ startClientY: clientY,
2004
+ startPosition: node.position,
2005
+ descendants: kids,
2006
+ skipClamp,
2007
+ evaluateReparent,
2008
+ rafScheduled: false,
2009
+ nextDelta: null
2010
+ };
2011
+ setDraggingId(nodeId);
2012
+ selectNode(nodeId, false);
2013
+ },
2014
+ [nodes, nodesDraggable, selectNode]
2015
+ );
2016
+ const [conn, setConn] = useState2(null);
2017
+ const connRef = useRef5(null);
2018
+ useEffect4(() => {
2019
+ connRef.current = conn;
2020
+ }, [conn]);
2021
+ const beginConnection = useCallback(
2022
+ (nodeId, handleId, handleType, pointerId, clientX, clientY) => {
2023
+ if (!nodesConnectable) return;
2024
+ const node = nodes.find((n) => n.id === nodeId);
2025
+ if (!node) return;
2026
+ const desc = handleRegistry.resolve(nodeId, handleType, handleId);
2027
+ const side = desc?.side ?? (handleType === "source" ? "bottom" : "top");
2028
+ const index = desc?.index ?? 0;
2029
+ const total = desc?.total ?? 1;
2030
+ const ratio = (index + 1) / (total + 1);
2031
+ const w = node.width ?? 368;
2032
+ const h = effectiveHeight(node);
2033
+ const start = (() => {
2034
+ switch (side) {
2035
+ case "top":
2036
+ return { x: node.position.x + w * ratio, y: node.position.y };
2037
+ case "bottom":
2038
+ return { x: node.position.x + w * ratio, y: node.position.y + h };
2039
+ case "left":
2040
+ return { x: node.position.x, y: node.position.y + h * ratio };
2041
+ case "right":
2042
+ return { x: node.position.x + w, y: node.position.y + h * ratio };
2043
+ }
2044
+ })();
2045
+ const from = { nodeId, handleId, handleType };
2046
+ const rect = containerRef.current?.getBoundingClientRect();
2047
+ const end = rect ? screenToFlow({ x: clientX - rect.left, y: clientY - rect.top }, viewport) : start;
2048
+ setConn({ pointerId, from, start, end });
2049
+ store.setConnection(from);
2050
+ onConnectStart?.({ clientX, clientY, pointerId }, from);
2051
+ },
2052
+ [nodes, nodesConnectable, handleRegistry, viewport, store, onConnectStart]
2053
+ );
2054
+ const viewportRef = useRef5(viewport);
2055
+ const nodesRef = useRef5(nodes);
2056
+ const edgesRef = useRef5(edges);
2057
+ const onNodesChangeRefForInstance = useRef5(onNodesChange);
2058
+ const onEdgesChangeRefForInstance = useRef5(onEdgesChange);
2059
+ const onBeforeDeleteRef = useRef5(onBeforeDelete);
2060
+ const snapToGridRef = useRef5(snapToGrid);
2061
+ const gridSizeRef = useRef5(gridSize);
2062
+ const nodeCollisionGapRef = useRef5(nodeCollisionGap);
2063
+ const subflowCollisionGapRef = useRef5(subflowCollisionGap ?? nodeCollisionGap);
2064
+ const reparentOnDragRef = useRef5(reparentOnDrag);
2065
+ const autoResizeContainersRef = useRef5(autoResizeContainers);
2066
+ const containerAutoResizePaddingRef = useRef5(containerAutoResizePadding);
2067
+ const containerMinWidthRef = useRef5(containerMinWidth);
2068
+ const containerMinHeightRef = useRef5(containerMinHeight);
2069
+ useEffect4(() => {
2070
+ edgesRef.current = edges;
2071
+ }, [edges]);
2072
+ useEffect4(() => {
2073
+ onNodesChangeRefForInstance.current = onNodesChange;
2074
+ }, [onNodesChange]);
2075
+ useEffect4(() => {
2076
+ onEdgesChangeRefForInstance.current = onEdgesChange;
2077
+ }, [onEdgesChange]);
2078
+ useEffect4(() => {
2079
+ onBeforeDeleteRef.current = onBeforeDelete;
2080
+ }, [onBeforeDelete]);
2081
+ useEffect4(() => {
2082
+ snapToGridRef.current = snapToGrid;
2083
+ }, [snapToGrid]);
2084
+ useEffect4(() => {
2085
+ gridSizeRef.current = gridSize;
2086
+ }, [gridSize]);
2087
+ useEffect4(() => {
2088
+ nodeCollisionGapRef.current = nodeCollisionGap;
2089
+ }, [nodeCollisionGap]);
2090
+ useEffect4(() => {
2091
+ subflowCollisionGapRef.current = subflowCollisionGap ?? nodeCollisionGap;
2092
+ }, [subflowCollisionGap, nodeCollisionGap]);
2093
+ useEffect4(() => {
2094
+ reparentOnDragRef.current = reparentOnDrag;
2095
+ }, [reparentOnDrag]);
2096
+ useEffect4(() => {
2097
+ autoResizeContainersRef.current = autoResizeContainers;
2098
+ }, [autoResizeContainers]);
2099
+ useEffect4(() => {
2100
+ containerAutoResizePaddingRef.current = containerAutoResizePadding;
2101
+ }, [containerAutoResizePadding]);
2102
+ useEffect4(() => {
2103
+ containerMinWidthRef.current = containerMinWidth;
2104
+ }, [containerMinWidth]);
2105
+ useEffect4(() => {
2106
+ containerMinHeightRef.current = containerMinHeight;
2107
+ }, [containerMinHeight]);
2108
+ const onNodesChangeRef = useRef5(onNodesChange);
2109
+ const onConnectRef = useRef5(onConnect);
2110
+ const onConnectEndRef = useRef5(onConnectEnd);
2111
+ const isValidConnectionRef = useRef5(isValidConnection);
2112
+ useEffect4(() => {
2113
+ viewportRef.current = viewport;
2114
+ }, [viewport]);
2115
+ useEffect4(() => {
2116
+ nodesRef.current = nodes;
2117
+ }, [nodes]);
2118
+ useEffect4(() => {
2119
+ onNodesChangeRef.current = onNodesChange;
2120
+ }, [onNodesChange]);
2121
+ useEffect4(() => {
2122
+ onConnectRef.current = onConnect;
2123
+ }, [onConnect]);
2124
+ useEffect4(() => {
2125
+ onConnectEndRef.current = onConnectEnd;
2126
+ }, [onConnectEnd]);
2127
+ useEffect4(() => {
2128
+ isValidConnectionRef.current = isValidConnection;
2129
+ }, [isValidConnection]);
2130
+ useEffect4(() => {
2131
+ const onPointerMove = (e) => {
2132
+ const vp = viewportRef.current;
2133
+ const drag = dragRef.current;
2134
+ if (drag && drag.pointerId === e.pointerId) {
2135
+ const dx = (e.clientX - drag.startClientX) / vp.zoom;
2136
+ const dy = (e.clientY - drag.startClientY) / vp.zoom;
2137
+ drag.nextDelta = { dx, dy };
2138
+ if (!drag.rafScheduled) {
2139
+ drag.rafScheduled = true;
2140
+ requestAnimationFrame(() => {
2141
+ const d = dragRef.current;
2142
+ if (!d) return;
2143
+ d.rafScheduled = false;
2144
+ const delta = d.nextDelta;
2145
+ if (!delta) return;
2146
+ const dragNode = nodesRef.current.find((n) => n.id === d.nodeId);
2147
+ if (!dragNode) return;
2148
+ const proposed = {
2149
+ x: d.startPosition.x + delta.dx,
2150
+ y: d.startPosition.y + delta.dy
2151
+ };
2152
+ const clamped = d.skipClamp ? proposed : clampToParentExtent(dragNode, proposed, nodesRef.current);
2153
+ const isContainer = dragNode.type === "group" || dragNode.type === "forEach";
2154
+ const gap = isContainer ? subflowCollisionGapRef.current : nodeCollisionGapRef.current;
2155
+ const excludeIds = /* @__PURE__ */ new Set([d.nodeId, ...d.descendants.map((kid) => kid.id)]);
2156
+ const finalPos = resolveNodeCollisions(dragNode, clamped, nodesRef.current, {
2157
+ gap,
2158
+ exclude: excludeIds
2159
+ });
2160
+ const realDx = finalPos.x - d.startPosition.x;
2161
+ const realDy = finalPos.y - d.startPosition.y;
2162
+ const changes = [change.node.position(d.nodeId, finalPos, true)];
2163
+ for (const kid of d.descendants) {
2164
+ changes.push(
2165
+ change.node.position(
2166
+ kid.id,
2167
+ { x: kid.startPosition.x + realDx, y: kid.startPosition.y + realDy },
2168
+ true
2169
+ )
2170
+ );
2171
+ }
2172
+ onNodesChangeRef.current?.(changes);
2173
+ });
2174
+ }
2175
+ }
2176
+ const c = connRef.current;
2177
+ if (c && c.pointerId === e.pointerId) {
2178
+ const rect = containerRef.current?.getBoundingClientRect();
2179
+ if (rect) {
2180
+ const end = screenToFlow({ x: e.clientX - rect.left, y: e.clientY - rect.top }, vp);
2181
+ setConn({ ...c, end });
2182
+ }
2183
+ }
2184
+ };
2185
+ const onPointerUp = (e) => {
2186
+ const vp = viewportRef.current;
2187
+ const drag = dragRef.current;
2188
+ if (drag && drag.pointerId === e.pointerId) {
2189
+ const dx = (e.clientX - drag.startClientX) / vp.zoom;
2190
+ const dy = (e.clientY - drag.startClientY) / vp.zoom;
2191
+ const dragNode = nodesRef.current.find((n) => n.id === drag.nodeId);
2192
+ if (dragNode) {
2193
+ let proposed = {
2194
+ x: drag.startPosition.x + dx,
2195
+ y: drag.startPosition.y + dy
2196
+ };
2197
+ if (snapToGridRef.current) {
2198
+ const g = gridSizeRef.current;
2199
+ proposed = {
2200
+ x: Math.round(proposed.x / g) * g,
2201
+ y: Math.round(proposed.y / g) * g
2202
+ };
2203
+ }
2204
+ const clamped = drag.skipClamp ? proposed : clampToParentExtent(dragNode, proposed, nodesRef.current);
2205
+ const isContainer = dragNode.type === "group" || dragNode.type === "forEach";
2206
+ const gap = isContainer ? subflowCollisionGapRef.current : nodeCollisionGapRef.current;
2207
+ const excludeIds = /* @__PURE__ */ new Set([
2208
+ drag.nodeId,
2209
+ ...drag.descendants.map((kid) => kid.id)
2210
+ ]);
2211
+ const finalPos = resolveNodeCollisions(dragNode, clamped, nodesRef.current, {
2212
+ gap,
2213
+ exclude: excludeIds
2214
+ });
2215
+ const realDx = finalPos.x - drag.startPosition.x;
2216
+ const realDy = finalPos.y - drag.startPosition.y;
2217
+ const changes = [change.node.position(drag.nodeId, finalPos, false)];
2218
+ for (const kid of drag.descendants) {
2219
+ changes.push(
2220
+ change.node.position(
2221
+ kid.id,
2222
+ { x: kid.startPosition.x + realDx, y: kid.startPosition.y + realDy },
2223
+ false
2224
+ )
2225
+ );
2226
+ }
2227
+ if (drag.evaluateReparent) {
2228
+ const targetGroup = findContainingGroup(
2229
+ {
2230
+ x: finalPos.x + (dragNode.width ?? 0) / 2,
2231
+ y: finalPos.y + (dragNode.height ?? 0) / 2
2232
+ },
2233
+ nodesRef.current,
2234
+ [drag.nodeId, ...drag.descendants.map((d) => d.id)]
2235
+ );
2236
+ const nextParentId = targetGroup?.id;
2237
+ if (nextParentId !== dragNode.parentId) {
2238
+ const updated = {
2239
+ ...dragNode,
2240
+ position: finalPos,
2241
+ parentId: nextParentId,
2242
+ // Adopting into a container always pins the child with
2243
+ // `extent: 'parent'` so it's clamped from the next drag
2244
+ // on. Detaching clears it.
2245
+ extent: nextParentId ? "parent" : void 0
2246
+ };
2247
+ changes.push(change.node.replace(drag.nodeId, updated));
2248
+ }
2249
+ }
2250
+ if (autoResizeContainersRef.current) {
2251
+ const containerChanges = computeContainerAutoResize(
2252
+ nodesRef.current,
2253
+ // Projected children: apply the position + reparent
2254
+ // changes we just built before measuring bboxes.
2255
+ changes,
2256
+ containerAutoResizePaddingRef.current,
2257
+ containerMinWidthRef.current,
2258
+ containerMinHeightRef.current
2259
+ );
2260
+ for (const c2 of containerChanges) changes.push(c2);
2261
+ }
2262
+ onNodesChangeRef.current?.(changes);
2263
+ }
2264
+ dragRef.current = null;
2265
+ setDraggingId(null);
2266
+ }
2267
+ const c = connRef.current;
2268
+ if (c && c.pointerId === e.pointerId) {
2269
+ const rect = containerRef.current?.getBoundingClientRect();
2270
+ const flowPos = rect ? screenToFlow({ x: e.clientX - rect.left, y: e.clientY - rect.top }, vp) : { x: 0, y: 0 };
2271
+ const snapRadius = 26 / Math.max(0.1, vp.zoom);
2272
+ let bestDesc = null;
2273
+ let bestDist = snapRadius;
2274
+ for (const desc of handleRegistry.all()) {
2275
+ if (desc.nodeId === c.from.nodeId) continue;
2276
+ if (desc.type === c.from.handleType) continue;
2277
+ if (!desc.canEnd) continue;
2278
+ const targetNode = nodesRef.current.find((n) => n.id === desc.nodeId);
2279
+ if (!targetNode || targetNode.hidden) continue;
2280
+ const centre = handleCentre(targetNode, desc.side, desc.index, desc.total);
2281
+ const dist = Math.hypot(centre.x - flowPos.x, centre.y - flowPos.y);
2282
+ if (dist < bestDist) {
2283
+ bestDist = dist;
2284
+ bestDesc = desc;
2285
+ }
2286
+ }
2287
+ let connection = null;
2288
+ let connectedTo;
2289
+ if (bestDesc) {
2290
+ const source = c.from.handleType === "source" ? c.from : {
2291
+ nodeId: bestDesc.nodeId,
2292
+ handleId: bestDesc.handleId,
2293
+ handleType: "source"
2294
+ };
2295
+ const target2 = c.from.handleType === "target" ? c.from : {
2296
+ nodeId: bestDesc.nodeId,
2297
+ handleId: bestDesc.handleId,
2298
+ handleType: "target"
2299
+ };
2300
+ connection = {
2301
+ source: source.nodeId,
2302
+ sourceHandle: source.handleId,
2303
+ target: target2.nodeId,
2304
+ targetHandle: target2.handleId
2305
+ };
2306
+ connectedTo = {
2307
+ nodeId: bestDesc.nodeId,
2308
+ handleId: bestDesc.handleId,
2309
+ handleType: bestDesc.type
2310
+ };
2311
+ const validator = isValidConnectionRef.current;
2312
+ if (validator && !validator(connection)) {
2313
+ connection = null;
2314
+ connectedTo = void 0;
2315
+ }
2316
+ }
2317
+ const endState = {
2318
+ cancelled: !connection,
2319
+ position: { x: e.clientX, y: e.clientY },
2320
+ flowPosition: flowPos,
2321
+ from: c.from,
2322
+ to: connectedTo
2323
+ };
2324
+ if (connection) onConnectRef.current?.(connection);
2325
+ onConnectEndRef.current?.(e, endState);
2326
+ setConn(null);
2327
+ store.setConnection(null);
2328
+ }
2329
+ };
2330
+ const onPointerCancel = () => {
2331
+ if (dragRef.current) {
2332
+ dragRef.current = null;
2333
+ setDraggingId(null);
2334
+ }
2335
+ if (connRef.current) {
2336
+ setConn(null);
2337
+ store.setConnection(null);
2338
+ }
2339
+ };
2340
+ window.addEventListener("pointermove", onPointerMove);
2341
+ window.addEventListener("pointerup", onPointerUp);
2342
+ window.addEventListener("pointercancel", onPointerCancel);
2343
+ return () => {
2344
+ window.removeEventListener("pointermove", onPointerMove);
2345
+ window.removeEventListener("pointerup", onPointerUp);
2346
+ window.removeEventListener("pointercancel", onPointerCancel);
2347
+ };
2348
+ }, [store]);
2349
+ useEffect4(() => {
2350
+ if (!autoResizeContainers || draggingId) return;
2351
+ const resizeChanges = computeContainerAutoResize(
2352
+ nodes,
2353
+ [],
2354
+ containerAutoResizePadding,
2355
+ containerMinWidth,
2356
+ containerMinHeight
2357
+ );
2358
+ if (resizeChanges.length > 0) onNodesChange?.(resizeChanges);
2359
+ }, [
2360
+ nodes,
2361
+ draggingId,
2362
+ autoResizeContainers,
2363
+ containerAutoResizePadding,
2364
+ containerMinWidth,
2365
+ containerMinHeight,
2366
+ onNodesChange
2367
+ ]);
2368
+ const panRef = useRef5(null);
2369
+ const onCanvasPointerDown = (e) => {
2370
+ if (e.button !== 0) return;
2371
+ const t = e.target;
2372
+ if (t.closest("[data-node-id]") || t.closest("[data-edge-id]") || t.closest("[data-handle-id]")) {
2373
+ return;
2374
+ }
2375
+ if (!panOnDrag) {
2376
+ panRef.current = {
2377
+ pointerId: e.pointerId,
2378
+ startClientX: e.clientX,
2379
+ startClientY: e.clientY,
2380
+ startVp: viewport,
2381
+ moved: false
2382
+ };
2383
+ return;
2384
+ }
2385
+ panRef.current = {
2386
+ pointerId: e.pointerId,
2387
+ startClientX: e.clientX,
2388
+ startClientY: e.clientY,
2389
+ startVp: viewport,
2390
+ moved: false
2391
+ };
2392
+ };
2393
+ useEffect4(() => {
2394
+ const onMove = (e) => {
2395
+ const pan = panRef.current;
2396
+ if (!pan || pan.pointerId !== e.pointerId) return;
2397
+ const dx = e.clientX - pan.startClientX;
2398
+ const dy = e.clientY - pan.startClientY;
2399
+ if (Math.abs(dx) > paneClickDistance || Math.abs(dy) > paneClickDistance) {
2400
+ if (!pan.moved) setPanGesture(true);
2401
+ pan.moved = true;
2402
+ }
2403
+ if (pan.moved && panOnDrag) {
2404
+ setViewport({ ...pan.startVp, x: pan.startVp.x + dx, y: pan.startVp.y + dy });
2405
+ }
2406
+ };
2407
+ const onUp = () => {
2408
+ const pan = panRef.current;
2409
+ if (!pan) return;
2410
+ if (!pan.moved) {
2411
+ onPaneClick?.();
2412
+ if (paneClickClearsSelection) clearSelection();
2413
+ }
2414
+ panRef.current = null;
2415
+ setPanGesture(false);
2416
+ };
2417
+ window.addEventListener("pointermove", onMove);
2418
+ window.addEventListener("pointerup", onUp);
2419
+ window.addEventListener("pointercancel", onUp);
2420
+ return () => {
2421
+ window.removeEventListener("pointermove", onMove);
2422
+ window.removeEventListener("pointerup", onUp);
2423
+ window.removeEventListener("pointercancel", onUp);
2424
+ };
2425
+ }, [
2426
+ setViewport,
2427
+ paneClickDistance,
2428
+ panOnDrag,
2429
+ onPaneClick,
2430
+ clearSelection,
2431
+ paneClickClearsSelection
2432
+ ]);
2433
+ const handleWheel = (e) => {
2434
+ if (!zoomOnScroll) return;
2435
+ e.preventDefault();
2436
+ const rect = containerRef.current?.getBoundingClientRect();
2437
+ if (!rect) return;
2438
+ const px = e.clientX - rect.left;
2439
+ const py = e.clientY - rect.top;
2440
+ const factor = Math.exp(-e.deltaY * 1e-3);
2441
+ const nextZoom = Math.max(minZoom, Math.min(maxZoom, viewport.zoom * factor));
2442
+ const k = nextZoom / viewport.zoom;
2443
+ setViewport({
2444
+ zoom: nextZoom,
2445
+ x: px - (px - viewport.x) * k,
2446
+ y: py - (py - viewport.y) * k
2447
+ });
2448
+ };
2449
+ const dispatch = useCallback(
2450
+ (a) => {
2451
+ if (a.type === "connection/start") {
2452
+ beginConnection(a.nodeId, a.handleId, a.handleType, a.pointerId, a.clientX, a.clientY);
2453
+ }
2454
+ },
2455
+ [beginConnection]
2456
+ );
2457
+ const reportDimensions = useCallback(
2458
+ (nodeId, width2, height2) => {
2459
+ const node = nodes.find((n) => n.id === nodeId);
2460
+ if (!node) return;
2461
+ if (node.width === width2 && node.height === height2) return;
2462
+ onNodesChange?.([change.node.dimensions(nodeId, { width: width2, height: height2 })]);
2463
+ },
2464
+ [nodes, onNodesChange]
2465
+ );
2466
+ const toggleNodeCollapseImpl = useCallback(
2467
+ (nodeId) => {
2468
+ const node = nodes.find((n) => n.id === nodeId);
2469
+ if (!node) return;
2470
+ const prevData = node.data ?? {};
2471
+ const nextNode = {
2472
+ ...node,
2473
+ data: { ...prevData, collapsed: !prevData.collapsed }
2474
+ };
2475
+ onNodesChange?.([change.node.replace(nodeId, nextNode)]);
2476
+ },
2477
+ [nodes, onNodesChange]
2478
+ );
2479
+ const deleteNodeImpl = useCallback(
2480
+ (nodeId) => {
2481
+ const incidentEdgeIds = edgesRef.current.filter((e) => e.source === nodeId || e.target === nodeId).map((e) => e.id);
2482
+ if (incidentEdgeIds.length > 0) {
2483
+ onEdgesChange?.(incidentEdgeIds.map((id) => change.edge.remove(id)));
2484
+ }
2485
+ onNodesChange?.([change.node.remove(nodeId)]);
2486
+ },
2487
+ [onNodesChange, onEdgesChange]
2488
+ );
2489
+ const instance = useMemo3(
2490
+ () => ({
2491
+ // viewport
2492
+ getViewport: () => viewportRef.current,
2493
+ setViewport: (vp) => setViewport(vp),
2494
+ setCenter: (x, y, opts) => {
2495
+ const z = opts?.zoom ?? viewportRef.current.zoom;
2496
+ const rect = containerRef.current?.getBoundingClientRect();
2497
+ if (!rect) return;
2498
+ setViewport({
2499
+ zoom: z,
2500
+ x: rect.width / 2 - x * z,
2501
+ y: rect.height / 2 - y * z
2502
+ });
2503
+ },
2504
+ fitView: async (opts) => {
2505
+ const rect = containerRef.current?.getBoundingClientRect();
2506
+ if (!rect) return false;
2507
+ const padding = opts?.padding ?? 80;
2508
+ const targetNodes = opts?.nodes ? nodesRef.current.filter((n) => opts.nodes.some((x) => x.id === n.id)) : nodesRef.current.filter((n) => !n.hidden);
2509
+ if (targetNodes.length === 0) return false;
2510
+ let minX = Number.POSITIVE_INFINITY;
2511
+ let minY = Number.POSITIVE_INFINITY;
2512
+ let maxX = Number.NEGATIVE_INFINITY;
2513
+ let maxY = Number.NEGATIVE_INFINITY;
2514
+ for (const n of targetNodes) {
2515
+ const w = n.width ?? DEFAULT_NODE_WIDTH;
2516
+ const h = effectiveHeight(n);
2517
+ if (n.position.x < minX) minX = n.position.x;
2518
+ if (n.position.y < minY) minY = n.position.y;
2519
+ if (n.position.x + w > maxX) maxX = n.position.x + w;
2520
+ if (n.position.y + h > maxY) maxY = n.position.y + h;
2521
+ }
2522
+ const cw = maxX - minX;
2523
+ const ch = maxY - minY;
2524
+ const zx = (rect.width - padding * 2) / cw;
2525
+ const zy = (rect.height - padding * 2) / ch;
2526
+ const zoom = Math.max(
2527
+ opts?.minZoom ?? 0.25,
2528
+ Math.min(opts?.maxZoom ?? 1.5, Math.min(zx, zy))
2529
+ );
2530
+ setViewport({
2531
+ zoom,
2532
+ x: rect.width / 2 - (minX + maxX) / 2 * zoom,
2533
+ y: rect.height / 2 - (minY + maxY) / 2 * zoom
2534
+ });
2535
+ return true;
2536
+ },
2537
+ zoomIn: (opts) => {
2538
+ const step = opts?.step ?? 0.2;
2539
+ const next = Math.min(maxZoom, viewportRef.current.zoom * (1 + step));
2540
+ setViewport({ ...viewportRef.current, zoom: next });
2541
+ },
2542
+ zoomOut: (opts) => {
2543
+ const step = opts?.step ?? 0.2;
2544
+ const next = Math.max(minZoom, viewportRef.current.zoom / (1 + step));
2545
+ setViewport({ ...viewportRef.current, zoom: next });
2546
+ },
2547
+ zoomTo: (level) => {
2548
+ setViewport({
2549
+ ...viewportRef.current,
2550
+ zoom: Math.max(minZoom, Math.min(maxZoom, level))
2551
+ });
2552
+ },
2553
+ // transforms
2554
+ screenToFlowPosition: (p) => screenToFlow(p, viewportRef.current),
2555
+ flowToScreenPosition: (p) => flowToScreen(p, viewportRef.current),
2556
+ // reads
2557
+ getNodes: () => nodesRef.current.slice(),
2558
+ getEdges: () => edgesRef.current.slice(),
2559
+ getNode: (id) => nodesRef.current.find((n) => n.id === id),
2560
+ getEdge: (id) => edgesRef.current.find((e) => e.id === id),
2561
+ getNodesBounds: (subset) => {
2562
+ const pool = subset ? nodesRef.current.filter((n) => subset.some((x) => x.id === n.id)) : nodesRef.current.filter((n) => !n.hidden);
2563
+ if (pool.length === 0) return { x: 0, y: 0, width: 0, height: 0 };
2564
+ let minX = Number.POSITIVE_INFINITY;
2565
+ let minY = Number.POSITIVE_INFINITY;
2566
+ let maxX = Number.NEGATIVE_INFINITY;
2567
+ let maxY = Number.NEGATIVE_INFINITY;
2568
+ for (const n of pool) {
2569
+ const w = n.width ?? DEFAULT_NODE_WIDTH;
2570
+ const h = effectiveHeight(n);
2571
+ minX = Math.min(minX, n.position.x);
2572
+ minY = Math.min(minY, n.position.y);
2573
+ maxX = Math.max(maxX, n.position.x + w);
2574
+ maxY = Math.max(maxY, n.position.y + h);
2575
+ }
2576
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
2577
+ },
2578
+ getIntersectingNodes: (area, partially = true) => {
2579
+ return nodesRef.current.filter((n) => {
2580
+ if (n.hidden) return false;
2581
+ const w = n.width ?? DEFAULT_NODE_WIDTH;
2582
+ const h = effectiveHeight(n);
2583
+ if (partially) {
2584
+ return n.position.x < area.x + area.width && n.position.x + w > area.x && n.position.y < area.y + area.height && n.position.y + h > area.y;
2585
+ }
2586
+ return n.position.x >= area.x && n.position.y >= area.y && n.position.x + w <= area.x + area.width && n.position.y + h <= area.y + area.height;
2587
+ });
2588
+ },
2589
+ // mutations
2590
+ addNodes: (nodes2) => {
2591
+ const arr = Array.isArray(nodes2) ? nodes2 : [nodes2];
2592
+ onNodesChangeRefForInstance.current?.(arr.map((item) => change.node.add(item)));
2593
+ },
2594
+ addEdges: (edges2) => {
2595
+ const arr = Array.isArray(edges2) ? edges2 : [edges2];
2596
+ onEdgesChangeRefForInstance.current?.(arr.map((item) => change.edge.add(item)));
2597
+ },
2598
+ updateNodeData: (id, partial) => {
2599
+ const cur = nodesRef.current.find((n) => n.id === id);
2600
+ if (!cur) return;
2601
+ const nextData = { ...cur.data ?? {}, ...partial };
2602
+ onNodesChangeRefForInstance.current?.([
2603
+ change.node.replace(id, { ...cur, data: nextData })
2604
+ ]);
2605
+ },
2606
+ updateNode: (id, partial) => {
2607
+ const cur = nodesRef.current.find((n) => n.id === id);
2608
+ if (!cur) return;
2609
+ onNodesChangeRefForInstance.current?.([change.node.replace(id, { ...cur, ...partial })]);
2610
+ },
2611
+ deleteElements: async ({ nodes: ns, edges: es }) => {
2612
+ const nodesToDelete = (ns ?? []).map((x) => nodesRef.current.find((n) => n.id === x.id)).filter((n) => !!n);
2613
+ const edgesToDelete = (es ?? []).map((x) => edgesRef.current.find((e) => e.id === x.id)).filter((e) => !!e);
2614
+ const before = onBeforeDeleteRef.current;
2615
+ if (before) {
2616
+ const ok = await before({ nodes: nodesToDelete, edges: edgesToDelete });
2617
+ if (!ok) return false;
2618
+ }
2619
+ if (nodesToDelete.length > 0) {
2620
+ onNodesChangeRefForInstance.current?.(nodesToDelete.map((n) => change.node.remove(n.id)));
2621
+ }
2622
+ if (edgesToDelete.length > 0) {
2623
+ onEdgesChangeRefForInstance.current?.(edgesToDelete.map((e) => change.edge.remove(e.id)));
2624
+ }
2625
+ return true;
2626
+ }
2627
+ }),
2628
+ [setViewport, minZoom, maxZoom]
2629
+ );
2630
+ const initFiredRef = useRef5(false);
2631
+ useEffect4(() => {
2632
+ if (initFiredRef.current) return;
2633
+ initFiredRef.current = true;
2634
+ onInit?.(instance);
2635
+ }, [instance, onInit]);
2636
+ const fitOnInitFiredRef = useRef5(false);
2637
+ useEffect4(() => {
2638
+ if (fitOnInitFiredRef.current) return;
2639
+ const opt = fitViewOnInit;
2640
+ const shouldFit = opt === false ? false : opt !== void 0 ? true : !viewportPropProvided;
2641
+ if (!shouldFit) return;
2642
+ if (nodes.length === 0) return;
2643
+ const rect = containerRef.current?.getBoundingClientRect();
2644
+ if (!rect || rect.width === 0 || rect.height === 0) return;
2645
+ fitOnInitFiredRef.current = true;
2646
+ const fitOpts = typeof opt === "object" && opt !== null ? opt : void 0;
2647
+ const raf = requestAnimationFrame(() => {
2648
+ void instance.fitView(fitOpts);
2649
+ });
2650
+ return () => cancelAnimationFrame(raf);
2651
+ }, [fitViewOnInit, viewportPropProvided, nodes.length, instance]);
2652
+ useEffect4(() => {
2653
+ const onKey = (e) => {
2654
+ if (e.key !== "Backspace" && e.key !== "Delete") return;
2655
+ const target = e.target;
2656
+ if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT" || target.isContentEditable)) {
2657
+ return;
2658
+ }
2659
+ if (!containerRef.current?.contains(target) && document.activeElement !== document.body) {
2660
+ return;
2661
+ }
2662
+ const sel = store.getSnapshot();
2663
+ if (sel.selectedNodeIds.size === 0 && sel.selectedEdgeIds.size === 0) return;
2664
+ e.preventDefault();
2665
+ void instance.deleteElements({
2666
+ nodes: Array.from(sel.selectedNodeIds, (id) => ({ id })),
2667
+ edges: Array.from(sel.selectedEdgeIds, (id) => ({ id }))
2668
+ });
2669
+ };
2670
+ window.addEventListener("keydown", onKey);
2671
+ return () => window.removeEventListener("keydown", onKey);
2672
+ }, [instance, store]);
2673
+ const bridge = useMemo3(
2674
+ () => ({
2675
+ beginNodeDrag,
2676
+ selectNode,
2677
+ notifyNodeClick,
2678
+ selectEdge,
2679
+ reportDimensions,
2680
+ deleteNode: deleteNodeImpl,
2681
+ toggleNodeCollapse: toggleNodeCollapseImpl
2682
+ }),
2683
+ [
2684
+ beginNodeDrag,
2685
+ selectNode,
2686
+ notifyNodeClick,
2687
+ selectEdge,
2688
+ reportDimensions,
2689
+ deleteNodeImpl,
2690
+ toggleNodeCollapseImpl
2691
+ ]
2692
+ );
2693
+ const [panGesture, setPanGesture] = useState2(false);
2694
+ const isEmpty = nodes.length === 0 && edges.length === 0;
2695
+ const isConnecting = conn !== null;
2696
+ const visibleNodes = useMemo3(() => nodes.filter((n) => !n.hidden), [nodes]);
2697
+ const visibleEdges = useMemo3(() => {
2698
+ if (visibleNodes.length === nodes.length) return edges;
2699
+ const visibleIds = new Set(visibleNodes.map((n) => n.id));
2700
+ return edges.filter((e) => visibleIds.has(e.source) && visibleIds.has(e.target));
2701
+ }, [edges, nodes, visibleNodes]);
2702
+ const orderedNodes = useMemo3(() => {
2703
+ const isContainer = (n) => n.type === "group" || n.type === "forEach";
2704
+ const depth = (n) => {
2705
+ let d = 0;
2706
+ let cursor = n.parentId;
2707
+ const seen = /* @__PURE__ */ new Set();
2708
+ while (cursor) {
2709
+ if (seen.has(cursor)) return Number.POSITIVE_INFINITY;
2710
+ seen.add(cursor);
2711
+ d++;
2712
+ cursor = visibleNodes.find((x) => x.id === cursor)?.parentId;
2713
+ }
2714
+ return d;
2715
+ };
2716
+ const containers = visibleNodes.filter(isContainer);
2717
+ const others = visibleNodes.filter((n) => !isContainer(n));
2718
+ containers.sort((a, b) => depth(a) - depth(b));
2719
+ return [...containers, ...others];
2720
+ }, [visibleNodes]);
2721
+ return /* @__PURE__ */ jsx7(FlowStoreContext.Provider, { value: store, children: /* @__PURE__ */ jsx7(FlowInstanceContext.Provider, { value: instance, children: /* @__PURE__ */ jsx7(HandleRegistryContext.Provider, { value: handleRegistry, children: /* @__PURE__ */ jsx7(FlowDispatchContext.Provider, { value: dispatch, children: /* @__PURE__ */ jsx7(FlowNodeBridgeContext.Provider, { value: bridge, children: /* @__PURE__ */ jsxs5(
2722
+ "div",
2723
+ {
2724
+ ref: containerRef,
2725
+ className: cn(
2726
+ "ods-flow-canvas-v2",
2727
+ panGesture && "ods-flow-canvas-v2--panning",
2728
+ isConnecting && "ods-flow-canvas-v2--connecting",
2729
+ draggingId && "ods-flow-canvas-v2--dragging",
2730
+ className
2731
+ ),
2732
+ style: {
2733
+ position: "relative",
2734
+ width,
2735
+ height,
2736
+ overflow: "hidden",
2737
+ userSelect: "none",
2738
+ touchAction: "none",
2739
+ // Cursor: state-driven so it flips instantly with the
2740
+ // gesture. CSS `:active` would lag behind pointer-capture.
2741
+ cursor: panGesture ? "grabbing" : isConnecting ? "crosshair" : panOnDrag ? "grab" : "default",
2742
+ ...style
2743
+ },
2744
+ onPointerDown: onCanvasPointerDown,
2745
+ onWheel: handleWheel,
2746
+ onContextMenu: (e) => {
2747
+ const t = e.target;
2748
+ const nodeEl = t.closest("[data-node-id]");
2749
+ if (nodeEl && onNodeContextMenu) {
2750
+ const id = nodeEl.dataset.nodeId;
2751
+ const node = nodes.find((n) => n.id === id);
2752
+ if (node) onNodeContextMenu(e, node);
2753
+ return;
2754
+ }
2755
+ const edgeEl = t.closest("[data-edge-id]");
2756
+ if (edgeEl && onEdgeContextMenu) {
2757
+ const id = edgeEl.dataset.edgeId;
2758
+ const edge = edges.find((x) => x.id === id);
2759
+ if (edge) onEdgeContextMenu(e, edge);
2760
+ return;
2761
+ }
2762
+ onPaneContextMenu?.(e);
2763
+ },
2764
+ "data-empty": isEmpty ? "true" : void 0,
2765
+ children: [
2766
+ background !== "none" && /* @__PURE__ */ jsx7(
2767
+ "div",
2768
+ {
2769
+ className: cn(
2770
+ "ods-flow-canvas-v2__grid",
2771
+ `ods-flow-canvas-v2__grid--${background}`
2772
+ ),
2773
+ style: {
2774
+ // Custom property drives the four variants' SCSS.
2775
+ "--ods-flow-grid-size": `${gridSize * viewport.zoom}px`,
2776
+ backgroundPosition: `${viewport.x}px ${viewport.y}px`
2777
+ }
2778
+ }
2779
+ ),
2780
+ /* @__PURE__ */ jsxs5(
2781
+ "div",
2782
+ {
2783
+ className: "ods-flow-canvas-v2__viewport",
2784
+ style: {
2785
+ position: "absolute",
2786
+ inset: 0,
2787
+ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})`,
2788
+ transformOrigin: "0 0"
2789
+ },
2790
+ children: [
2791
+ /* @__PURE__ */ jsx7(
2792
+ EdgesLayer,
2793
+ {
2794
+ edges: visibleEdges,
2795
+ nodes: visibleNodes,
2796
+ onSelect: (id) => bridge.selectEdge(id, false),
2797
+ onDelete: (id) => onEdgesChangeRef(id, onEdgesChange),
2798
+ onLabelChange: onEdgeLabelChange,
2799
+ ghost: conn ? { start: conn.start, end: conn.end } : null,
2800
+ handleVersion
2801
+ }
2802
+ ),
2803
+ orderedNodes.map((node) => {
2804
+ const Kind = kinds[node.type] ?? kinds.action;
2805
+ if (!Kind) return null;
2806
+ return /* @__PURE__ */ jsx7(
2807
+ FlowNode,
2808
+ {
2809
+ node,
2810
+ selected: selectedNodeIds.has(node.id),
2811
+ dragging: draggingId === node.id,
2812
+ isConnecting,
2813
+ Kind
2814
+ },
2815
+ node.id
2816
+ );
2817
+ })
2818
+ ]
2819
+ }
2820
+ ),
2821
+ isEmpty && emptyState && /* @__PURE__ */ jsx7("div", { className: "ods-flow-canvas-v2__empty", children: emptyState }),
2822
+ children
2823
+ ]
2824
+ }
2825
+ ) }) }) }) }) });
2826
+ }
2827
+ function onEdgesChangeRef(id, cb) {
2828
+ cb?.([change.edge.remove(id)]);
2829
+ }
2830
+ var CONTAINER_DROP_HEADROOM_W = 220;
2831
+ var CONTAINER_DROP_HEADROOM_H = 2 * 128;
2832
+ function computeContainerAutoResize(nodes, pending, padding, minWidth, minHeight) {
2833
+ const projected = /* @__PURE__ */ new Map();
2834
+ for (const n of nodes) projected.set(n.id, n);
2835
+ for (const c of pending) {
2836
+ if (c.type === "position" && c.position) {
2837
+ const cur = projected.get(c.id);
2838
+ if (cur) projected.set(c.id, { ...cur, position: c.position });
2839
+ } else if (c.type === "replace" && c.item) {
2840
+ projected.set(c.id, { ...projected.get(c.id), ...c.item });
2841
+ } else if (c.type === "add" && c.item) {
2842
+ projected.set(c.item.id, c.item);
2843
+ }
2844
+ }
2845
+ const HEADER = 56;
2846
+ const out = [];
2847
+ for (const parent of projected.values()) {
2848
+ if (parent.type !== "group" && parent.type !== "forEach") continue;
2849
+ const children = [];
2850
+ for (const n of projected.values()) {
2851
+ if (n.parentId === parent.id) children.push(n);
2852
+ }
2853
+ if (children.length === 0) {
2854
+ const curW2 = parent.width ?? 480;
2855
+ const curH2 = parent.height ?? 240;
2856
+ if (curW2 !== minWidth || curH2 !== minHeight) {
2857
+ out.push(change.node.dimensions(parent.id, { width: minWidth, height: minHeight }));
2858
+ }
2859
+ continue;
2860
+ }
2861
+ let minX = Number.POSITIVE_INFINITY;
2862
+ let minY = Number.POSITIVE_INFINITY;
2863
+ let maxX = Number.NEGATIVE_INFINITY;
2864
+ let maxY = Number.NEGATIVE_INFINITY;
2865
+ for (const c of children) {
2866
+ const cw = c.width ?? 240;
2867
+ const ch = c.height ?? 96;
2868
+ if (c.position.x < minX) minX = c.position.x;
2869
+ if (c.position.y < minY) minY = c.position.y;
2870
+ if (c.position.x + cw > maxX) maxX = c.position.x + cw;
2871
+ if (c.position.y + ch > maxY) maxY = c.position.y + ch;
2872
+ }
2873
+ const targetX = minX - padding;
2874
+ const targetY = minY - padding - HEADER;
2875
+ const curW = parent.width ?? 480;
2876
+ const curH = parent.height ?? 240;
2877
+ const fitW = maxX - minX + padding * 2 + CONTAINER_DROP_HEADROOM_W;
2878
+ const fitH = maxY - minY + padding * 2 + HEADER + CONTAINER_DROP_HEADROOM_H;
2879
+ const nextW = Math.max(minWidth, fitW);
2880
+ const nextH = Math.max(minHeight, fitH);
2881
+ const positionDirty = parent.position.x !== targetX || parent.position.y !== targetY;
2882
+ const sizeDirty = curW !== nextW || curH !== nextH;
2883
+ if (positionDirty) {
2884
+ out.push(change.node.position(parent.id, { x: targetX, y: targetY }, false));
2885
+ }
2886
+ if (sizeDirty) {
2887
+ out.push(change.node.dimensions(parent.id, { width: nextW, height: nextH }));
2888
+ }
2889
+ }
2890
+ return out;
2891
+ }
2892
+ var EdgesLayer = memo2(function EdgesLayer2({
2893
+ edges,
2894
+ nodes,
2895
+ onSelect,
2896
+ onDelete,
2897
+ onLabelChange,
2898
+ ghost,
2899
+ handleVersion: _handleVersion
2900
+ }) {
2901
+ return /* @__PURE__ */ jsxs5(
2902
+ "svg",
2903
+ {
2904
+ className: "ods-flow-canvas-v2__edges",
2905
+ style: { position: "absolute", inset: 0, overflow: "visible", pointerEvents: "none" },
2906
+ width: "100%",
2907
+ height: "100%",
2908
+ children: [
2909
+ /* @__PURE__ */ jsx7("g", { style: { pointerEvents: "auto" }, children: edges.map((edge) => /* @__PURE__ */ jsx7(
2910
+ FlowEdge,
2911
+ {
2912
+ edge,
2913
+ nodes,
2914
+ onSelect,
2915
+ onDelete,
2916
+ onLabelChange,
2917
+ handleVersion: _handleVersion
2918
+ },
2919
+ edge.id
2920
+ )) }),
2921
+ ghost && /* @__PURE__ */ jsx7(
2922
+ "path",
2923
+ {
2924
+ d: `M ${ghost.start.x} ${ghost.start.y} L ${ghost.end.x} ${ghost.end.y}`,
2925
+ stroke: "var(--ods-accent, #4f46e5)",
2926
+ strokeWidth: 1.5,
2927
+ strokeDasharray: "4 4",
2928
+ fill: "none"
2929
+ }
2930
+ )
2931
+ ]
2932
+ }
2933
+ );
2934
+ });
2935
+
2936
+ export {
2937
+ buildEdgePath,
2938
+ bezierPath,
2939
+ stepPath,
2940
+ smoothStepPath,
2941
+ straightPath,
2942
+ FlowInstanceContext,
2943
+ useFlow,
2944
+ FlowStoreContext,
2945
+ useFlowSelector,
2946
+ useNodes,
2947
+ useEdges,
2948
+ useViewport,
2949
+ useViewportOrNull,
2950
+ useNodeById,
2951
+ useNodeData,
2952
+ useEdgeById,
2953
+ useIsNodeSelected,
2954
+ useIsEdgeSelected,
2955
+ useConnection,
2956
+ useSelection,
2957
+ applyNodeChanges,
2958
+ applyEdgeChanges,
2959
+ change,
2960
+ DEFAULT_NODE_WIDTH,
2961
+ DEFAULT_NODE_HEIGHT,
2962
+ handleCentre,
2963
+ bezierPath2,
2964
+ screenToFlow,
2965
+ flowToScreen,
2966
+ descendantsOf,
2967
+ findAncestor,
2968
+ clampToParentExtent,
2969
+ findContainingGroup,
2970
+ FlowEdge,
2971
+ useFlowNodeContext,
2972
+ FlowNode,
2973
+ buildNodeKindRegistry,
2974
+ Handle,
2975
+ NodeResizer,
2976
+ ActionNode,
2977
+ TriggerNode,
2978
+ ConditionNode,
2979
+ GroupNode,
2980
+ ForEachNode,
2981
+ OutputNode,
2982
+ ErrorNode,
2983
+ WaitNode,
2984
+ ParallelNode,
2985
+ StickyNode,
2986
+ WebhookNode,
2987
+ HttpRequestNode,
2988
+ DEFAULT_NODE_KINDS,
2989
+ FlowCanvas
2990
+ };
2991
+ //# sourceMappingURL=chunk-6QCJK7H7.js.map