Skip to main content

santui_core/widgets/
popup.rs

1use ratatui::layout::Rect;
2
3pub fn centered_rect(parent: Rect, min_w: u16, ideal_w: u16, height: u16) -> Rect {
4    let width = ideal_w
5        .min(parent.width.saturating_sub(2))
6        .max(min_w)
7        .min(parent.width);
8    let x = parent.x + (parent.width.saturating_sub(width)) / 2;
9    let y = parent.y + (parent.height.saturating_sub(height)) / 2;
10    Rect {
11        x,
12        y,
13        width,
14        height,
15    }
16}
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21
22    #[test]
23    fn centered_rect_basic() {
24        let r = centered_rect(Rect::new(0, 0, 100, 50), 30, 40, 20);
25        assert_eq!((r.x, r.y, r.width, r.height), (30, 15, 40, 20));
26    }
27
28    #[test]
29    fn centered_rect_clamps_ideal_width_to_parent_minus_2() {
30        let r = centered_rect(Rect::new(0, 0, 50, 50), 10, 100, 10);
31        assert_eq!(r.width, 48);
32    }
33
34    #[test]
35    fn centered_rect_enforces_min_width() {
36        let r = centered_rect(Rect::new(0, 0, 100, 50), 80, 10, 20);
37        assert_eq!(r.width, 80);
38    }
39
40    #[test]
41    fn centered_rect_caps_min_width_to_parent() {
42        let r = centered_rect(Rect::new(0, 0, 5, 50), 10, 20, 10);
43        assert_eq!(r.width, 5);
44    }
45
46    #[test]
47    fn centered_rect_with_parent_offset() {
48        let r = centered_rect(Rect::new(10, 5, 100, 50), 30, 40, 20);
49        assert_eq!((r.x, r.y), (40, 20));
50    }
51}