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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! [`BoxPlot`]: five-number summaries with outliers on one shared horizontal scale.

use std::collections::HashSet;

use dioxus::prelude::*;

use super::super::format::css_percent;
use super::super::frame::{ChartPresentation, render_frame};
use super::super::model::{ChartDomain, ChartLabels, ChartTone, format_with};
use super::super::scale::{chart_ticks, nice_domain, scale_value};
use super::{empty_status, is_blank, summary_table, tick_style};
use crate::class::{Glass, compose};

/// One distribution in a [`BoxPlot`]: either all five statistics or none of them.
#[derive(Clone, Debug, PartialEq)]
pub struct BoxPlotDatum {
    /// A unique, non-blank id.
    pub id: String,
    /// The non-blank row name.
    pub label: String,
    /// The lower whisker.
    pub min: Option<f64>,
    /// The first quartile.
    pub q1: Option<f64>,
    /// The median.
    pub median: Option<f64>,
    /// The third quartile.
    pub q3: Option<f64>,
    /// The upper whisker.
    pub max: Option<f64>,
    /// Values outside the whiskers. Must be empty when the statistics are missing.
    pub outliers: Vec<f64>,
    /// The row color; defaults to the series tone for the row position.
    pub tone: Option<ChartTone>,
}

impl BoxPlotDatum {
    /// A row with ordered statistics: `min <= q1 <= median <= q3 <= max`.
    pub fn new(
        id: impl Into<String>,
        label: impl Into<String>,
        [min, q1, median, q3, max]: [f64; 5],
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            min: Some(min),
            q1: Some(q1),
            median: Some(median),
            q3: Some(q3),
            max: Some(max),
            outliers: Vec::new(),
            tone: None,
        }
    }

    /// A row without statistics.
    pub fn missing(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            min: None,
            q1: None,
            median: None,
            q3: None,
            max: None,
            outliers: Vec::new(),
            tone: None,
        }
    }

    /// Sets the outliers.
    #[must_use]
    pub fn with_outliers(mut self, outliers: impl IntoIterator<Item = f64>) -> Self {
        self.outliers = outliers.into_iter().collect();
        self
    }

    /// Sets the row color.
    #[must_use]
    pub fn with_tone(mut self, tone: ChartTone) -> Self {
        self.tone = Some(tone);
        self
    }

    fn statistics(&self) -> [Option<f64>; 5] {
        [self.min, self.q1, self.median, self.q3, self.max]
    }
}

/// Names of the five statistics and the outliers, shown in labels and the table.
#[derive(Clone, Debug, PartialEq)]
pub struct BoxPlotStatisticLabels {
    /// The lower whisker.
    pub min: String,
    /// The first quartile.
    pub q1: String,
    /// The median.
    pub median: String,
    /// The third quartile.
    pub q3: String,
    /// The upper whisker.
    pub max: String,
    /// The outliers.
    pub outliers: String,
}

impl Default for BoxPlotStatisticLabels {
    fn default() -> Self {
        Self {
            min: "Lower whisker".into(),
            q1: "First quartile".into(),
            median: "Median".into(),
            q3: "Third quartile".into(),
            max: "Upper whisker".into(),
            outliers: "Outliers".into(),
        }
    }
}

impl BoxPlotStatisticLabels {
    fn statistics(&self) -> [&str; 5] {
        [&self.min, &self.q1, &self.median, &self.q3, &self.max]
    }
}

/// Props for [`BoxPlot`].
#[derive(Props, Clone, PartialEq)]
pub struct BoxPlotProps {
    /// The rows. Any invalid row (blank id or label, unordered or partial statistics,
    /// non-finite numbers, duplicate id) marks the whole chart invalid.
    #[props(default)]
    pub data: Vec<BoxPlotDatum>,
    /// The scale; defaults to the extent of every statistic and outlier. It must enclose them.
    pub domain: Option<ChartDomain>,
    /// Names of the statistics.
    pub statistic_labels: Option<BoxPlotStatisticLabels>,
    /// Formats values. Defaults to JavaScript's `String(value)`.
    pub format_value: Option<Callback<f64, String>>,
    /// Visible and assistive text.
    pub labels: Option<ChartLabels>,
    /// Shows the collapsible data table; otherwise a screen reader list carries the values.
    #[props(default = true)]
    pub show_table: bool,
    /// 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 every row's statistics.
    #[props(into)]
    pub summary: Option<String>,
    /// A visible caption.
    #[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>,
}

