lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! [`PieChart`]: shares of a whole as a donut or a pie.

use dioxus::prelude::*;

use super::activation::{ChartDatumActivation, DatumAction};
use super::format::format_chart_percentage;
use super::frame::{
    ChartFrame, ChartPresentation, activate_on_click, datum_actions, render_frame, serialized,
};
use super::geometry::{PieChartVariant, pie_geometry, pie_values};
use super::model::{ChartLabels, ChartSeries, format_with, summarize};
use super::native_paints::paint_attributes;
use crate::class::{Glass, compose};

fn default_pie_series() -> ChartSeries {
    ChartSeries::new("pie", "Values", [])
}

/// Props for [`PieChart`].
#[derive(Props, Clone, PartialEq)]
pub struct PieChartProps {
    /// The slices. Only finite, positive values are drawn.
    #[props(default = default_pie_series())]
    pub series: ChartSeries,
    /// Donut (default) or pie.
    #[props(default)]
    pub variant: PieChartVariant,
    /// A label in the donut's center.
    #[props(into)]
    pub center_label: Option<String>,
    /// A value in the donut's center.
    #[props(into)]
    pub center_value: Option<String>,
    /// Formats slice values. Defaults to `String(value)`.
    pub value_formatter: Option<Callback<f64, String>>,
    /// Localized chart text.
    pub labels: Option<ChartLabels>,
    /// Shows the legend.
    #[props(default = true)]
    pub show_legend: bool,
    /// Shows the collapsible data table.
    #[props(default = true)]
    pub show_table: bool,
    /// Makes every slice clickable and adds a keyboard-reachable action menu.
    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
    /// 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 a generated description 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.
    #[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>,
}

struct SliceView {
    paints: Vec<Attribute>,
    key: String,
    class: &'static str,
    label: String,
    path: String,
    value: String,
    share: String,
    action: Option<DatumAction>,
}

/// Shows how parts make up a whole, with a legend, a share table, and optional datum activation.
#[component]
#[allow(clippy::too_many_lines)]
pub fn PieChart(props: PieChartProps) -> Element {
    let native_paints =
        super::native_paints::use_native_chart_paints(super::model::ChartTone::Series1);
    let labels = props.labels.clone().unwrap_or_default();
    let formatter = props.value_formatter.as_ref();
    let geometry = pie_geometry(&props.series.data, props.variant);
    let rendered = ChartSeries {
        data: pie_values(&props.series.data),
        ..props.series.clone()
    };
    let has_data = !rendered.data.is_empty();
    let on_activate = props.on_datum_activate;
    let slices: Vec<SliceView> = geometry
        .slices
        .iter()
        .map(|slice| {
            let value = format_with(formatter, slice.value);
            let action = on_activate.and_then(|_| {
                DatumAction::new(
                    ChartDatumActivation::series(&props.series.id, &slice.datum),
                    &format!("{} · {}: {value}", slice.label, props.series.label),
                    &labels,
                )
            });

            SliceView {
                paints: paint_attributes(native_paints, "pie", Some(slice.tone)),
                key: slice.datum.x.key(),
                class: slice.tone.class_name(),
                label: slice.label.clone(),
                path: slice.path.clone(),
                share: format_chart_percentage(slice.percentage),
                value,
                action,
            }
        })
        .collect();
    let actions: Vec<Option<DatumAction>> =
        slices.iter().map(|slice| slice.action.clone()).collect();
    let summary = props
        .summary
        .clone()
        .or_else(|| Some(labels.summary(summarize(std::slice::from_ref(&rendered), formatter))));
    let frame = ChartFrame {
        chart_class: Some(compose([
            Some("ui-pie-chart"),
            Some(props.variant.class_name()),
            props.class.as_deref(),
        ])),
        heading: props.heading.clone(),
        description: props.description.clone(),
        value: props.value.clone(),
        summary,
        caption: props.caption.clone(),
        presentation: props.presentation,
        glass: props.glass,
        activation: on_activate.is_some(),
        attributes: props.attributes.clone(),
        on_mounted: None,
    };
    let show_center = props.variant == PieChartVariant::Donut
        && (props.center_label.is_some() || props.center_value.is_some());
    let center_text = format!(
        "{} {}",
        props.center_value.clone().unwrap_or_default(),
        props.center_label.clone().unwrap_or_default()
    );
    let body = rsx! {
        if props.show_legend && has_data {
            ul { aria_label: "{labels.chart_legend}", class: "ui-chart__legend",
                for slice in slices.iter() {
                    li { key: "{slice.key}", class: slice.class,
                        span { aria_hidden: "true" }
                        "{slice.label}"
                    }
                }
            }
        }
        if !has_data {
            p { class: "ui-chart__empty", role: "status", "{labels.empty}" }
        }
        div { class: "ui-chart__plot ui-pie-chart__plot", hidden: (!has_data).then_some(true),
            svg {
                "aria-hidden": "true",
                "preserveAspectRatio": "xMidYMid meet",
                "viewBox": "0 0 320 320",
                width: native_paints.map(|_| "320"),
                height: native_paints.map(|_| "320"),
                g { class: "ui-pie-chart__slices",
                    for slice in slices.iter() {
                        path {
                            key: "{slice.key}",
                            class: slice.class,
                            "data-ui-chart-datum": serialized(slice.action.as_ref()),
                            d: "{slice.path}",
                            "fill-rule": "evenodd",
                            onclick: activate_on_click(slice.action.as_ref(), on_activate),
                            ..slice.paints.clone(),
                            title { "{slice.label}: {slice.value} ({slice.share})" }
                        }
                    }
                }
            }
            if show_center {
                div { aria_hidden: "true", class: "ui-pie-chart__center",
                    if let Some(value) = props.center_value.clone() {
                        strong { "{value}" }
                    }
                    if let Some(label) = props.center_label.clone() {
                        span { "{label}" }
                    }
                }
                div { class: "ui-sr-only", "{center_text}" }
            }
        }
        if props.show_table && has_data {
            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}" }
                                th { scope: "col", "{labels.value}" }
                                th { scope: "col", "Share" }
                            }
                        }
                        tbody {
                            for slice in slices.iter() {
                                tr { key: "{slice.key}",
                                    th { scope: "row", "{slice.label}" }
                                    td { "{slice.value}" }
                                    td { "{slice.share}" }
                                }
                            }
                        }
                    }
                }
            }
        }
        if on_activate.is_some() {
            {datum_actions(&actions, &labels.explore_data, on_activate)}
        }
    };

    render_frame(frame, body)
}