File size: 24,384 Bytes
3ff344a
 
 
ad2d527
837c995
5d1d174
3ff344a
 
 
 
 
837c995
3ff344a
5d1d174
5ccea09
5d1d174
d615ba9
5d1d174
73622ec
3ff344a
837c995
 
 
 
 
 
 
5d1d174
837c995
 
 
 
5d1d174
837c995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2d527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d1d174
ad2d527
 
 
 
 
837c995
ad2d527
 
d615ba9
ad2d527
 
5ccea09
5d1d174
 
 
 
73622ec
 
 
 
ad2d527
 
 
837c995
ad2d527
ee85fe1
 
 
 
 
 
 
ad2d527
ee85fe1
 
 
 
 
 
 
73622ec
ee85fe1
 
 
 
 
ad85069
ee85fe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73622ec
ad2d527
73622ec
 
ad85069
 
 
 
 
 
 
 
ad2d527
 
 
 
ee85fe1
ad2d527
73622ec
ad2d527
 
 
5d1d174
ad85069
3ff344a
ad2d527
 
3ff344a
 
 
837c995
5d1d174
 
 
 
 
3ff344a
5d1d174
 
ad2d527
3ff344a
 
 
 
 
837c995
3ff344a
837c995
3ff344a
 
 
5d1d174
3ff344a
5d1d174
3ff344a
 
 
 
 
5d1d174
d615ba9
 
 
 
ad2d527
 
 
 
d615ba9
 
ad2d527
d615ba9
 
 
 
5d1d174
ad2d527
 
 
d615ba9
 
 
837c995
d615ba9
 
 
 
 
5d1d174
d615ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d1d174
d615ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d1d174
d615ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2d527
 
 
837c995
6a4e54c
ad2d527
 
 
d615ba9
 
ad2d527
5d1d174
 
 
 
3ff344a
 
5d1d174
 
 
 
 
 
73622ec
 
 
 
5d1d174
 
364311b
 
 
 
 
 
 
 
 
ae47bd6
 
f08a8a8
28021fd
4bb0f33
 
364311b
4bb0f33
58dff6d
 
 
364311b
 
 
5d1d174
73622ec
 
5d1d174
 
 
 
 
 
 
 
 
 
 
73622ec
 
 
 
 
 
 
 
 
 
 
 
364311b
 
 
73622ec
5d1d174
33273fc
 
ed8945f
33273fc
5d1d174
73622ec
 
5d1d174
73622ec
5d1d174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73622ec
 
 
 
5d1d174
 
 
 
 
 
 
837c995
3ff344a
 
 
73622ec
5d1d174
73622ec
 
 
 
 
 
5d1d174
3ff344a
 
 
 
ad2d527
 
 
5d1d174
d615ba9
 
 
 
 
 
 
 
 
5ccea09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d615ba9
 
 
 
 
 
5ccea09
 
 
 
5d1d174
5ccea09
 
d615ba9
5ccea09
 
 
 
 
5d1d174
 
ee85fe1
5d1d174
 
 
 
 
 
 
 
 
5ccea09
 
 
 
d615ba9
 
 
 
 
 
 
 
 
 
 
5ccea09
 
 
5d1d174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ccea09
 
 
 
5d1d174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee85fe1
5d1d174
 
 
 
 
 
 
 
 
 
 
 
 
837c995
ad2d527
 
ee85fe1
 
ad2d527
 
d615ba9
 
5d1d174
 
 
 
ad2d527
3ff344a
 
 
ad2d527
3ff344a
 
ee85fe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837c995
3ff344a
5ccea09
d615ba9
 
 
5ccea09
d615ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff344a
 
 
 
 
 
837c995
3ff344a
 
 
 
 
 
 
d615ba9
 
 
 
 
 
 
5d1d174
 
 
 
d615ba9
3ff344a
 
ad85069
 
 
 
3ff344a
 
837c995
3ff344a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// Initialize Konva stage
const stage = new Konva.Stage({
    container: 'container',
    width: 1000,
    height: 600,
    draggable: true
});

const layer = new Konva.Layer();
stage.add(layer);

// Store nodes, connections, and parsed data
let nodes = [];
let connections = [];
let parsedConnections = [];
let selectedPort = null;
let disconnectMode = false;
let codeWindow = null; // Track open code window
let codeTextarea = null; // Track textarea element

