Skip to main content

lumen_dioxus/charts/
frame.rs

1// cspell:words figcaption
2//! The [`Chart`] frame and the parts every data chart shares: legend, data table, and the datum
3//! action menu.
4
5use dioxus::prelude::*;
6
7use super::activation::{ChartDatumActivation, DatumAction};
8use super::model::{
9    ChartLabels, ChartSeries, ChartTone, ChartX, format_category_with, format_with,
10};
11use super::scale::{LabelContext, align_series, category_label};
12use crate::class::{Glass, compose};
13use crate::{Button, ButtonVariant};
14
15/// How much chrome a [`Chart`] draws around its content.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum ChartPresentation {
19    /// Bordered card surface.
20    #[default]
21    Default,
22    /// No border, background, or padding, for charts placed inside another surface.
23    Bare,
24}
25
26/// Props for [`Chart`].
27#[derive(Props, Clone, PartialEq)]
28pub struct ChartProps {
29    /// The chart title, rendered as an `h3`.
30    #[props(into)]
31    pub heading: Option<String>,
32    /// Supporting text under the heading.
33    #[props(into)]
34    pub description: Option<String>,
35    /// A headline value shown beside the heading.
36    #[props(into)]
37    pub value: Option<String>,
38    /// A screen reader summary of the data.
39    #[props(into)]
40    pub summary: Option<String>,
41    /// A visible caption, such as the data source.
42    #[props(into)]
43    pub caption: Option<String>,
44    /// `Bare` removes the card chrome.
45    #[props(default)]
46    pub presentation: ChartPresentation,
47    /// Glass intensity. Needs a renderer with `backdrop-filter` support.
48    #[props(default, into)]
49    pub glass: Glass,
50    /// Extra classes appended after the Lumen classes.
51    #[props(into)]
52    pub class: Option<String>,
53    /// Any other `<figure>` or global attribute.
54    #[props(extends = GlobalAttributes, extends = figure)]
55    pub attributes: Vec<Attribute>,
56    /// The chart body.
57    pub children: Element,
58}
59
60/// A captioned figure that frames a visualization: heading, description, headline value, a
61/// screen reader summary, the content, and a caption.
62#[component]
63pub fn Chart(props: ChartProps) -> Element {
64    let frame = ChartFrame {
65        chart_class: props.class.clone(),
66        heading: props.heading,
67        description: props.description,
68        value: props.value,
69        summary: props.summary,
70        caption: props.caption,
71        presentation: props.presentation,
72        glass: props.glass,
73        activation: false,
74        attributes: props.attributes,
75        on_mounted: None,
76    };
77
78    render_frame(frame, props.children)
79}
80
81/// Everything [`render_frame`] needs; the shared [`Chart`] props of every chart component.
82#[derive(Default)]
83pub(crate) struct ChartFrame {
84    /// The chart-specific classes plus the consumer's classes.
85    pub(crate) chart_class: Option<String>,
86    pub(crate) heading: Option<String>,
87    pub(crate) description: Option<String>,
88    pub(crate) value: Option<String>,
89    pub(crate) summary: Option<String>,
90    pub(crate) caption: Option<String>,
91    pub(crate) presentation: ChartPresentation,
92    pub(crate) glass: Glass,
93    /// Marks the root as handling datum activation in Rust.
94    pub(crate) activation: bool,
95    pub(crate) attributes: Vec<Attribute>,
96    /// Receives the mounted `<figure>` (web and desktop) for layout measurements.
97    pub(crate) on_mounted: Option<EventHandler<std::rc::Rc<MountedData>>>,
98}
99
100/// Builds a [`ChartFrame`] from a chart's props struct, which all share the same field names.
101macro_rules! chart_frame {
102    ($props:expr, $class:expr, $summary:expr) => {
103        $crate::charts::frame::ChartFrame {
104            chart_class: Some($class),
105            heading: $props.heading.clone(),
106            description: $props.description.clone(),
107            value: $props.value.clone(),
108            summary: $summary,
109            caption: $props.caption.clone(),
110            presentation: $props.presentation,
111            glass: $props.glass,
112            activation: false,
113            attributes: $props.attributes.clone(),
114            on_mounted: None,
115        }
116    };
117}
118
119pub(crate) use chart_frame;
120
121/// Renders the `<figure class="ui-chart">` frame around `children`.
122pub(crate) fn render_frame(frame: ChartFrame, children: Element) -> Element {
123    let glass = frame.glass.class("ui-chart");
124    let class = compose([
125        Some("ui-chart"),
126        (frame.presentation == ChartPresentation::Bare).then_some("ui-chart--bare"),
127        glass.as_deref(),
128        frame.chart_class.as_deref(),
129    ]);
130    let on_mounted = frame.on_mounted;
131    let has_header = non_empty(frame.heading.as_ref()).is_some()
132        || non_empty(frame.description.as_ref()).is_some()
133        || non_empty(frame.value.as_ref()).is_some();
134
135    rsx! {
136        figure {
137            class,
138            "data-ui-chart-activation": frame.activation.then_some("true"),
139            "data-ui-chart-adapter": frame.activation.then_some("dioxus"),
140            onmounted: move |event| {
141                if let Some(handler) = on_mounted {
142                    handler.call(event.data());
143                }
144            },
145            ..frame.attributes,
146            if has_header {
147                header {
148                    div { class: "ui-chart__heading",
149                        if let Some(heading) = non_empty(frame.heading.as_ref()) {
150                            h3 { "{heading}" }
151                        }
152                        if let Some(description) = non_empty(frame.description.as_ref()) {
153                            p { "{description}" }
154                        }
155                    }
156                    if let Some(value) = non_empty(frame.value.as_ref()) {
157                        strong { "data-ui-chart-value": "true", "{value}" }
158                    }
159                }
160            }
161            if let Some(summary) = non_empty(frame.summary.as_ref()) {
162                p { class: "ui-sr-only", "data-ui-chart-summary": "true", "{summary}" }
163            }
164            {children}
165            if let Some(caption) = non_empty(frame.caption.as_ref()) {
166                figcaption { "{caption}" }
167            }
168        }
169    }
170}
171
172/// React skips empty strings in `{value && …}` conditions.
173fn non_empty(value: Option<&String>) -> Option<&String> {
174    value.filter(|text| !text.is_empty())
175}
176
177/// The text value of a spread attribute such as `aria-label`.
178pub(crate) fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
179    attributes
180        .iter()
181        .find(|attribute| attribute.name == name)
182        .and_then(|attribute| match &attribute.value {
183            dioxus::dioxus_core::AttributeValue::Text(text) => Some(text.clone()),
184            _ => None,
185        })
186}
187
188/// `getChartPlotLabel`: the chart's `aria-label`, then its heading, then the fallback.
189pub(crate) fn plot_label(
190    attributes: &[Attribute],
191    heading: Option<&String>,
192    fallback: &str,
193) -> String {
194    attribute_text(attributes, "aria-label")
195        .or_else(|| heading.cloned())
196        .unwrap_or_else(|| fallback.to_string())
197}
198
199/// The `ui-chart__legend` list for a set of series.
200pub(crate) fn chart_legend(label: &str, series: &[ChartSeries]) -> Element {
201    rsx! {
202        ul { aria_label: "{label}", class: "ui-chart__legend",
203            for (index, item) in series.iter().enumerate() {
204                li { key: "{item.id}", class: ChartTone::resolve(item.tone, index).class_name(),
205                    span { aria_hidden: "true" }
206                    "{item.label}"
207                }
208            }
209        }
210    }
211}
212
213/// `formatReactChartTableValue`.
214pub(crate) fn table_value(
215    value: Option<f64>,
216    format_value: Option<&Callback<f64, String>>,
217    not_available: &str,
218) -> String {
219    match value.filter(|value| value.is_finite()) {
220        Some(value) => format_with(format_value, value),
221        None => not_available.to_string(),
222    }
223}
224
225/// A data table row: its key, its category label, and one `(series id, text)` cell per series.
226type TableRow = (String, String, Vec<(String, String)>);
227
228/// The collapsible `ui-chart__data` table with one row per category and one column per series.
229pub(crate) fn chart_data_table(
230    categories: &[ChartX],
231    format_category: Option<&Callback<ChartX, String>>,
232    format_value: Option<&Callback<f64, String>>,
233    labels: &ChartLabels,
234    series: &[ChartSeries],
235) -> Element {
236    let aligned: Vec<ChartSeries> = series
237        .iter()
238        .map(|item| align_series(item, categories))
239        .collect();
240    let rows: Vec<TableRow> = categories
241        .iter()
242        .map(|category| {
243            let cells = aligned
244                .iter()
245                .map(|item| {
246                    let datum = item.data.iter().find(|candidate| candidate.x == *category);
247                    let text = datum
248                        .and_then(|datum| datum.label.clone())
249                        .unwrap_or_else(|| {
250                            table_value(
251                                datum.and_then(|datum| datum.y),
252                                format_value,
253                                &labels.not_available,
254                            )
255                        });
256
257                    (item.id.clone(), text)
258                })
259                .collect();
260
261            (
262                category.key(),
263                category_label(&aligned, category, format_category, LabelContext::Detail),
264                cells,
265            )
266        })
267        .collect();
268
269    rsx! {
270        details { class: "ui-chart__data",
271            summary { "{labels.view_data}" }
272            div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
273                table {
274                    thead {
275                        tr {
276                            th { scope: "col", "{labels.category}" }
277                            for item in series.iter() {
278                                th { key: "{item.id}", scope: "col", "{item.label}" }
279                            }
280                        }
281                    }
282                    tbody {
283                        for (key, label, cells) in rows {
284                            tr { key: "{key}",
285                                th { scope: "row", "{label}" }
286                                for (id, text) in cells {
287                                    td { key: "{id}", "{text}" }
288                                }
289                            }
290                        }
291                    }
292                }
293            }
294        }
295    }
296}
297
298/// The collapsible `ui-chart__actions` menu: one keyboard-reachable button per clickable mark.
299pub(crate) fn datum_actions(
300    actions: &[Option<DatumAction>],
301    label: &str,
302    on_activate: Option<EventHandler<ChartDatumActivation>>,
303) -> Element {
304    let available: Vec<DatumAction> = actions.iter().flatten().cloned().collect();
305
306    if available.is_empty() {
307        return rsx! {};
308    }
309
310    rsx! {
311        details { class: "ui-chart__actions", "data-ui-chart-actions": "true",
312            summary { "{label}" }
313            ul {
314                for action in available {
315                    li { key: "{action.serialized}",
316                        Button {
317                            variant: ButtonVariant::Ghost,
318                            "data-ui-chart-datum": action.serialized.clone(),
319                            onclick: move |_| {
320                                if let Some(handler) = on_activate {
321                                    handler.call(action.detail.clone());
322                                }
323                            },
324                            "{action.label}"
325                        }
326                    }
327                }
328            }
329        }
330    }
331}
332
333/// A click handler for an clickable SVG mark: primary button only, like lumen-react.
334pub(crate) fn activate_on_click(
335    action: Option<&DatumAction>,
336    on_activate: Option<EventHandler<ChartDatumActivation>>,
337) -> impl FnMut(MouseEvent) + 'static {
338    let detail = action.map(|action| action.detail.clone());
339
340    move |event: MouseEvent| {
341        let primary = event
342            .trigger_button()
343            .is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);
344
345        if !primary {
346            return;
347        }
348
349        if let (Some(handler), Some(detail)) = (on_activate, detail.clone()) {
350            handler.call(detail);
351        }
352    }
353}
354
355/// The datum action's serialized detail, for `data-ui-chart-datum`.
356pub(crate) fn serialized(action: Option<&DatumAction>) -> Option<String> {
357    action.map(|action| action.serialized.clone())
358}
359
360/// A category formatter shortcut used by the series charts.
361pub(crate) fn detail_label(
362    series: &[ChartSeries],
363    category: &ChartX,
364    format_category: Option<&Callback<ChartX, String>>,
365) -> String {
366    category_label(series, category, format_category, LabelContext::Detail)
367}
368
369/// `formatCategory?.(x) ?? String(x)` for tooltips that do not consult `x_label`.
370pub(crate) fn plain_category(
371    category: &ChartX,
372    format: Option<&Callback<ChartX, String>>,
373) -> String {
374    format_category_with(format, category)
375}