pynode-flow 0.2.0__py3-none-any.whl

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 (227) hide show
  1. pynode/__init__.py +37 -0
  2. pynode/__main__.py +9 -0
  3. pynode/_perf.py +65 -0
  4. pynode/_version.py +24 -0
  5. pynode/api/__init__.py +15 -0
  6. pynode/api/helpers.py +79 -0
  7. pynode/api/nodes.py +423 -0
  8. pynode/api/services.py +124 -0
  9. pynode/api/sse.py +58 -0
  10. pynode/api/uploads.py +59 -0
  11. pynode/api/workflows.py +466 -0
  12. pynode/config.py +93 -0
  13. pynode/install_nodes.py +143 -0
  14. pynode/main.py +118 -0
  15. pynode/node_registry.py +156 -0
  16. pynode/nodes/AutoSyncNode/auto_sync_node.py +151 -0
  17. pynode/nodes/BBoxMetricsNode/__init__.py +3 -0
  18. pynode/nodes/BBoxMetricsNode/bbox_metrics_node.py +250 -0
  19. pynode/nodes/BBoxMetricsNode/requirements.txt +1 -0
  20. pynode/nodes/BatchNode/__init__.py +3 -0
  21. pynode/nodes/BatchNode/batch_node.py +86 -0
  22. pynode/nodes/BatchNode/requirements.txt +1 -0
  23. pynode/nodes/CameraNode/__init__.py +4 -0
  24. pynode/nodes/CameraNode/camera_node.py +204 -0
  25. pynode/nodes/CameraNode/requirements.txt +2 -0
  26. pynode/nodes/ChangeNode/__init__.py +1 -0
  27. pynode/nodes/ChangeNode/change_node.py +255 -0
  28. pynode/nodes/ChangeNode/requirements.txt +1 -0
  29. pynode/nodes/ConfidenceFilterNode/__init__.py +4 -0
  30. pynode/nodes/ConfidenceFilterNode/confidence_filter_node.py +208 -0
  31. pynode/nodes/ConfidenceFilterNode/requirements.txt +1 -0
  32. pynode/nodes/CounterNode/__init__.py +3 -0
  33. pynode/nodes/CounterNode/counter_node.py +191 -0
  34. pynode/nodes/CropNode/__init__.py +4 -0
  35. pynode/nodes/CropNode/crop_node.py +317 -0
  36. pynode/nodes/CropNode/requirements.txt +2 -0
  37. pynode/nodes/DebugNode/__init__.py +4 -0
  38. pynode/nodes/DebugNode/debug_node.py +169 -0
  39. pynode/nodes/DebugNode/requirements.txt +1 -0
  40. pynode/nodes/DelayNode/delay_node.py +218 -0
  41. pynode/nodes/DelayNode/requirements.txt +1 -0
  42. pynode/nodes/DrawPredictionsNode/__init__.py +3 -0
  43. pynode/nodes/DrawPredictionsNode/draw_predictions_node.py +365 -0
  44. pynode/nodes/DrawPredictionsNode/requirements.txt +2 -0
  45. pynode/nodes/ErrorNode/error_node.py +94 -0
  46. pynode/nodes/ErrorNode/requirements.txt +1 -0
  47. pynode/nodes/FilterNode/__init__.py +3 -0
  48. pynode/nodes/FilterNode/filter_node.py +102 -0
  49. pynode/nodes/FilterNode/requirements.txt +1 -0
  50. pynode/nodes/FrameSourceNode/__init__.py +4 -0
  51. pynode/nodes/FrameSourceNode/frame_source_node.py +319 -0
  52. pynode/nodes/FrameSourceNode/requirements.txt +1 -0
  53. pynode/nodes/FunctionNode/__init__.py +3 -0
  54. pynode/nodes/FunctionNode/function_node.py +168 -0
  55. pynode/nodes/FunctionNode/requirements.txt +1 -0
  56. pynode/nodes/GateNode/gate_node.py +60 -0
  57. pynode/nodes/GateNode/requirements.txt +1 -0
  58. pynode/nodes/GetiUploadNode/__init__.py +3 -0
  59. pynode/nodes/GetiUploadNode/geti_upload_node.py +278 -0
  60. pynode/nodes/GetiUploadNode/requirements.txt +1 -0
  61. pynode/nodes/ImageFormatNode/__init__.py +4 -0
  62. pynode/nodes/ImageFormatNode/image_format_node.py +310 -0
  63. pynode/nodes/ImageFormatNode/requirements.txt +2 -0
  64. pynode/nodes/ImageUploadNode/image_upload_node.py +96 -0
  65. pynode/nodes/ImageViewerNode/__init__.py +4 -0
  66. pynode/nodes/ImageViewerNode/image_viewer_node.py +162 -0
  67. pynode/nodes/ImageViewerNode/requirements.txt +2 -0
  68. pynode/nodes/ImageWriterNode/__init__.py +3 -0
  69. pynode/nodes/ImageWriterNode/imagewriter_node.py +352 -0
  70. pynode/nodes/ImageWriterNode/requirements.txt +1 -0
  71. pynode/nodes/InferenceNode/InferenceEngine/__init__.py +15 -0
  72. pynode/nodes/InferenceNode/InferenceEngine/device_detection.py +149 -0
  73. pynode/nodes/InferenceNode/InferenceEngine/engines/base_engine.py +155 -0
  74. pynode/nodes/InferenceNode/InferenceEngine/engines/example_engine_template.py +272 -0
  75. pynode/nodes/InferenceNode/InferenceEngine/engines/geti_engine.py +309 -0
  76. pynode/nodes/InferenceNode/InferenceEngine/engines/onnx_engine.py +346 -0
  77. pynode/nodes/InferenceNode/InferenceEngine/engines/pass_engine.py +86 -0
  78. pynode/nodes/InferenceNode/InferenceEngine/engines/ultralytics_engine.py +863 -0
  79. pynode/nodes/InferenceNode/InferenceEngine/inference_engine_factory.py +533 -0
  80. pynode/nodes/InferenceNode/InferenceEngine/readme.md +107 -0
  81. pynode/nodes/InferenceNode/InferenceEngine/result_converters.py +121 -0
  82. pynode/nodes/InferenceNode/inference_node.py +451 -0
  83. pynode/nodes/InferenceNode/requirements.txt +13 -0
  84. pynode/nodes/InjectNode/inject_node.py +245 -0
  85. pynode/nodes/InjectNode/requirements.txt +1 -0
  86. pynode/nodes/JoinNode/__init__.py +3 -0
  87. pynode/nodes/JoinNode/join_node.py +156 -0
  88. pynode/nodes/JoinNode/requirements.txt +1 -0
  89. pynode/nodes/LabelFilterNode/__init__.py +3 -0
  90. pynode/nodes/LabelFilterNode/label_filter_node.py +188 -0
  91. pynode/nodes/LabelFilterNode/requirements.txt +1 -0
  92. pynode/nodes/MQTTNode/__init__.py +8 -0
  93. pynode/nodes/MQTTNode/mqtt_in_node.py +148 -0
  94. pynode/nodes/MQTTNode/mqtt_out_node.py +157 -0
  95. pynode/nodes/MQTTNode/mqtt_service.py +367 -0
  96. pynode/nodes/MQTTNode/requirements.txt +1 -0
  97. pynode/nodes/MessageWriterNode/__init__.py +7 -0
  98. pynode/nodes/MessageWriterNode/messagereader_node.py +568 -0
  99. pynode/nodes/MessageWriterNode/messagewriter_node.py +505 -0
  100. pynode/nodes/OmronCameraNode/__init__.py +3 -0
  101. pynode/nodes/OmronCameraNode/omron_camera_node.py +652 -0
  102. pynode/nodes/OmronCameraNode/requirements.txt +4 -0
  103. pynode/nodes/OpenCV/__init__.py +1 -0
  104. pynode/nodes/OpenCV/arithmetic_node.py +376 -0
  105. pynode/nodes/OpenCV/bitwise_node.py +127 -0
  106. pynode/nodes/OpenCV/blend_node.py +127 -0
  107. pynode/nodes/OpenCV/blob_detector_node.py +233 -0
  108. pynode/nodes/OpenCV/blur_node.py +141 -0
  109. pynode/nodes/OpenCV/color_space_node.py +139 -0
  110. pynode/nodes/OpenCV/colormap_node.py +262 -0
  111. pynode/nodes/OpenCV/contours_node.py +258 -0
  112. pynode/nodes/OpenCV/denormalize_coords_node.py +365 -0
  113. pynode/nodes/OpenCV/draw_node.py +312 -0
  114. pynode/nodes/OpenCV/edge_detector_node.py +177 -0
  115. pynode/nodes/OpenCV/equirectangular_node.py +447 -0
  116. pynode/nodes/OpenCV/fft_node.py +102 -0
  117. pynode/nodes/OpenCV/focus_estimation_node.py +189 -0
  118. pynode/nodes/OpenCV/frequency_filter_node.py +241 -0
  119. pynode/nodes/OpenCV/histogram_node.py +160 -0
  120. pynode/nodes/OpenCV/hough_circles_node.py +224 -0
  121. pynode/nodes/OpenCV/hough_lines_node.py +243 -0
  122. pynode/nodes/OpenCV/in_range_node.py +186 -0
  123. pynode/nodes/OpenCV/morphology_node.py +136 -0
  124. pynode/nodes/OpenCV/normalize_coords_node.py +344 -0
  125. pynode/nodes/OpenCV/paste_node.py +244 -0
  126. pynode/nodes/OpenCV/perspective_node.py +174 -0
  127. pynode/nodes/OpenCV/realsense_depth_node.py +253 -0
  128. pynode/nodes/OpenCV/requirements.txt +2 -0
  129. pynode/nodes/OpenCV/resize_node.py +175 -0
  130. pynode/nodes/OpenCV/rotate_node.py +159 -0
  131. pynode/nodes/OpenCV/template_match_node.py +227 -0
  132. pynode/nodes/OpenCV/threshold_node.py +167 -0
  133. pynode/nodes/PointInShapeNode/__init__.py +3 -0
  134. pynode/nodes/PointInShapeNode/point_in_shape_node.py +313 -0
  135. pynode/nodes/PointInShapeNode/requirements.txt +2 -0
  136. pynode/nodes/PolygonMetricsNode/__init__.py +3 -0
  137. pynode/nodes/PolygonMetricsNode/polygon_metrics_node.py +331 -0
  138. pynode/nodes/PolygonMetricsNode/requirements.txt +2 -0
  139. pynode/nodes/QueueLengthProbeNode/__init__.py +3 -0
  140. pynode/nodes/QueueLengthProbeNode/queue_length_probe_node.py +116 -0
  141. pynode/nodes/Qwen3VLMNode/__init__.py +3 -0
  142. pynode/nodes/Qwen3VLMNode/qwen3_vlm_node.py +519 -0
  143. pynode/nodes/Qwen3VLMNode/requirements.txt +5 -0
  144. pynode/nodes/RESTEndpointNode/__init__.py +3 -0
  145. pynode/nodes/RESTEndpointNode/rest_endpoint_node.py +491 -0
  146. pynode/nodes/RangeNode/__init__.py +3 -0
  147. pynode/nodes/RangeNode/range_node.py +115 -0
  148. pynode/nodes/RangeNode/requirements.txt +1 -0
  149. pynode/nodes/RateProbeNode/__init__.py +3 -0
  150. pynode/nodes/RateProbeNode/rate_probe_node.py +183 -0
  151. pynode/nodes/RateProbeNode/requirements.txt +1 -0
  152. pynode/nodes/RoboflowUploadNode/__init__.py +3 -0
  153. pynode/nodes/RoboflowUploadNode/requirements.txt +1 -0
  154. pynode/nodes/RoboflowUploadNode/roboflow_upload_node.py +229 -0
  155. pynode/nodes/SliceNode/README.md +149 -0
  156. pynode/nodes/SliceNode/__init__.py +5 -0
  157. pynode/nodes/SliceNode/merge_predictions_node.py +444 -0
  158. pynode/nodes/SliceNode/requirements.txt +3 -0
  159. pynode/nodes/SliceNode/slice_collector_node.py +370 -0
  160. pynode/nodes/SliceNode/slice_image_node.py +380 -0
  161. pynode/nodes/SplitNode/__init__.py +3 -0
  162. pynode/nodes/SplitNode/requirements.txt +1 -0
  163. pynode/nodes/SplitNode/split_node.py +155 -0
  164. pynode/nodes/SwitchNode/requirements.txt +1 -0
  165. pynode/nodes/SwitchNode/switch_node.py +259 -0
  166. pynode/nodes/SyncNode/__init__.py +3 -0
  167. pynode/nodes/SyncNode/sync_node.py +287 -0
  168. pynode/nodes/TemplateNode/requirements.txt +1 -0
  169. pynode/nodes/TemplateNode/template_node.py +86 -0
  170. pynode/nodes/TrackerNode/__init__.py +2 -0
  171. pynode/nodes/TrackerNode/supervision_tracker_node.py +248 -0
  172. pynode/nodes/TrackerNode/tracker_node.py +745 -0
  173. pynode/nodes/UltralyticsNode/__init__.py +4 -0
  174. pynode/nodes/UltralyticsNode/requirements.txt +2 -0
  175. pynode/nodes/UltralyticsNode/ultralytics_node.py +364 -0
  176. pynode/nodes/UnknownNode/__init__.py +93 -0
  177. pynode/nodes/VLLMNode/__init__.py +3 -0
  178. pynode/nodes/VLLMNode/vllm_node.py +345 -0
  179. pynode/nodes/VideoReaderNode/__init__.py +3 -0
  180. pynode/nodes/VideoReaderNode/video_reader_node.py +425 -0
  181. pynode/nodes/VideoWriterNode/__init__.py +3 -0
  182. pynode/nodes/VideoWriterNode/video_writer_node.py +441 -0
  183. pynode/nodes/WebhookNode/__init__.py +3 -0
  184. pynode/nodes/WebhookNode/webhook_node.py +591 -0
  185. pynode/nodes/__init__.py +109 -0
  186. pynode/nodes/base_node.py +562 -0
  187. pynode/nodes/image_utils.py +291 -0
  188. pynode/nodes/info.py +109 -0
  189. pynode/nodes/mDNSNode/__init__.py +13 -0
  190. pynode/nodes/mDNSNode/mdns_broadcast_node.py +214 -0
  191. pynode/nodes/mDNSNode/mdns_discovery_node.py +362 -0
  192. pynode/nodes/mDNSNode/mdns_manager.py +399 -0
  193. pynode/nodes/mDNSNode/requirements.txt +1 -0
  194. pynode/nodes/messages.py +81 -0
  195. pynode/server.py +187 -0
  196. pynode/static/images/favicon4.png +0 -0
  197. pynode/static/index.html +200 -0
  198. pynode/static/js/README.md +139 -0
  199. pynode/static/js/auth.js +89 -0
  200. pynode/static/js/clipboard.js +152 -0
  201. pynode/static/js/config.js +14 -0
  202. pynode/static/js/connections.js +844 -0
  203. pynode/static/js/debug.js +524 -0
  204. pynode/static/js/events.js +775 -0
  205. pynode/static/js/history.js +199 -0
  206. pynode/static/js/main.js +55 -0
  207. pynode/static/js/minimap.js +242 -0
  208. pynode/static/js/nodes.js +995 -0
  209. pynode/static/js/palette.js +255 -0
  210. pynode/static/js/properties.js +1270 -0
  211. pynode/static/js/selection.js +241 -0
  212. pynode/static/js/state.js +211 -0
  213. pynode/static/js/ui-utils.js +28 -0
  214. pynode/static/js/viewport.js +204 -0
  215. pynode/static/js/workflow.js +469 -0
  216. pynode/static/js/workflows.js +344 -0
  217. pynode/static/style.css +2751 -0
  218. pynode/workflow_engine.py +483 -0
  219. pynode/workflow_manager.py +440 -0
  220. pynode_flow-0.2.0.dist-info/METADATA +520 -0
  221. pynode_flow-0.2.0.dist-info/RECORD +227 -0
  222. pynode_flow-0.2.0.dist-info/WHEEL +5 -0
  223. pynode_flow-0.2.0.dist-info/entry_points.txt +3 -0
  224. pynode_flow-0.2.0.dist-info/licenses/LICENSE +21 -0
  225. pynode_flow-0.2.0.dist-info/scm_file_list.json +270 -0
  226. pynode_flow-0.2.0.dist-info/scm_version.json +8 -0
  227. pynode_flow-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,844 @@
