lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
// cspell:words figcaption
//! The [`Chart`] frame and the parts every data chart shares: legend, data table, and the datum
//! action menu.

use dioxus::prelude::*;

use super::activation::{ChartDatumActivation, DatumAction};
use super::model::{
    ChartLabels, ChartSeries, ChartTone, ChartX, format_category_with, format_with,
};
use super::scale::{LabelContext, align_series, category_label};
use crate::class::{Glass, compose};
use crate::{Button, ButtonVariant};

/// How much chrome a [`Chart`] draws around its content.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChartPresentation {
    /// Bordered card surface.
    #[default]
    Default,
    /// No border, background, or padding, for charts placed inside another surface.
    Bare,
}

/// Props for [`Chart`].
#[derive(Props, Clone, PartialEq)]
pub struct ChartProps {
    /// The chart title, rendered as an `h3`.
    #[props(into)]
    pub heading: Option<String>,
    /// Supporting text under the heading.
    #[props(into)]
    pub description: Option<String>,
    /// A headline value shown beside the heading.
    #[props(into)]
    pub value: Option<String>,
    /// A screen reader summary of the data.
    #[props(into)]
    pub summary: Option<String>,
    /// A visible caption, such as the data source.
    #[props(into)]
    pub caption: Option<String>,
    /// `Bare` removes the card chrome.
    #[props(default)]
    pub presentation: ChartPresentation,
    /// Glass intensity. Needs a renderer with `backdrop-filter` support.
    #[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>,
    /// The chart body.
    pub children: Element,
}

/// A captioned figure that frames a visualization: heading, description, headline value, a
/// screen reader summary, the content, and a caption.
#[component]
pub fn Chart(props: ChartProps) -> Element {
    let frame = ChartFrame {
        chart_class: props.class.clone(),
        heading: props.heading,
        description: props.description,
        value: props.value,
        summary: props.summary,
        caption: props.caption,
        presentation: props.presentation,
        glass: props.glass,
        activation: false,
        attributes: props.attributes,
        on_mounted: None,
    };

    render_frame(frame, props.children)
}

/// Everything [`render_frame`] needs; the shared [`Chart`] props of every chart component.
#[derive(Default)]
pub(crate) struct ChartFrame {
    /// The chart-specific classes plus the consumer's classes.
    pub(crate) chart_class: Option<String>,
    pub(crate) heading: Option<String>,
    pub(crate) description: Option<String>,
    pub(crate) value: Option<String>,
    pub(crate) summary: Option<String>,
    pub(crate) caption: Option<String>,
    pub(crate) presentation: ChartPresentation,
    pub(crate) glass: Glass,
    /// Marks the root as handling datum activation in Rust.
    pub(crate) activation: bool,
    pub(crate) attributes: Vec<Attribute>,
    /// Receives the mounted `<figure>` (web and desktop) for layout measurements.
    pub(crate) on_mounted: Option<EventHandler<std::rc::Rc<MountedData>>>,
}

/// Builds a [`ChartFrame`] from a chart's props struct, which all share the same field names.
macro_rules! chart_frame {
    ($props:expr, $class:expr, $summary:expr) => {
        $crate::charts::frame::ChartFrame {
            chart_class: Some($class),
            heading: $props.heading.clone(),
            description: $props.description.clone(),
            value: $props.value.clone(),
            summary: $summary,
            caption: $props.caption.clone(),
            presentation: $props.presentation,
            glass: $props.glass,
            activation: false,
            attributes: $props.attributes.clone(),
            on_mounted: None,
        }
    };
}

pub(crate) use chart_frame;

/// Renders the `<figure class="ui-chart">` frame around `children`.
pub(crate) fn render_frame(frame: ChartFrame, children: Element) -> Element {
    let glass = frame.glass.class("ui-chart");
    let class = compose([
        Some("ui-chart"),
        (frame.presentation == ChartPresentation::Bare).then_some("ui-chart--bare"),
        glass.as_deref(),
        frame.chart_class.as_deref(),
    ]);
    let on_mounted = frame.on_mounted;
    let has_header = non_empty(frame.heading.as_ref()).is_some()
        || non_empty(frame.description.as_ref()).is_some()
        || non_empty(frame.value.as_ref()).is_some();

    rsx! {
        figure {
            class,
            "data-ui-chart-activation": frame.activation.then_some("true"),
            "data-ui-chart-adapter": frame.activation.then_some("dioxus"),
            onmounted: move |event| {
                if let Some(handler) = on_mounted {
                    handler.call(event.data());
                }
            },
            ..frame.attributes,
            if has_header {
                header {
                    div { class: "ui-chart__heading",
                        if let Some(heading) = non_empty(frame.heading.as_ref()) {
                            h3 { "{heading}" }
                        }
                        if let Some(description) = non_empty(frame.description.as_ref()) {
                            p { "{description}" }
                        }
                    }
                    if let Some(value) = non_empty(frame.value.as_ref()) {
                        strong { "data-ui-chart-value": "true", "{value}" }
                    }
                }
            }
            if let Some(summary) = non_empty(frame.summary.as_ref()) {
                p { class: "ui-sr-only", "data-ui-chart-summary": "true", "{summary}" }
            }
            {children}
            if let Some(caption) = non_empty(frame.caption.as_ref()) {
                figcaption { "{caption}" }
            }
        }
    }
}

/// React skips empty strings in `{value && …}` conditions.
fn non_empty(value: Option<&String>) -> Option<&String> {
    value.filter(|text| !text.is_empty())
}

