Skip to main content

gpui_component/chart/
sankey_chart.rs

1use std::rc::Rc;
2
3use gpui::ColorExt as _;
4use gpui::{
5    App, Bounds, Corners, Hsla, Pixels, SharedString, TextAlign, Window, fill, linear_color_stop,
6    linear_gradient, point, px,
7};
8use gpui_component_macros::IntoPlot;
9
10use crate::{
11    ActiveTheme,
12    plot::{
13        Plot,
14        label::{PlotLabel, TEXT_GAP, TEXT_SIZE, Text, measure_text_width, truncate_text_to_width},
15        origin_point,
16        shape::{Sankey, SankeyAlign, SankeyLink, SankeyValueScale, sankey_link_path},
17    },
18};
19
20const DEFAULT_NODE_WIDTH: f32 = 10.;
21const DEFAULT_NODE_PADDING: f32 = 16.;
22const DEFAULT_LINK_OPACITY: f32 = 0.3;
23const DEFAULT_MIN_LINK_WIDTH: f32 = 1.;
24const DEFAULT_LABEL_GAP: f32 = 6.;
25/// Cap each side's label margin (as a fraction of width) so a long label is
26/// truncated to a modest column beside the flow instead of dominating it.
27const MAX_LABEL_WIDTH_RATIO: f32 = 0.2;
28/// Cap the reserved top+bottom label band as a fraction of height.
29const MAX_LABEL_MARGIN_RATIO: f32 = 0.6;
30
31/// A styled line of a sankey node label.
32#[derive(Clone)]
33pub struct SankeyLabel {
34    text: SharedString,
35    color: Option<Hsla>,
36    font_size: Option<f32>,
37}
38
39impl SankeyLabel {
40    /// Create a label line with the default color and font size.
41    pub fn new(text: impl Into<SharedString>) -> Self {
42        Self {
43            text: text.into(),
44            color: None,
45            font_size: None,
46        }
47    }
48
49    /// Set the text color. Defaults to the theme foreground.
50    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
51        self.color = Some(color.into());
52        self
53    }
54
55    /// Set the font size. Defaults to 10.
56    pub fn font_size(mut self, font_size: f32) -> Self {
57        self.font_size = Some(font_size);
58        self
59    }
60
61    fn line_height(&self) -> f32 {
62        self.font_size.unwrap_or(TEXT_SIZE) + TEXT_GAP
63    }
64}
65
66fn block_height(lines: &[SankeyLabel]) -> f32 {
67    lines.iter().map(|line| line.line_height()).sum()
68}
69
70/// A Sankey diagram, layout modeled after [d3-sankey](https://github.com/d3/d3-sankey).
71///
72/// Links reference nodes by their index in the node list; map string ids to
73/// indices before constructing.
74#[derive(IntoPlot)]
75pub struct SankeyChart<T: 'static> {
76    nodes: Vec<T>,
77    links: Vec<SankeyLink>,
78    node_width: f32,
79    node_padding: f32,
80    align: SankeyAlign,
81    iterations: usize,
82    value_scale: SankeyValueScale,
83    node_corner_radius: Option<Pixels>,
84    node_color: Option<Rc<dyn Fn(&T) -> Hsla>>,
85    node_label: Option<Rc<dyn Fn(&T) -> SharedString>>,
86    value_label: Option<Rc<dyn Fn(&T, f64) -> SharedString>>,
87    labels: Option<Rc<dyn Fn(&T, f64) -> Vec<SankeyLabel>>>,
88    link_opacity: f32,
89    min_link_width: f32,
90    label_gap: f32,
91}
92
93impl<T> SankeyChart<T> {
94    /// Create a chart from nodes and links; links reference nodes by their
95    /// index in `nodes` (map string ids to indices before constructing).
96    pub fn new<I, L>(nodes: I, links: L) -> Self
97    where
98        I: IntoIterator<Item = T>,
99        L: IntoIterator<Item = SankeyLink>,
100    {
101        Self {
102            nodes: nodes.into_iter().collect(),
103            links: links.into_iter().collect(),
104            node_width: DEFAULT_NODE_WIDTH,
105            node_padding: DEFAULT_NODE_PADDING,
106            align: SankeyAlign::default(),
107            iterations: 6,
108            value_scale: SankeyValueScale::default(),
109            node_corner_radius: None,
110            node_color: None,
111            node_label: None,
112            value_label: None,
113            labels: None,
114            link_opacity: DEFAULT_LINK_OPACITY,
115            min_link_width: DEFAULT_MIN_LINK_WIDTH,
116            label_gap: DEFAULT_LABEL_GAP,
117        }
118    }
119
120    /// Set the node rectangle width. Defaults to 10.
121    pub fn node_width(mut self, node_width: f32) -> Self {
122        self.node_width = node_width;
123        self
124    }
125
126    /// Set the vertical gap between nodes in a column. Defaults to 16.
127    pub fn node_padding(mut self, node_padding: f32) -> Self {
128        self.node_padding = node_padding;
129        self
130    }
131
132    /// Set the node alignment. Defaults to [`SankeyAlign::Justify`].
133    pub fn node_align(mut self, align: SankeyAlign) -> Self {
134        self.align = align;
135        self
136    }
137
138    /// Set the number of relaxation passes. Defaults to 6.
139    pub fn iterations(mut self, iterations: usize) -> Self {
140        self.iterations = iterations;
141        self
142    }
143
144    /// Set how flow values map to node heights.
145    ///
146    /// Defaults to [`SankeyValueScale::Linear`]. Use [`SankeyValueScale::Sqrt`]
147    /// to keep a dominant flow from dwarfing the small ones without
148    /// pre-transforming the data; labels still receive the raw values.
149    pub fn value_scale(mut self, value_scale: SankeyValueScale) -> Self {
150        self.value_scale = value_scale;
151        self
152    }
153
154    /// Set the corner radius of the node rectangles. Defaults to 0.
155    pub fn node_corner_radius(mut self, radius: impl Into<Pixels>) -> Self {
156        self.node_corner_radius = Some(radius.into());
157        self
158    }
159
160    /// Set the color of each node.
161    ///
162    /// Defaults to cycling the theme chart palette by node index.
163    pub fn node_color<H>(mut self, color: impl Fn(&T) -> H + 'static) -> Self
164    where
165        H: Into<Hsla> + 'static,
166    {
167        self.node_color = Some(Rc::new(move |t| color(t).into()));
168        self
169    }
170
171    /// Set the name label of each node, drawn in muted foreground. No name
172    /// label is drawn unless set.
173    pub fn node_label(mut self, label: impl Fn(&T) -> SharedString + 'static) -> Self {
174        self.node_label = Some(Rc::new(label));
175        self
176    }
177
178    /// Set the value label of each node, drawn above the name label. No value
179    /// label is drawn unless set.
180    ///
181    /// The closure receives the datum and the node's raw computed throughput
182    /// (max of incoming and outgoing flow, in unscaled units).
183    pub fn value_label(mut self, label: impl Fn(&T, f64) -> SharedString + 'static) -> Self {
184        self.value_label = Some(Rc::new(label));
185        self
186    }
187
188    /// Set fully custom node labels, one [`SankeyLabel`] per line, top to
189    /// bottom. Takes precedence over `node_label`/`value_label` when set;
190    /// unset by default.
191    ///
192    /// The closure receives the datum and the node's raw computed throughput
193    /// (max of incoming and outgoing flow, in unscaled units).
194    pub fn labels(mut self, labels: impl Fn(&T, f64) -> Vec<SankeyLabel> + 'static) -> Self {
195        self.labels = Some(Rc::new(labels));
196        self
197    }
198
199    /// Set the opacity of the link ribbons. Defaults to 0.3.
200    pub fn link_opacity(mut self, opacity: f32) -> Self {
201        self.link_opacity = opacity;
202        self
203    }
204
205    /// Set the minimum ribbon thickness, so tiny flows stay visible. Defaults to 1.
206    pub fn min_link_width(mut self, width: f32) -> Self {
207        self.min_link_width = width;
208        self
209    }
210
211    /// Set the gap between a node and its labels. Defaults to 6.
212    pub fn label_gap(mut self, gap: f32) -> Self {
213        self.label_gap = gap;
214        self
215    }
216
217    fn sankey(&self) -> Sankey {
218        Sankey::new()
219            .node_width(self.node_width)
220            .node_padding(self.node_padding)
221            .node_align(self.align)
222            .iterations(self.iterations)
223            .value_scale(self.value_scale)
224    }
225
226    /// Raw per-node throughput (max of raw incoming and outgoing sums), for
227    /// labels — the layout's `node.value` is in scaled units under a
228    /// non-linear value scale, so labels must not use it.
229    fn raw_throughput(&self) -> Vec<f64> {
230        let mut incoming = vec![0f64; self.nodes.len()];
231        let mut outgoing = vec![0f64; self.nodes.len()];
232        for link in &self.links {
233            if let (Some(o), Some(i)) =
234                (outgoing.get_mut(link.source), incoming.get_mut(link.target))
235            {
236                *o += link.value;
237                *i += link.value;
238            }
239        }
240        incoming
241            .into_iter()
242            .zip(outgoing)
243            .map(|(i, o)| i.max(o))
244            .collect()
245    }
246}
247
248impl<T> Plot for SankeyChart<T> {
249    fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
250        let width = bounds.size.width.as_f32();
251        let height = bounds.size.height.as_f32();
252        if self.nodes.is_empty() || self.links.is_empty() || width <= 0. || height <= 0. {
253            return;
254        }
255
256        // First pass: only the topology (each node's `layer`) is needed to
257        // measure the label margins; label values come from `raw_throughput`.
258        let Ok(topology) = self.sankey().topology(self.nodes.len(), &self.links) else {
259            return;
260        };
261        let layer_count = topology.layer_count();
262        // Labels get the raw throughput, not the layout's (possibly scaled) value.
263        let raw_value = self.raw_throughput();
264
265        // Collect each node's label lines: the custom `labels` closure wins,
266        // otherwise synthesize the value/name lines with the default styles.
267        let node_labels: Vec<Vec<SankeyLabel>> = topology
268            .nodes
269            .iter()
270            .map(|node| {
271                let datum = &self.nodes[node.index];
272                let value = raw_value[node.index];
273                if let Some(labels) = &self.labels {
274                    labels(datum, value)
275                } else {
276                    let mut lines = Vec::new();
277                    if let Some(value_label) = &self.value_label {
278                        lines.push(SankeyLabel::new(value_label(datum, value)));
279                    }
280                    if let Some(node_label) = &self.node_label {
281                        lines.push(
282                            SankeyLabel::new(node_label(datum)).color(cx.theme().muted_foreground),
283                        );
284                    }
285                    lines
286                }
287            })
288            .collect();
289        let has_labels = node_labels.iter().any(|lines| !lines.is_empty());
290
291        // Reserve margins so the labels beside the first/last columns and
292        // above the middle columns are not clipped.
293        let mut left = 0f32;
294        let mut right = 0f32;
295        if has_labels {
296            for node in &topology.nodes {
297                if node.layer != 0 && node.layer + 1 != layer_count {
298                    continue;
299                }
300                let mut label_width = 0f32;
301                for line in &node_labels[node.index] {
302                    label_width = label_width.max(measure_text_width(
303                        &line.text,
304                        px(line.font_size.unwrap_or(TEXT_SIZE)),
305                        window,
306                    ));
307                }
308                if node.layer == 0 {
309                    left = left.max(label_width + self.label_gap);
310                } else {
311                    right = right.max(label_width + self.label_gap);
312                }
313            }
314
315            // Cap each side independently so one long label is truncated to a
316            // modest column rather than eating into the flow area.
317            let side_cap = width * MAX_LABEL_WIDTH_RATIO;
318            left = left.min(side_cap);
319            right = right.min(side_cap);
320        }
321        // Above-node labels are only emitted for middle columns, so reserve
322        // the top band for the tallest such label block. Cap the vertical
323        // margins like the horizontal ones so a short chart doesn't collapse
324        // the flow.
325        let mut top = 0f32;
326        if has_labels && layer_count > 2 {
327            for node in &topology.nodes {
328                if node.layer == 0 || node.layer + 1 == layer_count {
329                    continue;
330                }
331                let block = block_height(&node_labels[node.index]);
332                if block > 0. {
333                    top = top.max(block + TEXT_GAP);
334                }
335            }
336        }
337        let mut bottom = if has_labels { TEXT_GAP } else { 0. };
338        let max_vertical = height * MAX_LABEL_MARGIN_RATIO;
339        if top + bottom > max_vertical {
340            let k = max_vertical / (top + bottom);
341            top *= k;
342            bottom *= k;
343        }
344
345        // Second pass: complete the placement on the final extent, reusing
346        // the first pass's topology.
347        let graph = self
348            .sankey()
349            .extent(
350                left,
351                top,
352                (width - right).max(left + 1.),
353                (height - bottom).max(top + 1.),
354            )
355            .layout_from(topology);
356
357        let palette = [
358            cx.theme().chart_1,
359            cx.theme().chart_2,
360            cx.theme().chart_3,
361            cx.theme().chart_4,
362            cx.theme().chart_5,
363        ];
364        let colors: Vec<Hsla> = self
365            .nodes
366            .iter()
367            .enumerate()
368            .map(|(index, datum)| match &self.node_color {
369                Some(color) => color(datum),
370                None => palette[index % palette.len()],
371            })
372            .collect();
373
374        // Links first, under the nodes.
375        for link in &graph.links {
376            if link.value <= 0. {
377                continue;
378            }
379            let source = &graph.nodes[link.source];
380            let target = &graph.nodes[link.target];
381            let Some(path) =
382                sankey_link_path(source, target, link, self.min_link_width, bounds.origin)
383            else {
384                continue;
385            };
386            window.paint_path(
387                path,
388                linear_gradient(
389                    90.,
390                    linear_color_stop(colors[link.source].opacity(self.link_opacity), 0.),
391                    linear_color_stop(colors[link.target].opacity(self.link_opacity), 1.),
392                ),
393            );
394        }
395
396        let corner_radii = Corners::all(self.node_corner_radius.unwrap_or_default());
397        for node in &graph.nodes {
398            let node_bounds = Bounds::from_corners(
399                origin_point(px(node.x0), px(node.y0), bounds.origin),
400                // Keep tiny nodes visible with a minimum 1px height.
401                origin_point(px(node.x1), px(node.y1.max(node.y0 + 1.)), bounds.origin),
402            );
403            window.paint_quad(fill(node_bounds, colors[node.index]).corner_radii(corner_radii));
404        }
405
406        let mut texts = Vec::new();
407        for node in &graph.nodes {
408            let lines = &node_labels[node.index];
409            if lines.is_empty() {
410                continue;
411            }
412
413            let is_first = node.layer == 0;
414            let is_last = node.layer + 1 == layer_count;
415            // `x`/`align` place the label beside (first/last) or centered above
416            // (middle) the node, and `max_width` bounds it so a long label is
417            // truncated with an ellipsis instead of drawn outside the plot:
418            // first/last to their reserved margin, middle to twice the smaller
419            // gap to the plot edge (generous for interior nodes, only bites a
420            // label long enough to actually run off-plot).
421            let (x, align, max_width) = if is_first {
422                (
423                    node.x0 - self.label_gap,
424                    TextAlign::Right,
425                    left - self.label_gap,
426                )
427            } else if is_last {
428                (
429                    node.x1 + self.label_gap,
430                    TextAlign::Left,
431                    right - self.label_gap,
432                )
433            } else {
434                let center = (node.x0 + node.x1) / 2.;
435                let edge_budget = 2. * center.min(width - center);
436                (center, TextAlign::Center, edge_budget)
437            };
438
439            let block = block_height(lines);
440            let mut y = if is_first || is_last {
441                // Block vertically centered beside the node, clamped into
442                // the plot area so labels of nodes near the top or bottom
443                // edge are not clipped.
444                ((node.y0 + node.y1) / 2. - block / 2.)
445                    .min(height - block)
446                    .max(0.)
447            } else {
448                // Block above the node.
449                node.y0 - block - TEXT_GAP
450            };
451
452            for line in lines {
453                let font_size = px(line.font_size.unwrap_or(TEXT_SIZE));
454                let text = truncate_text_to_width(&line.text, font_size, max_width, window);
455                texts.push(
456                    Text::new(
457                        text,
458                        point(px(x), px(y)),
459                        line.color.unwrap_or(cx.theme().foreground),
460                    )
461                    .font_size(font_size)
462                    .align(align),
463                );
464                y += line.line_height();
465            }
466        }
467        PlotLabel::new(texts).paint(&bounds, window, cx);
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    #[test]
476    fn test_sankey_chart_builder() {
477        let chart = SankeyChart::new(vec!["a", "b"], vec![SankeyLink::new(0, 1, 5.)]);
478        assert_eq!(chart.nodes.len(), 2);
479        assert_eq!(chart.links.len(), 1);
480        assert_eq!(chart.node_width, DEFAULT_NODE_WIDTH);
481        assert_eq!(chart.node_padding, DEFAULT_NODE_PADDING);
482        assert_eq!(chart.align, SankeyAlign::Justify);
483        assert_eq!(chart.iterations, 6);
484        assert_eq!(chart.node_corner_radius, None);
485        assert_eq!(chart.link_opacity, DEFAULT_LINK_OPACITY);
486        assert_eq!(chart.min_link_width, DEFAULT_MIN_LINK_WIDTH);
487        assert_eq!(chart.label_gap, DEFAULT_LABEL_GAP);
488        assert!(chart.node_color.is_none());
489        assert!(chart.node_label.is_none());
490        assert!(chart.value_label.is_none());
491        assert!(chart.labels.is_none());
492
493        let chart = chart
494            .node_width(8.)
495            .node_padding(20.)
496            .node_align(SankeyAlign::Left)
497            .iterations(10)
498            .node_corner_radius(px(2.))
499            .node_color(|_| gpui::red())
500            .node_label(|d| SharedString::from(d.to_string()))
501            .value_label(|_, value| SharedString::from(format!("{}", value)))
502            .labels(|d, value| {
503                vec![
504                    SankeyLabel::new(format!("{}", value)),
505                    SankeyLabel::new(d.to_string()),
506                ]
507            })
508            .link_opacity(0.5)
509            .min_link_width(2.)
510            .label_gap(10.);
511        assert_eq!(chart.node_width, 8.);
512        assert_eq!(chart.node_padding, 20.);
513        assert_eq!(chart.align, SankeyAlign::Left);
514        assert_eq!(chart.iterations, 10);
515        assert_eq!(chart.node_corner_radius, Some(px(2.)));
516        assert_eq!(chart.link_opacity, 0.5);
517        assert_eq!(chart.min_link_width, 2.);
518        assert_eq!(chart.label_gap, 10.);
519        assert!(chart.node_color.is_some());
520        assert!(chart.node_label.is_some());
521        assert!(chart.value_label.is_some());
522        assert!(chart.labels.is_some());
523    }
524
525    #[test]
526    fn test_sankey_label_builder() {
527        let label = SankeyLabel::new("a");
528        assert_eq!(label.text, "a");
529        assert_eq!(label.color, None);
530        assert_eq!(label.font_size, None);
531        assert_eq!(label.line_height(), TEXT_SIZE + TEXT_GAP);
532
533        let label = SankeyLabel::new("b").color(gpui::red()).font_size(14.);
534        assert_eq!(label.color, Some(gpui::red()));
535        assert_eq!(label.font_size, Some(14.));
536        assert_eq!(label.line_height(), 14. + TEXT_GAP);
537
538        assert_eq!(
539            block_height(&[SankeyLabel::new("a"), SankeyLabel::new("b").font_size(14.)]),
540            TEXT_SIZE + TEXT_GAP + 14. + TEXT_GAP
541        );
542        assert_eq!(block_height(&[]), 0.);
543    }
544
545    #[test]
546    fn test_sankey_chart_raw_throughput() {
547        // A(out 30) -> B, B -> C(20) + D(10): B's throughput is max(in, out).
548        let chart = SankeyChart::new(
549            vec!["a", "b", "c", "d"],
550            vec![
551                SankeyLink::new(0, 1, 30.),
552                SankeyLink::new(1, 2, 20.),
553                SankeyLink::new(1, 3, 10.),
554            ],
555        );
556        let raw = chart.raw_throughput();
557        assert_eq!(raw, vec![30., 30., 20., 10.]);
558
559        // Under Sqrt the layout's node value is scaled, but raw_throughput
560        // (used for labels) must stay in raw units — the two must differ.
561        let sqrt = chart
562            .value_scale(SankeyValueScale::Sqrt)
563            .sankey()
564            .layout(4, &chart_links())
565            .unwrap();
566        // Node A: layout value is sqrt-scaled (30 -> sqrt(30)), raw is 30.
567        assert!((sqrt.nodes[0].value - 30f64.sqrt()).abs() < 1e-6);
568        assert!((raw[0] - 30.).abs() < 1e-6);
569        assert!(raw[0] != sqrt.nodes[0].value);
570    }
571
572    fn chart_links() -> Vec<SankeyLink> {
573        vec![
574            SankeyLink::new(0, 1, 30.),
575            SankeyLink::new(1, 2, 20.),
576            SankeyLink::new(1, 3, 10.),
577        ]
578    }
579}