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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! [`ComboChart`]: bars, lines, and areas on one shared value scale.

use std::collections::{HashMap, HashSet};

use dioxus::prelude::*;

use super::activation::{ChartDatumActivation, DatumAction};
use super::format::js_number;
use super::frame::{
    ChartFrame, ChartPresentation, activate_on_click, chart_data_table, chart_legend,
    datum_actions, plot_label, render_frame, serialized,
};
use super::geometry::{
    BarGeometryOptions, COMPACT_AXIS_LABEL_SIZE, LineChartScale, LineGeometryOptions, bar_geometry,
    chart_size, line_geometry,
};
use super::model::{
    ChartBounds, ChartDatum, ChartLabels, ChartSeries, ChartSeriesDash, ChartTone, ChartX,
    format_with, summarize,
};
use super::scale::{
    CategoryTick, CategoryTickOptions, LabelContext, align_series, axis_domain, category_label,
    category_ticks, chart_categories, chart_ticks, format_ticks, has_chart_data, scale_value,
};
use crate::class::{Glass, compose};

/// How a [`ComboChartSeries`] is drawn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ComboChartMark {
    /// Bars, grouped with the other bar series.
    #[default]
    Bar,
    /// A line with point markers.
    Line,
    /// A line with a filled area.
    Area,
}

/// A series of a [`ComboChart`] and how it is drawn.
#[derive(Clone, Debug, PartialEq)]
pub struct ComboChartSeries {
    /// The data.
    pub series: ChartSeries,
    /// The mark.
    pub mark: ComboChartMark,
}

impl ComboChartSeries {
    /// A series drawn with `mark`.
    pub fn new(mark: ComboChartMark, series: ChartSeries) -> Self {
        Self { series, mark }
    }

    /// A bar series.
    pub fn bar(series: ChartSeries) -> Self {
        Self::new(ComboChartMark::Bar, series)
    }

    /// A line series.
    pub fn line(series: ChartSeries) -> Self {
        Self::new(ComboChartMark::Line, series)
    }

    /// An area series.
    pub fn area(series: ChartSeries) -> Self {
        Self::new(ComboChartMark::Area, series)
    }
}

/// Props for [`ComboChart`].
#[derive(Props, Clone, PartialEq)]
pub struct ComboChartProps {
    /// SVG coordinate width, at least 240 (default 640).
    pub width: Option<f64>,
    /// SVG coordinate height, at least 240 (default 320).
    pub height: Option<f64>,
    /// The series and their marks. Every series shares one value scale that includes zero.
    #[props(default)]
    pub series: Vec<ComboChartSeries>,
    /// 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>>,
    /// 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 bar and point 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 BarView {
    key: String,
    class: &'static str,
    x: String,
    y: String,
    width: String,
    height: String,
    title: String,
    hit: [String; 4],
    action: Option<DatumAction>,
}

struct PointView {
    key: String,
    cx: String,
    cy: String,
    action: Option<DatumAction>,
}

struct LineView {
    dash: Option<ChartSeriesDash>,
    key: String,
    class: String,
    areas: Vec<String>,
    path: String,
    points: Vec<PointView>,
}

