Skip to main content

tvui/menu/
bar.rs

1use ratatui::buffer::Buffer;
2use ratatui::layout::Rect;
3use ratatui::text::{Line, Span};
4use ratatui::widgets::Widget;
5
6use super::styles;
7use crate::markup::{plain, spans};
8use 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.
12pub struct MenuBar<'a> {
13    theme: &'a Theme,
14    titles: &'a [&'a str],
15    selected: Option<usize>,
16}
17
18impl<'a> MenuBar<'a> {
19    #[must_use]
20    pub fn new(theme: &'a Theme, titles: &'a [&'a str], selected: Option<usize>) -> Self {
21        MenuBar {
22            theme,
23            titles,
24            selected,
25        }
26    }
27
28    /// The cells of each title, padding included, clipped to `area`.
29    #[must_use]
30    pub fn title_areas(area: Rect, titles: &[&str]) -> Vec<Rect> {
31        let mut x = area.x.saturating_add(1);
32        let mut areas = Vec::new();
33        for title in titles {
34            let width = u16::try_from(plain(title).chars().count() + 2).unwrap_or(u16::MAX);
35            let cell = Rect::new(x, area.y, width, 1).intersection(area);
36            areas.push(cell);
37            x = x.saturating_add(width);
38        }
39        areas
40    }
41}
42
43impl Widget for MenuBar<'_> {
44    fn render(self, area: Rect, buf: &mut Buffer) {
45        buf.set_style(area, self.theme.style(Role::Menu));
46        let areas = Self::title_areas(area, self.titles);
47        for (index, (title, cell)) in self.titles.iter().zip(areas).enumerate() {
48            let (base, hot) = styles(self.theme, self.selected == Some(index), true);
49            let mut line = Vec::from([Span::styled(" ", base)]);
50            line.extend(spans(title, base, hot));
51            line.push(Span::styled(" ", base));
52            buf.set_style(cell, base);
53            Line::from(line).render(cell, buf);
54        }
55    }
56}