Skip to main content

arc_ui/chart/
bar_chart.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! `BarChart`: single-measure comparison chart across days/weeks/months with clean gridlines,
3//! animated bar heights, dashed average reference line, pointer/keyboard scrubbing, and headline readout.
4
5use std::cell::RefCell;
6use std::rc::Rc;
7
8use arc_motion::{arc_spring_with_options, spring::SpringOptions};
9use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
10use gpui_kit::{
11    App, Bounds, Corners, ElementId, FocusHandle, IntoElement, KeyDownEvent, MouseButton,
12    MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
13    Window, base::StyledExt as _, canvas, div, fill, point, prelude::*, px, size,
14};
15
16use super::common::{build_dashed_polyline, format_grouped, nice_scale_positive};
17
18pub const BAR_CHART_TOP_PAD: f32 = 12.0;
19pub const BAR_CHART_FILL_RATIO: f32 = 0.58;
20pub const BAR_CHART_MAX_BAR_W: f32 = 28.0;
21pub const BAR_CHART_RADIUS: f32 = 4.0;
22
23#[derive(Clone, Debug, PartialEq)]
24pub struct BarChartDatum {
25    pub key: SharedString,
26    pub label: SharedString,
27    pub axis_label: Option<SharedString>,
28    pub value: f64,
29}
30
31impl BarChartDatum {
32    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>, value: f64) -> Self {
33        Self {
34            key: key.into(),
35            label: label.into(),
36            axis_label: None,
37            value,
38        }
39    }
40
41    pub fn axis_label(mut self, text: impl Into<SharedString>) -> Self {
42        self.axis_label = Some(text.into());
43        self
44    }
45}
46
47/// Compute average and peak values for a bar chart dataset.
48pub fn bar_chart_stats(data: &[BarChartDatum]) -> (f64, f64) {
49    if data.is_empty() {
50        return (0.0, 0.0);
51    }
52    let sum: f64 = data.iter().map(|d| d.value.max(0.0)).sum();
53    let peak = data.iter().map(|d| d.value.max(0.0)).fold(0.0f64, f64::max);
54    (sum / data.len() as f64, peak)
55}
56
57/// Select axis label indices spaced cleanly from right to left so the newest bar is always labeled.
58pub fn bar_chart_visible_axis_indices(data: &[BarChartDatum], plot_width: f32) -> Vec<usize> {
59    if data.is_empty() || plot_width <= 20.0 {
60        return Vec::new();
61    }
62    let labeled: Vec<usize> = data
63        .iter()
64        .enumerate()
65        .filter_map(|(i, d)| d.axis_label.as_ref().map(|_| i))
66        .collect();
67    if labeled.is_empty() {
68        return Vec::new();
69    }
70    let max_labels = (plot_width / 46.0).floor().max(2.0) as usize;
71    let stride = labeled.len().div_ceil(max_labels).max(1);
72    let mut picked: Vec<usize> = labeled
73        .into_iter()
74        .rev()
75        .enumerate()
76        .filter_map(|(rank, idx)| if rank % stride == 0 { Some(idx) } else { None })
77        .collect();
78    picked.reverse();
79    picked
80}
81
82/// Map pointer x inside `[left, left + width]` to a bar index.
83pub fn bar_chart_index_at(x: f32, left: f32, width: f32, count: usize) -> usize {
84    if count <= 1 || width <= 1e-4 {
85        return 0;
86    }
87    let frac = ((x - left) / width).clamp(0.0, 0.9999);
88    (frac * count as f32).floor() as usize
89}
90
91struct BarChartState {
92    active: Option<usize>,
93    plot_bounds: Option<Bounds<Pixels>>,
94    focus: FocusHandle,
95}
96
97#[derive(IntoElement)]
98pub struct BarChart {
99    id: ElementId,
100    data: Vec<BarChartDatum>,
101    label: SharedString,
102    period: SharedString,
103    unit: SharedString,
104    average_label: SharedString,
105    value_label: SharedString,
106    show_average: bool,
107    height: f32,
108}
109
110impl BarChart {
111    pub fn new(
112        id: impl Into<ElementId>,
113        label: impl Into<SharedString>,
114        period: impl Into<SharedString>,
115        data: Vec<BarChartDatum>,
116    ) -> Self {
117        Self {
118            id: id.into(),
119            data,
120            label: label.into(),
121            period: period.into(),
122            unit: SharedString::default(),
123            average_label: SharedString::from("Daily average"),
124            value_label: SharedString::from("Total"),
125            show_average: true,
126            height: 176.0,
127        }
128    }
129
130    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
131        self.unit = unit.into();
132        self
133    }
134
135    pub fn average_label(mut self, label: impl Into<SharedString>) -> Self {
136        self.average_label = label.into();
137        self
138    }
139
140    pub fn value_label(mut self, label: impl Into<SharedString>) -> Self {
141        self.value_label = label.into();
142        self
143    }
144
145    pub fn show_average(mut self, show: bool) -> Self {
146        self.show_average = show;
147        self
148    }
149
150    pub fn height(mut self, px_val: f32) -> Self {
151        self.height = px_val.clamp(100.0, 360.0);
152        self
153    }
154}
155
156impl RenderOnce for BarChart {
157    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
158        let theme = cx.arc_theme().clone();
159        let colors = theme.colors;
160        let count = self.data.len();
161        let last = count.saturating_sub(1);
162        let (average, peak) = bar_chart_stats(&self.data);
163        let scale = nice_scale_positive(peak);
164
165        let state = window.use_keyed_state(
166            SharedString::from(format!("arc-barchart-state-{:?}", self.id)),
167            cx,
168            |_w, cx| {
169                Rc::new(RefCell::new(BarChartState {
170                    active: None,
171                    plot_bounds: None,
172                    focus: cx.focus_handle(),
173                }))
174            },
175        );
176        let st_rc = state.read(cx).clone();
177        let (active_idx, focus_handle, plot_w) = {
178            let st = st_rc.borrow();
179            let idx = st.active.filter(|_| count > 0).map(|i| i.min(last));
180            let w: f32 = st.plot_bounds.map(|b| b.size.width.into()).unwrap_or(480.0);
181            (idx, st.focus.clone(), w)
182        };
183
184        // Spring-animated scale top & average line
185        let anim_top = arc_spring_with_options(
186            SharedString::from(format!("arc-barchart-top-{:?}", self.id)),
187            scale.max as f32,
188            SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
189            window,
190            cx,
191        )
192        .value
193        .max(1.0);
194
195        let anim_avg = arc_spring_with_options(
196            SharedString::from(format!("arc-barchart-avg-{:?}", self.id)),
197            average as f32,
198            SpringOptions::new(SpringSpec::visual(0.4, 0.0)),
199            window,
200            cx,
201        )
202        .value
203        .max(0.0);
204
205        // Animate each bar's value keyed by its stable datum key
206        let mut anim_values = Vec::with_capacity(count);
207        for d in &self.data {
208            let v = arc_spring_with_options(
209                SharedString::from(format!("arc-barchart-bar-{:?}-{}", self.id, d.key)),
210                d.value.max(0.0) as f32,
211                SpringOptions::new(SpringSpec::visual(0.38, 0.0)),
212                window,
213                cx,
214            )
215            .value
216            .max(0.0);
217            anim_values.push(v);
218        }
219
220        let scrubbing = active_idx.is_some();
221        let cursor_target = active_idx.map(|i| i as f32).unwrap_or(0.0);
222        let cursor_slot = arc_spring_with_options(
223            SharedString::from(format!("arc-barchart-cursor-{:?}", self.id)),
224            cursor_target,
225            SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
226            window,
227            cx,
228        )
229        .value;
230
231        let shown_val = active_idx
232            .and_then(|i| self.data.get(i))
233            .map(|d| d.value)
234            .unwrap_or(average);
235        let heading_sub = if scrubbing {
236            self.value_label.clone()
237        } else {
238            self.average_label.clone()
239        };
240        let period_text = active_idx
241            .and_then(|i| self.data.get(i))
242            .map(|d| d.label.clone())
243            .unwrap_or_else(|| self.period.clone());
244        let unit_suffix = if self.unit.is_empty() {
245            String::new()
246        } else {
247            format!(" {}", self.unit)
248        };
249        let headline_num = format!("{}{}", format_grouped(shown_val.round(), 0), unit_suffix);
250
251        let bar_color = colors.accent;
252        let bar_dim_color = oklab_mix(colors.accent, colors.surface, 0.45);
253        let grid_color = colors.border_subtle;
254        let avg_color = colors.text_muted;
255        let cursor_color = colors.border_strong;
256        let ticks = scale.ticks.clone();
257        let show_avg = self.show_average;
258        let plot_height = self.height;
259
260        let st_paint = st_rc.clone();
261        let st_down = st_rc.clone();
262        let st_move = st_rc.clone();
263        let st_leave = st_rc.clone();
264        let st_key = st_rc.clone();
265
266        let plot_canvas = canvas(
267            move |bounds, _w, _cx| {
268                st_paint.borrow_mut().plot_bounds = Some(bounds);
269                bounds
270            },
271            move |bounds, _, window, _cx| {
272                let left: f32 = bounds.origin.x.into();
273                let top: f32 = bounds.origin.y.into();
274                let w: f32 = bounds.size.width.into();
275                let h: f32 = bounds.size.height.into();
276                if w <= 2.0 || h <= 2.0 {
277                    return;
278                }
279                let usable_h = (h - BAR_CHART_TOP_PAD).max(8.0);
280                let to_y = |v: f32| -> f32 { top + h - (v / anim_top) * usable_h };
281
282                // Horizontal gridlines
283                for &t in &ticks {
284                    let y = to_y(t as f32).round();
285                    window.paint_quad(fill(
286                        Bounds::new(point(px(left), px(y)), size(px(w), px(1.0))),
287                        grid_color,
288                    ));
289                }
290
291                // Scrubbing cursor guide behind bars
292                if scrubbing && count > 0 {
293                    let slot_w = w / count as f32;
294                    let cx_px = left + (cursor_slot + 0.5) * slot_w;
295                    window.paint_quad(fill(
296                        Bounds::new(point(px(cx_px - 0.5), px(top)), size(px(1.0), px(h))),
297                        cursor_color,
298                    ));
299                }
300
301                // Bars with rounded top corners
302                if count > 0 {
303                    let slot_w = w / count as f32;
304                    let bar_w = (slot_w * BAR_CHART_FILL_RATIO).clamp(3.0, BAR_CHART_MAX_BAR_W);
305                    for (i, &val) in anim_values.iter().enumerate() {
306                        let bar_h = ((val / anim_top) * usable_h).clamp(0.0, usable_h);
307                        if bar_h <= 0.5 {
308                            continue;
309                        }
310                        let center = left + (i as f32 + 0.5) * slot_w;
311                        let x = center - bar_w * 0.5;
312                        let y = top + h - bar_h;
313                        let r = BAR_CHART_RADIUS.min(bar_w * 0.5).min(bar_h);
314                        let is_active = active_idx == Some(i);
315                        let col = if scrubbing && !is_active {
316                            bar_dim_color
317                        } else {
318                            bar_color
319                        };
320                        window.paint_quad(
321                            fill(
322                                Bounds::new(point(px(x), px(y)), size(px(bar_w), px(bar_h))),
323                                col,
324                            )
325                            .corner_radii(Corners {
326                                top_left: px(r),
327                                top_right: px(r),
328                                bottom_right: px(0.0),
329                                bottom_left: px(0.0),
330                            }),
331                        );
332                    }
333                }
334
335                // Dashed average reference line
336                if show_avg && anim_avg > 0.0 {
337                    let ay_min = top + 2.0;
338                    let ay_max = (top + h - 1.0).max(ay_min);
339                    let ay = to_y(anim_avg).clamp(ay_min, ay_max);
340                    let dashes = build_dashed_polyline(
341                        &[point(px(left), px(ay)), point(px(left + w), px(ay))],
342                        1.25,
343                        4.0,
344                        4.0,
345                    );
346                    for dash in dashes {
347                        window.paint_path(dash, avg_color);
348                    }
349                }
350            },
351        )
352        .w_full()
353        .h(px(plot_height));
354
355        let visible_axis = bar_chart_visible_axis_indices(&self.data, plot_w);
356
357        // Y-axis tick labels column on right
358        let mut y_axis = div().w(px(44.0)).h(px(plot_height)).flex_none().relative();
359        let usable_h = (plot_height - BAR_CHART_TOP_PAD).max(8.0);
360        for &t in &scale.ticks {
361            let y = (plot_height - (t as f32 / anim_top) * usable_h - 7.0)
362                .clamp(0.0, (plot_height - 14.0).max(0.0));
363            y_axis = y_axis.child(
364                div()
365                    .absolute()
366                    .top(px(y))
367                    .right_0()
368                    .text_size(Typography::TEXT_XS)
369                    .text_color(colors.text_muted)
370                    .child(format_grouped(t, 0)),
371            );
372        }
373
374        // X-axis label row
375        let mut x_axis = div().w_full().h(px(20.0)).relative();
376        if count > 0 {
377            let slot_w = plot_w / count as f32;
378            for idx in visible_axis {
379                if let Some(ref text) = self.data[idx].axis_label {
380                    let left_px =
381                        ((idx as f32 + 0.5) * slot_w - 22.0).clamp(0.0, (plot_w - 44.0).max(0.0));
382                    x_axis = x_axis.child(
383                        div()
384                            .absolute()
385                            .left(px(left_px))
386                            .top(px(2.0))
387                            .w(px(44.0))
388                            .flex()
389                            .justify_center()
390                            .text_size(Typography::TEXT_XS)
391                            .text_color(if active_idx == Some(idx) {
392                                colors.foreground
393                            } else {
394                                colors.text_muted
395                            })
396                            .child(text.clone()),
397                    );
398                }
399            }
400        }
401
402        div()
403            .id(self.id)
404            .w_full()
405            .p(Spacing::S5)
406            .rounded(Radii::PANEL)
407            .border_1()
408            .border_color(colors.border)
409            .bg(colors.surface)
410            .flex()
411            .flex_col()
412            .gap(Spacing::S3)
413            .child(
414                // Headline readout
415                div()
416                    .flex()
417                    .items_baseline()
418                    .justify_between()
419                    .gap(Spacing::S2)
420                    .child(
421                        div()
422                            .flex()
423                            .flex_col()
424                            .gap(px(2.0))
425                            .child(
426                                div()
427                                    .text_size(Typography::TEXT_XS)
428                                    .font_medium()
429                                    .text_color(colors.text_muted)
430                                    .child(heading_sub),
431                            )
432                            .child(
433                                div()
434                                    .text_size(Typography::TEXT_2XL)
435                                    .font_semibold()
436                                    .text_color(colors.foreground)
437                                    .child(headline_num),
438                            ),
439                    )
440                    .child(
441                        div()
442                            .flex()
443                            .flex_col()
444                            .items_end()
445                            .gap(px(2.0))
446                            .child(
447                                div()
448                                    .text_size(Typography::TEXT_XS)
449                                    .font_medium()
450                                    .text_color(colors.text_secondary)
451                                    .child(self.label),
452                            )
453                            .child(
454                                div()
455                                    .text_size(Typography::TEXT_XS)
456                                    .text_color(colors.text_muted)
457                                    .child(period_text),
458                            ),
459                    ),
460            )
461            .child(
462                div()
463                    .w_full()
464                    .flex()
465                    .items_start()
466                    .gap(Spacing::S2)
467                    .child(
468                        div()
469                            .flex_1()
470                            .min_w_0()
471                            .flex()
472                            .flex_col()
473                            .child(
474                                div()
475                                    .id(SharedString::from(format!("arc-barchart-plot-{}", count)))
476                                    .w_full()
477                                    .h(px(plot_height))
478                                    .track_focus(&focus_handle)
479                                    .role(Role::Slider)
480                                    .cursor_pointer()
481                                    .on_mouse_down(
482                                        MouseButton::Left,
483                                        move |ev: &MouseDownEvent, window, _cx| {
484                                            if count == 0 {
485                                                return;
486                                            }
487                                            let bounds = st_down.borrow().plot_bounds;
488                                            if let Some(b) = bounds {
489                                                let x: f32 = ev.position.x.into();
490                                                let left: f32 = b.origin.x.into();
491                                                let w: f32 = b.size.width.into();
492                                                st_down.borrow_mut().active =
493                                                    Some(bar_chart_index_at(x, left, w, count));
494                                                window.refresh();
495                                            }
496                                        },
497                                    )
498                                    .on_mouse_move(move |ev: &MouseMoveEvent, window, _cx| {
499                                        if count == 0 {
500                                            return;
501                                        }
502                                        let bounds = st_move.borrow().plot_bounds;
503                                        if let Some(b) = bounds {
504                                            let x: f32 = ev.position.x.into();
505                                            let y: f32 = ev.position.y.into();
506                                            let left: f32 = b.origin.x.into();
507                                            let top: f32 = b.origin.y.into();
508                                            let w: f32 = b.size.width.into();
509                                            let h: f32 = b.size.height.into();
510                                            let inside = x >= left
511                                                && x <= left + w
512                                                && y >= top
513                                                && y <= top + h;
514                                            let next = if inside {
515                                                Some(bar_chart_index_at(x, left, w, count))
516                                            } else {
517                                                None
518                                            };
519                                            let mut st = st_move.borrow_mut();
520                                            if st.active != next {
521                                                st.active = next;
522                                                window.refresh();
523                                            }
524                                        }
525                                    })
526                                    .on_hover(move |hovered, window, _cx| {
527                                        if !*hovered {
528                                            let mut st = st_leave.borrow_mut();
529                                            if st.active.is_some() {
530                                                st.active = None;
531                                                window.refresh();
532                                            }
533                                        }
534                                    })
535                                    .on_key_down(move |ev: &KeyDownEvent, window, _cx| {
536                                        if count == 0 {
537                                            return;
538                                        }
539                                        let mut st = st_key.borrow_mut();
540                                        let cur = st.active.unwrap_or(last);
541                                        let next = match ev.keystroke.key.as_str() {
542                                            "escape" => {
543                                                st.active = None;
544                                                window.refresh();
545                                                return;
546                                            }
547                                            "left" | "down" => cur.saturating_sub(1),
548                                            "right" | "up" => (cur + 1).min(last),
549                                            "home" => 0,
550                                            "end" => last,
551                                            _ => return,
552                                        };
553                                        st.active = Some(next);
554                                        window.refresh();
555                                    })
556                                    .child(plot_canvas),
557                            )
558                            .child(x_axis),
559                    )
560                    .child(y_axis),
561            )
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568
569    #[test]
570    fn bar_chart_stats_axis_thinning_and_pointer_hit() {
571        let data = vec![
572            BarChartDatum::new("d1", "Mon", 30.0).axis_label("M"),
573            BarChartDatum::new("d2", "Tue", 60.0).axis_label("T"),
574            BarChartDatum::new("d3", "Wed", 45.0).axis_label("W"),
575            BarChartDatum::new("d4", "Thu", 85.0).axis_label("T"),
576        ];
577        let (avg, peak) = bar_chart_stats(&data);
578        assert!((avg - 55.0).abs() < 1e-6);
579        assert!((peak - 85.0).abs() < 1e-6);
580
581        let picks = bar_chart_visible_axis_indices(&data, 320.0);
582        assert_eq!(picks, vec![0, 1, 2, 3]);
583        let tight = bar_chart_visible_axis_indices(&data, 96.0);
584        assert_eq!(*tight.last().unwrap(), 3);
585
586        assert_eq!(bar_chart_index_at(10.0, 0.0, 100.0, 4), 0);
587        assert_eq!(bar_chart_index_at(55.0, 0.0, 100.0, 4), 2);
588        assert_eq!(bar_chart_index_at(99.0, 0.0, 100.0, 4), 3);
589    }
590}