Skip to main content

ansiq_widgets/
chart.rs

1use ansiq_core::{ChartDataset, ChartProps, Element, ElementKind, Layout, Length, Style};
2
3pub struct Chart<Message = ()> {
4    element: Element<Message>,
5}
6
7impl<Message> Chart<Message> {
8    pub fn new() -> Self {
9        Self {
10            element: Element::new(ElementKind::Chart(ChartProps {
11                datasets: Vec::new(),
12                min_y: None,
13                max_y: None,
14            }))
15            .with_layout(Layout {
16                width: Length::Fill,
17                height: Length::Fixed(8),
18            }),
19        }
20    }
21
22    pub fn dataset<I>(mut self, points: I) -> Self
23    where
24        I: IntoIterator<Item = (i64, i64)>,
25    {
26        if let ElementKind::Chart(props) = &mut self.element.kind {
27            props.datasets.push(ChartDataset {
28                label: None,
29                points: points.into_iter().collect(),
30            });
31        }
32        self
33    }
34
35    pub fn named_dataset<I>(mut self, label: impl Into<String>, points: I) -> Self
36    where
37        I: IntoIterator<Item = (i64, i64)>,
38    {
39        if let ElementKind::Chart(props) = &mut self.element.kind {
40            props.datasets.push(ChartDataset {
41                label: Some(label.into()),
42                points: points.into_iter().collect(),
43            });
44        }
45        self
46    }
47
48    pub fn min_y(mut self, min_y: i64) -> Self {
49        if let ElementKind::Chart(props) = &mut self.element.kind {
50            props.min_y = Some(min_y);
51        }
52        self
53    }
54
55    pub fn max_y(mut self, max_y: i64) -> Self {
56        if let ElementKind::Chart(props) = &mut self.element.kind {
57            props.max_y = Some(max_y);
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}