use std::rc::Rc;
use arc_motion::{is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role,
SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};
use super::common::{
ChartSpring, build_circle_fill, build_polyline_stroke, format_grouped,
slice_polyline_by_progress,
};
const LABEL_GAP: f32 = 22.0;
const PLOT_PAD: f32 = 16.0;
const HEAD_H: f32 = 28.0;
#[derive(Clone, Debug)]
pub struct SlopeItem {
pub key: SharedString,
pub label: SharedString,
pub start: f64,
pub end: f64,
}
impl SlopeItem {
pub fn new(
key: impl Into<SharedString>,
label: impl Into<SharedString>,
start: f64,
end: f64,
) -> Self {
Self {
key: key.into(),
label: label.into(),
start,
end,
}
}
}
pub fn slope_spread_labels(wanted: &[f32], gap: f32, low: f32, high: f32) -> Vec<f32> {
if wanted.is_empty() {
return Vec::new();
}
let mut order: Vec<(usize, f32)> = wanted.iter().copied().enumerate().collect();
order.sort_by(|a, b| a.1.total_cmp(&b.1));
struct Group {
members: Vec<(usize, f32)>,
top: f32,
}
let mut groups: Vec<Group> = order
.into_iter()
.map(|entry| Group {
top: entry.1,
members: vec![entry],
})
.collect();
loop {
let mut changed = false;
let mut next: Vec<Group> = Vec::with_capacity(groups.len());
for group in groups {
if let Some(prev) = next.last_mut()
&& prev.top + prev.members.len() as f32 * gap > group.top
{
prev.members.extend(group.members);
let sum: f32 = prev
.members
.iter()
.enumerate()
.map(|(k, &(_, y))| y - k as f32 * gap)
.sum();
prev.top = sum / prev.members.len() as f32;
changed = true;
continue;
}
next.push(group);
}
for g in &mut next {
let max_top = (high - (g.members.len().saturating_sub(1) as f32) * gap).max(low);
g.top = g.top.clamp(low, max_top);
}
groups = next;
if !changed {
break;
}
}
let mut out = vec![0.0f32; wanted.len()];
for g in groups {
for (k, &(idx, _)) in g.members.iter().enumerate() {
out[idx] = g.top + k as f32 * gap;
}
}
out
}
pub fn slope_ranks(values: &[f64]) -> Vec<usize> {
let mut indexed: Vec<(usize, f64)> = values.iter().copied().enumerate().collect();
indexed.sort_by(|a, b| b.1.total_cmp(&a.1));
let mut ranks = vec![1usize; values.len()];
for (pos, (idx, _)) in indexed.into_iter().enumerate() {
ranks[idx] = pos + 1;
}
ranks
}
#[derive(Clone)]
struct SlopeRow {
item: SlopeItem,
y0: f32,
y1: f32,
l0: f32,
l1: f32,
rank0: usize,
rank1: usize,
end_order: usize,
}
#[derive(Clone)]
struct SlopeState {
focus_handle: FocusHandle,
own_active: Option<String>,
stage_bounds: Bounds<Pixels>,
reveal_spring: ChartSpring,
last_tick: f64,
}
type ChangeFormatter = Rc<dyn Fn(f64, &SlopeItem) -> String>;
type ActiveChangeHandler = Rc<dyn Fn(Option<SharedString>, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct SlopeChart {
id: ElementId,
data: Vec<SlopeItem>,
label: SharedString,
start_label: SharedString,
end_label: SharedString,
format_value: Option<Rc<dyn Fn(f64) -> String>>,
format_change: Option<ChangeFormatter>,
height: Option<f32>,
highlight_key: Option<SharedString>,
active_key: Option<Option<SharedString>>,
on_active_change: Option<ActiveChangeHandler>,
ranks: bool,
empty_label: SharedString,
}
impl SlopeChart {
pub fn new(
id: impl Into<ElementId>,
data: Vec<SlopeItem>,
label: impl Into<SharedString>,
start_label: impl Into<SharedString>,
end_label: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
data,
label: label.into(),
start_label: start_label.into(),
end_label: end_label.into(),
format_value: None,
format_change: None,
height: None,
highlight_key: None,
active_key: None,
on_active_change: None,
ranks: true,
empty_label: "No data".into(),
}
}
pub fn format_value(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
self.format_value = Some(Rc::new(f));
self
}
pub fn format_change(mut self, f: impl Fn(f64, &SlopeItem) -> String + 'static) -> Self {
self.format_change = Some(Rc::new(f));
self
}
pub fn height(mut self, height: f32) -> Self {
self.height = Some(height.max(160.0));
self
}
pub fn highlight_key(mut self, key: impl Into<SharedString>) -> Self {
self.highlight_key = Some(key.into());
self
}
pub fn active_key(mut self, key: Option<impl Into<SharedString>>) -> Self {
self.active_key = Some(key.map(Into::into));
self
}
pub fn on_active_change(
mut self,
f: impl Fn(Option<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_active_change = Some(Rc::new(f));
self
}
pub fn ranks(mut self, show: bool) -> Self {
self.ranks = show;
self
}
pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
self.empty_label = label.into();
self
}
fn fmt_val(&self, v: f64) -> String {
if let Some(f) = &self.format_value {
f(v)
} else {
format_grouped(v, 1)
}
}
fn fmt_change(&self, item: &SlopeItem) -> String {
let delta = item.end - item.start;
if let Some(f) = &self.format_change {
f(delta, item)
} else {
let sign = if delta >= 0.0 { "+" } else { "−" };
format!("{sign}{}", self.fmt_val(delta.abs()))
}
}
}
impl RenderOnce for SlopeChart {
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 empty = self.data.is_empty();
let plot_h = self
.height
.unwrap_or_else(|| (self.data.len() as f32 * 44.0).max(200.0));
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "__slope-state".into()),
cx,
|_w, cx| SlopeState {
focus_handle: cx.focus_handle(),
own_active: None,
stage_bounds: Bounds::default(),
reveal_spring: {
let mut sp = ChartSpring::new(if reduced { 1.0 } else { 0.0 });
sp.set_target(1.0);
sp
},
last_tick: now,
},
);
let mut running = false;
state.update(cx, |s, _cx| {
let dt = (now - s.last_tick).clamp(0.0, 0.05);
s.last_tick = now;
if reduced {
s.reveal_spring.snap(1.0);
} else if dt > 0.0 && !s.reveal_spring.is_settled() {
s.reveal_spring.step(0.76, 0.02, dt as f32);
}
running = !s.reveal_spring.is_settled();
});
if running {
window.request_animation_frame();
}
let snap = state.read(cx).clone();
let measured_w: f32 = snap.stage_bounds.size.width.into();
let stage_w = if measured_w > 120.0 {
measured_w
} else {
520.0
};
let narrow = stage_w < 440.0;
let left_room = if narrow { 132.0 } else { 172.0 };
let right_room = if self.ranks {
if narrow { 82.0 } else { 104.0 }
} else if narrow {
56.0
} else {
68.0
};
let x0 = left_room;
let x1 = (stage_w - right_room).max(x0 + 60.0);
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for item in &self.data {
if item.start.is_finite() {
lo = lo.min(item.start);
hi = hi.max(item.start);
}
if item.end.is_finite() {
lo = lo.min(item.end);
hi = hi.max(item.end);
}
}
if !lo.is_finite() || !hi.is_finite() {
lo = 0.0;
hi = 1.0;
}
if (hi - lo).abs() < 1e-9 {
lo -= 1.0;
hi += 1.0;
}
let y_of = |v: f64| -> f32 {
let t = ((v - lo) / (hi - lo)).clamp(0.0, 1.0) as f32;
PLOT_PAD + (1.0 - t) * (plot_h - PLOT_PAD * 2.0)
};
let starts: Vec<f64> = self.data.iter().map(|d| d.start).collect();
let ends: Vec<f64> = self.data.iter().map(|d| d.end).collect();
let ranks0 = slope_ranks(&starts);
let ranks1 = slope_ranks(&ends);
let y0s: Vec<f32> = self.data.iter().map(|d| y_of(d.start)).collect();
let y1s: Vec<f32> = self.data.iter().map(|d| y_of(d.end)).collect();
let l0s = slope_spread_labels(&y0s, LABEL_GAP, 10.0, plot_h - 10.0);
let l1s = slope_spread_labels(&y1s, LABEL_GAP, 10.0, plot_h - 10.0);
let mut rows: Vec<SlopeRow> = self
.data
.iter()
.enumerate()
.map(|(i, item)| SlopeRow {
item: item.clone(),
y0: y0s[i],
y1: y1s[i],
l0: l0s[i],
l1: l1s[i],
rank0: ranks0[i],
rank1: ranks1[i],
end_order: 0,
})
.collect();
let mut by_end_indices: Vec<usize> = (0..rows.len()).collect();
by_end_indices.sort_by_key(|&i| rows[i].rank1);
for (ord, &idx) in by_end_indices.iter().enumerate() {
rows[idx].end_order = ord;
}
let by_end_keys: Vec<String> = by_end_indices
.iter()
.map(|&i| rows[i].item.key.to_string())
.collect();
let is_controlled = self.active_key.is_some();
let wanted_active = match &self.active_key {
Some(opt) => opt.as_ref().map(|s| s.to_string()),
None => snap.own_active.clone(),
};
let active_key = wanted_active.filter(|k| self.data.iter().any(|d| d.key.as_ref() == k));
let active_row = active_key
.as_deref()
.and_then(|k| rows.iter().find(|r| r.item.key.as_ref() == k))
.cloned();
let reveal_p = snap.reveal_spring.position().clamp(0.0, 1.0);
let highlight_key = self.highlight_key.as_ref().map(|s| s.to_string());
let canvas_state = state.clone();
let canvas_rows = rows.clone();
let canvas_active = active_key.clone();
let canvas_highlight = highlight_key.clone();
let axis_color = colors.border;
let muted_line = oklab_mix(colors.foreground, colors.surface, 0.38);
let accent_color = colors.series.series_1;
let fg_color = colors.foreground;
let surface_color = colors.surface;
let plot_canvas = canvas(
move |bounds, _w, cx| {
canvas_state.update(cx, |s, _cx| {
s.stage_bounds = bounds;
});
},
move |bounds, _, window, _cx| {
let ox: f32 = bounds.origin.x.into();
let oy: f32 = bounds.origin.y.into();
for ax in [x0, x1] {
if let Some(p) = build_polyline_stroke(
&[
point(px(ox + ax), px(oy)),
point(px(ox + ax), px(oy + plot_h)),
],
1.0,
) {
window.paint_path(p, axis_color.opacity(0.75));
}
}
let mut draw_indices: Vec<usize> = (0..canvas_rows.len()).collect();
draw_indices.sort_by_key(|&i| {
if canvas_active.as_deref() == Some(canvas_rows[i].item.key.as_ref()) {
2u8
} else if canvas_highlight.as_deref() == Some(canvas_rows[i].item.key.as_ref())
{
1u8
} else {
0u8
}
});
for idx in draw_indices {
let row = &canvas_rows[idx];
let is_on = canvas_active.as_deref() == Some(row.item.key.as_ref());
let is_accent = canvas_highlight.as_deref() == Some(row.item.key.as_ref());
let is_dim = canvas_active.is_some() && !is_on;
let delay = (idx as f32 * 0.04).min(0.24);
let line_p = ((reveal_p - delay) / (1.0 - delay).max(0.01)).clamp(0.0, 1.0);
let stroke_col = if is_accent {
accent_color
} else if is_on {
fg_color
} else {
muted_line
};
let alpha = if is_dim { 0.22 } else { 1.0 };
let stroke_w = if is_on || is_accent { 2.4 } else { 1.5 };
if (row.l0 - row.y0).abs() > 1.5
&& let Some(p) = build_polyline_stroke(
&[
point(px(ox + x0 - 7.0), px(oy + row.l0)),
point(px(ox + x0 - 2.0), px(oy + row.y0)),
],
1.0,
)
{
window.paint_path(p, stroke_col.opacity(alpha * 0.45));
}
if (row.l1 - row.y1).abs() > 1.5
&& let Some(p) = build_polyline_stroke(
&[
point(px(ox + x1 + 7.0), px(oy + row.l1)),
point(px(ox + x1 + 2.0), px(oy + row.y1)),
],
1.0,
)
{
window.paint_path(p, stroke_col.opacity(alpha * 0.45));
}
let full_seg = [
point(px(ox + x0), px(oy + row.y0)),
point(px(ox + x1), px(oy + row.y1)),
];
let drawn_seg = slice_polyline_by_progress(&full_seg, line_p);
if let Some(p) = build_polyline_stroke(&drawn_seg, stroke_w) {
window.paint_path(p, stroke_col.opacity(alpha));
}
let dot_r = if is_on {
4.8
} else if is_accent {
4.2
} else {
3.6
};
if line_p > 0.02 {
if let Some(c) = build_circle_fill(ox + x0, oy + row.y0, dot_r + 1.2, 16) {
window.paint_path(c, surface_color);
}
if let Some(c) = build_circle_fill(ox + x0, oy + row.y0, dot_r, 16) {
window.paint_path(c, stroke_col.opacity(alpha));
}
}
if line_p > 0.85 {
let end_scale = ((line_p - 0.85) / 0.15).clamp(0.0, 1.0);
if let Some(c) =
build_circle_fill(ox + x1, oy + row.y1, (dot_r + 1.2) * end_scale, 16)
{
window.paint_path(c, surface_color);
}
if let Some(c) =
build_circle_fill(ox + x1, oy + row.y1, dot_r * end_scale, 16)
{
window.paint_path(c, stroke_col.opacity(alpha));
}
}
}
},
)
.w_full()
.h(px(plot_h));
let hit_rows = rows.clone();
let on_active = self.on_active_change.clone();
let move_state = state.clone();
let move_cb = on_active.clone();
let click_state = state.clone();
let key_state = state.clone();
let key_cb = on_active.clone();
let nearest_key = move |lx: f32, ly: f32| -> Option<String> {
let clamped_x = lx.clamp(x0, x1);
let t = (clamped_x - x0) / (x1 - x0).max(1.0);
let mut best: Option<&SlopeRow> = None;
let mut best_dist = f32::INFINITY;
for row in &hit_rows {
let y_line = row.y0 + (row.y1 - row.y0) * t;
let d_line = (y_line - ly).abs();
let d_label = if lx < x0 {
(row.l0 - ly).abs()
} else if lx > x1 {
(row.l1 - ly).abs()
} else {
f32::INFINITY
};
let d = d_line.min(d_label);
if d < best_dist {
best_dist = d;
best = Some(row);
}
}
if best_dist <= 22.0 {
best.map(|r| r.item.key.to_string())
} else {
None
}
};
let nearest_for_down = nearest_key.clone();
let header = div()
.relative()
.w_full()
.h(px(HEAD_H))
.child(
div()
.absolute()
.left(px((x0 - 44.0).max(0.0)))
.top(px(4.0))
.w(px(88.0))
.flex()
.justify_center()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.text_muted)
.child(self.start_label.clone()),
)
.child(
div()
.absolute()
.left(px((x1 - 44.0).max(0.0)))
.top(px(4.0))
.w(px(88.0))
.flex()
.justify_center()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.text_muted)
.child(self.end_label.clone()),
);
let mut plot = div().relative().w_full().h(px(plot_h)).child(plot_canvas);
for row in &rows {
let is_on = active_key.as_deref() == Some(row.item.key.as_ref());
let is_accent = highlight_key.as_deref() == Some(row.item.key.as_ref());
let is_dim = active_key.is_some() && !is_on;
let opacity = reveal_p * if is_dim { 0.30 } else { 1.0 };
let text_col = if is_accent {
accent_color
} else {
colors.foreground
};
plot = plot.child(
div()
.absolute()
.left(px(0.0))
.top(px(row.l0 - 9.0))
.w(px((x0 - 12.0).max(40.0)))
.h(px(18.0))
.flex()
.items_center()
.justify_end()
.gap(px(6.0))
.opacity(opacity)
.child(
div()
.text_size(Typography::TEXT_XS)
.when(is_on || is_accent, |this| this.font_semibold())
.text_color(text_col)
.truncate()
.child(row.item.label.clone()),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_muted)
.flex_shrink_0()
.child(self.fmt_val(row.item.start)),
),
);
let move_delta = row.rank0 as isize - row.rank1 as isize;
let mut end_row = div()
.absolute()
.left(px(x1 + 12.0))
.top(px(row.l1 - 9.0))
.h(px(18.0))
.flex()
.items_center()
.gap(px(6.0))
.opacity(opacity)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.when(is_on || is_accent, |this| this.font_semibold())
.text_color(text_col)
.child(self.fmt_val(row.item.end)),
);
if self.ranks {
let (badge_text, badge_color) = if move_delta > 0 {
(format!("↑{move_delta}"), colors.success)
} else if move_delta < 0 {
(format!("↓{}", move_delta.abs()), colors.danger)
} else {
("=".to_string(), colors.text_muted)
};
end_row = end_row.child(
div()
.text_size(px(11.0))
.font_medium()
.text_color(badge_color)
.child(badge_text),
);
}
plot = plot.child(end_row);
}
if let Some(row) = &active_row {
let mid_y = (row.y0 + row.y1) * 0.5;
let mid_x = (x0 + x1) * 0.5;
let tip_w = 188.0f32;
let tip_h = 84.0f32;
let left = (mid_x - tip_w * 0.5).clamp(4.0, (stage_w - tip_w - 4.0).max(4.0));
let top = if mid_y - tip_h - 14.0 >= 0.0 {
mid_y - tip_h - 14.0
} else {
(mid_y + 14.0).min((plot_h - tip_h).max(0.0))
};
let rank_note = if row.rank0 == row.rank1 {
format!("Rank #{} (unchanged)", row.rank1)
} else if row.rank1 < row.rank0 {
format!("↑{} to rank #{}", row.rank0 - row.rank1, row.rank1)
} else {
format!("↓{} to rank #{}", row.rank1 - row.rank0, row.rank1)
};
plot = plot.child(
div()
.absolute()
.left(px(left))
.top(px(top))
.w(px(tip_w))
.px(Spacing::S3)
.py(Spacing::S2)
.rounded(Radii::CONTROL)
.bg(colors.surface_raised)
.border_1()
.border_color(colors.border)
.shadow_md()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.child(row.item.label.clone()),
)
.child(
div()
.flex()
.items_center()
.justify_between()
.text_size(px(11.0))
.child(
div()
.text_color(colors.text_muted)
.child(self.start_label.clone()),
)
.child(
div()
.font_medium()
.text_color(colors.foreground)
.child(self.fmt_val(row.item.start)),
),
)
.child(
div()
.flex()
.items_center()
.justify_between()
.text_size(px(11.0))
.child(
div()
.text_color(colors.text_muted)
.child(self.end_label.clone()),
)
.child(
div()
.font_medium()
.text_color(colors.foreground)
.child(self.fmt_val(row.item.end)),
),
)
.child(
div()
.pt(px(2.0))
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(format!("{}, {}", self.fmt_change(&row.item), rank_note)),
),
);
}
if empty {
plot = plot.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.text_size(px(13.0))
.text_color(colors.text_muted)
.child(self.empty_label.clone()),
);
}
let active_order = active_row.as_ref().map(|r| r.end_order);
div()
.id(self.id)
.role(Role::Group)
.aria_label(self.label)
.track_focus(&snap.focus_handle)
.w_full()
.flex()
.flex_col()
.on_mouse_move(move |ev: &MouseMoveEvent, window, cx| {
let (in_bounds, next) = {
let s = move_state.read(cx);
let b = s.stage_bounds;
let lx: f32 = (ev.position.x - b.origin.x).into();
let ly: f32 = (ev.position.y - b.origin.y).into();
let bw: f32 = b.size.width.into();
let bh: f32 = b.size.height.into();
if lx < 0.0 || ly < 0.0 || lx > bw || ly > bh {
(false, None)
} else {
(true, nearest_key(lx, ly))
}
};
let prev = move_state.read(cx).own_active.clone();
if (!in_bounds && prev.is_some()) || (in_bounds && prev != next) {
if !is_controlled {
move_state.update(cx, |s, cx| {
s.own_active = next.clone();
cx.notify();
});
}
if let Some(cb) = &move_cb {
cb(next.map(SharedString::from), window, cx);
}
}
})
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
let fh = click_state.read(cx).focus_handle.clone();
window.focus(&fh, cx);
let next = {
let s = click_state.read(cx);
let b = s.stage_bounds;
let lx: f32 = (ev.position.x - b.origin.x).into();
let ly: f32 = (ev.position.y - b.origin.y).into();
nearest_for_down(lx, ly)
};
if !is_controlled {
click_state.update(cx, |s, cx| {
s.own_active = next;
cx.notify();
});
}
})
.on_key_down(move |ev: &KeyDownEvent, window, cx| {
if by_end_keys.is_empty() {
return;
}
let key = ev.keystroke.key.as_str();
if key == "escape" {
if !is_controlled {
key_state.update(cx, |s, cx| {
s.own_active = None;
cx.notify();
});
}
if let Some(cb) = &key_cb {
cb(None, window, cx);
}
return;
}
let last = by_end_keys.len() - 1;
let next_idx = match key {
"down" | "right" => Some(match active_order {
Some(o) => (o + 1).min(last),
None => 0,
}),
"up" | "left" => Some(match active_order {
Some(o) => o.saturating_sub(1),
None => 0,
}),
"home" => Some(0),
"end" => Some(last),
_ => None,
};
if let Some(i) = next_idx {
cx.stop_propagation();
let k = by_end_keys[i].clone();
if !is_controlled {
key_state.update(cx, |s, cx| {
s.own_active = Some(k.clone());
cx.notify();
});
}
if let Some(cb) = &key_cb {
cb(Some(SharedString::from(k)), window, cx);
}
}
})
.child(header)
.child(plot)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slope_label_spreading_and_rank_deltas() {
let spread = slope_spread_labels(&[50.0, 52.0, 150.0], 20.0, 8.0, 200.0);
assert!((spread[1] - spread[0]) >= 19.9);
assert!((spread[2] - 150.0).abs() < 1e-4);
let r0 = slope_ranks(&[10.0, 40.0, 25.0]);
assert_eq!(r0, vec![3, 1, 2]);
let r1 = slope_ranks(&[50.0, 30.0, 25.0]);
assert_eq!(r1, vec![1, 2, 3]);
}
}