lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! [`BarChart`]: grouped or stacked bars, vertical or horizontal.

use std::fmt::Write as _;

use dioxus::prelude::*;

use super::activation::{ChartDatumActivation, DatumAction, motion_key};
use super::format::js_number;
use super::frame::{
    ChartFrame, ChartPresentation, activate_on_click, chart_data_table, chart_legend,
    datum_actions, detail_label, plot_label, render_frame, serialized,
};
use super::geometry::{
    BarChartLayout, BarChartOrientation, BarGeometryOptions, COMPACT_AXIS_LABEL_SIZE, bar_geometry,
    chart_size,
};
use super::model::{ChartDatum, ChartLabels, ChartSeries, ChartX, format_with, summarize};
use super::native_paints::paint_attributes;
use super::scale::{
    CategoryTick, CategoryTickOptions, align_series, category_ticks, chart_categories,
    fitted_label, has_chart_data, scale_value,
};
use crate::class::{Glass, compose};

/// Props for [`BarChart`].
#[derive(Props, Clone, PartialEq)]
pub struct BarChartProps {
    /// SVG coordinate width, at least 240 (default 640).
    pub width: Option<f64>,
    /// SVG coordinate height, at least 240 (default 240).
    pub height: Option<f64>,
    /// The series to compare. Categories come from every series' x values, in first-seen order.
    #[props(default)]
    pub series: Vec<ChartSeries>,
    /// Grouped (default) or stacked bars.
    #[props(default)]
    pub layout: BarChartLayout,
    /// Vertical (default) or horizontal bars.
    #[props(default)]
    pub orientation: BarChartOrientation,
    /// The category label column width of horizontal bars, from 64 to 240 (default 160).
    pub category_width: Option<f64>,
    /// Formats values on the axis, in tooltips, and in the table. Without it, tooltips and the table
    /// use `String(value)` and axis ticks use grouped `en-US` numbers (`1,000`), switching the whole
    /// axis to compact notation (`15K`) when a label would exceed five characters.
    pub format_value: Option<Callback<f64, String>>,
    /// Formats categories in tooltips and the table (axis labels prefer `x_label`).
    pub format_category: Option<Callback<ChartX, String>>,
    /// Text shown instead of the plot when there is no data.
    #[props(into)]
    pub empty_label: Option<String>,
    /// Localized chart text.
    pub labels: Option<ChartLabels>,
    /// Shows the legend. Defaults to `true` with more than one series.
    pub show_legend: Option<bool>,
    /// Shows the collapsible data table.
    #[props(default = true)]
    pub show_table: bool,
    /// Makes every bar clickable with a pointer and through 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 TickText {
    key: String,
    anchor: &'static str,
    x: String,
    label: String,
}

struct BarRect {
    paints: Vec<Attribute>,
    key: String,
    class: &'static str,
    motion_key: String,
    datum: Option<String>,
    x: String,
    y: String,
    width: String,
    height: String,
    title: String,
    hit: [String; 4],
    action: Option<DatumAction>,
}

