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
//! `Stat` and its parts, `StatGroup`, and `Meter`.

use dioxus::prelude::*;

use crate::class::compose;

/// Element a [`Stat`] or one of its text parts renders.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatAs {
    /// `<div>`.
    #[default]
    Div,
    /// `<article>`, for a self-contained metric.
    Article,
    /// `<section>`.
    Section,
}

/// Surface treatment of a [`Stat`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatVariant {
    /// Bordered surface.
    #[default]
    Default,
    /// Brand-tinted surface.
    Accent,
    /// No surface; keeps the layout.
    Bare,
    /// Glass surface.
    Glass,
}

impl StatVariant {
    /// The `data-variant` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Accent => "accent",
            Self::Bare => "bare",
            Self::Glass => "glass",
        }
    }
}

/// Semantic tone that colors the [`StatValue`] and [`StatIcon`] of a [`Stat`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatTone {
    /// No tone.
    #[default]
    Default,
    /// Positive.
    Success,
    /// Needs attention.
    Warning,
    /// Negative.
    Danger,
    /// Brand color.
    Brand,
}

impl StatTone {
    /// The `data-tone` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Success => "success",
            Self::Warning => "warning",
            Self::Danger => "danger",
            Self::Brand => "brand",
        }
    }
}

/// Props for [`Stat`].
#[derive(Props, Clone, PartialEq)]
pub struct StatProps {
    /// Root element. Defaults to `<div>`.
    #[props(default)]
    pub r#as: StatAs,
    /// Shorthand label, rendered as a [`StatLabel`] before the children.
    #[props(into)]
    pub label: Option<String>,
    /// Shorthand value, rendered as a [`StatValue`] before the children.
    #[props(into)]
    pub value: Option<String>,
    /// Surface treatment.
    #[props(default)]
    pub variant: StatVariant,
    /// Semantic tone for the value and icon.
    #[props(default)]
    pub tone: StatTone,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Composed parts such as [`StatLabel`], [`StatValue`], and [`StatTrend`].
    pub children: Element,
}