/// A row with its positions on the `0..1` scale.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BoxRow {
    pub(crate) datum: BoxPlotDatum,
    pub(crate) positions: [Option<f64>; 5],
    pub(crate) outlier_positions: Vec<f64>,
}

/// `createLumenBoxPlotGeometry`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BoxModel {
    pub(crate) valid: bool,
    pub(crate) domain: ChartDomain,
    pub(crate) ticks: Vec<f64>,
    pub(crate) rows: Vec<BoxRow>,
}

fn valid_row(datum: &BoxPlotDatum) -> bool {
    if is_blank(&datum.id) || is_blank(&datum.label) {
        return false;
    }

    let statistics = datum.statistics();
    let missing = statistics.iter().all(Option::is_none);
    let ordered = statistics.iter().enumerate().all(|(index, value)| {
        value.is_some_and(f64::is_finite)
            && (index == 0 || matches!((statistics[index - 1], value), (Some(previous), Some(current)) if *current >= previous))
    });

    (missing || ordered)
        && datum.outliers.iter().all(|value| value.is_finite())
        && (!missing || datum.outliers.is_empty())
}

/// The extent of the values, padded by 1% (at least 1) when they are all equal.
fn automatic_domain(values: &[f64]) -> ChartDomain {
    let Some(first) = values.first() else {
        return ChartDomain::new(0.0, 1.0);
    };
    let (mut min, mut max) = (*first, *first);

    for value in values {
        min = min.min(*value);
        max = max.max(*value);
    }

    // Both bounds are finite, so a zero span means they are equal (0 and -0 included).
    if max - min == 0.0 {
        let padding = (min.abs() * 0.01).max(1.0);
        let lower = min - padding;
        let upper = max + padding;
        min = if lower.is_finite() { lower } else { min };
        max = if upper.is_finite() { upper } else { max };
    }

    ChartDomain::new(min, max)
}

fn encloses(domain: ChartDomain, values: &[f64]) -> bool {
    domain.min.is_finite()
        && domain.max.is_finite()
        && domain.min < domain.max
        && values
            .iter()
            .all(|value| domain.min <= *value && *value <= domain.max)
}

pub(crate) fn box_geometry(data: &[BoxPlotDatum], domain: Option<ChartDomain>) -> BoxModel {
    let mut ids = HashSet::new();
    let valid_data = data
        .iter()
        .all(|datum| valid_row(datum) && ids.insert(datum.id.as_str()));
    let values: Vec<f64> = if valid_data {
        data.iter()
            .flat_map(|datum| {
                datum
                    .statistics()
                    .into_iter()
                    .flatten()
                    .chain(datum.outliers.iter().copied())
            })
            .collect()
    } else {
        Vec::new()
    };
    let requested = domain.unwrap_or_else(|| nice_domain(automatic_domain(&values)));
    let valid = valid_data && encloses(requested, &values);
    let domain = if valid {
        requested
    } else {
        ChartDomain::new(0.0, 1.0)
    };
    let position = |value: f64| scale_value(value, domain, 0.0, 1.0);
    let rows = if valid {
        data.iter()
            .map(|datum| BoxRow {
                positions: datum.statistics().map(|value| value.map(position)),
                outlier_positions: datum
                    .outliers
                    .iter()
                    .map(|value| position(*value))
                    .collect(),
                datum: datum.clone(),
            })
            .collect()
    } else {
        Vec::new()
    };

    BoxModel {
        valid,
        domain,
        ticks: chart_ticks(domain),
        rows,
    }
}

/// Distinct positions in first-seen order, like `Array.from(new Set(positions))`.
fn unique_positions(positions: &[f64]) -> Vec<f64> {
    let mut unique: Vec<f64> = Vec::new();

    for position in positions {
        // `Set` treats 0 and -0 as one value and stores +0.
        let position = if *position == 0.0 { 0.0 } else { *position };

        if !unique
            .iter()
            .any(|seen| seen.to_bits() == position.to_bits())
        {
            unique.push(position);
        }
    }

    unique
}

