Skip to main content

tui_chart/
waterfall.rs

1//! Waterfall: delta steps with a running total.
2
3use 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/// Waterfall chart widget.
27#[derive(Debug, Clone)]
28pub struct Waterfall {
29    steps: Vec<Step>,
30    initial: f64,
31    up: Option<Color>,
32    down: Option<Color>,
33    total: Option<Color>,
34    theme: Option<Theme>,
35    base: Option<Style>,
36    connectors: bool,
37    marker: Option<Marker>,
38    show_values: bool,
39    block: Option<Block<'static>>,
40}
41
42impl Default for Waterfall {
43    fn default() -> Self {
44        Self::new()
45    }
46}
47
48impl Waterfall {
49    /// Empty chart starting at 0.
50    pub fn new() -> Self {
51        Self {
52            steps: vec![],
53            initial: 0.0,
54            up: None,
55            down: None,
56            total: None,
57            theme: None,
58            base: None,
59            connectors: true,
60            marker: None,
61            show_values: true,
62            block: None,
63        }
64    }
65
66    /// Add a delta step (non-finite deltas count as 0).
67    pub fn delta(mut self, label: impl Into<String>, v: f64) -> Self {
68        let v = if v.is_finite() { v } else { 0.0 };
69        self.steps.push(Step {
70            label: label.into(),
71            kind: Kind::Delta(v),
72        });
73        self
74    }
75
76    /// Add a total bar showing the running total so far.
77    pub fn total(mut self, label: impl Into<String>) -> Self {
78        self.steps.push(Step {
79            label: label.into(),
80            kind: Kind::Total,
81        });
82        self
83    }
84
85    /// Starting value of the running total (default 0).
86    pub fn initial(mut self, v: f64) -> Self {
87        self.initial = if v.is_finite() { v } else { 0.0 };
88        self
89    }
90
91    /// Colors for increases, decreases and totals.
92    pub fn colors(mut self, up: Color, down: Color, total: Color) -> Self {
93        self.up = Some(up);
94        self.down = Some(down);
95        self.total = Some(total);
96        self
97    }
98
99    theme_setter!(
100        /// Apply a [`Theme`]: bull/bear/neutral bar colors, axis/label colors and
101        /// background fill. Explicit [`Waterfall::colors`] win.
102        theme
103    );
104
105    base_style_setter!(base);
106
107    opt_setter!(
108        /// Draw connectors as dot lines (e.g. [`Marker::Braille`], a thin
109        /// sub-cell line at the exact level) instead of `┄` (the default).
110        marker: Marker
111    );
112
113    setter!(
114        /// Draw connector lines between bars (default on).
115        connectors: bool
116    );
117
118    setter!(
119        /// Print values above/below bars (default on).
120        show_values: bool
121    );
122
123    block_setter!(block, 'static);
124
125    /// Bars as `(start, end, is_total)` with the running total applied.
126    pub fn levels(&self) -> Vec<(f64, f64, bool)> {
127        let mut run = self.initial;
128        self.steps
129            .iter()
130            .map(|s| match s.kind {
131                Kind::Delta(d) => {
132                    let start = run;
133                    run += d;
134                    (start, run, false)
135                }
136                Kind::Total => (0.0, run, true),
137            })
138            .collect()
139    }
140}
141
142impl Waterfall {
143    fn render_into(&self, area: Rect, buf: &mut Buffer) {
144        let area = area.intersection(buf.area);
145        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
146        if inner.width < 4 || inner.height < 4 || self.steps.is_empty() {
147            return;
148        }
149        let levels = self.levels();
150        let mut lo = 0f64.min(self.initial);
151        let mut hi = 0f64.max(self.initial);
152        for (s, e, _) in &levels {
153            lo = lo.min(*s).min(*e);
154            hi = hi.max(*s).max(*e);
155        }
156        if !(hi - lo).is_finite() || hi <= lo {
157            hi = lo + 1.0;
158        }
159        let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
160        let text = self
161            .theme
162            .as_ref()
163            .map_or(Style::default(), |t| t.label_style());
164        let ticks = nice_ticks(lo, hi, (inner.height as usize / 3).max(2));
165        let tstep = if ticks.len() >= 2 {
166            ticks[1] - ticks[0]
167        } else {
168            1.0
169        };
170        let labels: Vec<String> = ticks.iter().map(|v| format_tick(*v, tstep)).collect();
171        let lw = labels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16;
172        let gutter = (lw + 1).min(inner.width / 2);
173        // Top row reserved for value labels, bottom row for step labels.
174        let plot = Rect::new(
175            inner.x + gutter,
176            inner.y + 1,
177            inner.width - gutter,
178            inner.height - 2,
179        );
180        if plot.width == 0 || plot.height == 0 {
181            return;
182        }
183        let row = |v: f64| -> u16 {
184            let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
185            plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16
186        };
187        for (v, l) in ticks.iter().zip(&labels) {
188            let y = row(*v);
189            let w = l.chars().count() as u16;
190            put_str(
191                buf,
192                inner.x + gutter.saturating_sub(w + 1),
193                y,
194                plot.x,
195                l,
196                dim,
197            );
198        }
199        // faint horizontal grid at each tick (under the bars)
200        for v in &ticks {
201            let y = row(*v);
202            for x in (plot.x..plot.right()).step_by(2) {
203                buf[(x, y)].set_char('·').set_style(dim);
204            }
205        }
206        // zero line
207        if lo < 0.0 && hi > 0.0 {
208            let y = row(0.0);
209            for x in plot.x..plot.right() {
210                buf[(x, y)].set_char('─').set_style(dim);
211            }
212        }
213
214        let n = self.steps.len();
215        let slot = plot.width as f64 / n as f64;
216        let mut prev_end: Option<(f64, u16)> = None; // (level, right edge x)
217        for (i, ((s, e, is_total), step)) in levels.iter().zip(&self.steps).enumerate() {
218            let x0 = plot.x + (i as f64 * slot).floor() as u16;
219            let x1 = plot.x + (((i + 1) as f64 * slot).floor() as u16).max(x0 - plot.x + 1);
220            let x1 = x1.min(plot.right());
221            if x0 >= x1 {
222                continue;
223            }
224            let slot_w = x1 - x0;
225            let bw = if slot_w >= 3 { slot_w - 1 } else { slot_w };
226            let th = self.theme.as_ref();
227            let color = if *is_total {
228                self.total
229                    .unwrap_or_else(|| th.map_or(Color::Blue, |t| t.neutral))
230            } else if e >= s {
231                self.up
232                    .unwrap_or_else(|| th.map_or(Color::Green, |t| t.bull))
233            } else {
234                self.down
235                    .unwrap_or_else(|| th.map_or(Color::Red, |t| t.bear))
236            };
237            let st = Style::default().fg(color);
238            let (ra, rb) = (row(*s), row(*e));
239            let (top, bot) = (ra.min(rb), ra.max(rb));
240            if self.connectors {
241                if let Some((lvl, px)) = prev_end {
242                    let y = row(lvl);
243                    if let (Some(m), true) = (self.marker, x0 > px) {
244                        let mut cv = Canvas::new(x0 - px, 1, m);
245                        let py = cv.px_h() / 2;
246                        for dx in 0..cv.px_w() {
247                            cv.set(dx, py, dim.fg.unwrap_or(Color::Reset));
248                        }
249                        cv.render(buf, Rect::new(px, y, x0 - px, 1));
250                    } else {
251                        for x in px..x0 {
252                            buf[(x, y)].set_char('┄').set_style(dim);
253                        }
254                    }
255                }
256            }
257            for y in top..=bot {
258                for x in x0..x0 + bw {
259                    buf[(x, y)].set_char('█').set_style(st);
260                }
261            }
262            prev_end = Some((*e, x0 + bw));
263            if self.show_values {
264                let v = if *is_total {
265                    format_compact(*e)
266                } else if e >= s {
267                    format!("+{}", format_compact(e - s))
268                } else {
269                    format_compact(e - s)
270                };
271                let vw = v.chars().count() as u16;
272                let off = bw.saturating_sub(vw) / 2;
273                let ty = if top > plot.y {
274                    Some(top - 1)
275                } else if inner.y < plot.y {
276                    Some(inner.y)
277                } else {
278                    None
279                };
280                if let Some(y) = ty {
281                    put_str(buf, x0 + off, y, x1, &v, st);
282                }
283            }
284            let l: String = step.label.chars().take(slot_w as usize).collect();
285            let lx = x0 + bw.saturating_sub(l.chars().count() as u16) / 2;
286            put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text);
287        }
288    }
289}
290
291widget_impls!(Waterfall);
292
293#[cfg(feature = "theme")]
294impl tui_nuances::Themed for Waterfall {
295    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
296        self.theme(theme)
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use ratatui::widgets::Widget;
304
305    fn render(w: &Waterfall, width: u16, height: u16) -> Buffer {
306        let area = Rect::new(0, 0, width, height);
307        let mut buf = Buffer::empty(area);
308        w.render(area, &mut buf);
309        buf
310    }
311
312    fn sample() -> Waterfall {
313        Waterfall::new()
314            .delta("Sales", 100.0)
315            .delta("Cost", -40.0)
316            .total("Net")
317    }
318
319    #[test]
320    fn running_total() {
321        let l = sample().levels();
322        assert_eq!(
323            l,
324            vec![(0.0, 100.0, false), (100.0, 60.0, false), (0.0, 60.0, true)]
325        );
326    }
327
328    #[test]
329    fn colors_by_sign() {
330        let b = render(&sample(), 40, 14);
331        let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
332        assert!(fg(Color::Green) && fg(Color::Red) && fg(Color::Blue));
333        assert!(b.content().iter().any(|x| x.symbol() == "┄"));
334    }
335
336    #[cfg(feature = "theme")]
337    #[test]
338    fn theme_colors_and_override() {
339        let t = Theme::dracula();
340        let b = render(&sample().theme(&t), 40, 14);
341        let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
342        assert!(fg(t.bull) && fg(t.bear) && fg(t.neutral));
343        assert_eq!(b[(0, 0)].bg, t.background.unwrap());
344        let b = render(
345            &sample()
346                .theme(&t)
347                .colors(Color::Yellow, Color::Magenta, Color::White),
348            40,
349            14,
350        );
351        let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
352        assert!(fg(Color::Yellow) && fg(Color::Magenta) && fg(Color::White));
353        assert!(!fg(t.bull));
354    }
355
356    #[test]
357    fn tiny_and_empty_no_panic() {
358        let w = sample().delta("nan", f64::NAN).block(Block::bordered());
359        for x in 0..8 {
360            for y in 0..6 {
361                render(&w, x, y);
362            }
363        }
364        render(&Waterfall::new(), 10, 5);
365    }
366}