/// A single metric: a label, a prominent value, and optional icon, trend, and description.
#[component]
pub fn Stat(props: StatProps) -> Element {
    let variant = (props.variant != StatVariant::Default)
        .then(|| format!("ui-stat--{}", props.variant.as_str()));
    let tone =
        (props.tone != StatTone::Default).then(|| format!("ui-stat--tone-{}", props.tone.as_str()));
    let class = compose([
        Some("ui-stat"),
        variant.as_deref(),
        tone.as_deref(),
        props.class.as_deref(),
    ]);
    let data_tone = (props.tone != StatTone::Default).then_some(props.tone.as_str());
    let data_variant = props.variant.as_str();
    let body = rsx! {
        if let Some(label) = props.label.filter(|label| !label.is_empty()) {
            div { class: "ui-stat-label", "data-slot": "stat-label", "{label}" }
        }
        if let Some(value) = props.value.filter(|value| !value.is_empty()) {
            div { class: "ui-stat-value", "data-slot": "stat-value", "{value}" }
        }
        {props.children}
    };

    match props.r#as {
        StatAs::Div => rsx! {
            div { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
        },
        StatAs::Article => rsx! {
            article { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
        },
        StatAs::Section => rsx! {
            section { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
        },
    }
}

/// Props shared by [`StatLabel`], [`StatValue`], and [`StatDescription`].
#[derive(Props, Clone, PartialEq)]
pub struct StatPartProps {
    /// Element to render. Defaults to `<div>`.
    #[props(default)]
    pub r#as: StatAs,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Content.
    pub children: Element,
}

fn stat_part(base: &str, slot: &'static str, props: StatPartProps) -> Element {
    let class = compose([Some(base), props.class.as_deref()]);

    match props.r#as {
        StatAs::Div => rsx! {
            div { class, "data-slot": slot, ..props.attributes, {props.children} }
        },
        StatAs::Article => rsx! {
            article { class, "data-slot": slot, ..props.attributes, {props.children} }
        },
        StatAs::Section => rsx! {
            section { class, "data-slot": slot, ..props.attributes, {props.children} }
        },
    }
}

/// The label of a composed [`Stat`].
#[component]
pub fn StatLabel(props: StatPartProps) -> Element {
    stat_part("ui-stat-label", "stat-label", props)
}

/// The prominent value of a composed [`Stat`].
#[component]
pub fn StatValue(props: StatPartProps) -> Element {
    stat_part("ui-stat-value", "stat-value", props)
}

/// Supporting context under a [`StatValue`].
#[component]
pub fn StatDescription(props: StatPartProps) -> Element {
    stat_part("ui-stat-description", "stat-description", props)
}

/// Props for [`StatIcon`].
#[derive(Props, Clone, PartialEq)]
pub struct StatIconProps {
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<span>` or global attribute.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
    /// The icon, usually an [`Icon`](crate::Icon).
    pub children: Element,
}

/// The icon region of a composed [`Stat`].
#[component]
pub fn StatIcon(props: StatIconProps) -> Element {
    let class = compose([Some("ui-stat-icon"), props.class.as_deref()]);

    rsx! {
        span { class, "data-slot": "stat-icon", ..props.attributes, {props.children} }
    }
}

/// Tone of a [`StatTrend`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatTrendTone {
    /// No judgement.
    #[default]
    Neutral,
    /// Positive change.
    Success,
    /// Change that needs attention.
    Warning,
    /// Negative change.
    Danger,
}

impl StatTrendTone {
    /// The class suffix and `data-tone` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Neutral => "neutral",
            Self::Success => "success",
            Self::Warning => "warning",
            Self::Danger => "danger",
        }
    }
}

/// Props for [`StatTrend`].
#[derive(Props, Clone, PartialEq)]
pub struct StatTrendProps {
    /// Semantic tone of the change.
    #[props(default)]
    pub tone: StatTrendTone,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<span>` or global attribute.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
    /// The delta text, such as `+8%`.
    pub children: Element,
}

/// A metric delta with a semantic tone.
#[component]
pub fn StatTrend(props: StatTrendProps) -> Element {
    let tone = format!("ui-stat-trend--{}", props.tone.as_str());
    let class = compose([
        Some("ui-stat-trend"),
        Some(tone.as_str()),
        props.class.as_deref(),
    ]);

    rsx! {
        span {
            class,
            "data-slot": "stat-trend",
            "data-tone": props.tone.as_str(),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`StatGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct StatGroupProps {
    /// Joins the stats into one framed strip with dividers between them.
    #[props(default)]
    pub dividers: bool,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the group with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The [`Stat`]s.
    pub children: Element,
}

/// A responsive row of [`Stat`]s that wraps on narrow widths.
#[component]
pub fn StatGroup(props: StatGroupProps) -> Element {
    let class = compose([
        Some("ui-stat-group"),
        props.dividers.then_some("ui-stat-group--dividers"),
        props.class.as_deref(),
    ]);

    rsx! {
        div {
            class,
            "data-dividers": props.dividers.then_some(""),
            "data-slot": "stat-group",
            role: "group",
            ..props.attributes,
            {props.children}
        }
    }
}

/// Most slots a segmented [`Meter`] draws; larger counts render a continuous bar.
pub const METER_MAX_SEGMENTS: u32 = 24;

/// Default value text of a segmented [`Meter`], counted from `min`.
pub const METER_DEFAULT_VALUE_LABEL: &str = "{value} of {max}";

/// A segment count from 2 to 24, or `None` for a continuous meter.
pub fn resolve_meter_segments(segments: Option<u32>) -> Option<u32> {
    segments.filter(|count| (2..=METER_MAX_SEGMENTS).contains(count))
}

/// The clamped range a [`Meter`] shows, like the native `<meter>` element.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeterRange {
    /// Lower bound; defaults to 0.
    pub min: f64,
    /// Upper bound; defaults to 100 and never falls below `min`.
    pub max: f64,
    /// The value clamped into the range.
    pub value: f64,
}

fn finite(value: Option<f64>) -> Option<f64> {
    value.filter(|number| number.is_finite())
}

/// Normalizes a meter range the way the native element does.
pub fn resolve_meter_range(min: Option<f64>, max: Option<f64>, value: f64) -> MeterRange {
    let min = finite(min).unwrap_or(0.0);
    let fallback_max = if min < 100.0 { 100.0 } else { min + 1.0 };
    let max = finite(max).unwrap_or(fallback_max).max(min);
    let value = finite(Some(value)).unwrap_or(min).clamp(min, max);

    MeterRange { min, max, value }
}

/// Replaces `{name}` placeholders with a linear scan; unknown placeholders stay as written.
pub(crate) fn fill_template(template: &str, values: &[(&str, &str)]) -> String {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;

    while let Some(open) = rest.find('{') {
        out.push_str(&rest[..open]);
        let after = &rest[open + 1..];

        match after.find(['}', '{']) {
            Some(close) if after.as_bytes()[close] == b'}' => {
                let name = &after[..close];

                if let Some((_, value)) = values.iter().find(|(key, _)| *key == name) {
                    out.push_str(value);
                } else {
                    out.push('{');
                    out.push_str(name);
                    out.push('}');
                }

                rest = &after[close + 1..];
            }
            _ => {
                out.push('{');
                rest = after;
            }
        }
    }

    out.push_str(rest);
    out
}

/// Formats a number like `Intl.NumberFormat("en")`: up to three fraction digits, rounded half
/// away from zero from the shortest decimal form, with comma grouping.
pub(crate) fn format_en_number(value: f64) -> String {
    if value.is_nan() {
        return "NaN".to_string();
    }

    if value.is_infinite() {
        return if value > 0.0 { "∞" } else { "-∞" }.to_string();
    }

    let negative = value.is_sign_negative();
    let digits = format!("{}", value.abs());
    let (integer, fraction) = digits.split_once('.').unwrap_or((digits.as_str(), ""));
    let mut whole: Vec<u8> = integer.bytes().map(|byte| byte - b'0').collect();
    let mut kept: Vec<u8> = fraction.bytes().take(3).map(|byte| byte - b'0').collect();

    if fraction
        .as_bytes()
        .get(3)
        .is_some_and(|digit| *digit >= b'5')
    {
        let mut carry = true;

        for digit in kept.iter_mut().rev().chain(whole.iter_mut().rev()) {
            if !carry {
                break;
            }

            if *digit == 9 {
                *digit = 0;
            } else {
                *digit += 1;
                carry = false;
            }
        }

        if carry {
            whole.insert(0, 1);
        }
    }

    while kept.last() == Some(&0) {
        kept.pop();
    }

    let mut out = String::new();

    if negative {
        out.push('-');
    }

    for (index, digit) in whole.iter().enumerate() {
        if index > 0 && (whole.len() - index).is_multiple_of(3) {
            out.push(',');
        }

        out.push(char::from(b'0' + digit));
    }

    if !kept.is_empty() {
        out.push('.');
        out.extend(kept.iter().map(|digit| char::from(b'0' + digit)));
    }

    out
}

/// Text for a meter's `aria-valuetext`, such as `3 of 5`, or `None` for a continuous meter
/// without a `value_label` (which keeps the native percentage reading).
pub fn resolve_meter_value_text(
    range: MeterRange,
    segmented: bool,
    value_label: Option<&str>,
) -> Option<String> {
    let label = value_label.filter(|label| !label.trim().is_empty());

    match label {
        None if !segmented => None,
        None => Some(fill_template(
            METER_DEFAULT_VALUE_LABEL,
            &[
                ("max", &format_en_number(range.max - range.min)),
                ("value", &format_en_number(range.value - range.min)),
            ],
        )),
        Some(label) => Some(fill_template(
            label,
            &[
                ("max", &format_en_number(range.max)),
                ("min", &format_en_number(range.min)),
                ("value", &format_en_number(range.value)),
            ],
        )),
    }
}

/// Props for [`Meter`].
#[derive(Props, Clone, PartialEq)]
pub struct MeterProps {
    /// Current value; clamped into `min..=max` for the value text.
    #[props(default)]
    pub value: f64,
    /// Lower bound. Defaults to 0.
    pub min: Option<f64>,
    /// Upper bound. Defaults to 100.
    pub max: Option<f64>,
    /// Draws one mark per slot, such as 5 for "3 of 5 seats". Whole counts from 2 to 24, normally
    /// `max - min`; other values render the continuous bar.
    pub segments: Option<u32>,
    /// Accessible value text with `{value}`, `{min}`, and `{max}` placeholders. Segmented meters
    /// default to `{value} of {max}`.
    #[props(into)]
    pub value_label: Option<String>,
    /// Explicit `aria-valuetext`; wins over the computed text.
    #[props(into)]
    pub aria_valuetext: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<meter>` or global attribute, such as `aria_label`, `low`, `high`, or `optimum`.
    #[props(extends = GlobalAttributes, extends = meter)]
    pub attributes: Vec<Attribute>,
    /// Fallback content; defaults to the value text.
    pub children: Element,
}

/// A native `<meter>` for a measurement in a known range, with optional quota segments.
///
/// Numbers in the value text use English formatting.
#[component]
pub fn Meter(props: MeterProps) -> Element {
    let segments = resolve_meter_segments(props.segments);
    let range = resolve_meter_range(props.min, props.max, props.value);
    let value_text =
        resolve_meter_value_text(range, segments.is_some(), props.value_label.as_deref());
    let class = compose([
        Some("ui-meter"),
        segments.is_some().then_some("ui-meter--segmented"),
        props.class.as_deref(),
    ]);
    let has_children = super::has_content(&props.children);
    let aria_valuetext = props.aria_valuetext.or_else(|| value_text.clone());

    rsx! {
        meter {
            aria_valuetext,
            class,
            "data-segments": segments.map(|count| count.to_string()),
            style: segments.map(|count| format!("--ui-meter-segments:{count}")),
            max: props.max.map(|max| max.to_string()),
            min: props.min.map(|min| min.to_string()),
            value: "{props.value}",
            ..props.attributes,
            if has_children {
                {props.children}
            } else if let Some(text) = value_text {
                "{text}"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        MeterRange, fill_template, format_en_number, resolve_meter_range, resolve_meter_segments,
        resolve_meter_value_text,
    };

    #[test]
    fn english_numbers_match_intl() {
        assert_eq!(format_en_number(1.0005), "1.001");
        assert_eq!(format_en_number(0.0625), "0.063");
        assert_eq!(format_en_number(-1.5), "-1.5");
        assert_eq!(format_en_number(1_234_567.891_5), "1,234,567.892");
        assert_eq!(format_en_number(1e21), "1,000,000,000,000,000,000,000");
        assert_eq!(format_en_number(0.1 + 0.2), "0.3");
        assert_eq!(format_en_number(-0.0004), "-0");
        assert_eq!(format_en_number(0.9996), "1");
        assert_eq!(format_en_number(999.9999), "1,000");
        assert_eq!(format_en_number(0.0), "0");
    }

    #[test]
    fn meter_segments_are_whole_counts_from_two_to_twenty_four() {
        assert_eq!(resolve_meter_segments(Some(5)), Some(5));
        assert_eq!(resolve_meter_segments(Some(1)), None);
        assert_eq!(resolve_meter_segments(Some(25)), None);
        assert_eq!(resolve_meter_segments(None), None);
    }

    #[test]
    fn meter_range_clamps_like_the_native_element() {
        assert_eq!(
            resolve_meter_range(None, None, 150.0),
            MeterRange {
                min: 0.0,
                max: 100.0,
                value: 100.0
            }
        );
        assert_eq!(
            resolve_meter_range(Some(200.0), Some(10.0), 5.0),
            MeterRange {
                min: 200.0,
                max: 200.0,
                value: 200.0
            }
        );
        assert_eq!(
            resolve_meter_range(Some(150.0), None, f64::NAN),
            MeterRange {
                min: 150.0,
                max: 151.0,
                value: 150.0
            }
        );
    }

    #[test]
    fn meter_value_text_counts_segments_from_min() {
        let range = resolve_meter_range(Some(10.0), Some(20.0), 15.0);

        assert_eq!(
            resolve_meter_value_text(range, true, None).as_deref(),
            Some("5 of 10")
        );
        assert_eq!(resolve_meter_value_text(range, false, None), None);
        assert_eq!(
            resolve_meter_value_text(range, false, Some("{value} of {max} ({min})")).as_deref(),
            Some("15 of 20 (10)")
        );
        assert_eq!(resolve_meter_value_text(range, false, Some("  ")), None);
    }

    #[test]
    fn templates_keep_unknown_and_unbalanced_placeholders() {
        assert_eq!(fill_template("{a} {b} {", &[("a", "1")]), "1 {b} {");
        assert_eq!(fill_template("{{a}", &[("a", "1")]), "{1");
        let long = "{".repeat(100_000);
        assert_eq!(fill_template(&long, &[]).len(), 100_000);
    }
}