// Zoom functionality
let scale = 1;
const scaleFactor = 1.1;
const minScale = 0.5;
const maxScale = 2.0;

stage.on('wheel', (e) => {
    e.evt.preventDefault();
    const oldScale = scale;
    const pointer = stage.getPointerPosition();
    const delta = e.evt.deltaY > 0 ? 1 / scaleFactor : scaleFactor;
    const newScale = Math.max(minScale, Math.min(maxScale, oldScale * delta));
    if (newScale === scale) return;
    scale = newScale;
    const mousePointTo = {
        x: (pointer.x - stage.x()) / oldScale,
        y: (pointer.y - stage.y()) / oldScale
    };
    stage.scale({ x: scale, y: scale });
    const newPos = {
        x: pointer.x - mousePointTo.x * scale,
        y: pointer.y - mousePointTo.y * scale
    };
    stage.position(newPos);
    stage.batchDraw();
});

// Submit code or file for parsing
function submitCode() {
    const fileInput = document.getElementById('codeFile');
    const codeInput = document.getElementById('codeInput').value;
    const formData = new FormData();

    if (fileInput.files.length > 0) {
        formData.append('file', fileInput.files[0]);
    } else if (codeInput) {
        formData.append('code', codeInput);
    } else {
        alert('Please upload a file or paste code.');
        return;
    }

    fetch('/parse_code', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
            return;
        }
        clearCanvas();
        parsedConnections = data.connections;
        createNodesFromParsedData(data.nodes, data.connections);
    })
    .catch(error => console.error('Error:', error));
}

// Clear existing nodes and connections
function clearCanvas() {
    nodes.forEach(node => node.destroy());
    layer.find('Shape').forEach(shape => shape.destroy());
    nodes = [];
    connections = [];
    parsedConnections = [];
    if (codeWindow) {
        codeWindow.destroy();
        codeWindow = null;
    }
    if (codeTextarea) {
        codeTextarea.remove();
        codeTextarea = null;
    }
    layer.draw();
}

// Create nodes and connections from parsed data
function createNodesFromParsedData(parsedNodes, parsedConnections) {
    const columns = {
        imports: { x: 50, y: 50, count: 0 }, // Column for imports
        global: { x: 250, y: 50, count: 0 }, // Column for global scope
        functions: {} // Columns for functions
    };

    // First pass: Assign function nodes to columns
    parsedNodes.forEach(nodeData => {
        if (nodeData.type === 'function') {
            const functionId = nodeData.id || `Function_${Object.keys(columns.functions).length + 1}`;
            columns.functions[functionId] = {
                x: 450 + Object.keys(columns.functions).length * 200,
                y: 50,
                count: 0
            };
        }
    });

    // Second pass: Create nodes with column-based positioning
    parsedNodes.forEach(nodeData => {
        const parentPath = nodeData.parent_path || 'global';
        const level = nodeData.level || 0;
        let x, y;

        if (nodeData.type === 'import') {
            // Imports column
            x = columns.imports.x;
            y = columns.imports.y + columns.imports.count * 80;
            columns.imports.count++;
        } else if (nodeData.type === 'function') {
            // Function column
            const functionId = nodeData.id;
            x = columns.functions[functionId].x;
            y = columns.functions[functionId].y + columns.functions[functionId].count * 80;
            columns.functions[functionId].count++;
        } else if (parentPath !== 'global' && parentPath.includes('Function')) {
            // Child of a function
            const functionId = parentPath.split(' -> ')[0];
            if (columns.functions[functionId]) {
                x = columns.functions[functionId].x;
                y = columns.functions[functionId].y + columns.functions[functionId].count * 80;
                columns.functions[functionId].count++;
            } else {
                // Fallback to global if function not found
                x = columns.global.x;
                y = columns.global.y + columns.global.count * 80;
                columns.global.count++;
            }
        } else {
            // Global scope (non-import, non-function)
            x = columns.global.x;
            y = columns.global.y + columns.global.count * 80;
            columns.global.count++;
        }

        const node = createNode(
            x,
            y,
            nodeData.label || 'Unnamed',
            nodeData.type || 'other',
            nodeData.inputs || [],
            nodeData.outputs || [],
            nodeData.id || `node_${nodes.length}`,
            nodeData.source || '',
            parentPath,
            level
        );
        nodes.push(node);
        layer.add(node);
    });

    layer.draw();
    autoConnect();
    saveNodes();
}

