src/global/functions/popup_area.rs

49 lines · 1240 bytes

1 symbol in this file
 1use ratatui::layout::Rect;
 2
 3/// Tries to create a centered area for popup, returns `Err` if not enough space is given
 4pub fn popup_area(
 5    (max_width_percentage, max_height_percentage): (u16, u16),
 6    (min_width_length, min_height_length): (u16, u16),
 7    area: Rect,
 8) -> Result<Rect, Rect> {
 9    let mut success = true;
10
11    let (width, x) = {
12        if min_width_length >= area.width {
13            success = false;
14            (area.width, 0)
15        } else {
16            let mut width = area.width * max_width_percentage / 100;
17            if width < min_width_length {
18                width = min_width_length;
19            }
20            (width, (area.width - width) / 2)
21        }
22    };
23
24    let (height, y) = {
25        if min_height_length >= area.height {
26            success = false;
27            (area.height, 0)
28        } else {
29            let mut height = area.height * max_height_percentage / 100;
30            if height < min_height_length {
31                height = min_height_length;
32            }
33            (height, (area.height - height) / 2)
34        }
35    };
36
37    let rect = Rect {
38        x,
39        y,
40        width,
41        height,
42    };
43
44    if success {
45        Ok(rect)
46    } else {
47        Err(rect)
48    }
49}