1use std::{hash::Hash, ops::RangeInclusive, rc::Rc};
2
3use gpui::{
4 AnyElement, App, Background, Bounds, ColorExt as _, Corners, ElementId, Hsla, IntoElement,
5 LinearColorStop, Pixels, Point, SharedString, Size, TextAlign, Window, linear_gradient, point,
6 px,
7};
8use gpui_component_macros::IntoPlot;
9
10use crate::{
11 ActiveTheme,
12 plot::{
13 AxisLabelPlacement, AxisLabelSide, AxisText, Grid, Plot, PlotAppear, PlotAxis, PlotLabel,
14 label::{TEXT_GAP, TEXT_HEIGHT, TEXT_SIZE, Text, measure_text_width},
15 scale::{PlotValue, Scale, ScaleBand, ScaleLinear},
16 shape::{Bar, BarAlignment},
17 tooltip::{CrossLine, PlotHover, Tooltip, TooltipState},
18 },
19};
20
21use super::{
22 AXIS_GAP, ChartAppear, MAX_BAND_WIDTH, TickFormat, TooltipContent, VALUE_AXIS_GAP,
23 build_band_labels, caller_id, format_tick, labeled_items, value_axis_gap,
24};
25
26const HOVER_DIM: f32 = 0.45;
28
29#[derive(Clone, Copy)]
31struct BarHover {
32 center: f32,
34 focus: f32,
36}
37
38#[derive(IntoPlot)]
39pub struct BarChart<T, B, V>
40where
41 T: 'static,
42 B: Eq + Hash + Into<SharedString> + 'static,
43 V: PlotValue,
44{
45 data: Vec<T>,
46 band: Option<Rc<dyn Fn(&T) -> B>>,
47 value: Option<Rc<dyn Fn(&T) -> V>>,
48 fill: Option<Rc<dyn Fn(&T, Bounds<f32>, Bounds<f32>, BarAlignment) -> Background>>,
49 #[allow(clippy::type_complexity)]
50 fill_gradient:
51 Option<Rc<dyn Fn(&T, RangeInclusive<f32>, &dyn Fn(f32) -> f32) -> [LinearColorStop; 2]>>,
52 tick_margin: usize,
53 label: Option<Rc<dyn Fn(&T) -> SharedString>>,
54 label_color: Option<Rc<dyn Fn(&T) -> Hsla>>,
55 label_axis: bool,
56 value_axis: bool,
57 value_axis_label_placement: AxisLabelPlacement,
58 value_tick_count: usize,
59 value_tick_format: Option<TickFormat>,
60 band_count: Option<usize>,
61 band_tick_count: Option<usize>,
62 grid: bool,
63 grid_dashed: bool,
64 alignment: BarAlignment,
65 corner_radii: Corners<Pixels>,
66 padding_inner: f32,
67 padding_outer: f32,
68 max_band_width: Pixels,
69 min_length: f32,
70 id: ElementId,
71 interactive: bool,
72 appear: ChartAppear,
73 name: Option<SharedString>,
74 tooltip_content: TooltipContent<T>,
75 horizontal_gaps: (f32, f32),
78 value_label_gap: f32,
81 hover: Option<BarHover>,
82}
83
84impl<T, B, V> BarChart<T, B, V>
85where
86 B: Eq + Hash + Into<SharedString> + 'static,
87 V: PlotValue,
88{
89 #[track_caller]
90 pub fn new<I>(data: I) -> Self
91 where
92 I: IntoIterator<Item = T>,
93 {
94 Self {
95 data: data.into_iter().collect(),
96 band: None,
97 value: None,
98 fill: None,
99 fill_gradient: None,
100 tick_margin: 1,
101 label: None,
102 label_color: None,
103 label_axis: true,
104 value_axis: false,
105 value_axis_label_placement: AxisLabelPlacement::default(),
106 value_tick_count: 5,
107 value_tick_format: None,
108 band_count: None,
109 band_tick_count: None,
110 grid: true,
111 grid_dashed: true,
112 alignment: BarAlignment::default(),
113 corner_radii: Corners::all(px(0.)),
114 padding_inner: 0.4,
115 padding_outer: 0.2,
116 max_band_width: px(MAX_BAND_WIDTH),
117 min_length: 0.,
118 id: caller_id(),
119 interactive: true,
120 appear: ChartAppear::default(),
121 name: None,
122 tooltip_content: TooltipContent::default(),
123 horizontal_gaps: (0., 0.),
124 value_label_gap: VALUE_AXIS_GAP,
125 hover: None,
126 }
127 }
128
129 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
136 self.id = id.into();
137 self
138 }
139
140 pub fn interactive(mut self, interactive: bool) -> Self {
148 self.interactive = interactive;
149 self
150 }
151
152 pub fn appear(mut self, appear: bool) -> Self {
159 self.appear.set_enabled(appear);
160 self
161 }
162
163 pub fn appear_key(mut self, key: impl Hash) -> Self {
168 self.appear.set_key(key);
169 self
170 }
171
172 pub fn name(mut self, name: impl Into<SharedString>) -> Self {
174 self.name = Some(name.into());
175 self
176 }
177
178 pub fn tooltip_title(mut self, title: impl Fn(&T) -> SharedString + 'static) -> Self {
180 self.tooltip_content.set_title(title);
181 self
182 }
183
184 pub fn tooltip_value(mut self, value: impl Fn(&T, f64) -> SharedString + 'static) -> Self {
188 self.tooltip_content.set_value(move |d, _, v| value(d, v));
189 self
190 }
191
192 pub fn tooltip_value_color<H>(mut self, color: impl Fn(&T, f64) -> H + 'static) -> Self
198 where
199 H: Into<Hsla>,
200 {
201 self.tooltip_content
202 .set_value_color(move |d, _, value| color(d, value));
203 self
204 }
205
206 pub fn tooltip_content<E>(
213 mut self,
214 content: impl Fn(&T, &mut Window, &mut App) -> E + 'static,
215 ) -> Self
216 where
217 E: IntoElement,
218 {
219 self.tooltip_content.set_content(content);
220 self
221 }
222
223 pub fn band(mut self, band: impl Fn(&T) -> B + 'static) -> Self {
225 self.band = Some(Rc::new(band));
226 self
227 }
228
229 pub fn value(mut self, value: impl Fn(&T) -> V + 'static) -> Self {
231 self.value = Some(Rc::new(value));
232 self
233 }
234
235 pub fn fill<Bg>(
255 mut self,
256 fill: impl Fn(&T, Bounds<f32>, Bounds<f32>, BarAlignment) -> Bg + 'static,
257 ) -> Self
258 where
259 Bg: Into<Background> + 'static,
260 {
261 self.fill = Some(Rc::new(move |t, bar_bounds, chart_bounds, alignment| {
262 fill(t, bar_bounds, chart_bounds, alignment).into()
263 }));
264 self.fill_gradient = None;
265 self
266 }
267
268 pub fn fill_gradient(
304 mut self,
305 fill: impl Fn(&T, RangeInclusive<f32>, &dyn Fn(f32) -> f32) -> [LinearColorStop; 2] + 'static,
306 ) -> Self {
307 self.fill_gradient = Some(Rc::new(fill));
308 self.fill = None;
309 self
310 }
311
312 pub fn tick_margin(mut self, tick_margin: usize) -> Self {
313 self.tick_margin = tick_margin;
314 self
315 }
316
317 pub fn label<S>(mut self, label: impl Fn(&T) -> S + 'static) -> Self
318 where
319 S: Into<SharedString> + 'static,
320 {
321 self.label = Some(Rc::new(move |t| label(t).into()));
322 self
323 }
324
325 pub fn label_color<H>(mut self, color: impl Fn(&T) -> H + 'static) -> Self
331 where
332 H: Into<Hsla> + 'static,
333 {
334 self.label_color = Some(Rc::new(move |t| color(t).into()));
335 self
336 }
337
338 pub fn label_axis(mut self, label_axis: bool) -> Self {
342 self.label_axis = label_axis;
343 self
344 }
345
346 pub fn value_axis(mut self, value_axis: bool) -> Self {
354 self.value_axis = value_axis;
355 self
356 }
357
358 pub fn value_tick_count(mut self, count: usize) -> Self {
367 self.value_tick_count = count.max(2);
368 self
369 }
370
371 pub fn value_axis_label_placement(mut self, placement: AxisLabelPlacement) -> Self {
376 self.value_axis_label_placement = placement;
377 self
378 }
379
380 pub fn value_tick_format<S>(mut self, format: impl Fn(f64) -> S + 'static) -> Self
384 where
385 S: Into<SharedString> + 'static,
386 {
387 self.value_tick_format = Some(Rc::new(move |value| format(value).into()));
388 self
389 }
390
391 pub fn band_count(mut self, count: usize) -> Self {
398 self.band_count = Some(count);
399 self
400 }
401
402 pub fn band_tick_count(mut self, count: usize) -> Self {
409 self.band_tick_count = Some(count);
410 self
411 }
412
413 pub fn grid(mut self, grid: bool) -> Self {
414 self.grid = grid;
415 self
416 }
417
418 pub fn grid_dashed(mut self, dashed: bool) -> Self {
422 self.grid_dashed = dashed;
423 self
424 }
425
426 pub fn alignment(mut self, alignment: BarAlignment) -> Self {
430 self.alignment = alignment;
431 self
432 }
433
434 pub fn corner_radii(mut self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
439 self.corner_radii = corner_radii.into();
440 self
441 }
442
443 pub fn padding_inner(mut self, padding: f32) -> Self {
447 self.padding_inner = padding;
448 self
449 }
450
451 pub fn padding_outer(mut self, padding: f32) -> Self {
455 self.padding_outer = padding;
456 self
457 }
458
459 pub fn max_band_width(mut self, width: impl Into<Pixels>) -> Self {
464 self.max_band_width = width.into();
465 self
466 }
467
468 pub fn min_length(mut self, length: f32) -> Self {
477 self.min_length = length;
478 self
479 }
480
481 fn band_scale(&self, bounds: Bounds<Pixels>) -> Option<ScaleBand<B>> {
484 let band_fn = self.band.as_ref()?;
485 let band_extent = if self.alignment.is_horizontal() {
486 bounds.size.height.as_f32()
487 } else {
488 bounds.size.width.as_f32()
489 };
490 let extent = (band_extent - self.value_axis_gap()).max(0.);
493 Some(
494 ScaleBand::new(self.data.iter().map(|v| band_fn(v)), [0., extent])
495 .band_count(self.band_count.unwrap_or(0))
496 .max_band_width(self.max_band_width.as_f32())
497 .padding_inner(self.padding_inner)
498 .padding_outer(self.padding_outer),
499 )
500 }
501
502 fn band_offset(&self) -> f32 {
509 if self.alignment.is_horizontal() {
510 0.
511 } else {
512 self.value_axis_gap()
513 }
514 }
515
516 fn value_scale(&self, bounds: Bounds<Pixels>) -> Option<(ScaleLinear<V>, f32, f32)> {
520 let value_fn = self.value.as_ref()?;
521 let value_dim = if self.alignment.is_horizontal() {
522 bounds.size.width.as_f32()
523 } else {
524 bounds.size.height.as_f32()
525 };
526 let axis_gap = if self.label_axis { AXIS_GAP } else { 0. };
527 let far_gap = if self.label.is_some() {
535 TEXT_HEIGHT
536 } else {
537 10.
538 };
539 let (band_gap, value_end_gap) = if self.alignment.is_horizontal() {
540 self.horizontal_gaps
541 } else {
542 (axis_gap, far_gap)
543 };
544 let (baseline, far) = match self.alignment {
546 BarAlignment::Bottom => (value_dim - axis_gap, far_gap),
547 BarAlignment::Top => (axis_gap, value_dim - far_gap),
548 BarAlignment::Left => (band_gap, value_dim - value_end_gap),
549 BarAlignment::Right => (value_dim - band_gap, value_end_gap),
550 };
551 let scale = ScaleLinear::new(
552 self.data.iter().map(|v| value_fn(v)).chain(Some(V::zero())),
553 [baseline, far],
554 );
555 Some((scale, baseline, far))
556 }
557
558 fn bar_frame(
560 &self,
561 d: &T,
562 band_scale: &ScaleBand<B>,
563 bounds: Bounds<Pixels>,
564 ) -> Option<Bounds<f32>> {
565 let (band_fn, value_fn) = (self.band.as_ref()?, self.value.as_ref()?);
566 let (value_scale, baseline, _) = self.value_scale(bounds)?;
567 let zero = value_scale.tick(&V::zero()).unwrap_or(baseline);
568 let cross = band_scale.tick(&band_fn(d))? + self.band_offset();
569 let end = bar_end(
570 &value_scale,
571 value_fn(d),
572 zero,
573 self.alignment,
574 self.min_length,
575 )?;
576 let (lo, length) = (end.min(zero), (end - zero).abs());
577 let band_width = band_scale.band_width();
578 Some(if self.alignment.is_horizontal() {
579 Bounds {
580 origin: Point::new(lo, cross),
581 size: Size::new(length, band_width),
582 }
583 } else {
584 Bounds {
585 origin: Point::new(cross, lo),
586 size: Size::new(band_width, length),
587 }
588 })
589 }
590
591 fn gradient_range(&self) -> RangeInclusive<f32> {
593 let Some(value_fn) = self.value.as_ref() else {
594 return 0.0..=0.0;
595 };
596 let mut lo = 0.0_f32;
597 let mut hi = 0.0_f32;
598 for v in &self.data {
599 if let Some(f) = value_fn(v).to_f32() {
600 lo = lo.min(f);
601 hi = hi.max(f);
602 }
603 }
604 lo..=hi
605 }
606
607 fn bar_color(&self, d: &T, frame: Bounds<f32>, bounds: Bounds<Pixels>, cx: &App) -> Hsla {
612 let default = cx.theme().chart_2;
613 if let Some(fill) = self.fill_gradient.as_ref() {
614 let value = self
615 .value
616 .as_ref()
617 .and_then(|value_fn| value_fn(d).to_f32())
618 .unwrap_or(0.);
619 let [first, _] = bar_gradient(fill.as_ref(), d, value, self.gradient_range());
620 return first.color.into();
621 }
622 let Some(fill) = self.fill.as_ref() else {
623 return default;
624 };
625 let chart_bounds = Bounds {
626 origin: Point::new(0., 0.),
627 size: Size::new(bounds.size.width.as_f32(), bounds.size.height.as_f32()),
628 };
629 fill(d, frame, chart_bounds, self.alignment)
630 .as_solid()
631 .unwrap_or(default)
632 }
633
634 fn value_axis_gap(&self) -> f32 {
637 if !self.value_axis || self.value_axis_label_placement != AxisLabelPlacement::Outside {
638 0.
639 } else if self.alignment.is_horizontal() {
640 VALUE_AXIS_GAP
642 } else {
643 self.value_label_gap
644 }
645 }
646
647 fn band_slots(&self) -> usize {
650 self.band_count.unwrap_or(0).max(self.data.len())
651 }
652
653 fn value_tick_labels(&self) -> Vec<SharedString> {
656 let Some(value_fn) = self.value.as_ref() else {
657 return vec![];
658 };
659 let (lo, hi) = self.data.iter().fold((0.0_f32, 0.0_f32), |(lo, hi), v| {
661 let f = value_fn(v).to_f32().unwrap_or(0.);
662 (lo.min(f), hi.max(f))
663 });
664 let steps = (self.value_tick_count - 1) as f32;
665 (0..self.value_tick_count)
666 .map(|i| {
667 let value = (hi - (hi - lo) * i as f32 / steps) as f64;
668 match self.value_tick_format.as_ref() {
669 Some(format) => format(value),
670 None => format_tick(value),
671 }
672 })
673 .collect()
674 }
675
676 fn measure_horizontal_gaps(&self, window: &mut Window) -> (f32, f32) {
681 let Some(band_fn) = self.band.as_ref() else {
682 return (0., 0.);
683 };
684 let font_size = px(TEXT_SIZE);
685 let band_gap = if self.label_axis {
686 self.data
687 .iter()
688 .map(|v| {
689 let s: SharedString = band_fn(v).into();
690 measure_text_width(&s, font_size, window)
691 })
692 .fold(0f32, f32::max)
693 + TEXT_GAP * 2.
694 } else {
695 0.
696 };
697 let value_end_gap = if let Some(label_fn) = self.label.as_ref() {
698 self.data
699 .iter()
700 .map(|v| measure_text_width(&label_fn(v), font_size, window))
701 .fold(0f32, f32::max)
702 + TEXT_GAP * 2.
703 } else {
704 TEXT_GAP * 4.
705 };
706 (band_gap, value_end_gap)
707 }
708
709 fn value_extent(&self, bounds: Bounds<Pixels>) -> (f32, f32) {
712 if self.alignment.is_horizontal() {
713 let (band_gap, value_end_gap) = self.horizontal_gaps;
714 let length = (bounds.size.width.as_f32() - band_gap - value_end_gap).max(0.);
715 let start = if matches!(self.alignment, BarAlignment::Left) {
716 band_gap
717 } else {
718 value_end_gap
719 };
720 (start, length)
721 } else {
722 let axis_gap = if self.label_axis { AXIS_GAP } else { 0. };
723 let length = bounds.size.height.as_f32() - axis_gap;
724 let start = if matches!(self.alignment, BarAlignment::Top) {
725 axis_gap
726 } else {
727 0.
728 };
729 (start, length)
730 }
731 }
732
733 fn is_over_bars(&self, position: Point<Pixels>, bounds: Bounds<Pixels>) -> bool {
735 let (start, length) = self.value_extent(bounds);
736 if self.alignment.is_horizontal() {
737 let value_labels_top = bounds.size.height.as_f32() - VALUE_AXIS_GAP;
738 (start..=start + length).contains(&position.x.as_f32())
739 && !(self.value_axis_gap() > 0. && position.y.as_f32() > value_labels_top)
740 } else {
741 (start..=start + length).contains(&position.y.as_f32())
742 && position.x.as_f32() >= self.band_offset()
743 }
744 }
745}
746
747impl<T, B, V> Plot for BarChart<T, B, V>
748where
749 B: Eq + Hash + Into<SharedString> + 'static,
750 V: PlotValue,
751{
752 fn prepaint(
753 &mut self,
754 _bounds: Bounds<Pixels>,
755 window: &mut Window,
756 _cx: &mut App,
757 ) -> Vec<AnyElement> {
758 self.horizontal_gaps = if self.alignment.is_horizontal() {
759 self.measure_horizontal_gaps(window)
760 } else {
761 (0., 0.)
762 };
763 if self.value_axis && !self.alignment.is_horizontal() {
764 self.value_label_gap = value_axis_gap(self.value_tick_labels(), window);
765 }
766 vec![]
767 }
768
769 fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
770 let (Some(band_fn), Some(value_fn)) = (self.band.as_ref(), self.value.as_ref()) else {
771 return;
772 };
773
774 let total_width = bounds.size.width.as_f32();
775 let total_height = bounds.size.height.as_f32();
776 let alignment = self.alignment;
777 let is_horizontal = alignment.is_horizontal();
778
779 let Some(band_scale) = self.band_scale(bounds) else {
782 return;
783 };
784 let band_width = band_scale.band_width();
785
786 let Some((value_scale, baseline, far)) = self.value_scale(bounds) else {
787 return;
788 };
789
790 let zero_pixel = value_scale.tick(&V::zero()).unwrap_or(baseline);
794 let band_offset = self.band_offset();
795
796 let value_axis_gap = self.value_axis_gap();
800 let plot_bounds = if is_horizontal {
801 Bounds {
802 origin: bounds.origin,
803 size: Size::new(bounds.size.width, bounds.size.height - px(value_axis_gap)),
804 }
805 } else {
806 Bounds {
807 origin: bounds.origin + point(px(value_axis_gap), px(0.)),
808 size: Size::new(bounds.size.width - px(value_axis_gap), bounds.size.height),
809 }
810 };
811
812 let mut axis = PlotAxis::new().stroke(cx.theme().border);
814 if self.label_axis {
815 match alignment {
816 BarAlignment::Bottom | BarAlignment::Top => {
817 axis = axis.x(zero_pixel);
818
819 let labeled =
824 labeled_items(self.band_slots(), self.band_tick_count, self.tick_margin);
825 let labels = self
826 .data
827 .iter()
828 .enumerate()
829 .filter(|(i, _)| labeled[*i])
830 .filter_map(|(_, d)| {
831 let band_x = band_scale.tick(&band_fn(d))?;
832 let value = value_fn(d).to_f32().unwrap_or(0.);
833 let label_y = if label_below_zero_line(value, alignment) {
834 zero_pixel + TEXT_GAP
835 } else {
836 zero_pixel - TEXT_GAP - TEXT_SIZE
837 };
838
839 Some(
840 Text::new(
841 band_fn(d).into(),
842 point(px(band_x + band_offset + band_width / 2.), px(label_y)),
843 cx.theme().muted_foreground,
844 )
845 .align(TextAlign::Center),
846 )
847 })
848 .collect();
849 PlotLabel::new(labels).paint(&bounds, window, cx);
850 }
851 BarAlignment::Left | BarAlignment::Right => {
852 let labels = build_band_labels(
853 &self.data,
854 band_fn.as_ref(),
855 &band_scale,
856 band_width,
857 &labeled_items(self.band_slots(), self.band_tick_count, self.tick_margin),
858 cx.theme().muted_foreground,
859 );
860 let (side, align) = if matches!(alignment, BarAlignment::Left) {
861 (AxisLabelSide::Start, TextAlign::Right)
862 } else {
863 (AxisLabelSide::End, TextAlign::Left)
864 };
865 axis = axis
866 .y(zero_pixel)
867 .y_label_side(side)
868 .y_label(labels.into_iter().map(|t| t.align(align)));
869 }
870 }
871 }
872 axis.paint(&plot_bounds, window, cx);
873
874 let value_ticks = value_tick_positions(far, baseline, self.value_tick_count);
875 let steps = value_ticks.len() - 1;
876
877 if self.grid {
879 let grid = Grid::new().stroke(cx.theme().chart_grid);
880 let grid = if self.grid_dashed {
881 grid.dash_array(&[px(4.), px(2.)])
882 } else {
883 grid
884 };
885 let lines = value_ticks[..steps].to_vec();
886 let grid = if is_horizontal {
887 grid.x(lines)
888 } else {
889 grid.y(lines)
890 };
891 grid.paint(&plot_bounds, window);
892 }
893
894 let mut inside_labels = None;
896 if self.value_axis {
897 let color = cx.theme().muted_foreground;
900 let texts = self
901 .value_tick_labels()
902 .into_iter()
903 .zip(value_ticks.iter().copied());
904
905 match self.value_axis_label_placement {
906 AxisLabelPlacement::Outside => {
910 let labels = texts.map(|(text, tick)| AxisText::new(text, px(tick), color));
911 let value_axis = if is_horizontal {
912 PlotAxis::new()
913 .x_axis(false)
914 .x(px(total_height - VALUE_AXIS_GAP))
915 .x_label(labels.map(|t| t.align(TextAlign::Center)))
916 } else {
917 PlotAxis::new()
918 .y_axis(false)
919 .y(px(value_axis_gap - TEXT_GAP * 2.))
920 .y_label(labels.map(|t| t.align(TextAlign::Right)))
921 };
922 value_axis.paint(&bounds, window, cx);
923 }
924 AxisLabelPlacement::Inside => {
928 let labels = texts
929 .map(|(text, tick)| {
930 if is_horizontal {
931 Text::new(text, point(tick, total_height - TEXT_HEIGHT), color)
932 .align(TextAlign::Center)
933 } else {
934 let top = if tick < TEXT_HEIGHT {
935 tick + TEXT_GAP
936 } else {
937 tick - TEXT_HEIGHT
938 };
939 Text::new(text, point(TEXT_GAP, top), color)
940 }
941 })
942 .collect();
943 inside_labels = Some(PlotLabel::new(labels));
944 }
945 }
946 }
947
948 let band_fn_cloned = band_fn.clone();
950 let value_fn_cloned = value_fn.clone();
951 let default_fill: Background = cx.theme().chart_2.into();
952 let fill = self.fill.clone();
953 let fill_gradient = self.fill_gradient.clone();
954 let label_color = cx.theme().foreground;
955 let label_color_fn = self.label_color.clone();
956 let min_length = self.min_length;
957
958 let chart_bounds: Bounds<f32> = Bounds {
962 origin: Point::new(0., 0.),
963 size: Size::new(total_width, total_height),
964 };
965
966 let chart_range = self.gradient_range();
969
970 let hover = self.hover;
974 let step = band_scale.step().max(f32::EPSILON);
975 let emphasis = move |frame: Bounds<f32>| -> f32 {
976 let Some(hover) = hover else {
977 return 1.;
978 };
979 let center = if is_horizontal {
980 frame.origin.y + frame.size.height / 2.
981 } else {
982 frame.origin.x + frame.size.width / 2.
983 };
984 let distance = ((center - hover.center).abs() / step).min(1.);
985 1. - HOVER_DIM * hover.focus * distance
986 };
987
988 let appear = self.appear.get().progress();
991
992 let mut bar = Bar::new()
993 .data(&self.data)
994 .alignment(alignment)
995 .band_width(band_width)
996 .cross(move |d| band_scale.tick(&band_fn_cloned(d)).map(|t| t + band_offset))
997 .base(move |_| zero_pixel)
998 .value(move |d| {
999 let end = bar_end(
1000 &value_scale,
1001 value_fn_cloned(d),
1002 zero_pixel,
1003 alignment,
1004 min_length,
1005 )?;
1006 Some(zero_pixel + (end - zero_pixel) * appear)
1007 })
1008 .corner_radii(self.corner_radii);
1009
1010 bar = match (fill, fill_gradient) {
1011 (_, Some(fg)) => {
1012 let value_fn_for_grad = value_fn.clone();
1013 bar.fill(move |d, frame, alignment| {
1014 let v = value_fn_for_grad(d).to_f32().unwrap_or(0.);
1015 let [s0, s1] = bar_gradient(fg.as_ref(), d, v, chart_range.clone());
1016 let bg: Background = linear_gradient(alignment.gradient_angle(), s0, s1);
1017 bg.opacity(emphasis(frame))
1018 })
1019 }
1020 (Some(f), _) => bar.fill(move |d, frame, alignment| {
1021 f(d, frame, chart_bounds, alignment).opacity(emphasis(frame))
1022 }),
1023 _ => bar.fill(move |_, frame, _| default_fill.opacity(emphasis(frame))),
1024 };
1025
1026 if let Some(label) = self.label.as_ref() {
1027 let label = label.clone();
1028 let text_align = match alignment {
1029 BarAlignment::Bottom | BarAlignment::Top => TextAlign::Center,
1030 BarAlignment::Left => TextAlign::Left,
1031 BarAlignment::Right => TextAlign::Right,
1032 };
1033 bar = bar.label(move |d, p| {
1034 let color = label_color_fn
1036 .as_ref()
1037 .map_or(label_color, |f| f(d))
1038 .opacity(appear);
1039 vec![Text::new(label(d), p, color).align(text_align)]
1040 });
1041 }
1042
1043 bar.paint(&bounds, window, cx);
1044 if let Some(labels) = inside_labels {
1045 labels.paint(&bounds, window, cx);
1046 }
1047 }
1048
1049 fn id(&self) -> Option<ElementId> {
1050 Some(self.id.clone())
1051 }
1052
1053 fn interactive(&self) -> bool {
1054 self.interactive
1055 }
1056
1057 fn appear(&mut self, appear: PlotAppear, _window: &mut Window, _cx: &mut App) {
1058 self.appear.update(appear);
1059 }
1060
1061 fn appear_generation(&self) -> Option<u64> {
1062 self.appear.generation()
1063 }
1064
1065 fn tooltip_state(
1066 &self,
1067 position: Point<Pixels>,
1068 bounds: Bounds<Pixels>,
1069 _cx: &App,
1070 ) -> Option<TooltipState> {
1071 let band_fn = self.band.as_ref()?;
1072 self.value.as_ref()?;
1073
1074 if !self.is_over_bars(position, bounds) {
1076 return None;
1077 }
1078
1079 let is_horizontal = self.alignment.is_horizontal();
1082 let band_scale = self.band_scale(bounds)?;
1083 let band_width = band_scale.band_width();
1084
1085 let band_offset = self.band_offset();
1086 let cursor_band = if is_horizontal {
1087 position.y
1088 } else {
1089 position.x
1090 };
1091 let index = band_scale.nearest_index(cursor_band.as_f32() - band_offset);
1092 let d = self.data.get(index)?;
1093 let center = band_scale.tick(&band_fn(d))? + band_offset + band_width / 2.;
1094
1095 let cross_line = if is_horizontal {
1098 point(position.x, px(center))
1099 } else {
1100 point(px(center), position.y)
1101 };
1102
1103 Some(TooltipState::new(index, cross_line, vec![]))
1104 }
1105
1106 fn hover(&mut self, hover: Option<&PlotHover>, window: &mut Window, cx: &mut App) {
1107 self.hover = hover.map(|hover| {
1108 let target = if self.alignment.is_horizontal() {
1111 hover.state().cross_line.y
1112 } else {
1113 hover.state().cross_line.x
1114 };
1115 let center = hover.glide(("bar-chart", "band"), target, window, cx);
1116 BarHover {
1117 center: center.as_f32(),
1118 focus: hover.progress(),
1119 }
1120 });
1121 }
1122
1123 fn tooltip(
1124 &self,
1125 state: &TooltipState,
1126 cursor: Point<Pixels>,
1127 bounds: Bounds<Pixels>,
1128 window: &mut Window,
1129 cx: &mut App,
1130 ) -> Option<AnyElement> {
1131 let (band_fn, value_fn) = (self.band.as_ref()?, self.value.as_ref()?);
1132 let d = self.data.get(state.index)?;
1133 let name = self.name.clone().unwrap_or_default();
1134
1135 let band_scale = self.band_scale(bounds)?;
1139 let band_width = band_scale.band_width();
1140 let center = self.hover.map_or(state.cross_line, |hover| {
1141 if self.alignment.is_horizontal() {
1142 point(state.cross_line.x, px(hover.center))
1143 } else {
1144 point(px(hover.center), state.cross_line.y)
1145 }
1146 });
1147 let (start, length) = self.value_extent(bounds);
1148 let cross_line = if self.alignment.is_horizontal() {
1149 CrossLine::new(center)
1150 .horizontal()
1151 .h_span(start, length)
1152 .band(px(band_width))
1153 } else {
1154 CrossLine::new(center)
1155 .span(start, length)
1156 .band(px(band_width))
1157 };
1158
1159 let frame = self.bar_frame(d, &band_scale, bounds).unwrap_or_default();
1160 let swatch = self.bar_color(d, frame, bounds, cx);
1161
1162 let tooltip = Tooltip::new(cursor, bounds.size)
1164 .glide(false)
1165 .gap(px(8.))
1166 .cross_line(cross_line);
1167
1168 let tooltip = self.tooltip_content.apply(
1169 tooltip,
1170 d,
1171 || Some(band_fn(d).into()),
1172 || Some([(swatch, name, value_fn(d).to_f64()?)]),
1173 window,
1174 cx,
1175 )?;
1176
1177 Some(tooltip.into_any_element())
1178 }
1179}
1180
1181fn bar_end<V>(
1184 scale: &ScaleLinear<V>,
1185 value: V,
1186 zero: f32,
1187 alignment: BarAlignment,
1188 min_length: f32,
1189) -> Option<f32>
1190where
1191 V: PlotValue,
1192{
1193 let tick = scale.tick(&value)?;
1194 Some(extend_to_min_length(
1195 tick,
1196 zero,
1197 value < V::zero(),
1198 alignment,
1199 min_length,
1200 ))
1201}
1202
1203fn extend_to_min_length(
1206 tick: f32,
1207 zero: f32,
1208 negative: bool,
1209 alignment: BarAlignment,
1210 min: f32,
1211) -> f32 {
1212 if (tick - zero).abs() >= min {
1213 return tick;
1214 }
1215 let grows_toward_origin = matches!(alignment, BarAlignment::Bottom | BarAlignment::Right);
1216 if grows_toward_origin != negative {
1217 zero - min
1218 } else {
1219 zero + min
1220 }
1221}
1222
1223fn bar_gradient<T>(
1226 fill: &dyn Fn(&T, RangeInclusive<f32>, &dyn Fn(f32) -> f32) -> [LinearColorStop; 2],
1227 d: &T,
1228 value: f32,
1229 range: RangeInclusive<f32>,
1230) -> [LinearColorStop; 2] {
1231 let bar_lo = value.min(0.);
1232 let bar_span = (value.max(0.) - bar_lo).max(f32::EPSILON);
1233 let chart_to_bar = |chart_value: f32| (chart_value - bar_lo) / bar_span;
1234 clip_stops_to_bar(fill(d, range, &chart_to_bar))
1235}
1236
1237fn clip_stops_to_bar(stops: [LinearColorStop; 2]) -> [LinearColorStop; 2] {
1248 let [a, b] = stops;
1249 let p0 = a.percentage;
1250 let p1 = b.percentage;
1251 let a_color: Hsla = a.color.into();
1252 let b_color: Hsla = b.color.into();
1253 let lerp = |t: f32| -> Hsla {
1254 gpui::hsla(
1255 (a_color.color.hue.into_degrees()
1256 + (b_color.color.hue.into_degrees() - a_color.color.hue.into_degrees()) * t)
1257 / 360.,
1258 a_color.color.saturation + (b_color.color.saturation - a_color.color.saturation) * t,
1259 a_color.color.lightness + (b_color.color.lightness - a_color.color.lightness) * t,
1260 a_color.alpha + (b_color.alpha - a_color.alpha) * t,
1261 )
1262 };
1263 let span = p1 - p0;
1264 let sample = |target: f32| -> Hsla {
1265 if span.abs() < f32::EPSILON {
1266 a_color
1267 } else {
1268 lerp((target - p0) / span)
1269 }
1270 };
1271 let new_a = if (0. ..=1.).contains(&p0) {
1272 a
1273 } else {
1274 LinearColorStop {
1275 color: sample(p0.clamp(0., 1.)).into(),
1276 percentage: p0.clamp(0., 1.),
1277 }
1278 };
1279 let new_b = if (0. ..=1.).contains(&p1) {
1280 b
1281 } else {
1282 LinearColorStop {
1283 color: sample(p1.clamp(0., 1.)).into(),
1284 percentage: p1.clamp(0., 1.),
1285 }
1286 };
1287 [new_a, new_b]
1288}
1289
1290fn label_below_zero_line(value: f32, alignment: BarAlignment) -> bool {
1297 (value < 0.) == (alignment == BarAlignment::Top)
1298}
1299
1300fn value_tick_positions(far: f32, baseline: f32, count: usize) -> Vec<f32> {
1305 let steps = (count - 1) as f32;
1306 (0..count)
1307 .map(|i| far + (baseline - far) * i as f32 / steps)
1308 .collect()
1309}
1310
1311#[cfg(test)]
1312mod tests {
1313 use super::*;
1314
1315 #[test]
1316 fn test_label_below_zero_line() {
1317 assert!(label_below_zero_line(5., BarAlignment::Bottom));
1319 assert!(label_below_zero_line(0., BarAlignment::Bottom));
1320 assert!(!label_below_zero_line(-5., BarAlignment::Bottom));
1321
1322 assert!(!label_below_zero_line(5., BarAlignment::Top));
1324 assert!(!label_below_zero_line(0., BarAlignment::Top));
1325 assert!(label_below_zero_line(-5., BarAlignment::Top));
1326 }
1327
1328 #[test]
1329 fn test_value_tick_positions() {
1330 assert_eq!(
1332 value_tick_positions(10., 110., 5),
1333 vec![10., 35., 60., 85., 110.]
1334 );
1335
1336 assert_eq!(value_tick_positions(110., 10., 3), vec![110., 60., 10.]);
1338
1339 assert_eq!(value_tick_positions(0., 50., 2), vec![0., 50.]);
1340 }
1341
1342 #[test]
1343 fn test_min_length_extends_away_from_zero() {
1344 assert_eq!(
1346 extend_to_min_length(100., 100., false, BarAlignment::Bottom, 2.),
1347 98.
1348 );
1349 assert_eq!(
1350 extend_to_min_length(10., 10., false, BarAlignment::Top, 2.),
1351 12.
1352 );
1353 assert_eq!(
1354 extend_to_min_length(10., 10., false, BarAlignment::Left, 2.),
1355 12.
1356 );
1357 assert_eq!(
1358 extend_to_min_length(90., 90., false, BarAlignment::Right, 2.),
1359 88.
1360 );
1361
1362 assert_eq!(
1364 extend_to_min_length(50.5, 50., true, BarAlignment::Bottom, 2.),
1365 52.
1366 );
1367
1368 assert_eq!(
1370 extend_to_min_length(40., 100., false, BarAlignment::Bottom, 2.),
1371 40.
1372 );
1373 }
1374
1375 #[test]
1376 fn value_tick_labels_walk_the_domain_from_the_far_end() {
1377 use super::BarChart;
1378
1379 let chart = BarChart::new([10., 20.])
1380 .band(|v| format!("{v}"))
1381 .value(|v| *v)
1382 .value_tick_count(3);
1383 assert_eq!(chart.value_tick_labels(), vec!["20", "10", "0"]);
1384
1385 let money = chart.value_tick_format(|v| format!("${v:.0}"));
1386 assert_eq!(money.value_tick_labels(), vec!["$20", "$10", "$0"]);
1387
1388 assert_eq!(money.band_count(12).band_slots(), 12);
1390 }
1391
1392 #[test]
1393 fn a_band_count_keeps_each_bar_in_its_band() {
1394 use gpui::{Bounds, point, px, size};
1395
1396 use super::BarChart;
1397 use crate::plot::{AxisLabelPlacement, scale::Scale};
1398
1399 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(40.), px(100.)));
1400 let chart = |data: &[f64], count| {
1401 BarChart::new(data.to_vec())
1402 .band(|v| format!("{v}"))
1403 .value(|v| *v)
1404 .band_count(count)
1405 };
1406
1407 let wide = chart(&[1., 2.], 2).band_scale(bounds).unwrap();
1409 let narrow = chart(&[1., 2.], 4).band_scale(bounds).unwrap();
1410 assert_eq!(narrow.band_width() * 2., wide.band_width());
1411 assert!(narrow.tick(&"2".to_string()).unwrap() < 20.);
1412
1413 let grown = chart(&[1., 2., 3.], 4).band_scale(bounds).unwrap();
1415 assert_eq!(grown.tick(&"2".to_string()), narrow.tick(&"2".to_string()));
1416 assert_eq!(grown.band_width(), narrow.band_width());
1417
1418 let outside = chart(&[1., 2.], 2).value_axis(true);
1420 let inside = chart(&[1., 2.], 2)
1421 .value_axis(true)
1422 .value_axis_label_placement(AxisLabelPlacement::Inside);
1423 assert_eq!(outside.value_axis_gap(), super::VALUE_AXIS_GAP);
1424 assert_eq!(inside.value_axis_gap(), 0.);
1425 }
1426
1427 #[gpui::test]
1430 fn the_tooltip_swatch_follows_the_bar_color(cx: &mut gpui::TestAppContext) {
1431 cx.update(crate::init);
1432 let bars = || {
1433 BarChart::new([1., -2.])
1434 .band(|d: &f64| SharedString::from(format!("{d}")))
1435 .value(|d: &f64| *d)
1436 };
1437 let frame = Bounds::default();
1438 let bounds = Bounds::new(point(px(0.), px(0.)), gpui::size(px(100.), px(100.)));
1439 let (default, solid, gradient, stops) = cx.update(|cx| {
1440 let gain = gpui::green();
1441 let loss = gpui::red();
1442 let default = bars().bar_color(&1., frame, bounds, cx);
1443 let solid = bars()
1444 .fill(move |d: &f64, _, _, _| if *d >= 0. { gain } else { loss })
1445 .bar_color(&-2., frame, bounds, cx);
1446 let gradient = bars()
1447 .fill(move |_: &f64, _, _, _| {
1448 linear_gradient(
1449 0.,
1450 gpui::linear_color_stop(gain, 0.),
1451 gpui::linear_color_stop(loss, 1.),
1452 )
1453 })
1454 .bar_color(&1., frame, bounds, cx);
1455 let stops = bars()
1456 .fill_gradient(move |_: &f64, _, _| {
1457 [
1458 gpui::linear_color_stop(gain, 0.),
1459 gpui::linear_color_stop(loss, 1.),
1460 ]
1461 })
1462 .bar_color(&1., frame, bounds, cx);
1463 (default, solid, gradient, stops)
1464 });
1465 let chart_2 = cx.update(|cx| cx.theme().chart_2);
1466
1467 assert_eq!(default, chart_2);
1468 assert_eq!(solid, gpui::red());
1469 assert_eq!(gradient, chart_2);
1470 assert_eq!(stops, gpui::green());
1471 }
1472
1473 #[test]
1476 fn the_tooltip_reads_the_painted_bar_frame() {
1477 let bars = BarChart::new([1., -2.])
1478 .band(|d: &f64| SharedString::from(format!("{d}")))
1479 .value(|d: &f64| *d);
1480 let bounds = Bounds::new(point(px(0.), px(0.)), gpui::size(px(100.), px(100.)));
1481 let band_scale = bars.band_scale(bounds).expect("bars have a band scale");
1482 let up = bars.bar_frame(&1., &band_scale, bounds).expect("a frame");
1483 let down = bars.bar_frame(&-2., &band_scale, bounds).expect("a frame");
1484
1485 assert_eq!(up.origin.y + up.size.height, down.origin.y);
1487 assert!((down.size.height - 2. * up.size.height).abs() < 0.01);
1488 assert!(up.origin.x < down.origin.x);
1489 assert_eq!(up.size.width, band_scale.band_width());
1490 }
1491}