use std::collections::{BTreeMap, HashMap};
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_band_fill, build_polyline_stroke, chart_series_color, format_grouped,
};
const SAMPLES: usize = 97;
const PLOT_PAD: f32 = 10.0;
const TIP_GAP: f32 = 12.0;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum StreamgraphOffset {
#[default]
Wiggle,
Silhouette,
Zero,
}
#[derive(Clone, Debug)]
pub struct StreamgraphSeries {
pub key: SharedString,
pub label: SharedString,
pub color: Option<Hsla>,
}
impl StreamgraphSeries {
pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
label: label.into(),
color: None,
}
}
pub fn color(mut self, color: Hsla) -> Self {
self.color = Some(color);
self
}
}
#[derive(Clone, Debug)]
pub struct StreamgraphDatum {
pub key: SharedString,
pub label: SharedString,
pub axis_label: Option<SharedString>,
pub values: BTreeMap<SharedString, f64>,
}
impl StreamgraphDatum {
pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
label: label.into(),
axis_label: None,
values: BTreeMap::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>, value: f64) -> Self {
self.values.insert(series_key.into(), value.max(0.0));
self
}
pub fn with_values<I, K>(mut self, entries: I) -> Self
where
I: IntoIterator<Item = (K, f64)>,
K: Into<SharedString>,
{
for (k, v) in entries {
self.values.insert(k.into(), v.max(0.0));
}
self
}
}
pub fn streamgraph_stack_order(count: usize, offset: StreamgraphOffset) -> Vec<usize> {
if count == 0 {
return Vec::new();
}
if offset == StreamgraphOffset::Zero {
return (0..count).collect();
}
let mut order = Vec::with_capacity(count);
for idx in 0..count {
if idx == 0 {
order.push(0);
} else if idx % 2 == 1 {
order.push(idx);
} else {
order.insert(0, idx);
}
}
order
}
pub fn streamgraph_resample(raw: &[f64]) -> Vec<f64> {
let values: Vec<f64> = raw
.iter()
.map(|&v| if v.is_finite() { v.max(0.0) } else { 0.0 })
.collect();
if values.is_empty() {
return vec![0.0; SAMPLES];
}
if values.len() == 1 {
return vec![values[0]; SAMPLES];
}
let last = values.len() - 1;
let slopes: Vec<f64> = (0..last).map(|i| values[i + 1] - values[i]).collect();
let mut tangents = vec![0.0; values.len()];
if last > 1 {
for i in 1..last {
let s0 = slopes[i - 1];
let s1 = slopes[i];
if s0 * s1 > 0.0 {
let sign = s0.signum() + s1.signum();
let mag = s0.abs().min(s1.abs()).min((s0 + s1).abs() / 4.0);
tangents[i] = sign * mag;
}
}
tangents[0] = (3.0 * slopes[0] - tangents[1]) / 2.0;
tangents[last] = (3.0 * slopes[last - 1] - tangents[last - 1]) / 2.0;
} else {
tangents[0] = slopes[0];
tangents[1] = slopes[0];
}
let mut out = Vec::with_capacity(SAMPLES);
for k in 0..SAMPLES {
let at = (k as f64 / (SAMPLES - 1) as f64) * last as f64;
let seg = (at.floor() as usize).min(last - 1);
let t = at - seg as f64;
let t2 = t * t;
let t3 = t2 * t;
let a = values[seg];
let b = values[seg + 1];
let v = (2.0 * t3 - 3.0 * t2 + 1.0) * a
+ (t3 - 2.0 * t2 + t) * tangents[seg]
+ (3.0 * t2 - 2.0 * t3) * b
+ (t3 - t2) * tangents[seg + 1];
out.push(v.clamp(a.min(b), a.max(b)));
}
out
}
pub fn streamgraph_baseline(layers: &[Vec<f64>], offset: StreamgraphOffset) -> Vec<f64> {
let mut g = vec![0.0; SAMPLES];
if layers.is_empty() || offset == StreamgraphOffset::Zero {
return g;
}
let totals: Vec<f64> = (0..SAMPLES)
.map(|j| layers.iter().map(|l| l[j]).sum::<f64>())
.collect();
if offset == StreamgraphOffset::Silhouette {
return totals.into_iter().map(|t| -t * 0.5).collect();
}
for j in 1..SAMPLES {
let mut s1 = 0.0;
let mut s2 = 0.0;
let mut below = 0.0;
for layer in layers {
let change = layer[j] - layer[j - 1];
s1 += layer[j];
s2 += (below + change * 0.5) * layer[j];
below += change;
}
g[j] = g[j - 1] - if s1 > 1e-12 { s2 / s1 } else { 0.0 };
}
let centers: Vec<f64> = (0..SAMPLES).map(|j| g[j] + totals[j] * 0.5).collect();
let mx = (SAMPLES - 1) as f64 * 0.5;
let my = centers.iter().sum::<f64>() / SAMPLES as f64;
let mut num = 0.0;
let mut den = 0.0;
for (j, &c) in centers.iter().enumerate() {
let dx = j as f64 - mx;
num += dx * (c - my);
den += dx * dx;
}
let slope = if den > 1e-12 { num / den } else { 0.0 };
g.into_iter()
.enumerate()
.map(|(j, val)| val - (my + slope * (j as f64 - mx)))
.collect()
}
pub fn streamgraph_axis_picks(data: &[StreamgraphDatum], 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 <= 1.0 || labeled.is_empty() {
return Vec::new();
}
let max_ticks = ((width / 72.0).floor() as usize).max(2);
let stride = labeled.len().div_ceil(max_ticks).max(1);
let mut picks: Vec<usize> = labeled
.into_iter()
.rev()
.enumerate()
.filter_map(|(rank, idx)| (rank % stride == 0).then_some(idx))
.collect();
picks.reverse();
picks
}
#[derive(Clone, Debug)]
struct ComputedStream {
lower: Vec<Vec<f64>>,
upper: Vec<Vec<f64>>,
center: Vec<f64>,
lo: f64,
hi: f64,
}
impl ComputedStream {
fn to_y(&self, value: f64, height: f32, swell: f32, j: usize) -> f32 {
let span = (self.hi - self.lo).max(1e-9);
let c = self.center[j];
let v = c + (value - c) * swell as f64;
PLOT_PAD + (1.0 - ((v - self.lo) / span) as f32) * (height - PLOT_PAD * 2.0)
}
}
fn compute_stream(
series: &[StreamgraphSeries],
shapes: &HashMap<SharedString, Vec<f64>>,
presence: &HashMap<SharedString, f32>,
offset: StreamgraphOffset,
) -> ComputedStream {
let n = series.len();
let layers: Vec<Vec<f64>> = series
.iter()
.map(|s| {
let p = presence.get(&s.key).copied().unwrap_or(1.0).max(0.0) as f64;
match shapes.get(&s.key) {
Some(vals) => vals.iter().map(|&v| v * p).collect(),
None => vec![0.0; SAMPLES],
}
})
.collect();
let stack = streamgraph_stack_order(n, offset);
let ordered: Vec<Vec<f64>> = stack.iter().map(|&i| layers[i].clone()).collect();
let g = streamgraph_baseline(&ordered, offset);
let mut lower = vec![vec![0.0; SAMPLES]; n];
let mut upper = vec![vec![0.0; SAMPLES]; n];
let mut running = g.clone();
for &i in &stack {
lower[i] = running.clone();
for j in 0..SAMPLES {
running[j] += layers[i][j];
}
upper[i] = running.clone();
}
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for j in 0..SAMPLES {
lo = lo.min(g[j]);
hi = hi.max(running[j]);
}
if !lo.is_finite() || (hi - lo) < 1e-9 {
lo = -1.0;
hi = 1.0;
}
let center: Vec<f64> = (0..SAMPLES).map(|j| (g[j] + running[j]) * 0.5).collect();
ComputedStream {
lower,
upper,
center,
lo,
hi,
}
}
type FormatValueFn = Rc<dyn Fn(f64, &StreamgraphSeries) -> SharedString>;
type OnActiveFn = Rc<dyn Fn(Option<usize>, Option<SharedString>, &mut Window, &mut App)>;
struct StreamgraphState {
focus_handle: FocusHandle,
hidden: Vec<SharedString>,
hover_index: Option<usize>,
hover_key: Option<SharedString>,
hover_y: Option<f32>,
legend_hover: Option<SharedString>,
plot_bounds: Option<Bounds<Pixels>>,
swell: ChartSpring,
presence: HashMap<SharedString, ChartSpring>,
cursor_x: ChartSpring,
last_frame_secs: Option<f64>,
last_signature: String,
cached_shapes: HashMap<SharedString, Vec<f64>>,
label_spots: HashMap<SharedString, usize>,
}
impl StreamgraphState {
fn new(cx: &mut Context<Self>) -> Self {
Self {
focus_handle: cx.focus_handle(),
hidden: Vec::new(),
hover_index: None,
hover_key: None,
hover_y: None,
legend_hover: None,
plot_bounds: None,
swell: ChartSpring::new(0.0),
presence: HashMap::new(),
cursor_x: ChartSpring::new(0.0),
last_frame_secs: None,
last_signature: String::new(),
cached_shapes: HashMap::new(),
label_spots: HashMap::new(),
}
}
}
#[derive(IntoElement)]
pub struct Streamgraph {
id: ElementId,
label: SharedString,
series: Vec<StreamgraphSeries>,
data: Vec<StreamgraphDatum>,
unit: SharedString,
height: f32,
offset: StreamgraphOffset,
legend: bool,
direct_labels: bool,
empty_label: SharedString,
format_value: Option<FormatValueFn>,
on_active_change: Option<OnActiveFn>,
}
impl Streamgraph {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
series: Vec<StreamgraphSeries>,
data: Vec<StreamgraphDatum>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
series,
data,
unit: SharedString::from(""),
height: 256.0,
offset: StreamgraphOffset::Wiggle,
legend: true,
direct_labels: true,
empty_label: SharedString::from("No data for this range"),
format_value: None,
on_active_change: None,
}
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = unit.into();
self
}
pub fn height(mut self, height: f32) -> Self {
self.height = height.max(120.0);
self
}
pub fn offset(mut self, offset: StreamgraphOffset) -> Self {
self.offset = offset;
self
}
pub fn legend(mut self, show: bool) -> Self {
self.legend = show;
self
}
pub fn direct_labels(mut self, show: bool) -> Self {
self.direct_labels = show;
self
}
pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
self.empty_label = label.into();
self
}
pub fn format_value(
mut self,
f: impl Fn(f64, &StreamgraphSeries) -> SharedString + 'static,
) -> Self {
self.format_value = Some(Rc::new(f));
self
}
pub fn on_active_change(
mut self,
f: impl Fn(Option<usize>, Option<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_active_change = Some(Rc::new(f));
self
}
fn format_datum_value(&self, v: f64, s: &StreamgraphSeries) -> String {
let base = if let Some(ref f) = self.format_value {
f(v, s).to_string()
} else {
format_grouped(v, 1)
};
if self.unit.is_empty() {
base
} else {
format!("{base} {}", self.unit)
}
}
}
impl RenderOnce for Streamgraph {
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| StreamgraphState::new(cx),
);
let empty = self.data.is_empty();
let last = self.data.len().saturating_sub(1);
let mut sig = String::new();
for s in &self.series {
sig.push_str(s.key.as_ref());
sig.push(',');
}
sig.push('|');
for d in &self.data {
for s in &self.series {
let v = d.values.get(&s.key).copied().unwrap_or(0.0);
sig.push_str(&format!("{:.2},", v));
}
sig.push(';');
}
let mut animating = false;
let (
hidden_list,
hover_index,
active_key,
swell_val,
presence_vals,
cursor_x_val,
plot_w,
shapes_map,
) = 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 st.last_signature != sig {
st.last_signature = sig.clone();
st.hover_index = None;
st.hover_key = None;
let mut next_shapes = HashMap::new();
for s in &self.series {
let raw: Vec<f64> = self
.data
.iter()
.map(|d| d.values.get(&s.key).copied().unwrap_or(0.0))
.collect();
next_shapes.insert(s.key.clone(), streamgraph_resample(&raw));
}
st.cached_shapes = next_shapes;
}
if empty || reduced {
st.swell.snap(1.0);
} else if !st.swell.is_settled_at(1.0, 0.002) {
st.swell.step_to(1.0, 0.82, 0.0, dt);
animating = true;
}
let mut pres = HashMap::new();
for s in &self.series {
let target = if st.hidden.contains(&s.key) { 0.0 } else { 1.0 };
let sp = st
.presence
.entry(s.key.clone())
.or_insert_with(|| ChartSpring::new(target));
if reduced {
sp.snap(target);
} else if !sp.is_settled_at(target, 0.002) {
sp.step_to(target, 0.36, 0.0, dt);
animating = true;
}
pres.insert(s.key.clone(), sp.value.clamp(0.0, 1.0));
}
let w = st
.plot_bounds
.map(|b| f32::from(b.size.width))
.unwrap_or(520.0)
.max(120.0);
let idx = st.hover_index.filter(|_| !empty).map(|i| i.min(last));
if let Some(i) = idx {
let target_x = if last > 0 {
(i as f32 / last as f32) * w
} else {
w * 0.5
};
if reduced {
st.cursor_x.snap(target_x);
} else if !st.cursor_x.is_settled_at(target_x, 0.25) {
st.cursor_x.step_to(target_x, 0.22, 0.0, dt);
animating = true;
}
}
let wanted = st.hover_key.clone().or_else(|| st.legend_hover.clone());
let active_k = wanted
.filter(|k| self.series.iter().any(|s| &s.key == k) && !st.hidden.contains(k));
(
st.hidden.clone(),
idx,
active_k,
st.swell.value.clamp(0.0, 1.0),
pres,
st.cursor_x.value,
w,
st.cached_shapes.clone(),
)
});
if animating {
window.request_animation_frame();
}
let computed = compute_stream(&self.series, &shapes_map, &presence_vals, self.offset);
let visible_series: Vec<&StreamgraphSeries> = self
.series
.iter()
.filter(|s| !hidden_list.contains(&s.key))
.collect();
let series_colors: Vec<Hsla> = self
.series
.iter()
.enumerate()
.map(|(i, s)| s.color.unwrap_or_else(|| chart_series_color(&colors, i)))
.collect();
let mut label_placements: Vec<(SharedString, f32, f32, bool, Hsla)> = Vec::new();
if self.direct_labels && !empty {
state.update(cx, |st, _| {
let span = (computed.hi - computed.lo).max(1e-9);
for (i, s) in self.series.iter().enumerate() {
if hidden_list.contains(&s.key) {
continue;
}
let top = &computed.upper[i];
let bottom = &computed.lower[i];
let mut best = 4usize.min(SAMPLES - 1);
for j in 4..SAMPLES.saturating_sub(4) {
if (top[j] - bottom[j]) > (top[best] - bottom[best]) {
best = j;
}
}
let best_thick = top[best] - bottom[best];
let j = match st.label_spots.get(&s.key).copied() {
Some(held)
if held < SAMPLES && (top[held] - bottom[held]) >= best_thick * 0.8 =>
{
held
}
_ => best,
};
st.label_spots.insert(s.key.clone(), j);
let px_thick = ((top[j] - bottom[j]) / span) as f32
* (self.height - PLOT_PAD * 2.0)
* swell_val;
let est_w = (s.label.len() as f32 * 6.8).max(36.0);
let min_x = (est_w * 0.5 + 8.0).min(plot_w * 0.5);
let max_x = (plot_w - est_w * 0.5 - 8.0).max(min_x);
let x = ((j as f32 / (SAMPLES - 1) as f32) * plot_w).clamp(min_x, max_x);
let y = computed.to_y((top[j] + bottom[j]) * 0.5, self.height, swell_val, j);
let fits = px_thick >= 20.0 && est_w + 16.0 < plot_w;
label_placements.push((s.label.clone(), x, y, fits, series_colors[i]));
}
});
}
let legend_row = (self.legend && self.series.len() > 1).then(|| {
let mut row = div().flex().flex_wrap().items_center().gap(Spacing::S2);
for (i, s) in self.series.iter().enumerate() {
let is_hidden = hidden_list.contains(&s.key);
let is_active = active_key.as_ref() == Some(&s.key);
let is_dim = active_key.is_some() && !is_active;
let col = series_colors[i];
let key_click = s.key.clone();
let key_hover = s.key.clone();
let state_click = state.clone();
let state_hover = state.clone();
row = row.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("legend-{}", s.key).into(),
))
.flex()
.items_center()
.gap(px(6.0))
.px(Spacing::S2)
.py(px(3.0))
.rounded(Radii::PILL)
.border_1()
.border_color(if is_active { col } else { colors.border_subtle })
.bg(if is_active {
oklab_mix(col, colors.surface, 0.14)
} else {
colors.surface
})
.opacity(if is_hidden {
0.42
} else if is_dim {
0.55
} else {
1.0
})
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
state_hover.update(cx, |st, _| {
if *hovered {
st.legend_hover = Some(key_hover.clone());
} else if st.legend_hover.as_ref() == Some(&key_hover) {
st.legend_hover = None;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
state_click.update(cx, |st, _| {
if let Some(pos) = st.hidden.iter().position(|k| k == &key_click) {
st.hidden.remove(pos);
} else {
st.hidden.push(key_click.clone());
}
});
window.refresh();
})
.child(div().size(px(8.0)).rounded(Radii::PILL).bg(col))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.foreground)
.child(s.label.clone()),
),
);
}
row
});
let paint_computed = computed.clone();
let paint_colors = series_colors.clone();
let paint_series_keys: Vec<SharedString> =
self.series.iter().map(|s| s.key.clone()).collect();
let paint_active_key = active_key.clone();
let paint_hover_idx = hover_index;
let paint_height = self.height;
let paint_swell = swell_val;
let paint_cursor_x = cursor_x_val;
let crosshair_color = oklab_mix(colors.foreground, colors.surface, 0.35);
let state_bounds = state.clone();
let plot_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);
for (i, key) in paint_series_keys.iter().enumerate() {
let top_vals = &paint_computed.upper[i];
let bot_vals = &paint_computed.lower[i];
let mut upper_pts = Vec::with_capacity(SAMPLES);
let mut lower_pts = Vec::with_capacity(SAMPLES);
for j in 0..SAMPLES {
let x = ox + (j as f32 / (SAMPLES - 1) as f32) * w;
let yt = oy + paint_computed.to_y(top_vals[j], h, paint_swell, j);
let yb = oy + paint_computed.to_y(bot_vals[j], h, paint_swell, j);
upper_pts.push(point(px(x), px(yt)));
lower_pts.push(point(px(x), px(yb)));
}
if let Some(path) = build_band_fill(&upper_pts, &lower_pts) {
let base_col = paint_colors[i];
let is_active = paint_active_key.as_ref() == Some(key);
let is_dim = paint_active_key.is_some() && !is_active;
let fill = if is_dim {
Hsla {
a: base_col.a * 0.28,
..base_col
}
} else if is_active {
Hsla {
a: (base_col.a * 0.96).min(1.0),
..base_col
}
} else {
Hsla {
a: base_col.a * 0.84,
..base_col
}
};
window.paint_path(path, fill);
}
}
if paint_hover_idx.is_some() {
let cx_px = ox + paint_cursor_x.clamp(0.0, w);
if let Some(line) = build_polyline_stroke(
&[
point(px(cx_px), px(oy)),
point(px(cx_px), px(oy + paint_height)),
],
1.0,
) {
window.paint_path(line, crosshair_color);
}
}
},
)
.size_full();
let state_move = state.clone();
let state_down = state.clone();
let state_hover = state.clone();
let state_key = state.clone();
let move_computed = computed.clone();
let move_series_keys: Vec<SharedString> =
self.series.iter().map(|s| s.key.clone()).collect();
let move_height = self.height;
let move_swell = swell_val;
let move_on_active = self.on_active_change.clone();
let down_computed = computed.clone();
let down_series_keys = move_series_keys.clone();
let down_on_active = self.on_active_change.clone();
let key_series_keys: Vec<SharedString> =
self.series.iter().map(|s| s.key.clone()).collect();
let key_on_active = self.on_active_change.clone();
let data_len = self.data.len();
let hit_test = move |pos_x: f32,
pos_y: f32,
bounds: Bounds<Pixels>,
comp: &ComputedStream,
keys: &[SharedString],
hidden: &[SharedString],
h: f32,
swell: f32|
-> (usize, Option<SharedString>, f32) {
let w = f32::from(bounds.size.width).max(1.0);
let local_x = (pos_x - f32::from(bounds.origin.x)).clamp(0.0, w);
let local_y = (pos_y - f32::from(bounds.origin.y)).clamp(0.0, h);
let share = (local_x / w).clamp(0.0, 1.0);
let idx = if last > 0 {
(share * last as f32).round() as usize
} else {
0
}
.min(last);
let j = ((share * (SAMPLES - 1) as f32).round() as usize).min(SAMPLES - 1);
let mut hit_key = None;
for (i, k) in keys.iter().enumerate() {
if hidden.contains(k) {
continue;
}
let yt = comp.to_y(comp.upper[i][j], h, swell, j);
let yb = comp.to_y(comp.lower[i][j], h, swell, j);
if local_y >= yt - 1.5 && local_y <= yb + 1.5 {
hit_key = Some(k.clone());
}
}
(idx, hit_key, local_y)
};
let focus_handle = state.read(cx).focus_handle.clone();
let tooltip_el = hover_index.and_then(|idx| self.data.get(idx)).map(|datum| {
let tip_w = 176.0f32;
let row_count = visible_series.len().max(1);
let tip_h = 34.0 + row_count as f32 * 20.0;
let x_anchor = if last > 0 {
(hover_index.unwrap_or(0) as f32 / last as f32) * plot_w
} else {
plot_w * 0.5
};
let left = if x_anchor + TIP_GAP + tip_w <= plot_w {
x_anchor + TIP_GAP
} else {
(x_anchor - TIP_GAP - tip_w).max(4.0)
};
let hover_y = state.read(cx).hover_y.unwrap_or(self.height * 0.5);
let top = (hover_y - tip_h * 0.5).clamp(4.0, (self.height - tip_h - 4.0).max(4.0));
let stack_rev: Vec<usize> = streamgraph_stack_order(self.series.len(), self.offset)
.into_iter()
.rev()
.collect();
let mut box_el = 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(4.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.child(datum.label.clone()),
);
for i in stack_rev {
let s = &self.series[i];
if hidden_list.contains(&s.key) {
continue;
}
let val = datum.values.get(&s.key).copied().unwrap_or(0.0);
let is_active = active_key.as_ref() == Some(&s.key);
let is_dim = active_key.is_some() && !is_active;
box_el = box_el.child(
div()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S2)
.opacity(if is_dim { 0.45 } else { 1.0 })
.child(
div()
.flex()
.items_center()
.gap(px(6.0))
.child(
div()
.size(px(7.0))
.rounded(Radii::PILL)
.bg(series_colors[i]),
)
.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(self.format_datum_value(val, s)),
),
);
}
box_el
});
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(self.height))
.overflow_hidden()
.cursor_crosshair()
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
if empty {
return;
}
let mut changed = None;
state_move.update(cx, |st, _| {
if let Some(bounds) = st.plot_bounds {
let (idx, key, ly) = hit_test(
f32::from(event.position.x),
f32::from(event.position.y),
bounds,
&move_computed,
&move_series_keys,
&st.hidden,
move_height,
move_swell,
);
if st.hover_index != Some(idx) || st.hover_key != key {
changed = Some((Some(idx), key.clone()));
}
st.hover_index = Some(idx);
st.hover_key = key;
st.hover_y = Some(ly);
}
});
if let (Some(cb), Some((idx, key))) = (&move_on_active, changed) {
cb(idx, key, window, cx);
}
window.refresh();
})
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
if empty {
return;
}
let mut changed = 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 (idx, key, ly) = hit_test(
f32::from(event.position.x),
f32::from(event.position.y),
bounds,
&down_computed,
&down_series_keys,
&st.hidden,
move_height,
move_swell,
);
st.hover_index = Some(idx);
st.hover_key = key.clone();
st.hover_y = Some(ly);
changed = Some((Some(idx), key));
}
});
if let (Some(cb), Some((idx, key))) = (&down_on_active, changed) {
cb(idx, key, window, cx);
}
window.refresh();
},
)
.on_hover(move |hovered, window, cx| {
if !*hovered {
state_hover.update(cx, |st, _| {
st.hover_index = None;
st.hover_key = None;
st.hover_y = None;
});
window.refresh();
}
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if empty || data_len == 0 {
return;
}
let key = event.keystroke.key.as_str();
let mut result: Option<(Option<usize>, Option<SharedString>)> = None;
state_key.update(cx, |st, _| {
let visible_keys: Vec<SharedString> = key_series_keys
.iter()
.filter(|k| !st.hidden.contains(k))
.cloned()
.collect();
let from = st.hover_index.unwrap_or(last);
let page = (data_len / 6).max(1);
let cur_k = st.hover_key.clone();
let pos_k = cur_k
.as_ref()
.and_then(|k| visible_keys.iter().position(|vk| vk == k));
match key {
"escape" => {
st.hover_index = None;
st.hover_key = None;
result = Some((None, None));
}
"left" => {
let next = from.saturating_sub(1);
st.hover_index = Some(next);
result = Some((Some(next), cur_k));
}
"right" => {
let next = if st.hover_index.is_none() {
last
} else {
(from + 1).min(last)
};
st.hover_index = Some(next);
result = Some((Some(next), cur_k));
}
"pageup" => {
let next = (from + page).min(last);
st.hover_index = Some(next);
result = Some((Some(next), cur_k));
}
"pagedown" => {
let next = from.saturating_sub(page);
st.hover_index = Some(next);
result = Some((Some(next), cur_k));
}
"home" => {
st.hover_index = Some(0);
result = Some((Some(0), cur_k));
}
"end" => {
st.hover_index = Some(last);
result = Some((Some(last), cur_k));
}
"up" if !visible_keys.is_empty() => {
let next_k = match pos_k {
None => visible_keys.last().cloned(),
Some(p) => visible_keys
.get((p + 1).min(visible_keys.len() - 1))
.cloned(),
};
st.hover_index = Some(from);
st.hover_key = next_k.clone();
result = Some((Some(from), next_k));
}
"down" if !visible_keys.is_empty() => {
let next_k = match pos_k {
None => visible_keys.first().cloned(),
Some(p) => visible_keys.get(p.saturating_sub(1)).cloned(),
};
st.hover_index = Some(from);
st.hover_key = next_k.clone();
result = Some((Some(from), next_k));
}
_ => {}
}
});
if let Some((idx, k)) = result {
if let Some(ref cb) = key_on_active {
cb(idx, k, window, cx);
}
cx.stop_propagation();
window.refresh();
}
})
.child(plot_canvas);
for (lbl, lx, ly, fits, _col) in label_placements {
if !fits {
continue;
}
plot_box = plot_box.child(
div()
.absolute()
.left(px((lx - 42.0).max(4.0)))
.top(px((ly - 8.0).max(2.0)))
.w(px(84.0))
.flex()
.justify_center()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.background)
.child(lbl),
);
}
if let Some(tip) = tooltip_el {
plot_box = plot_box.child(tip);
}
if empty || visible_series.is_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(if empty {
self.empty_label.clone()
} else {
SharedString::from("Choose a layer to show")
}),
);
}
let picks = streamgraph_axis_picks(&self.data, plot_w);
let axis_row =
div()
.relative()
.w_full()
.h(px(20.0))
.children(picks.into_iter().filter_map(|idx| {
let d = self.data.get(idx)?;
let text = d.axis_label.clone()?;
let share = if last > 0 {
idx as f32 / last as f32
} else {
0.5
};
let left = (share * plot_w - 28.0).clamp(0.0, (plot_w - 56.0).max(0.0));
Some(
div()
.absolute()
.left(px(left))
.top(px(2.0))
.w(px(56.0))
.flex()
.justify_center()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(text),
)
}));
div()
.id(self.id)
.w_full()
.flex()
.flex_col()
.gap(Spacing::S3)
.p(Spacing::S4)
.rounded(Radii::PANEL)
.bg(colors.surface)
.border_1()
.border_color(colors.border_subtle)
.child(
div()
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(self.label),
)
.children(legend_row),
)
.child(plot_box)
.child(axis_row)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn streamgraph_stack_order_resample_and_baselines() {
assert_eq!(
streamgraph_stack_order(5, StreamgraphOffset::Zero),
vec![0, 1, 2, 3, 4]
);
assert_eq!(
streamgraph_stack_order(5, StreamgraphOffset::Wiggle),
vec![4, 2, 0, 1, 3]
);
let resampled = streamgraph_resample(&[10.0, 40.0, 20.0, 60.0]);
assert_eq!(resampled.len(), SAMPLES);
assert!((resampled[0] - 10.0).abs() < 1e-6);
assert!((resampled[SAMPLES - 1] - 60.0).abs() < 1e-6);
assert!(
resampled
.iter()
.all(|&v| (10.0 - 1e-6..=60.0 + 1e-6).contains(&v))
);
let l1 = streamgraph_resample(&[10.0, 20.0, 30.0]);
let l2 = streamgraph_resample(&[5.0, 15.0, 10.0]);
let sil = streamgraph_baseline(&[l1.clone(), l2.clone()], StreamgraphOffset::Silhouette);
assert!((sil[0] + 7.5).abs() < 1e-6);
let wig = streamgraph_baseline(&[l1, l2], StreamgraphOffset::Wiggle);
assert_eq!(wig.len(), SAMPLES);
assert!(wig.iter().all(|v| v.is_finite()));
}
}