Skip to main content

lumen_dioxus/charts/
pie.rs

1//! [`PieChart`]: shares of a whole as a donut or a pie.
2
3use dioxus::prelude::*;
4
5use super::activation::{ChartDatumActivation, DatumAction};
6use super::format::format_chart_percentage;
7use super::frame::{
8    ChartFrame, ChartPresentation, activate_on_click, datum_actions, render_frame, serialized,
9};
10use super::geometry::{PieChartVariant, pie_geometry, pie_values};
11use super::model::{ChartLabels, ChartSeries, format_with, summarize};
12use super::native_paints::paint_attributes;
13use crate::class::{Glass, compose};
14
15fn default_pie_series() -> ChartSeries {
16    ChartSeries::new("pie", "Values", [])
17}
18
19/// Props for [`PieChart`].
20#[derive(Props, Clone, PartialEq)]
21pub struct PieChartProps {
22    /// The slices. Only finite, positive values are drawn.
23    #[props(default = default_pie_series())]
24    pub series: ChartSeries,
25    /// Donut (default) or pie.
26    #[props(default)]
27    pub variant: PieChartVariant,
28    /// A label in the donut's center.
29    #[props(into)]
30    pub center_label: Option<String>,
31    /// A value in the donut's center.
32    #[props(into)]
33    pub center_value: Option<String>,
34    /// Formats slice values. Defaults to `String(value)`.
35    pub value_formatter: Option<Callback<f64, String>>,
36    /// Localized chart text.
37    pub labels: Option<ChartLabels>,
38    /// Shows the legend.
39    #[props(default = true)]
40    pub show_legend: bool,
41    /// Shows the collapsible data table.
42    #[props(default = true)]
43    pub show_table: bool,
44    /// Makes every slice clickable and adds a keyboard-reachable action menu.
45    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
46    /// The chart title.
47    #[props(into)]
48    pub heading: Option<String>,
49    /// Supporting text under the heading.
50    #[props(into)]
51    pub description: Option<String>,
52    /// A headline value beside the heading.
53    #[props(into)]
54    pub value: Option<String>,
55    /// A screen reader summary; defaults to a generated description of the data.
56    #[props(into)]
57    pub summary: Option<String>,
58    /// A visible caption, such as the data source.
59    #[props(into)]
60    pub caption: Option<String>,
61    /// `Bare` removes the card chrome.
62    #[props(default)]
63    pub presentation: ChartPresentation,
64    /// Glass intensity.
65    #[props(default, into)]
66    pub glass: Glass,
67    /// Extra classes appended after the Lumen classes.
68    #[props(into)]
69    pub class: Option<String>,
70    /// Any other `<figure>` or global attribute.
71    #[props(extends = GlobalAttributes, extends = figure)]
72    pub attributes: Vec<Attribute>,
73}
74
75struct SliceView {
76    paints: Vec<Attribute>,
77    key: String,
78    class: &'static str,
79    label: String,
80    path: String,
81    value: String,
82    share: String,
83    action: Option<DatumAction>,
84}
85
86/// Shows how parts make up a whole, with a legend, a share table, and optional datum activation.
87#[component]
88#[allow(clippy::too_many_lines)]
89pub fn PieChart(props: PieChartProps) -> Element {
90    let native_paints =
91        super::native_paints::use_native_chart_paints(super::model::ChartTone::Series1);
92    let labels = props.labels.clone().unwrap_or_default();
93    let formatter = props.value_formatter.as_ref();
94    let geometry = pie_geometry(&props.series.data, props.variant);
95    let rendered = ChartSeries {
96        data: pie_values(&props.series.data),
97        ..props.series.clone()
98    };
99    let has_data = !rendered.data.is_empty();
100    let on_activate = props.on_datum_activate;
101    let slices: Vec<SliceView> = geometry
102        .slices
103        .iter()
104        .map(|slice| {
105            let value = format_with(formatter, slice.value);
106            let action = on_activate.and_then(|_| {
107                DatumAction::new(
108                    ChartDatumActivation::series(&props.series.id, &slice.datum),
109                    &format!("{} ยท {}: {value}", slice.label, props.series.label),
110                    &labels,
111                )
112            });
113
114            SliceView {
115                paints: paint_attributes(native_paints, "pie", Some(slice.tone)),
116                key: slice.datum.x.key(),
117                class: slice.tone.class_name(),
118                label: slice.label.clone(),
119                path: slice.path.clone(),
120                share: format_chart_percentage(slice.percentage),
121                value,
122                action,
123            }
124        })
125        .collect();
126    let actions: Vec<Option<DatumAction>> =
127        slices.iter().map(|slice| slice.action.clone()).collect();
128    let summary = props
129        .summary
130        .clone()
131        .or_else(|| Some(labels.summary(summarize(std::slice::from_ref(&rendered), formatter))));
132    let frame = ChartFrame {
133        chart_class: Some(compose([
134            Some("ui-pie-chart"),
135            Some(props.variant.class_name()),
136            props.class.as_deref(),
137        ])),
138        heading: props.heading.clone(),
139        description: props.description.clone(),
140        value: props.value.clone(),
141        summary,
142        caption: props.caption.clone(),
143        presentation: props.presentation,
144        glass: props.glass,
145        activation: on_activate.is_some(),
146        attributes: props.attributes.clone(),
147        on_mounted: None,
148    };
149    let show_center = props.variant == PieChartVariant::Donut
150        && (props.center_label.is_some() || props.center_value.is_some());
151    let center_text = format!(
152        "{} {}",
153        props.center_value.clone().unwrap_or_default(),
154        props.center_label.clone().unwrap_or_default()
155    );
156    let body = rsx! {
157        if props.show_legend && has_data {
158            ul { aria_label: "{labels.chart_legend}", class: "ui-chart__legend",
159                for slice in slices.iter() {
160                    li { key: "{slice.key}", class: slice.class,
161                        span { aria_hidden: "true" }
162                        "{slice.label}"
163                    }
164                }
165            }
166        }
167        if !has_data {
168            p { class: "ui-chart__empty", role: "status", "{labels.empty}" }
169        }
170        div { class: "ui-chart__plot ui-pie-chart__plot", hidden: (!has_data).then_some(true),
171            svg {
172                "aria-hidden": "true",
173                "preserveAspectRatio": "xMidYMid meet",
174                "viewBox": "0 0 320 320",
175                width: native_paints.map(|_| "320"),
176                height: native_paints.map(|_| "320"),
177                g { class: "ui-pie-chart__slices",
178                    for slice in slices.iter() {
179                        path {
180                            key: "{slice.key}",
181                            class: slice.class,
182                            "data-ui-chart-datum": serialized(slice.action.as_ref()),
183                            d: "{slice.path}",
184                            "fill-rule": "evenodd",
185                            onclick: activate_on_click(slice.action.as_ref(), on_activate),
186                            ..slice.paints.clone(),
187                            title { "{slice.label}: {slice.value} ({slice.share})" }
188                        }
189                    }
190                }
191            }
192            if show_center {
193                div { aria_hidden: "true", class: "ui-pie-chart__center",
194                    if let Some(value) = props.center_value.clone() {
195                        strong { "{value}" }
196                    }
197                    if let Some(label) = props.center_label.clone() {
198                        span { "{label}" }
199                    }
200                }
201                div { class: "ui-sr-only", "{center_text}" }
202            }
203        }
204        if props.show_table && has_data {
205            details { class: "ui-chart__data",
206                summary { "{labels.view_data}" }
207                div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
208                    table {
209                        thead {
210                            tr {
211                                th { scope: "col", "{labels.category}" }
212                                th { scope: "col", "{labels.value}" }
213                                th { scope: "col", "Share" }
214                            }
215                        }
216                        tbody {
217                            for slice in slices.iter() {
218                                tr { key: "{slice.key}",
219                                    th { scope: "row", "{slice.label}" }
220                                    td { "{slice.value}" }
221                                    td { "{slice.share}" }
222                                }
223                            }
224                        }
225                    }
226                }
227            }
228        }
229        if on_activate.is_some() {
230            {datum_actions(&actions, &labels.explore_data, on_activate)}
231        }
232    };
233
234    render_frame(frame, body)
235}