Skip to main content

ez_tui/components/mock/
legend.rs

1use crate::inputs::legend::Legend;
2use crate::{MockComponent, Props, Theme};
3use eztui_derive::MockProps;
4use ratatui::buffer::Buffer;
5use ratatui::layout::Rect;
6use ratatui::prelude::Stylize;
7use ratatui::style::Style;
8use ratatui::text::{Line, Span, Text};
9use ratatui::widgets::{Paragraph, Widget};
10use std::fmt::Debug;
11
12/// A mock component to display a colored indicator inside the TUI. The indicator is a simple box alternating its style from a given set of [`Style`] when [`Self::cycle`] is called.
13#[derive(Debug, Default, MockProps)]
14pub struct LegendMock {
15    props: Props,
16    legend: Legend,
17}
18
19impl LegendMock {
20    /// Create a new [`LegendMock`] component by picking two colors from the given [`Palette`].
21    #[must_use]
22    pub fn with_hotkeys(legend: Legend) -> Self {
23        LegendMock {
24            legend,
25            ..Default::default()
26        }
27    }
28}
29
30impl MockComponent for LegendMock {
31    fn draw(&mut self, area: Rect, buf: &mut Buffer, theme: &Theme) {
32        let style0 = Style::new()
33            .bg(theme.main_palette.c900)
34            .fg(theme.accent_palette.c300)
35            .bold();
36        let style1 = Style::new().fg(theme.accent_palette.c300).bold();
37        let style2 = Style::new().fg(theme.main_palette.c300);
38        let mut ations_str: Vec<Span> = self
39            .legend
40            .matchers
41            .iter()
42            .flat_map(|matcher| {
43                let key_str: String = matcher
44                    .hotkeys()
45                    .iter()
46                    .map(|key| format!("{key}"))
47                    .collect::<Vec<_>>()
48                    .join(",");
49
50                [
51                    Span::styled(key_str, style1),
52                    Span::styled(format!(" : {}", matcher.name()), style2),
53                    Span::from(" "),
54                    Span::styled("/", style0),
55                    Span::from(" "),
56                ]
57            })
58            .collect();
59        ations_str.pop();
60        ations_str.insert(0, Span::from(" ".to_string()));
61        ations_str.insert(0, Span::styled(format!("{}:", self.legend.name), style0));
62        Paragraph::new(Text::from(vec![Line::from(ations_str)])).render(area, buf);
63    }
64}