Skip to main content

gpui_component/chart/
sankey_chart.rs

1use std::{
2    hash::{DefaultHasher, Hash, Hasher},
3    rc::Rc,
4};
5
6use gpui::ColorExt as _;
7use gpui::{
8    AnyElement, App, Bounds, Corners, ElementId, Hsla, IntoElement, Pixels, Point, SharedString,
9    TextAlign, Window, linear_color_stop, linear_gradient, point, prelude::FluentBuilder, px,
10};
11use gpui_component_macros::IntoPlot;
12
13use super::{ChartAppear, caller_id, reveal_mask};
14use crate::{
15    ActiveTheme,
16    plot::{
17        PathCaches, Plot, PlotAppear, ShapeKey,
18        label::{PlotLabel, TEXT_GAP, TEXT_SIZE, Text, measure_text_width, truncate_text_to_width},
19        origin_point,
20        shape::{
21            Sankey, SankeyAlign, SankeyGraph, SankeyLink, SankeyLinkLayout, SankeyValueScale,
22            sankey_link_path,
23        },
24        tooltip::{PlotHover, Tooltip, TooltipState},
25    },
26};
27
28const DEFAULT_NODE_WIDTH: f32 = 10.;
29const DEFAULT_NODE_PADDING: f32 = 16.;
30const DEFAULT_LINK_OPACITY: f32 = 0.3;
31const DEFAULT_MIN_LINK_WIDTH: f32 = 1.;
32const DEFAULT_LABEL_GAP: f32 = 6.;
33/// Cap each side's label margin (as a fraction of width) so a long label is
34/// truncated to a modest column beside the flow instead of dominating it.
35const MAX_LABEL_WIDTH_RATIO: f32 = 0.2;
36/// Cap the reserved top+bottom label band as a fraction of height.
37const MAX_LABEL_MARGIN_RATIO: f32 = 0.6;
38/// How much the links not attached to the hovered node fade, as a share of
39/// their opacity.
40const HOVER_DIM: f32 = 0.7;
41
42/// The placement of a sankey chart for one bounds size: the graph plus the
43/// label lines and margins it was laid out with.
44///
45/// Placing the graph relaxes the node order over several iterations, and the
46/// label margins need every label measured, so a chart keeps the frame in
47/// element state and reuses it while its key is unchanged.
48struct SankeyFrame {
49    graph: SankeyGraph,
50    layer_count: usize,
51    node_labels: Vec<Vec<SankeyLabel>>,
52    /// The label margins reserved on the left and right of the flow.
53    left: f32,
54    right: f32,
55}
56
57/// The frame of the last placement with the key it was placed for.
58#[derive(Default)]
59struct SankeyFrameCache {
60    key: Option<u64>,
61    frame: Option<Rc<SankeyFrame>>,
62}
63
64/// The hover a sankey chart paints, sampled once per frame in [`Plot::hover`].
65#[derive(Clone, Copy)]
66struct SankeyHover {
67    /// The hovered node.
68    node: usize,
69    /// How far the hover has faded in.
70    focus: f32,
71}
72
73/// A styled line of a sankey node label.
74#[derive(Clone)]
75pub struct SankeyLabel {
76    text: SharedString,
77    color: Option<Hsla>,
78    font_size: Option<f32>,
79}
80
81impl SankeyLabel {
82    /// Create a label line with the default color and font size.
83    pub fn new(text: impl Into<SharedString>) -> Self {
84        Self {
85            text: text.into(),
86            color: None,
87            font_size: None,
88        }
89    }
90
91    /// Set the text color. Defaults to the theme foreground.
92    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
93        self.color = Some(color.into());
94        self
95    }
96
97    /// Set the font size. Defaults to 10.
98    pub fn font_size(mut self, font_size: f32) -> Self {
99        self.font_size = Some(font_size);
100        self
101    }
102
103    fn line_height(&self) -> f32 {
104        self.font_size.unwrap_or(TEXT_SIZE) + TEXT_GAP
105    }
106}
107
108fn block_height(lines: &[SankeyLabel]) -> f32 {
109    lines.iter().map(|line| line.line_height()).sum()
110}
111
112/// A Sankey diagram, layout modeled after [d3-sankey](https://github.com/d3/d3-sankey).
113///
114/// Links reference nodes by their index in the node list; map string ids to
115/// indices before constructing.
116#[derive(IntoPlot)]
117pub struct SankeyChart<T: 'static> {
118    nodes: Vec<T>,
119    links: Vec<SankeyLink>,
120    node_width: f32,
121    node_padding: f32,
122    align: SankeyAlign,
123    iterations: usize,
124    value_scale: SankeyValueScale,
125    node_corner_radius: Option<Pixels>,
126    node_color: Option<Rc<dyn Fn(&T) -> Hsla>>,
127    node_label: Option<Rc<dyn Fn(&T) -> SharedString>>,
128    value_label: Option<Rc<dyn Fn(&T, f64) -> SharedString>>,
129    labels: Option<Rc<dyn Fn(&T, f64) -> Vec<SankeyLabel>>>,
130    link_opacity: f32,
131    min_link_width: f32,
132    label_gap: f32,
133    tooltip_name: Option<Rc<dyn Fn(&T) -> SharedString + 'static>>,
134    tooltip_value: Option<Rc<dyn Fn(&T, f64) -> SharedString + 'static>>,
135    id: ElementId,
136    interactive: bool,
137    appear: ChartAppear,
138    /// The placement for this frame, resolved in `prepaint` (measuring labels
139    /// needs the window) and read by `tooltip_state` and `paint`.
140    frame: Option<Rc<SankeyFrame>>,
141    hover: Option<SankeyHover>,
142}
143
144impl<T> SankeyChart<T> {
145    /// Create a chart from nodes and links; links reference nodes by their
146    /// index in `nodes` (map string ids to indices before constructing).
147    #[track_caller]
148    pub fn new<I, L>(nodes: I, links: L) -> Self
149    where
150        I: IntoIterator<Item = T>,
151        L: IntoIterator<Item = SankeyLink>,
152    {
153        Self {
154            nodes: nodes.into_iter().collect(),
155            links: links.into_iter().collect(),
156            node_width: DEFAULT_NODE_WIDTH,
157            node_padding: DEFAULT_NODE_PADDING,
158            align: SankeyAlign::default(),
159            iterations: 6,
160            value_scale: SankeyValueScale::default(),
161            node_corner_radius: None,
162            node_color: None,
163            node_label: None,
164            value_label: None,
165            labels: None,
166            link_opacity: DEFAULT_LINK_OPACITY,
167            min_link_width: DEFAULT_MIN_LINK_WIDTH,
168            label_gap: DEFAULT_LABEL_GAP,
169            tooltip_name: None,
170            tooltip_value: None,
171            id: caller_id(),
172            interactive: true,
173            appear: ChartAppear::default(),
174            frame: None,
175            hover: None,
176        }
177    }
178
179    /// Name this chart's [`ElementId`], replacing the default taken from the
180    /// construction site.
181    ///
182    /// Pass one where a single construction site renders several of these
183    /// charts as siblings: they share the default id, and with it one hover
184    /// state and one path cache. The id must be unique among those siblings.
185    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
186        self.id = id.into();
187        self
188    }
189
190    /// Turn this chart's interactive layer on or off. On by default.
191    ///
192    /// The layer is the hitbox under the cursor and what it drives: the hovered
193    /// node's links stand out from the rest, and a tooltip shows its label and
194    /// throughput. Turn it off for a chart that only decorates, or one an element
195    /// above it wants the cursor for: without a hitbox it neither answers the
196    /// mouse nor takes the hover from what sits over it.
197    pub fn interactive(mut self, interactive: bool) -> Self {
198        self.interactive = interactive;
199        self
200    }
201
202    /// Draw the data in the first time this chart is painted. On by default.
203    ///
204    /// The theme sets how long it takes, and the system's reduced-motion
205    /// setting skips it. Turn it off for a chart that is painted again and
206    /// again as it scrolls in and out of view, such as one in each row of a
207    /// long list, where it would draw in every time.
208    pub fn appear(mut self, appear: bool) -> Self {
209        self.appear.set_enabled(appear);
210        self
211    }
212
213    /// Draw the data in again whenever `key` changes, such as the symbol or
214    /// period a chart shows.
215    ///
216    /// Without one the data draws in once, and later data paints in place.
217    pub fn appear_key(mut self, key: impl Hash) -> Self {
218        self.appear.set_key(key);
219        self
220    }
221
222    /// Set the node rectangle width. Defaults to 10.
223    pub fn node_width(mut self, node_width: f32) -> Self {
224        self.node_width = node_width;
225        self
226    }
227
228    /// Set the vertical gap between nodes in a column. Defaults to 16.
229    pub fn node_padding(mut self, node_padding: f32) -> Self {
230        self.node_padding = node_padding;
231        self
232    }
233
234    /// Set the node alignment. Defaults to [`SankeyAlign::Justify`].
235    pub fn node_align(mut self, align: SankeyAlign) -> Self {
236        self.align = align;
237        self
238    }
239
240    /// Set the number of relaxation passes. Defaults to 6.
241    pub fn iterations(mut self, iterations: usize) -> Self {
242        self.iterations = iterations;
243        self
244    }
245
246    /// Set how flow values map to node heights.
247    ///
248    /// Defaults to [`SankeyValueScale::Linear`]. Use [`SankeyValueScale::Sqrt`]
249    /// to keep a dominant flow from dwarfing the small ones without
250    /// pre-transforming the data; labels still receive the raw values.
251    pub fn value_scale(mut self, value_scale: SankeyValueScale) -> Self {
252        self.value_scale = value_scale;
253        self
254    }
255
256    /// Set the corner radius of the node rectangles. Defaults to 0.
257    pub fn node_corner_radius(mut self, radius: impl Into<Pixels>) -> Self {
258        self.node_corner_radius = Some(radius.into());
259        self
260    }
261
262    /// Set the color of each node.
263    ///
264    /// Defaults to cycling the theme chart palette by node index.
265    pub fn node_color<H>(mut self, color: impl Fn(&T) -> H + 'static) -> Self
266    where
267        H: Into<Hsla> + 'static,
268    {
269        self.node_color = Some(Rc::new(move |t| color(t).into()));
270        self
271    }
272
273    /// Set the name label of each node, drawn in muted foreground. No name
274    /// label is drawn unless set.
275    pub fn node_label(mut self, label: impl Fn(&T) -> SharedString + 'static) -> Self {
276        self.node_label = Some(Rc::new(label));
277        self
278    }
279
280    /// Set the value label of each node, drawn above the name label. No value
281    /// label is drawn unless set.
282    ///
283    /// The closure receives the datum and the node's raw computed throughput
284    /// (max of incoming and outgoing flow, in unscaled units).
285    pub fn value_label(mut self, label: impl Fn(&T, f64) -> SharedString + 'static) -> Self {
286        self.value_label = Some(Rc::new(label));
287        self
288    }
289
290    /// Set fully custom node labels, one [`SankeyLabel`] per line, top to
291    /// bottom. Takes precedence over `node_label`/`value_label` when set;
292    /// unset by default.
293    ///
294    /// The closure receives the datum and the node's raw computed throughput
295    /// (max of incoming and outgoing flow, in unscaled units).
296    pub fn labels(mut self, labels: impl Fn(&T, f64) -> Vec<SankeyLabel> + 'static) -> Self {
297        self.labels = Some(Rc::new(labels));
298        self
299    }
300
301    /// Name the node under the cursor in the hover tooltip's row, beside its
302    /// throughput. Unset, the row carries no name at all.
303    ///
304    /// A sankey shows one number per node, so the node's own name is what the
305    /// row wants; without it the row reads as a swatch and a number with a gap
306    /// between them. The alternative was to title the tooltip from
307    /// `node_label`, but that also draws the name beside the node — and a chart
308    /// drawing its text through `labels` sets neither.
309    pub fn tooltip_name(mut self, name: impl Fn(&T) -> SharedString + 'static) -> Self {
310        self.tooltip_name = Some(Rc::new(name));
311        self
312    }
313
314    /// Set the text of the hover tooltip's row, the node's throughput.
315    ///
316    /// `value_label` supplies it when this is unset, and the raw number when
317    /// neither is set — which is what a chart drawing its text through `labels`
318    /// gets, however carefully it formats the value it draws.
319    pub fn tooltip_value(mut self, value: impl Fn(&T, f64) -> SharedString + 'static) -> Self {
320        self.tooltip_value = Some(Rc::new(value));
321        self
322    }
323
324    /// Set the opacity of the link ribbons. Defaults to 0.3.
325    pub fn link_opacity(mut self, opacity: f32) -> Self {
326        self.link_opacity = opacity;
327        self
328    }
329
330    /// Set the minimum ribbon thickness, so tiny flows stay visible. Defaults to 1.
331    pub fn min_link_width(mut self, width: f32) -> Self {
332        self.min_link_width = width;
333        self
334    }
335
336    /// Set the gap between a node and its labels. Defaults to 6.
337    pub fn label_gap(mut self, gap: f32) -> Self {
338        self.label_gap = gap;
339        self
340    }
341
342    fn sankey(&self) -> Sankey {
343        Sankey::new()
344            .node_width(self.node_width)
345            .node_padding(self.node_padding)
346            .node_align(self.align)
347            .iterations(self.iterations)
348            .value_scale(self.value_scale)
349    }
350
351    /// Raw per-node throughput (max of raw incoming and outgoing sums), for
352    /// labels — the layout's `node.value` is in scaled units under a
353    /// non-linear value scale, so labels must not use it.
354    fn raw_throughput(&self) -> Vec<f64> {
355        let mut incoming = vec![0f64; self.nodes.len()];
356        let mut outgoing = vec![0f64; self.nodes.len()];
357        for link in &self.links {
358            if let (Some(o), Some(i)) =
359                (outgoing.get_mut(link.source), incoming.get_mut(link.target))
360            {
361                *o += link.value;
362                *i += link.value;
363            }
364        }
365        incoming
366            .into_iter()
367            .zip(outgoing)
368            .map(|(i, o)| i.max(o))
369            .collect()
370    }
371}
372
373impl<T> SankeyChart<T> {
374    /// Each node's label lines: the custom `labels` closure wins, otherwise the
375    /// value/name lines with the default styles. Labels get the raw throughput,
376    /// not the layout's (possibly scaled) value.
377    fn node_labels(&self, cx: &App) -> Vec<Vec<SankeyLabel>> {
378        let raw_value = self.raw_throughput();
379        self.nodes
380            .iter()
381            .zip(raw_value)
382            .map(|(datum, value)| {
383                if let Some(labels) = &self.labels {
384                    labels(datum, value)
385                } else {
386                    let mut lines = Vec::new();
387                    if let Some(value_label) = &self.value_label {
388                        lines.push(SankeyLabel::new(value_label(datum, value)));
389                    }
390                    if let Some(node_label) = &self.node_label {
391                        lines.push(
392                            SankeyLabel::new(node_label(datum)).color(cx.theme().muted_foreground),
393                        );
394                    }
395                    lines
396                }
397            })
398            .collect()
399    }
400
401    /// The key a placement is reused under: everything that shapes it, which is
402    /// the bounds size, the graph, the placement settings and the label lines.
403    fn frame_key(&self, bounds: Bounds<Pixels>, node_labels: &[Vec<SankeyLabel>]) -> u64 {
404        let mut hasher = DefaultHasher::new();
405        bounds.size.width.as_f32().to_bits().hash(&mut hasher);
406        bounds.size.height.as_f32().to_bits().hash(&mut hasher);
407        self.nodes.len().hash(&mut hasher);
408        for link in &self.links {
409            link.source.hash(&mut hasher);
410            link.target.hash(&mut hasher);
411            link.value.to_bits().hash(&mut hasher);
412        }
413        self.node_width.to_bits().hash(&mut hasher);
414        self.node_padding.to_bits().hash(&mut hasher);
415        self.align.hash(&mut hasher);
416        self.iterations.hash(&mut hasher);
417        self.value_scale.hash(&mut hasher);
418        self.label_gap.to_bits().hash(&mut hasher);
419        for lines in node_labels {
420            lines.len().hash(&mut hasher);
421            for line in lines {
422                line.text.hash(&mut hasher);
423                line.font_size.map(f32::to_bits).hash(&mut hasher);
424                line.color
425                    .map(|color| {
426                        [
427                            color.color.hue.into_degrees(),
428                            color.color.saturation,
429                            color.color.lightness,
430                            color.alpha,
431                        ]
432                        .map(f32::to_bits)
433                    })
434                    .hash(&mut hasher);
435            }
436        }
437        hasher.finish()
438    }
439
440    /// Place the graph within `bounds`, reserving margins for the labels.
441    fn place(
442        &self,
443        bounds: Bounds<Pixels>,
444        node_labels: Vec<Vec<SankeyLabel>>,
445        window: &mut Window,
446    ) -> Option<SankeyFrame> {
447        let width = bounds.size.width.as_f32();
448        let height = bounds.size.height.as_f32();
449
450        // First pass: only the topology (each node's `layer`) is needed to
451        // measure the label margins.
452        let topology = self.sankey().topology(self.nodes.len(), &self.links).ok()?;
453        let layer_count = topology.layer_count();
454        let has_labels = node_labels.iter().any(|lines| !lines.is_empty());
455
456        // Reserve margins so the labels beside the first/last columns and
457        // above the middle columns are not clipped.
458        let mut left = 0f32;
459        let mut right = 0f32;
460        if has_labels {
461            for node in &topology.nodes {
462                if node.layer != 0 && node.layer + 1 != layer_count {
463                    continue;
464                }
465                let mut label_width = 0f32;
466                for line in &node_labels[node.index] {
467                    label_width = label_width.max(measure_text_width(
468                        &line.text,
469                        px(line.font_size.unwrap_or(TEXT_SIZE)),
470                        window,
471                    ));
472                }
473                if node.layer == 0 {
474                    left = left.max(label_width + self.label_gap);
475                } else {
476                    right = right.max(label_width + self.label_gap);
477                }
478            }
479
480            // Cap each side independently so one long label is truncated to a
481            // modest column rather than eating into the flow area.
482            let side_cap = width * MAX_LABEL_WIDTH_RATIO;
483            left = left.min(side_cap);
484            right = right.min(side_cap);
485        }
486        // Above-node labels are only emitted for middle columns, so reserve
487        // the top band for the tallest such label block. Cap the vertical
488        // margins like the horizontal ones so a short chart doesn't collapse
489        // the flow.
490        let mut top = 0f32;
491        if has_labels && layer_count > 2 {
492            for node in &topology.nodes {
493                if node.layer == 0 || node.layer + 1 == layer_count {
494                    continue;
495                }
496                let block = block_height(&node_labels[node.index]);
497                if block > 0. {
498                    top = top.max(block + TEXT_GAP);
499                }
500            }
501        }
502        let mut bottom = if has_labels { TEXT_GAP } else { 0. };
503        let max_vertical = height * MAX_LABEL_MARGIN_RATIO;
504        if top + bottom > max_vertical {
505            let k = max_vertical / (top + bottom);
506            top *= k;
507            bottom *= k;
508        }
509
510        // Second pass: complete the placement on the final extent, reusing
511        // the first pass's topology.
512        let graph = self
513            .sankey()
514            .extent(
515                left,
516                top,
517                (width - right).max(left + 1.),
518                (height - bottom).max(top + 1.),
519            )
520            .layout_from(topology);
521
522        Some(SankeyFrame {
523            graph,
524            layer_count,
525            node_labels,
526            left,
527            right,
528        })
529    }
530
531    /// Whether `link` starts or ends at `node`.
532    fn is_attached(link: &SankeyLinkLayout, node: usize) -> bool {
533        link.source == node || link.target == node
534    }
535}
536
537impl<T> Plot for SankeyChart<T> {
538    /// Resolve the placement for the frame, reusing the last one while nothing
539    /// that shapes it has changed. Measuring the labels needs the window, which
540    /// `tooltip_state` does not have, so this runs here rather than in `paint`.
541    fn prepaint(
542        &mut self,
543        bounds: Bounds<Pixels>,
544        window: &mut Window,
545        cx: &mut App,
546    ) -> Vec<AnyElement> {
547        self.frame = None;
548        let width = bounds.size.width.as_f32();
549        let height = bounds.size.height.as_f32();
550        if self.nodes.is_empty() || self.links.is_empty() || width <= 0. || height <= 0. {
551            return vec![];
552        }
553
554        let node_labels = self.node_labels(cx);
555
556        let key = self.frame_key(bounds, &node_labels);
557        let cache = window.use_keyed_state("sankey-frame", cx, |_, _| SankeyFrameCache::default());
558        let cached = cache.read(cx);
559        self.frame = if cached.key == Some(key) {
560            cached.frame.clone()
561        } else {
562            let frame = self.place(bounds, node_labels, window).map(Rc::new);
563            cache.update(cx, |cache, _| {
564                cache.key = Some(key);
565                cache.frame = frame.clone();
566            });
567            frame
568        };
569
570        vec![]
571    }
572
573    fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
574        let Some(frame) = self.frame.clone() else {
575            return;
576        };
577        let SankeyFrame {
578            graph,
579            layer_count,
580            node_labels,
581            left,
582            right,
583        } = &*frame;
584        let (layer_count, left, right) = (*layer_count, *left, *right);
585        let width = bounds.size.width.as_f32();
586        let height = bounds.size.height.as_f32();
587
588        let palette = [
589            cx.theme().chart_1,
590            cx.theme().chart_2,
591            cx.theme().chart_3,
592            cx.theme().chart_4,
593            cx.theme().chart_5,
594        ];
595        let colors: Vec<Hsla> = self
596            .nodes
597            .iter()
598            .enumerate()
599            .map(|(index, datum)| match &self.node_color {
600                Some(color) => color(datum),
601                None => palette[index % palette.len()],
602            })
603            .collect();
604
605        // Links first, under the nodes. The links of the hovered node keep their
606        // opacity while the rest fade behind them.
607        //
608        // Hovering changes only a ribbon's opacity, so the chart keeps each
609        // tessellated ribbon, slotted by the link's index in the graph so a
610        // skipped zero-value link doesn't shift the others.
611        //
612        // Links and nodes draw in from the left under a mask as the chart
613        // appears, which leaves the cached ribbons whole; the labels fade in.
614        let min_width = self.min_link_width;
615        let caches = PathCaches::for_paint("links", window, cx);
616        let appear = self.appear.get().progress();
617        window.with_content_mask(reveal_mask(bounds, 0., appear), |window| {
618            for (ix, link) in graph.links.iter().enumerate() {
619                if link.value <= 0. {
620                    continue;
621                }
622                let source = &graph.nodes[link.source];
623                let target = &graph.nodes[link.target];
624                let path = caches.update(cx, |caches, _| {
625                    let key = ShapeKey::new(())
626                        .f32(source.x1)
627                        .f32(target.x0)
628                        .f32(link.y0)
629                        .f32(link.y1)
630                        .f32(link.source_width.max(min_width))
631                        .f32(link.target_width.max(min_width))
632                        .finish();
633                    caches.slot(ix).get(key, bounds.origin, || {
634                        sankey_link_path(source, target, link, min_width, Point::default())
635                    })
636                });
637                let Some(path) = path else {
638                    continue;
639                };
640                let opacity = match self.hover {
641                    Some(hover) if !Self::is_attached(link, hover.node) => {
642                        self.link_opacity * (1. - HOVER_DIM * hover.focus)
643                    }
644                    _ => self.link_opacity,
645                };
646                window.paint_path(
647                    path,
648                    linear_gradient(
649                        90.,
650                        linear_color_stop(colors[link.source].opacity(opacity), 0.),
651                        linear_color_stop(colors[link.target].opacity(opacity), 1.),
652                    ),
653                );
654            }
655
656            let corner_radii = Corners::all(self.node_corner_radius.unwrap_or_default());
657            for node in &graph.nodes {
658                let node_bounds = Bounds::from_corners(
659                    origin_point(px(node.x0), px(node.y0), bounds.origin),
660                    // Keep tiny nodes visible with a minimum 1px height.
661                    origin_point(px(node.x1), px(node.y1.max(node.y0 + 1.)), bounds.origin),
662                );
663                window.paint_quad(
664                    gpui::PaintQuad::new(node_bounds)
665                        .background(colors[node.index])
666                        .corner_radii(corner_radii),
667                );
668            }
669        });
670
671        let mut texts = Vec::new();
672        for node in &graph.nodes {
673            let lines = &node_labels[node.index];
674            if lines.is_empty() {
675                continue;
676            }
677
678            let is_first = node.layer == 0;
679            let is_last = node.layer + 1 == layer_count;
680            // `x`/`align` place the label beside (first/last) or centered above
681            // (middle) the node, and `max_width` bounds it so a long label is
682            // truncated with an ellipsis instead of drawn outside the plot:
683            // first/last to their reserved margin, middle to twice the smaller
684            // gap to the plot edge (generous for interior nodes, only bites a
685            // label long enough to actually run off-plot).
686            let (x, align, max_width) = if is_first {
687                (
688                    node.x0 - self.label_gap,
689                    TextAlign::Right,
690                    left - self.label_gap,
691                )
692            } else if is_last {
693                (
694                    node.x1 + self.label_gap,
695                    TextAlign::Left,
696                    right - self.label_gap,
697                )
698            } else {
699                let center = (node.x0 + node.x1) / 2.;
700                let edge_budget = 2. * center.min(width - center);
701                (center, TextAlign::Center, edge_budget)
702            };
703
704            let block = block_height(lines);
705            let mut y = if is_first || is_last {
706                // Block vertically centered beside the node, clamped into
707                // the plot area so labels of nodes near the top or bottom
708                // edge are not clipped.
709                ((node.y0 + node.y1) / 2. - block / 2.)
710                    .min(height - block)
711                    .max(0.)
712            } else {
713                // Block above the node.
714                node.y0 - block - TEXT_GAP
715            };
716
717            for line in lines {
718                let font_size = px(line.font_size.unwrap_or(TEXT_SIZE));
719                let text = truncate_text_to_width(&line.text, font_size, max_width, window);
720                texts.push(
721                    Text::new(
722                        text,
723                        point(px(x), px(y)),
724                        line.color.unwrap_or(cx.theme().foreground).opacity(appear),
725                    )
726                    .font_size(font_size)
727                    .align(align),
728                );
729                y += line.line_height();
730            }
731        }
732        PlotLabel::new(texts).paint(&bounds, window, cx);
733    }
734
735    fn id(&self) -> Option<ElementId> {
736        Some(self.id.clone())
737    }
738
739    fn interactive(&self) -> bool {
740        self.interactive
741    }
742
743    fn appear(&mut self, appear: PlotAppear, _window: &mut Window, _cx: &mut App) {
744        self.appear.update(appear);
745    }
746
747    fn appear_generation(&self) -> Option<u64> {
748        self.appear.generation()
749    }
750
751    fn tooltip_state(
752        &self,
753        position: Point<Pixels>,
754        _bounds: Bounds<Pixels>,
755        _cx: &App,
756    ) -> Option<TooltipState> {
757        let frame = self.frame.as_ref()?;
758        let (x, y) = (position.x.as_f32(), position.y.as_f32());
759        let node = frame.graph.nodes.iter().find(|node| {
760            (node.x0..=node.x1).contains(&x) && (node.y0..=node.y1.max(node.y0 + 1.)).contains(&y)
761        })?;
762        Some(TooltipState::new(node.index, position, vec![]))
763    }
764
765    fn hover(&mut self, hover: Option<&PlotHover>, _window: &mut Window, _cx: &mut App) {
766        self.hover = hover.map(|hover| SankeyHover {
767            node: hover.state().index,
768            focus: hover.progress(),
769        });
770    }
771
772    fn tooltip(
773        &self,
774        state: &TooltipState,
775        cursor: Point<Pixels>,
776        bounds: Bounds<Pixels>,
777        _window: &mut Window,
778        cx: &mut App,
779    ) -> Option<AnyElement> {
780        let datum = self.nodes.get(state.index)?;
781        let value = self.raw_throughput().get(state.index).copied()?;
782        let color = match &self.node_color {
783            Some(color) => color(datum),
784            None => {
785                let palette = [
786                    cx.theme().chart_1,
787                    cx.theme().chart_2,
788                    cx.theme().chart_3,
789                    cx.theme().chart_4,
790                    cx.theme().chart_5,
791                ];
792                palette[state.index % palette.len()]
793            }
794        };
795        let value_text = match self.tooltip_value.as_ref().or(self.value_label.as_ref()) {
796            Some(value_text) => value_text(datum, value),
797            None => format!("{value}").into(),
798        };
799
800        Some(
801            // Follow the cursor; the node's links mark it.
802            Tooltip::new(cursor, bounds.size)
803                .gap(px(8.))
804                .when_some(self.node_label.as_ref(), |this, label| {
805                    this.title(label(datum))
806                })
807                .row(
808                    color,
809                    match self.tooltip_name.as_ref() {
810                        Some(tooltip_name) => tooltip_name(datum),
811                        None => SharedString::default(),
812                    },
813                    value_text,
814                )
815                .into_any_element(),
816        )
817    }
818}
819
820#[cfg(test)]
821mod tests {
822    use super::*;
823
824    #[test]
825    fn test_sankey_chart_builder() {
826        let chart = SankeyChart::new(vec!["a", "b"], vec![SankeyLink::new(0, 1, 5.)]);
827        assert_eq!(chart.nodes.len(), 2);
828        assert_eq!(chart.links.len(), 1);
829        assert_eq!(chart.node_width, DEFAULT_NODE_WIDTH);
830        assert_eq!(chart.node_padding, DEFAULT_NODE_PADDING);
831        assert_eq!(chart.align, SankeyAlign::Justify);
832        assert_eq!(chart.iterations, 6);
833        assert_eq!(chart.node_corner_radius, None);
834        assert_eq!(chart.link_opacity, DEFAULT_LINK_OPACITY);
835        assert_eq!(chart.min_link_width, DEFAULT_MIN_LINK_WIDTH);
836        assert_eq!(chart.label_gap, DEFAULT_LABEL_GAP);
837        assert!(chart.node_color.is_none());
838        assert!(chart.node_label.is_none());
839        assert!(chart.value_label.is_none());
840        assert!(chart.labels.is_none());
841
842        let chart = chart
843            .node_width(8.)
844            .node_padding(20.)
845            .node_align(SankeyAlign::Left)
846            .iterations(10)
847            .node_corner_radius(px(2.))
848            .node_color(|_| gpui::red())
849            .node_label(|d| SharedString::from(d.to_string()))
850            .value_label(|_, value| SharedString::from(format!("{}", value)))
851            .labels(|d, value| {
852                vec![
853                    SankeyLabel::new(format!("{}", value)),
854                    SankeyLabel::new(d.to_string()),
855                ]
856            })
857            .link_opacity(0.5)
858            .min_link_width(2.)
859            .label_gap(10.);
860        assert_eq!(chart.node_width, 8.);
861        assert_eq!(chart.node_padding, 20.);
862        assert_eq!(chart.align, SankeyAlign::Left);
863        assert_eq!(chart.iterations, 10);
864        assert_eq!(chart.node_corner_radius, Some(px(2.)));
865        assert_eq!(chart.link_opacity, 0.5);
866        assert_eq!(chart.min_link_width, 2.);
867        assert_eq!(chart.label_gap, 10.);
868        assert!(chart.node_color.is_some());
869        assert!(chart.node_label.is_some());
870        assert!(chart.value_label.is_some());
871        assert!(chart.labels.is_some());
872    }
873
874    #[test]
875    fn test_sankey_label_builder() {
876        let label = SankeyLabel::new("a");
877        assert_eq!(label.text, "a");
878        assert_eq!(label.color, None);
879        assert_eq!(label.font_size, None);
880        assert_eq!(label.line_height(), TEXT_SIZE + TEXT_GAP);
881
882        let label = SankeyLabel::new("b").color(gpui::red()).font_size(14.);
883        assert_eq!(label.color, Some(gpui::red()));
884        assert_eq!(label.font_size, Some(14.));
885        assert_eq!(label.line_height(), 14. + TEXT_GAP);
886
887        assert_eq!(
888            block_height(&[SankeyLabel::new("a"), SankeyLabel::new("b").font_size(14.)]),
889            TEXT_SIZE + TEXT_GAP + 14. + TEXT_GAP
890        );
891        assert_eq!(block_height(&[]), 0.);
892    }
893
894    #[test]
895    fn test_sankey_chart_raw_throughput() {
896        // A(out 30) -> B, B -> C(20) + D(10): B's throughput is max(in, out).
897        let chart = SankeyChart::new(
898            vec!["a", "b", "c", "d"],
899            vec![
900                SankeyLink::new(0, 1, 30.),
901                SankeyLink::new(1, 2, 20.),
902                SankeyLink::new(1, 3, 10.),
903            ],
904        );
905        let raw = chart.raw_throughput();
906        assert_eq!(raw, vec![30., 30., 20., 10.]);
907
908        // Under Sqrt the layout's node value is scaled, but raw_throughput
909        // (used for labels) must stay in raw units — the two must differ.
910        let sqrt = chart
911            .value_scale(SankeyValueScale::Sqrt)
912            .sankey()
913            .layout(4, &chart_links())
914            .unwrap();
915        // Node A: layout value is sqrt-scaled (30 -> sqrt(30)), raw is 30.
916        assert!((sqrt.nodes[0].value - 30f64.sqrt()).abs() < 1e-6);
917        assert!((raw[0] - 30.).abs() < 1e-6);
918        assert!(raw[0] != sqrt.nodes[0].value);
919    }
920
921    fn chart_links() -> Vec<SankeyLink> {
922        vec![
923            SankeyLink::new(0, 1, 30.),
924            SankeyLink::new(1, 2, 20.),
925            SankeyLink::new(1, 3, 10.),
926        ]
927    }
928
929    /// A chart drawing its text through `labels` sets neither `node_label` nor
930    /// `value_label`, so its tooltip row had no name and an unformatted number.
931    #[test]
932    fn test_tooltip_text_is_settable_without_drawing_labels() {
933        let chart = SankeyChart::new(vec!["Revenue"], Vec::<SankeyLink>::new())
934            .tooltip_name(|_| "Revenue".into())
935            .tooltip_value(|_, value| format!("{value:.0}M").into());
936        assert!(chart.tooltip_name.is_some());
937        assert!(chart.tooltip_value.is_some());
938        assert!(chart.node_label.is_none());
939        assert!(chart.value_label.is_none());
940    }
941}