Skip to main content

gpui_component/chart/
area_chart.rs

1use std::rc::Rc;
2
3use gpui::ColorExt as _;
4use gpui::{
5    AnyElement, App, Background, Bounds, ElementId, Hsla, IntoElement, Pixels, Point, SharedString,
6    Window, point, px,
7};
8use gpui_component_macros::IntoPlot;
9use num_traits::{Num, ToPrimitive};
10
11use crate::{
12    ActiveTheme,
13    plot::{
14        AXIS_GAP, Grid, Plot, PlotAxis, StrokeStyle,
15        scale::{Scale, ScaleLinear, ScalePoint, Sealed},
16        shape::Area,
17        tooltip::{CrossLine, Dot, Tooltip, TooltipState},
18    },
19};
20
21use super::build_point_x_labels;
22
23#[derive(IntoPlot)]
24pub struct AreaChart<T, X, Y>
25where
26    T: 'static,
27    X: Clone + PartialEq + Into<SharedString> + 'static,
28    Y: Clone + Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
29{
30    data: Vec<T>,
31    x: Option<Rc<dyn Fn(&T) -> X>>,
32    y: Vec<Rc<dyn Fn(&T) -> Y>>,
33    strokes: Vec<Hsla>,
34    stroke_styles: Vec<StrokeStyle>,
35    fills: Vec<Background>,
36    names: Vec<SharedString>,
37    tick_margin: usize,
38    x_axis: bool,
39    grid: bool,
40    id: Option<ElementId>,
41}
42
43impl<T, X, Y> AreaChart<T, X, Y>
44where
45    X: Clone + PartialEq + Into<SharedString> + 'static,
46    Y: Clone + Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
47{
48    pub fn new<I>(data: I) -> Self
49    where
50        I: IntoIterator<Item = T>,
51    {
52        Self {
53            data: data.into_iter().collect(),
54            stroke_styles: vec![],
55            strokes: vec![],
56            fills: vec![],
57            names: vec![],
58            tick_margin: 1,
59            x: None,
60            y: vec![],
61            x_axis: true,
62            grid: true,
63            id: None,
64        }
65    }
66
67    /// Enable an interactive hover tooltip (crosshair + a dot and row per series).
68    ///
69    /// The `id` must be unique among sibling elements. Without it, the chart stays a
70    /// non-interactive plot.
71    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
72        self.id = Some(id.into());
73        self
74    }
75
76    /// Set the name of the most recently added series, shown in its tooltip row.
77    ///
78    /// Call after the matching [`AreaChart::y`] (e.g. `.y(..).stroke(..).name("Desktop")`).
79    pub fn name(mut self, name: impl Into<SharedString>) -> Self {
80        self.names.push(name.into());
81        self
82    }
83
84    pub fn x(mut self, x: impl Fn(&T) -> X + 'static) -> Self {
85        self.x = Some(Rc::new(x));
86        self
87    }
88
89    pub fn y(mut self, y: impl Fn(&T) -> Y + 'static) -> Self {
90        self.y.push(Rc::new(y));
91        self
92    }
93
94    pub fn stroke(mut self, stroke: impl Into<Hsla>) -> Self {
95        self.strokes.push(stroke.into());
96        self
97    }
98
99    pub fn fill(mut self, fill: impl Into<Background>) -> Self {
100        self.fills.push(fill.into());
101        self
102    }
103
104    pub fn natural(mut self) -> Self {
105        self.stroke_styles.push(StrokeStyle::Natural);
106        self
107    }
108
109    pub fn linear(mut self) -> Self {
110        self.stroke_styles.push(StrokeStyle::Linear);
111        self
112    }
113
114    pub fn step_after(mut self) -> Self {
115        self.stroke_styles.push(StrokeStyle::StepAfter);
116        self
117    }
118
119    pub fn tick_margin(mut self, tick_margin: usize) -> Self {
120        self.tick_margin = tick_margin;
121        self
122    }
123
124    /// Show or hide the x-axis line and labels.
125    ///
126    /// Default is true.
127    pub fn x_axis(mut self, x_axis: bool) -> Self {
128        self.x_axis = x_axis;
129        self
130    }
131
132    pub fn grid(mut self, grid: bool) -> Self {
133        self.grid = grid;
134        self
135    }
136
137    /// Build the x (point) and y (linear) scales for the given bounds.
138    ///
139    /// Shared by `paint` and `tooltip_state` so the two stay in sync. Returns `None` when there
140    /// is no x accessor or no series.
141    fn scales(&self, bounds: Bounds<Pixels>) -> Option<(ScalePoint<X>, ScaleLinear<Y>)> {
142        let x_fn = self.x.as_ref()?;
143        if self.y.is_empty() {
144            return None;
145        }
146
147        let width = bounds.size.width.as_f32();
148        let axis_gap = if self.x_axis { AXIS_GAP } else { 0. };
149        let height = bounds.size.height.as_f32() - axis_gap;
150
151        let x = ScalePoint::new(self.data.iter().map(|v| x_fn(v)).collect(), vec![0., width]);
152        let domain = self
153            .data
154            .iter()
155            .flat_map(|v| self.y.iter().map(|y_fn| y_fn(v)))
156            .chain(Some(Y::zero()))
157            .collect::<Vec<_>>();
158        let y = ScaleLinear::new(domain, vec![height, 10.]);
159
160        Some((x, y))
161    }
162}
163
164impl<T, X, Y> Plot for AreaChart<T, X, Y>
165where
166    X: Clone + PartialEq + Into<SharedString> + 'static,
167    Y: Clone + Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
168{
169    fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
170        let Some(x_fn) = self.x.as_ref() else {
171            return;
172        };
173        let Some((x, y)) = self.scales(bounds) else {
174            return;
175        };
176
177        let axis_gap = if self.x_axis { AXIS_GAP } else { 0. };
178        let height = bounds.size.height.as_f32() - axis_gap;
179
180        // Draw X axis
181        let mut axis = PlotAxis::new().stroke(cx.theme().border);
182        if self.x_axis {
183            let labels = build_point_x_labels(
184                &self.data,
185                x_fn.as_ref(),
186                &x,
187                self.tick_margin,
188                cx.theme().muted_foreground,
189            );
190            axis = axis.x(height).x_label(labels);
191        }
192        axis.paint(&bounds, window, cx);
193
194        // Draw grid
195        if self.grid {
196            Grid::new()
197                .y((0..=3).map(|i| height * i as f32 / 4.0).collect())
198                .stroke(cx.theme().border)
199                .dash_array(&[px(4.), px(2.)])
200                .paint(&bounds, window);
201        }
202
203        // Draw area
204        for (i, y_fn) in self.y.iter().enumerate() {
205            let x = x.clone();
206            let y = y.clone();
207            let x_fn = x_fn.clone();
208            let y_fn = y_fn.clone();
209
210            let fill = *self
211                .fills
212                .get(i)
213                .unwrap_or(&cx.theme().chart_2.opacity(0.4).into());
214
215            let stroke = *self.strokes.get(i).unwrap_or(&cx.theme().chart_2);
216
217            let stroke_style = *self
218                .stroke_styles
219                .get(i)
220                .unwrap_or(self.stroke_styles.first().unwrap_or(&Default::default()));
221
222            Area::new()
223                .data(&self.data)
224                .x(move |d| x.tick(&x_fn(d)))
225                .y0(height)
226                .y1(move |d| y.tick(&y_fn(d)))
227                .stroke(stroke)
228                .stroke_style(stroke_style)
229                .fill(fill)
230                .paint(&bounds, window);
231        }
232    }
233
234    fn id(&self) -> Option<ElementId> {
235        self.id.clone()
236    }
237
238    fn tooltip_state(
239        &self,
240        position: Point<Pixels>,
241        bounds: Bounds<Pixels>,
242        _cx: &App,
243    ) -> Option<TooltipState> {
244        let x_fn = self.x.as_ref()?;
245        let (x, y) = self.scales(bounds)?;
246
247        // Ignore the x-axis label gutter so hovering the labels doesn't show a tooltip.
248        let axis_gap = if self.x_axis { AXIS_GAP } else { 0. };
249        if position.y.as_f32() > bounds.size.height.as_f32() - axis_gap {
250            return None;
251        }
252
253        let index = x.least_index(position.x.as_f32());
254        let d = self.data.get(index)?;
255        let x_tick = x.tick(&x_fn(d))?;
256
257        // One dot per series at the hovered x.
258        let dots = self
259            .y
260            .iter()
261            .filter_map(|y_fn| Some(point(px(x_tick), px(y.tick(&y_fn(d))?))))
262            .collect();
263
264        Some(TooltipState::new(
265            index,
266            point(px(x_tick), position.y),
267            dots,
268        ))
269    }
270
271    fn tooltip(
272        &self,
273        state: &TooltipState,
274        cursor: Point<Pixels>,
275        bounds: Bounds<Pixels>,
276        _window: &mut Window,
277        cx: &mut App,
278    ) -> Option<AnyElement> {
279        let x_fn = self.x.as_ref()?;
280        let d = self.data.get(state.index)?;
281        let title: SharedString = x_fn(d).into();
282
283        let default_color = cx.theme().chart_2;
284        let dot_stroke = cx.theme().background;
285        let color = |i: usize| *self.strokes.get(i).unwrap_or(&default_color);
286
287        // Follow the cursor; the crosshair and dots stay snapped to the data point.
288        let mut tooltip = Tooltip::new(cursor, bounds.size)
289            .gap(px(8.))
290            // Confine the crosshair to the plot area so it doesn't cross the x-axis.
291            .cross_line(
292                CrossLine::new(state.cross_line)
293                    .height(bounds.size.height.as_f32() - if self.x_axis { AXIS_GAP } else { 0. }),
294            )
295            .dots(
296                state
297                    .dots
298                    .iter()
299                    .enumerate()
300                    .map(|(i, p)| Dot::new(*p).stroke(dot_stroke).fill(color(i))),
301            )
302            .title(title);
303
304        // One row per series: swatch + label + value.
305        for (i, y_fn) in self.y.iter().enumerate() {
306            let name = self.names.get(i).cloned().unwrap_or_default();
307            let value = y_fn(d).to_f64()?;
308            tooltip = tooltip.row(color(i), name, format!("{}", value));
309        }
310
311        Some(tooltip.into_any_element())
312    }
313}