// Create a node with inputs, outputs, and code segment
function createNode(x, y, label, type, inputs = [], outputs = [], id, source = '', parent_path = 'global', level = 0) {
    const node = new Konva.Group({
        x: x,
        y: y,
        draggable: true
    });

    // Node rectangle
    const isNumberBox = type === 'number_box';
    const color = isNumberBox ? '#ffcccb' : type === 'function' ? '#ffeb3b' : type.includes('variable') ? '#90caf9' : type === 'import' ? '#a5d6a7' : '#ccc';
    const width = isNumberBox ? 80 : 100;
    const height = isNumberBox ? 40 : 50;

    const box = new Konva.Rect({
        width: width,
        height: height,
        fill: color,
        stroke: 'black',
        strokeWidth: 2,
        cornerRadius: 5
    });

    // Node label
    const text = new Konva.Text({
        text: label,
        fontSize: 12,
        fontFamily: 'Arial',
        fill: 'black',
        width: width,
        align: 'center',
        y: isNumberBox ? 14 : 20
    });

    node.add(box);
    node.add(text);

    // Input/output ports
    const inputPorts = inputs.map((input, i) => ({
        id: `input-${id}-${i}`,
        name: input,
        circle: new Konva.Circle({
            x: 0,
            y: 10 + i * 20,
            radius: 5,
            fill: 'red'
        })
    }));

    const outputPorts = outputs.map((output, i) => ({
        id: `output-${id}-${i}`,
        name: output,
        circle: new Konva.Circle({
            x: width,
            y: 10 + i * 20,
            radius: 5,
            fill: 'green'
        })
    }));

    // Add ports to node and set up click handlers
    inputPorts.forEach(port => {
        node.add(port.circle);
        port.circle.on('click', () => {
            if (!selectedPort) {
                selectedPort = { node, portId: port.id, type: 'input' };
                disconnectMode = true;
            } else if (selectedPort.type === 'output' && selectedPort.node !== node) {
                createSplineConnection(
                    selectedPort.node,
                    selectedPort.portId,
                    node,
                    port.id
                );
                connections.push({
                    fromNodeId: selectedPort.node.data.id,
                    fromPortId: selectedPort.portId,
                    toNodeId: node.data.id,
                    toPortId: port.id
                });
                selectedPort = null;
                disconnectMode = false;
                saveNodes();
            } else if (disconnectMode && selectedPort.type === 'input' && selectedPort.node === node) {
                selectedPort = { node, portId: port.id, type: 'input' };
            } else {
                selectedPort = null;
                disconnectMode = false;
            }
        });
    });

    outputPorts.forEach(port => {
        node.add(port.circle);
        port.circle.on('click', () => {
            if (!selectedPort) {
                selectedPort = { node, portId: port.id, type: 'output' };
                disconnectMode = false;
            } else if (disconnectMode && selectedPort.type === 'input') {
                const connIndex = connections.findIndex(
                    c => c.toNodeId === selectedPort.node.data.id &&
                         c.toPortId === selectedPort.portId &&
                         c.fromNodeId === node.data.id &&
                         c.fromPortId === port.id
                );
                if (connIndex !== -1) {
                    const conn = connections[connIndex];
                    const spline = layer.find('Shape').find(s =>
                        s.data.fromNodeId === conn.fromNodeId &&
                        s.data.fromPortId === conn.fromPortId &&
                        s.data.toNodeId === conn.toNodeId &&
                        s.data.toPortId === conn.toPortId
                    );
                    if (spline) spline.destroy();
                    connections.splice(connIndex, 1);
                    layer.draw();
                    saveNodes();
                }
                selectedPort = null;
                disconnectMode = false;
            } else {
                selectedPort = null;
                disconnectMode = false;
            }
        });
    });

    // Node data
    node.data = {
        id: id,
        type: type,
        label: label,
        inputs: inputPorts,
        outputs: outputPorts,
        x: x,
        y: y,
        source: source,
        parent_path: parent_path,
        level: level
    };

    // Click handler to show code window
    box.on('click', () => {
        if (codeWindow) {
            codeWindow.destroy();
            codeWindow = null;
        }
        if (codeTextarea) {
            codeTextarea.remove();
            codeTextarea = null;
        }

        const nodePos = node.getAbsolutePosition();
      
        // Create textarea for editing
        codeTextarea = document.createElement('textarea');
        codeTextarea.style.position = 'relative';
        const canvasRect = stage.container().getBoundingClientRect();
        const textareaX = nodePos.x;
      //  const textareaX = (nodePos.x + stage.x()) / scale + canvasRect.left;
       // const textareaY = (nodePos.y + height + 10 + stage.y()) / scale + canvasRect.top;
        const textareaY = nodePos.y;
        //codeTextarea.style.right = `${textareaX}px`;
        //codeTextarea.style.top = `${textareaY}px`;
        codeTextarea.style.left = '15px' || `${textareaX}px`;
        codeTextarea.style.top = '-200px' || `${textareaY}px`;
        codeTextarea.style.width = '300px' || `${300 / scale}px`;
        codeTextarea.style.height = '200px' || `${100 / scale}px`;
        codeTextarea.style.fontFamily = 'monospace';
        codeTextarea.style.fontSize = '12px' || `${12 / scale}px`;
        codeTextarea.style.background = '#ebebeb';
        codeTextarea.style.border = 'solid';
        codeTextarea.style.borderColor = 'grey';
        codeTextarea.style.resize = 'none';
        codeTextarea.value = source || '';
        document.body.appendChild(codeTextarea);
        codeWindow = new Konva.Group({
            x: node.x(),
            y: node.y() + height + 10
        });

        const codeBox = new Konva.Rect({
            width: 300,
            height: 100,
            fill: '#f0f0f0',
            stroke: 'black',
            strokeWidth: 1,
            cornerRadius: 5
        });

        // Display source in Konva Text for visual containment
        const codeText = new Konva.Text({
            x: 5,
            y: 5,
            text: source || '',
            fontSize: 12,
            fontFamily: 'monospace',
            fill: 'black',
            width: 290,
            padding: 5
        });

        //codeWindow.add(codeBox);
        //codeWindow.add(codeText);



        codeWindow.add(codeBox);
        codeWindow.add(codeText);
        //codeWindow.add(codeTextarea);
        layer.add(codeWindow);
        // Update code on change
        codeTextarea.addEventListener('change', () => {
            const newSource = codeTextarea.value;
            node.data.source = newSource;
            codeText.text(newSource);
            fetch('/update_node', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    id: node.data.id,
                    source: newSource
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    console.log('Node updated:', data);
                    updateProgram();
                }
            })
            .catch(error => console.error('Error:', error));
        });

        // Close window on click outside
        stage.on('click', (e) => {
            if (e.target !== box && codeWindow) {
                codeWindow.destroy();
                codeWindow = null;
                if (codeTextarea) {
                    codeTextarea.remove();
                    codeTextarea = null;
                }
                stage.off('click');
            }
        });

        layer.draw();
    });

    // Update position and connections on drag
    node.on('dragmove', () => {
        node.data.x = node.x();
        node.data.y = node.y();
        if (codeWindow && codeTextarea) {
            const nodePos = node.getAbsolutePosition();
            codeWindow.position({ x: node.x(), y: node.y() + height + 10 });
            const canvasRect = stage.container().getBoundingClientRect();
            const textareaX = (nodePos.x + stage.x()) / scale + canvasRect.left;
            const textareaY = (nodePos.y + height + 10 + stage.y()) / scale + canvasRect.top;
            codeTextarea.style.left = `${textareaX}px`;
            codeTextarea.style.top = `${textareaY}px`;
        }
        updateConnections();
        saveNodes();
    });

    return node;
}

