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)]
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 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 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 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 pub fn initial(mut self, v: f64) -> Self {
87 self.initial = if v.is_finite() { v } else { 0.0 };
88 self
89 }
90
91 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 theme
103 );
104
105 base_style_setter!(base);
106
107 opt_setter!(
108 marker: Marker
111 );
112
113 setter!(
114 connectors: bool
116 );
117
118 setter!(
119 show_values: bool
121 );
122
123 block_setter!(block, 'static);
124
125 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 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 if lo < 0.0 && hi > 0.0 {
201 let y = row(0.0);
202 for x in plot.x..plot.right() {
203 buf[(x, y)].set_char('─').set_style(dim);
204 }
205 }
206
207 let n = self.steps.len();
208 let slot = plot.width as f64 / n as f64;
209 let mut prev_end: Option<(f64, u16)> = None; for (i, ((s, e, is_total), step)) in levels.iter().zip(&self.steps).enumerate() {
211 let x0 = plot.x + (i as f64 * slot).floor() as u16;
212 let x1 = plot.x + (((i + 1) as f64 * slot).floor() as u16).max(x0 - plot.x + 1);
213 let x1 = x1.min(plot.right());
214 if x0 >= x1 {
215 continue;
216 }
217 let slot_w = x1 - x0;
218 let bw = if slot_w >= 3 { slot_w - 1 } else { slot_w };
219 let th = self.theme.as_ref();
220 let color = if *is_total {
221 self.total
222 .unwrap_or_else(|| th.map_or(Color::Blue, |t| t.neutral))
223 } else if e >= s {
224 self.up
225 .unwrap_or_else(|| th.map_or(Color::Green, |t| t.bull))
226 } else {
227 self.down
228 .unwrap_or_else(|| th.map_or(Color::Red, |t| t.bear))
229 };
230 let st = Style::default().fg(color);
231 let (ra, rb) = (row(*s), row(*e));
232 let (top, bot) = (ra.min(rb), ra.max(rb));
233 if self.connectors {
234 if let Some((lvl, px)) = prev_end {
235 let y = row(lvl);
236 if let (Some(m), true) = (self.marker, x0 > px) {
237 let mut cv = Canvas::new(x0 - px, 1, m);
238 let py = cv.px_h() / 2;
239 for dx in 0..cv.px_w() {
240 cv.set(dx, py, dim.fg.unwrap_or(Color::Reset));
241 }
242 cv.render(buf, Rect::new(px, y, x0 - px, 1));
243 } else {
244 for x in px..x0 {
245 buf[(x, y)].set_char('┄').set_style(dim);
246 }
247 }
248 }
249 }
250 for y in top..=bot {
251 for x in x0..x0 + bw {
252 buf[(x, y)].set_char('█').set_style(st);
253 }
254 }
255 prev_end = Some((*e, x0 + bw));
256 if self.show_values {
257 let v = if *is_total {
258 format_compact(*e)
259 } else if e >= s {
260 format!("+{}", format_compact(e - s))
261 } else {
262 format_compact(e - s)
263 };
264 let vw = v.chars().count() as u16;
265 let off = bw.saturating_sub(vw) / 2;
266 let ty = if top > plot.y {
267 Some(top - 1)
268 } else if inner.y < plot.y {
269 Some(inner.y)
270 } else {
271 None
272 };
273 if let Some(y) = ty {
274 put_str(buf, x0 + off, y, x1, &v, st);
275 }
276 }
277 let l: String = step.label.chars().take(slot_w as usize).collect();
278 put_str(buf, x0, inner.bottom() - 1, inner.right(), &l, text);
279 }
280 }
281}
282
283widget_impls!(Waterfall);
284
285#[cfg(feature = "theme")]
286impl tui_nuances::Themed for Waterfall {
287 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
288 self.theme(theme)
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295 use ratatui::widgets::Widget;
296
297 fn render(w: &Waterfall, width: u16, height: u16) -> Buffer {
298 let area = Rect::new(0, 0, width, height);
299 let mut buf = Buffer::empty(area);
300 w.render(area, &mut buf);
301 buf
302 }
303
304 fn sample() -> Waterfall {
305 Waterfall::new()
306 .delta("Sales", 100.0)
307 .delta("Cost", -40.0)
308 .total("Net")
309 }
310
311 #[test]
312 fn running_total() {
313 let l = sample().levels();
314 assert_eq!(
315 l,
316 vec![(0.0, 100.0, false), (100.0, 60.0, false), (0.0, 60.0, true)]
317 );
318 }
319
320 #[test]
321 fn colors_by_sign() {
322 let b = render(&sample(), 40, 14);
323 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
324 assert!(fg(Color::Green) && fg(Color::Red) && fg(Color::Blue));
325 assert!(b.content().iter().any(|x| x.symbol() == "┄"));
326 }
327
328 #[cfg(feature = "theme")]
329 #[test]
330 fn theme_colors_and_override() {
331 let t = Theme::dracula();
332 let b = render(&sample().theme(&t), 40, 14);
333 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
334 assert!(fg(t.bull) && fg(t.bear) && fg(t.neutral));
335 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
336 let b = render(
337 &sample()
338 .theme(&t)
339 .colors(Color::Yellow, Color::Magenta, Color::White),
340 40,
341 14,
342 );
343 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "█" && x.fg == c);
344 assert!(fg(Color::Yellow) && fg(Color::Magenta) && fg(Color::White));
345 assert!(!fg(t.bull));
346 }
347
348 #[test]
349 fn tiny_and_empty_no_panic() {
350 let w = sample().delta("nan", f64::NAN).block(Block::bordered());
351 for x in 0..8 {
352 for y in 0..6 {
353 render(&w, x, y);
354 }
355 }
356 render(&Waterfall::new(), 10, 5);
357 }
358}