Skip to main content

rgpui_component/chart/
area_chart.rs

1use std::rc::Rc;
2
3use num_traits::{Num, ToPrimitive};
4use rgpui::{App, Background, Bounds, Hsla, Pixels, SharedString, Window, px};
5use rgpui_component_macros::IntoPlot;
6
7use crate::{
8    ActiveTheme,
9    plot::{
10        AXIS_GAP, Grid, Plot, PlotAxis, StrokeStyle,
11        scale::{Scale, ScaleLinear, ScalePoint, Sealed},
12        shape::Area,
13    },
14};
15
16use super::build_point_x_labels;
17
18#[derive(IntoPlot)]
19pub struct AreaChart<T, X, Y>
20where
21    T: 'static,
22    X: Clone + PartialEq + Into<SharedString> + 'static,
23    Y: Clone + Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
24{
25    data: Vec<T>,
26    x: Option<Rc<dyn Fn(&T) -> X>>,
27    y: Vec<Rc<dyn Fn(&T) -> Y>>,
28    strokes: Vec<Hsla>,
29    stroke_styles: Vec<StrokeStyle>,
30    fills: Vec<Background>,
31    tick_margin: usize,
32    x_axis: bool,
33    grid: bool,
34}
35
36impl<T, X, Y> AreaChart<T, X, Y>
37where
38    X: Clone + PartialEq + Into<SharedString> + 'static,
39    Y: Clone + Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
40{
41    pub fn new<I>(data: I) -> Self
42    where
43        I: IntoIterator<Item = T>,
44    {
45        Self {
46            data: data.into_iter().collect(),
47            stroke_styles: vec![],
48            strokes: vec![],
49            fills: vec![],
50            tick_margin: 1,
51            x: None,
52            y: vec![],
53            x_axis: true,
54            grid: true,
55        }
56    }
57
58    pub fn x(mut self, x: impl Fn(&T) -> X + 'static) -> Self {
59        self.x = Some(Rc::new(x));
60        self
61    }
62
63    pub fn y(mut self, y: impl Fn(&T) -> Y + 'static) -> Self {
64        self.y.push(Rc::new(y));
65        self
66    }
67
68    pub fn stroke(mut self, stroke: impl Into<Hsla>) -> Self {
69        self.strokes.push(stroke.into());
70        self
71    }
72
73    pub fn fill(mut self, fill: impl Into<Background>) -> Self {
74        self.fills.push(fill.into());
75        self
76    }
77
78    pub fn natural(mut self) -> Self {
79        self.stroke_styles.push(StrokeStyle::Natural);
80        self
81    }
82
83    pub fn linear(mut self) -> Self {
84        self.stroke_styles.push(StrokeStyle::Linear);
85        self
86    }
87
88    pub fn step_after(mut self) -> Self {
89        self.stroke_styles.push(StrokeStyle::StepAfter);
90        self
91    }
92
93    pub fn tick_margin(mut self, tick_margin: usize) -> Self {
94        self.tick_margin = tick_margin;
95        self
96    }
97
98    /// Show or hide the x-axis line and labels.
99    ///
100    /// Default is true.
101    pub fn x_axis(mut self, x_axis: bool) -> Self {
102        self.x_axis = x_axis;
103        self
104    }
105
106    pub fn grid(mut self, grid: bool) -> Self {
107        self.grid = grid;
108        self
109    }
110}
111
112impl<T, X, Y> Plot for AreaChart<T, X, Y>
113where
114    X: Clone + PartialEq + Into<SharedString> + 'static,
115    Y: Clone + Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
116{
117    fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
118        let Some(x_fn) = self.x.as_ref() else {
119            return;
120        };
121
122        if self.y.len() == 0 {
123            return;
124        }
125
126        let width = bounds.size.width.as_f32();
127        let axis_gap = if self.x_axis { AXIS_GAP } else { 0. };
128        let height = bounds.size.height.as_f32() - axis_gap;
129
130        // X scale
131        let x = ScalePoint::new(self.data.iter().map(|v| x_fn(v)).collect(), vec![0., width]);
132
133        // Y scale
134        let domain = self
135            .data
136            .iter()
137            .flat_map(|v| self.y.iter().map(|y_fn| y_fn(v)))
138            .chain(Some(Y::zero()))
139            .collect::<Vec<_>>();
140        let y = ScaleLinear::new(domain, vec![height, 10.]);
141
142        // Draw X axis
143        let mut axis = PlotAxis::new().stroke(cx.theme().border);
144        if self.x_axis {
145            let labels = build_point_x_labels(
146                &self.data,
147                x_fn.as_ref(),
148                &x,
149                self.tick_margin,
150                cx.theme().muted_foreground,
151            );
152            axis = axis.x(height).x_label(labels);
153        }
154        axis.paint(&bounds, window, cx);
155
156        // Draw grid
157        if self.grid {
158            Grid::new()
159                .y((0..=3).map(|i| height * i as f32 / 4.0).collect())
160                .stroke(cx.theme().border)
161                .dash_array(&[px(4.), px(2.)])
162                .paint(&bounds, window);
163        }
164
165        // Draw area
166        for (i, y_fn) in self.y.iter().enumerate() {
167            let x = x.clone();
168            let y = y.clone();
169            let x_fn = x_fn.clone();
170            let y_fn = y_fn.clone();
171
172            let fill = *self
173                .fills
174                .get(i)
175                .unwrap_or(&cx.theme().chart_2.opacity(0.4).into());
176
177            let stroke = *self.strokes.get(i).unwrap_or(&cx.theme().chart_2);
178
179            let stroke_style = *self
180                .stroke_styles
181                .get(i)
182                .unwrap_or(self.stroke_styles.first().unwrap_or(&Default::default()));
183
184            Area::new()
185                .data(&self.data)
186                .x(move |d| x.tick(&x_fn(d)))
187                .y0(height)
188                .y1(move |d| y.tick(&y_fn(d)))
189                .stroke(stroke)
190                .stroke_style(stroke_style)
191                .fill(fill)
192                .paint(&bounds, window);
193        }
194    }
195}