1use crate::canvas::{Canvas, Marker};
5use crate::text::put_str;
6use crate::theme::{self, Theme};
7use crate::util::{darken, dim_text, format_compact, pick};
8use ratatui::{
9 buffer::Buffer,
10 layout::Rect,
11 style::{Color, Modifier, Style},
12 widgets::Block,
13};
14
15#[derive(Debug, Clone, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct SankeyLink {
19 pub from: String,
21 pub to: String,
23 pub value: f64,
25}
26
27impl SankeyLink {
28 pub fn new(from: impl Into<String>, to: impl Into<String>, value: f64) -> Self {
30 Self {
31 from: from.into(),
32 to: to.into(),
33 value,
34 }
35 }
36}
37
38#[derive(Debug, Clone)]
53pub struct Sankey {
54 links: Vec<SankeyLink>,
55 colors: Vec<(String, Color)>,
56 node_width: u16,
57 node_gap: u16,
58 show_values: bool,
59 marker: Marker,
60 theme: Option<Theme>,
61 base: Option<Style>,
62 block: Option<Block<'static>>,
63}
64
65struct Node {
66 name: String,
67 layer: usize,
68 inflow: f64,
69 outflow: f64,
70 y: f64,
71 h: f64,
72}
73
74impl Sankey {
75 pub fn new(links: impl IntoIterator<Item = SankeyLink>) -> Self {
77 Self {
78 links: links.into_iter().collect(),
79 colors: Vec::new(),
80 node_width: 2,
81 node_gap: 1,
82 show_values: true,
83 marker: Marker::HalfBlock,
84 theme: None,
85 base: None,
86 block: None,
87 }
88 }
89
90 pub fn node_color(mut self, name: impl Into<String>, color: Color) -> Self {
92 self.colors.push((name.into(), color));
93 self
94 }
95
96 setter!(
97 node_width: u16
99 );
100 setter!(
101 node_gap: u16
103 );
104 setter!(
105 show_values: bool
107 );
108 setter!(
109 marker: Marker
111 );
112 theme_setter!(
113 theme
115 );
116 base_style_setter!(base);
117 block_setter!(block, 'static);
118
119 fn render_into(&self, area: Rect, buf: &mut Buffer) {
120 let area = area.intersection(buf.area);
121 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
122 if inner.width < 12 || inner.height < 3 {
123 return;
124 }
125 let mut nodes: Vec<Node> = Vec::new();
127 let index = |name: &str, nodes: &mut Vec<Node>| -> usize {
128 if let Some(i) = nodes.iter().position(|n| n.name == name) {
129 return i;
130 }
131 nodes.push(Node {
132 name: name.to_string(),
133 layer: 0,
134 inflow: 0.0,
135 outflow: 0.0,
136 y: 0.0,
137 h: 0.0,
138 });
139 nodes.len() - 1
140 };
141 let mut links: Vec<(usize, usize, f64)> = Vec::new();
142 for l in &self.links {
143 if !(l.value.is_finite() && l.value > 0.0) || l.from == l.to {
144 continue;
145 }
146 let (a, b) = (index(&l.from, &mut nodes), index(&l.to, &mut nodes));
147 nodes[a].outflow += l.value;
148 nodes[b].inflow += l.value;
149 links.push((a, b, l.value));
150 }
151 let n = nodes.len();
152 if n < 2 {
153 return;
154 }
155 for _ in 0..n {
157 let mut changed = false;
158 for &(a, b, _) in &links {
159 if nodes[b].layer < nodes[a].layer + 1 && nodes[a].layer < n {
160 nodes[b].layer = nodes[a].layer + 1;
161 changed = true;
162 }
163 }
164 if !changed {
165 break;
166 }
167 }
168 let mut used: Vec<usize> = nodes.iter().map(|n| n.layer).collect();
169 used.sort_unstable();
170 used.dedup();
171 for nd in nodes.iter_mut() {
172 nd.layer = used.iter().position(|l| *l == nd.layer).unwrap_or(0);
173 }
174 let layers = used.len();
175 if layers < 2 {
176 return;
177 }
178 let flow = |nd: &Node| nd.inflow.max(nd.outflow);
179 let label_of = |nd: &Node| {
180 if self.show_values {
181 format!("{} {}", nd.name, format_compact(flow(nd)))
182 } else {
183 nd.name.clone()
184 }
185 };
186 let (dim, text) = dim_text(&self.theme);
187
188 let cap = inner.width / 4;
190 let left_w = nodes
191 .iter()
192 .filter(|n| n.layer == 0)
193 .map(|n| label_of(n).chars().count() as u16 + 1)
194 .max()
195 .unwrap_or(0)
196 .min(cap);
197 let right_w = nodes
198 .iter()
199 .filter(|n| n.layer == layers - 1)
200 .map(|n| label_of(n).chars().count() as u16 + 1)
201 .max()
202 .unwrap_or(0)
203 .min(cap);
204 let plot = Rect::new(
205 inner.x + left_w,
206 inner.y,
207 inner.width.saturating_sub(left_w + right_w),
208 inner.height,
209 );
210 if plot.width < 2 * self.node_width + 2 || plot.height < 2 {
211 return;
212 }
213 let mut cv = Canvas::new(plot.width, plot.height, self.marker);
214 let (pw, ph) = (cv.px_w(), cv.px_h());
215 let (rxd, ryd) = self.marker.resolution();
216 let nw = (self.node_width.max(1) as i32) * rxd as i32;
217 let gap = self.node_gap as i32 * ryd as i32;
218 let mut k = f64::MAX;
220 for l in 0..layers {
221 let col: Vec<&Node> = nodes.iter().filter(|n| n.layer == l).collect();
222 let total: f64 = col.iter().map(|n| flow(n)).sum();
223 let avail = ph as f64 - (gap * (col.len() as i32 - 1)) as f64;
224 if total > 0.0 {
225 k = k.min(avail.max(col.len() as f64) / total);
226 }
227 }
228 if !k.is_finite() {
229 return;
230 }
231 for l in 0..layers {
232 let ids: Vec<usize> = (0..n).filter(|i| nodes[*i].layer == l).collect();
233 let used_h: f64 = ids.iter().map(|i| flow(&nodes[*i]) * k).sum::<f64>()
234 + (gap * (ids.len() as i32 - 1)) as f64;
235 let mut y = (ph as f64 - used_h) / 2.0;
236 for i in ids {
237 nodes[i].y = y;
238 nodes[i].h = (flow(&nodes[i]) * k).max(1.0);
239 y += nodes[i].h + gap as f64;
240 }
241 }
242 let col_x = |layer: usize| -> i32 {
243 if layers == 1 {
244 0
245 } else {
246 (layer as i32 * (pw - nw)) / (layers as i32 - 1)
247 }
248 };
249 let color_of = |i: usize| -> Color {
250 self.colors
251 .iter()
252 .rev()
253 .find(|(name, _)| *name == nodes[i].name)
254 .map_or_else(|| pick(&self.theme, i), |(_, c)| *c)
255 };
256
257 let mut out_off = vec![0.0f64; n];
260 let mut in_off = vec![0.0f64; n];
261 let mut order: Vec<usize> = (0..links.len()).collect();
262 order.sort_by(|a, b| {
263 let (la, lb) = (links[*a], links[*b]);
264 nodes[la.1]
265 .y
266 .total_cmp(&nodes[lb.1].y)
267 .then(nodes[la.0].y.total_cmp(&nodes[lb.0].y))
268 });
269 let mut in_order = order.clone();
270 in_order.sort_by(|a, b| nodes[links[*a].0].y.total_cmp(&nodes[links[*b].0].y));
271 let mut src_y = vec![0.0; links.len()];
272 let mut dst_y = vec![0.0; links.len()];
273 for &li in &order {
274 let (a, _, v) = links[li];
275 src_y[li] = nodes[a].y + out_off[a];
276 out_off[a] += v * k;
277 }
278 for &li in &in_order {
279 let (_, b, v) = links[li];
280 dst_y[li] = nodes[b].y + in_off[b];
281 in_off[b] += v * k;
282 }
283 for (li, &(a, b, v)) in links.iter().enumerate() {
284 let (xa, xb) = (col_x(nodes[a].layer) + nw, col_x(nodes[b].layer));
285 let h = (v * k).max(1.0);
286 let c = darken(color_of(a), 0.55);
287 for px in xa..xb {
288 let t = (px - xa) as f64 / (xb - xa).max(1) as f64;
289 let s = t * t * (3.0 - 2.0 * t);
290 let top = src_y[li] + (dst_y[li] - src_y[li]) * s;
291 for py in top.round() as i32..(top + h).round().max(top.round() + 1.0) as i32 {
292 cv.set(px, py, c);
293 }
294 }
295 }
296 for (i, nd) in nodes.iter().enumerate() {
298 let x = col_x(nd.layer);
299 let c = color_of(i);
300 for py in nd.y.round() as i32..(nd.y + nd.h).round().max(nd.y.round() + 1.0) as i32 {
301 for px in x..x + nw {
302 cv.set(px, py, c);
303 }
304 }
305 }
306 cv.render(buf, plot);
307
308 for nd in &nodes {
310 let row = plot.y as i32 + ((nd.y + nd.h / 2.0) / ryd as f64) as i32;
311 let row = row.clamp(plot.y as i32, plot.bottom() as i32 - 1) as u16;
312 let label = label_of(nd);
313 let st = text.add_modifier(Modifier::BOLD);
314 let w = label.chars().count() as u16;
315 if nd.layer == 0 {
316 let l: String = label
317 .chars()
318 .take(left_w.saturating_sub(1) as usize)
319 .collect();
320 put_str(buf, inner.x, row, plot.x, &l, st);
321 } else if nd.layer == layers - 1 {
322 put_str(buf, plot.right() + 1, row, inner.right(), &label, st);
323 } else {
324 let x = plot.x + (col_x(nd.layer) / rxd as i32) as u16 + self.node_width + 1;
325 if x + w <= plot.right() {
326 put_str(buf, x, row, plot.right(), &label, st.fg(Color::White));
327 }
328 }
329 }
330 let _ = dim;
331 }
332}
333
334widget_impls!(Sankey);
335
336#[cfg(feature = "theme")]
337impl tui_nuances::Themed for Sankey {
338 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
339 self.theme(theme)
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use ratatui::widgets::Widget;
347
348 fn render(c: &Sankey, w: u16, h: u16) -> Buffer {
349 let a = Rect::new(0, 0, w, h);
350 let mut b = Buffer::empty(a);
351 c.render(a, &mut b);
352 b
353 }
354
355 fn links() -> Vec<SankeyLink> {
356 vec![
357 SankeyLink::new("Salary", "Budget", 70.0),
358 SankeyLink::new("Other", "Budget", 30.0),
359 SankeyLink::new("Budget", "Rent", 40.0),
360 SankeyLink::new("Budget", "Food", 25.0),
361 SankeyLink::new("Budget", "Savings", 35.0),
362 ]
363 }
364
365 #[test]
366 fn labels_all_columns_with_totals() {
367 let b = render(&Sankey::new(links()), 80, 20);
368 let t: String = b.content().iter().map(|c| c.symbol()).collect();
369 assert!(t.contains("Salary") && t.contains("Rent") && t.contains("Savings"));
370 assert!(t.contains("70") && t.contains("100"));
371 }
372
373 #[test]
374 fn node_colors_apply() {
375 let c = Sankey::new(links()).node_color("Salary", Color::Red);
376 assert!(render(&c, 80, 20)
377 .content()
378 .iter()
379 .any(|c| c.fg == Color::Red));
380 }
381
382 #[test]
383 fn values_toggle() {
384 let b = render(&Sankey::new(links()).show_values(false), 80, 20);
385 let t: String = b.content().iter().map(|c| c.symbol()).collect();
386 assert!(t.contains("Salary") && !t.contains("Salary 70"));
387 }
388
389 #[test]
390 fn thicker_flow_takes_more_cells() {
391 let cells = |v: f64| {
392 let c = Sankey::new([
393 SankeyLink::new("a", "b", v),
394 SankeyLink::new("a", "c", 100.0 - v),
395 ])
396 .node_color("a", Color::Red);
397 render(&c, 60, 20)
398 .content()
399 .iter()
400 .filter(|c| c.fg == Color::Red && c.symbol() != " ")
401 .count()
402 };
403 assert!(cells(50.0) > 0);
404 }
405
406 #[test]
407 fn cycles_and_garbage_do_not_panic_or_hang() {
408 let c = Sankey::new([
409 SankeyLink::new("a", "b", 1.0),
410 SankeyLink::new("b", "c", 1.0),
411 SankeyLink::new("c", "a", 1.0),
412 SankeyLink::new("a", "a", 5.0),
413 SankeyLink::new("x", "y", f64::NAN),
414 SankeyLink::new("x", "y", -3.0),
415 SankeyLink::new("p", "q", 1e300),
416 ]);
417 for (w, h) in [(0, 0), (1, 1), (12, 3), (8, 40), (200, 60)] {
418 render(&c, w, h);
419 render(&Sankey::new(links()), w, h);
420 }
421 render(&Sankey::new([]), 40, 10);
422 }
423}