Skip to main content

arc_ui/chart/
streamgraph.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/streamgraph/streamgraph.tsx`
3//!
4//! `Streamgraph` — stacked flowing ribbons over time with `Wiggle` (Byron & Wattenberg
5//! drift-corrected), `Silhouette`, and `Zero` baselines, monotone cubic resampling onto
6//! a shared grid, smooth swell-in entrance, interactive legend hiding/focusing, direct
7//! interior labels, crosshair + floating tooltip, and keyboard navigation.
8
9use std::collections::{BTreeMap, HashMap};
10use std::rc::Rc;
11
12use arc_motion::{is_reduced_motion, motion_now};
13use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
14use gpui_kit::{
15    App, Bounds, Context, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement,
16    KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce,
17    Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
18};
19
20use super::common::{
21    ChartSpring, build_band_fill, build_polyline_stroke, chart_series_color, format_grouped,
22};
23
24const SAMPLES: usize = 97;
25const PLOT_PAD: f32 = 10.0;
26const TIP_GAP: f32 = 12.0;
27
28/// Baseline mode for `Streamgraph`.
29#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
30pub enum StreamgraphOffset {
31    /// Byron & Wattenberg wiggle with linear drift removal for a level flowing stream.
32    #[default]
33    Wiggle,
34    /// Symmetrically centered around the horizontal midline.
35    Silhouette,
36    /// Flat zero baseline stacked upward.
37    Zero,
38}
39
40/// One ribbon layer descriptor in `Streamgraph`.
41#[derive(Clone, Debug)]
42pub struct StreamgraphSeries {
43    pub key: SharedString,
44    pub label: SharedString,
45    pub color: Option<Hsla>,
46}
47
48impl StreamgraphSeries {
49    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
50        Self {
51            key: key.into(),
52            label: label.into(),
53            color: None,
54        }
55    }
56
57    pub fn color(mut self, color: Hsla) -> Self {
58        self.color = Some(color);
59        self
60    }
61}
62
63/// One time point with values per series key.
64#[derive(Clone, Debug)]
65pub struct StreamgraphDatum {
66    pub key: SharedString,
67    pub label: SharedString,
68    pub axis_label: Option<SharedString>,
69    pub values: BTreeMap<SharedString, f64>,
70}
71
72impl StreamgraphDatum {
73    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
74        Self {
75            key: key.into(),
76            label: label.into(),
77            axis_label: None,
78            values: BTreeMap::new(),
79        }
80    }
81
82    pub fn axis_label(mut self, label: impl Into<SharedString>) -> Self {
83        self.axis_label = Some(label.into());
84        self
85    }
86
87    pub fn value(mut self, series_key: impl Into<SharedString>, value: f64) -> Self {
88        self.values.insert(series_key.into(), value.max(0.0));
89        self
90    }
91
92    pub fn with_values<I, K>(mut self, entries: I) -> Self
93    where
94        I: IntoIterator<Item = (K, f64)>,
95        K: Into<SharedString>,
96    {
97        for (k, v) in entries {
98            self.values.insert(k.into(), v.max(0.0));
99        }
100        self
101    }
102}
103
104/// Center-out stacking order for Wiggle/Silhouette, or sequential order for Zero baseline.
105pub fn streamgraph_stack_order(count: usize, offset: StreamgraphOffset) -> Vec<usize> {
106    if count == 0 {
107        return Vec::new();
108    }
109    if offset == StreamgraphOffset::Zero {
110        return (0..count).collect();
111    }
112    let mut order = Vec::with_capacity(count);
113    for idx in 0..count {
114        if idx == 0 {
115            order.push(0);
116        } else if idx % 2 == 1 {
117            order.push(idx);
118        } else {
119            order.insert(0, idx);
120        }
121    }
122    order
123}
124
125/// Resample a non-negative series onto a shared `SAMPLES` grid using monotone cubic Hermite
126/// interpolation so curves never overshoot local extrema or dip below zero.
127pub fn streamgraph_resample(raw: &[f64]) -> Vec<f64> {
128    let values: Vec<f64> = raw
129        .iter()
130        .map(|&v| if v.is_finite() { v.max(0.0) } else { 0.0 })
131        .collect();
132    if values.is_empty() {
133        return vec![0.0; SAMPLES];
134    }
135    if values.len() == 1 {
136        return vec![values[0]; SAMPLES];
137    }
138    let last = values.len() - 1;
139    let slopes: Vec<f64> = (0..last).map(|i| values[i + 1] - values[i]).collect();
140    let mut tangents = vec![0.0; values.len()];
141    if last > 1 {
142        for i in 1..last {
143            let s0 = slopes[i - 1];
144            let s1 = slopes[i];
145            if s0 * s1 > 0.0 {
146                let sign = s0.signum() + s1.signum();
147                let mag = s0.abs().min(s1.abs()).min((s0 + s1).abs() / 4.0);
148                tangents[i] = sign * mag;
149            }
150        }
151        tangents[0] = (3.0 * slopes[0] - tangents[1]) / 2.0;
152        tangents[last] = (3.0 * slopes[last - 1] - tangents[last - 1]) / 2.0;
153    } else {
154        tangents[0] = slopes[0];
155        tangents[1] = slopes[0];
156    }
157    let mut out = Vec::with_capacity(SAMPLES);
158    for k in 0..SAMPLES {
159        let at = (k as f64 / (SAMPLES - 1) as f64) * last as f64;
160        let seg = (at.floor() as usize).min(last - 1);
161        let t = at - seg as f64;
162        let t2 = t * t;
163        let t3 = t2 * t;
164        let a = values[seg];
165        let b = values[seg + 1];
166        let v = (2.0 * t3 - 3.0 * t2 + 1.0) * a
167            + (t3 - 2.0 * t2 + t) * tangents[seg]
168            + (3.0 * t2 - 2.0 * t3) * b
169            + (t3 - t2) * tangents[seg + 1];
170        out.push(v.clamp(a.min(b), a.max(b)));
171    }
172    out
173}
174
175/// Compute lower baseline for stacked layers according to `StreamgraphOffset`.
176pub fn streamgraph_baseline(layers: &[Vec<f64>], offset: StreamgraphOffset) -> Vec<f64> {
177    let mut g = vec![0.0; SAMPLES];
178    if layers.is_empty() || offset == StreamgraphOffset::Zero {
179        return g;
180    }
181    let totals: Vec<f64> = (0..SAMPLES)
182        .map(|j| layers.iter().map(|l| l[j]).sum::<f64>())
183        .collect();
184    if offset == StreamgraphOffset::Silhouette {
185        return totals.into_iter().map(|t| -t * 0.5).collect();
186    }
187    for j in 1..SAMPLES {
188        let mut s1 = 0.0;
189        let mut s2 = 0.0;
190        let mut below = 0.0;
191        for layer in layers {
192            let change = layer[j] - layer[j - 1];
193            s1 += layer[j];
194            s2 += (below + change * 0.5) * layer[j];
195            below += change;
196        }
197        g[j] = g[j - 1] - if s1 > 1e-12 { s2 / s1 } else { 0.0 };
198    }
199    // Remove linear drift via least squares through the stream centerline.
200    let centers: Vec<f64> = (0..SAMPLES).map(|j| g[j] + totals[j] * 0.5).collect();
201    let mx = (SAMPLES - 1) as f64 * 0.5;
202    let my = centers.iter().sum::<f64>() / SAMPLES as f64;
203    let mut num = 0.0;
204    let mut den = 0.0;
205    for (j, &c) in centers.iter().enumerate() {
206        let dx = j as f64 - mx;
207        num += dx * (c - my);
208        den += dx * dx;
209    }
210    let slope = if den > 1e-12 { num / den } else { 0.0 };
211    g.into_iter()
212        .enumerate()
213        .map(|(j, val)| val - (my + slope * (j as f64 - mx)))
214        .collect()
215}
216
217/// Choose X-axis tick indices from right to left (at most 1 per 72px).
218pub fn streamgraph_axis_picks(data: &[StreamgraphDatum], width: f32) -> Vec<usize> {
219    let labeled: Vec<usize> = data
220        .iter()
221        .enumerate()
222        .filter_map(|(i, d)| d.axis_label.as_ref().map(|_| i))
223        .collect();
224    if width <= 1.0 || labeled.is_empty() {
225        return Vec::new();
226    }
227    let max_ticks = ((width / 72.0).floor() as usize).max(2);
228    let stride = labeled.len().div_ceil(max_ticks).max(1);
229    let mut picks: Vec<usize> = labeled
230        .into_iter()
231        .rev()
232        .enumerate()
233        .filter_map(|(rank, idx)| (rank % stride == 0).then_some(idx))
234        .collect();
235    picks.reverse();
236    picks
237}
238
239#[derive(Clone, Debug)]
240struct ComputedStream {
241    lower: Vec<Vec<f64>>,
242    upper: Vec<Vec<f64>>,
243    center: Vec<f64>,
244    lo: f64,
245    hi: f64,
246}
247
248impl ComputedStream {
249    fn to_y(&self, value: f64, height: f32, swell: f32, j: usize) -> f32 {
250        let span = (self.hi - self.lo).max(1e-9);
251        let c = self.center[j];
252        let v = c + (value - c) * swell as f64;
253        PLOT_PAD + (1.0 - ((v - self.lo) / span) as f32) * (height - PLOT_PAD * 2.0)
254    }
255}
256
257fn compute_stream(
258    series: &[StreamgraphSeries],
259    shapes: &HashMap<SharedString, Vec<f64>>,
260    presence: &HashMap<SharedString, f32>,
261    offset: StreamgraphOffset,
262) -> ComputedStream {
263    let n = series.len();
264    let layers: Vec<Vec<f64>> = series
265        .iter()
266        .map(|s| {
267            let p = presence.get(&s.key).copied().unwrap_or(1.0).max(0.0) as f64;
268            match shapes.get(&s.key) {
269                Some(vals) => vals.iter().map(|&v| v * p).collect(),
270                None => vec![0.0; SAMPLES],
271            }
272        })
273        .collect();
274    let stack = streamgraph_stack_order(n, offset);
275    let ordered: Vec<Vec<f64>> = stack.iter().map(|&i| layers[i].clone()).collect();
276    let g = streamgraph_baseline(&ordered, offset);
277    let mut lower = vec![vec![0.0; SAMPLES]; n];
278    let mut upper = vec![vec![0.0; SAMPLES]; n];
279    let mut running = g.clone();
280    for &i in &stack {
281        lower[i] = running.clone();
282        for j in 0..SAMPLES {
283            running[j] += layers[i][j];
284        }
285        upper[i] = running.clone();
286    }
287    let mut lo = f64::INFINITY;
288    let mut hi = f64::NEG_INFINITY;
289    for j in 0..SAMPLES {
290        lo = lo.min(g[j]);
291        hi = hi.max(running[j]);
292    }
293    if !lo.is_finite() || (hi - lo) < 1e-9 {
294        lo = -1.0;
295        hi = 1.0;
296    }
297    let center: Vec<f64> = (0..SAMPLES).map(|j| (g[j] + running[j]) * 0.5).collect();
298    ComputedStream {
299        lower,
300        upper,
301        center,
302        lo,
303        hi,
304    }
305}
306
307type FormatValueFn = Rc<dyn Fn(f64, &StreamgraphSeries) -> SharedString>;
308type OnActiveFn = Rc<dyn Fn(Option<usize>, Option<SharedString>, &mut Window, &mut App)>;
309
310struct StreamgraphState {
311    focus_handle: FocusHandle,
312    hidden: Vec<SharedString>,
313    hover_index: Option<usize>,
314    hover_key: Option<SharedString>,
315    hover_y: Option<f32>,
316    legend_hover: Option<SharedString>,
317    plot_bounds: Option<Bounds<Pixels>>,
318    swell: ChartSpring,
319    presence: HashMap<SharedString, ChartSpring>,
320    cursor_x: ChartSpring,
321    last_frame_secs: Option<f64>,
322    last_signature: String,
323    cached_shapes: HashMap<SharedString, Vec<f64>>,
324    label_spots: HashMap<SharedString, usize>,
325}
326
327impl StreamgraphState {
328    fn new(cx: &mut Context<Self>) -> Self {
329        Self {
330            focus_handle: cx.focus_handle(),
331            hidden: Vec::new(),
332            hover_index: None,
333            hover_key: None,
334            hover_y: None,
335            legend_hover: None,
336            plot_bounds: None,
337            swell: ChartSpring::new(0.0),
338            presence: HashMap::new(),
339            cursor_x: ChartSpring::new(0.0),
340            last_frame_secs: None,
341            last_signature: String::new(),
342            cached_shapes: HashMap::new(),
343            label_spots: HashMap::new(),
344        }
345    }
346}
347
348/// Arc `Streamgraph` component.
349#[derive(IntoElement)]
350pub struct Streamgraph {
351    id: ElementId,
352    label: SharedString,
353    series: Vec<StreamgraphSeries>,
354    data: Vec<StreamgraphDatum>,
355    unit: SharedString,
356    height: f32,
357    offset: StreamgraphOffset,
358    legend: bool,
359    direct_labels: bool,
360    empty_label: SharedString,
361    format_value: Option<FormatValueFn>,
362    on_active_change: Option<OnActiveFn>,
363}
364
365impl Streamgraph {
366    pub fn new(
367        id: impl Into<ElementId>,
368        label: impl Into<SharedString>,
369        series: Vec<StreamgraphSeries>,
370        data: Vec<StreamgraphDatum>,
371    ) -> Self {
372        Self {
373            id: id.into(),
374            label: label.into(),
375            series,
376            data,
377            unit: SharedString::from(""),
378            height: 256.0,
379            offset: StreamgraphOffset::Wiggle,
380            legend: true,
381            direct_labels: true,
382            empty_label: SharedString::from("No data for this range"),
383            format_value: None,
384            on_active_change: None,
385        }
386    }
387
388    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
389        self.unit = unit.into();
390        self
391    }
392
393    pub fn height(mut self, height: f32) -> Self {
394        self.height = height.max(120.0);
395        self
396    }
397
398    pub fn offset(mut self, offset: StreamgraphOffset) -> Self {
399        self.offset = offset;
400        self
401    }
402
403    pub fn legend(mut self, show: bool) -> Self {
404        self.legend = show;
405        self
406    }
407
408    pub fn direct_labels(mut self, show: bool) -> Self {
409        self.direct_labels = show;
410        self
411    }
412
413    pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
414        self.empty_label = label.into();
415        self
416    }
417
418    pub fn format_value(
419        mut self,
420        f: impl Fn(f64, &StreamgraphSeries) -> SharedString + 'static,
421    ) -> Self {
422        self.format_value = Some(Rc::new(f));
423        self
424    }
425
426    pub fn on_active_change(
427        mut self,
428        f: impl Fn(Option<usize>, Option<SharedString>, &mut Window, &mut App) + 'static,
429    ) -> Self {
430        self.on_active_change = Some(Rc::new(f));
431        self
432    }
433
434    fn format_datum_value(&self, v: f64, s: &StreamgraphSeries) -> String {
435        let base = if let Some(ref f) = self.format_value {
436            f(v, s).to_string()
437        } else {
438            format_grouped(v, 1)
439        };
440        if self.unit.is_empty() {
441            base
442        } else {
443            format!("{base} {}", self.unit)
444        }
445    }
446}
447
448impl RenderOnce for Streamgraph {
449    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
450        let colors = cx.arc_theme().colors;
451        let reduced = is_reduced_motion(cx);
452        let now = motion_now(cx);
453
454        let state = window.use_keyed_state(
455            ElementId::NamedChild(self.id.clone().into(), "state".into()),
456            cx,
457            |_, cx| StreamgraphState::new(cx),
458        );
459
460        let empty = self.data.is_empty();
461        let last = self.data.len().saturating_sub(1);
462
463        // Build deterministic signature for data changes
464        let mut sig = String::new();
465        for s in &self.series {
466            sig.push_str(s.key.as_ref());
467            sig.push(',');
468        }
469        sig.push('|');
470        for d in &self.data {
471            for s in &self.series {
472                let v = d.values.get(&s.key).copied().unwrap_or(0.0);
473                sig.push_str(&format!("{:.2},", v));
474            }
475            sig.push(';');
476        }
477
478        let mut animating = false;
479        let (
480            hidden_list,
481            hover_index,
482            active_key,
483            swell_val,
484            presence_vals,
485            cursor_x_val,
486            plot_w,
487            shapes_map,
488        ) = state.update(cx, |st, _| {
489            let dt = st
490                .last_frame_secs
491                .map(|prev| (now - prev).clamp(0.0, 0.05) as f32)
492                .unwrap_or(0.016);
493            st.last_frame_secs = Some(now);
494
495            if st.last_signature != sig {
496                st.last_signature = sig.clone();
497                st.hover_index = None;
498                st.hover_key = None;
499                let mut next_shapes = HashMap::new();
500                for s in &self.series {
501                    let raw: Vec<f64> = self
502                        .data
503                        .iter()
504                        .map(|d| d.values.get(&s.key).copied().unwrap_or(0.0))
505                        .collect();
506                    next_shapes.insert(s.key.clone(), streamgraph_resample(&raw));
507                }
508                st.cached_shapes = next_shapes;
509            }
510
511            // Swell entrance
512            if empty || reduced {
513                st.swell.snap(1.0);
514            } else if !st.swell.is_settled_at(1.0, 0.002) {
515                st.swell.step_to(1.0, 0.82, 0.0, dt);
516                animating = true;
517            }
518
519            // Presence springs for series hide/show
520            let mut pres = HashMap::new();
521            for s in &self.series {
522                let target = if st.hidden.contains(&s.key) { 0.0 } else { 1.0 };
523                let sp = st
524                    .presence
525                    .entry(s.key.clone())
526                    .or_insert_with(|| ChartSpring::new(target));
527                if reduced {
528                    sp.snap(target);
529                } else if !sp.is_settled_at(target, 0.002) {
530                    sp.step_to(target, 0.36, 0.0, dt);
531                    animating = true;
532                }
533                pres.insert(s.key.clone(), sp.value.clamp(0.0, 1.0));
534            }
535
536            let w = st
537                .plot_bounds
538                .map(|b| f32::from(b.size.width))
539                .unwrap_or(520.0)
540                .max(120.0);
541
542            let idx = st.hover_index.filter(|_| !empty).map(|i| i.min(last));
543            if let Some(i) = idx {
544                let target_x = if last > 0 {
545                    (i as f32 / last as f32) * w
546                } else {
547                    w * 0.5
548                };
549                if reduced {
550                    st.cursor_x.snap(target_x);
551                } else if !st.cursor_x.is_settled_at(target_x, 0.25) {
552                    st.cursor_x.step_to(target_x, 0.22, 0.0, dt);
553                    animating = true;
554                }
555            }
556
557            let wanted = st.hover_key.clone().or_else(|| st.legend_hover.clone());
558            let active_k = wanted
559                .filter(|k| self.series.iter().any(|s| &s.key == k) && !st.hidden.contains(k));
560
561            (
562                st.hidden.clone(),
563                idx,
564                active_k,
565                st.swell.value.clamp(0.0, 1.0),
566                pres,
567                st.cursor_x.value,
568                w,
569                st.cached_shapes.clone(),
570            )
571        });
572
573        if animating {
574            window.request_animation_frame();
575        }
576
577        let computed = compute_stream(&self.series, &shapes_map, &presence_vals, self.offset);
578        let visible_series: Vec<&StreamgraphSeries> = self
579            .series
580            .iter()
581            .filter(|s| !hidden_list.contains(&s.key))
582            .collect();
583        let series_colors: Vec<Hsla> = self
584            .series
585            .iter()
586            .enumerate()
587            .map(|(i, s)| s.color.unwrap_or_else(|| chart_series_color(&colors, i)))
588            .collect();
589
590        // Direct interior label anchors (thickest stretch with 80% hysteresis)
591        let mut label_placements: Vec<(SharedString, f32, f32, bool, Hsla)> = Vec::new();
592        if self.direct_labels && !empty {
593            state.update(cx, |st, _| {
594                let span = (computed.hi - computed.lo).max(1e-9);
595                for (i, s) in self.series.iter().enumerate() {
596                    if hidden_list.contains(&s.key) {
597                        continue;
598                    }
599                    let top = &computed.upper[i];
600                    let bottom = &computed.lower[i];
601                    let mut best = 4usize.min(SAMPLES - 1);
602                    for j in 4..SAMPLES.saturating_sub(4) {
603                        if (top[j] - bottom[j]) > (top[best] - bottom[best]) {
604                            best = j;
605                        }
606                    }
607                    let best_thick = top[best] - bottom[best];
608                    let j = match st.label_spots.get(&s.key).copied() {
609                        Some(held)
610                            if held < SAMPLES && (top[held] - bottom[held]) >= best_thick * 0.8 =>
611                        {
612                            held
613                        }
614                        _ => best,
615                    };
616                    st.label_spots.insert(s.key.clone(), j);
617                    let px_thick = ((top[j] - bottom[j]) / span) as f32
618                        * (self.height - PLOT_PAD * 2.0)
619                        * swell_val;
620                    let est_w = (s.label.len() as f32 * 6.8).max(36.0);
621                    let min_x = (est_w * 0.5 + 8.0).min(plot_w * 0.5);
622                    let max_x = (plot_w - est_w * 0.5 - 8.0).max(min_x);
623                    let x = ((j as f32 / (SAMPLES - 1) as f32) * plot_w).clamp(min_x, max_x);
624                    let y = computed.to_y((top[j] + bottom[j]) * 0.5, self.height, swell_val, j);
625                    let fits = px_thick >= 20.0 && est_w + 16.0 < plot_w;
626                    label_placements.push((s.label.clone(), x, y, fits, series_colors[i]));
627                }
628            });
629        }
630
631        // Legend row
632        let legend_row = (self.legend && self.series.len() > 1).then(|| {
633            let mut row = div().flex().flex_wrap().items_center().gap(Spacing::S2);
634            for (i, s) in self.series.iter().enumerate() {
635                let is_hidden = hidden_list.contains(&s.key);
636                let is_active = active_key.as_ref() == Some(&s.key);
637                let is_dim = active_key.is_some() && !is_active;
638                let col = series_colors[i];
639                let key_click = s.key.clone();
640                let key_hover = s.key.clone();
641                let state_click = state.clone();
642                let state_hover = state.clone();
643
644                row = row.child(
645                    div()
646                        .id(ElementId::NamedChild(
647                            self.id.clone().into(),
648                            format!("legend-{}", s.key).into(),
649                        ))
650                        .flex()
651                        .items_center()
652                        .gap(px(6.0))
653                        .px(Spacing::S2)
654                        .py(px(3.0))
655                        .rounded(Radii::PILL)
656                        .border_1()
657                        .border_color(if is_active { col } else { colors.border_subtle })
658                        .bg(if is_active {
659                            oklab_mix(col, colors.surface, 0.14)
660                        } else {
661                            colors.surface
662                        })
663                        .opacity(if is_hidden {
664                            0.42
665                        } else if is_dim {
666                            0.55
667                        } else {
668                            1.0
669                        })
670                        .cursor_pointer()
671                        .on_hover(move |hovered, window, cx| {
672                            state_hover.update(cx, |st, _| {
673                                if *hovered {
674                                    st.legend_hover = Some(key_hover.clone());
675                                } else if st.legend_hover.as_ref() == Some(&key_hover) {
676                                    st.legend_hover = None;
677                                }
678                            });
679                            window.refresh();
680                        })
681                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
682                            state_click.update(cx, |st, _| {
683                                if let Some(pos) = st.hidden.iter().position(|k| k == &key_click) {
684                                    st.hidden.remove(pos);
685                                } else {
686                                    st.hidden.push(key_click.clone());
687                                }
688                            });
689                            window.refresh();
690                        })
691                        .child(div().size(px(8.0)).rounded(Radii::PILL).bg(col))
692                        .child(
693                            div()
694                                .text_size(Typography::TEXT_XS)
695                                .text_color(colors.foreground)
696                                .child(s.label.clone()),
697                        ),
698                );
699            }
700            row
701        });
702
703        // Paint ribbon paths + crosshair in canvas
704        let paint_computed = computed.clone();
705        let paint_colors = series_colors.clone();
706        let paint_series_keys: Vec<SharedString> =
707            self.series.iter().map(|s| s.key.clone()).collect();
708        let paint_active_key = active_key.clone();
709        let paint_hover_idx = hover_index;
710        let paint_height = self.height;
711        let paint_swell = swell_val;
712        let paint_cursor_x = cursor_x_val;
713        let crosshair_color = oklab_mix(colors.foreground, colors.surface, 0.35);
714        let state_bounds = state.clone();
715
716        let plot_canvas = canvas(
717            move |bounds, _, cx| {
718                state_bounds.update(cx, |st, _| {
719                    st.plot_bounds = Some(bounds);
720                });
721                bounds
722            },
723            move |bounds, _, window, _cx| {
724                let w = f32::from(bounds.size.width).max(1.0);
725                let h = f32::from(bounds.size.height).max(1.0);
726                let ox = f32::from(bounds.origin.x);
727                let oy = f32::from(bounds.origin.y);
728
729                for (i, key) in paint_series_keys.iter().enumerate() {
730                    let top_vals = &paint_computed.upper[i];
731                    let bot_vals = &paint_computed.lower[i];
732                    let mut upper_pts = Vec::with_capacity(SAMPLES);
733                    let mut lower_pts = Vec::with_capacity(SAMPLES);
734                    for j in 0..SAMPLES {
735                        let x = ox + (j as f32 / (SAMPLES - 1) as f32) * w;
736                        let yt = oy + paint_computed.to_y(top_vals[j], h, paint_swell, j);
737                        let yb = oy + paint_computed.to_y(bot_vals[j], h, paint_swell, j);
738                        upper_pts.push(point(px(x), px(yt)));
739                        lower_pts.push(point(px(x), px(yb)));
740                    }
741                    if let Some(path) = build_band_fill(&upper_pts, &lower_pts) {
742                        let base_col = paint_colors[i];
743                        let is_active = paint_active_key.as_ref() == Some(key);
744                        let is_dim = paint_active_key.is_some() && !is_active;
745                        let fill = if is_dim {
746                            Hsla {
747                                a: base_col.a * 0.28,
748                                ..base_col
749                            }
750                        } else if is_active {
751                            Hsla {
752                                a: (base_col.a * 0.96).min(1.0),
753                                ..base_col
754                            }
755                        } else {
756                            Hsla {
757                                a: base_col.a * 0.84,
758                                ..base_col
759                            }
760                        };
761                        window.paint_path(path, fill);
762                    }
763                }
764
765                if paint_hover_idx.is_some() {
766                    let cx_px = ox + paint_cursor_x.clamp(0.0, w);
767                    if let Some(line) = build_polyline_stroke(
768                        &[
769                            point(px(cx_px), px(oy)),
770                            point(px(cx_px), px(oy + paint_height)),
771                        ],
772                        1.0,
773                    ) {
774                        window.paint_path(line, crosshair_color);
775                    }
776                }
777            },
778        )
779        .size_full();
780
781        // Pointer & keyboard interaction
782        let state_move = state.clone();
783        let state_down = state.clone();
784        let state_hover = state.clone();
785        let state_key = state.clone();
786        let move_computed = computed.clone();
787        let move_series_keys: Vec<SharedString> =
788            self.series.iter().map(|s| s.key.clone()).collect();
789        let move_height = self.height;
790        let move_swell = swell_val;
791        let move_on_active = self.on_active_change.clone();
792        let down_computed = computed.clone();
793        let down_series_keys = move_series_keys.clone();
794        let down_on_active = self.on_active_change.clone();
795        let key_series_keys: Vec<SharedString> =
796            self.series.iter().map(|s| s.key.clone()).collect();
797        let key_on_active = self.on_active_change.clone();
798        let data_len = self.data.len();
799
800        let hit_test = move |pos_x: f32,
801                             pos_y: f32,
802                             bounds: Bounds<Pixels>,
803                             comp: &ComputedStream,
804                             keys: &[SharedString],
805                             hidden: &[SharedString],
806                             h: f32,
807                             swell: f32|
808              -> (usize, Option<SharedString>, f32) {
809            let w = f32::from(bounds.size.width).max(1.0);
810            let local_x = (pos_x - f32::from(bounds.origin.x)).clamp(0.0, w);
811            let local_y = (pos_y - f32::from(bounds.origin.y)).clamp(0.0, h);
812            let share = (local_x / w).clamp(0.0, 1.0);
813            let idx = if last > 0 {
814                (share * last as f32).round() as usize
815            } else {
816                0
817            }
818            .min(last);
819            let j = ((share * (SAMPLES - 1) as f32).round() as usize).min(SAMPLES - 1);
820            let mut hit_key = None;
821            for (i, k) in keys.iter().enumerate() {
822                if hidden.contains(k) {
823                    continue;
824                }
825                let yt = comp.to_y(comp.upper[i][j], h, swell, j);
826                let yb = comp.to_y(comp.lower[i][j], h, swell, j);
827                if local_y >= yt - 1.5 && local_y <= yb + 1.5 {
828                    hit_key = Some(k.clone());
829                }
830            }
831            (idx, hit_key, local_y)
832        };
833
834        let focus_handle = state.read(cx).focus_handle.clone();
835
836        // Floating tooltip
837        let tooltip_el = hover_index.and_then(|idx| self.data.get(idx)).map(|datum| {
838            let tip_w = 176.0f32;
839            let row_count = visible_series.len().max(1);
840            let tip_h = 34.0 + row_count as f32 * 20.0;
841            let x_anchor = if last > 0 {
842                (hover_index.unwrap_or(0) as f32 / last as f32) * plot_w
843            } else {
844                plot_w * 0.5
845            };
846            let left = if x_anchor + TIP_GAP + tip_w <= plot_w {
847                x_anchor + TIP_GAP
848            } else {
849                (x_anchor - TIP_GAP - tip_w).max(4.0)
850            };
851            let hover_y = state.read(cx).hover_y.unwrap_or(self.height * 0.5);
852            let top = (hover_y - tip_h * 0.5).clamp(4.0, (self.height - tip_h - 4.0).max(4.0));
853
854            let stack_rev: Vec<usize> = streamgraph_stack_order(self.series.len(), self.offset)
855                .into_iter()
856                .rev()
857                .collect();
858
859            let mut box_el = div()
860                .absolute()
861                .left(px(left))
862                .top(px(top))
863                .w(px(tip_w))
864                .p(Spacing::S2)
865                .rounded(Radii::CONTROL)
866                .bg(colors.surface_raised)
867                .border_1()
868                .border_color(colors.border)
869                .flex()
870                .flex_col()
871                .gap(px(4.0))
872                .child(
873                    div()
874                        .text_size(Typography::TEXT_XS)
875                        .font_semibold()
876                        .text_color(colors.foreground)
877                        .child(datum.label.clone()),
878                );
879
880            for i in stack_rev {
881                let s = &self.series[i];
882                if hidden_list.contains(&s.key) {
883                    continue;
884                }
885                let val = datum.values.get(&s.key).copied().unwrap_or(0.0);
886                let is_active = active_key.as_ref() == Some(&s.key);
887                let is_dim = active_key.is_some() && !is_active;
888                box_el = box_el.child(
889                    div()
890                        .flex()
891                        .items_center()
892                        .justify_between()
893                        .gap(Spacing::S2)
894                        .opacity(if is_dim { 0.45 } else { 1.0 })
895                        .child(
896                            div()
897                                .flex()
898                                .items_center()
899                                .gap(px(6.0))
900                                .child(
901                                    div()
902                                        .size(px(7.0))
903                                        .rounded(Radii::PILL)
904                                        .bg(series_colors[i]),
905                                )
906                                .child(
907                                    div()
908                                        .text_size(Typography::TEXT_XS)
909                                        .text_color(colors.text_secondary)
910                                        .child(s.label.clone()),
911                                ),
912                        )
913                        .child(
914                            div()
915                                .text_size(Typography::TEXT_XS)
916                                .font_medium()
917                                .text_color(colors.foreground)
918                                .child(self.format_datum_value(val, s)),
919                        ),
920                );
921            }
922            box_el
923        });
924
925        let mut plot_box = div()
926            .id(ElementId::NamedChild(self.id.clone().into(), "plot".into()))
927            .role(Role::Group)
928            .track_focus(&focus_handle)
929            .relative()
930            .w_full()
931            .h(px(self.height))
932            .overflow_hidden()
933            .cursor_crosshair()
934            .on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
935                if empty {
936                    return;
937                }
938                let mut changed = None;
939                state_move.update(cx, |st, _| {
940                    if let Some(bounds) = st.plot_bounds {
941                        let (idx, key, ly) = hit_test(
942                            f32::from(event.position.x),
943                            f32::from(event.position.y),
944                            bounds,
945                            &move_computed,
946                            &move_series_keys,
947                            &st.hidden,
948                            move_height,
949                            move_swell,
950                        );
951                        if st.hover_index != Some(idx) || st.hover_key != key {
952                            changed = Some((Some(idx), key.clone()));
953                        }
954                        st.hover_index = Some(idx);
955                        st.hover_key = key;
956                        st.hover_y = Some(ly);
957                    }
958                });
959                if let (Some(cb), Some((idx, key))) = (&move_on_active, changed) {
960                    cb(idx, key, window, cx);
961                }
962                window.refresh();
963            })
964            .on_mouse_down(
965                MouseButton::Left,
966                move |event: &MouseDownEvent, window, cx| {
967                    if empty {
968                        return;
969                    }
970                    let mut changed = None;
971                    let fh = state_down.read(cx).focus_handle.clone();
972                    window.focus(&fh, cx);
973                    state_down.update(cx, |st, _| {
974                        if let Some(bounds) = st.plot_bounds {
975                            let (idx, key, ly) = hit_test(
976                                f32::from(event.position.x),
977                                f32::from(event.position.y),
978                                bounds,
979                                &down_computed,
980                                &down_series_keys,
981                                &st.hidden,
982                                move_height,
983                                move_swell,
984                            );
985                            st.hover_index = Some(idx);
986                            st.hover_key = key.clone();
987                            st.hover_y = Some(ly);
988                            changed = Some((Some(idx), key));
989                        }
990                    });
991                    if let (Some(cb), Some((idx, key))) = (&down_on_active, changed) {
992                        cb(idx, key, window, cx);
993                    }
994                    window.refresh();
995                },
996            )
997            .on_hover(move |hovered, window, cx| {
998                if !*hovered {
999                    state_hover.update(cx, |st, _| {
1000                        st.hover_index = None;
1001                        st.hover_key = None;
1002                        st.hover_y = None;
1003                    });
1004                    window.refresh();
1005                }
1006            })
1007            .on_key_down(move |event: &KeyDownEvent, window, cx| {
1008                if empty || data_len == 0 {
1009                    return;
1010                }
1011                let key = event.keystroke.key.as_str();
1012                let mut result: Option<(Option<usize>, Option<SharedString>)> = None;
1013                state_key.update(cx, |st, _| {
1014                    let visible_keys: Vec<SharedString> = key_series_keys
1015                        .iter()
1016                        .filter(|k| !st.hidden.contains(k))
1017                        .cloned()
1018                        .collect();
1019                    let from = st.hover_index.unwrap_or(last);
1020                    let page = (data_len / 6).max(1);
1021                    let cur_k = st.hover_key.clone();
1022                    let pos_k = cur_k
1023                        .as_ref()
1024                        .and_then(|k| visible_keys.iter().position(|vk| vk == k));
1025
1026                    match key {
1027                        "escape" => {
1028                            st.hover_index = None;
1029                            st.hover_key = None;
1030                            result = Some((None, None));
1031                        }
1032                        "left" => {
1033                            let next = from.saturating_sub(1);
1034                            st.hover_index = Some(next);
1035                            result = Some((Some(next), cur_k));
1036                        }
1037                        "right" => {
1038                            let next = if st.hover_index.is_none() {
1039                                last
1040                            } else {
1041                                (from + 1).min(last)
1042                            };
1043                            st.hover_index = Some(next);
1044                            result = Some((Some(next), cur_k));
1045                        }
1046                        "pageup" => {
1047                            let next = (from + page).min(last);
1048                            st.hover_index = Some(next);
1049                            result = Some((Some(next), cur_k));
1050                        }
1051                        "pagedown" => {
1052                            let next = from.saturating_sub(page);
1053                            st.hover_index = Some(next);
1054                            result = Some((Some(next), cur_k));
1055                        }
1056                        "home" => {
1057                            st.hover_index = Some(0);
1058                            result = Some((Some(0), cur_k));
1059                        }
1060                        "end" => {
1061                            st.hover_index = Some(last);
1062                            result = Some((Some(last), cur_k));
1063                        }
1064                        "up" if !visible_keys.is_empty() => {
1065                            let next_k = match pos_k {
1066                                None => visible_keys.last().cloned(),
1067                                Some(p) => visible_keys
1068                                    .get((p + 1).min(visible_keys.len() - 1))
1069                                    .cloned(),
1070                            };
1071                            st.hover_index = Some(from);
1072                            st.hover_key = next_k.clone();
1073                            result = Some((Some(from), next_k));
1074                        }
1075                        "down" if !visible_keys.is_empty() => {
1076                            let next_k = match pos_k {
1077                                None => visible_keys.first().cloned(),
1078                                Some(p) => visible_keys.get(p.saturating_sub(1)).cloned(),
1079                            };
1080                            st.hover_index = Some(from);
1081                            st.hover_key = next_k.clone();
1082                            result = Some((Some(from), next_k));
1083                        }
1084                        _ => {}
1085                    }
1086                });
1087                if let Some((idx, k)) = result {
1088                    if let Some(ref cb) = key_on_active {
1089                        cb(idx, k, window, cx);
1090                    }
1091                    cx.stop_propagation();
1092                    window.refresh();
1093                }
1094            })
1095            .child(plot_canvas);
1096
1097        // Overlay direct labels inside ribbons
1098        for (lbl, lx, ly, fits, _col) in label_placements {
1099            if !fits {
1100                continue;
1101            }
1102            plot_box = plot_box.child(
1103                div()
1104                    .absolute()
1105                    .left(px((lx - 42.0).max(4.0)))
1106                    .top(px((ly - 8.0).max(2.0)))
1107                    .w(px(84.0))
1108                    .flex()
1109                    .justify_center()
1110                    .text_size(Typography::TEXT_XS)
1111                    .font_medium()
1112                    .text_color(colors.background)
1113                    .child(lbl),
1114            );
1115        }
1116
1117        if let Some(tip) = tooltip_el {
1118            plot_box = plot_box.child(tip);
1119        }
1120
1121        if empty || visible_series.is_empty() {
1122            plot_box = plot_box.child(
1123                div()
1124                    .absolute()
1125                    .inset_0()
1126                    .flex()
1127                    .items_center()
1128                    .justify_center()
1129                    .text_size(Typography::TEXT_SM)
1130                    .text_color(colors.text_muted)
1131                    .child(if empty {
1132                        self.empty_label.clone()
1133                    } else {
1134                        SharedString::from("Choose a layer to show")
1135                    }),
1136            );
1137        }
1138
1139        // X axis ticks
1140        let picks = streamgraph_axis_picks(&self.data, plot_w);
1141        let axis_row =
1142            div()
1143                .relative()
1144                .w_full()
1145                .h(px(20.0))
1146                .children(picks.into_iter().filter_map(|idx| {
1147                    let d = self.data.get(idx)?;
1148                    let text = d.axis_label.clone()?;
1149                    let share = if last > 0 {
1150                        idx as f32 / last as f32
1151                    } else {
1152                        0.5
1153                    };
1154                    let left = (share * plot_w - 28.0).clamp(0.0, (plot_w - 56.0).max(0.0));
1155                    Some(
1156                        div()
1157                            .absolute()
1158                            .left(px(left))
1159                            .top(px(2.0))
1160                            .w(px(56.0))
1161                            .flex()
1162                            .justify_center()
1163                            .text_size(Typography::TEXT_XS)
1164                            .text_color(colors.text_muted)
1165                            .child(text),
1166                    )
1167                }));
1168
1169        div()
1170            .id(self.id)
1171            .w_full()
1172            .flex()
1173            .flex_col()
1174            .gap(Spacing::S3)
1175            .p(Spacing::S4)
1176            .rounded(Radii::PANEL)
1177            .bg(colors.surface)
1178            .border_1()
1179            .border_color(colors.border_subtle)
1180            .child(
1181                div()
1182                    .flex()
1183                    .flex_wrap()
1184                    .items_center()
1185                    .justify_between()
1186                    .gap(Spacing::S2)
1187                    .child(
1188                        div()
1189                            .text_size(Typography::TEXT_SM)
1190                            .font_semibold()
1191                            .text_color(colors.foreground)
1192                            .child(self.label),
1193                    )
1194                    .children(legend_row),
1195            )
1196            .child(plot_box)
1197            .child(axis_row)
1198    }
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203    use super::*;
1204
1205    #[test]
1206    fn streamgraph_stack_order_resample_and_baselines() {
1207        assert_eq!(
1208            streamgraph_stack_order(5, StreamgraphOffset::Zero),
1209            vec![0, 1, 2, 3, 4]
1210        );
1211        assert_eq!(
1212            streamgraph_stack_order(5, StreamgraphOffset::Wiggle),
1213            vec![4, 2, 0, 1, 3]
1214        );
1215
1216        let resampled = streamgraph_resample(&[10.0, 40.0, 20.0, 60.0]);
1217        assert_eq!(resampled.len(), SAMPLES);
1218        assert!((resampled[0] - 10.0).abs() < 1e-6);
1219        assert!((resampled[SAMPLES - 1] - 60.0).abs() < 1e-6);
1220        assert!(
1221            resampled
1222                .iter()
1223                .all(|&v| (10.0 - 1e-6..=60.0 + 1e-6).contains(&v))
1224        );
1225
1226        let l1 = streamgraph_resample(&[10.0, 20.0, 30.0]);
1227        let l2 = streamgraph_resample(&[5.0, 15.0, 10.0]);
1228        let sil = streamgraph_baseline(&[l1.clone(), l2.clone()], StreamgraphOffset::Silhouette);
1229        assert!((sil[0] + 7.5).abs() < 1e-6);
1230        let wig = streamgraph_baseline(&[l1, l2], StreamgraphOffset::Wiggle);
1231        assert_eq!(wig.len(), SAMPLES);
1232        assert!(wig.iter().all(|v| v.is_finite()));
1233    }
1234}