Skip to main content

fc_ui/capabilities/data/
line_chart.rs

1use crate::capabilities::data::{
2    chart::{is_finite_data_point, DataPoint, DataRange},
3    palette::default_color,
4};
5use crate::capabilities::foundation::theme::use_theme;
6use gpui::{prelude::FluentBuilder as _, *};
7
8#[derive(Clone, Debug)]
9pub struct LineChartPoint {
10    pub x: f64,
11    pub y: f64,
12    pub label: Option<SharedString>,
13}
14
15impl LineChartPoint {
16    pub fn new(x: f64, y: f64) -> Self {
17        Self { x, y, label: None }
18    }
19
20    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
21        self.label = Some(label.into());
22        self
23    }
24}
25
26#[derive(Clone, Debug)]
27pub struct LineChartSeries {
28    pub name: SharedString,
29    pub points: Vec<LineChartPoint>,
30    pub color: Option<Hsla>,
31    pub show_points: bool,
32    pub fill_area: bool,
33}
34
35impl LineChartSeries {
36    pub fn new(name: impl Into<SharedString>, points: Vec<LineChartPoint>) -> Self {
37        Self {
38            name: name.into(),
39            points,
40            color: None,
41            show_points: false,
42            fill_area: false,
43        }
44    }
45
46    pub fn color(mut self, color: Hsla) -> Self {
47        self.color = Some(color);
48        self
49    }
50
51    pub fn show_points(mut self, show: bool) -> Self {
52        self.show_points = show;
53        self
54    }
55
56    pub fn fill_area(mut self, fill: bool) -> Self {
57        self.fill_area = fill;
58        self
59    }
60}
61
62fn range_from_series(
63    series: &[LineChartSeries],
64    y_min_override: Option<f64>,
65    y_max_override: Option<f64>,
66) -> DataRange {
67    let points: Vec<_> = series
68        .iter()
69        .flat_map(|series| series.points.iter())
70        .map(|point| DataPoint::new(point.x, point.y))
71        .collect();
72    let range = DataRange::from_points(&points);
73    let y_min = y_min_override
74        .filter(|value| value.is_finite())
75        .unwrap_or(range.y_min);
76    let y_max = y_max_override
77        .filter(|value| value.is_finite())
78        .unwrap_or(range.y_max);
79
80    DataRange::new(range.x_min, range.x_max, y_min, y_max)
81}
82
83#[derive(IntoElement)]
84pub struct LineChart {
85    series: Vec<LineChartSeries>,
86    show_grid: bool,
87    show_x_axis: bool,
88    show_y_axis: bool,
89    x_axis_labels: Vec<SharedString>,
90    y_min: Option<f64>,
91    y_max: Option<f64>,
92    smooth: bool,
93    show_legend: bool,
94    style: StyleRefinement,
95}
96
97impl LineChart {
98    pub fn new(series: Vec<LineChartSeries>) -> Self {
99        Self {
100            series,
101            show_grid: true,
102            show_x_axis: true,
103            show_y_axis: true,
104            x_axis_labels: Vec::new(),
105            y_min: None,
106            y_max: None,
107            smooth: false,
108            show_legend: true,
109            style: StyleRefinement::default(),
110        }
111    }
112
113    pub fn single(series: LineChartSeries) -> Self {
114        Self::new(vec![series])
115    }
116
117    pub fn show_grid(mut self, show: bool) -> Self {
118        self.show_grid = show;
119        self
120    }
121
122    pub fn show_x_axis(mut self, show: bool) -> Self {
123        self.show_x_axis = show;
124        self
125    }
126
127    pub fn show_y_axis(mut self, show: bool) -> Self {
128        self.show_y_axis = show;
129        self
130    }
131
132    pub fn smooth(mut self, smooth: bool) -> Self {
133        self.smooth = smooth;
134        self
135    }
136
137    pub fn y_range(mut self, min: f64, max: f64) -> Self {
138        self.y_min = Some(min);
139        self.y_max = Some(max);
140        self
141    }
142
143    pub fn x_labels(mut self, labels: Vec<impl Into<SharedString>>) -> Self {
144        self.x_axis_labels = labels.into_iter().map(|l| l.into()).collect();
145        self
146    }
147
148    pub fn show_legend(mut self, show: bool) -> Self {
149        self.show_legend = show;
150        self
151    }
152}
153
154impl Styled for LineChart {
155    fn style(&mut self) -> &mut StyleRefinement {
156        &mut self.style
157    }
158}
159
160fn format_y_value(value: f64) -> String {
161    if value.abs() >= 1000.0 {
162        format!("{:.0}k", value / 1000.0)
163    } else if value.abs() >= 1.0 {
164        format!("{:.0}", value)
165    } else {
166        format!("{:.2}", value)
167    }
168}
169
170struct PaintData {
171    series: Vec<LineChartSeries>,
172    show_grid: bool,
173    smooth: bool,
174    y_min: Option<f64>,
175    y_max: Option<f64>,
176    grid_color: Hsla,
177    padding_left: f32,
178    padding_right: f32,
179    padding_top: f32,
180    padding_bottom: f32,
181}
182
183impl RenderOnce for LineChart {
184    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
185        let theme = use_theme(cx);
186        let user_style = self.style;
187
188        let series = self.series.clone();
189        let show_grid = self.show_grid;
190        let show_x_axis = self.show_x_axis;
191        let show_y_axis = self.show_y_axis;
192        let smooth = self.smooth;
193        let y_min = self.y_min;
194        let y_max = self.y_max;
195        let x_axis_labels = self.x_axis_labels.clone();
196
197        let grid_color = theme.tokens.border;
198        let text_color = theme.tokens.muted_foreground;
199
200        let padding_left: f32 = if show_y_axis { 50.0 } else { 10.0 };
201        let padding_right: f32 = 20.0;
202        let padding_top: f32 = 20.0;
203        let padding_bottom: f32 = if show_x_axis { 40.0 } else { 10.0 };
204
205        let series_for_legend = series.clone();
206
207        let data_range = range_from_series(&series, y_min, y_max);
208
209        let y_labels: Vec<String> = if show_y_axis {
210            (0..=5)
211                .map(|i| {
212                    let normalized = i as f64 / 5.0;
213                    let value = data_range.y_min
214                        + (data_range.y_max - data_range.y_min) * (1.0 - normalized);
215                    format_y_value(value)
216                })
217                .collect()
218        } else {
219            Vec::new()
220        };
221
222        let paint_data = PaintData {
223            series,
224            show_grid,
225            smooth,
226            y_min,
227            y_max,
228            grid_color,
229            padding_left,
230            padding_right,
231            padding_top,
232            padding_bottom,
233        };
234
235        div()
236            .flex()
237            .flex_col()
238            .size_full()
239            .map(|this| {
240                let mut d = this;
241                d.style().refine(&user_style);
242                d
243            })
244            .child(
245                div()
246                    .flex_1()
247                    .min_h(px(200.0))
248                    .relative()
249                    .child(
250                        canvas(
251                            move |_bounds, _window, _cx| paint_data,
252                            move |bounds, paint_data, window, _cx| {
253                                if bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
254                                    return;
255                                }
256
257                                let data_range = range_from_series(
258                                    &paint_data.series,
259                                    paint_data.y_min,
260                                    paint_data.y_max,
261                                );
262
263                                let chart_left = bounds.left() + px(paint_data.padding_left);
264                                let chart_right = bounds.right() - px(paint_data.padding_right);
265                                let chart_top = bounds.top() + px(paint_data.padding_top);
266                                let chart_bottom = bounds.bottom() - px(paint_data.padding_bottom);
267                                let chart_width = chart_right - chart_left;
268                                let chart_height = chart_bottom - chart_top;
269
270                                if chart_width <= px(0.0) || chart_height <= px(0.0) {
271                                    return;
272                                }
273
274                                if paint_data.show_grid {
275                                    let grid_lines = 5;
276                                    for i in 0..=grid_lines {
277                                        let y = chart_top
278                                            + chart_height * (i as f32 / grid_lines as f32);
279                                        let mut builder = PathBuilder::stroke(px(1.0));
280                                        builder.move_to(point(chart_left, y));
281                                        builder.line_to(point(chart_right, y));
282                                        if let Ok(path) = builder.build() {
283                                            window.paint_path(
284                                                path,
285                                                paint_data.grid_color.opacity(0.3),
286                                            );
287                                        }
288                                    }
289
290                                    for i in 0..=grid_lines {
291                                        let x = chart_left
292                                            + chart_width * (i as f32 / grid_lines as f32);
293                                        let mut builder = PathBuilder::stroke(px(1.0));
294                                        builder.move_to(point(x, chart_top));
295                                        builder.line_to(point(x, chart_bottom));
296                                        if let Ok(path) = builder.build() {
297                                            window.paint_path(
298                                                path,
299                                                paint_data.grid_color.opacity(0.3),
300                                            );
301                                        }
302                                    }
303                                }
304
305                                for (series_index, s) in paint_data.series.iter().enumerate() {
306                                    if s.points.is_empty() {
307                                        continue;
308                                    }
309
310                                    let color =
311                                        s.color.unwrap_or_else(|| default_color(series_index));
312
313                                    let screen_points: Vec<Point<Pixels>> = s
314                                        .points
315                                        .iter()
316                                        .filter(|point| is_finite_data_point(point.x, point.y))
317                                        .map(|p| {
318                                            let norm_x = data_range.normalize_x(p.x);
319                                            let norm_y = data_range.normalize_y(p.y);
320                                            let screen_x = chart_left + chart_width * norm_x;
321                                            let screen_y = chart_bottom - chart_height * norm_y;
322                                            point(screen_x, screen_y)
323                                        })
324                                        .collect();
325
326                                    if s.fill_area && screen_points.len() >= 2 {
327                                        let mut builder = PathBuilder::fill();
328                                        builder.move_to(point(screen_points[0].x, chart_bottom));
329                                        builder.line_to(screen_points[0]);
330
331                                        for pt in screen_points.iter().skip(1) {
332                                            builder.line_to(*pt);
333                                        }
334
335                                        builder.line_to(point(
336                                            screen_points.last().unwrap().x,
337                                            chart_bottom,
338                                        ));
339                                        builder.close();
340
341                                        if let Ok(path) = builder.build() {
342                                            window.paint_path(path, color.opacity(0.15));
343                                        }
344                                    }
345
346                                    if screen_points.len() >= 2 {
347                                        let mut builder = PathBuilder::stroke(px(2.0));
348                                        builder.move_to(screen_points[0]);
349
350                                        if paint_data.smooth && screen_points.len() >= 3 {
351                                            for i in 0..screen_points.len() - 1 {
352                                                let p0 = screen_points[i];
353                                                let p1 = screen_points[i + 1];
354                                                let ctrl_x = (p0.x + p1.x) * 0.5;
355                                                builder.curve_to(p1, point(ctrl_x, p0.y));
356                                            }
357                                        } else {
358                                            for pt in screen_points.iter().skip(1) {
359                                                builder.line_to(*pt);
360                                            }
361                                        }
362
363                                        if let Ok(path) = builder.build() {
364                                            window.paint_path(path, color);
365                                        }
366                                    }
367
368                                    if s.show_points {
369                                        let point_radius = px(4.0);
370                                        for pt in &screen_points {
371                                            window.paint_quad(fill(
372                                                Bounds::centered_at(
373                                                    *pt,
374                                                    size(point_radius * 2.0, point_radius * 2.0),
375                                                ),
376                                                color,
377                                            ));
378                                        }
379                                    }
380                                }
381                            },
382                        )
383                        .size_full(),
384                    )
385                    .when(show_y_axis, |this| {
386                        this.children(y_labels.iter().enumerate().map(|(i, label)| {
387                            let top_percent = (i as f32 / 5.0) * 100.0;
388                            div()
389                                .absolute()
390                                .left(px(4.0))
391                                .top(relative(top_percent / 100.0))
392                                .mt(px(padding_top - 6.0))
393                                .text_size(px(11.0))
394                                .text_color(text_color)
395                                .child(label.clone())
396                        }))
397                    })
398                    .when(show_x_axis && !x_axis_labels.is_empty(), |this| {
399                        let num_labels = x_axis_labels.len();
400                        this.children(x_axis_labels.iter().enumerate().map(|(i, label)| {
401                            let left_percent = if num_labels == 1 {
402                                50.0
403                            } else {
404                                (i as f32 / (num_labels - 1) as f32) * 100.0
405                            };
406                            let chart_width_percent =
407                                (100.0 - padding_left / 4.0 - padding_right / 4.0) / 100.0;
408                            let adjusted_left =
409                                padding_left / 4.0 + left_percent * chart_width_percent;
410                            div()
411                                .absolute()
412                                .bottom(px(8.0))
413                                .left(relative(adjusted_left / 100.0))
414                                .ml(px(-15.0))
415                                .text_size(px(11.0))
416                                .text_color(text_color)
417                                .child(label.clone())
418                        }))
419                    }),
420            )
421            .when(self.show_legend && series_for_legend.len() > 1, |this| {
422                this.child(
423                    div()
424                        .flex()
425                        .flex_wrap()
426                        .gap(px(16.0))
427                        .px(px(padding_left))
428                        .py(px(8.0))
429                        .children(series_for_legend.iter().enumerate().map(|(i, s)| {
430                            let color = s.color.unwrap_or_else(|| default_color(i));
431                            div()
432                                .flex()
433                                .items_center()
434                                .gap(px(6.0))
435                                .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
436                                .child(div().text_sm().text_color(text_color).child(s.name.clone()))
437                        })),
438                )
439            })
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::{range_from_series, LineChartPoint, LineChartSeries};
446
447    fn series(points: &[(f64, f64)]) -> Vec<LineChartSeries> {
448        vec![LineChartSeries::new(
449            "series",
450            points
451                .iter()
452                .map(|&(x, y)| LineChartPoint::new(x, y))
453                .collect(),
454        )]
455    }
456
457    #[test]
458    fn range_ignores_non_finite_points_and_overrides() {
459        let range = range_from_series(
460            &series(&[
461                (0.0, 1.0),
462                (f64::NAN, 2.0),
463                (1.0, f64::INFINITY),
464                (2.0, 3.0),
465            ]),
466            Some(f64::NEG_INFINITY),
467            Some(f64::NAN),
468        );
469
470        assert_eq!(
471            (range.x_min, range.x_max, range.y_min, range.y_max),
472            (0.0, 2.0, 1.0, 3.0)
473        );
474        assert!(range.normalize_x(f64::NAN).is_finite());
475        assert!(range.normalize_y(f64::INFINITY).is_finite());
476    }
477}