lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
// cspell:words feff
//! [`FunnelChart`]: sequential stages drawn as bars relative to the largest stage.

use std::collections::HashSet;

use dioxus::prelude::*;

use super::super::format::css_percent;
use super::super::frame::{ChartPresentation, render_frame};
use super::super::model::{ChartLabels, ChartTone, format_with};
use super::{empty_status, is_blank, is_measurement, summary_table};
use crate::class::{Glass, compose};

/// One stage of a [`FunnelChart`].
#[derive(Clone, Debug, PartialEq)]
pub struct FunnelChartDatum {
    /// A unique, non-blank id.
    pub id: String,
    /// The non-blank stage name.
    pub label: String,
    /// The stage size, zero or more, or `None` when unknown.
    pub value: Option<f64>,
    /// The bar color; defaults to the series tone for the stage position.
    pub tone: Option<ChartTone>,
}

impl FunnelChartDatum {
    /// A stage with an id, a name, and a size.
    pub fn new(
        id: impl Into<String>,
        label: impl Into<String>,
        value: impl Into<Option<f64>>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value: value.into(),
            tone: None,
        }
    }

    /// Sets the bar color.
    #[must_use]
    pub fn with_tone(mut self, tone: ChartTone) -> Self {
        self.tone = Some(tone);
        self
    }
}

/// Props for [`FunnelChart`].
#[derive(Props, Clone, PartialEq)]
pub struct FunnelChartProps {
    /// The stages, in order. Any invalid stage (blank id or label, negative or non-finite
    /// value, duplicate id) marks the whole chart invalid.
    #[props(default)]
    pub data: Vec<FunnelChartDatum>,
    /// Formats values. Defaults to JavaScript's `String(value)`.
    pub format_value: Option<Callback<f64, String>>,
    /// Visible and assistive text.
    pub labels: Option<ChartLabels>,
    /// Shows the collapsible data table.
    #[props(default = true)]
    pub show_table: bool,
    /// The chart title.
    #[props(into)]
    pub heading: Option<String>,
    /// Supporting text under the heading.
    #[props(into)]
    pub description: Option<String>,
    /// A headline value beside the heading.
    #[props(into)]
    pub value: Option<String>,
    /// A screen reader summary; defaults to every stage and its value.
    #[props(into)]
    pub summary: Option<String>,
    /// A visible caption.
    #[props(into)]
    pub caption: Option<String>,
    /// `Bare` removes the card chrome.
    #[props(default)]
    pub presentation: ChartPresentation,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
}

/// One stage with its bar ratio.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct FunnelRow {
    pub(crate) datum: FunnelChartDatum,
    pub(crate) ratio: Option<f64>,
}

/// `createLumenFunnelGeometry`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct FunnelModel {
    pub(crate) valid: bool,
    pub(crate) max: f64,
    pub(crate) rows: Vec<FunnelRow>,
}

fn valid_stage(datum: &FunnelChartDatum) -> bool {
    !is_blank(&datum.id)
        && !is_blank(&datum.label)
        && is_measurement(datum.value)
        && datum.value.is_none_or(|value| value >= 0.0)
}

pub(crate) fn funnel_geometry(data: &[FunnelChartDatum]) -> FunnelModel {
    let mut ids = HashSet::new();
    let mut max: f64 = 0.0;

    for datum in data {
        if !valid_stage(datum) || !ids.insert(datum.id.as_str()) {
            return FunnelModel {
                valid: false,
                max: 0.0,
                rows: Vec::new(),
            };
        }

        max = max.max(datum.value.unwrap_or(0.0));
    }

    let rows = data
        .iter()
        .map(|datum| FunnelRow {
            ratio: datum
                .value
                .map(|value| if max == 0.0 { 0.0 } else { value / max }),
            datum: datum.clone(),
        })
        .collect();

    FunnelModel {
        valid: true,
        max,
        rows,
    }
}

