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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Chart data types shared by every chart: x identities, data points, series, tones, domains,
//! and the localizable labels.

use dioxus::prelude::*;

use super::format::{js_number, json_number, json_string};

/// An x value: a category name or a number (a linear value or a millisecond timestamp).
///
/// Equality follows JavaScript's `===`: `Number(0.0)` equals `Number(-0.0)`, `NaN` never equals
/// itself, and a number never equals text.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ChartX {
    /// A numeric x value.
    Number(f64),
    /// A category name or an ISO 8601 date.
    Text(String),
}

impl ChartX {
    /// `String(x)` in JavaScript: the default display label.
    pub fn display(&self) -> String {
        match self {
            Self::Number(value) => js_number(*value),
            Self::Text(text) => text.clone(),
        }
    }

    /// The identity key lumen-core uses to group categories: `number:1` or `string:Jan`.
    pub(crate) fn key(&self) -> String {
        match self {
            Self::Number(value) => format!("number:{}", js_number(*value)),
            Self::Text(text) => format!("string:{text}"),
        }
    }

    /// `JSON.stringify(x)` in JavaScript.
    pub(crate) fn json(&self) -> String {
        match self {
            Self::Number(value) => json_number(*value),
            Self::Text(text) => json_string(text),
        }
    }

    /// `[typeof x, x]` serialized as JSON, as used in motion keys.
    pub(crate) fn typed_json(&self) -> String {
        match self {
            Self::Number(value) => format!("[\"number\",{}]", json_number(*value)),
            Self::Text(text) => format!("[\"string\",{}]", json_string(text)),
        }
    }

    /// Whether the value is text or a finite number (the axis values lumen-core accepts).
    pub(crate) fn is_axis_value(&self) -> bool {
        match self {
            Self::Number(value) => value.is_finite(),
            Self::Text(_) => true,
        }
    }
}

impl From<f64> for ChartX {
    fn from(value: f64) -> Self {
        Self::Number(value)
    }
}

impl From<f32> for ChartX {
    fn from(value: f32) -> Self {
        Self::Number(f64::from(value))
    }
}

impl From<i32> for ChartX {
    fn from(value: i32) -> Self {
        Self::Number(f64::from(value))
    }
}

impl From<u32> for ChartX {
    fn from(value: u32) -> Self {
        Self::Number(f64::from(value))
    }
}

impl From<&str> for ChartX {
    fn from(value: &str) -> Self {
        Self::Text(value.to_string())
    }
}

impl From<String> for ChartX {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&String> for ChartX {
    fn from(value: &String) -> Self {
        Self::Text(value.clone())
    }
}

/// The chart color tokens. Series tones cycle through `series-1` to `series-8`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChartTone {
    /// `series-1`.
    #[default]
    Series1,
    /// `series-2`.
    Series2,
    /// `series-3`.
    Series3,
    /// `series-4`.
    Series4,
    /// `series-5`.
    Series5,
    /// `series-6`.
    Series6,
    /// `series-7`.
    Series7,
    /// `series-8`.
    Series8,
    /// The brand color.
    Brand,
    /// The accent color.
    Accent,
    /// Positive status.
    Success,
    /// Cautionary status.
    Warning,
    /// Negative status.
    Danger,
    /// Neutral gray.
    Neutral,
}

const SERIES_TONES: [ChartTone; 8] = [
    ChartTone::Series1,
    ChartTone::Series2,
    ChartTone::Series3,
    ChartTone::Series4,
    ChartTone::Series5,
    ChartTone::Series6,
    ChartTone::Series7,
    ChartTone::Series8,
];

impl ChartTone {
    /// The token name, such as `series-1` or `danger`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Series1 => "series-1",
            Self::Series2 => "series-2",
            Self::Series3 => "series-3",
            Self::Series4 => "series-4",
            Self::Series5 => "series-5",
            Self::Series6 => "series-6",
            Self::Series7 => "series-7",
            Self::Series8 => "series-8",
            Self::Brand => "brand",
            Self::Accent => "accent",
            Self::Success => "success",
            Self::Warning => "warning",
            Self::Danger => "danger",
            Self::Neutral => "neutral",
        }
    }

    /// The `ui-chart-tone--*` class that sets `--ui-chart-color`.
    pub fn class_name(self) -> &'static str {
        match self {
            Self::Series1 => "ui-chart-tone--series-1",
            Self::Series2 => "ui-chart-tone--series-2",
            Self::Series3 => "ui-chart-tone--series-3",
            Self::Series4 => "ui-chart-tone--series-4",
            Self::Series5 => "ui-chart-tone--series-5",
            Self::Series6 => "ui-chart-tone--series-6",
            Self::Series7 => "ui-chart-tone--series-7",
            Self::Series8 => "ui-chart-tone--series-8",
            Self::Brand => "ui-chart-tone--brand",
            Self::Accent => "ui-chart-tone--accent",
            Self::Success => "ui-chart-tone--success",
            Self::Warning => "ui-chart-tone--warning",
            Self::Danger => "ui-chart-tone--danger",
            Self::Neutral => "ui-chart-tone--neutral",
        }
    }

    /// The explicit tone, or the series tone for `index` (cycling through eight series colors).
    pub fn resolve(tone: Option<Self>, index: usize) -> Self {
        tone.unwrap_or(SERIES_TONES[index % SERIES_TONES.len()])
    }
}

