Skip to main content

lumen_dioxus/charts/extended/
funnel.rs

1// cspell:words feff
2//! [`FunnelChart`]: sequential stages drawn as bars relative to the largest stage.
3
4use std::collections::HashSet;
5
6use dioxus::prelude::*;
7
8use super::super::format::css_percent;
9use super::super::frame::{ChartPresentation, render_frame};
10use super::super::model::{ChartLabels, ChartTone, format_with};
11use super::{empty_status, is_blank, is_measurement, summary_table};
12use crate::class::{Glass, compose};
13
14/// One stage of a [`FunnelChart`].
15#[derive(Clone, Debug, PartialEq)]
16pub struct FunnelChartDatum {
17    /// A unique, non-blank id.
18    pub id: String,
19    /// The non-blank stage name.
20    pub label: String,
21    /// The stage size, zero or more, or `None` when unknown.
22    pub value: Option<f64>,
23    /// The bar color; defaults to the series tone for the stage position.
24    pub tone: Option<ChartTone>,
25}
26
27impl FunnelChartDatum {
28    /// A stage with an id, a name, and a size.
29    pub fn new(
30        id: impl Into<String>,
31        label: impl Into<String>,
32        value: impl Into<Option<f64>>,
33    ) -> Self {
34        Self {
35            id: id.into(),
36            label: label.into(),
37            value: value.into(),
38            tone: None,
39        }
40    }
41
42    /// Sets the bar color.
43    #[must_use]
44    pub fn with_tone(mut self, tone: ChartTone) -> Self {
45        self.tone = Some(tone);
46        self
47    }
48}
49
50/// Props for [`FunnelChart`].
51#[derive(Props, Clone, PartialEq)]
52pub struct FunnelChartProps {
53    /// The stages, in order. Any invalid stage (blank id or label, negative or non-finite
54    /// value, duplicate id) marks the whole chart invalid.
55    #[props(default)]
56    pub data: Vec<FunnelChartDatum>,
57    /// Formats values. Defaults to JavaScript's `String(value)`.
58    pub format_value: Option<Callback<f64, String>>,
59    /// Visible and assistive text.
60    pub labels: Option<ChartLabels>,
61    /// Shows the collapsible data table.
62    #[props(default = true)]
63    pub show_table: bool,
64    /// The chart title.
65    #[props(into)]
66    pub heading: Option<String>,
67    /// Supporting text under the heading.
68    #[props(into)]
69    pub description: Option<String>,
70    /// A headline value beside the heading.
71    #[props(into)]
72    pub value: Option<String>,
73    /// A screen reader summary; defaults to every stage and its value.
74    #[props(into)]
75    pub summary: Option<String>,
76    /// A visible caption.
77    #[props(into)]
78    pub caption: Option<String>,
79    /// `Bare` removes the card chrome.
80    #[props(default)]
81    pub presentation: ChartPresentation,
82    /// Glass intensity.
83    #[props(default, into)]
84    pub glass: Glass,
85    /// Extra classes appended after the Lumen classes.
86    #[props(into)]
87    pub class: Option<String>,
88    /// Any other `<figure>` or global attribute.
89    #[props(extends = GlobalAttributes, extends = figure)]
90    pub attributes: Vec<Attribute>,
91}
92
93/// One stage with its bar ratio.
94#[derive(Clone, Debug, PartialEq)]
95pub(crate) struct FunnelRow {
96    pub(crate) datum: FunnelChartDatum,
97    pub(crate) ratio: Option<f64>,
98}
99
100/// `createLumenFunnelGeometry`.
101#[derive(Clone, Debug, PartialEq)]
102pub(crate) struct FunnelModel {
103    pub(crate) valid: bool,
104    pub(crate) max: f64,
105    pub(crate) rows: Vec<FunnelRow>,
106}
107
108fn valid_stage(datum: &FunnelChartDatum) -> bool {
109    !is_blank(&datum.id)
110        && !is_blank(&datum.label)
111        && is_measurement(datum.value)
112        && datum.value.is_none_or(|value| value >= 0.0)
113}
114
115pub(crate) fn funnel_geometry(data: &[FunnelChartDatum]) -> FunnelModel {
116    let mut ids = HashSet::new();
117    let mut max: f64 = 0.0;
118
119    for datum in data {
120        if !valid_stage(datum) || !ids.insert(datum.id.as_str()) {
121            return FunnelModel {
122                valid: false,
123                max: 0.0,
124                rows: Vec::new(),
125            };
126        }
127
128        max = max.max(datum.value.unwrap_or(0.0));
129    }
130
131    let rows = data
132        .iter()
133        .map(|datum| FunnelRow {
134            ratio: datum
135                .value
136                .map(|value| if max == 0.0 { 0.0 } else { value / max }),
137            datum: datum.clone(),
138        })
139        .collect();
140
141    FunnelModel {
142        valid: true,
143        max,
144        rows,
145    }
146}
147
148/// Stage-by-stage drop-off, such as visits to sign-ups to purchases. Bars are sized relative to
149/// the largest stage; unknown stages show "Not available".
150#[component]
151pub fn FunnelChart(props: FunnelChartProps) -> Element {
152    let labels = props.labels.clone().unwrap_or_default();
153    let format_value = props.format_value;
154    let model = funnel_geometry(&props.data);
155    let format = |value: Option<f64>| match value {
156        Some(value) => format_with(format_value.as_ref(), value),
157        None => labels.not_available.clone(),
158    };
159    let rows: Vec<(FunnelRow, String, Option<String>, &'static str)> = model
160        .rows
161        .iter()
162        .enumerate()
163        .map(|(index, row)| {
164            (
165                row.clone(),
166                format(row.datum.value),
167                row.ratio.map(css_percent),
168                ChartTone::resolve(row.datum.tone, index).class_name(),
169            )
170        })
171        .collect();
172    let summary = props.summary.clone().or_else(|| {
173        Some(if model.valid {
174            rows.iter()
175                .map(|(row, value, _, _)| format!("{}: {value}", row.datum.label))
176                .collect::<Vec<_>>()
177                .join(". ")
178        } else {
179            labels.invalid_data.clone()
180        })
181    });
182    let class = compose([Some("ui-funnel-chart"), props.class.as_deref()]);
183    let frame = super::super::frame::chart_frame!(props, class, summary);
184
185    if !model.valid || model.rows.is_empty() {
186        let message = if model.valid {
187            &labels.empty
188        } else {
189            &labels.invalid_data
190        };
191
192        return render_frame(frame, empty_status(message));
193    }
194
195    let headings = [
196        ("category", labels.category.clone()),
197        ("value", labels.value.clone()),
198    ];
199    let body = rsx! {
200        ol { class: "ui-funnel-chart__rows",
201            for (row, value, width, tone) in rows.iter() {
202                li { key: "{row.datum.id}", class: *tone,
203                    div { class: "ui-funnel-chart__label",
204                        span { "{row.datum.label}" }
205                        strong { "{value}" }
206                    }
207                    div { class: "ui-funnel-chart__track", aria_hidden: "true",
208                        if let Some(width) = width {
209                            span { class: "ui-funnel-chart__bar", style: "width:{width}" }
210                        }
211                    }
212                }
213            }
214        }
215        if props.show_table {
216            {summary_table(&labels, &headings, rsx! {
217                for (row, value, _, _) in rows.iter() {
218                    tr { key: "{row.datum.id}",
219                        th { scope: "row", "{row.datum.label}" }
220                        td { "{value}" }
221                    }
222                }
223            })}
224        }
225    };
226
227    render_frame(frame, body)
228}
229
230#[cfg(test)]
231mod tests {
232    use super::{FunnelChartDatum, funnel_geometry};
233
234    #[test]
235    fn ratios_are_relative_to_the_largest_stage() {
236        let model = funnel_geometry(&[
237            FunnelChartDatum::new("a", "Visits", 200.0),
238            FunnelChartDatum::new("b", "Trials", None),
239            FunnelChartDatum::new("c", "Paid", 50.0),
240        ]);
241        assert!(model.valid);
242        assert!((model.max - 200.0).abs() < f64::EPSILON);
243        let ratios: Vec<Option<f64>> = model.rows.iter().map(|row| row.ratio).collect();
244        assert_eq!(ratios, vec![Some(1.0), None, Some(0.25)]);
245    }
246
247    #[test]
248    fn zero_and_empty_funnels_are_valid() {
249        let zero = funnel_geometry(&[FunnelChartDatum::new("a", "A", 0.0)]);
250        assert!(zero.valid);
251        assert_eq!(zero.rows[0].ratio, Some(0.0));
252        let empty = funnel_geometry(&[]);
253        assert!(empty.valid && empty.rows.is_empty());
254    }
255
256    #[test]
257    fn invalid_stages_fail_closed() {
258        for data in [
259            vec![FunnelChartDatum::new("a", "A", -1.0)],
260            vec![FunnelChartDatum::new("a", "A", f64::NAN)],
261            vec![FunnelChartDatum::new("a", "A", f64::INFINITY)],
262            vec![FunnelChartDatum::new(" ", "A", 1.0)],
263            vec![FunnelChartDatum::new("a", "\u{feff}", 1.0)],
264            vec![
265                FunnelChartDatum::new("a", "A", 1.0),
266                FunnelChartDatum::new("a", "B", 2.0),
267            ],
268        ] {
269            let model = funnel_geometry(&data);
270            assert!(!model.valid && model.rows.is_empty());
271        }
272    }
273}