Skip to main content

comb/widgets/
menu.rs

1//! A dropdown / context menu: a bordered overlay wrapping a selectable [`List`],
2//! rendered as a compositor layer so it floats over the scene.
3
4use crate::core::geom::Rect;
5use crate::draw::border::Border;
6use crate::term::terminal::Frame;
7use crate::widgets::list::List;
8use crate::widgets::Palette;
9
10pub struct Menu {
11    pub list: List,
12    pub border: Border,
13}
14
15impl Menu {
16    pub fn new(items: Vec<String>) -> Self {
17        Menu {
18            list: List::new(items),
19            border: Border::Rounded,
20        }
21    }
22
23    /// The rectangle the menu occupies if opened with its top-left at `(x, y)`.
24    pub fn area_at(&self, x: u16, y: u16) -> Rect {
25        let w = self
26            .list
27            .items
28            .iter()
29            .map(|s| s.chars().count())
30            .max()
31            .unwrap_or(4) as u16
32            + 4;
33        let h = self.list.items.len() as u16 + 2;
34        Rect::new(x, y, w, h)
35    }
36
37    /// Map a click at `(col, row)` — for a menu opened at `(x, y)` — to an item.
38    pub fn index_at(&self, x: u16, y: u16, col: u16, row: u16) -> Option<usize> {
39        let area = self.area_at(x, y);
40        if !area.contains(col, row) {
41            return None;
42        }
43        let inner = Rect::new(area.x + 1, area.y + 1, area.width - 2, area.height - 2);
44        self.list.index_at(inner, row)
45    }
46
47    /// Render as a layer at `z`, opened with its top-left at `(x, y)`.
48    pub fn render(&mut self, f: &mut Frame, x: u16, y: u16, z: i32, pal: &Palette) {
49        let area = self.area_at(x, y).intersection(f.area());
50        if area.is_empty() {
51            return;
52        }
53        let (w, h) = (area.width, area.height);
54        let lay = f.layer(area, z);
55        lay.block(
56            Rect::new(0, 0, w, h),
57            self.border,
58            pal.border,
59            Some(pal.panel),
60        );
61        let inner = Rect::new(1, 1, w.saturating_sub(2), h.saturating_sub(2));
62        self.list.render(lay, inner, pal);
63    }
64}