flow_rs_core/layout/
utils.rs

1//! Layout utility functions
2
3use crate::graph::Graph;
4use crate::types::Position;
5
6/// Layout utilities
7pub struct LayoutUtils;
8
9impl LayoutUtils {
10    /// Center a graph around the origin
11    pub fn center_graph<N: Clone, E>(graph: &mut Graph<N, E>) {
12        if let Some(bounds) = graph.bounds() {
13            let center = bounds.center();
14            let offset = Position::zero() - center;
15
16            for node in graph.nodes_mut() {
17                node.position += offset;
18            }
19        }
20    }
21
22    /// Scale a graph to fit within given bounds
23    pub fn scale_to_fit<N: Clone, E>(
24        graph: &mut Graph<N, E>,
25        target_width: f64,
26        target_height: f64,
27    ) {
28        if let Some(bounds) = graph.bounds() {
29            if bounds.width > 0.0 && bounds.height > 0.0 {
30                let scale_x = target_width / bounds.width;
31                let scale_y = target_height / bounds.height;
32                let scale = scale_x.min(scale_y);
33
34                let center = bounds.center();
35
36                for node in graph.nodes_mut() {
37                    let relative_pos = node.position - center;
38                    node.position = center + relative_pos * scale;
39                }
40            }
41        }
42    }
43
44    /// Apply padding around a graph
45    pub fn apply_padding<N, E>(graph: &mut Graph<N, E>, padding: f64) {
46        for node in graph.nodes_mut() {
47            node.position += Position::new(padding, padding);
48        }
49    }
50}