Skip to main content

ansiq_widgets/
bar_chart.rs

1use ansiq_core::{Bar, BarChartProps, Element, ElementKind, Layout, Length, Style};
2
3pub struct BarChart<Message = ()> {
4    element: Element<Message>,
5}
6
7impl<Message> BarChart<Message> {
8    pub fn new() -> Self {
9        Self {
10            element: Element::new(ElementKind::BarChart(BarChartProps {
11                bars: Vec::new(),
12                max: None,
13                bar_width: 3,
14            }))
15            .with_layout(Layout {
16                width: Length::Fill,
17                height: Length::Fixed(6),
18            }),
19        }
20    }
21
22    pub fn bar(mut self, label: impl Into<String>, value: u64) -> Self {
23        if let ElementKind::BarChart(props) = &mut self.element.kind {
24            props.bars.push(Bar {
25                label: label.into(),
26                value,
27            });
28        }
29        self
30    }
31
32    pub fn bars<I, S>(mut self, bars: I) -> Self
33    where
34        I: IntoIterator<Item = (S, u64)>,
35        S: Into<String>,
36    {
37        if let ElementKind::BarChart(props) = &mut self.element.kind {
38            props
39                .bars
40                .extend(bars.into_iter().map(|(label, value)| Bar {
41                    label: label.into(),
42                    value,
43                }));
44        }
45        self
46    }
47
48    pub fn max(mut self, max: u64) -> Self {
49        if let ElementKind::BarChart(props) = &mut self.element.kind {
50            props.max = Some(max);
51        }
52        self
53    }
54
55    pub fn bar_width(mut self, bar_width: u16) -> Self {
56        if let ElementKind::BarChart(props) = &mut self.element.kind {
57            props.bar_width = bar_width.max(1);
58        }
59        self
60    }
61
62    pub fn layout(mut self, layout: Layout) -> Self {
63        self.element.layout = layout;
64        self
65    }
66
67    pub fn style(mut self, style: Style) -> Self {
68        self.element.style = style;
69        self
70    }
71
72    pub fn build(self) -> Element<Message> {
73        self.element
74    }
75}