Skip to main content

tui_chart/
funnel.rs

1//! Funnel: stages narrowing from the largest value, with conversion percentages.
2
3use crate::PALETTE;
4use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::util::{darken, format_compact};
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///
45/// # Example
46///
47/// ```
48/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
49/// use tui_chart::{Funnel, FunnelStage};
50///
51/// let chart = Funnel::new([FunnelStage::new("Visits", 1000.0), FunnelStage::new("Signups", 240.0)]);
52/// let area = Rect::new(0, 0, 40, 12);
53/// let mut buf = Buffer::empty(area);
54/// chart.render(area, &mut buf);
55/// ```
56#[derive(Debug, Clone, Default)]
57pub struct Funnel {
58    stages: Vec<FunnelStage>,
59    theme: Option<Theme>,
60    base: Option<Style>,
61    show_percent: bool,
62    show_dropoff: bool,
63    taper: bool,
64    hidden: Vec<usize>,
65    block: Option<Block<'static>>,
66}
67
68impl Funnel {
69    /// Create a funnel from stages (first stage is the 100 % reference).
70    pub fn new(stages: impl IntoIterator<Item = FunnelStage>) -> Self {
71        Self {
72            stages: stages.into_iter().collect(),
73            theme: None,
74            base: None,
75            show_percent: true,
76            show_dropoff: true,
77            taper: true,
78            hidden: Vec::new(),
79            block: None,
80        }
81    }
82
83    setter!(
84        /// Show conversion percentage vs. the first stage (default on).
85        show_percent: bool
86    );
87
88    setter!(
89        /// Show the drop-off vs. the previous stage (default on).
90        show_dropoff: bool
91    );
92
93    setter!(
94        /// Connect stages into one tapering funnel (default on); off draws separate bars.
95        taper: bool
96    );
97
98    theme_setter!(
99        /// Apply a [`Theme`]; explicit stage colors win.
100        theme
101    );
102
103    base_style_setter!(base);
104
105    block_setter!(block, 'static);
106
107    /// Hide stages by index. The label stays (dimmed) so the stage can be
108    /// toggled back, see [`Interaction`](crate::Interaction).
109    #[must_use]
110    pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
111        self.hidden = hidden.into_iter().collect();
112        self
113    }
114
115    /// Conversion of each stage relative to the first (0..=1; 0 if the first is 0).
116    pub fn conversions(&self) -> Vec<f64> {
117        let v = |s: &FunnelStage| {
118            if s.value.is_finite() {
119                s.value.max(0.0)
120            } else {
121                0.0
122            }
123        };
124        let first = self.stages.first().map_or(0.0, v);
125        self.stages
126            .iter()
127            .map(|s| if first > 0.0 { v(s) / first } else { 0.0 })
128            .collect()
129    }
130
131    fn render_into(&self, area: Rect, buf: &mut Buffer) {
132        let area = area.intersection(buf.area);
133        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
134        if inner.width < 6 || inner.height == 0 || self.stages.is_empty() {
135            return;
136        }
137        let n = self.stages.len() as u16;
138        let rows_each = (inner.height / n).max(1);
139        let text = self
140            .theme
141            .as_ref()
142            .map_or(Style::default(), |t| t.label_style());
143        let dim = Style::default().fg(darken(
144            self.theme.as_ref().map_or(Color::Gray, |t| t.foreground),
145            0.4,
146        ));
147        let vals: Vec<f64> = self
148            .stages
149            .iter()
150            .enumerate()
151            .map(|(i, s)| {
152                if s.value.is_finite() && !self.hidden.contains(&i) {
153                    s.value.max(0.0)
154                } else {
155                    0.0
156                }
157            })
158            .collect();
159        let max = vals.iter().copied().fold(0.0, f64::max);
160        let conv: Vec<f64> = vals
161            .iter()
162            .map(|v| if vals[0] > 0.0 { v / vals[0] } else { 0.0 })
163            .collect();
164
165        // Columns: [labels] [funnel] [value + percent + drop-off]. Side columns
166        // are dropped on narrow areas, falling back to centered labels.
167        let label_w = (self
168            .stages
169            .iter()
170            .map(|s| s.label.chars().count())
171            .max()
172            .unwrap_or(0) as u16
173            + 2)
174        .min(inner.width / 4);
175        let stat_w: u16 = if self.show_percent { 16 } else { 8 };
176        let side = inner.width >= label_w + stat_w + 16;
177        let (fx, fw) = if side {
178            (inner.x + label_w, inner.width - label_w - stat_w)
179        } else {
180            (inner.x, inner.width)
181        };
182        let center = fx as f64 + fw as f64 / 2.0;
183
184        for (i, st) in self.stages.iter().enumerate() {
185            let y0 = inner.y as u32 + i as u32 * rows_each as u32;
186            if y0 >= inner.bottom() as u32 {
187                break;
188            }
189            let h = (rows_each as u32).min(inner.bottom() as u32 - y0) as u16;
190            let off = self.hidden.contains(&i);
191            let color = st.color.unwrap_or_else(|| {
192                self.theme
193                    .as_ref()
194                    .map_or(PALETTE[i % PALETTE.len()], |t| t.color(i))
195            });
196            let frac = |v: f64| if max > 0.0 { v / max } else { 0.0 };
197            let top_w = (frac(vals[i]) * fw as f64).max(1.0);
198            // bottom edge meets the next stage's top; the last stage narrows to a neck
199            let bot_w = if !self.taper {
200                top_w
201            } else if let Some(nv) = vals.get(i + 1) {
202                (frac(*nv) * fw as f64).max(1.0)
203            } else {
204                (top_w * 0.7).max(1.0)
205            };
206            let bar_h = if self.taper || rows_each <= 2 {
207                h
208            } else {
209                h - 1
210            };
211            for r in 0..if off { 0 } else { bar_h } {
212                let t = (r as f64 + 0.5) / bar_h as f64;
213                let w = top_w + (bot_w - top_w) * t;
214                let (l, rt) = (center - w / 2.0, center + w / 2.0);
215                let y = y0 as u16 + r;
216                let first = (l.floor() as i64).max(fx as i64) as u16;
217                let last = ((rt.ceil() as i64).min((fx + fw) as i64) - 1).max(first as i64) as u16;
218                for x in first..=last.min(fx + fw - 1) {
219                    let cover_l = (x as f64).max(l);
220                    let cover_r = (x as f64 + 1.0).min(rt);
221                    let cover = (cover_r - cover_l).max(0.0);
222                    let cell = &mut buf[(x, y)];
223                    if cover >= 0.75 {
224                        cell.set_char('█').set_fg(color);
225                    } else if cover >= 0.25 {
226                        // partial edge cell: half block on the side that is covered
227                        let left_side = (x as f64) < l + 0.5 && l > x as f64;
228                        cell.set_char(if left_side { '▐' } else { '▌' })
229                            .set_fg(color);
230                    }
231                }
232            }
233
234            let wmax = top_w.max(bot_w);
235            let hx = ((center - wmax / 2.0).floor().max(fx as f64)) as u16;
236            let hw = (wmax.ceil() as u16).min(fx + fw - hx).max(1);
237            if !off {
238                crate::interact::record_point(
239                    Rect::new(hx, y0 as u16, hw, bar_h.max(1)),
240                    0,
241                    i,
242                    || {
243                        let mut lines = vec![format!("value {}", format_compact(vals[i]))];
244                        lines.push(format!("of first {:.0}%", conv[i] * 100.0));
245                        if i > 0 && vals[i - 1] > 0.0 {
246                            lines.push(format!(
247                                "drop-off {:.0}%",
248                                (1.0 - vals[i] / vals[i - 1]) * 100.0
249                            ));
250                        }
251                        (st.label.clone(), lines)
252                    },
253                );
254            }
255
256            // value / percent / drop-off (side) or centered label (narrow)
257            let mid = y0 as u16 + bar_h.saturating_sub(1) / 2;
258            if side {
259                let lab = if off {
260                    text.add_modifier(
261                        ratatui::style::Modifier::DIM | ratatui::style::Modifier::CROSSED_OUT,
262                    )
263                } else {
264                    text
265                };
266                put_str(buf, inner.x, mid, fx, &st.label, lab);
267                crate::interact::record_legend(
268                    Rect::new(
269                        inner.x,
270                        mid,
271                        (st.label.chars().count() as u16).min(fx - inner.x),
272                        1,
273                    ),
274                    i,
275                    &st.label,
276                );
277                let mut stat = format_compact(vals[i]);
278                if self.show_percent {
279                    stat.push_str(&format!("  {:>3.0}%", conv[i] * 100.0));
280                }
281                put_str(buf, fx + fw + 1, mid, inner.right(), &stat, text);
282                if self.show_percent && self.show_dropoff && i > 0 && vals[i - 1] > 0.0 {
283                    let drop = (1.0 - vals[i] / vals[i - 1]) * 100.0;
284                    if h > 1 {
285                        let dy = y0 as u16;
286                        if dy != mid {
287                            put_str(
288                                buf,
289                                fx + fw + 1,
290                                dy,
291                                inner.right(),
292                                &format!("▼ {drop:.0}%"),
293                                dim,
294                            );
295                        }
296                    }
297                }
298            } else {
299                let mut label = format!("{} {}", st.label, format_compact(vals[i]));
300                if self.show_percent {
301                    label.push_str(&format!(" ({:.0}%)", conv[i] * 100.0));
302                }
303                let lw = label.chars().count() as u16;
304                let lx = inner.x + inner.width.saturating_sub(lw) / 2;
305                let on_bar = (lw as f64) <= top_w.min(bot_w);
306                let style = if on_bar {
307                    Style::default().fg(Color::Black).bg(color)
308                } else {
309                    text
310                };
311                let style = if off {
312                    text.add_modifier(
313                        ratatui::style::Modifier::DIM | ratatui::style::Modifier::CROSSED_OUT,
314                    )
315                } else {
316                    style
317                };
318                put_str(buf, lx, mid, inner.right(), &label, style);
319                crate::interact::record_legend(
320                    Rect::new(lx, mid, lw.min(inner.right().saturating_sub(lx)), 1),
321                    i,
322                    &st.label,
323                );
324            }
325        }
326    }
327}
328
329widget_impls!(Funnel);
330
331#[cfg(feature = "theme")]
332impl tui_nuances::Themed for Funnel {
333    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
334        self.theme(theme)
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341    use ratatui::widgets::Widget;
342
343    fn funnel() -> Funnel {
344        Funnel::new([
345            FunnelStage::new("Visits", 1000.0),
346            FunnelStage::new("Signups", 400.0),
347            FunnelStage::new("Paid", 100.0),
348        ])
349    }
350
351    #[test]
352    fn conversions_relative_to_first() {
353        assert_eq!(funnel().conversions(), vec![1.0, 0.4, 0.1]);
354        assert_eq!(
355            Funnel::new([FunnelStage::new("a", 0.0)]).conversions(),
356            vec![0.0]
357        );
358    }
359
360    #[test]
361    fn renders_labels_and_percent() {
362        let area = Rect::new(0, 0, 50, 9);
363        let mut b = Buffer::empty(area);
364        funnel().render(area, &mut b);
365        let all: String = b.content().iter().map(|c| c.symbol()).collect();
366        assert!(all.contains("Visits") && all.contains("40%") && all.contains("10%"));
367    }
368
369    #[test]
370    fn degenerate_inputs_do_not_panic() {
371        let mut b = Buffer::empty(Rect::new(0, 0, 3, 1));
372        funnel().render(Rect::new(0, 0, 3, 1), &mut b);
373        funnel().render(Rect::new(0, 0, 0, 0), &mut b);
374        Funnel::new([FunnelStage::new("x", f64::NAN)]).render(Rect::new(0, 0, 3, 1), &mut b);
375        let mut b = Buffer::empty(Rect::new(0, 0, 30, 2));
376        funnel().render(Rect::new(0, 0, 30, 2), &mut b);
377    }
378
379    fn text(b: &Buffer) -> String {
380        b.content().iter().map(|c| c.symbol()).collect()
381    }
382
383    fn draw(f: Funnel, w: u16, h: u16) -> Buffer {
384        let a = Rect::new(0, 0, w, h);
385        let mut b = Buffer::empty(a);
386        f.render(a, &mut b);
387        b
388    }
389
390    #[test]
391    fn dropoff_toggle() {
392        let on = text(&draw(funnel(), 60, 9));
393        let off = text(&draw(funnel().show_dropoff(false), 60, 9));
394        assert!(on.contains('▼') && !off.contains('▼'));
395    }
396
397    #[test]
398    fn percent_toggle() {
399        let off = text(&draw(funnel().show_percent(false), 60, 9));
400        assert!(!off.contains("40%"));
401    }
402
403    #[test]
404    fn taper_changes_output_and_custom_color_applies() {
405        let f = || funnel();
406        assert_ne!(
407            text(&draw(f().taper(false), 60, 9)),
408            text(&draw(f().taper(true), 60, 9))
409        );
410        let b = draw(
411            Funnel::new([FunnelStage::new("a", 5.0).color(Color::Red)]),
412            40,
413            4,
414        );
415        assert!(
416            b.content()
417                .iter()
418                .any(|c| c.fg == Color::Red || c.bg == Color::Red)
419        );
420    }
421
422    #[test]
423    fn narrow_and_tiny_areas_do_not_panic() {
424        for (w, h) in [(0, 0), (1, 1), (5, 2), (12, 3), (200, 40)] {
425            draw(funnel(), w, h);
426            draw(funnel().taper(false).show_dropoff(false), w, h);
427        }
428    }
429}