use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use arc_motion::{arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, RenderOnce, Role, SharedString,
Styled, Window, base::StyledExt as _, canvas, div, fill, point, prelude::*, px, size,
};
use super::common::{
build_area_fill, build_circle_fill, build_dashed_polyline, build_polyline_stroke,
chart_series_color, format_compact, format_grouped, nice_scale, sample_curve_at,
sample_monotone_curve, slice_polyline_by_progress,
};
pub const LINE_CHART_TOP_PAD: f32 = 12.0;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum LineCurve {
#[default]
Smooth,
Linear,
}
#[derive(Clone, Debug)]
pub struct LineChartSeries {
pub key: SharedString,
pub label: SharedString,
pub color: Option<Hsla>,
pub dashed: bool,
pub area: Option<bool>,
}
impl LineChartSeries {
pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
label: label.into(),
color: None,
dashed: false,
area: None,
}
}
pub fn color(mut self, color: Hsla) -> Self {
self.color = Some(color);
self
}
pub fn dashed(mut self, dashed: bool) -> Self {
self.dashed = dashed;
self
}
pub fn area(mut self, area: bool) -> Self {
self.area = Some(area);
self
}
}
#[derive(Clone, Debug)]
pub struct LineChartDatum {
pub key: SharedString,
pub label: SharedString,
pub axis_label: Option<SharedString>,
pub values: HashMap<SharedString, f64>,
}
impl LineChartDatum {
pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
label: label.into(),
axis_label: None,
values: HashMap::new(),
}
}
pub fn axis_label(mut self, label: impl Into<SharedString>) -> Self {
self.axis_label = Some(label.into());
self
}
pub fn value(mut self, series_key: impl Into<SharedString>, val: f64) -> Self {
self.values.insert(series_key.into(), val);
self
}
}
pub fn line_chart_visible_extents(
data: &[LineChartDatum],
series: &[LineChartSeries],
hidden: &HashSet<SharedString>,
) -> Option<(f64, f64)> {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for s in series {
if hidden.contains(&s.key) {
continue;
}
for d in data {
let v = d.values.get(&s.key).copied().unwrap_or(0.0);
lo = lo.min(v);
hi = hi.max(v);
}
}
if lo.is_finite() && hi.is_finite() {
Some((lo, hi))
} else {
None
}
}
pub fn line_chart_axis_picks(data: &[LineChartDatum], width: f32) -> Vec<usize> {
let labeled: Vec<usize> = data
.iter()
.enumerate()
.filter_map(|(i, d)| d.axis_label.as_ref().map(|_| i))
.collect();
if width <= 20.0 || labeled.is_empty() {
return Vec::new();
}
let room = (width / 76.0).floor().max(2.0) as usize;
let stride = labeled.len().div_ceil(room).max(1);
let mut out: Vec<usize> = labeled
.into_iter()
.rev()
.enumerate()
.filter_map(|(rank, i)| if rank % stride == 0 { Some(i) } else { None })
.collect();
out.reverse();
out
}
pub fn line_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, 1.0);
(frac * (count - 1) as f32).round() as usize
}
struct LineChartState {
active: Option<usize>,
own_hidden: HashSet<SharedString>,
mounted_at_secs: Option<f64>,
plot_bounds: Option<Bounds<Pixels>>,
focus: FocusHandle,
}
#[derive(IntoElement)]
pub struct LineChart {
id: ElementId,
label: SharedString,
series: Vec<LineChartSeries>,
data: Vec<LineChartDatum>,
unit: SharedString,
height: f32,
curve: LineCurve,
legend: Option<bool>,
loading: bool,
empty_label: SharedString,
}
impl LineChart {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
series: Vec<LineChartSeries>,
data: Vec<LineChartDatum>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
series,
data,
unit: SharedString::default(),
height: 220.0,
curve: LineCurve::Smooth,
legend: None,
loading: false,
empty_label: SharedString::from("No data for this range"),
}
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = unit.into();
self
}
pub fn height(mut self, px_val: f32) -> Self {
self.height = px_val.clamp(120.0, 420.0);
self
}
pub fn curve(mut self, curve: LineCurve) -> Self {
self.curve = curve;
self
}
pub fn legend(mut self, show: bool) -> Self {
self.legend = Some(show);
self
}
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
self.empty_label = label.into();
self
}
}
impl RenderOnce for LineChart {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let count = self.data.len();
let last = count.saturating_sub(1);
let show_legend = self.legend.unwrap_or(self.series.len() > 1);
let state = window.use_keyed_state(
SharedString::from(format!("arc-linechart-state-{:?}", self.id)),
cx,
|_w, cx| {
Rc::new(RefCell::new(LineChartState {
active: None,
own_hidden: HashSet::new(),
mounted_at_secs: None,
plot_bounds: None,
focus: cx.focus_handle(),
}))
},
);
let st_rc = state.read(cx).clone();
let (active_idx, hidden_set, focus_handle, draw_progress, plot_w) = {
let mut st = st_rc.borrow_mut();
let start = *st.mounted_at_secs.get_or_insert(now);
let progress = if reduced {
1.0
} else {
let dur = 0.7f64;
let t = ((now - start) / dur).clamp(0.0, 1.0) as f32;
let eased = if t < 0.5 {
4.0 * t * t * t
} else {
1.0 - (-2.0 * t + 2.0).powi(3) * 0.5
};
if t < 1.0 {
window.request_animation_frame();
}
eased
};
let w: f32 = st.plot_bounds.map(|b| b.size.width.into()).unwrap_or(520.0);
(
st.active.filter(|_| count > 0).map(|i| i.min(last)),
st.own_hidden.clone(),
st.focus.clone(),
progress,
w,
)
};
let extents = line_chart_visible_extents(&self.data, &self.series, &hidden_set)
.unwrap_or((0.0, 100.0));
let scale = nice_scale(extents.0, extents.1, 4);
let anim_min = arc_spring_with_options(
SharedString::from(format!("arc-linechart-min-{:?}", self.id)),
scale.min as f32,
SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
window,
cx,
)
.value;
let anim_max = arc_spring_with_options(
SharedString::from(format!("arc-linechart-max-{:?}", self.id)),
scale.max as f32,
SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
window,
cx,
)
.value;
let scrubbing = active_idx.is_some();
let cursor_target = active_idx
.map(|i| {
if last > 0 {
i as f32 / last as f32
} else {
0.5
}
})
.unwrap_or(1.0);
let cursor_norm = arc_spring_with_options(
SharedString::from(format!("arc-linechart-cursor-{:?}", self.id)),
cursor_target,
SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
window,
cx,
)
.value
.clamp(0.0, 1.0);
let smooth = self.curve == LineCurve::Smooth;
struct RenderSeries {
color: Hsla,
dashed: bool,
area: bool,
presence: f32,
curve: Vec<(f64, f64)>,
}
let mut render_series = Vec::with_capacity(self.series.len());
for (idx, s) in self.series.iter().enumerate() {
let visible = !hidden_set.contains(&s.key);
let presence = arc_spring_with_options(
SharedString::from(format!("arc-linechart-vis-{:?}-{}", self.id, s.key)),
if visible { 1.0 } else { 0.0 },
SpringOptions::new(SpringSpec::visual(0.32, 0.0)),
window,
cx,
)
.value
.clamp(0.0, 1.0);
let vals: Vec<f64> = self
.data
.iter()
.map(|d| d.values.get(&s.key).copied().unwrap_or(0.0))
.collect();
let color = s.color.unwrap_or_else(|| chart_series_color(&colors, idx));
let area = s.area.unwrap_or(idx == 0);
render_series.push(RenderSeries {
color,
dashed: s.dashed,
area,
presence,
curve: sample_monotone_curve(&vals, smooth, 160),
});
}
let grid_color = colors.border_subtle;
let crosshair_color = colors.border_strong;
let surface_color = colors.surface;
let ticks = scale.ticks.clone();
let plot_height = self.height;
let loading_alpha = if self.loading { 0.45 } else { 1.0 };
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 span = (anim_max - anim_min).abs().max(1e-4);
let usable_h = (h - LINE_CHART_TOP_PAD).max(8.0);
let to_y = |v: f32| -> f32 {
top + LINE_CHART_TOP_PAD + (1.0 - (v - anim_min) / span) * usable_h
};
for &t in &ticks {
let y = to_y(t as f32).round();
if y >= top && y <= top + h {
window.paint_quad(fill(
Bounds::new(point(px(left), px(y)), size(px(w), px(1.0))),
grid_color,
));
}
}
for rs in &render_series {
if rs.presence <= 0.02 || rs.curve.len() < 2 {
continue;
}
let pts: Vec<Point<Pixels>> = rs
.curve
.iter()
.map(|&(xn, yv)| {
let y_val = anim_min + (yv as f32 - anim_min) * rs.presence;
point(px(left + xn as f32 * w), px(to_y(y_val)))
})
.collect();
let drawn_pts = slice_polyline_by_progress(&pts, draw_progress);
if rs.area {
let area_col = oklab_mix(rs.color, surface_color, 0.14)
.alpha(0.24 * rs.presence * loading_alpha);
if let Some(area_path) = build_area_fill(&drawn_pts, px(top + h)) {
window.paint_path(area_path, area_col);
}
}
let stroke_col = rs.color.alpha(rs.color.a * rs.presence * loading_alpha);
if rs.dashed {
for dash in build_dashed_polyline(&drawn_pts, 2.0, 5.0, 4.0) {
window.paint_path(dash, stroke_col);
}
} else if let Some(path) = build_polyline_stroke(&drawn_pts, 2.2) {
window.paint_path(path, stroke_col);
}
}
if scrubbing && count > 0 {
let cx_px = left + cursor_norm * w;
window.paint_quad(fill(
Bounds::new(point(px(cx_px - 0.5), px(top)), size(px(1.0), px(h))),
crosshair_color,
));
for rs in &render_series {
if rs.presence <= 0.3 || rs.curve.is_empty() {
continue;
}
let val = sample_curve_at(&rs.curve, cursor_norm as f64) as f32;
let y_val = anim_min + (val - anim_min) * rs.presence;
let cy_px = to_y(y_val);
if let Some(halo) = build_circle_fill(cx_px, cy_px, 5.2, 16) {
window.paint_path(halo, surface_color);
}
if let Some(dot) = build_circle_fill(cx_px, cy_px, 3.6, 16) {
window.paint_path(dot, rs.color.alpha(rs.color.a * rs.presence));
}
}
}
},
)
.w_full()
.h(px(plot_height));
let tooltip_el = active_idx.and_then(|idx| self.data.get(idx)).map(|datum| {
let cx_px = cursor_norm * plot_w;
let tip_w = 168.0f32;
let flip_left = cx_px + 14.0 + tip_w > plot_w;
let left_px = if flip_left {
(cx_px - 14.0 - tip_w).max(4.0)
} else {
(cx_px + 14.0).min((plot_w - tip_w).max(4.0))
};
let unit_suffix = if self.unit.is_empty() {
String::new()
} else {
format!(" {}", self.unit)
};
let mut card = div()
.absolute()
.left(px(left_px))
.top(px(12.0))
.w(px(tip_w))
.p(Spacing::S2)
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.flex()
.flex_col()
.gap(px(4.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.child(datum.label.clone()),
);
for (s_idx, s) in self.series.iter().enumerate() {
if hidden_set.contains(&s.key) {
continue;
}
let val = datum.values.get(&s.key).copied().unwrap_or(0.0);
let col = s
.color
.unwrap_or_else(|| chart_series_color(&colors, s_idx));
card = card.child(
div()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.flex()
.items_center()
.gap(px(6.0))
.child(div().w(px(7.0)).h(px(7.0)).rounded(Radii::PILL).bg(col))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(s.label.clone()),
),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.foreground)
.child(format!("{}{}", format_grouped(val, 1), unit_suffix)),
),
);
}
card
});
let usable_h = (plot_height - LINE_CHART_TOP_PAD).max(8.0);
let span = (anim_max - anim_min).abs().max(1e-4);
let mut y_axis = div().w(px(44.0)).h(px(plot_height)).flex_none().relative();
for &t in &scale.ticks {
let y = (LINE_CHART_TOP_PAD + (1.0 - (t as f32 - anim_min) / span) * 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(px(6.0))
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(format_compact(t)),
);
}
let axis_picks = line_chart_axis_picks(&self.data, plot_w);
let mut x_axis = div().w_full().h(px(20.0)).relative();
if last > 0 {
for idx in axis_picks {
if let Some(ref text) = self.data[idx].axis_label {
let frac = idx as f32 / last as f32;
let left_px = (frac * plot_w - 28.0).clamp(0.0, (plot_w - 56.0).max(0.0));
x_axis = x_axis.child(
div()
.absolute()
.left(px(left_px))
.top(px(2.0))
.w(px(56.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()),
);
}
}
}
let legend_row = if show_legend {
let mut row = div().flex().items_center().flex_wrap().gap(Spacing::S2);
for (idx, s) in self.series.iter().enumerate() {
let is_hidden = hidden_set.contains(&s.key);
let col = s.color.unwrap_or_else(|| chart_series_color(&colors, idx));
let key = s.key.clone();
let st_toggle = st_rc.clone();
row = row.child(
div()
.id(SharedString::from(format!(
"arc-linechart-leg-{:?}-{}",
self.id, idx
)))
.px(Spacing::S2)
.py(px(3.0))
.rounded(Radii::PILL)
.border_1()
.border_color(if is_hidden {
colors.border_subtle
} else {
colors.border
})
.bg(if is_hidden {
colors.surface
} else {
colors.surface_muted
})
.cursor_pointer()
.flex()
.items_center()
.gap(px(6.0))
.on_mouse_down(MouseButton::Left, move |_, window, _cx| {
let mut st = st_toggle.borrow_mut();
if !st.own_hidden.remove(&key) {
st.own_hidden.insert(key.clone());
}
window.refresh();
})
.child(
div()
.w(px(10.0))
.h(px(3.0))
.rounded(Radii::PILL)
.bg(if is_hidden { colors.border_strong } else { col }),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(if is_hidden {
colors.text_muted
} else {
colors.foreground
})
.child(s.label.clone()),
),
);
}
Some(row)
} else {
None
};
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_center()
.justify_between()
.flex_wrap()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(self.label),
)
.when_some(legend_row, |this, leg| this.child(leg)),
)
.child(if count == 0 {
div()
.w_full()
.h(px(plot_height))
.flex()
.items_center()
.justify_center()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(self.empty_label)
.into_any_element()
} else {
div()
.w_full()
.flex()
.items_start()
.child(y_axis)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.id(SharedString::from(format!("arc-linechart-plot-{}", count)))
.relative()
.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| {
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(line_chart_index_at(x, left, w, count));
window.refresh();
}
},
)
.on_mouse_move(move |ev: &MouseMoveEvent, window, _cx| {
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(line_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| {
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)
.when_some(tooltip_el, |this, tip| this.child(tip)),
)
.child(x_axis),
)
.into_any_element()
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_chart_extents_and_axis_picks() {
let series = vec![
LineChartSeries::new("a", "Current"),
LineChartSeries::new("b", "Previous").dashed(true),
];
let data = vec![
LineChartDatum::new("d1", "Day 1")
.axis_label("Sep 1")
.value("a", 120.0)
.value("b", 80.0),
LineChartDatum::new("d2", "Day 2")
.axis_label("Sep 2")
.value("a", 240.0)
.value("b", 90.0),
LineChartDatum::new("d3", "Day 3")
.axis_label("Sep 3")
.value("a", 180.0)
.value("b", 110.0),
];
let hidden = HashSet::new();
assert_eq!(
line_chart_visible_extents(&data, &series, &hidden),
Some((80.0, 240.0))
);
let mut hide_a = HashSet::new();
hide_a.insert(SharedString::from("a"));
assert_eq!(
line_chart_visible_extents(&data, &series, &hide_a),
Some((80.0, 110.0))
);
let picks = line_chart_axis_picks(&data, 320.0);
assert_eq!(*picks.last().unwrap(), 2);
assert_eq!(line_chart_index_at(50.0, 0.0, 100.0, 3), 1);
}
}