gpui_component/chart/
line_chart.rs

1use std::rc::Rc;
2
3use gpui::{px, App, Bounds, Hsla, Pixels, SharedString, TextAlign, Window};
4use gpui_component_macros::IntoPlot;
5use num_traits::{Num, ToPrimitive};
6
7use crate::{
8    plot::{
9        scale::{Scale, ScaleLinear, ScalePoint, Sealed},
10        shape::Line,
11        Axis, AxisText, Grid, Plot, StrokeStyle, AXIS_GAP,
12    },
13    ActiveTheme, PixelsExt,
14};
15
16#[derive(IntoPlot)]
17pub struct LineChart<T, X, Y>
18where
19    T: 'static,
20    X: PartialEq + Into<SharedString> + 'static,
21    Y: Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
22{
23    data: Vec<T>,
24    x: Option<Rc<dyn Fn(&T) -> X>>,
25    y: Option<Rc<dyn Fn(&T) -> Y>>,
26    stroke: Option<Hsla>,
27    stroke_style: StrokeStyle,
28    dot: bool,
29    tick_margin: usize,
30}
31
32impl<T, X, Y> LineChart<T, X, Y>
33where
34    X: PartialEq + Into<SharedString> + 'static,
35    Y: Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
36{
37    pub fn new<I>(data: I) -> Self
38    where
39        I: IntoIterator<Item = T>,
40    {
41        Self {
42            data: data.into_iter().collect(),
43            stroke: None,
44            stroke_style: Default::default(),
45            dot: false,
46            x: None,
47            y: None,
48            tick_margin: 1,
49        }
50    }
51
52    pub fn x(mut self, x: impl Fn(&T) -> X + 'static) -> Self {
53        self.x = Some(Rc::new(x));
54        self
55    }
56
57    pub fn y(mut self, y: impl Fn(&T) -> Y + 'static) -> Self {
58        self.y = Some(Rc::new(y));
59        self
60    }
61
62    pub fn linear(mut self) -> Self {
63        self.stroke_style = StrokeStyle::Linear;
64        self
65    }
66
67    pub fn dot(mut self) -> Self {
68        self.dot = true;
69        self
70    }
71
72    pub fn tick_margin(mut self, tick_margin: usize) -> Self {
73        self.tick_margin = tick_margin;
74        self
75    }
76}
77
78impl<T, X, Y> Plot for LineChart<T, X, Y>
79where
80    X: PartialEq + Into<SharedString> + 'static,
81    Y: Copy + PartialOrd + Num + ToPrimitive + Sealed + 'static,
82{
83    fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
84        let (Some(x_fn), Some(y_fn)) = (self.x.as_ref(), self.y.as_ref()) else {
85            return;
86        };
87
88        let width = bounds.size.width.as_f32();
89        let height = bounds.size.height.as_f32() - AXIS_GAP;
90
91        // X scale
92        let x = ScalePoint::new(self.data.iter().map(|v| x_fn(v)).collect(), vec![0., width]);
93
94        // Y scale, ensure start from 0.
95        let y = ScaleLinear::new(
96            self.data
97                .iter()
98                .map(|v| y_fn(v))
99                .chain(Some(Y::zero()))
100                .collect(),
101            vec![height, 10.],
102        );
103
104        // Draw X axis
105        let data_len = self.data.len();
106        let x_label = self.data.iter().enumerate().filter_map(|(i, d)| {
107            if (i + 1) % self.tick_margin == 0 {
108                x.tick(&x_fn(d)).map(|x_tick| {
109                    let align = match i {
110                        0 => {
111                            if data_len == 1 {
112                                TextAlign::Center
113                            } else {
114                                TextAlign::Left
115                            }
116                        }
117                        i if i == data_len - 1 => TextAlign::Right,
118                        _ => TextAlign::Center,
119                    };
120                    AxisText::new(x_fn(d).into(), x_tick, cx.theme().muted_foreground).align(align)
121                })
122            } else {
123                None
124            }
125        });
126
127        Axis::new()
128            .x(height)
129            .x_label(x_label)
130            .stroke(cx.theme().border)
131            .paint(&bounds, window, cx);
132
133        // Draw grid
134        Grid::new()
135            .y((0..=3).map(|i| height * i as f32 / 4.0).collect())
136            .stroke(cx.theme().border)
137            .dash_array(&[px(4.), px(2.)])
138            .paint(&bounds, window);
139
140        // Draw line
141        let stroke = self.stroke.unwrap_or(cx.theme().chart_2);
142        let x_fn = x_fn.clone();
143        let y_fn = y_fn.clone();
144        let mut line = Line::new()
145            .data(&self.data)
146            .x(move |d| x.tick(&x_fn(d)))
147            .y(move |d| y.tick(&y_fn(d)))
148            .stroke(stroke)
149            .stroke_style(self.stroke_style)
150            .stroke_width(2.);
151
152        if self.dot {
153            line = line.dot().dot_size(8.).dot_fill_color(stroke);
154        }
155
156        line.paint(&bounds, window);
157    }
158}