/// One data point of a [`ChartSeries`].
#[derive(Clone, Debug, PartialEq)]
pub struct ChartDatum {
    /// The x identity: a category, a number, or an ISO 8601 date.
    pub x: ChartX,
    /// The value. `None` (or a non-finite number) is a missing measurement that breaks lines.
    pub y: Option<f64>,
    /// A stable id, used for motion keys and activation details.
    pub id: Option<String>,
    /// A formatted value label that replaces the formatted `y` in tooltips and tables.
    pub label: Option<String>,
    /// A display label for `x` on axes and in tables.
    pub x_label: Option<String>,
    /// The bubble size in a [`ScatterChart`](crate::ScatterChart).
    pub size: Option<f64>,
    /// A tone for this point (pie slices and scatter points).
    pub tone: Option<ChartTone>,
    /// A label describing the tone, for consumers that present it.
    pub tone_label: Option<String>,
}

impl ChartDatum {
    /// A point at `x` with value `y`.
    pub fn new(x: impl Into<ChartX>, y: impl Into<Option<f64>>) -> Self {
        Self {
            x: x.into(),
            y: y.into(),
            id: None,
            label: None,
            x_label: None,
            size: None,
            tone: None,
            tone_label: None,
        }
    }

    /// A point at `x` without a measurement.
    pub fn missing(x: impl Into<ChartX>) -> Self {
        Self::new(x, None)
    }

    /// Sets the stable id.
    #[must_use]
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Sets the formatted value label.
    #[must_use]
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets the x display label.
    #[must_use]
    pub fn with_x_label(mut self, label: impl Into<String>) -> Self {
        self.x_label = Some(label.into());
        self
    }

    /// Sets the bubble size.
    #[must_use]
    pub fn with_size(mut self, size: f64) -> Self {
        self.size = Some(size);
        self
    }

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

    /// The value when it is a finite number.
    pub(crate) fn value(&self) -> Option<f64> {
        self.y.filter(|value| value.is_finite())
    }
}

/// An explicit line pattern for a [`ChartSeries`] in `LineChart` or `ComboChart`.
/// Leave [`ChartSeries::dash`] unset to use the stylesheet's automatic series patterns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChartSeriesDash {
    /// A continuous stroke.
    #[default]
    Solid,
    /// A dashed stroke.
    Dashed,
    /// A dotted stroke.
    Dotted,
}

impl ChartSeriesDash {
    /// The shared `data-ui-chart-dash` attribute value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Solid => "solid",
            Self::Dashed => "dashed",
            Self::Dotted => "dotted",
        }
    }
}

/// A named sequence of [`ChartDatum`] values.
#[derive(Clone, Debug, PartialEq)]
pub struct ChartSeries {
    /// A unique id.
    pub id: String,
    /// The display name used in legends, tooltips, and tables.
    pub label: String,
    /// The points, in x order.
    pub data: Vec<ChartDatum>,
    /// The series color; defaults to the series tone for its position.
    pub tone: Option<ChartTone>,
    /// An explicit line pattern; `None` keeps automatic series patterns.
    pub dash: Option<ChartSeriesDash>,
}

impl ChartSeries {
    /// A series with an id, a display name, and its points.
    pub fn new(
        id: impl Into<String>,
        label: impl Into<String>,
        data: impl IntoIterator<Item = ChartDatum>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            data: data.into_iter().collect(),
            tone: None,
            dash: None,
        }
    }

    /// Sets the explicit line pattern for line and combo charts.
    #[must_use]
    pub fn with_dash(mut self, dash: ChartSeriesDash) -> Self {
        self.dash = Some(dash);
        self
    }

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

/// A numeric domain from `min` to `max`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChartDomain {
    /// The lower bound.
    pub min: f64,
    /// The upper bound.
    pub max: f64,
}

