Spaces:
Running
Running
// Initialize Konva stage | |
const stage = new Konva.Stage({ | |
container: 'container', | |
width: 800, | |
height: 600 | |
}); | |
const layer = new Konva.Layer(); | |
stage.add(layer); | |
// Store nodes and connections | |
let nodes = []; | |
let connections = []; | |
let selectedNode = null; | |
// Add a new node | |
function addNode() { | |
const node = new Konva.Group({ | |
x: Math.random() * (stage.width() - 100), | |
y: Math.random() * (stage.height() - 100), | |
draggable: true | |
}); | |
// Node rectangle | |
const box = new Konva.Rect({ | |
width: 100, | |
height: 50, | |
fill: '#ffeb3b', | |
stroke: 'black', | |
strokeWidth: 2, | |
cornerRadius: 5 | |
}); | |
// Node text (function name) | |
const text = new Konva.Text({ | |
text: 'Function', | |
fontSize: 12, | |
fontFamily: 'Arial', | |
fill: 'black', | |
width: 100, | |
align: 'center', | |
y: 20 | |
}); | |
node.add(box); | |
node.add(text); | |
// Node data | |
node.data = { | |
id: nodes.length, | |
function: 'sampleFunction', // Placeholder function name | |
x: node.x(), | |
y: node.y() | |
}; | |
// Handle node click for connections | |
node.on('click', () => { | |
if (!selectedNode) { | |
selectedNode = node; | |
} else { | |
// Create connection | |
const line = new Konva.Line({ | |
points: [ | |
selectedNode.x() + 50, selectedNode.y() + 25, | |
node.x() + 50, node.y() + 25 | |
], | |
stroke: 'black', | |
strokeWidth: 2 | |
}); | |
layer.add(line); | |
connections.push({ | |
from: selectedNode.data.id36 | |
to: node.data.id | |
}); | |
selectedNode = null; | |
saveNodes(); | |
} | |
}); | |
// Update position on drag | |
node.on('dragmove', () => { | |
node.data.x = node.x(); | |
node.data.y = node.y(); | |
updateConnections(); | |
saveNodes(); | |
}); | |
nodes.push(node); | |
layer.add(node); | |
layer.draw(); | |
} | |
// Update connection lines when nodes move | |
function updateConnections() { | |
connections.forEach((conn, index) => { | |
const fromNode = nodes.find(n => n.data.id === conn.from); | |
const toNode = nodes.find(n => n.data.id === conn.to); | |
if (fromNode && toNode) { | |
const line = layer.find('Line')[index]; | |
if (line) { | |
line.points([ | |
fromNode.x() + 50, fromNode.y() + 25, | |
toNode.x() + 50, toNode.y() + 25 | |
]); | |
} | |
} | |
}); | |
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 => n.data), | |
connections: connections | |
}) | |
}).then(response => response.json()) | |
.then(data => console.log('Saved:', data)) | |
.catch(error => console.error('Error:', error)); | |
} | |
// Initial draw | |
layer.draw(); |