// Create a spline connection
function createSplineConnection(fromNode, fromPortId, toNode, toPortId) {
    const fromPort = fromNode.data.outputs.find(p => p.id === fromPortId);
    const toPort = toNode.data.inputs.find(p => p.id === toPortId);
    if (!fromPort || !toPort) return;

    const startX = fromNode.x() + fromPort.circle.x();
    const startY = fromNode.y() + fromPort.circle.y();
    const endX = toNode.x() + toPort.circle.x();
    const endY = toNode.y() + toPort.circle.y();

    const control1X = startX + (endX - startX) / 3;
    const control1Y = startY;
    const control2X = startX + 2 * (endX - startX) / 3;
    const control2Y = endY;

    const spline = new Konva.Shape({
        sceneFunc: function(context, shape) {
            context.beginPath();
            context.moveTo(startX, startY);
            context.bezierCurveTo(control1X, control1Y, control2X, control2Y, endX, endY);
            context.fillStrokeShape(shape);
        },
        stroke: 'black',
        strokeWidth: 2
    });

    spline.data = {
        fromNodeId: fromNode.data.id,
        fromPortId: fromPortId,
        toNodeId: toNode.data.id,
        toPortId: toPortId
    };
    layer.add(spline);
    layer.draw();
}

// Enhanced auto-connect based on hierarchy, position, and role
function autoConnect() {
    layer.find('Shape').forEach(shape => {
        if (shape.data && shape.data.fromNodeId !== undefined) {
            shape.destroy();
        }
    });
    connections = [];

    const sortedNodes = [...nodes].sort((a, b) => {
        if (a.data.level !== b.data.level) return a.data.level - b.data.level;
        return a.data.y - b.data.y; // Sort by y within columns
    });

    const hierarchy = {};
    sortedNodes.forEach(node => {
        const parent = node.data.parent_path.split(' -> ')[0] || 'global';
        if (!hierarchy[parent]) hierarchy[parent] = [];
        hierarchy[parent].push(node);
    });

    parsedConnections.forEach(conn => {
        const fromNode = nodes.find(n => n.data.id === conn.from);
        const toNode = nodes.find(n => n.data.id === conn.to);
        if (fromNode && toNode) {
            const fromPort = fromNode.data.outputs[0];
            const toPort = toNode.data.inputs[0];
            if (fromPort && toPort) {
                createSplineConnection(fromNode, fromPort.id, toNode, toPort.id);
                connections.push({
                    fromNodeId: fromNode.data.id,
                    fromPortId: fromPort.id,
                    toNodeId: toNode.data.id,
                    toPortId: toPort.id
                });
            }
        }
    });

    sortedNodes.forEach(node => {
        const nodeId = node.data.id;
        const parent = node.data.parent_path.split(' -> ')[0] || 'global';
        const role = node.data.type;

        if (parent !== 'global') {
            const parentNode = nodes.find(n => n.data.id === parent || n.data.label === parent.split('[')[0]);
            if (parentNode && parentNode.data.outputs.length > 0 && node.data.inputs.length > 0) {
                const fromPort = parentNode.data.outputs[0];
                const toPort = node.data.inputs[0];
                if (!connections.some(c => c.fromNodeId === parentNode.data.id && c.toNodeId === nodeId)) {
                    createSplineConnection(parentNode, fromPort.id, node, toPort.id);
                    connections.push({
                        fromNodeId: parentNode.data.id,
                        fromPortId: fromPort.id,
                        toNodeId: nodeId,
                        toPortId: toPort.id
                    });
                }
            }
        }

        if (role.includes('variable')) {
            const varName = node.data.label;
            sortedNodes.forEach(otherNode => {
                if (otherNode !== node && otherNode.data.source.includes(varName)) {
                    const fromPort = node.data.outputs[0];
                    const toPort = otherNode.data.inputs[0];
                    if (fromPort && toPort && !connections.some(c => c.fromNodeId === nodeId && c.toNodeId === otherNode.data.id)) {
                        createSplineConnection(node, fromPort.id, otherNode, toPort.id);
                        connections.push({
                            fromNodeId: nodeId,
                            fromPortId: fromPort.id,
                            toNodeId: otherNode.data.id,
                            toPortId: toPort.id
                        });
                    }
                }
            });
        }
    });

    layer.draw();
    saveNodes();
}

