Skip to main content

leptos_node_graph/
utils.rs

1use crate::types::Position;
2
3pub fn bezier_control_points(start: Position, end: Position) -> (Position, Position) {
4    let dx = (end.x - start.x).abs();
5    let offset = dx.max(50.0) * 0.5;
6    let cp1 = Position::new(start.x + offset, start.y);
7    let cp2 = Position::new(end.x - offset, end.y);
8    (cp1, cp2)
9}
10
11pub fn bezier_path(start: Position, end: Position) -> String {
12    let (cp1, cp2) = bezier_control_points(start, end);
13    format!(
14        "M {},{} C {},{} {},{} {},{}",
15        start.x, start.y, cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y,
16    )
17}
18
19/// SVG path through a polyline, with each corner replaced by a quadratic turn
20/// of up to `radius` (clamped to half of the shorter adjoining leg, so short
21/// segments round proportionally instead of overshooting).
22///
23/// This is how routed subway paths are drawn: the router emits sharp waypoints
24/// and the corner rounding is purely presentational.
25pub fn rounded_polyline_path(pts: &[Position], radius: f64) -> String {
26    if pts.len() < 2 {
27        return String::new();
28    }
29    let mut d = format!("M {},{}", pts[0].x, pts[0].y);
30    for i in 1..pts.len() - 1 {
31        let (prev, curr, next) = (pts[i - 1], pts[i], pts[i + 1]);
32        let (dx1, dy1) = (curr.x - prev.x, curr.y - prev.y);
33        let (dx2, dy2) = (next.x - curr.x, next.y - curr.y);
34        let len1 = dx1.hypot(dy1);
35        let len2 = dx2.hypot(dy2);
36        if len1 == 0.0 || len2 == 0.0 {
37            d.push_str(&format!(" L {},{}", curr.x, curr.y));
38            continue;
39        }
40        let pull1 = radius.min(len1 / 2.0);
41        let pull2 = radius.min(len2 / 2.0);
42        let arc_start = Position::new(curr.x - dx1 / len1 * pull1, curr.y - dy1 / len1 * pull1);
43        let arc_end = Position::new(curr.x + dx2 / len2 * pull2, curr.y + dy2 / len2 * pull2);
44        d.push_str(&format!(
45            " L {},{} Q {},{} {},{}",
46            arc_start.x, arc_start.y, curr.x, curr.y, arc_end.x, arc_end.y
47        ));
48    }
49    let last = pts[pts.len() - 1];
50    d.push_str(&format!(" L {},{}", last.x, last.y));
51    d
52}
53
54/// Subway-style orthogonal routing: exit the source horizontally, turn at the
55/// mid-x, run vertically to the target's row, then enter the target horizontally —
56/// with small rounded corners (quadratic turns). Reads as right-angle "subway map"
57/// wiring rather than bezier curves.
58///
59/// This is the LOCAL fallback for a single pair of points (drafts, dangling
60/// stubs). Real connections are routed as a batch by [`crate::subway`], which
61/// also steers around nodes and separates shared corridors.
62pub fn orthogonal_path(start: Position, end: Position) -> String {
63    let mid_x = (start.x + end.x) / 2.0;
64    // Corner radius, clamped so it never exceeds half the vertical run or either leg.
65    let dy = (end.y - start.y).abs();
66    let leg_x = (mid_x - start.x).abs().min((end.x - mid_x).abs());
67    let r = 8.0_f64.min(dy / 2.0).min(leg_x).max(0.0);
68    if r < 0.5 {
69        // Degenerate (near-straight / no room to round) — a plain elbow.
70        return format!(
71            "M {},{} L {},{} L {},{} L {},{}",
72            start.x, start.y, mid_x, start.y, mid_x, end.y, end.x, end.y,
73        );
74    }
75    let down = end.y >= start.y;
76    let vy0 = if down { start.y + r } else { start.y - r };
77    let vy1 = if down { end.y - r } else { end.y + r };
78    format!(
79        "M {sx},{sy} L {c0x},{sy} Q {mx},{sy} {mx},{vy0} L {mx},{vy1} Q {mx},{ey} {c1x},{ey} L {ex},{ey}",
80        sx = start.x,
81        sy = start.y,
82        c0x = mid_x - r,
83        mx = mid_x,
84        vy0 = vy0,
85        vy1 = vy1,
86        ey = end.y,
87        c1x = mid_x + r,
88        ex = end.x,
89    )
90}
91
92pub fn bezier_point(start: Position, end: Position, t: f64) -> Position {
93    let (cp1, cp2) = bezier_control_points(start, end);
94    let t2 = t * t;
95    let t3 = t2 * t;
96    let mt = 1.0 - t;
97    let mt2 = mt * mt;
98    let mt3 = mt2 * mt;
99    Position {
100        x: mt3 * start.x + 3.0 * mt2 * t * cp1.x + 3.0 * mt * t2 * cp2.x + t3 * end.x,
101        y: mt3 * start.y + 3.0 * mt2 * t * cp1.y + 3.0 * mt * t2 * cp2.y + t3 * end.y,
102    }
103}
104
105pub fn distance_to_bezier(point: Position, start: Position, end: Position, steps: usize) -> f64 {
106    let mut min_dist = f64::MAX;
107    for i in 0..=steps {
108        let t = i as f64 / steps as f64;
109        let curve_point = bezier_point(start, end, t);
110        let dx = point.x - curve_point.x;
111        let dy = point.y - curve_point.y;
112        let dist = (dx * dx + dy * dy).sqrt();
113        if dist < min_dist {
114            min_dist = dist;
115        }
116    }
117    min_dist
118}
119
120pub fn snap_to_grid(pos: Position, grid_size: f64) -> Position {
121    Position {
122        x: (pos.x / grid_size).round() * grid_size,
123        y: (pos.y / grid_size).round() * grid_size,
124    }
125}
126
127/// Parse a CSS length that is a plain `px` value (e.g. `"160px"`). Returns
128/// `None` for any other unit or keyword, which callers read as "no constraint".
129pub fn parse_px(value: &str) -> Option<f64> {
130    value.trim().strip_suffix("px")?.trim().parse::<f64>().ok()
131}
132
133pub fn distance(a: Position, b: Position) -> f64 {
134    let dx = a.x - b.x;
135    let dy = a.y - b.y;
136    (dx * dx + dy * dy).sqrt()
137}