/// The text value of a spread attribute such as `aria-label`.
pub(crate) fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
    attributes
        .iter()
        .find(|attribute| attribute.name == name)
        .and_then(|attribute| match &attribute.value {
            dioxus::dioxus_core::AttributeValue::Text(text) => Some(text.clone()),
            _ => None,
        })
}

/// `getChartPlotLabel`: the chart's `aria-label`, then its heading, then the fallback.
pub(crate) fn plot_label(
    attributes: &[Attribute],
    heading: Option<&String>,
    fallback: &str,
) -> String {
    attribute_text(attributes, "aria-label")
        .or_else(|| heading.cloned())
        .unwrap_or_else(|| fallback.to_string())
}

/// The `ui-chart__legend` list for a set of series.
pub(crate) fn chart_legend(label: &str, series: &[ChartSeries]) -> Element {
    rsx! {
        ul { aria_label: "{label}", class: "ui-chart__legend",
            for (index, item) in series.iter().enumerate() {
                li { key: "{item.id}", class: ChartTone::resolve(item.tone, index).class_name(),
                    span { aria_hidden: "true" }
                    "{item.label}"
                }
            }
        }
    }
}

/// `formatReactChartTableValue`.
pub(crate) fn table_value(
    value: Option<f64>,
    format_value: Option<&Callback<f64, String>>,
    not_available: &str,
) -> String {
    match value.filter(|value| value.is_finite()) {
        Some(value) => format_with(format_value, value),
        None => not_available.to_string(),
    }
}

/// A data table row: its key, its category label, and one `(series id, text)` cell per series.
type TableRow = (String, String, Vec<(String, String)>);

/// The collapsible `ui-chart__data` table with one row per category and one column per series.
pub(crate) fn chart_data_table(
    categories: &[ChartX],
    format_category: Option<&Callback<ChartX, String>>,
    format_value: Option<&Callback<f64, String>>,
    labels: &ChartLabels,
    series: &[ChartSeries],
) -> Element {
    let aligned: Vec<ChartSeries> = series
        .iter()
        .map(|item| align_series(item, categories))
        .collect();
    let rows: Vec<TableRow> = categories
        .iter()
        .map(|category| {
            let cells = aligned
                .iter()
                .map(|item| {
                    let datum = item.data.iter().find(|candidate| candidate.x == *category);
                    let text = datum
                        .and_then(|datum| datum.label.clone())
                        .unwrap_or_else(|| {
                            table_value(
                                datum.and_then(|datum| datum.y),
                                format_value,
                                &labels.not_available,
                            )
                        });

                    (item.id.clone(), text)
                })
                .collect();

            (
                category.key(),
                category_label(&aligned, category, format_category, LabelContext::Detail),
                cells,
            )
        })
        .collect();

    rsx! {
        details { class: "ui-chart__data",
            summary { "{labels.view_data}" }
            div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
                table {
                    thead {
                        tr {
                            th { scope: "col", "{labels.category}" }
                            for item in series.iter() {
                                th { key: "{item.id}", scope: "col", "{item.label}" }
                            }
                        }
                    }
                    tbody {
                        for (key, label, cells) in rows {
                            tr { key: "{key}",
                                th { scope: "row", "{label}" }
                                for (id, text) in cells {
                                    td { key: "{id}", "{text}" }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/// The collapsible `ui-chart__actions` menu: one keyboard-reachable button per clickable mark.
pub(crate) fn datum_actions(
    actions: &[Option<DatumAction>],
    label: &str,
    on_activate: Option<EventHandler<ChartDatumActivation>>,
) -> Element {
    let available: Vec<DatumAction> = actions.iter().flatten().cloned().collect();

    if available.is_empty() {
        return rsx! {};
    }

    rsx! {
        details { class: "ui-chart__actions", "data-ui-chart-actions": "true",
            summary { "{label}" }
            ul {
                for action in available {
                    li { key: "{action.serialized}",
                        Button {
                            variant: ButtonVariant::Ghost,
                            "data-ui-chart-datum": action.serialized.clone(),
                            onclick: move |_| {
                                if let Some(handler) = on_activate {
                                    handler.call(action.detail.clone());
                                }
                            },
                            "{action.label}"
                        }
                    }
                }
            }
        }
    }
}

/// A click handler for an clickable SVG mark: primary button only, like lumen-react.
pub(crate) fn activate_on_click(
    action: Option<&DatumAction>,
    on_activate: Option<EventHandler<ChartDatumActivation>>,
) -> impl FnMut(MouseEvent) + 'static {
    let detail = action.map(|action| action.detail.clone());

    move |event: MouseEvent| {
        let primary = event
            .trigger_button()
            .is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);

        if !primary {
            return;
        }

        if let (Some(handler), Some(detail)) = (on_activate, detail.clone()) {
            handler.call(detail);
        }
    }
}

/// The datum action's serialized detail, for `data-ui-chart-datum`.
pub(crate) fn serialized(action: Option<&DatumAction>) -> Option<String> {
    action.map(|action| action.serialized.clone())
}

/// A category formatter shortcut used by the series charts.
pub(crate) fn detail_label(
    series: &[ChartSeries],
    category: &ChartX,
    format_category: Option<&Callback<ChartX, String>>,
) -> String {
    category_label(series, category, format_category, LabelContext::Detail)
}

/// `formatCategory?.(x) ?? String(x)` for tooltips that do not consult `x_label`.
pub(crate) fn plain_category(
    category: &ChartX,
    format: Option<&Callback<ChartX, String>>,
) -> String {
    format_category_with(format, category)
}