lumen_dioxus/charts/extended/
funnel.rs1use 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#[derive(Clone, Debug, PartialEq)]
16pub struct FunnelChartDatum {
17 pub id: String,
19 pub label: String,
21 pub value: Option<f64>,
23 pub tone: Option<ChartTone>,
25}
26
27impl FunnelChartDatum {
28 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 #[must_use]
44 pub fn with_tone(mut self, tone: ChartTone) -> Self {
45 self.tone = Some(tone);
46 self
47 }
48}
49
50#[derive(Props, Clone, PartialEq)]
52pub struct FunnelChartProps {
53 #[props(default)]
56 pub data: Vec<FunnelChartDatum>,
57 pub format_value: Option<Callback<f64, String>>,
59 pub labels: Option<ChartLabels>,
61 #[props(default = true)]
63 pub show_table: bool,
64 #[props(into)]
66 pub heading: Option<String>,
67 #[props(into)]
69 pub description: Option<String>,
70 #[props(into)]
72 pub value: Option<String>,
73 #[props(into)]
75 pub summary: Option<String>,
76 #[props(into)]
78 pub caption: Option<String>,
79 #[props(default)]
81 pub presentation: ChartPresentation,
82 #[props(default, into)]
84 pub glass: Glass,
85 #[props(into)]
87 pub class: Option<String>,
88 #[props(extends = GlobalAttributes, extends = figure)]
90 pub attributes: Vec<Attribute>,
91}
92
93#[derive(Clone, Debug, PartialEq)]
95pub(crate) struct FunnelRow {
96 pub(crate) datum: FunnelChartDatum,
97 pub(crate) ratio: Option<f64>,
98}
99
100#[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#[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}