impl ChartDomain {
    /// A domain from `min` to `max`.
    pub fn new(min: f64, max: f64) -> Self {
        Self { min, max }
    }
}

/// Optional domain bounds; a missing bound is calculated from the data.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ChartBounds {
    /// The requested lower bound.
    pub min: Option<f64>,
    /// The requested upper bound.
    pub max: Option<f64>,
}

impl ChartBounds {
    /// Both bounds.
    pub fn new(min: f64, max: f64) -> Self {
        Self {
            min: Some(min),
            max: Some(max),
        }
    }

    /// Only the lower bound.
    pub fn min(min: f64) -> Self {
        Self {
            min: Some(min),
            max: None,
        }
    }

    /// Only the upper bound.
    pub fn max(max: f64) -> Self {
        Self {
            min: None,
            max: Some(max),
        }
    }
}

impl From<ChartDomain> for ChartBounds {
    fn from(domain: ChartDomain) -> Self {
        Self::new(domain.min, domain.max)
    }
}

/// Facts about a chart's data, passed to [`ChartLabels::format_summary`].
#[derive(Clone, Debug, PartialEq)]
pub struct ChartSummary {
    /// Points with a finite value.
    pub available_point_count: usize,
    /// The largest finite value.
    pub maximum: Option<f64>,
    /// The smallest finite value.
    pub minimum: Option<f64>,
    /// Points without a finite value.
    pub missing_point_count: usize,
    /// The number of series.
    pub series_count: usize,
    /// `maximum` formatted with the chart's value formatter (`0` when missing).
    pub maximum_label: String,
    /// `minimum` formatted with the chart's value formatter (`0` when missing).
    pub minimum_label: String,
}

/// The visible and assistive text of every chart. Override fields with struct update syntax:
/// `ChartLabels { empty: "Nothing yet".into(), ..ChartLabels::default() }`.
#[derive(Clone, PartialEq)]
#[allow(missing_docs)]
pub struct ChartLabels {
    pub count: String,
    pub density: String,
    pub end: String,
    pub invalid_data: String,
    pub start: String,
    pub category: String,
    pub chart_data: String,
    pub chart_legend: String,
    pub column: String,
    pub empty: String,
    pub explore_data: String,
    pub high: String,
    pub low: String,
    pub not_available: String,
    pub row: String,
    pub series: String,
    pub size: String,
    pub value: String,
    pub view_data: String,
    pub x: String,
    /// The accessible name of a datum action button; receives the point's description.
    pub format_datum_action: Option<Callback<String, String>>,
    /// The heatmap summary for a count of available cells.
    pub format_heatmap_summary: Option<Callback<usize, String>>,
    /// The range chart summary for a count of available ranges.
    pub format_range_summary: Option<Callback<usize, String>>,
    /// The screen reader summary of series charts.
    pub format_summary: Option<Callback<ChartSummary, String>>,
}

impl Default for ChartLabels {
    fn default() -> Self {
        Self {
            count: "Count".into(),
            density: "Frequency density".into(),
            end: "End".into(),
            invalid_data: "Chart data is invalid. Check the supplied values.".into(),
            start: "Start".into(),
            category: "Category".into(),
            chart_data: "Chart data".into(),
            chart_legend: "Chart legend".into(),
            column: "Column".into(),
            empty: "No chart data available.".into(),
            explore_data: "Explore chart data".into(),
            high: "High".into(),
            low: "Low".into(),
            not_available: "Not available".into(),
            row: "Row".into(),
            series: "Series".into(),
            size: "Size".into(),
            value: "Value".into(),
            view_data: "View chart data".into(),
            x: "X".into(),
            format_datum_action: None,
            format_heatmap_summary: None,
            format_range_summary: None,
            format_summary: None,
        }
    }
}

impl ChartLabels {
    /// The accessible name of a datum action.
    pub fn datum_action(&self, context: &str) -> String {
        match &self.format_datum_action {
            Some(format) => format.call(context.to_string()),
            None => format!("Open details: {context}"),
        }
    }

    /// The heatmap summary.
    pub fn heatmap_summary(&self, count: usize) -> String {
        match &self.format_heatmap_summary {
            Some(format) => format.call(count),
            None if count == 0 => "No chart data available.".to_string(),
            None => format!(
                "{count} available heatmap {}.",
                if count == 1 { "cell" } else { "cells" }
            ),
        }
    }

    /// The range chart summary.
    pub fn range_summary(&self, count: usize) -> String {
        match &self.format_range_summary {
            Some(format) => format.call(count),
            None if count == 0 => "No chart data available.".to_string(),
            None => format!(
                "{count} available {}.",
                if count == 1 { "range" } else { "ranges" }
            ),
        }
    }