/// Combines bars with lines or areas that share one value scale, such as revenue bars with a
/// margin line, with a legend, a data table, and optional datum activation.
#[component]
#[allow(clippy::too_many_lines)]
pub fn ComboChart(props: ComboChartProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value.as_ref();
    let width = chart_size(props.width, 640.0);
    let height = chart_size(props.height, 320.0);
    let padding = 44.0;
    let on_activate = props.on_datum_activate;
    let plain: Vec<ChartSeries> = props
        .series
        .iter()
        .map(|item| item.series.clone())
        .collect();
    let categories = chart_categories(&plain);
    let aligned: Vec<(ComboChartMark, ChartSeries)> = props
        .series
        .iter()
        .map(|item| (item.mark, align_series(&item.series, &categories)))
        .collect();
    let values: Vec<Option<f64>> = aligned
        .iter()
        .flat_map(|(_, series)| series.data.iter().map(|datum| datum.y))
        .collect();
    let domain = axis_domain(&values, None, true);
    let bar_series: Vec<ChartSeries> = aligned
        .iter()
        .filter(|(mark, _)| *mark == ComboChartMark::Bar)
        .map(|(_, series)| series.clone())
        .collect();
    let line_series: Vec<(ComboChartMark, ChartSeries)> = aligned
        .iter()
        .filter(|(mark, _)| *mark != ComboChartMark::Bar)
        .cloned()
        .collect();
    let has_bars = !bar_series.is_empty();
    let all_aligned: Vec<ChartSeries> = aligned.iter().map(|(_, series)| series.clone()).collect();
    let mut bars = bar_geometry(
        if has_bars { &bar_series } else { &all_aligned },
        &BarGeometryOptions {
            axis_font_size: Some(COMPACT_AXIS_LABEL_SIZE),
            format_value,
            domain: Some(domain.into()),
            height,
            width,
            ..BarGeometryOptions::default()
        },
    );
    let bar_ids: HashSet<&str> = bar_series.iter().map(|item| item.id.as_str()).collect();
    bars.marks
        .retain(|mark| bar_ids.contains(mark.series_id.as_str()));
    let category_positions: HashMap<String, f64> = bars
        .categories
        .iter()
        .map(|category| (category.category.key(), category.x))
        .collect();
    let drawable_width = width - padding * 2.0;
    let align_line_datum = |datum: &ChartDatum| -> ChartDatum {
        if !has_bars {
            return datum.clone();
        }

        let position = category_positions
            .get(&datum.x.key())
            .copied()
            .unwrap_or(padding);

        ChartDatum {
            x: ChartX::Number((position - padding) / drawable_width),
            ..datum.clone()
        }
    };
    let mut line_options = LineGeometryOptions::new(width, height, padding);
    line_options.domain = Some(ChartBounds::from(domain));

    line_options.padding_bottom = bars.margin.bottom;
    line_options.padding_top = bars.margin.top;
    if has_bars {
        line_options.x_domain = Some(ChartBounds::new(0.0, 1.0));
        line_options.x_scale = LineChartScale::Linear;
    } else {
        line_options.padding_left = bars.margin.left;
        line_options.padding_right = bars.margin.right;
    }

    let lines: Vec<_> = line_series
        .iter()
        .map(|(_, item)| {
            let data: Vec<ChartDatum> = item.data.iter().map(align_line_datum).collect();
            line_geometry(&data, line_options)
        })
        .collect();
    let has_data = has_chart_data(&plain);
    let bar_views: Vec<BarView> = bars
        .marks
        .iter()
        .map(|mark| {
            let action = on_activate.and_then(|_| {
                let item = bar_series
                    .iter()
                    .find(|candidate| candidate.id == mark.series_id)?;
                let datum = item
                    .data
                    .iter()
                    .find(|candidate| candidate.x == mark.category)?;
                let context = format!(
                    "{} · {}: {}",
                    datum.x_label.clone().unwrap_or_else(|| datum.x.display()),
                    item.label,
                    datum
                        .label
                        .clone()
                        .unwrap_or_else(|| format_with(format_value, mark.value))
                );

                DatumAction::new(
                    ChartDatumActivation::series(&item.id, datum),
                    &context,
                    &labels,
                )
            });

            BarView {
                key: format!("{}:{}", mark.series_id, mark.category.key()),
                class: mark.tone.class_name(),
                x: js_number(mark.x),
                y: js_number(mark.y),
                width: js_number(mark.width),
                height: js_number(mark.height),
                title: format!(
                    "{}: {}",
                    mark.series_label,
                    format_with(format_value, mark.value)
                ),
                hit: [
                    js_number(mark.width.max(12.0)),
                    js_number(mark.height.max(12.0)),
                    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 line_views: Vec<LineView> = lines
        .iter()
        .zip(&line_series)
        .enumerate()
        .map(|(index, (geometry, (mark, item)))| {
            let tone = ChartTone::resolve(item.tone, index + bar_series.len());
            let points = geometry
                .points
                .iter()
                .map(|point| {
                    let action = on_activate.and_then(|_| {
                        let datum = item
                            .data
                            .iter()
                            .find(|candidate| align_line_datum(candidate).x == point.datum.x)?;
                        let context = format!(
                            "{} · {}: {}",
                            datum.x_label.clone().unwrap_or_else(|| datum.x.display()),
                            item.label,
                            datum.label.clone().unwrap_or_else(|| {
                                format_with(format_value, point.datum.y.unwrap_or(0.0))
                            })
                        );

                        DatumAction::new(
                            ChartDatumActivation::series(&item.id, datum),
                            &context,
                            &labels,
                        )
                    });

                    PointView {
                        key: point
                            .datum
                            .id
                            .clone()
                            .unwrap_or_else(|| point.datum.x.key()),
                        cx: js_number(point.x),
                        cy: js_number(point.y),
                        action,
                    }
                })
                .collect();

            LineView {
                key: item.id.clone(),
                class: compose([Some("ui-line-chart__series"), Some(tone.class_name())]),
                areas: if *mark == ComboChartMark::Area {
                    geometry.area_paths.clone()
                } else {
                    Vec::new()
                },
                dash: item.dash,
                path: geometry.path.clone(),
                points,
            }
        })
        .collect();
    let actions: Vec<Option<DatumAction>> = bar_views
        .iter()
        .map(|bar| bar.action.clone())
        .chain(
            line_views
                .iter()
                .flat_map(|line| line.points.iter().map(|point| point.action.clone())),
        )
        .collect();
    let (plot_top, plot_bottom, plot_left, plot_right) = (
        bars.margin.top,
        height - bars.margin.bottom,
        bars.margin.left,
        width - bars.margin.right,
    );
    let ticks = chart_ticks(domain);
    let grid: Vec<(String, String, String)> = ticks
        .iter()
        .zip(format_ticks(&ticks, format_value))
        .map(|(tick, label)| {
            (
                js_number(*tick),
                js_number(scale_value(*tick, domain, plot_bottom, plot_top)),
                label,
            )
        })
        .collect();
    let category_labels: Vec<String> = categories
        .iter()
        .map(|category| category_label(&plain, category, None, LabelContext::Axis))
        .collect();
    let bar_positions: Vec<f64> = bars.categories.iter().map(|category| category.x).collect();
    let mut tick_options = CategoryTickOptions::new(plot_left, plot_right)
        .bounds(0.0, width)
        .maximum_font_size(COMPACT_AXIS_LABEL_SIZE);

    if has_bars {
        tick_options = tick_options.positions(&bar_positions);
    }

    let axis_ticks: Vec<(String, &'static str, String, String)> =
        category_ticks(&category_labels, tick_options)
            .into_iter()
            .map(|tick| {
                (
                    tick.index.to_string(),
                    CategoryTick::ANCHOR,
                    js_number(tick.position),
                    tick.label,
                )
            })
            .collect();
    let summary = props
        .summary
        .clone()
        .or_else(|| Some(labels.summary(summarize(&plain, 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-combo-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 left = js_number(plot_left);
    let right = js_number(plot_right);
    let label_x = js_number(plot_left - 8.0);
    let view_box = format!("0 0 {} {}", js_number(width), js_number(height));
    let viewbox_width = js_number(width);

    let axis_y = js_number(height - 12.0);
    let body = rsx! {
        if props.show_legend && has_data {
            {chart_legend(&labels.chart_legend, &plain)}
        }
        if !has_data {
            p { class: "ui-chart__empty", role: "status", "{labels.empty}" }
        }
        div {
            aria_label: "{plot_name}",
            class: "ui-chart__plot",
            role: "region",
            tabindex: "0",
            hidden: !has_data,
            svg { "aria-hidden": "true", "style": "--ui-chart-viewbox-width: {viewbox_width}", "viewBox": "{view_box}",
                g { class: "ui-chart__grid",
                    for (key, y, text) in grid {
                        g { key: "{key}",
                            line { x1: "{left}", x2: "{right}", y1: "{y}", y2: "{y}" }
                            text { x: "{label_x}", y: "{y}", "{text}" }
                        }
                    }
                }
                g { class: "ui-chart__axis-labels",
                    for (key, anchor, x, label) in axis_ticks {
                        text { key: "{key}", x: "{x}", y: "{axis_y}", "text-anchor": anchor, "{label}" }
                    }
                }
                g { class: "ui-bar-chart__marks",
                    for bar in bar_views.iter() {
                        rect {
                            key: "{bar.key}",
                            "data-ui-chart-datum": serialized(bar.action.as_ref()),
                            class: bar.class,
                            height: "{bar.height}",
                            rx: "4",
                            width: "{bar.width}",
                            x: "{bar.x}",
                            y: "{bar.y}",
                            onclick: activate_on_click(bar.action.as_ref(), on_activate),
                            title { "{bar.title}" }
                        }
                    }
                    if on_activate.is_some() {
                        for bar in bar_views.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": serialized(bar.action.as_ref()),
                                onclick: activate_on_click(bar.action.as_ref(), on_activate),
                            }
                        }
                    }
                }
                for line in line_views.iter() {
                    g { key: "{line.key}", class: "{line.class}",
                        for area in line.areas.iter() {
                            path { key: "{area}", class: "ui-line-chart__area", d: "{area}" }
                        }
                        path {
                            class: "ui-line-chart__line",
                            "data-ui-chart-dash": line.dash.map(ChartSeriesDash::as_str),
                            d: "{line.path}",
                        }
                        for point in line.points.iter() {
                            circle {
                                key: "{point.key}",
                                class: "ui-line-chart__point",
                                cx: "{point.cx}",
                                cy: "{point.cy}",
                                r: "3.5",
                            }
                        }
                        if on_activate.is_some() {
                            for point in line.points.iter() {
                                circle {
                                    key: "hit-{point.key}",
                                    class: "ui-chart__datum-hit",
                                    cx: "{point.cx}",
                                    cy: "{point.cy}",
                                    r: "10",
                                    "data-ui-chart-datum": serialized(point.action.as_ref()),
                                    onclick: activate_on_click(point.action.as_ref(), on_activate),
                                }
                            }
                        }
                    }
                }
            }
        }
        if props.show_table && has_data {
            {chart_data_table(&categories, None, format_value, &labels, &plain)}
        }
        if on_activate.is_some() {
            {datum_actions(&actions, &labels.explore_data, on_activate)}
        }
    };

    render_frame(frame, body)
}