/// Compares values across categories with grouped or stacked bars, with a legend, a screen reader
/// summary, a data table, and optional datum activation.
#[component]
#[allow(clippy::too_many_lines)]
pub fn BarChart(props: BarChartProps) -> Element {
    let native_paints =
        super::native_paints::use_native_chart_paints(super::model::ChartTone::Series1);
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value.as_ref();
    let format_category = props.format_category.as_ref();
    let horizontal = props.orientation == BarChartOrientation::Horizontal;
    let categories = chart_categories(&props.series);
    let aligned: Vec<ChartSeries> = props
        .series
        .iter()
        .map(|item| align_series(item, &categories))
        .collect();
    let geometry = bar_geometry(
        &aligned,
        &BarGeometryOptions {
            axis_font_size: Some(COMPACT_AXIS_LABEL_SIZE),
            category_width: Some(props.category_width.unwrap_or(160.0)),
            domain: None,
            format_category,
            format_value,
            height: chart_size(props.height, 240.0),
            layout: props.layout,
            orientation: props.orientation,
            width: chart_size(props.width, 640.0),
        },
    );
    let has_data = has_chart_data(&aligned);
    let show_legend = props.show_legend.unwrap_or(props.series.len() > 1);
    let ticks = &geometry.ticks;
    let margin = geometry.margin;
    let plot_end = geometry.width - margin.right;
    let category_labels: Vec<String> = geometry
        .categories
        .iter()
        .map(|category| category.label.clone())
        .collect();
    let category_positions: Vec<f64> = geometry
        .categories
        .iter()
        .map(|category| category.x)
        .collect();
    let tick_texts = |font_size: Option<f64>| -> Vec<TickText> {
        let mut options = CategoryTickOptions::new(margin.left, plot_end)
            .bounds(0.0, geometry.width)
            .positions(&category_positions);

        if let Some(size) = font_size {
            options = options.font_size(size);
        }

        category_ticks(&category_labels, options)
            .into_iter()
            .map(|tick| TickText {
                key: tick.index.to_string(),
                anchor: CategoryTick::ANCHOR,
                x: js_number(tick.position),
                label: tick.label,
            })
            .collect()
    };
    let regular_ticks = tick_texts(None);
    let compact_ticks = tick_texts(Some(COMPACT_AXIS_LABEL_SIZE));
    let value_positions: Vec<f64> = ticks
        .iter()
        .map(|tick| scale_value(*tick, geometry.domain, margin.left, plot_end))
        .collect();
    // Value labels are culled at the larger compact label size so no width needs a second pass.
    let value_ticks: Vec<TickText> = category_ticks(
        &geometry.tick_labels,
        CategoryTickOptions::new(margin.left, plot_end)
            .bounds(0.0, geometry.width)
            .font_size(COMPACT_AXIS_LABEL_SIZE)
            .positions(&value_positions),
    )
    .into_iter()
    .map(|tick| TickText {
        key: tick.index.to_string(),
        anchor: CategoryTick::ANCHOR,
        x: js_number(tick.position),
        label: tick.label,
    })
    .collect();
    let grid: Vec<(String, String, String)> = ticks
        .iter()
        .zip(&geometry.tick_labels)
        .map(|(tick, label)| {
            let coordinate = if horizontal {
                scale_value(*tick, geometry.domain, margin.left, plot_end)
            } else {
                scale_value(
                    *tick,
                    geometry.domain,
                    geometry.height - margin.bottom,
                    margin.top,
                )
            };

            (js_number(*tick), js_number(coordinate), label.clone())
        })
        .collect();
    let category_rows: Vec<(String, String, String, String)> = geometry
        .categories
        .iter()
        .map(|category| {
            (
                category.category.key(),
                js_number(category.x),
                js_number(category.y),
                fitted_label(&category.label, margin.left - 16.0),
            )
        })
        .collect();
    let on_activate = props.on_datum_activate;
    let bars: Vec<BarRect> = geometry
        .marks
        .iter()
        .map(|mark| {
            let context = format!(
                "{} · {}: {}",
                detail_label(&aligned, &mark.category, format_category),
                mark.series_label,
                format_with(format_value, mark.value)
            );
            let action = on_activate.and_then(|_| {
                let mut datum = ChartDatum::new(mark.category.clone(), mark.value);
                datum.id.clone_from(&mark.datum_id);

                DatumAction::new(
                    ChartDatumActivation::series(&mark.series_id, &datum),
                    &context,
                    &labels,
                )
            });
            let hit_width = mark.width.max(12.0);
            let hit_height = mark.height.max(12.0);

            BarRect {
                paints: paint_attributes(native_paints, "bar", Some(mark.tone)),
                key: format!("{}:{}", mark.series_id, mark.category.key()),
                class: mark.tone.class_name(),
                motion_key: motion_key(&mark.series_id, mark.datum_id.as_ref(), &mark.category),
                datum: serialized(action.as_ref()),
                x: js_number(mark.x),
                y: js_number(mark.y),
                width: js_number(mark.width),
                height: js_number(mark.height),
                title: context,
                hit: [
                    js_number(hit_width),
                    js_number(hit_height),
                    js_number(mark.x - (12.0 - mark.width).max(0.0) / 2.0),
                    js_number(mark.y - (12.0 - mark.height).max(0.0) / 2.0),
                ],
                action,
            }
        })
        .collect();
    let actions: Vec<Option<DatumAction>> = bars.iter().map(|bar| bar.action.clone()).collect();
    let summary = props
        .summary
        .clone()
        .or_else(|| Some(labels.summary(summarize(&aligned, format_value))));
    let plot_name = plot_label(
        &props.attributes,
        props.heading.as_ref(),
        &labels.chart_data,
    );
    let frame = ChartFrame {
        chart_class: Some(compose([Some("ui-bar-chart"), 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 view_box = format!(
        "0 0 {} {}",
        js_number(geometry.width),
        js_number(geometry.height)
    );
    let viewbox_width = js_number(geometry.width);
    let viewbox_height = js_number(geometry.height);
    let mut svg_style = format!("--ui-chart-viewbox-width: {viewbox_width}");
    if native_paints.is_some() {
        let _ = write!(
            svg_style,
            ";width:{viewbox_width}px;height:auto;max-width:100%;min-width:0;aspect-ratio:{viewbox_width}/{viewbox_height}"
        );
    }
    let left = js_number(margin.left);
    let right = js_number(plot_end);
    let top = js_number(margin.top);
    let bottom = js_number(geometry.height - margin.bottom);
    let label_x = js_number(margin.left - 8.0);
    let category_y = js_number(geometry.height - 20.0);
    let value_y = js_number(geometry.height - 6.0);
    let body = rsx! {
        if show_legend && has_data {
            {chart_legend(&labels.chart_legend, &props.series)}
        }
        if !has_data {
            p { class: "ui-chart__empty", role: "status",
                "{props.empty_label.clone().unwrap_or_else(|| labels.empty.clone())}"
            }
        }
        div {
            aria_label: "{plot_name}",
            class: "ui-chart__plot",
            role: "region",
            tabindex: "0",
            hidden: (!has_data).then_some(true),
            svg {
                "aria-hidden": "true",
                "preserveAspectRatio": "xMidYMid meet",
                "style": "{svg_style}",
                "viewBox": "{view_box}",
                width: native_paints.map(|_| viewbox_width.clone()),
                height: native_paints.map(|_| viewbox_height.clone()),
                g { class: "ui-chart__grid",
                    for (key, coordinate, text) in grid {
                        if horizontal {
                            line {
                                key: "{key}", x1: "{coordinate}", x2: "{coordinate}", y1: "{top}", y2: "{bottom}",
                                ..paint_attributes(native_paints, "grid-line", None),
                            }
                        } else {
                            line {
                                key: "{key}-line", x1: "{left}", x2: "{right}", y1: "{coordinate}", y2: "{coordinate}",
                                ..paint_attributes(native_paints, "grid-line", None),
                            }
                            text {
                                x: "{label_x}", y: "{coordinate}",
                                ..paint_attributes(native_paints, "grid-label", None),
                                "{text}"
                            }
                        }
                    }
                }
                g { class: "ui-chart__axis-labels",
                    ..paint_attributes(native_paints, "axis-label", None),
                    if horizontal {
                        for (key, x, y, label) in category_rows {
                            text {
                                key: "{key}",
                                "dominant-baseline": "middle",
                                "text-anchor": "end",
                                x: "{x}",
                                y: "{y}",
                                "{label}"
                            }
                        }
                    } else {
                        g { class: "ui-chart__category-labels--regular",
                            for tick in regular_ticks {
                                text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{category_y}", "{tick.label}" }
                            }
                        }
                        g { class: "ui-chart__category-labels--compact",
                            ..paint_attributes(native_paints, "compact-labels", None),
                            for tick in compact_ticks {
                                text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{category_y}", "{tick.label}" }
                            }
                        }
                    }
                }
                if horizontal {
                    g { class: "ui-chart__axis-labels",
                        ..paint_attributes(native_paints, "axis-label", None),
                        for tick in value_ticks {
                            text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{value_y}", "{tick.label}" }
                        }
                    }
                }
                g { class: "ui-bar-chart__marks",
                    for bar in bars.iter() {
                        rect {
                            key: "{bar.key}",
                            class: bar.class,
                            "data-ui-chart-motion-key": "{bar.motion_key}",
                            "data-ui-chart-datum": bar.datum.clone(),
                            height: "{bar.height}",
                            rx: native_paints.is_none().then_some("4"),
                            width: "{bar.width}",
                            x: "{bar.x}",
                            y: "{bar.y}",
                            onclick: activate_on_click(bar.action.as_ref(), on_activate),
                            ..bar.paints.clone(),
                            title { "{bar.title}" }
                        }
                    }
                    if on_activate.is_some() {
                        for bar in bars.iter() {
                            rect {
                                key: "hit-{bar.key}",
                                class: "ui-chart__datum-hit",
                                width: "{bar.hit[0]}",
                                height: "{bar.hit[1]}",
                                x: "{bar.hit[2]}",
                                y: "{bar.hit[3]}",
                                "data-ui-chart-datum": bar.datum.clone(),
                                onclick: activate_on_click(bar.action.as_ref(), on_activate),
                                ..paint_attributes(native_paints, "datum-hit", None),
                            }
                        }
                    }
                }
            }
        }
        if props.show_table && has_data {
            {chart_data_table(&categories, format_category, format_value, &labels, &props.series)}
        }
        if on_activate.is_some() {
            {datum_actions(&actions, &labels.explore_data, on_activate)}
        }
    };

    render_frame(frame, body)
}