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

            
6
use super::styles;
7
use crate::markup::{plain, spans};
8
use crate::{Role, Theme};
9

            
10
/// One row of menu titles, each padded by a space, the first one column in. The selected
11
/// title, if any, is drawn in the `menu-selected` roles.
12
pub struct MenuBar<'a> {
13
    theme: &'a Theme,
14
    titles: &'a [&'a str],
15
    selected: Option<usize>,
16
}
17

            
18
impl<'a> MenuBar<'a> {
19
    #[must_use]
20
4238
    pub fn new(theme: &'a Theme, titles: &'a [&'a str], selected: Option<usize>) -> Self {
21
4238
        MenuBar {
22
4238
            theme,
23
4238
            titles,
24
4238
            selected,
25
4238
        }
26
4238
    }
27

            
28
    /// The cells of each title, padding included, clipped to `area`.
29
    #[must_use]
30
8482
    pub fn title_areas(area: Rect, titles: &[&str]) -> Vec<Rect> {
31
8482
        let mut x = area.x.saturating_add(1);
32
8482
        let mut areas = Vec::new();
33
8482
        for title in titles {
34
25439
            let width = u16::try_from(plain(title).chars().count() + 2).unwrap_or(u16::MAX);
35
25439
            let cell = Rect::new(x, area.y, width, 1).intersection(area);
36
25439
            areas.push(cell);
37
25439
            x = x.saturating_add(width);
38
        }
39
8482
        areas
40
8482
    }
41
}
42

            
43
impl Widget for MenuBar<'_> {
44
4238
    fn render(self, area: Rect, buf: &mut Buffer) {
45
4238
        buf.set_style(area, self.theme.style(Role::Menu));
46
4238
        let areas = Self::title_areas(area, self.titles);
47
4238
        for (index, (title, cell)) in self.titles.iter().zip(areas).enumerate() {
48
12712
            let (base, hot) = styles(self.theme, self.selected == Some(index), true);
49
12712
            let mut line = Vec::from([Span::styled(" ", base)]);
50
12712
            line.extend(spans(title, base, hot));
51
12712
            line.push(Span::styled(" ", base));
52
12712
            buf.set_style(cell, base);
53
12712
            Line::from(line).render(cell, buf);
54
        }
55
4238
    }
56
}