    /// The series summary.
    pub fn summary(&self, summary: ChartSummary) -> String {
        if let Some(format) = &self.format_summary {
            return format.call(summary);
        }

        if summary.available_point_count == 0 {
            return "No chart data available.".to_string();
        }

        let points = if summary.available_point_count == 1 {
            "point"
        } else {
            "points"
        };
        let missing = if summary.missing_point_count == 0 {
            String::new()
        } else {
            format!(
                " {} missing {}.",
                summary.missing_point_count,
                if summary.missing_point_count == 1 {
                    "value"
                } else {
                    "values"
                }
            )
        };

        format!(
            "{} series, {} {points}. Values range from {} to {}.{missing}",
            summary.series_count,
            summary.available_point_count,
            summary.minimum_label,
            summary.maximum_label
        )
    }
}

/// A value formatter: `formatValue` in lumen-react. Defaults to JavaScript's `String(value)`.
pub(crate) fn format_with(formatter: Option<&Callback<f64, String>>, value: f64) -> String {
    match formatter {
        Some(format) => format.call(value),
        None => js_number(value),
    }
}

/// A category formatter: `formatCategory` in lumen-react.
pub(crate) fn format_category_with(
    formatter: Option<&Callback<ChartX, String>>,
    value: &ChartX,
) -> String {
    match formatter {
        Some(format) => format.call(value.clone()),
        None => value.display(),
    }
}

/// `summarizeLumenChart` plus the formatted extremes.
pub(crate) fn summarize(
    series: &[ChartSeries],
    format_value: Option<&Callback<f64, String>>,
) -> ChartSummary {
    let mut available = 0;
    let mut missing = 0;
    let mut maximum = f64::NEG_INFINITY;
    let mut minimum = f64::INFINITY;

    for item in series {
        for datum in &item.data {
            match datum.value() {
                Some(value) => {
                    available += 1;
                    maximum = maximum.max(value);
                    minimum = minimum.min(value);
                }
                None => missing += 1,
            }
        }
    }

    let maximum = maximum.is_finite().then_some(maximum);
    let minimum = minimum.is_finite().then_some(minimum);

    ChartSummary {
        available_point_count: available,
        maximum,
        minimum,
        missing_point_count: missing,
        series_count: series.len(),
        maximum_label: format_with(format_value, maximum.unwrap_or(0.0)),
        minimum_label: format_with(format_value, minimum.unwrap_or(0.0)),
    }
}

#[cfg(test)]
mod tests {
    use super::{ChartDatum, ChartLabels, ChartSeries, ChartTone, ChartX, summarize};

    #[test]
    fn x_identity_follows_javascript() {
        assert_eq!(ChartX::from(0.0), ChartX::from(-0.0));
        assert_ne!(ChartX::Number(f64::NAN), ChartX::Number(f64::NAN));
        assert_ne!(ChartX::from(1), ChartX::from("1"));
        assert_eq!(ChartX::from(1.5).key(), "number:1.5");
        assert_eq!(ChartX::from("Jan").key(), "string:Jan");
        assert_eq!(ChartX::from(f64::NAN).json(), "null");
        assert_eq!(ChartX::from("a\"b").typed_json(), "[\"string\",\"a\\\"b\"]");
        assert!(!ChartX::from(f64::INFINITY).is_axis_value());
    }

    #[test]
    fn tones_cycle_through_eight_series_colors() {
        assert_eq!(ChartTone::resolve(None, 0), ChartTone::Series1);
        assert_eq!(ChartTone::resolve(None, 9), ChartTone::Series2);
        assert_eq!(
            ChartTone::resolve(Some(ChartTone::Danger), 3),
            ChartTone::Danger
        );
        assert_eq!(ChartTone::Series4.class_name(), "ui-chart-tone--series-4");
    }

    #[test]
    fn summaries_count_available_and_missing_points() {
        let series = vec![ChartSeries::new(
            "a",
            "A",
            [
                ChartDatum::new("x", 3.0),
                ChartDatum::missing("y"),
                ChartDatum::new("z", f64::NAN),
                ChartDatum::new("w", -2.0),
            ],
        )];
        let summary = summarize(&series, None);

        assert_eq!(summary.available_point_count, 2);
        assert_eq!(summary.missing_point_count, 2);
        assert_eq!(
            ChartLabels::default().summary(summary),
            "1 series, 2 points. Values range from -2 to 3. 2 missing values."
        );
        assert_eq!(
            ChartLabels::default().summary(summarize(&[], None)),
            "No chart data available."
        );
    }
}