Skip to main content

tvui/menu/
popup.rs

1use ratatui::buffer::Buffer;
2use ratatui::layout::Rect;
3use ratatui::text::{Line, Span};
4use ratatui::widgets::{Clear, Widget};
5
6use super::styles;
7use crate::frame::shadow;
8use crate::markup::{plain, spans};
9use crate::{RowWindow, Theme, menu_box, render_scrollbar};
10
11/// A drop-down row: the label with its `~X~` mark, the key text on the right, whether it is
12/// marked and whether it can be chosen.
13pub struct MenuItem<'a> {
14    pub label: &'a str,
15    pub key: &'a str,
16    pub marked: bool,
17    pub enabled: bool,
18}
19
20/// The drop-down under a menu title: a single-line box with a shadow, one item a row, the
21/// selected one in the `menu-selected` roles and the marked ones with a bullet. Rendered
22/// with the title's area as its anchor.
23pub struct MenuPopup<'a> {
24    theme: &'a Theme,
25    items: &'a [MenuItem<'a>],
26    selected: usize,
27    top: usize,
28    rows: usize,
29}
30
31fn columns(text: &str) -> usize {
32    text.chars().count()
33}
34
35impl<'a> MenuPopup<'a> {
36    #[must_use]
37    pub fn new(theme: &'a Theme, items: &'a [MenuItem<'a>], selected: usize) -> Self {
38        MenuPopup {
39            theme,
40            items,
41            selected,
42            top: 0,
43            rows: items.len(),
44        }
45    }
46
47    /// Shows only `rows` items from item `top`, with a scrollbar when some are hidden.
48    #[must_use]
49    pub fn scrolled(mut self, top: usize, rows: usize) -> Self {
50        self.top = top;
51        self.rows = rows;
52        self
53    }
54
55    /// The first item to show so that `selected` is in view among `rows` rows of `len` items;
56    /// `window` keeps it between frames, so the list moves only when the selection leaves it.
57    #[must_use]
58    pub fn fit(window: &RowWindow, len: usize, selected: usize, rows: usize) -> usize {
59        let held = window.fit(len, rows);
60        let top = match selected {
61            at if at < held => at,
62            at if at >= held + rows => at + 1 - rows,
63            _ => held,
64        };
65        window.set_top(top);
66        top
67    }
68
69    /// The box with its border: left edge one column left of `anchor`, top edge on the row below it.
70    #[must_use]
71    pub fn area(anchor: Rect, items: &[MenuItem<'_>]) -> Rect {
72        Self::area_rows(anchor, items, items.len())
73    }
74
75    /// The row of each item, the full width inside the border.
76    #[must_use]
77    pub fn item_areas(anchor: Rect, items: &[MenuItem<'_>]) -> Vec<Rect> {
78        Self::item_areas_rows(anchor, items, items.len())
79    }
80
81    /// [`Self::area`] tall enough for `rows` items, as wide as the widest of all of them.
82    #[must_use]
83    pub fn area_rows(anchor: Rect, items: &[MenuItem<'_>], rows: usize) -> Rect {
84        let label = items.iter().map(|i| columns(&plain(i.label))).max();
85        let key = items.iter().map(|i| columns(i.key)).max();
86        let inner = 4 + label.unwrap_or(0) + 2 + key.unwrap_or(0);
87        let width = u16::try_from(inner + 2).unwrap_or(u16::MAX);
88        let height = u16::try_from(rows + 2).unwrap_or(u16::MAX);
89        Rect::new(anchor.x.saturating_sub(1), anchor.bottom(), width, height)
90    }
91
92    /// [`Self::item_areas`] for the `rows` items shown.
93    #[must_use]
94    pub fn item_areas_rows(anchor: Rect, items: &[MenuItem<'_>], rows: usize) -> Vec<Rect> {
95        let inner = Self::area_rows(anchor, items, rows).inner(ratatui::layout::Margin::new(1, 1));
96        (0..inner.height)
97            .map(|row| Rect::new(inner.x, inner.y.saturating_add(row), inner.width, 1))
98            .collect()
99    }
100
101    fn row(&self, item: &MenuItem<'_>, width: u16, selected: bool) -> Line<'static> {
102        let (base, hot) = styles(self.theme, selected, item.enabled);
103        let mark = if item.marked { "•" } else { " " };
104        let used = 4 + columns(&plain(item.label)) + columns(item.key);
105        let gap = usize::from(width).saturating_sub(used);
106        let mut spans_of = Vec::from([Span::styled(format!(" {mark} "), base)]);
107        spans_of.extend(spans(item.label, base, hot));
108        spans_of.push(Span::styled(" ".repeat(gap), base));
109        spans_of.push(Span::styled(format!("{} ", item.key), base));
110        Line::from(spans_of)
111    }
112}
113
114impl Widget for MenuPopup<'_> {
115    fn render(self, anchor: Rect, buf: &mut Buffer) {
116        let full = Self::area_rows(anchor, self.items, self.rows);
117        let outer = full.intersection(buf.area);
118        Clear.render(outer, buf);
119        menu_box(self.theme).render(outer, buf);
120        let cells = Self::item_areas_rows(anchor, self.items, self.rows);
121        let shown = self.items.iter().enumerate().skip(self.top);
122        for ((index, item), cell) in shown.zip(cells) {
123            let selected = index == self.selected;
124            let style = styles(self.theme, selected, item.enabled).0;
125            let line = self.row(item, cell.width, selected).style(style);
126            line.render(cell.intersection(buf.area), buf);
127        }
128        render_scrollbar(
129            self.theme,
130            full,
131            buf,
132            (self.items.len(), self.rows, self.top),
133        );
134        shadow(buf, outer, self.theme);
135    }
136}