centerOnSelection method
void
centerOnSelection()
Centers the viewport on the center point of all selected nodes without changing zoom.
Calculates the geometric center of all selected nodes and pans the viewport to that point.
Does nothing if no nodes are selected or if the screen size is zero.
Example:
controller.selectNodes(['node1', 'node2', 'node3']);
controller.centerOnSelection();
Implementation
void centerOnSelection() {
if (_selectedNodeIds.isEmpty || _screenSize.value == Size.zero) return;
// Calculate center of selected nodes
double totalX = 0;
double totalY = 0;
int count = 0;
for (final nodeId in _selectedNodeIds) {
final node = _nodes[nodeId];
if (node != null) {
final pos = node.position.value;
final size = node.size.value;
totalX += pos.dx + size.width / 2;
totalY += pos.dy + size.height / 2;
count++;
}
}
if (count == 0) return;
final centerX = totalX / count;
final centerY = totalY / count;
final currentVp = _viewport.value;
setViewport(
GraphViewport(
x: _screenSize.value.width / 2 - centerX * currentVp.zoom,
y: _screenSize.value.height / 2 - centerY * currentVp.zoom,
zoom: currentVp.zoom,
),
);
}