1
//! The menu bar and the open drop-down.
2

            
3
use ratatui::Frame;
4
use ratatui::layout::Rect;
5
use tvui::{MenuBar, MenuItem, MenuPopup};
6

            
7
use crate::app::{App, MenuId};
8
use crate::hits::{Hits, Target};
9

            
10
/// The rows under the popup box: its border, its shadow and the status line.
11
const BELOW_POPUP: u16 = 3;
12

            
13
const TITLES: [&str; MenuId::ALL.len()] = [
14
    MenuId::View.title(),
15
    MenuId::Window.title(),
16
    MenuId::Options.title(),
17
];
18

            
19
1649
pub(super) fn draw_menu(frame: &mut Frame, bar: Rect, app: &App, hits: &mut Hits) {
20
1649
    let selected = app.menu_title().map(MenuId::index);
21
1649
    let titles = MenuBar::title_areas(bar, &TITLES);
22
1649
    frame.render_widget(MenuBar::new(&app.theme, &TITLES, selected), bar);
23
1649
    if let (Some(menu), Some(at)) = (app.menu_title(), app.menu_item()) {
24
34
        hits.push(frame.area(), Target::MenuBackdrop);
25
34
        draw_popup(frame, titles[menu.index()], at, app, hits);
26
1615
    }
27
1649
    for (index, title) in titles.into_iter().enumerate() {
28
4947
        hits.push(title, Target::MenuTitle(index));
29
    }
30
1649
}
31

            
32
34
fn draw_popup(frame: &mut Frame, anchor: Rect, selected: usize, app: &App, hits: &mut Hits) {
33
34
    let entries = app.menu_entries();
34
34
    let items: Vec<MenuItem> = entries
35
34
        .iter()
36
        .map(|entry| MenuItem {
37
494
            label: &entry.label,
38
494
            key: &entry.key,
39
494
            marked: entry.marked,
40
494
            enabled: entry.enabled,
41
494
        })
42
        .collect();
43
34
    let fits = usize::from(
44
34
        frame
45
34
            .area()
46
34
            .bottom()
47
34
            .saturating_sub(anchor.bottom() + BELOW_POPUP),
48
34
    );
49
34
    let rows = items.len().min(fits.max(1));
50
34
    let top = MenuPopup::fit(&app.menu_window, items.len(), selected, rows);
51
34
    let popup = MenuPopup::new(&app.theme, &items, selected).scrolled(top, rows);
52
34
    hits.push(MenuPopup::area_rows(anchor, &items, rows), Target::Block);
53
34
    let cells = MenuPopup::item_areas_rows(anchor, &items, rows);
54
34
    for (index, item) in cells.into_iter().enumerate() {
55
444
        hits.push(item, Target::MenuItem(top + index));
56
    }
57
34
    frame.render_widget(popup, anchor);
58
34
}
59

            
60
#[cfg(test)]
61
mod tests;