Skip to main content

lumen_dioxus/charts/
bar.rs

1//! [`BarChart`]: grouped or stacked bars, vertical or horizontal.
2
3use std::fmt::Write as _;
4
5use dioxus::prelude::*;
6
7use super::activation::{ChartDatumActivation, DatumAction, motion_key};
8use super::format::js_number;
9use super::frame::{
10    ChartFrame, ChartPresentation, activate_on_click, chart_data_table, chart_legend,
11    datum_actions, detail_label, plot_label, render_frame, serialized,
12};
13use super::geometry::{
14    BarChartLayout, BarChartOrientation, BarGeometryOptions, COMPACT_AXIS_LABEL_SIZE, bar_geometry,
15    chart_size,
16};
17use super::model::{ChartDatum, ChartLabels, ChartSeries, ChartX, format_with, summarize};
18use super::native_paints::paint_attributes;
19use super::scale::{
20    CategoryTick, CategoryTickOptions, align_series, category_ticks, chart_categories,
21    fitted_label, has_chart_data, scale_value,
22};
23use crate::class::{Glass, compose};
24
25/// Props for [`BarChart`].
26#[derive(Props, Clone, PartialEq)]
27pub struct BarChartProps {
28    /// SVG coordinate width, at least 240 (default 640).
29    pub width: Option<f64>,
30    /// SVG coordinate height, at least 240 (default 240).
31    pub height: Option<f64>,
32    /// The series to compare. Categories come from every series' x values, in first-seen order.
33    #[props(default)]
34    pub series: Vec<ChartSeries>,
35    /// Grouped (default) or stacked bars.
36    #[props(default)]
37    pub layout: BarChartLayout,
38    /// Vertical (default) or horizontal bars.
39    #[props(default)]
40    pub orientation: BarChartOrientation,
41    /// The category label column width of horizontal bars, from 64 to 240 (default 160).
42    pub category_width: Option<f64>,
43    /// Formats values on the axis, in tooltips, and in the table. Without it, tooltips and the table
44    /// use `String(value)` and axis ticks use grouped `en-US` numbers (`1,000`), switching the whole
45    /// axis to compact notation (`15K`) when a label would exceed five characters.
46    pub format_value: Option<Callback<f64, String>>,
47    /// Formats categories in tooltips and the table (axis labels prefer `x_label`).
48    pub format_category: Option<Callback<ChartX, String>>,
49    /// Text shown instead of the plot when there is no data.
50    #[props(into)]
51    pub empty_label: Option<String>,
52    /// Localized chart text.
53    pub labels: Option<ChartLabels>,
54    /// Shows the legend. Defaults to `true` with more than one series.
55    pub show_legend: Option<bool>,
56    /// Shows the collapsible data table.
57    #[props(default = true)]
58    pub show_table: bool,
59    /// Makes every bar clickable with a pointer and through a keyboard-reachable action menu.
60    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
61    /// The chart title.
62    #[props(into)]
63    pub heading: Option<String>,
64    /// Supporting text under the heading.
65    #[props(into)]
66    pub description: Option<String>,
67    /// A headline value beside the heading.
68    #[props(into)]
69    pub value: Option<String>,
70    /// A screen reader summary; defaults to a generated description of the data.
71    #[props(into)]
72    pub summary: Option<String>,
73    /// A visible caption, such as the data source.
74    #[props(into)]
75    pub caption: Option<String>,
76    /// `Bare` removes the card chrome.
77    #[props(default)]
78    pub presentation: ChartPresentation,
79    /// Glass intensity.
80    #[props(default, into)]
81    pub glass: Glass,
82    /// Extra classes appended after the Lumen classes.
83    #[props(into)]
84    pub class: Option<String>,
85    /// Any other `<figure>` or global attribute.
86    #[props(extends = GlobalAttributes, extends = figure)]
87    pub attributes: Vec<Attribute>,
88}
89
90struct TickText {
91    key: String,
92    anchor: &'static str,
93    x: String,
94    label: String,
95}
96
97struct BarRect {
98    paints: Vec<Attribute>,
99    key: String,
100    class: &'static str,
101    motion_key: String,
102    datum: Option<String>,
103    x: String,
104    y: String,
105    width: String,
106    height: String,
107    title: String,
108    hit: [String; 4],
109    action: Option<DatumAction>,
110}
111
112/// Compares values across categories with grouped or stacked bars, with a legend, a screen reader
113/// summary, a data table, and optional datum activation.
114#[component]
115#[allow(clippy::too_many_lines)]
116pub fn BarChart(props: BarChartProps) -> Element {
117    let native_paints =
118        super::native_paints::use_native_chart_paints(super::model::ChartTone::Series1);
119    let labels = props.labels.clone().unwrap_or_default();
120    let format_value = props.format_value.as_ref();
121    let format_category = props.format_category.as_ref();
122    let horizontal = props.orientation == BarChartOrientation::Horizontal;
123    let categories = chart_categories(&props.series);
124    let aligned: Vec<ChartSeries> = props
125        .series
126        .iter()
127        .map(|item| align_series(item, &categories))
128        .collect();
129    let geometry = bar_geometry(
130        &aligned,
131        &BarGeometryOptions {
132            axis_font_size: Some(COMPACT_AXIS_LABEL_SIZE),
133            category_width: Some(props.category_width.unwrap_or(160.0)),
134            domain: None,
135            format_category,
136            format_value,
137            height: chart_size(props.height, 240.0),
138            layout: props.layout,
139            orientation: props.orientation,
140            width: chart_size(props.width, 640.0),
141        },
142    );
143    let has_data = has_chart_data(&aligned);
144    let show_legend = props.show_legend.unwrap_or(props.series.len() > 1);
145    let ticks = &geometry.ticks;
146    let margin = geometry.margin;
147    let plot_end = geometry.width - margin.right;
148    let category_labels: Vec<String> = geometry
149        .categories
150        .iter()
151        .map(|category| category.label.clone())
152        .collect();
153    let category_positions: Vec<f64> = geometry
154        .categories
155        .iter()
156        .map(|category| category.x)
157        .collect();
158    let tick_texts = |font_size: Option<f64>| -> Vec<TickText> {
159        let mut options = CategoryTickOptions::new(margin.left, plot_end)
160            .bounds(0.0, geometry.width)
161            .positions(&category_positions);
162
163        if let Some(size) = font_size {
164            options = options.font_size(size);
165        }
166
167        category_ticks(&category_labels, options)
168            .into_iter()
169            .map(|tick| TickText {
170                key: tick.index.to_string(),
171                anchor: CategoryTick::ANCHOR,
172                x: js_number(tick.position),
173                label: tick.label,
174            })
175            .collect()
176    };
177    let regular_ticks = tick_texts(None);
178    let compact_ticks = tick_texts(Some(COMPACT_AXIS_LABEL_SIZE));
179    let value_positions: Vec<f64> = ticks
180        .iter()
181        .map(|tick| scale_value(*tick, geometry.domain, margin.left, plot_end))
182        .collect();
183    // Value labels are culled at the larger compact label size so no width needs a second pass.
184    let value_ticks: Vec<TickText> = category_ticks(
185        &geometry.tick_labels,
186        CategoryTickOptions::new(margin.left, plot_end)
187            .bounds(0.0, geometry.width)
188            .font_size(COMPACT_AXIS_LABEL_SIZE)
189            .positions(&value_positions),
190    )
191    .into_iter()
192    .map(|tick| TickText {
193        key: tick.index.to_string(),
194        anchor: CategoryTick::ANCHOR,
195        x: js_number(tick.position),
196        label: tick.label,
197    })
198    .collect();
199    let grid: Vec<(String, String, String)> = ticks
200        .iter()
201        .zip(&geometry.tick_labels)
202        .map(|(tick, label)| {
203            let coordinate = if horizontal {
204                scale_value(*tick, geometry.domain, margin.left, plot_end)
205            } else {
206                scale_value(
207                    *tick,
208                    geometry.domain,
209                    geometry.height - margin.bottom,
210                    margin.top,
211                )
212            };
213
214            (js_number(*tick), js_number(coordinate), label.clone())
215        })
216        .collect();
217    let category_rows: Vec<(String, String, String, String)> = geometry
218        .categories
219        .iter()
220        .map(|category| {
221            (
222                category.category.key(),
223                js_number(category.x),
224                js_number(category.y),
225                fitted_label(&category.label, margin.left - 16.0),
226            )
227        })
228        .collect();
229    let on_activate = props.on_datum_activate;
230    let bars: Vec<BarRect> = geometry
231        .marks
232        .iter()
233        .map(|mark| {
234            let context = format!(
235                "{} ยท {}: {}",
236                detail_label(&aligned, &mark.category, format_category),
237                mark.series_label,
238                format_with(format_value, mark.value)
239            );
240            let action = on_activate.and_then(|_| {
241                let mut datum = ChartDatum::new(mark.category.clone(), mark.value);
242                datum.id.clone_from(&mark.datum_id);
243
244                DatumAction::new(
245                    ChartDatumActivation::series(&mark.series_id, &datum),
246                    &context,
247                    &labels,
248                )
249            });
250            let hit_width = mark.width.max(12.0);
251            let hit_height = mark.height.max(12.0);
252
253            BarRect {
254                paints: paint_attributes(native_paints, "bar", Some(mark.tone)),
255                key: format!("{}:{}", mark.series_id, mark.category.key()),
256                class: mark.tone.class_name(),
257                motion_key: motion_key(&mark.series_id, mark.datum_id.as_ref(), &mark.category),
258                datum: serialized(action.as_ref()),
259                x: js_number(mark.x),
260                y: js_number(mark.y),
261                width: js_number(mark.width),
262                height: js_number(mark.height),
263                title: context,
264                hit: [
265                    js_number(hit_width),
266                    js_number(hit_height),
267                    js_number(mark.x - (12.0 - mark.width).max(0.0) / 2.0),
268                    js_number(mark.y - (12.0 - mark.height).max(0.0) / 2.0),
269                ],
270                action,
271            }
272        })
273        .collect();
274    let actions: Vec<Option<DatumAction>> = bars.iter().map(|bar| bar.action.clone()).collect();
275    let summary = props
276        .summary
277        .clone()
278        .or_else(|| Some(labels.summary(summarize(&aligned, format_value))));
279    let plot_name = plot_label(
280        &props.attributes,
281        props.heading.as_ref(),
282        &labels.chart_data,
283    );
284    let frame = ChartFrame {
285        chart_class: Some(compose([Some("ui-bar-chart"), props.class.as_deref()])),
286        heading: props.heading.clone(),
287        description: props.description.clone(),
288        value: props.value.clone(),
289        summary,
290        caption: props.caption.clone(),
291        presentation: props.presentation,
292        glass: props.glass,
293        activation: on_activate.is_some(),
294        attributes: props.attributes.clone(),
295        on_mounted: None,
296    };
297    let view_box = format!(
298        "0 0 {} {}",
299        js_number(geometry.width),
300        js_number(geometry.height)
301    );
302    let viewbox_width = js_number(geometry.width);
303    let viewbox_height = js_number(geometry.height);
304    let mut svg_style = format!("--ui-chart-viewbox-width: {viewbox_width}");
305    if native_paints.is_some() {
306        let _ = write!(
307            svg_style,
308            ";width:{viewbox_width}px;height:auto;max-width:100%;min-width:0;aspect-ratio:{viewbox_width}/{viewbox_height}"
309        );
310    }
311    let left = js_number(margin.left);
312    let right = js_number(plot_end);
313    let top = js_number(margin.top);
314    let bottom = js_number(geometry.height - margin.bottom);
315    let label_x = js_number(margin.left - 8.0);
316    let category_y = js_number(geometry.height - 20.0);
317    let value_y = js_number(geometry.height - 6.0);
318    let body = rsx! {
319        if show_legend && has_data {
320            {chart_legend(&labels.chart_legend, &props.series)}
321        }
322        if !has_data {
323            p { class: "ui-chart__empty", role: "status",
324                "{props.empty_label.clone().unwrap_or_else(|| labels.empty.clone())}"
325            }
326        }
327        div {
328            aria_label: "{plot_name}",
329            class: "ui-chart__plot",
330            role: "region",
331            tabindex: "0",
332            hidden: (!has_data).then_some(true),
333            svg {
334                "aria-hidden": "true",
335                "preserveAspectRatio": "xMidYMid meet",
336                "style": "{svg_style}",
337                "viewBox": "{view_box}",
338                width: native_paints.map(|_| viewbox_width.clone()),
339                height: native_paints.map(|_| viewbox_height.clone()),
340                g { class: "ui-chart__grid",
341                    for (key, coordinate, text) in grid {
342                        if horizontal {
343                            line {
344                                key: "{key}", x1: "{coordinate}", x2: "{coordinate}", y1: "{top}", y2: "{bottom}",
345                                ..paint_attributes(native_paints, "grid-line", None),
346                            }
347                        } else {
348                            line {
349                                key: "{key}-line", x1: "{left}", x2: "{right}", y1: "{coordinate}", y2: "{coordinate}",
350                                ..paint_attributes(native_paints, "grid-line", None),
351                            }
352                            text {
353                                x: "{label_x}", y: "{coordinate}",
354                                ..paint_attributes(native_paints, "grid-label", None),
355                                "{text}"
356                            }
357                        }
358                    }
359                }
360                g { class: "ui-chart__axis-labels",
361                    ..paint_attributes(native_paints, "axis-label", None),
362                    if horizontal {
363                        for (key, x, y, label) in category_rows {
364                            text {
365                                key: "{key}",
366                                "dominant-baseline": "middle",
367                                "text-anchor": "end",
368                                x: "{x}",
369                                y: "{y}",
370                                "{label}"
371                            }
372                        }
373                    } else {
374                        g { class: "ui-chart__category-labels--regular",
375                            for tick in regular_ticks {
376                                text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{category_y}", "{tick.label}" }
377                            }
378                        }
379                        g { class: "ui-chart__category-labels--compact",
380                            ..paint_attributes(native_paints, "compact-labels", None),
381                            for tick in compact_ticks {
382                                text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{category_y}", "{tick.label}" }
383                            }
384                        }
385                    }
386                }
387                if horizontal {
388                    g { class: "ui-chart__axis-labels",
389                        ..paint_attributes(native_paints, "axis-label", None),
390                        for tick in value_ticks {
391                            text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{value_y}", "{tick.label}" }
392                        }
393                    }
394                }
395                g { class: "ui-bar-chart__marks",
396                    for bar in bars.iter() {
397                        rect {
398                            key: "{bar.key}",
399                            class: bar.class,
400                            "data-ui-chart-motion-key": "{bar.motion_key}",
401                            "data-ui-chart-datum": bar.datum.clone(),
402                            height: "{bar.height}",
403                            rx: native_paints.is_none().then_some("4"),
404                            width: "{bar.width}",
405                            x: "{bar.x}",
406                            y: "{bar.y}",
407                            onclick: activate_on_click(bar.action.as_ref(), on_activate),
408                            ..bar.paints.clone(),
409                            title { "{bar.title}" }
410                        }
411                    }
412                    if on_activate.is_some() {
413                        for bar in bars.iter() {
414                            rect {
415                                key: "hit-{bar.key}",
416                                class: "ui-chart__datum-hit",
417                                width: "{bar.hit[0]}",
418                                height: "{bar.hit[1]}",
419                                x: "{bar.hit[2]}",
420                                y: "{bar.hit[3]}",
421                                "data-ui-chart-datum": bar.datum.clone(),
422                                onclick: activate_on_click(bar.action.as_ref(), on_activate),
423                                ..paint_attributes(native_paints, "datum-hit", None),
424                            }
425                        }
426                    }
427                }
428            }
429        }
430        if props.show_table && has_data {
431            {chart_data_table(&categories, format_category, format_value, &labels, &props.series)}
432        }
433        if on_activate.is_some() {
434            {datum_actions(&actions, &labels.explore_data, on_activate)}
435        }
436    };
437
438    render_frame(frame, body)
439}