// Update full program
function updateProgram() {
    const program = reconstructProgram();
    document.getElementById('codeInput').value = program;
    fetch('/update_program', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: program })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            console.log('Program updated:', data);
        }
    })
    .catch(error => console.error('Error:', error));
}

// Reconstruct the original program
function reconstructProgram() {
    const sortedNodes = [...nodes].sort((a, b) => {
        if (a.data.level !== b.data.level) return a.data.level - b.data.level;
        return a.data.y - b.data.y; // Sort by y within columns
    });

    let program = '';
    sortedNodes.forEach(node => {
        const source = node.data.source || '';
        const level = node.data.level || 0;
        const indent = '    '.repeat(level);
        program += indent + source.trim() + '\n';
    });

    return program.trim();
}

// Add a manual node
function addNode() {
    const node = createNode(
        250, // Add to global column
        50 + nodes.filter(n => n.data.parent_path === 'global').length * 80,
        'Function',
        'function',
        ['in1'],
        ['out1'],
        nodes.length,
        'def new_function(): pass',
        'global',
        0
    );
    nodes.push(node);
    layer.add(node);
    layer.draw();
    saveNodes();
}

// Update spline connections when nodes move
function createSplineConnection(fromNode, fromPortId, toNode, toPortId) {
    const fromPort = fromNode.data.outputs.find(p => p.id === fromPortId);
    const toPort = toNode.data.inputs.find(p => p.id === toPortId);
    if (!fromPort || !toPort) return;

    const startX = fromNode.x() + fromPort.circle.x();
    const startY = fromNode.y() + fromPort.circle.y();
    const endX = toNode.x() + toPort.circle.x();
    const endY = toNode.y() + toPort.circle.y();

    const control1X = startX + (endX - startX) / 3;
    const control1Y = startY;
    const control2X = startX + 2 * (endX - startX) / 3;
    const control2Y = endY;

    const spline = new Konva.Shape({
        sceneFunc: function(context, shape) {
            context.beginPath();
            context.moveTo(startX, startY);
            context.bezierCurveTo(control1X, control1Y, control2X, control2Y, endX, endY);
            context.fillStrokeShape(shape);
        },
        stroke: 'black',
        strokeWidth: 2
    });

    spline.data = {
        fromNodeId: fromNode.data.id,
        fromPortId: fromPortId,
        toNodeId: toNode.data.id,
        toPortId: toPortId
    };
    layer.add(spline);
    layer.draw();
}

