Skip to main content

tui_chart/
funnel.rs

1//! Funnel: stages narrowing from the largest value, with conversion percentages.
2
3use crate::text::put_str;
4use crate::theme::{self, Theme};
5use crate::util::{darken, format_compact};
6use crate::PALETTE;
7use ratatui::{
8    buffer::Buffer,
9    layout::Rect,
10    style::{Color, Style},
11    widgets::Block,
12};
13
14/// One funnel stage.
15#[derive(Debug, Clone, PartialEq)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct FunnelStage {
18    /// Stage label.
19    pub label: String,
20    /// Stage value (non-finite / negative values count as 0).
21    pub value: f64,
22    /// Explicit color.
23    pub color: Option<Color>,
24}
25
26impl FunnelStage {
27    /// Create a stage.
28    pub fn new(label: impl Into<String>, value: f64) -> Self {
29        Self {
30            label: label.into(),
31            value,
32            color: None,
33        }
34    }
35
36    /// Explicit stage color.
37    pub fn color(mut self, c: Color) -> Self {
38        self.color = Some(c);
39        self
40    }
41}
42
43/// Funnel chart widget: centered bars whose width follows the value.
44#[derive(Debug, Clone, Default)]
45pub struct Funnel {
46    stages: Vec<FunnelStage>,
47    theme: Option<Theme>,
48    base: Option<Style>,
49    show_percent: bool,
50    show_dropoff: bool,
51    taper: bool,
52    block: Option<Block<'static>>,
53}
54
55impl Funnel {
56    /// Create a funnel from stages (first stage is the 100 % reference).
57    pub fn new(stages: impl IntoIterator<Item = FunnelStage>) -> Self {
58        Self {
59            stages: stages.into_iter().collect(),
60            theme: None,
61            base: None,
62            show_percent: true,
63            show_dropoff: true,
64            taper: true,
65            block: None,
66        }
67    }
68
69    setter!(
70        /// Show conversion percentage vs. the first stage (default on).
71        show_percent: bool
72    );
73
74    setter!(
75        /// Show the drop-off vs. the previous stage (default on).
76        show_dropoff: bool
77    );
78
79    setter!(
80        /// Connect stages into one tapering funnel (default on); off draws separate bars.
81        taper: bool
82    );
83
84    theme_setter!(
85        /// Apply a [`Theme`]; explicit stage colors win.
86        theme
87    );
88
89    base_style_setter!(base);
90
91    block_setter!(block, 'static);
92
93    /// Conversion of each stage relative to the first (0..=1; 0 if the first is 0).
94    pub fn conversions(&self) -> Vec<f64> {
95        let v = |s: &FunnelStage| {
96            if s.value.is_finite() {
97                s.value.max(0.0)
98            } else {
99                0.0
100            }
101        };
102        let first = self.stages.first().map_or(0.0, v);
103        self.stages
104            .iter()
105            .map(|s| if first > 0.0 { v(s) / first } else { 0.0 })
106            .collect()
107    }
108
109    fn render_into(&self, area: Rect, buf: &mut Buffer) {
110        let area = area.intersection(buf.area);
111        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
112        if inner.width < 6 || inner.height == 0 || self.stages.is_empty() {
113            return;
114        }
115        let n = self.stages.len() as u16;
116        let rows_each = (inner.height / n).max(1);
117        let text = self
118            .theme
119            .as_ref()
120            .map_or(Style::default(), |t| t.label_style());
121        let dim = Style::default().fg(darken(
122            self.theme.as_ref().map_or(Color::Gray, |t| t.foreground),
123            0.4,
124        ));
125        let vals: Vec<f64> = self
126            .stages
127            .iter()
128            .map(|s| {
129                if s.value.is_finite() {
130                    s.value.max(0.0)
131                } else {
132                    0.0
133                }
134            })
135            .collect();
136        let max = vals.iter().copied().fold(0.0, f64::max);
137        let conv = self.conversions();
138
139        // Columns: [labels] [funnel] [value + percent + drop-off]. Side columns
140        // are dropped on narrow areas, falling back to centered labels.
141        let label_w = (self
142            .stages
143            .iter()
144            .map(|s| s.label.chars().count())
145            .max()
146            .unwrap_or(0) as u16
147            + 2)
148        .min(inner.width / 4);
149        let stat_w: u16 = if self.show_percent { 16 } else { 8 };
150        let side = inner.width >= label_w + stat_w + 16;
151        let (fx, fw) = if side {
152            (inner.x + label_w, inner.width - label_w - stat_w)
153        } else {
154            (inner.x, inner.width)
155        };
156        let center = fx as f64 + fw as f64 / 2.0;
157
158        for (i, st) in self.stages.iter().enumerate() {
159            let y0 = inner.y as u32 + i as u32 * rows_each as u32;
160            if y0 >= inner.bottom() as u32 {
161                break;
162            }
163            let h = (rows_each as u32).min(inner.bottom() as u32 - y0) as u16;
164            let color = st.color.unwrap_or_else(|| {
165                self.theme
166                    .as_ref()
167                    .map_or(PALETTE[i % PALETTE.len()], |t| t.color(i))
168            });
169            let frac = |v: f64| if max > 0.0 { v / max } else { 0.0 };
170            let top_w = (frac(vals[i]) * fw as f64).max(1.0);
171            // bottom edge meets the next stage's top; the last stage narrows to a neck
172            let bot_w = if !self.taper {
173                top_w
174            } else if let Some(nv) = vals.get(i + 1) {
175                (frac(*nv) * fw as f64).max(1.0)
176            } else {
177                (top_w * 0.7).max(1.0)
178            };
179            let bar_h = if self.taper || rows_each <= 2 {
180                h
181            } else {
182                h - 1
183            };
184            for r in 0..bar_h {
185                let t = (r as f64 + 0.5) / bar_h as f64;
186                let w = top_w + (bot_w - top_w) * t;
187                let (l, rt) = (center - w / 2.0, center + w / 2.0);
188                let y = y0 as u16 + r;
189                let first = (l.floor() as i64).max(fx as i64) as u16;
190                let last = ((rt.ceil() as i64).min((fx + fw) as i64) - 1).max(first as i64) as u16;
191                for x in first..=last.min(fx + fw - 1) {
192                    let cover_l = (x as f64).max(l);
193                    let cover_r = (x as f64 + 1.0).min(rt);
194                    let cover = (cover_r - cover_l).max(0.0);
195                    let cell = &mut buf[(x, y)];
196                    if cover >= 0.75 {
197                        cell.set_char('█').set_fg(color);
198                    } else if cover >= 0.25 {
199                        // partial edge cell: half block on the side that is covered
200                        let left_side = (x as f64) < l + 0.5 && l > x as f64;
201                        cell.set_char(if left_side { '▐' } else { '▌' })
202                            .set_fg(color);
203                    }
204                }
205            }
206
207            // value / percent / drop-off (side) or centered label (narrow)
208            let mid = y0 as u16 + bar_h.saturating_sub(1) / 2;
209            if side {
210                put_str(buf, inner.x, mid, fx, &st.label, text);
211                let mut stat = format_compact(vals[i]);
212                if self.show_percent {
213                    stat.push_str(&format!("  {:>3.0}%", conv[i] * 100.0));
214                }
215                put_str(buf, fx + fw + 1, mid, inner.right(), &stat, text);
216                if self.show_percent && self.show_dropoff && i > 0 && vals[i - 1] > 0.0 {
217                    let drop = (1.0 - vals[i] / vals[i - 1]) * 100.0;
218                    if h > 1 {
219                        let dy = y0 as u16;
220                        if dy != mid {
221                            put_str(
222                                buf,
223                                fx + fw + 1,
224                                dy,
225                                inner.right(),
226                                &format!("▼ {drop:.0}%"),
227                                dim,
228                            );
229                        }
230                    }
231                }
232            } else {
233                let mut label = format!("{} {}", st.label, format_compact(vals[i]));
234                if self.show_percent {
235                    label.push_str(&format!(" ({:.0}%)", conv[i] * 100.0));
236                }
237                let lw = label.chars().count() as u16;
238                let lx = inner.x + inner.width.saturating_sub(lw) / 2;
239                let on_bar = (lw as f64) <= top_w.min(bot_w);
240                let style = if on_bar {
241                    Style::default().fg(Color::Black).bg(color)
242                } else {
243                    text
244                };
245                put_str(buf, lx, mid, inner.right(), &label, style);
246            }
247        }
248    }
249}
250
251widget_impls!(Funnel);
252
253#[cfg(feature = "theme")]
254impl tui_nuances::Themed for Funnel {
255    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
256        self.theme(theme)
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use ratatui::widgets::Widget;
264
265    fn funnel() -> Funnel {
266        Funnel::new([
267            FunnelStage::new("Visits", 1000.0),
268            FunnelStage::new("Signups", 400.0),
269            FunnelStage::new("Paid", 100.0),
270        ])
271    }
272
273    #[test]
274    fn conversions_relative_to_first() {
275        assert_eq!(funnel().conversions(), vec![1.0, 0.4, 0.1]);
276        assert_eq!(
277            Funnel::new([FunnelStage::new("a", 0.0)]).conversions(),
278            vec![0.0]
279        );
280    }
281
282    #[test]
283    fn renders_labels_and_percent() {
284        let area = Rect::new(0, 0, 50, 9);
285        let mut b = Buffer::empty(area);
286        funnel().render(area, &mut b);
287        let all: String = b.content().iter().map(|c| c.symbol()).collect();
288        assert!(all.contains("Visits") && all.contains("40%") && all.contains("10%"));
289    }
290
291    #[test]
292    fn degenerate_inputs_do_not_panic() {
293        let mut b = Buffer::empty(Rect::new(0, 0, 3, 1));
294        funnel().render(Rect::new(0, 0, 3, 1), &mut b);
295        funnel().render(Rect::new(0, 0, 0, 0), &mut b);
296        Funnel::new([FunnelStage::new("x", f64::NAN)]).render(Rect::new(0, 0, 3, 1), &mut b);
297        let mut b = Buffer::empty(Rect::new(0, 0, 30, 2));
298        funnel().render(Rect::new(0, 0, 30, 2), &mut b);
299    }
300
301    fn text(b: &Buffer) -> String {
302        b.content().iter().map(|c| c.symbol()).collect()
303    }
304
305    fn draw(f: Funnel, w: u16, h: u16) -> Buffer {
306        let a = Rect::new(0, 0, w, h);
307        let mut b = Buffer::empty(a);
308        f.render(a, &mut b);
309        b
310    }
311
312    #[test]
313    fn dropoff_toggle() {
314        let on = text(&draw(funnel(), 60, 9));
315        let off = text(&draw(funnel().show_dropoff(false), 60, 9));
316        assert!(on.contains('▼') && !off.contains('▼'));
317    }
318
319    #[test]
320    fn percent_toggle() {
321        let off = text(&draw(funnel().show_percent(false), 60, 9));
322        assert!(!off.contains("40%"));
323    }
324
325    #[test]
326    fn taper_changes_output_and_custom_color_applies() {
327        let f = || funnel();
328        assert_ne!(
329            text(&draw(f().taper(false), 60, 9)),
330            text(&draw(f().taper(true), 60, 9))
331        );
332        let b = draw(
333            Funnel::new([FunnelStage::new("a", 5.0).color(Color::Red)]),
334            40,
335            4,
336        );
337        assert!(b
338            .content()
339            .iter()
340            .any(|c| c.fg == Color::Red || c.bg == Color::Red));
341    }
342
343    #[test]
344    fn narrow_and_tiny_areas_do_not_panic() {
345        for (w, h) in [(0, 0), (1, 1), (5, 2), (12, 3), (200, 40)] {
346            draw(funnel(), w, h);
347            draw(funnel().taper(false).show_dropoff(false), w, h);
348        }
349    }
350}