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 if crate::interact::recording() && xb > xa {
287 let (y0, y1) = (src_y[li].min(dst_y[li]), src_y[li].max(dst_y[li]) + h);
288 let rect = Rect::new(
289 plot.x + (xa / rxd as i32).max(0) as u16,
290 plot.y + (y0 / ryd as f64).max(0.0) as u16,
291 ((xb - xa) / rxd as i32).max(1) as u16,
292 (((y1 - y0) / ryd as f64).ceil() as u16).max(1),
293 )
294 .intersection(plot);
295 crate::interact::record_point(rect, 1, li, || {
296 (
297 format!("{} → {}", nodes[a].name, nodes[b].name),
298 vec![format!("flow {}", format_compact(v))],
299 )
300 });
301 }
302 let c = darken(color_of(a), 0.55);
303 for px in xa..xb {
304 let t = (px - xa) as f64 / (xb - xa).max(1) as f64;
305 let s = t * t * (3.0 - 2.0 * t);
306 let top = src_y[li] + (dst_y[li] - src_y[li]) * s;
307 for py in top.round() as i32..(top + h).round().max(top.round() + 1.0) as i32 {
308 cv.set(px, py, c);
309 }
310 }
311 }
312 for (i, nd) in nodes.iter().enumerate() {
314 let x = col_x(nd.layer);
315 let c = color_of(i);
316 if crate::interact::recording() {
317 let rect = Rect::new(
318 plot.x + (x / rxd as i32).max(0) as u16,
319 plot.y + (nd.y / ryd as f64).max(0.0) as u16,
320 self.node_width.max(1),
321 (((nd.h) / ryd as f64).ceil() as u16).max(1),
322 )
323 .intersection(plot);
324 crate::interact::record_point(rect, 0, i, || {
325 (
326 nd.name.clone(),
327 vec![
328 format!("in {}", format_compact(nd.inflow)),
329 format!("out {}", format_compact(nd.outflow)),
330 ],
331 )
332 });
333 }
334 for py in nd.y.round() as i32..(nd.y + nd.h).round().max(nd.y.round() + 1.0) as i32 {
335 for px in x..x + nw {
336 cv.set(px, py, c);
337 }
338 }
339 }
340 cv.render(buf, plot);
341
342 for nd in &nodes {
344 let row = plot.y as i32 + ((nd.y + nd.h / 2.0) / ryd as f64) as i32;
345 let row = row.clamp(plot.y as i32, plot.bottom() as i32 - 1) as u16;
346 let label = label_of(nd);
347 let st = text.add_modifier(Modifier::BOLD);
348 let w = label.chars().count() as u16;
349 if nd.layer == 0 {
350 let l: String = label
351 .chars()
352 .take(left_w.saturating_sub(1) as usize)
353 .collect();
354 put_str(buf, inner.x, row, plot.x, &l, st);
355 } else if nd.layer == layers - 1 {
356 put_str(buf, plot.right() + 1, row, inner.right(), &label, st);
357 } else {
358 let x = plot.x + (col_x(nd.layer) / rxd as i32) as u16 + self.node_width + 1;
359 if x + w <= plot.right() {
360 put_str(buf, x, row, plot.right(), &label, st.fg(Color::White));
361 }
362 }
363 }
364 let _ = dim;
365 }
366}
367
368widget_impls!(Sankey);
369
370#[cfg(feature = "theme")]
371impl tui_nuances::Themed for Sankey {
372 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
373 self.theme(theme)
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use ratatui::widgets::Widget;
381
382 fn render(c: &Sankey, w: u16, h: u16) -> Buffer {
383 let a = Rect::new(0, 0, w, h);
384 let mut b = Buffer::empty(a);
385 c.render(a, &mut b);
386 b
387 }
388
389 fn links() -> Vec<SankeyLink> {
390 vec![
391 SankeyLink::new("Salary", "Budget", 70.0),
392 SankeyLink::new("Other", "Budget", 30.0),
393 SankeyLink::new("Budget", "Rent", 40.0),
394 SankeyLink::new("Budget", "Food", 25.0),
395 SankeyLink::new("Budget", "Savings", 35.0),
396 ]
397 }
398
399 #[test]
400 fn labels_all_columns_with_totals() {
401 let b = render(&Sankey::new(links()), 80, 20);
402 let t: String = b.content().iter().map(|c| c.symbol()).collect();
403 assert!(t.contains("Salary") && t.contains("Rent") && t.contains("Savings"));
404 assert!(t.contains("70") && t.contains("100"));
405 }
406
407 #[test]
408 fn node_colors_apply() {
409 let c = Sankey::new(links()).node_color("Salary", Color::Red);
410 assert!(
411 render(&c, 80, 20)
412 .content()
413 .iter()
414 .any(|c| c.fg == Color::Red)
415 );
416 }
417
418 #[test]
419 fn values_toggle() {
420 let b = render(&Sankey::new(links()).show_values(false), 80, 20);
421 let t: String = b.content().iter().map(|c| c.symbol()).collect();
422 assert!(t.contains("Salary") && !t.contains("Salary 70"));
423 }
424
425 #[test]
426 fn thicker_flow_takes_more_cells() {
427 let cells = |v: f64| {
428 let c = Sankey::new([
429 SankeyLink::new("a", "b", v),
430 SankeyLink::new("a", "c", 100.0 - v),
431 ])
432 .node_color("a", Color::Red);
433 render(&c, 60, 20)
434 .content()
435 .iter()
436 .filter(|c| c.fg == Color::Red && c.symbol() != " ")
437 .count()
438 };
439 assert!(cells(50.0) > 0);
440 }
441
442 #[test]
443 fn cycles_and_garbage_do_not_panic_or_hang() {
444 let c = Sankey::new([
445 SankeyLink::new("a", "b", 1.0),
446 SankeyLink::new("b", "c", 1.0),
447 SankeyLink::new("c", "a", 1.0),
448 SankeyLink::new("a", "a", 5.0),
449 SankeyLink::new("x", "y", f64::NAN),
450 SankeyLink::new("x", "y", -3.0),
451 SankeyLink::new("p", "q", 1e300),
452 ]);
453 for (w, h) in [(0, 0), (1, 1), (12, 3), (8, 40), (200, 60)] {
454 render(&c, w, h);
455 render(&Sankey::new(links()), w, h);
456 }
457 render(&Sankey::new([]), 40, 10);
458 }
459}