1
+ // Connection management
2
+ import { state, markNodeModified, markConnectionAdded, markConnectionDeleted, setModified, isConnectionSelected } from './state.js';
3
+ import { clientToCanvas } from './viewport.js';
4
+ import { refreshMinimap } from './minimap.js';
5
+ import { categoryLabel } from './ui-utils.js';
6
+
7
+ // Track the currently hovered connection for insertion
8
+ let hoveredConnectionForInsert = null;
9
+
10
+ /**
11
+ * Center of a port element in canvas coordinates (zoom-aware).
12
+ */
13
+ function portCenterCanvas(portEl) {
14
+ const rect = portEl.getBoundingClientRect();
15
+ return clientToCanvas(rect.left + rect.width / 2, rect.top + rect.height / 2);
16
+ }
17
+
18
+ // Check if a node has any connections
19
+ export function nodeHasConnections(nodeId) {
20
+ return state.connections.some(c => c.source === nodeId || c.target === nodeId);
21
+ }
22
+
23
+ // Get the currently hovered connection (for insertion)
24
+ export function getHoveredConnection() {
25
+ return hoveredConnectionForInsert;
26
+ }
27
+
28
+ // Check if a point is near a connection path and return the connection if so
29
+ export function getConnectionAtPoint(x, y, threshold = 15) {
30
+ const paths = document.querySelectorAll('#connections path.connection');
31
+ let closestConnection = null;
32
+ let closestDistance = Infinity;
33
+
34
+ console.log(`Checking connections at (${x.toFixed(1)}, ${y.toFixed(1)}) with threshold ${threshold}px`);
35
+
36
+ for (const path of paths) {
37
+ // Calculate actual distance to the path by sampling points along it
38
+ const pathLength = path.getTotalLength();
39
+ const step = 10; // Sample every 10px for accuracy
40
+ let minDistanceForPath = Infinity;
41
+
42
+ for (let i = 0; i <= pathLength; i += step) {
43
+ const point = path.getPointAtLength(i);
44
+ const dx = point.x - x;
45
+ const dy = point.y - y;
46
+ const distance = Math.sqrt(dx * dx + dy * dy);
47
+
48
+ if (distance < minDistanceForPath) {
49
+ minDistanceForPath = distance;
50
+ }
51
+
52
+ if (distance < closestDistance) {
53
+ closestDistance = distance;
54
+ closestConnection = {
55
+ source: path.getAttribute('data-source'),
56
+ target: path.getAttribute('data-target'),
57
+ sourceOutput: parseInt(path.getAttribute('data-source-output') || '0'),
58
+ targetInput: parseInt(path.getAttribute('data-target-input') || '0'),
59
+ path: path
60
+ };
61
+ }
62
+ }
63
+
64
+ console.log(` Path ${path.getAttribute('data-source')} -> ${path.getAttribute('data-target')}: min distance = ${minDistanceForPath.toFixed(1)}px`);
65
+ }
66
+
67
+ if (closestConnection && closestDistance <= threshold) {
68
+ console.log(` → Selected connection at ${closestDistance.toFixed(1)}px distance`);
69
+ return closestConnection;
70
+ }
71
+
72
+ console.log(` → No connection within threshold`);
73
+ return null;
74
+ }
75
+
76
+ // Highlight a connection with dashed style (for hover-insert indication)
77
+ export function highlightConnectionForInsert(connection) {
78
+ clearConnectionHighlight();
79
+
80
+ if (!connection) return;
81
+
82
+ // Track the hovered connection
83
+ hoveredConnectionForInsert = connection;
84
+
85
+ const paths = document.querySelectorAll('#connections path.connection');
86
+ paths.forEach(path => {
87
+ if (path.getAttribute('data-source') === connection.source &&
88
+ path.getAttribute('data-target') === connection.target &&
89
+ parseInt(path.getAttribute('data-source-output') || '0') === connection.sourceOutput) {
90
+ path.classList.add('hover-insert');
91
+ }
92
+ });
93
+ }
94
+
95
+ // Clear connection highlight
96
+ export function clearConnectionHighlight() {
97
+ hoveredConnectionForInsert = null;
98
+ const paths = document.querySelectorAll('#connections path.connection.hover-insert');
99
+ paths.forEach(path => path.classList.remove('hover-insert'));
100
+ }
101
+
102
+ // Insert a node into an existing connection (split the connection)
103
+ export function insertNodeIntoConnection(nodeId, connection) {
104
+ if (!connection) return false;
105
+
106
+ const nodeData = state.nodes.get(nodeId);
107
+ if (!nodeData) return false;
108
+
109
+ // Check if node has both input and output ports
110
+ const inputCount = nodeData.inputCount !== undefined ? nodeData.inputCount : 1;
111
+ const outputCount = nodeData.outputCount !== undefined ? nodeData.outputCount : 1;
112
+
113
+ if (inputCount === 0 || outputCount === 0) {
114
+ // Can't insert a node without both input and output
115
+ return false;
116
+ }
117
+
118
+ // Save state for undo
119
+ import('./history.js').then(({ saveState }) => {
120
+ saveState('insert node into connection');
121
+ });
122
+
123
+ // Delete the original connection
124
+ deleteConnection(connection.source, connection.target, connection.sourceOutput);
125
+
126
+ // Create connection from original source to the new node (input port 0)
127
+ createConnection(connection.source, nodeId, connection.sourceOutput, 0);
128
+
129
+ // Create connection from the new node to the original target (preserve original target input port)
130
+ createConnection(nodeId, connection.target, 0, connection.targetInput || 0);
131
+
132
+ return true;
133
+ }
134
+
135
+ export function createConnection(sourceId, targetId, sourceOutput = 0, targetInput = 0) {
136
+ const connection = {
137
+ source: sourceId,
138
+ target: targetId,
139
+ sourceOutput: sourceOutput,
140
+ targetInput: targetInput
141
+ };
142
+
143
+ state.connections.push(connection);
144
+ renderConnection(connection);
145
+ markConnectionAdded(connection);
146
+ markNodeModified(sourceId);
147
+ markNodeModified(targetId);
148
+ setModified(true);
149
+ }
150
+
151
+ export function renderConnection(connection) {
152
+ const sourceNode = state.nodes.get(connection.source);
153
+ const targetNode = state.nodes.get(connection.target);
154
+
155
+ if (!sourceNode || !targetNode) return;
156
+
157
+ const sourceEl = document.getElementById(`node-${connection.source}`);
158
+ const targetEl = document.getElementById(`node-${connection.target}`);
159
+
160
+ if (!sourceEl || !targetEl) return;
161
+
162
+ // Get the correct output port based on index
163
+ const outputPorts = sourceEl.querySelectorAll('.port.output');
164
+ const sourcePort = outputPorts[connection.sourceOutput || 0] || sourceEl.querySelector('.port.output');
165
+
166
+ // Get the correct input port based on index
167
+ const inputPorts = targetEl.querySelectorAll('.port.input');
168
+ const targetPort = inputPorts[connection.targetInput || 0] || targetEl.querySelector('.port.input');
169
+
170
+ if (!sourcePort || !targetPort) return;
171
+
172
+ // Port centers in canvas coordinates (zoom-aware)
173
+ const sourceCenter = portCenterCanvas(sourcePort);
174
+ const targetCenter = portCenterCanvas(targetPort);
175
+
176
+ const x1 = sourceCenter.x;
177
+ const y1 = sourceCenter.y;
178
+ const x2 = targetCenter.x;
179
+ const y2 = targetCenter.y;
180
+
181
+ // Arrowhead always ends at the target port
182
+ // For near-vertical connections, adjust control points for a visible curve
183
+ // Arrowhead is always at the target port (x2, y2)
184
+ // Control points are adjusted for a smooth curve, but never move the end point
185
+ const dx = x2 - x1;
186
+
187
+ // Gradual transition: minCurve increases as the connection goes backwards
188
+ // Forward (dx > 0): minCurve = 30
189
+ // Backwards (dx < 0): minCurve grows larger as dx becomes more negative
190
+ let minCurve = 30;
191
+ if (dx < 0) {
192
+ // Gradually increase minCurve based on how far back it goes
193
+ // At dx = -100, minCurve ≈ 55; at dx = -200, minCurve ≈ 80
194
+ minCurve = 30 + Math.abs(dx) * 0.5;
195
+ minCurve = Math.min(minCurve, 100); // Cap at 100
196
+ }
197
+
198
+ const dy = y2 - y1;
199
+ const distance = Math.sqrt(dx * dx + dy * dy);
200
+ // minCurve = Math.min(minCurve, distance / 2 - 10);
201
+
202
+ let control = Math.max(Math.abs(dx) * 0.3, minCurve);
203
+ // let control = 0;
204
+ // Control points: always horizontally offset from source/target
205
+ const cx1 = x1 + control;
206
+ const cx2 = x2 - control;
207
+ const pathData = `M ${x1} ${y1} C ${cx1} ${y1}, ${cx2} ${y2}, ${x2} ${y2}`;
208
+
209
+ // Create visible path (no arrowhead)
210
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
211
+ path.setAttribute('class', 'connection');
212
+ path.setAttribute('d', pathData);
213
+ // No marker-end (arrowhead)
214
+ path.setAttribute('data-source', connection.source);
215
+ path.setAttribute('data-target', connection.target);
216
+ path.setAttribute('data-source-output', connection.sourceOutput || 0);
217
+ path.setAttribute('data-target-input', connection.targetInput || 0);
218
+ path.style.pointerEvents = 'none';
219
+
220
+ // Add disabled class if either node is disabled
221
+ if (sourceNode.enabled === false || targetNode.enabled === false) {
222
+ path.classList.add('disabled');
223
+ }
224
+
225
+ // Check if this connection is selected (single or multi-selection)
226
+ if (isConnectionSelected(connection)) {
227
+ path.classList.add('selected');
228
+ }
229
+
230
+ // Append visible path
231
+ document.getElementById('connections').appendChild(path);
232
+ }
233
+
234
+ export function updateConnections() {
235
+ const connectionsSvg = document.getElementById('connections');
236
+ // Ensure marker is present only once
237
+ let defs = connectionsSvg.querySelector('defs');
238
+ if (!defs) {
239
+ defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
240
+ const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
241
+ // marker.setAttribute('id', 'arrowhead');
242
+ marker.setAttribute('markerWidth', '10');
243
+ marker.setAttribute('markerHeight', '7');
244
+ marker.setAttribute('refX', '10');
245
+ marker.setAttribute('refY', '3.5');
246
+ marker.setAttribute('orient', 'auto');
247
+ marker.setAttribute('markerUnits', 'strokeWidth');
248
+ // const arrowPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
249
+ // arrowPath.setAttribute('d', 'M0,0 L10,3.5 L0,7 Z');
250
+ // arrowPath.setAttribute('fill', '#0e639c');
251
+ // marker.appendChild(arrowPath);
252
+ defs.appendChild(marker);
253
+ connectionsSvg.insertBefore(defs, connectionsSvg.firstChild);
254
+ }
255
+ // Remove only connection paths, not defs/marker
256
+ Array.from(connectionsSvg.querySelectorAll('path.connection, path[stroke="transparent"]')).forEach(el => el.remove());
257
+ state.connections.forEach(conn => renderConnection(conn));
258
+
259
+ // Node moves/deletes and tab switches all funnel through here
260
+ refreshMinimap();
261
+ }
262
+
263
+ export function deleteConnection(sourceId, targetId, sourceOutput = null) {
264
+ // Track deleted connections for incremental deploy
265
+ state.connections.forEach(c => {
266
+ if (c.source === sourceId && c.target === targetId &&
267
+ (sourceOutput === null || c.sourceOutput === sourceOutput)) {
268
+ markConnectionDeleted(c);
269
+ }
270
+ });
271
+
272
+ state.connections = state.connections.filter(
273
+ c => !(c.source === sourceId && c.target === targetId &&
274
+ (sourceOutput === null || c.sourceOutput === sourceOutput))
275
+ );
276
+ updateConnections();
277
+ markNodeModified(sourceId);
278
+ markNodeModified(targetId);
279
+ setModified(true);
280
+ }
281
+
282
+ export function startConnection(sourceId, e, outputIndex = 0) {
283
+ const sourceNode = document.getElementById(`node-${sourceId}`);
284
+ const outputPorts = sourceNode.querySelectorAll('.port.output');
285
+ const port = outputPorts[outputIndex] || sourceNode.querySelector('.port.output');
286
+
287
+ if (!port) return;
288
+
289
+ const portCenter = portCenterCanvas(port);
290
+
291
+ state.drawingConnection = {
292
+ sourceId: sourceId,
293
+ outputIndex: outputIndex,
294
+ startX: portCenter.x,
295
+ startY: portCenter.y
296
+ };
297
+
298
+ document.addEventListener('mousemove', drawTempConnection);
299
+ document.addEventListener('mouseup', cancelConnection);
300
+ }
301
+
302
+ // Start a backward connection (dragging from input port)
303
+ export function startBackwardConnection(targetId, e, inputIndex = 0) {
304
+ const targetNode = document.getElementById(`node-${targetId}`);
305
+ const inputPorts = targetNode.querySelectorAll('.port.input');
306
+ const port = inputPorts[inputIndex] || targetNode.querySelector('.port.input');
307
+
308
+ if (!port) return;
309
+
310
+ const portCenter = portCenterCanvas(port);
311
+
312
+ state.drawingConnection = {
313
+ targetId: targetId,
314
+ inputIndex: inputIndex,
315
+ startX: portCenter.x,
316
+ startY: portCenter.y,
317
+ backward: true // Flag to indicate backward connection
318
+ };
319
+
320
+ document.addEventListener('mousemove', drawTempConnection);
321
+ document.addEventListener('mouseup', cancelConnection);
322
+ }
323
+
324
+ export function drawTempConnection(e) {
325
+ if (!state.drawingConnection) return;
326
+
327
+ const endPoint = clientToCanvas(e.clientX, e.clientY);
328
+ const endX = endPoint.x;
329
+ const endY = endPoint.y;
330
+
331
+ const dx = endX - state.drawingConnection.startX;
332
+ const controlDistance = Math.abs(dx) * 0.5;
333
+
334
+ const tempLine = document.getElementById('temp-line');
335
+
336
+ if (state.drawingConnection.backward) {
337
+ // Backward connection: input port is on the left, so curve goes left first
338
+ tempLine.innerHTML = `
339
+ <path d="M ${state.drawingConnection.startX} ${state.drawingConnection.startY}
340
+ C ${state.drawingConnection.startX - controlDistance} ${state.drawingConnection.startY},
341
+ ${endX + controlDistance} ${endY},
342
+ ${endX} ${endY}"
343
+ stroke="#0e639c" stroke-width="2" fill="none" />
344
+ `;
345
+ } else {
346
+ // Forward connection: output port is on the right, so curve goes right first
347
+ tempLine.innerHTML = `
348
+ <path d="M ${state.drawingConnection.startX} ${state.drawingConnection.startY}
349
+ C ${state.drawingConnection.startX + controlDistance} ${state.drawingConnection.startY},
350
+ ${endX - controlDistance} ${endY},
351
+ ${endX} ${endY}"
352
+ stroke="#0e639c" stroke-width="2" fill="none" />
353
+ `;
354
+ }
355
+ }
356
+
357
+ export function endConnection(targetId, targetInputIndex = 0) {
358
+ if (!state.drawingConnection) return;
359
+
360
+ const sourceId = state.drawingConnection.sourceId;
361
+ const outputIndex = state.drawingConnection.outputIndex || 0;
362
+
363
+ if (sourceId !== targetId) {
364
+ // Save state before creating connection
365
+ import('./history.js').then(({ saveState }) => {
366
+ saveState('create connection');
367
+ });
368
+ createConnection(sourceId, targetId, outputIndex, targetInputIndex);
369
+ }
370
+
371
+ cancelConnection();
372
+ }
373
+
374
+ // End a backward connection (dropped on output port)
375
+ export function endBackwardConnection(sourceId, outputIndex = 0) {
376
+ if (!state.drawingConnection || !state.drawingConnection.backward) return;
377
+
378
+ const targetId = state.drawingConnection.targetId;
379
+ const inputIndex = state.drawingConnection.inputIndex || 0;
380
+
381
+ if (sourceId !== targetId) {
382
+ // Save state before creating connection
383
+ import('./history.js').then(({ saveState }) => {
384
+ saveState('create connection');
385
+ });
386
+ // Connection is source -> target (backward was just UI direction)
387
+ createConnection(sourceId, targetId, outputIndex, inputIndex);
388
+ }
389
+
390
+ cancelConnection();
391
+ }
392
+
393
+ export function cancelConnection(e) {
394
+ const hadConnection = state.drawingConnection !== null;
395
+ const isBackward = state.drawingConnection?.backward;
396
+ const mousePos = e ? { x: e.clientX, y: e.clientY } : null;
397
+
398
+ if (hadConnection && mousePos) {
399
+ // Draw the temp line to the final position before showing mini palette
400
+ // (temp line lives in the SVG -> canvas coords; the mini palette is an
401
+ // HTML overlay on document.body -> keeps client coords)
402
+ const endPoint = clientToCanvas(mousePos.x, mousePos.y);
403
+ const endX = endPoint.x;
404
+ const endY = endPoint.y;
405
+ const dx = endX - state.drawingConnection.startX;
406
+ const controlDistance = Math.abs(dx) * 0.5;
407
+
408
+ const tempLine = document.getElementById('temp-line');
409
+
410
+ if (isBackward) {
411
+ // Backward connection: curve goes left first from input port
412
+ tempLine.innerHTML = `
413
+ <path d="M ${state.drawingConnection.startX} ${state.drawingConnection.startY}
414
+ C ${state.drawingConnection.startX - controlDistance} ${state.drawingConnection.startY},
415
+ ${endX + controlDistance} ${endY},
416
+ ${endX} ${endY}"
417
+ stroke="#0e639c" stroke-width="2" fill="none" />
418
+ `;
419
+ } else {
420
+ // Forward connection: curve goes right first from output port
421
+ tempLine.innerHTML = `
422
+ <path d="M ${state.drawingConnection.startX} ${state.drawingConnection.startY}
423
+ C ${state.drawingConnection.startX + controlDistance} ${state.drawingConnection.startY},
424
+ ${endX - controlDistance} ${endY},
425
+ ${endX} ${endY}"
426
+ stroke="#0e639c" stroke-width="2" fill="none" />
427
+ `;
428
+ }
429
+
430
+ // Show mini palette at mouse position (temp line will be cleared when palette closes)
431
+ if (isBackward) {
432
+ // Backward connection: show palette to create node that outputs TO this input
433
+ showMiniPaletteBackward(mousePos.x, mousePos.y, state.drawingConnection.targetId, state.drawingConnection.inputIndex);
434
+ } else {
435
+ // Forward connection: show palette to create node that receives FROM this output
436
+ showMiniPalette(mousePos.x, mousePos.y, state.drawingConnection.sourceId, state.drawingConnection.outputIndex);
437
+ }
438
+ } else {
439
+ // No mini palette, clear the temp line immediately
440
+ document.getElementById('temp-line').innerHTML = '';
441
+ }
442
+
443
+ state.drawingConnection = null;
444
+ document.removeEventListener('mousemove', drawTempConnection);
445
+ document.removeEventListener('mouseup', cancelConnection);
446
+ }
447
+
448
+ export function selectConnection(sourceId, targetId, sourceOutput = 0) {
449
+ console.log('selectConnection called:', sourceId, targetId, sourceOutput);
450
+
451
+ // Deselect any selected nodes
452
+ import('./selection.js').then(({ deselectAllNodes }) => {
453
+ deselectAllNodes();
454
+ });
455
+
456
+ // Store selected connection
457
+ state.selectedConnection = {
458
+ source: sourceId,
459
+ target: targetId,
460
+ sourceOutput: sourceOutput
461
+ };
462
+
463
+ console.log('Selected connection state:', state.selectedConnection);
464
+
465
+ // Update visual state
466
+ updateConnections();
467
+ }
468
+
469
+ export function deselectConnection() {
470
+ if (state.selectedConnection) {
471
+ state.selectedConnection = null;
472
+ updateConnections();
473
+ }
474
+ }
475
+
476
+ export function deleteSelectedConnection() {
477
+ if (state.selectedConnection) {
478
+ deleteConnection(
479
+ state.selectedConnection.source,
480
+ state.selectedConnection.target,
481
+ state.selectedConnection.sourceOutput
482
+ );
483
+ state.selectedConnection = null;
484
+ }
485
+ }
486
+
487
+ function showMiniPalette(x, y, sourceId, outputIndex) {
488
+ // Remove existing mini palette if any
489
+ const existing = document.getElementById('mini-palette');
490
+ if (existing) existing.remove();
491
+
492
+ // Create mini palette
493
+ const miniPalette = document.createElement('div');
494
+ miniPalette.id = 'mini-palette';
495
+ miniPalette.className = 'mini-palette';
496
+ miniPalette.style.left = `${x}px`;
497
+ miniPalette.style.top = `${y}px`;
498
+
499
+ // Store context for Enter key handling
500
+ miniPalette.dataset.x = x;
501
+ miniPalette.dataset.y = y;
502
+ miniPalette.dataset.sourceId = sourceId || '';
503
+ miniPalette.dataset.outputIndex = outputIndex !== null ? outputIndex : '';
504
+
505
+ // Add search field
506
+ const searchContainer = document.createElement('div');
507
+ searchContainer.className = 'mini-palette-search-container';
508
+ const searchInput = document.createElement('input');
509
+ searchInput.type = 'text';
510
+ searchInput.className = 'mini-palette-search';
511
+ searchInput.placeholder = 'Filter nodes...';
512
+ searchInput.addEventListener('click', (e) => e.stopPropagation());
513
+ searchInput.addEventListener('input', (e) => {
514
+ const filter = e.target.value.toLowerCase().trim();
515
+ filterMiniPaletteNodes(miniPalette, filter);
516
+ });
517
+ searchInput.addEventListener('keydown', (e) => {
518
+ if (e.key === 'Enter') {
519
+ e.preventDefault();
520
+ e.stopPropagation();
521
+
522
+ // Find the first visible item
523
+ const firstVisibleItem = miniPalette.querySelector('.mini-palette-item[style*="display: none"]')
524
+ ? miniPalette.querySelector('.mini-palette-item:not([style*="display: none"])')
525
+ : miniPalette.querySelector('.mini-palette-item');
526
+
527
+ if (firstVisibleItem) {
528
+ firstVisibleItem.click();
529
+ }
530
+ }
531
+ });
532
+ // Clear button for mini palette search
533
+ const clearBtn = document.createElement('button');
534
+ clearBtn.className = 'search-clear-btn mini-search-clear-btn';
535
+ clearBtn.setAttribute('aria-label', 'Clear search');
536
+ clearBtn.textContent = '✕';
537
+ clearBtn.style.display = 'none';
538
+ clearBtn.addEventListener('click', (ev) => {
539
+ ev.preventDefault();
540
+ ev.stopPropagation();
541
+ searchInput.value = '';
542
+ filterMiniPaletteNodes(miniPalette, '');
543
+ clearBtn.style.display = 'none';
544
+ searchInput.focus();
545
+ });
546
+ searchInput.addEventListener('input', (e) => {
547
+ clearBtn.style.display = e.target.value.trim() ? 'block' : 'none';
548
+ });
549
+ searchContainer.appendChild(searchInput);
550
+ searchContainer.appendChild(clearBtn);
551
+ miniPalette.appendChild(searchContainer);
552
+
553
+ // Create content container for categories
554
+ const contentContainer = document.createElement('div');
555
+ contentContainer.className = 'mini-palette-content';
556
+
557
+ // Only show nodes that have inputs (filter out source-only nodes like Inject)
558
+ // Dynamically group nodes by category, preserving order of first appearance
559
+ const categories = {};
560
+ const categoryOrder = [];
561
+
562
+ state.nodeTypes.forEach(nodeType => {
563
+ // Only show nodes that have at least one input
564
+ if (nodeType.inputCount === 0) return;
565
+
566
+ const category = String(nodeType.category || 'custom').toLowerCase();
567
+ if (!categories[category]) {
568
+ categories[category] = {
569
+ title: categoryLabel(category),
570
+ nodes: []
571
+ };
572
+ categoryOrder.push(category);
573
+ }
574
+ categories[category].nodes.push(nodeType);
575
+ });
576
+
577
+ // Create palette items in category order
578
+ categoryOrder.forEach(category => {
579
+ const categoryData = categories[category];
580
+ if (!categoryData || categoryData.nodes.length === 0) return;
581
+
582
+ const categoryDiv = document.createElement('div');
583
+ categoryDiv.className = 'mini-palette-category';
584
+
585
+ const categoryLabel = document.createElement('div');
586
+ categoryLabel.className = 'mini-palette-category-label';
587
+ categoryLabel.textContent = categoryData.title;
588
+ categoryDiv.appendChild(categoryLabel);
589
+
590
+ categoryData.nodes.forEach(nodeType => {
591
+ const item = document.createElement('div');
592
+ item.className = 'mini-palette-item';
593
+ item.innerHTML = `<span class="mini-palette-icon">${nodeType.icon}</span><span class="mini-palette-item-name">${nodeType.name}</span>`;
594
+ if (nodeType.color) item.style.backgroundColor = nodeType.color;
595
+ if (nodeType.borderColor) item.style.borderColor = nodeType.borderColor;
596
+ if (nodeType.textColor) item.style.color = nodeType.textColor;
597
+
598
+ item.addEventListener('click', (e) => {
599
+ e.stopPropagation();
600
+ createNodeAndConnect(nodeType.type, x, y, sourceId, outputIndex);
601
+ closeMiniPalette();
602
+ });
603
+
604
+ categoryDiv.appendChild(item);
605
+ });
606
+
607
+ contentContainer.appendChild(categoryDiv);
608
+ });
609
+
610
+ miniPalette.appendChild(contentContainer);
611
+ document.body.appendChild(miniPalette);
612
+
613
+ // Focus the search input
614
+ setTimeout(() => {
615
+ searchInput.focus();
616
+ }, 0);
617
+
618
+ // Close on click outside
619
+ setTimeout(() => {
620
+ document.addEventListener('click', closeMiniPalette, { once: true });
621
+ document.addEventListener('keydown', handleMiniPaletteKeydown);
622
+ }, 0);
623
+ }
624
+
625
+ function filterMiniPaletteNodes(palette, filter) {
626
+ const categories = palette.querySelectorAll('.mini-palette-category');
627
+
628
+ categories.forEach(category => {
629
+ const items = category.querySelectorAll('.mini-palette-item');
630
+ let visibleCount = 0;
631
+
632
+ items.forEach(item => {
633
+ const itemName = item.querySelector('.mini-palette-item-name').textContent.toLowerCase();
634
+ if (!filter || itemName.includes(filter)) {
635
+ item.style.display = '';
636
+ visibleCount++;
637
+ } else {
638
+ item.style.display = 'none';
639
+ }
640
+ });
641
+
642
+ // Hide category if no items match
643
+ category.style.display = visibleCount > 0 ? '' : 'none';
644
+ });
645
+ }
646
+
647
+ function closeMiniPalette() {
648
+ const miniPalette = document.getElementById('mini-palette');
649
+ if (miniPalette) {
650
+ miniPalette.remove();
651
+ }
652
+ // Clear the temp connection line
653
+ document.getElementById('temp-line').innerHTML = '';
654
+ document.removeEventListener('keydown', handleMiniPaletteKeydown);
655
+ }
656
+
657
+ function handleMiniPaletteKeydown(e) {
658
+ if (e.key === 'Escape') {
659
+ closeMiniPalette();
660
+ }
661
+ }
662
+
663
+ function createNodeAndConnect(nodeType, x, y, sourceId, outputIndex, targetInputIndex = 0) {
664
+ import('./nodes.js').then(({ createNode, snapNodeToGrid }) => {
665
+ // Convert client (mouse) coordinates to canvas coordinates (zoom-aware)
666
+ const canvasPoint = clientToCanvas(x, y);
667
+ const canvasX = canvasPoint.x;
668
+ const canvasY = canvasPoint.y;
669
+
670
+ // Create the new node
671
+ const newNodeId = createNode(nodeType, canvasX, canvasY);
672
+
673
+ // Snap to grid and create connection after a brief delay to ensure node is rendered
674
+ setTimeout(() => {
675
+ snapNodeToGrid(newNodeId);
676
+ // Connect based on direction: sourceId->newNode or newNode->sourceId
677
+ if (sourceId && outputIndex !== null) {
678
+ createConnection(sourceId, newNodeId, outputIndex, targetInputIndex);
679
+ }
680
+ }, 50);
681
+ });
682
+ }
683
+
684
+ // Show mini palette for backward connection (dragged from input port)
685
+ // Creates a node that will OUTPUT to the target node's input
686
+ function showMiniPaletteBackward(x, y, targetId, inputIndex) {
687
+ // Remove existing mini palette if any
688
+ const existing = document.getElementById('mini-palette');
689
+ if (existing) existing.remove();
690
+
691
+ // Create mini palette
692
+ const miniPalette = document.createElement('div');
693
+ miniPalette.id = 'mini-palette';
694
+ miniPalette.className = 'mini-palette';
695
+ miniPalette.style.left = `${x}px`;
696
+ miniPalette.style.top = `${y}px`;
697
+
698
+ // Store context for Enter key handling (backward mode)
699
+ miniPalette.dataset.x = x;
700
+ miniPalette.dataset.y = y;
701
+ miniPalette.dataset.targetId = targetId || '';
702
+ miniPalette.dataset.inputIndex = inputIndex !== null ? inputIndex : '';
703
+ miniPalette.dataset.backward = 'true';
704
+
705
+ // Add search field
706
+ const searchContainer = document.createElement('div');
707
+ searchContainer.className = 'mini-palette-search-container';
708
+ const searchInput = document.createElement('input');
709
+ searchInput.type = 'text';
710
+ searchInput.className = 'mini-palette-search';
711
+ searchInput.placeholder = 'Filter nodes...';
712
+ searchInput.addEventListener('click', (e) => e.stopPropagation());
713
+ searchInput.addEventListener('input', (e) => {
714
+ const filter = e.target.value.toLowerCase().trim();
715
+ filterMiniPaletteNodes(miniPalette, filter);
716
+ });
717
+ searchInput.addEventListener('keydown', (e) => {
718
+ if (e.key === 'Enter') {
719
+ e.preventDefault();
720
+ e.stopPropagation();
721
+
722
+ // Find the first visible item
723
+ const firstVisibleItem = miniPalette.querySelector('.mini-palette-item[style*="display: none"]')
724
+ ? miniPalette.querySelector('.mini-palette-item:not([style*="display: none"])')
725
+ : miniPalette.querySelector('.mini-palette-item');
726
+
727
+ if (firstVisibleItem) {
728
+ firstVisibleItem.click();
729
+ }
730
+ }
731
+ });
732
+ // Clear button for mini palette search (backward)
733
+ const clearBtnBack = document.createElement('button');
734
+ clearBtnBack.className = 'search-clear-btn mini-search-clear-btn';
735
+ clearBtnBack.setAttribute('aria-label', 'Clear search');
736
+ clearBtnBack.textContent = '✕';
737
+ clearBtnBack.style.display = 'none';
738
+ clearBtnBack.addEventListener('click', (ev) => {
739
+ ev.preventDefault();
740
+ ev.stopPropagation();
741
+ searchInput.value = '';
742
+ filterMiniPaletteNodes(miniPalette, '');
743
+ clearBtnBack.style.display = 'none';
744
+ searchInput.focus();
745
+ });
746
+ searchInput.addEventListener('input', (e) => {
747
+ clearBtnBack.style.display = e.target.value.trim() ? 'block' : 'none';
748
+ });
749
+ searchContainer.appendChild(searchInput);
750
+ searchContainer.appendChild(clearBtnBack);
751
+ miniPalette.appendChild(searchContainer);
752
+
753
+ // Create content container for categories
754
+ const contentContainer = document.createElement('div');
755
+ contentContainer.className = 'mini-palette-content';
756
+
757
+ // Show nodes that have outputs (filter out terminal nodes with no outputs)
758
+ // Dynamically group nodes by category, preserving order of first appearance
759
+ const categories = {};
760
+ const categoryOrder = [];
761
+
762
+ state.nodeTypes.forEach(nodeType => {
763
+ // Only show nodes that have at least one output
764
+ if (nodeType.outputCount === 0) return;
765
+
766
+ const category = String(nodeType.category || 'custom').toLowerCase();
767
+ if (!categories[category]) {
768
+ categories[category] = {
769
+ title: categoryLabel(category),
770
+ nodes: []
771
+ };
772
+ categoryOrder.push(category);
773
+ }
774
+ categories[category].nodes.push(nodeType);
775
+ });
776
+
777
+ // Create palette items in category order
778
+ categoryOrder.forEach(category => {
779
+ const categoryData = categories[category];
780
+ if (!categoryData || categoryData.nodes.length === 0) return;
781
+
782
+ const categoryDiv = document.createElement('div');
783
+ categoryDiv.className = 'mini-palette-category';
784
+
785
+ const categoryLabel = document.createElement('div');
786
+ categoryLabel.className = 'mini-palette-category-label';
787
+ categoryLabel.textContent = categoryData.title;
788
+ categoryDiv.appendChild(categoryLabel);
789
+
790
+ categoryData.nodes.forEach(nodeType => {
791
+ const item = document.createElement('div');
792
+ item.className = 'mini-palette-item';
793
+ item.innerHTML = `<span class="mini-palette-icon">${nodeType.icon}</span><span class="mini-palette-item-name">${nodeType.name}</span>`;
794
+ if (nodeType.color) item.style.backgroundColor = nodeType.color;
795
+ if (nodeType.borderColor) item.style.borderColor = nodeType.borderColor;
796
+ if (nodeType.textColor) item.style.color = nodeType.textColor;
797
+
798
+ item.addEventListener('click', (e) => {
799
+ e.stopPropagation();
800
+ // Create node and connect its output (0) to target's input
801
+ createNodeAndConnectBackward(nodeType.type, x, y, targetId, inputIndex);
802
+ closeMiniPalette();
803
+ });
804
+
805
+ categoryDiv.appendChild(item);
806
+ });
807
+
808
+ contentContainer.appendChild(categoryDiv);
809
+ });
810
+
811
+ miniPalette.appendChild(contentContainer);
812
+ document.body.appendChild(miniPalette);
813
+
814
+ // Focus the search input
815
+ setTimeout(() => {
816
+ searchInput.focus();
817
+ }, 0);
818
+
819
+ // Close on click outside
820
+ setTimeout(() => {
821
+ document.addEventListener('click', closeMiniPalette, { once: true });
822
+ document.addEventListener('keydown', handleMiniPaletteKeydown);
823
+ }, 0);
824
+ }
825
+
826
+ // Create a node and connect its output to an existing target node's input
827
+ function createNodeAndConnectBackward(nodeType, x, y, targetId, targetInputIndex = 0) {
828
+ import('./nodes.js').then(({ createNode, snapNodeToGrid }) => {
829
+ // Convert client (mouse) coordinates to canvas coordinates (zoom-aware)
830
+ const canvasPoint = clientToCanvas(x, y);
831
+ const canvasX = canvasPoint.x;
832
+ const canvasY = canvasPoint.y;
833
+
834
+ // Create the new node
835
+ const newNodeId = createNode(nodeType, canvasX, canvasY);
836
+
837
+ // Snap to grid and create connection after a brief delay to ensure node is rendered
838
+ setTimeout(() => {
839
+ snapNodeToGrid(newNodeId);
840
+ // Connect newNode's output 0 to targetId's input
841
+ createConnection(newNodeId, targetId, 0, targetInputIndex);
842
+ }, 50);
843
+ });
844
+ }