use std::cell::RefCell;
use std::rc::Rc;
use arc_motion::{arc_spring_with_options, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, Corners, ElementId, FocusHandle, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
Window, base::StyledExt as _, canvas, div, fill, point, prelude::*, px, size,
};
use super::common::{build_dashed_polyline, format_grouped, nice_scale_positive};
pub const BAR_CHART_TOP_PAD: f32 = 12.0;
pub const BAR_CHART_FILL_RATIO: f32 = 0.58;
pub const BAR_CHART_MAX_BAR_W: f32 = 28.0;
pub const BAR_CHART_RADIUS: f32 = 4.0;
#[derive(Clone, Debug, PartialEq)]
pub struct BarChartDatum {
pub key: SharedString,
pub label: SharedString,
pub axis_label: Option<SharedString>,
pub value: f64,
}
impl BarChartDatum {
pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>, value: f64) -> Self {
Self {
key: key.into(),
label: label.into(),
axis_label: None,
value,
}
}
pub fn axis_label(mut self, text: impl Into<SharedString>) -> Self {
self.axis_label = Some(text.into());
self
}
}
pub fn bar_chart_stats(data: &[BarChartDatum]) -> (f64, f64) {
if data.is_empty() {
return (0.0, 0.0);
}
let sum: f64 = data.iter().map(|d| d.value.max(0.0)).sum();
let peak = data.iter().map(|d| d.value.max(0.0)).fold(0.0f64, f64::max);
(sum / data.len() as f64, peak)
}
pub fn bar_chart_visible_axis_indices(data: &[BarChartDatum], plot_width: f32) -> Vec<usize> {
if data.is_empty() || plot_width <= 20.0 {
return Vec::new();
}
let labeled: Vec<usize> = data
.iter()
.enumerate()
.filter_map(|(i, d)| d.axis_label.as_ref().map(|_| i))
.collect();
if labeled.is_empty() {
return Vec::new();
}
let max_labels = (plot_width / 46.0).floor().max(2.0) as usize;
let stride = labeled.len().div_ceil(max_labels).max(1);
let mut picked: Vec<usize> = labeled
.into_iter()
.rev()
.enumerate()
.filter_map(|(rank, idx)| if rank % stride == 0 { Some(idx) } else { None })
.collect();
picked.reverse();
picked
}
pub fn bar_chart_index_at(x: f32, left: f32, width: f32, count: usize) -> usize {
if count <= 1 || width <= 1e-4 {
return 0;
}
let frac = ((x - left) / width).clamp(0.0, 0.9999);
(frac * count as f32).floor() as usize
}
struct BarChartState {
active: Option<usize>,
plot_bounds: Option<Bounds<Pixels>>,
focus: FocusHandle,
}
#[derive(IntoElement)]
pub struct BarChart {
id: ElementId,
data: Vec<BarChartDatum>,
label: SharedString,
period: SharedString,
unit: SharedString,
average_label: SharedString,
value_label: SharedString,
show_average: bool,
height: f32,
}
impl BarChart {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
period: impl Into<SharedString>,
data: Vec<BarChartDatum>,
) -> Self {
Self {
id: id.into(),
data,
label: label.into(),
period: period.into(),
unit: SharedString::default(),
average_label: SharedString::from("Daily average"),
value_label: SharedString::from("Total"),
show_average: true,
height: 176.0,
}
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = unit.into();
self
}
pub fn average_label(mut self, label: impl Into<SharedString>) -> Self {
self.average_label = label.into();
self
}
pub fn value_label(mut self, label: impl Into<SharedString>) -> Self {
self.value_label = label.into();
self
}
pub fn show_average(mut self, show: bool) -> Self {
self.show_average = show;
self
}
pub fn height(mut self, px_val: f32) -> Self {
self.height = px_val.clamp(100.0, 360.0);
self
}
}
impl RenderOnce for BarChart {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let count = self.data.len();
let last = count.saturating_sub(1);
let (average, peak) = bar_chart_stats(&self.data);
let scale = nice_scale_positive(peak);
let state = window.use_keyed_state(
SharedString::from(format!("arc-barchart-state-{:?}", self.id)),
cx,
|_w, cx| {
Rc::new(RefCell::new(BarChartState {
active: None,
plot_bounds: None,
focus: cx.focus_handle(),
}))
},
);
let st_rc = state.read(cx).clone();
let (active_idx, focus_handle, plot_w) = {
let st = st_rc.borrow();
let idx = st.active.filter(|_| count > 0).map(|i| i.min(last));
let w: f32 = st.plot_bounds.map(|b| b.size.width.into()).unwrap_or(480.0);
(idx, st.focus.clone(), w)
};
let anim_top = arc_spring_with_options(
SharedString::from(format!("arc-barchart-top-{:?}", self.id)),
scale.max as f32,
SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
window,
cx,
)
.value
.max(1.0);
let anim_avg = arc_spring_with_options(
SharedString::from(format!("arc-barchart-avg-{:?}", self.id)),
average as f32,
SpringOptions::new(SpringSpec::visual(0.4, 0.0)),
window,
cx,
)
.value
.max(0.0);
let mut anim_values = Vec::with_capacity(count);
for d in &self.data {
let v = arc_spring_with_options(
SharedString::from(format!("arc-barchart-bar-{:?}-{}", self.id, d.key)),
d.value.max(0.0) as f32,
SpringOptions::new(SpringSpec::visual(0.38, 0.0)),
window,
cx,
)
.value
.max(0.0);
anim_values.push(v);
}
let scrubbing = active_idx.is_some();
let cursor_target = active_idx.map(|i| i as f32).unwrap_or(0.0);
let cursor_slot = arc_spring_with_options(
SharedString::from(format!("arc-barchart-cursor-{:?}", self.id)),
cursor_target,
SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
window,
cx,
)
.value;
let shown_val = active_idx
.and_then(|i| self.data.get(i))
.map(|d| d.value)
.unwrap_or(average);
let heading_sub = if scrubbing {
self.value_label.clone()
} else {
self.average_label.clone()
};
let period_text = active_idx
.and_then(|i| self.data.get(i))
.map(|d| d.label.clone())
.unwrap_or_else(|| self.period.clone());
let unit_suffix = if self.unit.is_empty() {
String::new()
} else {
format!(" {}", self.unit)
};
let headline_num = format!("{}{}", format_grouped(shown_val.round(), 0), unit_suffix);
let bar_color = colors.accent;
let bar_dim_color = oklab_mix(colors.accent, colors.surface, 0.45);
let grid_color = colors.border_subtle;
let avg_color = colors.text_muted;
let cursor_color = colors.border_strong;
let ticks = scale.ticks.clone();
let show_avg = self.show_average;
let plot_height = self.height;
let st_paint = st_rc.clone();
let st_down = st_rc.clone();
let st_move = st_rc.clone();
let st_leave = st_rc.clone();
let st_key = st_rc.clone();
let plot_canvas = canvas(
move |bounds, _w, _cx| {
st_paint.borrow_mut().plot_bounds = Some(bounds);
bounds
},
move |bounds, _, window, _cx| {
let left: f32 = bounds.origin.x.into();
let top: f32 = bounds.origin.y.into();
let w: f32 = bounds.size.width.into();
let h: f32 = bounds.size.height.into();
if w <= 2.0 || h <= 2.0 {
return;
}
let usable_h = (h - BAR_CHART_TOP_PAD).max(8.0);
let to_y = |v: f32| -> f32 { top + h - (v / anim_top) * usable_h };
for &t in &ticks {
let y = to_y(t as f32).round();
window.paint_quad(fill(
Bounds::new(point(px(left), px(y)), size(px(w), px(1.0))),
grid_color,
));
}
if scrubbing && count > 0 {
let slot_w = w / count as f32;
let cx_px = left + (cursor_slot + 0.5) * slot_w;
window.paint_quad(fill(
Bounds::new(point(px(cx_px - 0.5), px(top)), size(px(1.0), px(h))),
cursor_color,
));
}
if count > 0 {
let slot_w = w / count as f32;
let bar_w = (slot_w * BAR_CHART_FILL_RATIO).clamp(3.0, BAR_CHART_MAX_BAR_W);
for (i, &val) in anim_values.iter().enumerate() {
let bar_h = ((val / anim_top) * usable_h).clamp(0.0, usable_h);
if bar_h <= 0.5 {
continue;
}
let center = left + (i as f32 + 0.5) * slot_w;
let x = center - bar_w * 0.5;
let y = top + h - bar_h;
let r = BAR_CHART_RADIUS.min(bar_w * 0.5).min(bar_h);
let is_active = active_idx == Some(i);
let col = if scrubbing && !is_active {
bar_dim_color
} else {
bar_color
};
window.paint_quad(
fill(
Bounds::new(point(px(x), px(y)), size(px(bar_w), px(bar_h))),
col,
)
.corner_radii(Corners {
top_left: px(r),
top_right: px(r),
bottom_right: px(0.0),
bottom_left: px(0.0),
}),
);
}
}
if show_avg && anim_avg > 0.0 {
let ay_min = top + 2.0;
let ay_max = (top + h - 1.0).max(ay_min);
let ay = to_y(anim_avg).clamp(ay_min, ay_max);
let dashes = build_dashed_polyline(
&[point(px(left), px(ay)), point(px(left + w), px(ay))],
1.25,
4.0,
4.0,
);
for dash in dashes {
window.paint_path(dash, avg_color);
}
}
},
)
.w_full()
.h(px(plot_height));
let visible_axis = bar_chart_visible_axis_indices(&self.data, plot_w);
let mut y_axis = div().w(px(44.0)).h(px(plot_height)).flex_none().relative();
let usable_h = (plot_height - BAR_CHART_TOP_PAD).max(8.0);
for &t in &scale.ticks {
let y = (plot_height - (t as f32 / anim_top) * usable_h - 7.0)
.clamp(0.0, (plot_height - 14.0).max(0.0));
y_axis = y_axis.child(
div()
.absolute()
.top(px(y))
.right_0()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(format_grouped(t, 0)),
);
}
let mut x_axis = div().w_full().h(px(20.0)).relative();
if count > 0 {
let slot_w = plot_w / count as f32;
for idx in visible_axis {
if let Some(ref text) = self.data[idx].axis_label {
let left_px =
((idx as f32 + 0.5) * slot_w - 22.0).clamp(0.0, (plot_w - 44.0).max(0.0));
x_axis = x_axis.child(
div()
.absolute()
.left(px(left_px))
.top(px(2.0))
.w(px(44.0))
.flex()
.justify_center()
.text_size(Typography::TEXT_XS)
.text_color(if active_idx == Some(idx) {
colors.foreground
} else {
colors.text_muted
})
.child(text.clone()),
);
}
}
}
div()
.id(self.id)
.w_full()
.p(Spacing::S5)
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.flex()
.flex_col()
.gap(Spacing::S3)
.child(
div()
.flex()
.items_baseline()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_muted)
.child(heading_sub),
)
.child(
div()
.text_size(Typography::TEXT_2XL)
.font_semibold()
.text_color(colors.foreground)
.child(headline_num),
),
)
.child(
div()
.flex()
.flex_col()
.items_end()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_secondary)
.child(self.label),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(period_text),
),
),
)
.child(
div()
.w_full()
.flex()
.items_start()
.gap(Spacing::S2)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.id(SharedString::from(format!("arc-barchart-plot-{}", count)))
.w_full()
.h(px(plot_height))
.track_focus(&focus_handle)
.role(Role::Slider)
.cursor_pointer()
.on_mouse_down(
MouseButton::Left,
move |ev: &MouseDownEvent, window, _cx| {
if count == 0 {
return;
}
let bounds = st_down.borrow().plot_bounds;
if let Some(b) = bounds {
let x: f32 = ev.position.x.into();
let left: f32 = b.origin.x.into();
let w: f32 = b.size.width.into();
st_down.borrow_mut().active =
Some(bar_chart_index_at(x, left, w, count));
window.refresh();
}
},
)
.on_mouse_move(move |ev: &MouseMoveEvent, window, _cx| {
if count == 0 {
return;
}
let bounds = st_move.borrow().plot_bounds;
if let Some(b) = bounds {
let x: f32 = ev.position.x.into();
let y: f32 = ev.position.y.into();
let left: f32 = b.origin.x.into();
let top: f32 = b.origin.y.into();
let w: f32 = b.size.width.into();
let h: f32 = b.size.height.into();
let inside = x >= left
&& x <= left + w
&& y >= top
&& y <= top + h;
let next = if inside {
Some(bar_chart_index_at(x, left, w, count))
} else {
None
};
let mut st = st_move.borrow_mut();
if st.active != next {
st.active = next;
window.refresh();
}
}
})
.on_hover(move |hovered, window, _cx| {
if !*hovered {
let mut st = st_leave.borrow_mut();
if st.active.is_some() {
st.active = None;
window.refresh();
}
}
})
.on_key_down(move |ev: &KeyDownEvent, window, _cx| {
if count == 0 {
return;
}
let mut st = st_key.borrow_mut();
let cur = st.active.unwrap_or(last);
let next = match ev.keystroke.key.as_str() {
"escape" => {
st.active = None;
window.refresh();
return;
}
"left" | "down" => cur.saturating_sub(1),
"right" | "up" => (cur + 1).min(last),
"home" => 0,
"end" => last,
_ => return,
};
st.active = Some(next);
window.refresh();
})
.child(plot_canvas),
)
.child(x_axis),
)
.child(y_axis),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bar_chart_stats_axis_thinning_and_pointer_hit() {
let data = vec![
BarChartDatum::new("d1", "Mon", 30.0).axis_label("M"),
BarChartDatum::new("d2", "Tue", 60.0).axis_label("T"),
BarChartDatum::new("d3", "Wed", 45.0).axis_label("W"),
BarChartDatum::new("d4", "Thu", 85.0).axis_label("T"),
];
let (avg, peak) = bar_chart_stats(&data);
assert!((avg - 55.0).abs() < 1e-6);
assert!((peak - 85.0).abs() < 1e-6);
let picks = bar_chart_visible_axis_indices(&data, 320.0);
assert_eq!(picks, vec![0, 1, 2, 3]);
let tight = bar_chart_visible_axis_indices(&data, 96.0);
assert_eq!(*tight.last().unwrap(), 3);
assert_eq!(bar_chart_index_at(10.0, 0.0, 100.0, 4), 0);
assert_eq!(bar_chart_index_at(55.0, 0.0, 100.0, 4), 2);
assert_eq!(bar_chart_index_at(99.0, 0.0, 100.0, 4), 3);
}
}