/// One rendered row: the label, median text, and track marks as CSS.
#[derive(Clone, PartialEq)]
struct BoxView {
    id: String,
    label: String,
    tone: &'static str,
    median: String,
    whisker: Option<String>,
    box_style: Option<String>,
    median_left: Option<String>,
    caps: Vec<(&'static str, String)>,
    outliers: Vec<String>,
    cells: Vec<(&'static str, String)>,
    outlier_text: String,
    exact: String,
}

/// Distributions side by side: whiskers, quartile box, median, and outliers for each row on a
/// shared scale, with exact values in the table or a screen reader list.
#[component]
pub fn BoxPlot(props: BoxPlotProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let names = props.statistic_labels.clone().unwrap_or_default();
    let format_value = props.format_value;
    let model = box_geometry(&props.data, props.domain);
    let format = |value: Option<f64>| match value {
        Some(value) => format_with(format_value.as_ref(), value),
        None => labels.not_available.clone(),
    };
    let keys = ["min", "q1", "median", "q3", "max"];
    let views: Vec<BoxView> = model
        .rows
        .iter()
        .enumerate()
        .map(|(index, row)| {
            let statistics = row.datum.statistics();
            let [min, q1, median, q3, max] = row.positions;
            let outlier_text = row
                .datum
                .outliers
                .iter()
                .map(|value| format_with(format_value.as_ref(), *value))
                .collect::<Vec<_>>()
                .join(", ");
            let outlier_text = if outlier_text.is_empty() {
                "—".to_string()
            } else {
                outlier_text
            };
            let parts = names
                .statistics()
                .iter()
                .zip(statistics)
                .map(|(name, value)| format!("{name}: {}", format(value)))
                .collect::<Vec<_>>()
                .join(", ");

            BoxView {
                id: row.datum.id.clone(),
                label: row.datum.label.clone(),
                tone: ChartTone::resolve(row.datum.tone, index).class_name(),
                median: format(row.datum.median),
                whisker: min.zip(max).map(|(min, max)| {
                    format!("left:{};width:{}", css_percent(min), css_percent(max - min))
                }),
                box_style: q1.zip(q3).map(|(q1, q3)| {
                    format!("left:{};width:{}", css_percent(q1), css_percent(q3 - q1))
                }),
                median_left: median.map(css_percent),
                caps: [("min", min), ("max", max)]
                    .into_iter()
                    .filter_map(|(key, position)| {
                        position.map(|position| (key, css_percent(position)))
                    })
                    .collect(),
                outliers: unique_positions(&row.outlier_positions)
                    .into_iter()
                    .map(css_percent)
                    .collect(),
                cells: keys.iter().copied().zip(statistics.map(format)).collect(),
                exact: format!(
                    "{}: {parts}. {}: {outlier_text}",
                    row.datum.label, names.outliers
                ),
                outlier_text,
            }
        })
        .collect();
    let summary = props.summary.clone().or_else(|| {
        Some(if model.valid {
            views
                .iter()
                .map(|view| view.exact.clone())
                .collect::<Vec<_>>()
                .join(". ")
        } else {
            labels.invalid_data.clone()
        })
    });
    let class = compose([Some("ui-box-plot"), props.class.as_deref()]);
    let frame = super::super::frame::chart_frame!(props, class, summary);

    if !model.valid || model.rows.is_empty() {
        let message = if model.valid {
            &labels.empty
        } else {
            &labels.invalid_data
        };

        return render_frame(frame, empty_status(message));
    }

    let ticks: Vec<(String, String)> = model
        .ticks
        .iter()
        .map(|tick| {
            (
                tick_style(scale_value(*tick, model.domain, 0.0, 1.0)),
                format_with(format_value.as_ref(), *tick),
            )
        })
        .collect();
    let mut headings = vec![("category", labels.category.clone())];
    headings.extend(
        keys.iter()
            .copied()
            .zip(names.statistics().map(str::to_string)),
    );
    headings.push(("outliers", names.outliers.clone()));
    let details = if props.show_table {
        summary_table(
            &labels,
            &headings,
            rsx! {
                for view in views.iter() {
                    tr { key: "{view.id}",
                        th { scope: "row", "{view.label}" }
                        for (key, text) in view.cells.iter() {
                            td { key: "{key}", "{text}" }
                        }
                        td { "{view.outlier_text}" }
                    }
                }
            },
        )
    } else {
        rsx! {
            ul { class: "ui-sr-only",
                for view in views.iter() {
                    li { key: "{view.id}", "{view.exact}" }
                }
            }
        }
    };
    let body = rsx! {
        ul { class: "ui-box-plot__rows",
            for view in views.iter() {
                li { key: "{view.id}", class: view.tone,
                    div { class: "ui-box-plot__label",
                        span { "{view.label}" }
                        strong { "{names.median}: {view.median}" }
                    }
                    div { class: "ui-box-plot__track", aria_hidden: "true",
                        if let Some(style) = &view.whisker {
                            span { class: "ui-box-plot__whisker", style: "{style}" }
                        }
                        if let Some(style) = &view.box_style {
                            span { class: "ui-box-plot__box", style: "{style}" }
                        }
                        if let Some(left) = &view.median_left {
                            span { class: "ui-box-plot__median", style: "left:{left}" }
                        }
                        for (key, left) in view.caps.iter() {
                            span { key: "{key}", class: "ui-box-plot__cap", style: "left:{left}" }
                        }
                        for left in view.outliers.iter() {
                            span { key: "{left}", class: "ui-box-plot__outlier", style: "left:{left}" }
                        }
                    }
                }
            }
        }
        div { class: "ui-bullet-chart__ticks", aria_hidden: "true",
            for (key, text) in ticks {
                span { key: "{key}", style: "{key}", "{text}" }
            }
        }
        {details}
    };

    render_frame(frame, body)
}

#[cfg(test)]
mod tests {
    use super::{BoxPlotDatum, box_geometry, unique_positions};
    use crate::charts::model::ChartDomain;

    fn api() -> BoxPlotDatum {
        BoxPlotDatum::new("api", "API", [40.0, 120.0, 180.0, 260.0, 410.0])
            .with_outliers([520.0, 610.0])
    }

    #[test]
    fn rows_share_one_domain() {
        let model = box_geometry(&[api(), BoxPlotDatum::missing("jobs", "Jobs")], None);
        assert!(model.valid);
        assert_eq!(model.domain, ChartDomain::new(0.0, 750.0));
        assert_eq!(model.ticks, vec![0.0, 250.0, 500.0, 750.0]);
        assert_eq!(model.rows[0].positions[0], Some(40.0 / 750.0));
        assert_eq!(model.rows[0].outlier_positions[1], 610.0 / 750.0);
        assert_eq!(model.rows[1].positions, [None; 5]);
    }

    #[test]
    fn negative_and_flat_rows_are_supported() {
        let flat = box_geometry(&[BoxPlotDatum::new("a", "A", [-5.0; 5])], None);
        assert!(flat.valid);
        assert_eq!(flat.domain, ChartDomain::new(-6.0, -4.0));
        let empty = box_geometry(&[], None);
        assert!(empty.valid && empty.rows.is_empty());
        assert_eq!(empty.domain, ChartDomain::new(0.0, 1.0));
    }

    #[test]
    fn exact_bounds_keep_whiskers_and_outliers_on_the_same_scale() {
        let domain = ChartDomain::new(39.0, 611.0);
        let model = box_geometry(&[api()], Some(domain));
        assert!(model.valid);
        assert_eq!(model.domain, domain);
        assert_eq!(model.rows[0].positions[0], Some(1.0 / 572.0));
        assert_eq!(model.rows[0].outlier_positions[1], 571.0 / 572.0);
        assert_eq!(model.ticks, vec![100.0, 200.0, 300.0, 400.0, 500.0, 600.0]);
    }

    #[test]
    fn invalid_rows_fail_closed() {
        let mut partial = api();
        partial.q1 = None;
        let unordered = BoxPlotDatum::new("a", "A", [1.0, 2.0, 5.0, 4.0, 3.0]);
        let infinite = BoxPlotDatum::new("a", "A", [1.0, 2.0, 3.0, 4.0, f64::INFINITY]);
        let missing_with_outliers = BoxPlotDatum::missing("a", "A").with_outliers([1.0]);
        let nan_outlier = api().with_outliers([f64::NAN]);
        for data in [
            vec![partial],
            vec![unordered],
            vec![infinite],
            vec![missing_with_outliers],
            vec![nan_outlier],
            vec![api(), api()],
        ] {
            let model = box_geometry(&data, None);
            assert!(!model.valid && model.rows.is_empty());
            assert_eq!(model.domain, ChartDomain::new(0.0, 1.0));
        }
        assert!(!box_geometry(&[api()], Some(ChartDomain::new(0.0, 500.0))).valid);
        assert!(!box_geometry(&[api()], Some(ChartDomain::new(f64::NAN, 900.0))).valid);
    }

    #[test]
    fn duplicate_outlier_positions_render_once() {
        assert_eq!(
            unique_positions(&[0.5, 0.5, -0.0, 0.0, 1.0]),
            vec![0.5, 0.0, 1.0]
        );
    }
}