Skip to main content

gpui_component/chart/
bar_chart.rs

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
26/// How much the bars away from the hovered one fade, as a share of their opacity.
27const HOVER_DIM: f32 = 0.45;
28
29/// The hover a bar chart paints, sampled once per frame in [`Plot::hover`].
30#[derive(Clone, Copy)]
31struct BarHover {
32    /// Cross-axis center of the highlight band, gliding between bars.
33    center: f32,
34    /// How far the hover has faded in.
35    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    /// The label gaps of horizontal bars, measured in `prepaint` for the frame,
76    /// so `tooltip_state` (which has no window) can keep the hover off the labels.
77    horizontal_gaps: (f32, f32),
78    /// The value-axis gutter of vertical bars, measured in `prepaint`; see
79    /// [`value_axis_gap`].
80    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    /// Name this chart's [`ElementId`], replacing the default taken from the
130    /// construction site.
131    ///
132    /// Pass one where a single construction site renders several of these
133    /// charts as siblings: they share the default id, and with it one hover
134    /// state and one path cache. The id must be unique among those siblings.
135    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
136        self.id = id.into();
137        self
138    }
139
140    /// Turn this chart's interactive layer on or off. On by default.
141    ///
142    /// The layer is the hitbox under the cursor and what it drives: a crosshair
143    /// marks the hovered band, and a tooltip shows its category and value. Turn
144    /// it off for a chart that only decorates, or one an element above it wants
145    /// the cursor for: without a hitbox it neither answers the mouse nor takes
146    /// the hover from what sits over it.
147    pub fn interactive(mut self, interactive: bool) -> Self {
148        self.interactive = interactive;
149        self
150    }
151
152    /// Draw the data in the first time this chart is painted. On by default.
153    ///
154    /// The theme sets how long it takes, and the system's reduced-motion
155    /// setting skips it. Turn it off for a chart that is painted again and
156    /// again as it scrolls in and out of view, such as one in each row of a
157    /// long list, where it would draw in every time.
158    pub fn appear(mut self, appear: bool) -> Self {
159        self.appear.set_enabled(appear);
160        self
161    }
162
163    /// Draw the data in again whenever `key` changes, such as the symbol or
164    /// period a chart shows.
165    ///
166    /// Without one the data draws in once, and later data paints in place.
167    pub fn appear_key(mut self, key: impl Hash) -> Self {
168        self.appear.set_key(key);
169        self
170    }
171
172    /// Set the series name shown in the hover tooltip row (e.g. "Desktop").
173    pub fn name(mut self, name: impl Into<SharedString>) -> Self {
174        self.name = Some(name.into());
175        self
176    }
177
178    /// Set the hover tooltip's title for a datum, instead of its band value.
179    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    /// Set the text of the tooltip row's value; the raw number by default.
185    ///
186    /// The closure receives the datum and the value the row reads.
187    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    /// Color the tooltip row's value, such as green or red by its sign; the
193    /// tooltip's text color by default.
194    ///
195    /// The closure receives the same arguments as
196    /// [`tooltip_value`](Self::tooltip_value).
197    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    /// Draw the tooltip box's content for a datum yourself, in place of the
207    /// title and rows, for a layout they cannot express such as a table.
208    ///
209    /// The highlight band and where the box sits stay the chart's, and
210    /// [`tooltip_title`](Self::tooltip_title), [`tooltip_value`](Self::tooltip_value)
211    /// and [`tooltip_value_color`](Self::tooltip_value_color) no longer apply.
212    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    /// Map each datum to its band-axis value (the categorical/ordinal axis).
224    pub fn band(mut self, band: impl Fn(&T) -> B + 'static) -> Self {
225        self.band = Some(Rc::new(band));
226        self
227    }
228
229    /// Map each datum to its numeric value along the value axis.
230    pub fn value(mut self, value: impl Fn(&T) -> V + 'static) -> Self {
231        self.value = Some(Rc::new(value));
232        self
233    }
234
235    /// Set a per-datum verbatim fill.
236    ///
237    /// The closure receives:
238    ///
239    /// 1. the datum,
240    /// 2. the **bar's bounds** in pixel space, expressed relative to the
241    ///    chart's origin (i.e. the bar's painted rectangle within the chart),
242    /// 3. the **chart's bounds** in pixel space with origin `(0, 0)` and size
243    ///    equal to the full chart extent, and
244    /// 4. the bar's [`BarAlignment`] (so callers can branch on orientation,
245    ///    e.g. flip a gradient angle).
246    ///
247    /// Both rectangles share the same coordinate system, so callers can
248    /// implement arbitrary chart-aware backgrounds — bar-local gradients,
249    /// chart-wide gradients, patterns, sampled colormaps, etc. — without any
250    /// help from the library.
251    ///
252    /// Accepts any type convertible to [`Background`]. Setting this clears any
253    /// previously set [`BarChart::fill_gradient`].
254    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    /// Set a per-datum auto-oriented linear gradient fill.
269    ///
270    /// The closure receives the datum, the chart's full data range
271    /// (`chart_range`, derived from all data values), and a `chart_to_bar`
272    /// remap helper that maps a chart-value coordinate to a bar-local
273    /// gradient position (where `0.0` is the bar's base and `1.0` is its tip).
274    ///
275    /// Use bar-local positions directly for per-bar gradients (every bar
276    /// looks the same regardless of its value):
277    ///
278    /// ```ignore
279    /// .fill_gradient(|_, _, _| [
280    ///     linear_color_stop(c.opacity(0.3), 0.0),
281    ///     linear_color_stop(c, 1.0),
282    /// ])
283    /// ```
284    ///
285    /// Or use `chart_to_bar` to position stops at chart-relative values, so
286    /// each bar shows the slice of a chart-wide gradient corresponding to
287    /// its own `[base, value]` span:
288    ///
289    /// ```ignore
290    /// .fill_gradient(|_, chart_range, chart_to_bar| [
291    ///     linear_color_stop(c.opacity(0.3), chart_to_bar(*chart_range.start())),
292    ///     linear_color_stop(c,              chart_to_bar(*chart_range.end())),
293    /// ])
294    /// ```
295    ///
296    /// Stop positions returned outside `[0, 1]` are clipped to the bar; the
297    /// library interpolates colors at the clip points so the on-bar gradient
298    /// still matches the chart-wide one.
299    ///
300    /// The gradient angle is derived from [`BarAlignment`] so stop-0 is at the
301    /// base and stop-1 at the tip. Setting this clears any previously set
302    /// [`BarChart::fill`].
303    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    /// Color each bar's [`label`](Self::label) text, instead of the theme's
326    /// foreground for all of them.
327    ///
328    /// Takes a closure per bar, as [`fill`](Self::fill) does, so a label can
329    /// follow its bar's color.
330    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    /// Show or hide the band-axis line and labels.
339    ///
340    /// Default is true.
341    pub fn label_axis(mut self, label_axis: bool) -> Self {
342        self.label_axis = label_axis;
343        self
344    }
345
346    /// Show or hide the value-axis tick labels.
347    ///
348    /// Placed [`Outside`](AxisLabelPlacement::Outside), the default, the labels
349    /// take a gutter along the band axis, left of vertical bars and below
350    /// horizontal ones.
351    ///
352    /// Default is false.
353    pub fn value_axis(mut self, value_axis: bool) -> Self {
354        self.value_axis = value_axis;
355        self
356    }
357
358    /// Set how many ticks the value axis carries, evenly spaced from the
359    /// baseline to the far edge with both ends included, which drives both the
360    /// grid lines and the value-axis tick labels.
361    ///
362    /// Unlike [`Self::tick_margin`], a stride over the band axis categories,
363    /// this counts the ticks themselves. Values below 2 are raised to 2.
364    ///
365    /// Default is 5.
366    pub fn value_tick_count(mut self, count: usize) -> Self {
367        self.value_tick_count = count.max(2);
368        self
369    }
370
371    /// Set where the value-axis tick labels sit: in a gutter beside the bars,
372    /// or inside the plot beside their grid lines, which keeps the bars' room.
373    ///
374    /// Default is [`AxisLabelPlacement::Outside`].
375    pub fn value_axis_label_placement(mut self, placement: AxisLabelPlacement) -> Self {
376        self.value_axis_label_placement = placement;
377        self
378    }
379
380    /// Set the text of each value-axis tick label from the value at its tick.
381    ///
382    /// Default is whole numbers bare and the rest to one decimal.
383    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    /// Lay the band axis out for `count` bands instead of the data's own
392    /// length.
393    ///
394    /// The data takes the leading bands in order and the rest stay empty, so
395    /// each bar keeps its width and place as the data grows. A `count` below
396    /// the data's length has no effect.
397    pub fn band_count(mut self, count: usize) -> Self {
398        self.band_count = Some(count);
399        self
400    }
401
402    /// Label `count` of the bands, spread evenly from the first to the last,
403    /// instead of every `tick_margin`-th.
404    ///
405    /// With [`Self::band_count`] set, the labels spread over all the bands, so
406    /// they keep their places as the data grows; one that falls on an empty band
407    /// is not drawn yet.
408    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    /// Draw the grid dashed or solid.
419    ///
420    /// Default is true.
421    pub fn grid_dashed(mut self, dashed: bool) -> Self {
422        self.grid_dashed = dashed;
423        self
424    }
425
426    /// Set the bar alignment.
427    ///
428    /// Default is [`BarAlignment::Bottom`].
429    pub fn alignment(mut self, alignment: BarAlignment) -> Self {
430        self.alignment = alignment;
431        self
432    }
433
434    /// Set the corner radii applied to every bar rectangle.
435    ///
436    /// Use [`Corners::all`] for uniform rounding, or construct [`Corners`] manually
437    /// to round only specific corners (e.g. just the tip end of each bar).
438    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    /// Set the gap between neighbouring bars, as a share of each band.
444    ///
445    /// Default is 0.4.
446    pub fn padding_inner(mut self, padding: f32) -> Self {
447        self.padding_inner = padding;
448        self
449    }
450
451    /// Set the gap before the first bar and after the last, as a share of a band.
452    ///
453    /// Default is 0.2.
454    pub fn padding_outer(mut self, padding: f32) -> Self {
455        self.padding_outer = padding;
456        self
457    }
458
459    /// Keep every bar at most `width` wide, so a few bars across a wide chart
460    /// stay narrow instead of filling their bands.
461    ///
462    /// Default is 30px.
463    pub fn max_band_width(mut self, width: impl Into<Pixels>) -> Self {
464        self.max_band_width = width.into();
465        self
466    }
467
468    /// Draw every bar at least `length` pixels long, so a zero or tiny value
469    /// still shows a stub instead of disappearing into the baseline.
470    ///
471    /// The stub grows the way the bar's value would: away from the zero line,
472    /// to the negative side for a negative value and to the positive side for
473    /// zero. A bar already that long is left alone.
474    ///
475    /// Default is 0.
476    pub fn min_length(mut self, length: f32) -> Self {
477        self.min_length = length;
478        self
479    }
480
481    /// The band scale (matching `paint`): spans the height for horizontal bars, the width
482    /// otherwise. Shared by `tooltip_state` and `tooltip`.
483    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        // Value-axis labels eat into the band extent at one end; `band_offset`
491        // shifts the bands away from that end when it is the leading one.
492        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    /// Offset added to every band-scale tick.
503    ///
504    /// [`ScaleBand`] ignores the start of its range, so vertical bars are shifted
505    /// by hand to clear the value-axis labels on their left. Horizontal bars put
506    /// those labels below the plot, past the end of the band axis, so they need no
507    /// shift.
508    fn band_offset(&self) -> f32 {
509        if self.alignment.is_horizontal() {
510            0.
511        } else {
512            self.value_axis_gap()
513        }
514    }
515
516    /// The value axis for `bounds`: the scale the bars grow along, and the
517    /// pixel positions of its baseline and far edge. `paint` lays the bars out
518    /// on it and the tooltip reads the hovered bar's frame from it.
519    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        // For horizontal charts the band labels (category names) are rendered
528        // along the value axis and can be arbitrarily wide, so we measure the
529        // actual maximum label width instead of using a fixed constant.
530        // Similarly, value labels (numbers) at the bar ends are measured so the
531        // scale range is always shrunk by exactly the right amount.
532        // Vertical bars keep a line of text clear past the tallest bar when they
533        // carry value labels, so the label above it stays inside the chart.
534        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        // The baseline, and the far edge opposite it.
545        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    /// The frame `paint` gives datum `d`'s bar, the one `fill` receives.
559    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    /// The data range `fill_gradient` reads, the same for every bar.
592    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    /// The color a tooltip row shows for datum `d`: its bar's, the first stop
608    /// of a gradient, or the default fill when `fill` returns a gradient,
609    /// whose stops can't be read back. `frame` is the bar's, as `paint` lays it
610    /// out.
611    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    /// The gutter the value-axis labels take along the band axis: none unless
635    /// they are shown outside the plot.
636    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            // Below the plot, where the gap is a line of text tall.
641            VALUE_AXIS_GAP
642        } else {
643            self.value_label_gap
644        }
645    }
646
647    /// The bands the band axis is laid out for: the data's, or the
648    /// [`Self::band_count`] when larger.
649    fn band_slots(&self) -> usize {
650        self.band_count.unwrap_or(0).max(self.data.len())
651    }
652
653    /// The value-axis tick label text, from the domain maximum at the far end
654    /// down to the minimum at the baseline, matching the value scale.
655    fn value_tick_labels(&self) -> Vec<SharedString> {
656        let Some(value_fn) = self.value.as_ref() else {
657            return vec![];
658        };
659        // The data plus zero, as `value_scale` spans.
660        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    /// Label gaps `(band_side, value_end_side)` reserved along the value axis for
677    /// horizontal bars, measured from the actual label text. Measured once per frame
678    /// in `prepaint` and kept in `horizontal_gaps`, so `paint` and the tooltip share
679    /// one measurement and the crosshair lines up with the bar region.
680    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    /// The extent `(start, length)` of the bars along the value axis, which the
710    /// hover is confined to so the axis labels never show a tooltip.
711    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    /// Whether the cursor is over a bar's row or column rather than the axis labels.
734    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        // Band scale spans the full extent perpendicular to the value axis. Shared with the
780        // tooltip via `band_scale()` so the bars and the hover crosshair stay aligned.
781        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        // Where zero sits along the value axis. Bars grow from here rather than from
791        // the geometric baseline, so negative values extend to the opposite side. With
792        // no negative data zero is the domain minimum and this is the baseline.
793        let zero_pixel = value_scale.tick(&V::zero()).unwrap_or(baseline);
794        let band_offset = self.band_offset();
795
796        // Grid lines and the zero line span their bounds edge to edge, so they are
797        // painted into bounds inset by the value-axis gap. Without this they run
798        // straight through the value-axis labels.
799        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        // Draw band axis (with categorical labels).
813        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                    // Labels are placed one at a time rather than through
820                    // `x_label`, because a chart with negative values needs them
821                    // on either side of the zero line: each label goes on the side
822                    // its own bar leaves empty.
823                    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        // Draw grid, excluding the line at the baseline.
878        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        // Labels inside the plot are painted after the bars, so no bar covers them.
895        let mut inside_labels = None;
896        if self.value_axis {
897            // Ticks run from `far` (the domain maximum) to `baseline` (the minimum),
898            // so the labels walk the domain in the same direction.
899            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                // The labels go in the gap `band_scale` kept clear for them,
907                // right-aligned against the plot area for vertical bars and centred
908                // under it otherwise.
909                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                // Over the plot beside each grid line: above it for vertical bars
925                // but for the topmost, which would leave the plot, and along the
926                // bottom edge for horizontal ones.
927                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        // Draw bars.
949        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        // Chart bounds in pixel space, with origin (0, 0) and size equal to
959        // the full chart extent. Passed to user `fill` closures so they can
960        // position chart-wide backgrounds (gradients, patterns, etc.).
961        let chart_bounds: Bounds<f32> = Bounds {
962            origin: Point::new(0., 0.),
963            size: Size::new(total_width, total_height),
964        };
965
966        // Chart data range in f32 — passed to `fill_gradient` callers and used
967        // by the `chart_to_bar` remap helper.
968        let chart_range = self.gradient_range();
969
970        // The hovered bar keeps its color while the others fade behind it. The
971        // highlight band springs between bars, so each bar's emphasis follows the
972        // band's distance from it and the focus hands over as the band slides.
973        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        // Every bar grows out of the zero line together as the chart appears,
989        // the way Chart.js draws bars in.
990        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                // A value label rides the end of its bar and fades in with it.
1035                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        // Skip the tooltip when the cursor is over the axis labels, not a bar.
1075        if !self.is_over_bars(position, bounds) {
1076            return None;
1077        }
1078
1079        // Only the band scale is needed to hit-test which bar is hovered; the label
1080        // gaps were measured in `prepaint`, so no `window` is required here.
1081        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        // Vertical bars: vertical crosshair at the bar's x. Horizontal bars: horizontal
1096        // crosshair at the bar's y. The box tracks the cursor either way.
1097        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            // The band slides to the hovered bar; on the first hovered frame it
1109            // adopts the bar instead of travelling from where the last hover ended.
1110            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        // Highlight the hovered bar with a translucent band the width of the bar, instead
1136        // of a hairline. Confined to the plot area so it doesn't cover the axis labels,
1137        // and centered where the band has glided to, which the other bars also fade by.
1138        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        // Follow the cursor; `hover` already glides the band.
1163        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
1181/// The end a bar showing `value` reaches along the value axis, at least
1182/// `min_length` pixels from `zero`.
1183fn 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
1203/// Push a bar's value end away from `zero` until the bar is `min` pixels long,
1204/// in the direction its value grows for `alignment`.
1205fn 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
1223/// The two stops `fill` gives datum `d` with bar value `value`, mapped from the
1224/// chart's `range` onto the bar and clipped to it.
1225fn 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
1237/// Clip a two-stop gradient to bar-local `[0, 1]`, interpolating colors at the
1238/// clip points so the on-bar gradient matches the (possibly broader) gradient
1239/// the caller defined.
1240///
1241/// When a stop position falls outside `[0, 1]` (e.g. because `chart_to_bar`
1242/// returned a value past the bar's edge for a chart-relative gradient),
1243/// gpui's renderer would clamp the position and lose the gradient effect.
1244/// This function instead replaces such a stop with the color sampled along
1245/// the line through both stops at position `0.0` or `1.0`, preserving the
1246/// visual slice.
1247fn 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
1290/// Whether a vertical bar's category label belongs below the zero line.
1291///
1292/// A bar grows away from the zero line, so its label goes on the side the bar
1293/// leaves empty. Which side that is flips with both the sign of the value and the
1294/// alignment. A zero-length bar counts as positive, which puts its label in the
1295/// axis gap rather than inside the plot.
1296fn label_below_zero_line(value: f32, alignment: BarAlignment) -> bool {
1297    (value < 0.) == (alignment == BarAlignment::Top)
1298}
1299
1300/// `count` evenly spaced tick positions along the value axis.
1301///
1302/// Runs from `far` (the value domain's maximum) through `baseline` (its minimum)
1303/// inclusive, so the last position is the baseline. `count` is at least 2.
1304fn 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        // Bottom-aligned: positive bars grow up, leaving the space below free.
1318        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        // Top-aligned bars grow the other way, so the sides swap.
1323        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        // Both ends are included, so 5 ticks means 4 intervals.
1331        assert_eq!(
1332            value_tick_positions(10., 110., 5),
1333            vec![10., 35., 60., 85., 110.]
1334        );
1335
1336        // Top-aligned charts have the baseline before the far edge.
1337        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        // A zero or tiny bar grows the way a positive one would.
1345        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        // A small negative bar grows to the other side of the zero line.
1363        assert_eq!(
1364            extend_to_min_length(50.5, 50., true, BarAlignment::Bottom, 2.),
1365            52.
1366        );
1367
1368        // A bar already long enough is left alone.
1369        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        // Labels spread over every band, so they stay put as the data grows.
1389        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        // Two bars laid out for four bands take the first half of the width.
1408        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        // A bar keeps its place as the data grows into the empty bands.
1414        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        // Labels inside the plot leave the bars their full width.
1419        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    /// A tooltip row shows its bar's color: a solid fill as is, a
1428    /// `fill_gradient` by its first stop, and the default fill otherwise.
1429    #[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    /// The tooltip reads each bar's frame as `paint` lays it out, so a `fill`
1474    /// that reads the frame colors the swatch as it colors the bar.
1475    #[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        // Both grow from zero: one up, one down twice as far.
1486        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}