Skip to main content

fc_ui/capabilities/data/
bar_chart.rs

1use crate::capabilities::data::palette::default_color;
2use crate::capabilities::foundation::theme::use_theme;
3use gpui::{prelude::FluentBuilder as _, *};
4
5fn pixels_to_f32(p: Pixels) -> f32 {
6    p / px(1.0)
7}
8
9fn finite_or_zero(value: f64) -> f64 {
10    if value.is_finite() {
11        value
12    } else {
13        0.0
14    }
15}
16
17#[derive(Clone, Copy)]
18struct ValueDomain {
19    min: f64,
20    max: f64,
21    span: f64,
22    zero_ratio: f32,
23}
24
25impl ValueDomain {
26    fn from_values(values: impl IntoIterator<Item = f64>) -> Self {
27        let (min, max) = values
28            .into_iter()
29            .map(finite_or_zero)
30            .fold((0.0_f64, 0.0_f64), |(min, max), value| {
31                (min.min(value), max.max(value))
32            });
33        let span = (max - min).max(f64::EPSILON);
34        Self {
35            min,
36            max,
37            span,
38            zero_ratio: (max / span) as f32,
39        }
40    }
41
42    fn vertical_y(self, value: f64, height: Pixels) -> Pixels {
43        height * ((self.max - finite_or_zero(value)) / self.span) as f32
44    }
45
46    fn vertical_segment(self, start: f64, end: f64, height: Pixels) -> (Pixels, Pixels) {
47        let start_y = self.vertical_y(start, height);
48        let end_y = self.vertical_y(end, height);
49        (start_y.min(end_y), (start_y - end_y).abs())
50    }
51
52    fn horizontal_x(self, value: f64) -> f32 {
53        ((finite_or_zero(value) - self.min) / self.span) as f32
54    }
55
56    fn horizontal_segment(self, start: f64, end: f64) -> (f32, f32) {
57        let start_x = self.horizontal_x(start);
58        let end_x = self.horizontal_x(end);
59        (start_x.min(end_x), (start_x - end_x).abs())
60    }
61
62    fn zero_y(self, height: Pixels) -> Pixels {
63        height * self.zero_ratio
64    }
65}
66
67fn stacked_domain(series: &[BarChartSeries], label_count: usize) -> ValueDomain {
68    ValueDomain::from_values((0..label_count).flat_map(|index| {
69        let mut positive = 0.0;
70        let mut negative = 0.0;
71        for value in series {
72            let value = finite_or_zero(value.data.get(index).copied().unwrap_or(0.0));
73            if value >= 0.0 {
74                positive += value;
75            } else {
76                negative += value;
77            }
78        }
79        [positive, negative]
80    }))
81}
82
83#[derive(Clone)]
84pub struct BarChartData {
85    pub label: SharedString,
86    /// Finite values are rendered around a zero axis. Non-finite values are
87    /// treated as zero.
88    pub value: f64,
89    pub color: Option<Hsla>,
90}
91
92impl BarChartData {
93    pub fn new(label: impl Into<SharedString>, value: f64) -> Self {
94        Self {
95            label: label.into(),
96            value,
97            color: None,
98        }
99    }
100
101    pub fn color(mut self, color: Hsla) -> Self {
102        self.color = Some(color);
103        self
104    }
105}
106
107#[derive(Clone)]
108pub struct BarChartSeries {
109    pub name: SharedString,
110    /// Finite values are rendered around a zero axis. Non-finite values render
111    /// as 0.
112    pub data: Vec<f64>,
113    pub color: Option<Hsla>,
114}
115
116impl BarChartSeries {
117    pub fn new(name: impl Into<SharedString>, data: Vec<f64>) -> Self {
118        Self {
119            name: name.into(),
120            data,
121            color: None,
122        }
123    }
124
125    pub fn color(mut self, color: Hsla) -> Self {
126        self.color = Some(color);
127        self
128    }
129}
130
131#[derive(Copy, Clone, Default, PartialEq, Eq)]
132pub enum BarChartOrientation {
133    #[default]
134    Vertical,
135    Horizontal,
136}
137
138#[derive(Copy, Clone, Default, PartialEq, Eq)]
139pub enum BarChartMode {
140    #[default]
141    Single,
142    Grouped,
143    Stacked,
144}
145
146#[derive(IntoElement)]
147pub struct BarChart {
148    data: Vec<BarChartData>,
149    series: Vec<BarChartSeries>,
150    labels: Vec<SharedString>,
151    orientation: BarChartOrientation,
152    mode: BarChartMode,
153    show_values: bool,
154    show_grid: bool,
155    show_legend: bool,
156    show_axis_labels: bool,
157    bar_width: Option<Pixels>,
158    gap: Pixels,
159    height: Pixels,
160    style: StyleRefinement,
161}
162
163impl BarChart {
164    pub fn new(data: Vec<BarChartData>) -> Self {
165        Self {
166            data,
167            series: Vec::new(),
168            labels: Vec::new(),
169            orientation: BarChartOrientation::default(),
170            mode: BarChartMode::Single,
171            show_values: false,
172            show_grid: false,
173            show_legend: false,
174            show_axis_labels: true,
175            bar_width: None,
176            gap: px(8.0),
177            height: px(300.0),
178            style: StyleRefinement::default(),
179        }
180    }
181
182    pub fn multi_series(labels: Vec<impl Into<SharedString>>, series: Vec<BarChartSeries>) -> Self {
183        Self {
184            data: Vec::new(),
185            series,
186            labels: labels.into_iter().map(|l| l.into()).collect(),
187            orientation: BarChartOrientation::default(),
188            mode: BarChartMode::Grouped,
189            show_values: false,
190            show_grid: false,
191            show_legend: true,
192            show_axis_labels: true,
193            bar_width: None,
194            gap: px(8.0),
195            height: px(300.0),
196            style: StyleRefinement::default(),
197        }
198    }
199
200    pub fn vertical(mut self) -> Self {
201        self.orientation = BarChartOrientation::Vertical;
202        self
203    }
204
205    pub fn horizontal(mut self) -> Self {
206        self.orientation = BarChartOrientation::Horizontal;
207        self
208    }
209
210    pub fn orientation(mut self, orientation: BarChartOrientation) -> Self {
211        self.orientation = orientation;
212        self
213    }
214
215    pub fn stacked(mut self) -> Self {
216        self.mode = BarChartMode::Stacked;
217        self
218    }
219
220    pub fn grouped(mut self) -> Self {
221        self.mode = BarChartMode::Grouped;
222        self
223    }
224
225    pub fn mode(mut self, mode: BarChartMode) -> Self {
226        self.mode = mode;
227        self
228    }
229
230    pub fn show_values(mut self, show: bool) -> Self {
231        self.show_values = show;
232        self
233    }
234
235    pub fn show_grid(mut self, show: bool) -> Self {
236        self.show_grid = show;
237        self
238    }
239
240    pub fn show_legend(mut self, show: bool) -> Self {
241        self.show_legend = show;
242        self
243    }
244
245    pub fn show_axis_labels(mut self, show: bool) -> Self {
246        self.show_axis_labels = show;
247        self
248    }
249
250    pub fn bar_width(mut self, width: Pixels) -> Self {
251        self.bar_width = Some(width);
252        self
253    }
254
255    pub fn gap(mut self, gap: Pixels) -> Self {
256        self.gap = gap;
257        self
258    }
259
260    pub fn chart_height(mut self, height: Pixels) -> Self {
261        self.height = height;
262        self
263    }
264
265    fn render_single_vertical(self, theme: &crate::capabilities::foundation::theme::Theme) -> Div {
266        let domain = ValueDomain::from_values(self.data.iter().map(|d| d.value));
267
268        let chart_height = self.height;
269        let bar_width = self.bar_width.unwrap_or(px(40.0));
270        let gap = self.gap;
271        let show_values = self.show_values;
272        let show_grid = self.show_grid;
273        let show_axis_labels = self.show_axis_labels;
274
275        let grid_lines = if show_grid {
276            Some(
277                div()
278                    .absolute()
279                    .inset_0()
280                    .flex()
281                    .flex_col()
282                    .justify_between()
283                    .children((0..5).map(|_| {
284                        div()
285                            .w_full()
286                            .h(px(1.0))
287                            .bg(theme.tokens.border.opacity(0.3))
288                    })),
289            )
290        } else {
291            None
292        };
293
294        div()
295            .flex()
296            .flex_col()
297            .gap(px(8.0))
298            .child(
299                div()
300                    .relative()
301                    .h(chart_height)
302                    .w_full()
303                    .when_some(grid_lines, |this, grid| this.child(grid))
304                    .child(
305                        div()
306                            .relative()
307                            .h_full()
308                            .w_full()
309                            .flex()
310                            .items_end()
311                            .justify_around()
312                            .gap(gap)
313                            .px(px(16.0))
314                            .child(
315                                div()
316                                    .absolute()
317                                    .left_0()
318                                    .right_0()
319                                    .top(domain.zero_y(chart_height))
320                                    .h(px(1.0))
321                                    .bg(theme.tokens.border.opacity(0.7)),
322                            )
323                            .children(self.data.iter().enumerate().map(|(i, item)| {
324                                let value = finite_or_zero(item.value);
325                                let (top, bar_height) =
326                                    domain.vertical_segment(0.0, value, chart_height);
327                                let label_top = if value >= 0.0 {
328                                    top - px(18.0)
329                                } else {
330                                    top + bar_height + px(2.0)
331                                };
332                                let bar_color = item.color.unwrap_or_else(|| default_color(i));
333
334                                div()
335                                    .flex_1()
336                                    .h_full()
337                                    .flex()
338                                    .justify_center()
339                                    .child(
340                                        div().relative().w(bar_width).h_full().child(
341                                            div()
342                                                .absolute()
343                                                .left_0()
344                                                .right_0()
345                                                .top(top)
346                                                .h(bar_height)
347                                                .bg(bar_color)
348                                                .rounded(theme.tokens.radius_sm),
349                                        ),
350                                    )
351                                    .when(show_values, |this| {
352                                        this.child(
353                                            div()
354                                                .absolute()
355                                                .top(label_top)
356                                                .left_0()
357                                                .right_0()
358                                                .text_xs()
359                                                .text_color(theme.tokens.muted_foreground)
360                                                .text_center()
361                                                .child(format!("{:.0}", value)),
362                                        )
363                                    })
364                            })),
365                    ),
366            )
367            .when(show_axis_labels, |this| {
368                this.child(div().flex().justify_around().px(px(16.0)).children(
369                    self.data.iter().map(|item| {
370                        div()
371                            .text_xs()
372                            .text_color(theme.tokens.muted_foreground)
373                            .text_center()
374                            .child(item.label.clone())
375                    }),
376                ))
377            })
378    }
379
380    fn render_single_horizontal(
381        self,
382        theme: &crate::capabilities::foundation::theme::Theme,
383    ) -> Div {
384        let domain = ValueDomain::from_values(self.data.iter().map(|d| d.value));
385
386        let bar_height = self.bar_width.unwrap_or(px(24.0));
387        let gap = self.gap;
388        let show_values = self.show_values;
389        let show_grid = self.show_grid;
390        let show_axis_labels = self.show_axis_labels;
391        let grid_color = theme.tokens.border.opacity(0.3);
392
393        div()
394            .flex()
395            .flex_col()
396            .gap(gap)
397            .children(self.data.iter().enumerate().map(|(i, item)| {
398                let value = finite_or_zero(item.value);
399                let (left, width_percent) = domain.horizontal_segment(0.0, value);
400                let bar_color = item.color.unwrap_or_else(|| default_color(i));
401                let label = item.label.clone();
402
403                div()
404                    .flex()
405                    .items_center()
406                    .gap(px(8.0))
407                    .when(show_axis_labels, |this| {
408                        this.child(
409                            div()
410                                .w(px(80.0))
411                                .text_xs()
412                                .text_color(theme.tokens.muted_foreground)
413                                .text_right()
414                                .overflow_hidden()
415                                .child(label),
416                        )
417                    })
418                    .child(
419                        div()
420                            .flex_1()
421                            .relative()
422                            .h(bar_height)
423                            .child(
424                                div()
425                                    .absolute()
426                                    .top_0()
427                                    .bottom_0()
428                                    .left(relative(domain.zero_ratio))
429                                    .w(px(1.0))
430                                    .bg(theme.tokens.border.opacity(0.7)),
431                            )
432                            .when(show_grid, |this| {
433                                this.child(
434                                    div()
435                                        .absolute()
436                                        .inset_0()
437                                        .flex()
438                                        .justify_between()
439                                        .children(
440                                            (0..5)
441                                                .map(|_| div().h_full().w(px(1.0)).bg(grid_color)),
442                                        ),
443                                )
444                            })
445                            .child({
446                                let width = width_percent;
447                                div()
448                                    .absolute()
449                                    .top_0()
450                                    .bottom_0()
451                                    .left(relative(left))
452                                    .w(relative(width))
453                                    .bg(bar_color)
454                                    .rounded(theme.tokens.radius_sm)
455                            }),
456                    )
457                    .when(show_values, |this| {
458                        this.child(
459                            div()
460                                .w(px(50.0))
461                                .text_xs()
462                                .text_color(theme.tokens.muted_foreground)
463                                .child(format!("{:.0}", value)),
464                        )
465                    })
466            }))
467    }
468
469    fn render_multi_vertical_grouped(
470        self,
471        theme: &crate::capabilities::foundation::theme::Theme,
472    ) -> Div {
473        let domain =
474            ValueDomain::from_values(self.series.iter().flat_map(|s| s.data.iter()).copied());
475
476        let chart_height = self.height;
477        let series_count = self.series.len();
478        let bar_width = self.bar_width.unwrap_or(px(24.0));
479        let single_bar_width = px(pixels_to_f32(bar_width) / series_count.max(1) as f32);
480        let gap = self.gap;
481        let show_values = self.show_values;
482        let show_grid = self.show_grid;
483        let show_axis_labels = self.show_axis_labels;
484        let show_legend = self.show_legend;
485
486        let grid_lines = if show_grid {
487            Some(
488                div()
489                    .absolute()
490                    .inset_0()
491                    .flex()
492                    .flex_col()
493                    .justify_between()
494                    .children((0..5).map(|_| {
495                        div()
496                            .w_full()
497                            .h(px(1.0))
498                            .bg(theme.tokens.border.opacity(0.3))
499                    })),
500            )
501        } else {
502            None
503        };
504
505        let labels = self.labels.clone();
506        let series_for_legend = self.series.clone();
507        let label_count = labels.len();
508
509        div()
510            .flex()
511            .flex_col()
512            .gap(px(16.0))
513            .child(
514                div()
515                    .relative()
516                    .h(chart_height)
517                    .w_full()
518                    .when_some(grid_lines, |this, grid| this.child(grid))
519                    .child(
520                        div()
521                            .h_full()
522                            .w_full()
523                            .flex()
524                            .items_end()
525                            .justify_around()
526                            .gap(gap)
527                            .px(px(16.0))
528                            .child(
529                                div()
530                                    .absolute()
531                                    .left_0()
532                                    .right_0()
533                                    .top(domain.zero_y(chart_height))
534                                    .h(px(1.0))
535                                    .bg(theme.tokens.border.opacity(0.7)),
536                            )
537                            .children((0..label_count).map(|label_idx| {
538                                div().flex().items_end().h_full().gap(px(2.0)).children(
539                                    self.series.iter().enumerate().map(|(series_idx, series)| {
540                                        let value = finite_or_zero(
541                                            series.data.get(label_idx).copied().unwrap_or(0.0),
542                                        );
543                                        let (top, bar_height) =
544                                            domain.vertical_segment(0.0, value, chart_height);
545                                        let label_top = if value >= 0.0 {
546                                            top - px(18.0)
547                                        } else {
548                                            top + bar_height + px(2.0)
549                                        };
550                                        let bar_color = series
551                                            .color
552                                            .unwrap_or_else(|| default_color(series_idx));
553
554                                        div()
555                                            .relative()
556                                            .w(single_bar_width)
557                                            .h_full()
558                                            .child(
559                                                div()
560                                                    .absolute()
561                                                    .left_0()
562                                                    .right_0()
563                                                    .top(top)
564                                                    .h(bar_height)
565                                                    .bg(bar_color)
566                                                    .rounded(theme.tokens.radius_sm),
567                                            )
568                                            .when(show_values, |this| {
569                                                this.child(
570                                                    div()
571                                                        .absolute()
572                                                        .top(label_top)
573                                                        .left_0()
574                                                        .right_0()
575                                                        .text_xs()
576                                                        .text_color(theme.tokens.muted_foreground)
577                                                        .text_center()
578                                                        .child(format!("{:.0}", value)),
579                                                )
580                                            })
581                                    }),
582                                )
583                            })),
584                    ),
585            )
586            .when(show_axis_labels, |this| {
587                this.child(
588                    div()
589                        .flex()
590                        .justify_around()
591                        .px(px(16.0))
592                        .children(labels.iter().map(|label| {
593                            div()
594                                .text_xs()
595                                .text_color(theme.tokens.muted_foreground)
596                                .text_center()
597                                .child(label.clone())
598                        })),
599                )
600            })
601            .when(show_legend, |this| {
602                this.child(
603                    div()
604                        .flex()
605                        .flex_wrap()
606                        .gap(px(16.0))
607                        .justify_center()
608                        .children(series_for_legend.iter().enumerate().map(|(i, s)| {
609                            let color = s.color.unwrap_or_else(|| default_color(i));
610                            div()
611                                .flex()
612                                .items_center()
613                                .gap(px(6.0))
614                                .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
615                                .child(
616                                    div()
617                                        .text_xs()
618                                        .text_color(theme.tokens.muted_foreground)
619                                        .child(s.name.clone()),
620                                )
621                        })),
622                )
623            })
624    }
625
626    fn render_multi_vertical_stacked(
627        self,
628        theme: &crate::capabilities::foundation::theme::Theme,
629    ) -> Div {
630        let label_count = self.labels.len();
631        let domain = stacked_domain(&self.series, label_count);
632
633        let chart_height = self.height;
634        let bar_width = self.bar_width.unwrap_or(px(40.0));
635        let gap = self.gap;
636        let show_values = self.show_values;
637        let show_grid = self.show_grid;
638        let show_axis_labels = self.show_axis_labels;
639        let show_legend = self.show_legend;
640
641        let grid_lines = if show_grid {
642            Some(
643                div()
644                    .absolute()
645                    .inset_0()
646                    .flex()
647                    .flex_col()
648                    .justify_between()
649                    .children((0..5).map(|_| {
650                        div()
651                            .w_full()
652                            .h(px(1.0))
653                            .bg(theme.tokens.border.opacity(0.3))
654                    })),
655            )
656        } else {
657            None
658        };
659
660        let labels = self.labels.clone();
661        let series_for_legend = self.series.clone();
662
663        div()
664            .flex()
665            .flex_col()
666            .gap(px(16.0))
667            .child(
668                div()
669                    .relative()
670                    .h(chart_height)
671                    .w_full()
672                    .when_some(grid_lines, |this, grid| this.child(grid))
673                    .child(
674                        div()
675                            .h_full()
676                            .w_full()
677                            .flex()
678                            .items_end()
679                            .justify_around()
680                            .gap(gap)
681                            .px(px(16.0))
682                            .child(
683                                div()
684                                    .absolute()
685                                    .left_0()
686                                    .right_0()
687                                    .top(domain.zero_y(chart_height))
688                                    .h(px(1.0))
689                                    .bg(theme.tokens.border.opacity(0.7)),
690                            )
691                            .children((0..label_count).map(|label_idx| {
692                                let total_value: f64 = self
693                                    .series
694                                    .iter()
695                                    .map(|series| {
696                                        finite_or_zero(
697                                            series.data.get(label_idx).copied().unwrap_or(0.0),
698                                        )
699                                    })
700                                    .sum();
701                                let mut positive = 0.0;
702                                let mut negative = 0.0;
703
704                                div()
705                                    .flex_1()
706                                    .h_full()
707                                    .flex()
708                                    .justify_center()
709                                    .when(show_values, |this| {
710                                        let label_top = if total_value >= 0.0 {
711                                            domain.zero_y(chart_height) - px(18.0)
712                                        } else {
713                                            domain.zero_y(chart_height) + px(2.0)
714                                        };
715                                        this.child(
716                                            div()
717                                                .absolute()
718                                                .top(label_top)
719                                                .left_0()
720                                                .right_0()
721                                                .text_xs()
722                                                .text_color(theme.tokens.muted_foreground)
723                                                .text_center()
724                                                .child(format!("{:.0}", total_value)),
725                                        )
726                                    })
727                                    .child(div().relative().w(bar_width).h_full().children(
728                                        self.series.iter().enumerate().map(
729                                            |(series_idx, series)| {
730                                                let value = finite_or_zero(
731                                                    series
732                                                        .data
733                                                        .get(label_idx)
734                                                        .copied()
735                                                        .unwrap_or(0.0),
736                                                );
737                                                let (start, end) = if value >= 0.0 {
738                                                    let start = positive;
739                                                    positive += value;
740                                                    (start, positive)
741                                                } else {
742                                                    let start = negative;
743                                                    negative += value;
744                                                    (start, negative)
745                                                };
746                                                let (top, height) = domain.vertical_segment(
747                                                    start,
748                                                    end,
749                                                    chart_height,
750                                                );
751                                                let bar_color = series
752                                                    .color
753                                                    .unwrap_or_else(|| default_color(series_idx));
754
755                                                div()
756                                                    .absolute()
757                                                    .left_0()
758                                                    .right_0()
759                                                    .top(top)
760                                                    .h(height)
761                                                    .bg(bar_color)
762                                            },
763                                        ),
764                                    ))
765                            })),
766                    ),
767            )
768            .when(show_axis_labels, |this| {
769                this.child(
770                    div()
771                        .flex()
772                        .justify_around()
773                        .px(px(16.0))
774                        .children(labels.iter().map(|label| {
775                            div()
776                                .text_xs()
777                                .text_color(theme.tokens.muted_foreground)
778                                .text_center()
779                                .child(label.clone())
780                        })),
781                )
782            })
783            .when(show_legend, |this| {
784                this.child(
785                    div()
786                        .flex()
787                        .flex_wrap()
788                        .gap(px(16.0))
789                        .justify_center()
790                        .children(series_for_legend.iter().enumerate().map(|(i, s)| {
791                            let color = s.color.unwrap_or_else(|| default_color(i));
792                            div()
793                                .flex()
794                                .items_center()
795                                .gap(px(6.0))
796                                .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
797                                .child(
798                                    div()
799                                        .text_xs()
800                                        .text_color(theme.tokens.muted_foreground)
801                                        .child(s.name.clone()),
802                                )
803                        })),
804                )
805            })
806    }
807
808    fn render_multi_horizontal_grouped(
809        self,
810        theme: &crate::capabilities::foundation::theme::Theme,
811    ) -> Div {
812        let domain =
813            ValueDomain::from_values(self.series.iter().flat_map(|s| s.data.iter()).copied());
814
815        let series_count = self.series.len();
816        let bar_height = self.bar_width.unwrap_or(px(16.0));
817        let single_bar_height = px(pixels_to_f32(bar_height) / series_count.max(1) as f32);
818        let gap = self.gap;
819        let show_values = self.show_values;
820        let show_grid = self.show_grid;
821        let show_axis_labels = self.show_axis_labels;
822        let show_legend = self.show_legend;
823        let grid_color = theme.tokens.border.opacity(0.3);
824
825        let labels = self.labels.clone();
826        let series_for_legend = self.series.clone();
827
828        div()
829            .flex()
830            .flex_col()
831            .gap(px(16.0))
832            .child(
833                div()
834                    .flex()
835                    .flex_col()
836                    .gap(gap)
837                    .children(labels.iter().enumerate().map(|(label_idx, label)| {
838                        div()
839                            .flex()
840                            .items_center()
841                            .gap(px(8.0))
842                            .when(show_axis_labels, |this| {
843                                this.child(
844                                    div()
845                                        .w(px(80.0))
846                                        .text_xs()
847                                        .text_color(theme.tokens.muted_foreground)
848                                        .text_right()
849                                        .overflow_hidden()
850                                        .child(label.clone()),
851                                )
852                            })
853                            .child(
854                                div()
855                                    .flex_1()
856                                    .relative()
857                                    .h(bar_height)
858                                    .when(show_grid, |this| {
859                                        this.child(
860                                            div()
861                                                .absolute()
862                                                .inset_0()
863                                                .flex()
864                                                .justify_between()
865                                                .children((0..5).map(|_| {
866                                                    div().h_full().w(px(1.0)).bg(grid_color)
867                                                })),
868                                        )
869                                    })
870                                    .child(
871                                        div()
872                                            .absolute()
873                                            .top_0()
874                                            .bottom_0()
875                                            .left(relative(domain.zero_ratio))
876                                            .w(px(1.0))
877                                            .bg(theme.tokens.border.opacity(0.7)),
878                                    )
879                                    .children(self.series.iter().enumerate().map(
880                                        |(series_idx, series)| {
881                                            let value = finite_or_zero(
882                                                series.data.get(label_idx).copied().unwrap_or(0.0),
883                                            );
884                                            let (left, width_percent) =
885                                                domain.horizontal_segment(0.0, value);
886                                            let bar_color = series
887                                                .color
888                                                .unwrap_or_else(|| default_color(series_idx));
889
890                                            div()
891                                                .flex()
892                                                .items_center()
893                                                .gap(px(4.0))
894                                                .child(
895                                                    div()
896                                                        .absolute()
897                                                        .top(single_bar_height * series_idx as f32)
898                                                        .left(relative(left))
899                                                        .h(single_bar_height)
900                                                        .w(relative(width_percent))
901                                                        .bg(bar_color)
902                                                        .rounded_r(theme.tokens.radius_sm),
903                                                )
904                                                .when(show_values, |this| {
905                                                    this.child(
906                                                        div()
907                                                            .text_xs()
908                                                            .text_color(
909                                                                theme.tokens.muted_foreground,
910                                                            )
911                                                            .child(format!("{:.0}", value)),
912                                                    )
913                                                })
914                                        },
915                                    )),
916                            )
917                    })),
918            )
919            .when(show_legend, |this| {
920                this.child(
921                    div()
922                        .flex()
923                        .flex_wrap()
924                        .gap(px(16.0))
925                        .justify_center()
926                        .children(series_for_legend.iter().enumerate().map(|(i, s)| {
927                            let color = s.color.unwrap_or_else(|| default_color(i));
928                            div()
929                                .flex()
930                                .items_center()
931                                .gap(px(6.0))
932                                .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
933                                .child(
934                                    div()
935                                        .text_xs()
936                                        .text_color(theme.tokens.muted_foreground)
937                                        .child(s.name.clone()),
938                                )
939                        })),
940                )
941            })
942    }
943
944    fn render_multi_horizontal_stacked(
945        self,
946        theme: &crate::capabilities::foundation::theme::Theme,
947    ) -> Div {
948        let domain = stacked_domain(&self.series, self.labels.len());
949
950        let bar_height = self.bar_width.unwrap_or(px(24.0));
951        let gap = self.gap;
952        let show_values = self.show_values;
953        let show_grid = self.show_grid;
954        let show_axis_labels = self.show_axis_labels;
955        let show_legend = self.show_legend;
956        let grid_color = theme.tokens.border.opacity(0.3);
957
958        let labels = self.labels.clone();
959        let series_for_legend = self.series.clone();
960
961        div()
962            .flex()
963            .flex_col()
964            .gap(px(16.0))
965            .child(
966                div()
967                    .flex()
968                    .flex_col()
969                    .gap(gap)
970                    .children(labels.iter().enumerate().map(|(label_idx, label)| {
971                        let total_value: f64 = self
972                            .series
973                            .iter()
974                            .map(|series| {
975                                finite_or_zero(series.data.get(label_idx).copied().unwrap_or(0.0))
976                            })
977                            .sum();
978                        let mut positive = 0.0;
979                        let mut negative = 0.0;
980
981                        div()
982                            .flex()
983                            .items_center()
984                            .gap(px(8.0))
985                            .when(show_axis_labels, |this| {
986                                this.child(
987                                    div()
988                                        .w(px(80.0))
989                                        .text_xs()
990                                        .text_color(theme.tokens.muted_foreground)
991                                        .text_right()
992                                        .overflow_hidden()
993                                        .child(label.clone()),
994                                )
995                            })
996                            .child(
997                                div()
998                                    .flex_1()
999                                    .relative()
1000                                    .h(bar_height)
1001                                    .when(show_grid, |this| {
1002                                        this.child(
1003                                            div()
1004                                                .absolute()
1005                                                .inset_0()
1006                                                .flex()
1007                                                .justify_between()
1008                                                .children((0..5).map(|_| {
1009                                                    div().h_full().w(px(1.0)).bg(grid_color)
1010                                                })),
1011                                        )
1012                                    })
1013                                    .child(
1014                                        div()
1015                                            .absolute()
1016                                            .top_0()
1017                                            .bottom_0()
1018                                            .left(relative(domain.zero_ratio))
1019                                            .w(px(1.0))
1020                                            .bg(theme.tokens.border.opacity(0.7)),
1021                                    )
1022                                    .child(div().absolute().inset_0().children(
1023                                        self.series.iter().enumerate().map(
1024                                            |(series_idx, series)| {
1025                                                let value = finite_or_zero(
1026                                                    series
1027                                                        .data
1028                                                        .get(label_idx)
1029                                                        .copied()
1030                                                        .unwrap_or(0.0),
1031                                                );
1032                                                let (start, end) = if value >= 0.0 {
1033                                                    let start = positive;
1034                                                    positive += value;
1035                                                    (start, positive)
1036                                                } else {
1037                                                    let start = negative;
1038                                                    negative += value;
1039                                                    (start, negative)
1040                                                };
1041                                                let (left, width) =
1042                                                    domain.horizontal_segment(start, end);
1043                                                let bar_color = series
1044                                                    .color
1045                                                    .unwrap_or_else(|| default_color(series_idx));
1046
1047                                                div()
1048                                                    .absolute()
1049                                                    .top_0()
1050                                                    .bottom_0()
1051                                                    .left(relative(left))
1052                                                    .w(relative(width))
1053                                                    .bg(bar_color)
1054                                            },
1055                                        ),
1056                                    )),
1057                            )
1058                            .when(show_values, |this| {
1059                                this.child(
1060                                    div()
1061                                        .w(px(50.0))
1062                                        .text_xs()
1063                                        .text_color(theme.tokens.muted_foreground)
1064                                        .child(format!("{:.0}", total_value)),
1065                                )
1066                            })
1067                    })),
1068            )
1069            .when(show_legend, |this| {
1070                this.child(
1071                    div()
1072                        .flex()
1073                        .flex_wrap()
1074                        .gap(px(16.0))
1075                        .justify_center()
1076                        .children(series_for_legend.iter().enumerate().map(|(i, s)| {
1077                            let color = s.color.unwrap_or_else(|| default_color(i));
1078                            div()
1079                                .flex()
1080                                .items_center()
1081                                .gap(px(6.0))
1082                                .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
1083                                .child(
1084                                    div()
1085                                        .text_xs()
1086                                        .text_color(theme.tokens.muted_foreground)
1087                                        .child(s.name.clone()),
1088                                )
1089                        })),
1090                )
1091            })
1092    }
1093}
1094
1095impl Styled for BarChart {
1096    fn style(&mut self) -> &mut StyleRefinement {
1097        &mut self.style
1098    }
1099}
1100
1101impl RenderOnce for BarChart {
1102    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1103        let theme = use_theme(cx);
1104        let user_style = self.style.clone();
1105
1106        let is_single = self.series.is_empty();
1107        let is_vertical = self.orientation == BarChartOrientation::Vertical;
1108        let is_stacked = self.mode == BarChartMode::Stacked;
1109
1110        let content = match (is_single, is_vertical, is_stacked) {
1111            (true, true, _) => self.render_single_vertical(&theme),
1112            (true, false, _) => self.render_single_horizontal(&theme),
1113            (false, true, false) => self.render_multi_vertical_grouped(&theme),
1114            (false, true, true) => self.render_multi_vertical_stacked(&theme),
1115            (false, false, false) => self.render_multi_horizontal_grouped(&theme),
1116            (false, false, true) => self.render_multi_horizontal_stacked(&theme),
1117        };
1118
1119        content.map(|this| {
1120            let mut div = this;
1121            div.style().refine(&user_style);
1122            div
1123        })
1124    }
1125}
1126
1127#[cfg(test)]
1128mod tests {
1129    use super::ValueDomain;
1130    use super::{BarChart, BarChartSeries};
1131    use crate::capabilities::foundation::theme::{install_theme, Theme};
1132    use gpui::{div, px, Context, IntoElement, ParentElement, Render, Styled, TestApp, Window};
1133
1134    #[test]
1135    fn signed_domain_places_zero_between_positive_and_negative_values() {
1136        let domain = ValueDomain::from_values([10.0, -5.0, f64::NAN]);
1137        assert!((domain.zero_ratio - (10.0 / 15.0) as f32).abs() < f32::EPSILON);
1138
1139        let (positive_top, positive_height) = domain.vertical_segment(0.0, 10.0, px(300.0));
1140        let (negative_top, negative_height) = domain.vertical_segment(0.0, -5.0, px(300.0));
1141        assert_eq!(positive_top, px(0.0));
1142        assert_eq!(positive_height, px(200.0));
1143        assert_eq!(negative_top, px(200.0));
1144        assert_eq!(negative_height, px(100.0));
1145    }
1146
1147    #[test]
1148    fn non_finite_values_are_zero_but_negative_values_are_preserved() {
1149        let domain = ValueDomain::from_values([f64::INFINITY, -4.0]);
1150        assert_eq!(domain.min, -4.0);
1151        assert_eq!(domain.max, 0.0);
1152        let (left, width) = domain.horizontal_segment(0.0, -4.0);
1153        assert_eq!(left, 0.0);
1154        assert_eq!(width, 1.0);
1155    }
1156
1157    struct SignedBarChartView;
1158
1159    impl Render for SignedBarChartView {
1160        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1161            div()
1162                .flex()
1163                .flex_col()
1164                .gap(px(16.0))
1165                .child(
1166                    BarChart::multi_series(
1167                        vec!["Jan", "Feb"],
1168                        vec![
1169                            BarChartSeries::new("Revenue", vec![10.0, -5.0]),
1170                            BarChartSeries::new("Cost", vec![-3.0, 4.0]),
1171                        ],
1172                    )
1173                    .stacked()
1174                    .show_values(true),
1175                )
1176                .child(
1177                    BarChart::multi_series(
1178                        vec!["Jan", "Feb"],
1179                        vec![
1180                            BarChartSeries::new("Revenue", vec![10.0, -5.0]),
1181                            BarChartSeries::new("Cost", vec![-3.0, 4.0]),
1182                        ],
1183                    )
1184                    .horizontal()
1185                    .grouped()
1186                    .show_values(true),
1187                )
1188        }
1189    }
1190
1191    #[gpui::test]
1192    fn signed_bar_chart_renders_without_panic() {
1193        let mut app = TestApp::new();
1194        app.update(|cx| install_theme(cx, Theme::light()));
1195        let mut window = app.open_window(|_, _| SignedBarChartView);
1196        window.draw();
1197    }
1198}