// Update spline connections when nodes move
function updateConnections() {
    layer.find('Shape').forEach(shape => {
        if (shape.data && shape.data.fromNodeId !== undefined) {
            const fromNode = nodes.find(n => n.data.id === shape.data.fromNodeId);
            const toNode = nodes.find(n => n.data.id === shape.data.toNodeId);
            if (fromNode && toNode) {
                const fromPort = fromNode.data.outputs.find(p => p.id === shape.data.fromPortId);
                const toPort = toNode.data.inputs.find(p => p.id === shape.data.toPortId);
                if (fromPort && toPort) {
                    const startX = fromNode.x() + fromPort.circle.x();
                    const startY = fromNode.y() + fromPort.circle.y();
                    const endX = toNode.x() + toPort.circle.x();
                    const endY = toNode.y() + toPort.circle.y();

                    const control1X = startX + (endX - startX) / 3;
                    const control1Y = startY;
                    const control2X = startX + 2 * (endX - startX) / 3;
                    const control2Y = endY;

                    shape.sceneFunc(function(context, shape) {
                        context.beginPath();
                        context.moveTo(startX, startY);
                        context.bezierCurveTo(control1X, control1Y, control2X, control2Y, endX, endY);
                        context.fillStrokeShape(shape);
                    });
                }
            }
        }
    });
    layer.draw();
}

// Save nodes and connections to backend
function saveNodes() {
    fetch('/save_nodes', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            nodes: nodes.map(n => ({
                id: n.data.id,
                type: n.data.type,
                label: n.data.label,
                x: n.data.x,
                y: n.data.y,
                inputs: n.data.inputs.map(p => p.name),
                outputs: n.data.outputs.map(p => p.name),
                source: n.data.source,
                parent_path: n.data.parent_path,
                level: n.data.level
            })),
            connections: connections
        })
    })
    .then(response => response.json())
    .then(data => console.log('Saved:', data))
    .catch(error => console.error('Error:', error));
}

// Initial draw
layer.draw();