use std::f64::consts::TAU;
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, Context, ElementId, FocusHandle, Hsla, 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_area_fill, build_polyline_stroke, format_grouped};
const SAMPLES: usize = 80;
const AXIS_H: f32 = 26.0;
const LIFT_PX: f32 = 6.0;
const TIP_GAP: f32 = 12.0;
#[derive(Clone, Debug)]
pub struct RidgelineSeries {
pub id: SharedString,
pub label: SharedString,
pub values: Vec<f64>,
}
impl RidgelineSeries {
pub fn new(
id: impl Into<SharedString>,
label: impl Into<SharedString>,
values: Vec<f64>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
values,
}
}
}
#[derive(Clone, Debug)]
pub struct RidgelineStats {
pub sorted: Vec<f64>,
pub n: usize,
pub min: f64,
pub max: f64,
pub q1: f64,
pub median: f64,
pub q3: f64,
}
pub fn ridgeline_quantile(sorted: &[f64], q: f64) -> f64 {
if sorted.is_empty() {
return 0.0;
}
let at = (sorted.len() - 1) as f64 * q.clamp(0.0, 1.0);
let lo = at.floor() as usize;
let hi = at.ceil() as usize;
sorted[lo] + (sorted[hi] - sorted[lo]) * (at - lo as f64)
}
pub fn ridgeline_stats(values: &[f64]) -> RidgelineStats {
let mut sorted: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
sorted.sort_by(|a, b| a.total_cmp(b));
let n = sorted.len();
RidgelineStats {
min: sorted.first().copied().unwrap_or(0.0),
max: sorted.last().copied().unwrap_or(0.0),
q1: ridgeline_quantile(&sorted, 0.25),
median: ridgeline_quantile(&sorted, 0.5),
q3: ridgeline_quantile(&sorted, 0.75),
sorted,
n,
}
}
pub fn ridgeline_silverman_bandwidth(stats: &RidgelineStats) -> f64 {
if stats.n < 2 {
return 1.0;
}
let mean = stats.sorted.iter().sum::<f64>() / stats.n as f64;
let var = stats
.sorted
.iter()
.map(|&v| (v - mean).powi(2))
.sum::<f64>()
/ (stats.n - 1) as f64;
let sd = var.sqrt();
let iqr_sd = (stats.q3 - stats.q1) / 1.34;
let spread = if iqr_sd > 1e-9 { sd.min(iqr_sd) } else { sd };
let base = if spread > 1e-9 { spread } else { 1.0 };
(0.9 * base * (stats.n as f64).powf(-0.2)).max(1e-6)
}
pub fn ridgeline_kde(
stats: &RidgelineStats,
lo: f64,
hi: f64,
bandwidth: f64,
) -> (Vec<f64>, Vec<f64>) {
let mut xs = Vec::with_capacity(SAMPLES);
let mut ys = Vec::with_capacity(SAMPLES);
let norm = 1.0 / ((stats.n.max(1) as f64) * bandwidth * TAU.sqrt());
for i in 0..SAMPLES {
let x = lo + ((hi - lo) * i as f64) / (SAMPLES - 1) as f64;
let mut sum = 0.0;
for &v in &stats.sorted {
let u = (x - v) / bandwidth;
if u > -5.0 && u < 5.0 {
sum += (-0.5 * u * u).exp();
}
}
xs.push(x);
ys.push(sum * norm);
}
(xs, ys)
}
fn nice_step(span: f64, count: usize) -> f64 {
let raw = (span / count.max(1) as f64).max(1e-9);
let power = 10f64.powf(raw.log10().floor());
let unit = raw / power;
let factor = if unit >= 5.0 {
5.0
} else if unit >= 2.0 {
2.0
} else {
1.0
};
factor * power
}
#[derive(Clone, Debug)]
struct RidgeShape {
id: SharedString,
xs: Vec<f64>,
ys: Vec<f64>,
row: usize,
stats: RidgelineStats,
}
impl RidgeShape {
fn height_at(&self, x: f64) -> f64 {
if self.xs.is_empty() || x <= self.xs[0] || x >= *self.xs.last().unwrap() {
return 0.0;
}
let mut i = 1usize;
while i < self.xs.len() - 1 && self.xs[i] < x {
i += 1;
}
let denom = (self.xs[i] - self.xs[i - 1]).max(1e-9);
let t = ((x - self.xs[i - 1]) / denom).clamp(0.0, 1.0);
self.ys[i - 1] + (self.ys[i] - self.ys[i - 1]) * t
}
}
type OnActiveFn = Rc<dyn Fn(Option<SharedString>, &mut Window, &mut App)>;
struct RidgelineState {
focus_handle: FocusHandle,
active_id: Option<SharedString>,
cursor_value: Option<f64>,
pointer_y: Option<f32>,
plot_bounds: Option<Bounds<Pixels>>,
reveal: ChartSpring,
last_frame_secs: Option<f64>,
}
impl RidgelineState {
fn new(cx: &mut Context<Self>) -> Self {
Self {
focus_handle: cx.focus_handle(),
active_id: None,
cursor_value: None,
pointer_y: None,
plot_bounds: None,
reveal: ChartSpring::new(0.0),
last_frame_secs: None,
}
}
}
#[derive(IntoElement)]
pub struct Ridgeline {
id: ElementId,
label: SharedString,
series: Vec<RidgelineSeries>,
unit: SharedString,
domain: Option<(f64, f64)>,
overlap: f32,
row_height: f32,
bandwidth: Option<f64>,
tint: bool,
empty_label: SharedString,
on_active_change: Option<OnActiveFn>,
}
impl Ridgeline {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
series: Vec<RidgelineSeries>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
series,
unit: SharedString::from(""),
domain: None,
overlap: 2.3,
row_height: 30.0,
bandwidth: None,
tint: true,
empty_label: SharedString::from("No data yet"),
on_active_change: None,
}
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = unit.into();
self
}
pub fn domain(mut self, lo: f64, hi: f64) -> Self {
self.domain = Some((lo, hi));
self
}
pub fn overlap(mut self, overlap: f32) -> Self {
self.overlap = overlap.clamp(1.1, 4.0);
self
}
pub fn row_height(mut self, row_height: f32) -> Self {
self.row_height = row_height.clamp(20.0, 56.0);
self
}
pub fn bandwidth(mut self, bw: f64) -> Self {
self.bandwidth = Some(bw.max(1e-6));
self
}
pub fn tint(mut self, tint: bool) -> Self {
self.tint = tint;
self
}
pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
self.empty_label = label.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
}
fn format_val(&self, v: f64) -> String {
let base = format_grouped(v, 1).replace('-', "\u{2212}");
if self.unit.is_empty() {
base
} else {
format!("{base}{}", self.unit)
}
}
}
impl RenderOnce for Ridgeline {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = cx.arc_theme().colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "state".into()),
cx,
|_, cx| RidgelineState::new(cx),
);
let empty = self.series.is_empty() || self.series.iter().all(|s| s.values.is_empty());
let stats_vec: Vec<RidgelineStats> = self
.series
.iter()
.map(|s| ridgeline_stats(&s.values))
.collect();
let bws: Vec<f64> = stats_vec
.iter()
.map(|st| {
self.bandwidth
.unwrap_or_else(|| ridgeline_silverman_bandwidth(st))
})
.collect();
let (mut lo, mut hi) = if let Some((d_lo, d_hi)) = self.domain {
(d_lo, d_hi)
} else {
let mut min_v = f64::INFINITY;
let mut max_v = f64::NEG_INFINITY;
for (st, &bw) in stats_vec.iter().zip(bws.iter()) {
if st.n > 0 {
min_v = min_v.min(st.min - 2.5 * bw);
max_v = max_v.max(st.max + 2.5 * bw);
}
}
if !min_v.is_finite() || !max_v.is_finite() || (max_v - min_v).abs() < 1e-9 {
(0.0, 1.0)
} else {
let step = nice_step(max_v - min_v, 5);
((min_v / step).floor() * step, (max_v / step).ceil() * step)
}
};
if (hi - lo).abs() < 1e-9 {
lo = 0.0;
hi = 1.0;
}
let raw_curves: Vec<(Vec<f64>, Vec<f64>)> = stats_vec
.iter()
.zip(bws.iter())
.map(|(st, &bw)| {
if st.n > 0 {
ridgeline_kde(st, lo, hi, bw)
} else {
let xs = (0..SAMPLES)
.map(|i| lo + ((hi - lo) * i as f64) / (SAMPLES - 1) as f64)
.collect();
(xs, vec![0.0; SAMPLES])
}
})
.collect();
let peak = raw_curves
.iter()
.flat_map(|(_, ys)| ys.iter().copied())
.fold(1e-9f64, f64::max);
let shapes: Vec<RidgeShape> = self
.series
.iter()
.enumerate()
.map(|(row, s)| {
let (xs, ys) = &raw_curves[row];
RidgeShape {
id: s.id.clone(),
xs: xs.clone(),
ys: ys.iter().map(|&y| y / peak).collect(),
row,
stats: stats_vec[row].clone(),
}
})
.collect();
let top_pad = ((self.overlap - 1.0) * self.row_height).ceil() + LIFT_PX + 8.0;
let total_height = top_pad + self.series.len().max(1) as f32 * self.row_height + AXIS_H;
let mut animating = false;
let (active_id, cursor_value, pointer_y, total_w, reveal_val) =
state.update(cx, |st, _| {
let dt = st
.last_frame_secs
.map(|prev| (now - prev).clamp(0.0, 0.05) as f32)
.unwrap_or(0.016);
st.last_frame_secs = Some(now);
if empty || reduced {
st.reveal.snap(1.0);
} else if !st.reveal.is_settled_at(1.0, 0.002) {
st.reveal.step_to(1.0, 0.95, 0.0, dt);
animating = true;
}
let w = st
.plot_bounds
.map(|b| f32::from(b.size.width))
.unwrap_or(520.0)
.max(160.0);
(
st.active_id.clone(),
st.cursor_value,
st.pointer_y,
w,
st.reveal.value.clamp(0.0, 1.0),
)
});
if animating {
window.request_animation_frame();
}
let gutter = if total_w < 420.0 { 44.0 } else { 58.0 };
let plot_w = (total_w - gutter - 8.0).max(60.0);
let lift_h = self.row_height * self.overlap;
let tick_count = ((plot_w / 78.0).floor() as usize).max(2);
let tick_step = nice_step(hi - lo, tick_count);
let mut ticks = Vec::new();
let mut tv = (lo / tick_step).ceil() * tick_step;
while tv <= hi + 1e-9 {
ticks.push((tv * 1e6).round() / 1e6);
tv += tick_step;
}
let series_1 = colors.series.series_1;
let ridge_color = |median: f64| -> Hsla {
if !self.tint {
series_1
} else {
let t = (((median - lo) / (hi - lo).max(1e-9)) as f32).clamp(0.0, 1.0);
oklab_mix(series_1, colors.surface, 0.38 + t * 0.62)
}
};
let paint_shapes = shapes.clone();
let paint_ticks = ticks.clone();
let paint_active = active_id.clone();
let paint_cursor = cursor_value;
let paint_row_h = self.row_height;
let paint_tint = self.tint;
let state_bounds = state.clone();
let grid_col = colors.border_subtle;
let crosshair_col = oklab_mix(colors.foreground, colors.surface, 0.40);
let ridge_canvas = canvas(
move |bounds, _, cx| {
state_bounds.update(cx, |st, _| st.plot_bounds = Some(bounds));
bounds
},
move |bounds, _, window, _cx| {
let w = f32::from(bounds.size.width).max(1.0);
let h = f32::from(bounds.size.height).max(1.0);
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let g = if w < 420.0 { 44.0 } else { 58.0 };
let pw = (w - g - 8.0).max(40.0);
let sx = |v: f64| ox + g + (((v - lo) / (hi - lo).max(1e-9)) as f32) * pw;
let base_y = |row: usize| oy + top_pad + (row as f32 + 1.0) * paint_row_h;
for &tk in &paint_ticks {
let tx = sx(tk);
if let Some(p) = build_polyline_stroke(
&[
point(px(tx), px(oy + top_pad - paint_row_h * 0.5)),
point(px(tx), px(oy + h - AXIS_H)),
],
1.0,
) {
window.paint_path(p, grid_col);
}
}
let n_rows = paint_shapes.len().max(1);
let color_for = |med: f64| -> Hsla {
if !paint_tint {
series_1
} else {
let t = (((med - lo) / (hi - lo).max(1e-9)) as f32).clamp(0.0, 1.0);
oklab_mix(series_1, colors.surface, 0.38 + t * 0.62)
}
};
for shape in &paint_shapes {
let stagger = (shape.row as f32 * 0.03).min(0.45);
let denom = (1.0 - (n_rows as f32 * 0.03).min(0.45)).max(0.2);
let local = ((reveal_val - stagger) / denom).clamp(0.0, 1.0);
let by = base_y(shape.row);
let is_active = paint_active.as_ref() == Some(&shape.id);
let is_dim = paint_active.is_some() && !is_active;
let col = color_for(shape.stats.median);
let pts: Vec<_> = shape
.xs
.iter()
.zip(shape.ys.iter())
.map(|(&xv, &yv)| point(px(sx(xv)), px(by - (yv as f32 * lift_h * local))))
.collect();
if let Some(fill) = build_area_fill(&pts, px(by)) {
let mask_col =
oklab_mix(col, colors.surface, if is_dim { 0.16 } else { 0.55 });
window.paint_path(fill, mask_col);
}
let mx = sx(shape.stats.median);
let mh = shape.height_at(shape.stats.median) as f32 * lift_h * local;
if mh > 1.0
&& let Some(mp) = build_polyline_stroke(
&[point(px(mx), px(by)), point(px(mx), px(by - mh))],
1.0,
)
{
window.paint_path(
mp,
Hsla {
a: if is_dim { 0.18 } else { 0.55 },
..colors.foreground
},
);
}
if let Some(stroke) =
build_polyline_stroke(&pts, if is_active { 1.8 } else { 1.25 })
{
window.paint_path(
stroke,
Hsla {
a: if is_dim { 0.30 } else { 0.92 },
..col
},
);
}
}
if let Some(ref aid) = paint_active
&& let Some(shape) = paint_shapes.iter().find(|s| &s.id == aid)
{
let by = base_y(shape.row) - LIFT_PX * 0.5;
let col = color_for(shape.stats.median);
let full_pts: Vec<_> = shape
.xs
.iter()
.zip(shape.ys.iter())
.map(|(&xv, &yv)| point(px(sx(xv)), px(by - yv as f32 * lift_h)))
.collect();
if let Some(fill) = build_area_fill(&full_pts, px(by)) {
window.paint_path(fill, oklab_mix(col, colors.surface, 0.72));
}
let mut iqr_pts = Vec::new();
iqr_pts.push(point(
px(sx(shape.stats.q1)),
px(by - shape.height_at(shape.stats.q1) as f32 * lift_h),
));
for (&xv, &yv) in shape.xs.iter().zip(shape.ys.iter()) {
if xv > shape.stats.q1 && xv < shape.stats.q3 {
iqr_pts.push(point(px(sx(xv)), px(by - yv as f32 * lift_h)));
}
}
iqr_pts.push(point(
px(sx(shape.stats.q3)),
px(by - shape.height_at(shape.stats.q3) as f32 * lift_h),
));
if let Some(iqr_fill) = build_area_fill(&iqr_pts, px(by)) {
window.paint_path(iqr_fill, oklab_mix(col, colors.surface, 0.92));
}
let mx = sx(shape.stats.median);
let mh = shape.height_at(shape.stats.median) as f32 * lift_h;
if let Some(mp) = build_polyline_stroke(
&[point(px(mx), px(by)), point(px(mx), px(by - mh))],
1.5,
) {
window.paint_path(mp, colors.background);
}
if let Some(stroke) = build_polyline_stroke(&full_pts, 2.0) {
window.paint_path(stroke, col);
}
}
if let Some(cv) = paint_cursor {
let cx_px = sx(cv);
if let Some(cp) = build_polyline_stroke(
&[
point(px(cx_px), px(oy + top_pad - paint_row_h * 0.5)),
point(px(cx_px), px(oy + h - AXIS_H)),
],
1.0,
) {
window.paint_path(cp, crosshair_col);
}
}
},
)
.size_full();
let state_move = state.clone();
let state_down = state.clone();
let state_hover = state.clone();
let state_key = state.clone();
let hit_shapes = shapes.clone();
let down_shapes = shapes.clone();
let key_ids: Vec<(SharedString, f64)> = shapes
.iter()
.map(|s| (s.id.clone(), s.stats.median))
.collect();
let move_on_active = self.on_active_change.clone();
let down_on_active = self.on_active_change.clone();
let key_on_active = self.on_active_change.clone();
let row_h = self.row_height;
let pick_at = move |x_local: f32,
y_local: f32,
bounds: Bounds<Pixels>,
all: &[RidgeShape]|
-> Option<(SharedString, f64)> {
let w = f32::from(bounds.size.width).max(1.0);
let h = f32::from(bounds.size.height).max(1.0);
let g = if w < 420.0 { 44.0 } else { 58.0 };
let pw = (w - g - 8.0).max(40.0);
if x_local < g - 8.0 || y_local > h - AXIS_H + 4.0 {
return None;
}
let val = lo + ((x_local - g) / pw).clamp(0.0, 1.0) as f64 * (hi - lo);
let mut best: Option<&RidgeShape> = None;
for sh in all {
let base = top_pad + (sh.row as f32 + 1.0) * row_h;
let rh = sh.height_at(val) as f32 * lift_h;
if y_local <= base + 2.0
&& y_local >= base - rh - 4.0
&& best.map(|b| sh.row > b.row).unwrap_or(true)
{
best = Some(sh);
}
}
let chosen = best.or_else(|| {
let r = (((y_local - top_pad) / row_h).floor() as isize)
.clamp(0, all.len().saturating_sub(1) as isize)
as usize;
all.get(r)
})?;
Some((chosen.id.clone(), val))
};
let focus_handle = state.read(cx).focus_handle.clone();
let tooltip_el = active_id
.as_ref()
.and_then(|aid| {
let shape = shapes.iter().find(|s| &s.id == aid)?;
let ser = self.series.iter().find(|s| &s.id == aid)?;
Some((shape, ser))
})
.map(|(shape, ser)| {
let tip_w = 192.0f32;
let tip_h = 98.0f32;
let anchor_val = cursor_value.unwrap_or(shape.stats.median);
let ax = gutter + (((anchor_val - lo) / (hi - lo).max(1e-9)) as f32) * plot_w;
let ay = pointer_y
.unwrap_or(top_pad + (shape.row as f32 + 1.0) * self.row_height - 24.0);
let left = if ax + TIP_GAP + tip_w <= total_w {
ax + TIP_GAP
} else {
(ax - TIP_GAP - tip_w).max(gutter)
};
let top = if ay - tip_h - TIP_GAP >= 4.0 {
ay - tip_h - TIP_GAP
} else {
(ay + TIP_GAP).min((total_height - tip_h - 4.0).max(4.0))
};
let below_pct = cursor_value.and_then(|cv| {
if shape.stats.n > 0 {
let cnt = shape.stats.sorted.iter().filter(|&&v| v <= cv).count();
Some((cnt as f64 / shape.stats.n as f64 * 100.0).round() as usize)
} else {
None
}
});
div()
.absolute()
.left(px(left))
.top(px(top))
.w(px(tip_w))
.p(Spacing::S2)
.rounded(Radii::CONTROL)
.bg(colors.surface_raised)
.border_1()
.border_color(colors.border)
.flex()
.flex_col()
.gap(px(3.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.child(ser.label.clone()),
)
.child(
div()
.flex()
.justify_between()
.text_size(Typography::TEXT_XS)
.child(div().text_color(colors.text_muted).child("Median"))
.child(
div()
.font_medium()
.text_color(colors.foreground)
.child(self.format_val(shape.stats.median)),
),
)
.child(
div()
.flex()
.justify_between()
.text_size(Typography::TEXT_XS)
.child(div().text_color(colors.text_muted).child("IQR"))
.child(div().text_color(colors.text_secondary).child(format!(
"{} – {}",
self.format_val(shape.stats.q1),
self.format_val(shape.stats.q3)
))),
)
.child(
div()
.flex()
.justify_between()
.text_size(Typography::TEXT_XS)
.child(div().text_color(colors.text_muted).child("Range"))
.child(div().text_color(colors.text_secondary).child(format!(
"{} – {}",
self.format_val(shape.stats.min),
self.format_val(shape.stats.max)
))),
)
.when_some(below_pct.zip(cursor_value), |this, (pct, cv)| {
this.child(
div()
.pt(px(2.0))
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(format!("{pct}% at or below {}", self.format_val(cv))),
)
})
});
let mut plot_box = div()
.id(ElementId::NamedChild(self.id.clone().into(), "plot".into()))
.role(Role::Group)
.track_focus(&focus_handle)
.relative()
.w_full()
.h(px(total_height))
.overflow_hidden()
.cursor_crosshair()
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
if empty {
return;
}
let mut emitted = None;
state_move.update(cx, |st, _| {
if let Some(bounds) = st.plot_bounds {
let lx = f32::from(event.position.x) - f32::from(bounds.origin.x);
let ly = f32::from(event.position.y) - f32::from(bounds.origin.y);
match pick_at(lx, ly, bounds, &hit_shapes) {
Some((id, val)) => {
if st.active_id.as_ref() != Some(&id) {
emitted = Some(Some(id.clone()));
}
st.active_id = Some(id);
st.cursor_value = Some(val);
st.pointer_y = Some(ly);
}
None => {
if st.active_id.is_some() {
emitted = Some(None);
}
st.active_id = None;
st.cursor_value = None;
st.pointer_y = None;
}
}
}
});
if let (Some(cb), Some(next_id)) = (&move_on_active, emitted) {
cb(next_id, window, cx);
}
window.refresh();
})
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
if empty {
return;
}
let mut emitted = None;
let fh = state_down.read(cx).focus_handle.clone();
window.focus(&fh, cx);
state_down.update(cx, |st, _| {
if let Some(bounds) = st.plot_bounds {
let lx = f32::from(event.position.x) - f32::from(bounds.origin.x);
let ly = f32::from(event.position.y) - f32::from(bounds.origin.y);
if let Some((id, val)) = pick_at(lx, ly, bounds, &down_shapes) {
st.active_id = Some(id.clone());
st.cursor_value = Some(val);
st.pointer_y = Some(ly);
emitted = Some(Some(id));
}
}
});
if let (Some(cb), Some(next_id)) = (&down_on_active, emitted) {
cb(next_id, window, cx);
}
window.refresh();
},
)
.on_hover(move |hovered, window, cx| {
if !*hovered {
state_hover.update(cx, |st, _| {
st.active_id = None;
st.cursor_value = None;
st.pointer_y = None;
});
window.refresh();
}
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if empty || key_ids.is_empty() {
return;
}
let key = event.keystroke.key.as_str();
let mut emitted = None;
let mut handled = true;
state_key.update(cx, |st, _| {
let cur_idx = st
.active_id
.as_ref()
.and_then(|aid| key_ids.iter().position(|(id, _)| id == aid));
match key {
"down" => {
let next = cur_idx.map(|i| (i + 1).min(key_ids.len() - 1)).unwrap_or(0);
st.active_id = Some(key_ids[next].0.clone());
st.cursor_value.get_or_insert(key_ids[next].1);
st.pointer_y = None;
emitted = Some(st.active_id.clone());
}
"up" => {
let next = cur_idx.map(|i| i.saturating_sub(1)).unwrap_or(0);
st.active_id = Some(key_ids[next].0.clone());
st.cursor_value.get_or_insert(key_ids[next].1);
st.pointer_y = None;
emitted = Some(st.active_id.clone());
}
"home" => {
st.active_id = Some(key_ids[0].0.clone());
st.cursor_value = Some(key_ids[0].1);
emitted = Some(st.active_id.clone());
}
"end" => {
let last_i = key_ids.len() - 1;
st.active_id = Some(key_ids[last_i].0.clone());
st.cursor_value = Some(key_ids[last_i].1);
emitted = Some(st.active_id.clone());
}
"left" | "right" => {
let dir = if key == "right" { 1.0 } else { -1.0 };
if st.active_id.is_none() {
st.active_id = Some(key_ids[0].0.clone());
st.cursor_value = Some(key_ids[0].1);
} else {
let base = st.cursor_value.unwrap_or(lo);
let next_v =
(((base / tick_step).round() + dir) * tick_step).clamp(lo, hi);
st.cursor_value = Some(next_v);
}
st.pointer_y = None;
}
"escape" => {
st.active_id = None;
st.cursor_value = None;
emitted = Some(None);
}
_ => handled = false,
}
});
if handled {
if let (Some(cb), Some(next_id)) = (&key_on_active, emitted) {
cb(next_id, window, cx);
}
cx.stop_propagation();
window.refresh();
}
})
.child(ridge_canvas);
for (row, s) in self.series.iter().enumerate() {
let is_active = active_id.as_ref() == Some(&s.id);
let y = top_pad + (row as f32 + 1.0) * self.row_height - 16.0;
plot_box = plot_box.child(
div()
.absolute()
.left(px(0.0))
.top(px(y))
.w(px(gutter - 8.0))
.flex()
.justify_end()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(if is_active {
colors.foreground
} else {
colors.text_secondary
})
.child(s.label.clone()),
);
}
for &tk in &ticks {
let x = gutter + (((tk - lo) / (hi - lo).max(1e-9)) as f32) * plot_w;
let left = (x - 24.0).clamp(gutter - 8.0, (total_w - 48.0).max(gutter));
plot_box = plot_box.child(
div()
.absolute()
.left(px(left))
.top(px(total_height - AXIS_H + 5.0))
.w(px(48.0))
.flex()
.justify_center()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(self.format_val(tk)),
);
}
if let Some(tip) = tooltip_el {
plot_box = plot_box.child(tip);
}
if empty {
plot_box = plot_box.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(self.empty_label.clone()),
);
}
let scale_row = (self.tint && !empty).then(|| {
let mut swatches = div().flex().items_center().gap(px(2.0));
for step_t in [0.0f32, 0.25, 0.5, 0.75, 1.0] {
let col = ridge_color(lo + (hi - lo) * step_t as f64);
swatches = swatches.child(div().w(px(16.0)).h(px(8.0)).rounded(px(2.0)).bg(col));
}
div()
.flex()
.items_center()
.justify_end()
.gap(Spacing::S2)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child("Median")
.child(self.format_val(lo))
.child(swatches)
.child(self.format_val(hi))
});
div()
.id(self.id)
.w_full()
.flex()
.flex_col()
.gap(Spacing::S2)
.p(Spacing::S4)
.rounded(Radii::PANEL)
.bg(colors.surface)
.border_1()
.border_color(colors.border_subtle)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(self.label),
)
.child(plot_box)
.children(scale_row)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ridgeline_stats_silverman_and_kde_peak() {
let stats = ridgeline_stats(&[10.0, 12.0, 14.0, 15.0, 16.0, 18.0, 20.0]);
assert_eq!(stats.n, 7);
assert!((stats.median - 15.0).abs() < 1e-6);
assert!(stats.q1 < stats.median && stats.median < stats.q3);
let bw = ridgeline_silverman_bandwidth(&stats);
assert!(bw > 0.5 && bw < 10.0);
let (xs, ys) = ridgeline_kde(&stats, 0.0, 30.0, bw);
assert_eq!(xs.len(), SAMPLES);
let peak_idx = ys
.iter()
.enumerate()
.max_by(|a, b| a.1.total_cmp(b.1))
.unwrap()
.0;
assert!((xs[peak_idx] - 15.0).abs() < 2.0);
}
}