use std::cell::RefCell;
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, 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::{
ChartTone, build_area_fill, build_circle_fill, build_polyline_stroke, format_grouped,
sample_curve_at, sample_monotone_curve, slice_polyline_by_progress,
};
pub const SPARKLINE_INSET_PX: f32 = 6.0;
pub fn sparkline_curve(data: &[f64]) -> Vec<(f64, f64)> {
let safe: Vec<f64> = if data.len() > 1 {
data.to_vec()
} else {
let v = data.first().copied().unwrap_or(0.0);
vec![v, v]
};
let min = safe.iter().copied().fold(f64::INFINITY, f64::min);
let max = safe.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let span = max - min;
let norm: Vec<f64> = safe
.iter()
.map(|&v| {
if span.abs() > 1e-12 {
(v - min) / span
} else {
0.5
}
})
.collect();
sample_monotone_curve(&norm, true, 128)
}
pub fn sparkline_index_at(x: f32, left: f32, width: f32, count: usize) -> usize {
if count <= 1 || width <= 1e-4 {
return 0;
}
let last = count - 1;
let frac = ((x - left) / width).clamp(0.0, 1.0);
(frac * last as f32).round() as usize
}
struct SparklineState {
active: Option<usize>,
mounted_at_secs: Option<f64>,
plot_bounds: Option<Bounds<Pixels>>,
focus: FocusHandle,
}
#[derive(IntoElement)]
pub struct Sparkline {
id: ElementId,
data: Vec<f64>,
label: SharedString,
value: Option<SharedString>,
change: Option<SharedString>,
tone: ChartTone,
width: f32,
height: f32,
labels: Vec<SharedString>,
area: bool,
interactive: bool,
format_value: Option<Rc<dyn Fn(f64, usize) -> SharedString>>,
}
impl Sparkline {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, data: Vec<f64>) -> Self {
Self {
id: id.into(),
data,
label: label.into(),
value: None,
change: None,
tone: ChartTone::Accent,
width: 240.0,
height: 60.0,
labels: Vec::new(),
area: true,
interactive: true,
format_value: None,
}
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn change(mut self, change: impl Into<SharedString>) -> Self {
self.change = Some(change.into());
self
}
pub fn tone(mut self, tone: ChartTone) -> Self {
self.tone = tone;
self
}
pub fn size(mut self, width: f32, height: f32) -> Self {
self.width = width.max(64.0);
self.height = height.max(24.0);
self
}
pub fn labels(mut self, labels: Vec<SharedString>) -> Self {
self.labels = labels;
self
}
pub fn area(mut self, area: bool) -> Self {
self.area = area;
self
}
pub fn interactive(mut self, interactive: bool) -> Self {
self.interactive = interactive;
self
}
pub fn format_value(mut self, f: impl Fn(f64, usize) -> SharedString + 'static) -> Self {
self.format_value = Some(Rc::new(f));
self
}
}
impl RenderOnce for Sparkline {
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 safe_data: Vec<f64> = if self.data.len() > 1 {
self.data.clone()
} else {
let v = self.data.first().copied().unwrap_or(0.0);
vec![v, v]
};
let count = safe_data.len();
let last = count - 1;
let curve = sparkline_curve(&safe_data);
let state = window.use_keyed_state(
SharedString::from(format!("arc-sparkline-state-{:?}", self.id)),
cx,
|_w, cx| {
Rc::new(RefCell::new(SparklineState {
active: None,
mounted_at_secs: None,
plot_bounds: None,
focus: cx.focus_handle(),
}))
},
);
let st_rc = state.read(cx).clone();
let (active_idx, focus_handle, draw_progress) = {
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.65f64;
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 idx = st.active.map(|i| i.min(last));
(idx, st.focus.clone(), progress)
};
let scrubbing = active_idx.is_some();
let cursor_target = active_idx.map(|i| i as f32 / last as f32).unwrap_or(1.0);
let cursor_norm = arc_spring_with_options(
SharedString::from(format!("arc-sparkline-cursor-{:?}", self.id)),
cursor_target,
SpringOptions::new(SpringSpec::visual(0.24, 0.0)),
window,
cx,
)
.value
.clamp(0.0, 1.0);
let format_point = |at: usize| -> SharedString {
if let Some(ref f) = self.format_value {
f(safe_data[at], at)
} else {
SharedString::from(format_grouped(safe_data[at], 1))
}
};
let point_text = format_point(active_idx.unwrap_or(last));
let when_text = active_idx
.and_then(|i| self.labels.get(i).cloned())
.or_else(|| self.labels.get(last).cloned());
let headline = self.value.as_ref().map(|v| {
if scrubbing {
point_text.clone()
} else {
v.clone()
}
});
let aside: SharedString = match active_idx {
None => self.change.clone().unwrap_or_default(),
Some(i) => {
if self.value.is_none() {
match &when_text {
Some(w) => SharedString::from(format!("{point_text} · {w}")),
None => point_text.clone(),
}
} else {
when_text
.clone()
.unwrap_or_else(|| SharedString::from(format!("{} of {}", i + 1, count)))
}
}
};
let tone_color = self.tone.color(&colors);
let area_color = oklab_mix(tone_color, colors.surface, 0.14).alpha(0.32);
let trail_color = oklab_mix(colors.foreground, colors.surface, 0.22);
let baseline_color = colors.border_subtle;
let cursor_line_color = colors.border_strong;
let surface_color = colors.surface;
let landed = draw_progress >= 0.99;
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_height = self.height;
let plot_width = self.width;
let show_area = self.area;
let interactive = self.interactive;
let plot_canvas = canvas(
move |bounds, _window, _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 || curve.len() < 2 {
return;
}
let inner_h = (h - SPARKLINE_INSET_PX * 2.0).max(4.0);
let to_y =
|yn: f64| -> f32 { top + SPARKLINE_INSET_PX + (1.0 - yn as f32) * inner_h };
let pts: Vec<Point<Pixels>> = curve
.iter()
.map(|&(xn, yn)| point(px(left + xn as f32 * w), px(to_y(yn))))
.collect();
let drawn_pts = slice_polyline_by_progress(&pts, draw_progress);
if show_area && let Some(area_path) = build_area_fill(&drawn_pts, px(top + h - 0.5))
{
window.paint_path(area_path, area_color);
}
window.paint_quad(fill(
Bounds::new(point(px(left), px(top + h - 1.0)), size(px(w), px(1.0))),
baseline_color,
));
if scrubbing && landed {
let split_x = left + cursor_norm * w;
let cy = to_y(sample_curve_at(&curve, cursor_norm as f64));
let split_pt = point(px(split_x), px(cy));
let mut lit_pts: Vec<Point<Pixels>> = pts
.iter()
.copied()
.take_while(|p| {
let x: f32 = p.x.into();
x <= split_x
})
.collect();
lit_pts.push(split_pt);
let mut dim_pts: Vec<Point<Pixels>> = vec![split_pt];
dim_pts.extend(pts.iter().copied().skip_while(|p| {
let x: f32 = p.x.into();
x <= split_x
}));
if let Some(p) = build_polyline_stroke(&dim_pts, 2.0) {
window.paint_path(p, trail_color);
}
if let Some(p) = build_polyline_stroke(&lit_pts, 2.2) {
window.paint_path(p, tone_color);
}
window.paint_quad(fill(
Bounds::new(point(px(split_x - 0.5), px(top)), size(px(1.0), px(h))),
cursor_line_color,
));
} else if let Some(p) = build_polyline_stroke(&drawn_pts, 2.2) {
window.paint_path(p, tone_color);
}
if landed {
let cx_px = left + cursor_norm * w;
let cy_px = to_y(sample_curve_at(&curve, cursor_norm as f64));
let outer_r = if scrubbing { 5.2 } else { 3.6 };
if let Some(halo) = build_circle_fill(cx_px, cy_px, outer_r + 1.5, 18) {
window.paint_path(halo, surface_color);
}
if let Some(dot) = build_circle_fill(cx_px, cy_px, outer_r, 18) {
window.paint_path(dot, tone_color);
}
}
},
)
.w_full()
.h(px(plot_height));
let mut plot_wrap = div()
.id(SharedString::from(format!(
"arc-sparkline-plot-{:?}",
self.id
)))
.w_full()
.min_w(px(plot_width))
.h(px(plot_height))
.relative()
.child(plot_canvas);
if interactive {
plot_wrap = plot_wrap
.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(sparkline_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 left: f32 = b.origin.x.into();
let w: f32 = b.size.width.into();
let top: f32 = b.origin.y.into();
let h: f32 = b.size.height.into();
let y: f32 = ev.position.y.into();
let inside = x >= left && x <= left + w && y >= top && y <= top + h;
let mut st = st_move.borrow_mut();
let next = if inside {
Some(sparkline_index_at(x, left, w, count))
} else {
None
};
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 page = (count / 6).max(1);
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),
"pageup" => (cur + page).min(last),
"pagedown" => cur.saturating_sub(page),
"home" => 0,
"end" => last,
_ => return,
};
st.active = Some(next);
window.refresh();
});
}
div()
.id(self.id)
.w_full()
.p(Spacing::S4)
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.flex()
.flex_col()
.gap(Spacing::S2)
.child(
div()
.w_full()
.flex()
.items_baseline()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.flex()
.items_baseline()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_secondary)
.child(self.label),
)
.when_some(headline, |this, val| {
this.child(
div()
.text_size(Typography::TEXT_LG)
.font_semibold()
.text_color(colors.foreground)
.child(val),
)
}),
)
.when(!aside.is_empty(), |this| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(if scrubbing {
colors.text_secondary
} else {
tone_color
})
.child(aside),
)
}),
)
.child(plot_wrap)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sparkline_curve_and_pointer_mapping() {
let curve = sparkline_curve(&[12.0, 24.0, 18.0, 36.0]);
assert!(curve.len() >= 4);
assert!(
curve
.iter()
.all(|&(x, y)| (0.0..=1.0).contains(&x) && (0.0..=1.0).contains(&y))
);
assert_eq!(sparkline_index_at(0.0, 0.0, 100.0, 5), 0);
assert_eq!(sparkline_index_at(50.0, 0.0, 100.0, 5), 2);
assert_eq!(sparkline_index_at(120.0, 0.0, 100.0, 5), 4);
}
}