1
use ratatui::buffer::Buffer;
2
use ratatui::layout::Rect;
3
use ratatui::text::{Line, Span};
4
use ratatui::widgets::{Clear, Widget};
5

            
6
use super::styles;
7
use crate::frame::shadow;
8
use crate::markup::{plain, spans};
9
use 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.
13
pub 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.
23
pub struct MenuPopup<'a> {
24
    theme: &'a Theme,
25
    items: &'a [MenuItem<'a>],
26
    selected: usize,
27
    top: usize,
28
    rows: usize,
29
}
30

            
31
14660
fn columns(text: &str) -> usize {
32
14660
    text.chars().count()
33
14660
}
34

            
35
impl<'a> MenuPopup<'a> {
36
    #[must_use]
37
108
    pub fn new(theme: &'a Theme, items: &'a [MenuItem<'a>], selected: usize) -> Self {
38
108
        MenuPopup {
39
108
            theme,
40
108
            items,
41
108
            selected,
42
108
            top: 0,
43
108
            rows: items.len(),
44
108
        }
45
108
    }
46

            
47
    /// Shows only `rows` items from item `top`, with a scrollbar when some are hidden.
48
    #[must_use]
49
102
    pub fn scrolled(mut self, top: usize, rows: usize) -> Self {
50
102
        self.top = top;
51
102
        self.rows = rows;
52
102
        self
53
102
    }
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
102
    pub fn fit(window: &RowWindow, len: usize, selected: usize, rows: usize) -> usize {
59
102
        let held = window.fit(len, rows);
60
102
        let top = match selected {
61
102
            at if at < held => at,
62
99
            at if at >= held + rows => at + 1 - rows,
63
93
            _ => held,
64
        };
65
102
        window.set_top(top);
66
102
        top
67
102
    }
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
1
    pub fn area(anchor: Rect, items: &[MenuItem<'_>]) -> Rect {
72
1
        Self::area_rows(anchor, items, items.len())
73
1
    }
74

            
75
    /// The row of each item, the full width inside the border.
76
    #[must_use]
77
4
    pub fn item_areas(anchor: Rect, items: &[MenuItem<'_>]) -> Vec<Rect> {
78
4
        Self::item_areas_rows(anchor, items, items.len())
79
4
    }
80

            
81
    /// [`Self::area`] tall enough for `rows` items, as wide as the widest of all of them.
82
    #[must_use]
83
425
    pub fn area_rows(anchor: Rect, items: &[MenuItem<'_>], rows: usize) -> Rect {
84
5986
        let label = items.iter().map(|i| columns(&plain(i.label))).max();
85
5986
        let key = items.iter().map(|i| columns(i.key)).max();
86
425
        let inner = 4 + label.unwrap_or(0) + 2 + key.unwrap_or(0);
87
425
        let width = u16::try_from(inner + 2).unwrap_or(u16::MAX);
88
425
        let height = u16::try_from(rows + 2).unwrap_or(u16::MAX);
89
425
        Rect::new(anchor.x.saturating_sub(1), anchor.bottom(), width, height)
90
425
    }
91

            
92
    /// [`Self::item_areas`] for the `rows` items shown.
93
    #[must_use]
94
214
    pub fn item_areas_rows(anchor: Rect, items: &[MenuItem<'_>], rows: usize) -> Vec<Rect> {
95
214
        let inner = Self::area_rows(anchor, items, rows).inner(ratatui::layout::Margin::new(1, 1));
96
214
        (0..inner.height)
97
2708
            .map(|row| Rect::new(inner.x, inner.y.saturating_add(row), inner.width, 1))
98
            .collect()
99
214
    }
100

            
101
1344
    fn row(&self, item: &MenuItem<'_>, width: u16, selected: bool) -> Line<'static> {
102
1344
        let (base, hot) = styles(self.theme, selected, item.enabled);
103
1344
        let mark = if item.marked { "•" } else { " " };
104
1344
        let used = 4 + columns(&plain(item.label)) + columns(item.key);
105
1344
        let gap = usize::from(width).saturating_sub(used);
106
1344
        let mut spans_of = Vec::from([Span::styled(format!(" {mark} "), base)]);
107
1344
        spans_of.extend(spans(item.label, base, hot));
108
1344
        spans_of.push(Span::styled(" ".repeat(gap), base));
109
1344
        spans_of.push(Span::styled(format!("{} ", item.key), base));
110
1344
        Line::from(spans_of)
111
1344
    }
112
}
113

            
114
impl Widget for MenuPopup<'_> {
115
108
    fn render(self, anchor: Rect, buf: &mut Buffer) {
116
108
        let full = Self::area_rows(anchor, self.items, self.rows);
117
108
        let outer = full.intersection(buf.area);
118
108
        Clear.render(outer, buf);
119
108
        menu_box(self.theme).render(outer, buf);
120
108
        let cells = Self::item_areas_rows(anchor, self.items, self.rows);
121
108
        let shown = self.items.iter().enumerate().skip(self.top);
122
108
        for ((index, item), cell) in shown.zip(cells) {
123
1344
            let selected = index == self.selected;
124
1344
            let style = styles(self.theme, selected, item.enabled).0;
125
1344
            let line = self.row(item, cell.width, selected).style(style);
126
1344
            line.render(cell.intersection(buf.area), buf);
127
        }
128
108
        render_scrollbar(
129
108
            self.theme,
130
108
            full,
131
108
            buf,
132
108
            (self.items.len(), self.rows, self.top),
133
108
        );
134
108
        shadow(buf, outer, self.theme);
135
108
    }
136
}