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 if let Some((lvl, px)) = prev_end {
254 let y = row(lvl);
255 if let (Some(m), true) = (self.marker, x0 > px) {
256 let mut cv = Canvas::new(x0 - px, 1, m);
257 let py = cv.px_h() / 2;
258 for dx in 0..cv.px_w() {
259 cv.set(dx, py, dim.fg.unwrap_or(Color::Reset));
260 }
261 cv.render(buf, Rect::new(px, y, x0 - px, 1));
262 } else {
263 for x in px..x0 {
264 buf[(x, y)].set_char('┄').set_style(dim);
265 }
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 prev_end = Some((*e, x0 + bw));
275 if self.show_values {
276 let v = if *is_total {
277 format_compact(*e)
278 } else if e >= s {
279 format!("+{}", format_compact(e - s))
280 } else {
281 format_compact(e - s)
282 };
283 let vw = v.chars().count() as u16;
284 let off = bw.saturating_sub(vw) / 2;
285 let ty = if top > plot.y {
286 Some(top - 1)
287 } else if inner.y < plot.y {
288 Some(inner.y)
289 } else {
290 None
291 };
292 if let Some(y) = ty {
293 put_str(buf, x0 + off, y, x1, &v, st);
294 }
295 }
296 let l: String = step.label.chars().take(slot_w as usize).collect();
297 let lx = x0 + bw.saturating_sub(l.chars().count() as u16) / 2;
298 put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text);
299 }
300 }
301}
302
303widget_impls!(Waterfall);
304
305#[cfg(feature = "theme")]
306impl tui_nuances::Themed for Waterfall {
307 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
308 self.theme(theme)
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315 use ratatui::widgets::Widget;
316
317 fn render(w: &Waterfall, width: u16, height: u16) -> Buffer {
318 let area = Rect::new(0, 0, width, height);
319 let mut buf = Buffer::empty(area);
320 w.render(area, &mut buf);
321 buf
322 }
323
324 fn sample() -> Waterfall {
325 Waterfall::new()
326 .delta("Sales", 100.0)
327 .delta("Cost", -40.0)
328 .total("Net")
329 }
330
331 #[test]
332 fn running_total() {
333 let l = sample().levels();
334 assert_eq!(
335 l,
336 vec![(0.0, 100.0, false), (100.0, 60.0, false), (0.0, 60.0, true)]
337 );
338 }
339
340 #[test]
341 fn colors_by_sign() {
342 let b = render(&sample(), 40, 14);
343 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
344 assert!(fg(Color::Green) && fg(Color::Red) && fg(Color::Blue));
345 assert!(b.content().iter().any(|x| x.symbol() == "┄"));
346 }
347
348 #[cfg(feature = "theme")]
349 #[test]
350 fn theme_colors_and_override() {
351 let t = Theme::dracula();
352 let b = render(&sample().theme(&t), 40, 14);
353 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
354 assert!(fg(t.bull) && fg(t.bear) && fg(t.neutral));
355 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
356 let b = render(
357 &sample()
358 .theme(&t)
359 .colors(Color::Yellow, Color::Magenta, Color::White),
360 40,
361 14,
362 );
363 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
364 assert!(fg(Color::Yellow) && fg(Color::Magenta) && fg(Color::White));
365 assert!(!fg(t.bull));
366 }
367
368 #[test]
369 fn tiny_and_empty_no_panic() {
370 let w = sample().delta("nan", f64::NAN).block(Block::bordered());
371 for x in 0..8 {
372 for y in 0..6 {
373 render(&w, x, y);
374 }
375 }
376 render(&Waterfall::new(), 10, 5);
377 }
378}