1use crate::canvas::{Canvas, Marker};
4use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::util::{format_compact, format_tick, nice_ticks};
7use ratatui::{
8 buffer::Buffer,
9 layout::Rect,
10 style::{Color, Style},
11 widgets::Block,
12};
13
14#[derive(Debug, Clone)]
15enum Kind {
16 Delta(f64),
17 Total,
18}
19
20#[derive(Debug, Clone)]
21struct Step {
22 label: String,
23 kind: Kind,
24}
25
26#[derive(Debug, Clone)]
40pub struct Waterfall {
41 steps: Vec<Step>,
42 initial: f64,
43 up: Option<Color>,
44 down: Option<Color>,
45 total: Option<Color>,
46 theme: Option<Theme>,
47 base: Option<Style>,
48 connectors: bool,
49 marker: Option<Marker>,
50 show_values: bool,
51 block: Option<Block<'static>>,
52}
53
54impl Default for Waterfall {
55 fn default() -> Self {
56 Self::new()
57 }
58}
59
60impl Waterfall {
61 pub fn new() -> Self {
63 Self {
64 steps: vec![],
65 initial: 0.0,
66 up: None,
67 down: None,
68 total: None,
69 theme: None,
70 base: None,
71 connectors: true,
72 marker: None,
73 show_values: true,
74 block: None,
75 }
76 }
77
78 pub fn delta(mut self, label: impl Into<String>, v: f64) -> Self {
80 let v = if v.is_finite() { v } else { 0.0 };
81 self.steps.push(Step {
82 label: label.into(),
83 kind: Kind::Delta(v),
84 });
85 self
86 }
87
88 pub fn total(mut self, label: impl Into<String>) -> Self {
90 self.steps.push(Step {
91 label: label.into(),
92 kind: Kind::Total,
93 });
94 self
95 }
96
97 pub fn initial(mut self, v: f64) -> Self {
99 self.initial = if v.is_finite() { v } else { 0.0 };
100 self
101 }
102
103 pub fn colors(mut self, up: Color, down: Color, total: Color) -> Self {
105 self.up = Some(up);
106 self.down = Some(down);
107 self.total = Some(total);
108 self
109 }
110
111 theme_setter!(
112 theme
115 );
116
117 base_style_setter!(base);
118
119 opt_setter!(
120 marker: Marker
123 );
124
125 setter!(
126 connectors: bool
128 );
129
130 setter!(
131 show_values: bool
133 );
134
135 block_setter!(block, 'static);
136
137 pub fn levels(&self) -> Vec<(f64, f64, bool)> {
139 let mut run = self.initial;
140 self.steps
141 .iter()
142 .map(|s| match s.kind {
143 Kind::Delta(d) => {
144 let start = run;
145 run += d;
146 (start, run, false)
147 }
148 Kind::Total => (0.0, run, true),
149 })
150 .collect()
151 }
152}
153
154impl Waterfall {
155 fn render_into(&self, area: Rect, buf: &mut Buffer) {
156 let area = area.intersection(buf.area);
157 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
158 if inner.width < 4 || inner.height < 4 || self.steps.is_empty() {
159 return;
160 }
161 let levels = self.levels();
162 let mut lo = 0f64.min(self.initial);
163 let mut hi = 0f64.max(self.initial);
164 for (s, e, _) in &levels {
165 lo = lo.min(*s).min(*e);
166 hi = hi.max(*s).max(*e);
167 }
168 if !(hi - lo).is_finite() || hi <= lo {
169 hi = lo + 1.0;
170 }
171 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
172 let text = self
173 .theme
174 .as_ref()
175 .map_or(Style::default(), |t| t.label_style());
176 let ticks = nice_ticks(lo, hi, (inner.height as usize / 3).max(2));
177 let tstep = if ticks.len() >= 2 {
178 ticks[1] - ticks[0]
179 } else {
180 1.0
181 };
182 let labels: Vec<String> = ticks.iter().map(|v| format_tick(*v, tstep)).collect();
183 let lw = labels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16;
184 let gutter = (lw + 1).min(inner.width / 2);
185 let plot = Rect::new(
187 inner.x + gutter,
188 inner.y + 1,
189 inner.width - gutter,
190 inner.height - 2,
191 );
192 if plot.width == 0 || plot.height == 0 {
193 return;
194 }
195 let row = |v: f64| -> u16 {
196 let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
197 plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16
198 };
199 for (v, l) in ticks.iter().zip(&labels) {
200 let y = row(*v);
201 let w = l.chars().count() as u16;
202 put_str(
203 buf,
204 inner.x + gutter.saturating_sub(w + 1),
205 y,
206 plot.x,
207 l,
208 dim,
209 );
210 }
211 for v in &ticks {
213 let y = row(*v);
214 for x in (plot.x..plot.right()).step_by(2) {
215 buf[(x, y)].set_char('·').set_style(dim);
216 }
217 }
218 if lo < 0.0 && hi > 0.0 {
220 let y = row(0.0);
221 for x in plot.x..plot.right() {
222 buf[(x, y)].set_char('─').set_style(dim);
223 }
224 }
225
226 let n = self.steps.len();
227 let slot = plot.width as f64 / n as f64;
228 let mut prev_end: Option<(f64, u16)> = None; for (i, ((s, e, is_total), step)) in levels.iter().zip(&self.steps).enumerate() {
230 let x0 = plot.x + (i as f64 * slot).floor() as u16;
231 let x1 = plot.x + (((i + 1) as f64 * slot).floor() as u16).max(x0 - plot.x + 1);
232 let x1 = x1.min(plot.right());
233 if x0 >= x1 {
234 continue;
235 }
236 let slot_w = x1 - x0;
237 let bw = if slot_w >= 3 { slot_w - 1 } else { slot_w };
238 let th = self.theme.as_ref();
239 let color = if *is_total {
240 self.total
241 .unwrap_or_else(|| th.map_or(Color::Blue, |t| t.neutral))
242 } else if e >= s {
243 self.up
244 .unwrap_or_else(|| th.map_or(Color::Green, |t| t.bull))
245 } else {
246 self.down
247 .unwrap_or_else(|| th.map_or(Color::Red, |t| t.bear))
248 };
249 let st = Style::default().fg(color);
250 let (ra, rb) = (row(*s), row(*e));
251 let (top, bot) = (ra.min(rb), ra.max(rb));
252 if self.connectors
253 && let Some((lvl, px)) = prev_end
254 {
255 let y = row(lvl);
256 if let (Some(m), true) = (self.marker, x0 > px) {
257 let mut cv = Canvas::new(x0 - px, 1, m);
258 let py = cv.px_h() / 2;
259 for dx in 0..cv.px_w() {
260 cv.set(dx, py, dim.fg.unwrap_or(Color::Reset));
261 }
262 cv.render(buf, Rect::new(px, y, x0 - px, 1));
263 } else {
264 for x in px..x0 {
265 buf[(x, y)].set_char('┄').set_style(dim);
266 }
267 }
268 }
269 for y in top..=bot {
270 for x in x0..x0 + bw {
271 buf[(x, y)].set_char('█').set_style(st);
272 }
273 }
274 crate::interact::record_point(Rect::new(x0, top, bw, bot - top + 1), 0, i, || {
275 let line = if *is_total {
276 format!("total {}", format_compact(*e))
277 } else {
278 format!("{} → {}", format_compact(*s), format_compact(*e))
279 };
280 let mut lines = vec![line];
281 if !*is_total {
282 lines.push(format!("change {}", format_compact(e - s)));
283 }
284 (step.label.clone(), lines)
285 });
286 prev_end = Some((*e, x0 + bw));
287 if self.show_values {
288 let v = if *is_total {
289 format_compact(*e)
290 } else if e >= s {
291 format!("+{}", format_compact(e - s))
292 } else {
293 format_compact(e - s)
294 };
295 let vw = v.chars().count() as u16;
296 let off = bw.saturating_sub(vw) / 2;
297 let ty = if top > plot.y {
298 Some(top - 1)
299 } else if inner.y < plot.y {
300 Some(inner.y)
301 } else {
302 None
303 };
304 if let Some(y) = ty {
305 put_str(buf, x0 + off, y, x1, &v, st);
306 }
307 }
308 let l: String = step.label.chars().take(slot_w as usize).collect();
309 let lx = x0 + bw.saturating_sub(l.chars().count() as u16) / 2;
310 put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text);
311 }
312 }
313}
314
315widget_impls!(Waterfall);
316
317#[cfg(feature = "theme")]
318impl tui_nuances::Themed for Waterfall {
319 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
320 self.theme(theme)
321 }
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327 use ratatui::widgets::Widget;
328
329 fn render(w: &Waterfall, width: u16, height: u16) -> Buffer {
330 let area = Rect::new(0, 0, width, height);
331 let mut buf = Buffer::empty(area);
332 w.render(area, &mut buf);
333 buf
334 }
335
336 fn sample() -> Waterfall {
337 Waterfall::new()
338 .delta("Sales", 100.0)
339 .delta("Cost", -40.0)
340 .total("Net")
341 }
342
343 #[test]
344 fn running_total() {
345 let l = sample().levels();
346 assert_eq!(
347 l,
348 vec![(0.0, 100.0, false), (100.0, 60.0, false), (0.0, 60.0, true)]
349 );
350 }
351
352 #[test]
353 fn colors_by_sign() {
354 let b = render(&sample(), 40, 14);
355 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
356 assert!(fg(Color::Green) && fg(Color::Red) && fg(Color::Blue));
357 assert!(b.content().iter().any(|x| x.symbol() == "┄"));
358 }
359
360 #[cfg(feature = "theme")]
361 #[test]
362 fn theme_colors_and_override() {
363 let t = Theme::dracula();
364 let b = render(&sample().theme(&t), 40, 14);
365 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
366 assert!(fg(t.bull) && fg(t.bear) && fg(t.neutral));
367 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
368 let b = render(
369 &sample()
370 .theme(&t)
371 .colors(Color::Yellow, Color::Magenta, Color::White),
372 40,
373 14,
374 );
375 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
376 assert!(fg(Color::Yellow) && fg(Color::Magenta) && fg(Color::White));
377 assert!(!fg(t.bull));
378 }
379
380 #[test]
381 fn tiny_and_empty_no_panic() {
382 let w = sample().delta("nan", f64::NAN).block(Block::bordered());
383 for x in 0..8 {
384 for y in 0..6 {
385 render(&w, x, y);
386 }
387 }
388 render(&Waterfall::new(), 10, 5);
389 }
390}