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.;
33const MAX_LABEL_WIDTH_RATIO: f32 = 0.2;
36const MAX_LABEL_MARGIN_RATIO: f32 = 0.6;
38const HOVER_DIM: f32 = 0.7;
41
42struct SankeyFrame {
49 graph: SankeyGraph,
50 layer_count: usize,
51 node_labels: Vec<Vec<SankeyLabel>>,
52 left: f32,
54 right: f32,
55}
56
57#[derive(Default)]
59struct SankeyFrameCache {
60 key: Option<u64>,
61 frame: Option<Rc<SankeyFrame>>,
62}
63
64#[derive(Clone, Copy)]
66struct SankeyHover {
67 node: usize,
69 focus: f32,
71}
72
73#[derive(Clone)]
75pub struct SankeyLabel {
76 text: SharedString,
77 color: Option<Hsla>,
78 font_size: Option<f32>,
79}
80
81impl SankeyLabel {
82 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 pub fn color(mut self, color: impl Into<Hsla>) -> Self {
93 self.color = Some(color.into());
94 self
95 }
96
97 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#[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 frame: Option<Rc<SankeyFrame>>,
141 hover: Option<SankeyHover>,
142}
143
144impl<T> SankeyChart<T> {
145 #[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 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
186 self.id = id.into();
187 self
188 }
189
190 pub fn interactive(mut self, interactive: bool) -> Self {
198 self.interactive = interactive;
199 self
200 }
201
202 pub fn appear(mut self, appear: bool) -> Self {
209 self.appear.set_enabled(appear);
210 self
211 }
212
213 pub fn appear_key(mut self, key: impl Hash) -> Self {
218 self.appear.set_key(key);
219 self
220 }
221
222 pub fn node_width(mut self, node_width: f32) -> Self {
224 self.node_width = node_width;
225 self
226 }
227
228 pub fn node_padding(mut self, node_padding: f32) -> Self {
230 self.node_padding = node_padding;
231 self
232 }
233
234 pub fn node_align(mut self, align: SankeyAlign) -> Self {
236 self.align = align;
237 self
238 }
239
240 pub fn iterations(mut self, iterations: usize) -> Self {
242 self.iterations = iterations;
243 self
244 }
245
246 pub fn value_scale(mut self, value_scale: SankeyValueScale) -> Self {
252 self.value_scale = value_scale;
253 self
254 }
255
256 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 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 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 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 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 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 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 pub fn link_opacity(mut self, opacity: f32) -> Self {
326 self.link_opacity = opacity;
327 self
328 }
329
330 pub fn min_link_width(mut self, width: f32) -> Self {
332 self.min_link_width = width;
333 self
334 }
335
336 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 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 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 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 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 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 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 let side_cap = width * MAX_LABEL_WIDTH_RATIO;
483 left = left.min(side_cap);
484 right = right.min(side_cap);
485 }
486 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 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 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 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 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 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 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 ((node.y0 + node.y1) / 2. - block / 2.)
710 .min(height - block)
711 .max(0.)
712 } else {
713 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 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 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 let sqrt = chart
911 .value_scale(SankeyValueScale::Sqrt)
912 .sankey()
913 .layout(4, &chart_links())
914 .unwrap();
915 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 #[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}