/// Stage-by-stage drop-off, such as visits to sign-ups to purchases. Bars are sized relative to
/// the largest stage; unknown stages show "Not available".
#[component]
pub fn FunnelChart(props: FunnelChartProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value;
    let model = funnel_geometry(&props.data);
    let format = |value: Option<f64>| match value {
        Some(value) => format_with(format_value.as_ref(), value),
        None => labels.not_available.clone(),
    };
    let rows: Vec<(FunnelRow, String, Option<String>, &'static str)> = model
        .rows
        .iter()
        .enumerate()
        .map(|(index, row)| {
            (
                row.clone(),
                format(row.datum.value),
                row.ratio.map(css_percent),
                ChartTone::resolve(row.datum.tone, index).class_name(),
            )
        })
        .collect();
    let summary = props.summary.clone().or_else(|| {
        Some(if model.valid {
            rows.iter()
                .map(|(row, value, _, _)| format!("{}: {value}", row.datum.label))
                .collect::<Vec<_>>()
                .join(". ")
        } else {
            labels.invalid_data.clone()
        })
    });
    let class = compose([Some("ui-funnel-chart"), props.class.as_deref()]);
    let frame = super::super::frame::chart_frame!(props, class, summary);

    if !model.valid || model.rows.is_empty() {
        let message = if model.valid {
            &labels.empty
        } else {
            &labels.invalid_data
        };

        return render_frame(frame, empty_status(message));
    }

    let headings = [
        ("category", labels.category.clone()),
        ("value", labels.value.clone()),
    ];
    let body = rsx! {
        ol { class: "ui-funnel-chart__rows",
            for (row, value, width, tone) in rows.iter() {
                li { key: "{row.datum.id}", class: *tone,
                    div { class: "ui-funnel-chart__label",
                        span { "{row.datum.label}" }
                        strong { "{value}" }
                    }
                    div { class: "ui-funnel-chart__track", aria_hidden: "true",
                        if let Some(width) = width {
                            span { class: "ui-funnel-chart__bar", style: "width:{width}" }
                        }
                    }
                }
            }
        }
        if props.show_table {
            {summary_table(&labels, &headings, rsx! {
                for (row, value, _, _) in rows.iter() {
                    tr { key: "{row.datum.id}",
                        th { scope: "row", "{row.datum.label}" }
                        td { "{value}" }
                    }
                }
            })}
        }
    };

    render_frame(frame, body)
}

#[cfg(test)]
mod tests {
    use super::{FunnelChartDatum, funnel_geometry};

    #[test]
    fn ratios_are_relative_to_the_largest_stage() {
        let model = funnel_geometry(&[
            FunnelChartDatum::new("a", "Visits", 200.0),
            FunnelChartDatum::new("b", "Trials", None),
            FunnelChartDatum::new("c", "Paid", 50.0),
        ]);
        assert!(model.valid);
        assert!((model.max - 200.0).abs() < f64::EPSILON);
        let ratios: Vec<Option<f64>> = model.rows.iter().map(|row| row.ratio).collect();
        assert_eq!(ratios, vec![Some(1.0), None, Some(0.25)]);
    }

    #[test]
    fn zero_and_empty_funnels_are_valid() {
        let zero = funnel_geometry(&[FunnelChartDatum::new("a", "A", 0.0)]);
        assert!(zero.valid);
        assert_eq!(zero.rows[0].ratio, Some(0.0));
        let empty = funnel_geometry(&[]);
        assert!(empty.valid && empty.rows.is_empty());
    }

    #[test]
    fn invalid_stages_fail_closed() {
        for data in [
            vec![FunnelChartDatum::new("a", "A", -1.0)],
            vec![FunnelChartDatum::new("a", "A", f64::NAN)],
            vec![FunnelChartDatum::new("a", "A", f64::INFINITY)],
            vec![FunnelChartDatum::new(" ", "A", 1.0)],
            vec![FunnelChartDatum::new("a", "\u{feff}", 1.0)],
            vec![
                FunnelChartDatum::new("a", "A", 1.0),
                FunnelChartDatum::new("a", "B", 2.0),
            ],
        ] {
            let model = funnel_geometry(&data);
            assert!(!model.valid && model.rows.is_empty());
        }
    }
}