Skip to main content

lumen_dioxus/data/
stat.rs

1//! `Stat` and its parts, `StatGroup`, and `Meter`.
2
3use dioxus::prelude::*;
4
5use crate::class::compose;
6
7/// Element a [`Stat`] or one of its text parts renders.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum StatAs {
11    /// `<div>`.
12    #[default]
13    Div,
14    /// `<article>`, for a self-contained metric.
15    Article,
16    /// `<section>`.
17    Section,
18}
19
20/// Surface treatment of a [`Stat`].
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum StatVariant {
24    /// Bordered surface.
25    #[default]
26    Default,
27    /// Brand-tinted surface.
28    Accent,
29    /// No surface; keeps the layout.
30    Bare,
31    /// Glass surface.
32    Glass,
33}
34
35impl StatVariant {
36    /// The `data-variant` value.
37    pub fn as_str(self) -> &'static str {
38        match self {
39            Self::Default => "default",
40            Self::Accent => "accent",
41            Self::Bare => "bare",
42            Self::Glass => "glass",
43        }
44    }
45}
46
47/// Semantic tone that colors the [`StatValue`] and [`StatIcon`] of a [`Stat`].
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum StatTone {
51    /// No tone.
52    #[default]
53    Default,
54    /// Positive.
55    Success,
56    /// Needs attention.
57    Warning,
58    /// Negative.
59    Danger,
60    /// Brand color.
61    Brand,
62}
63
64impl StatTone {
65    /// The `data-tone` value.
66    pub fn as_str(self) -> &'static str {
67        match self {
68            Self::Default => "default",
69            Self::Success => "success",
70            Self::Warning => "warning",
71            Self::Danger => "danger",
72            Self::Brand => "brand",
73        }
74    }
75}
76
77/// Props for [`Stat`].
78#[derive(Props, Clone, PartialEq)]
79pub struct StatProps {
80    /// Root element. Defaults to `<div>`.
81    #[props(default)]
82    pub r#as: StatAs,
83    /// Shorthand label, rendered as a [`StatLabel`] before the children.
84    #[props(into)]
85    pub label: Option<String>,
86    /// Shorthand value, rendered as a [`StatValue`] before the children.
87    #[props(into)]
88    pub value: Option<String>,
89    /// Surface treatment.
90    #[props(default)]
91    pub variant: StatVariant,
92    /// Semantic tone for the value and icon.
93    #[props(default)]
94    pub tone: StatTone,
95    /// Extra classes appended after the Lumen classes.
96    #[props(into)]
97    pub class: Option<String>,
98    /// Any other global attribute.
99    #[props(extends = GlobalAttributes, extends = div)]
100    pub attributes: Vec<Attribute>,
101    /// Composed parts such as [`StatLabel`], [`StatValue`], and [`StatTrend`].
102    pub children: Element,
103}
104
105/// A single metric: a label, a prominent value, and optional icon, trend, and description.
106#[component]
107pub fn Stat(props: StatProps) -> Element {
108    let variant = (props.variant != StatVariant::Default)
109        .then(|| format!("ui-stat--{}", props.variant.as_str()));
110    let tone =
111        (props.tone != StatTone::Default).then(|| format!("ui-stat--tone-{}", props.tone.as_str()));
112    let class = compose([
113        Some("ui-stat"),
114        variant.as_deref(),
115        tone.as_deref(),
116        props.class.as_deref(),
117    ]);
118    let data_tone = (props.tone != StatTone::Default).then_some(props.tone.as_str());
119    let data_variant = props.variant.as_str();
120    let body = rsx! {
121        if let Some(label) = props.label.filter(|label| !label.is_empty()) {
122            div { class: "ui-stat-label", "data-slot": "stat-label", "{label}" }
123        }
124        if let Some(value) = props.value.filter(|value| !value.is_empty()) {
125            div { class: "ui-stat-value", "data-slot": "stat-value", "{value}" }
126        }
127        {props.children}
128    };
129
130    match props.r#as {
131        StatAs::Div => rsx! {
132            div { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
133        },
134        StatAs::Article => rsx! {
135            article { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
136        },
137        StatAs::Section => rsx! {
138            section { class, "data-slot": "stat", "data-tone": data_tone, "data-variant": data_variant, ..props.attributes, {body} }
139        },
140    }
141}
142
143/// Props shared by [`StatLabel`], [`StatValue`], and [`StatDescription`].
144#[derive(Props, Clone, PartialEq)]
145pub struct StatPartProps {
146    /// Element to render. Defaults to `<div>`.
147    #[props(default)]
148    pub r#as: StatAs,
149    /// Extra classes appended after the Lumen class.
150    #[props(into)]
151    pub class: Option<String>,
152    /// Any other global attribute.
153    #[props(extends = GlobalAttributes, extends = div)]
154    pub attributes: Vec<Attribute>,
155    /// Content.
156    pub children: Element,
157}
158
159fn stat_part(base: &str, slot: &'static str, props: StatPartProps) -> Element {
160    let class = compose([Some(base), props.class.as_deref()]);
161
162    match props.r#as {
163        StatAs::Div => rsx! {
164            div { class, "data-slot": slot, ..props.attributes, {props.children} }
165        },
166        StatAs::Article => rsx! {
167            article { class, "data-slot": slot, ..props.attributes, {props.children} }
168        },
169        StatAs::Section => rsx! {
170            section { class, "data-slot": slot, ..props.attributes, {props.children} }
171        },
172    }
173}
174
175/// The label of a composed [`Stat`].
176#[component]
177pub fn StatLabel(props: StatPartProps) -> Element {
178    stat_part("ui-stat-label", "stat-label", props)
179}
180
181/// The prominent value of a composed [`Stat`].
182#[component]
183pub fn StatValue(props: StatPartProps) -> Element {
184    stat_part("ui-stat-value", "stat-value", props)
185}
186
187/// Supporting context under a [`StatValue`].
188#[component]
189pub fn StatDescription(props: StatPartProps) -> Element {
190    stat_part("ui-stat-description", "stat-description", props)
191}
192
193/// Props for [`StatIcon`].
194#[derive(Props, Clone, PartialEq)]
195pub struct StatIconProps {
196    /// Extra classes appended after the Lumen class.
197    #[props(into)]
198    pub class: Option<String>,
199    /// Any other `<span>` or global attribute.
200    #[props(extends = GlobalAttributes, extends = span)]
201    pub attributes: Vec<Attribute>,
202    /// The icon, usually an [`Icon`](crate::Icon).
203    pub children: Element,
204}
205
206/// The icon region of a composed [`Stat`].
207#[component]
208pub fn StatIcon(props: StatIconProps) -> Element {
209    let class = compose([Some("ui-stat-icon"), props.class.as_deref()]);
210
211    rsx! {
212        span { class, "data-slot": "stat-icon", ..props.attributes, {props.children} }
213    }
214}
215
216/// Tone of a [`StatTrend`].
217#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
218#[non_exhaustive]
219pub enum StatTrendTone {
220    /// No judgement.
221    #[default]
222    Neutral,
223    /// Positive change.
224    Success,
225    /// Change that needs attention.
226    Warning,
227    /// Negative change.
228    Danger,
229}
230
231impl StatTrendTone {
232    /// The class suffix and `data-tone` value.
233    pub fn as_str(self) -> &'static str {
234        match self {
235            Self::Neutral => "neutral",
236            Self::Success => "success",
237            Self::Warning => "warning",
238            Self::Danger => "danger",
239        }
240    }
241}
242
243/// Props for [`StatTrend`].
244#[derive(Props, Clone, PartialEq)]
245pub struct StatTrendProps {
246    /// Semantic tone of the change.
247    #[props(default)]
248    pub tone: StatTrendTone,
249    /// Extra classes appended after the Lumen classes.
250    #[props(into)]
251    pub class: Option<String>,
252    /// Any other `<span>` or global attribute.
253    #[props(extends = GlobalAttributes, extends = span)]
254    pub attributes: Vec<Attribute>,
255    /// The delta text, such as `+8%`.
256    pub children: Element,
257}
258
259/// A metric delta with a semantic tone.
260#[component]
261pub fn StatTrend(props: StatTrendProps) -> Element {
262    let tone = format!("ui-stat-trend--{}", props.tone.as_str());
263    let class = compose([
264        Some("ui-stat-trend"),
265        Some(tone.as_str()),
266        props.class.as_deref(),
267    ]);
268
269    rsx! {
270        span {
271            class,
272            "data-slot": "stat-trend",
273            "data-tone": props.tone.as_str(),
274            ..props.attributes,
275            {props.children}
276        }
277    }
278}
279
280/// Props for [`StatGroup`].
281#[derive(Props, Clone, PartialEq)]
282pub struct StatGroupProps {
283    /// Joins the stats into one framed strip with dividers between them.
284    #[props(default)]
285    pub dividers: bool,
286    /// Extra classes appended after the Lumen classes.
287    #[props(into)]
288    pub class: Option<String>,
289    /// Any other `<div>` or global attribute. Name the group with `aria_label`.
290    #[props(extends = GlobalAttributes, extends = div)]
291    pub attributes: Vec<Attribute>,
292    /// The [`Stat`]s.
293    pub children: Element,
294}
295
296/// A responsive row of [`Stat`]s that wraps on narrow widths.
297#[component]
298pub fn StatGroup(props: StatGroupProps) -> Element {
299    let class = compose([
300        Some("ui-stat-group"),
301        props.dividers.then_some("ui-stat-group--dividers"),
302        props.class.as_deref(),
303    ]);
304
305    rsx! {
306        div {
307            class,
308            "data-dividers": props.dividers.then_some(""),
309            "data-slot": "stat-group",
310            role: "group",
311            ..props.attributes,
312            {props.children}
313        }
314    }
315}
316
317/// Most slots a segmented [`Meter`] draws; larger counts render a continuous bar.
318pub const METER_MAX_SEGMENTS: u32 = 24;
319
320/// Default value text of a segmented [`Meter`], counted from `min`.
321pub const METER_DEFAULT_VALUE_LABEL: &str = "{value} of {max}";
322
323/// A segment count from 2 to 24, or `None` for a continuous meter.
324pub fn resolve_meter_segments(segments: Option<u32>) -> Option<u32> {
325    segments.filter(|count| (2..=METER_MAX_SEGMENTS).contains(count))
326}
327
328/// The clamped range a [`Meter`] shows, like the native `<meter>` element.
329#[derive(Clone, Copy, Debug, PartialEq)]
330pub struct MeterRange {
331    /// Lower bound; defaults to 0.
332    pub min: f64,
333    /// Upper bound; defaults to 100 and never falls below `min`.
334    pub max: f64,
335    /// The value clamped into the range.
336    pub value: f64,
337}
338
339fn finite(value: Option<f64>) -> Option<f64> {
340    value.filter(|number| number.is_finite())
341}
342
343/// Normalizes a meter range the way the native element does.
344pub fn resolve_meter_range(min: Option<f64>, max: Option<f64>, value: f64) -> MeterRange {
345    let min = finite(min).unwrap_or(0.0);
346    let fallback_max = if min < 100.0 { 100.0 } else { min + 1.0 };
347    let max = finite(max).unwrap_or(fallback_max).max(min);
348    let value = finite(Some(value)).unwrap_or(min).clamp(min, max);
349
350    MeterRange { min, max, value }
351}
352
353/// Replaces `{name}` placeholders with a linear scan; unknown placeholders stay as written.
354pub(crate) fn fill_template(template: &str, values: &[(&str, &str)]) -> String {
355    let mut out = String::with_capacity(template.len());
356    let mut rest = template;
357
358    while let Some(open) = rest.find('{') {
359        out.push_str(&rest[..open]);
360        let after = &rest[open + 1..];
361
362        match after.find(['}', '{']) {
363            Some(close) if after.as_bytes()[close] == b'}' => {
364                let name = &after[..close];
365
366                if let Some((_, value)) = values.iter().find(|(key, _)| *key == name) {
367                    out.push_str(value);
368                } else {
369                    out.push('{');
370                    out.push_str(name);
371                    out.push('}');
372                }
373
374                rest = &after[close + 1..];
375            }
376            _ => {
377                out.push('{');
378                rest = after;
379            }
380        }
381    }
382
383    out.push_str(rest);
384    out
385}
386
387/// Formats a number like `Intl.NumberFormat("en")`: up to three fraction digits, rounded half
388/// away from zero from the shortest decimal form, with comma grouping.
389pub(crate) fn format_en_number(value: f64) -> String {
390    if value.is_nan() {
391        return "NaN".to_string();
392    }
393
394    if value.is_infinite() {
395        return if value > 0.0 { "∞" } else { "-∞" }.to_string();
396    }
397
398    let negative = value.is_sign_negative();
399    let digits = format!("{}", value.abs());
400    let (integer, fraction) = digits.split_once('.').unwrap_or((digits.as_str(), ""));
401    let mut whole: Vec<u8> = integer.bytes().map(|byte| byte - b'0').collect();
402    let mut kept: Vec<u8> = fraction.bytes().take(3).map(|byte| byte - b'0').collect();
403
404    if fraction
405        .as_bytes()
406        .get(3)
407        .is_some_and(|digit| *digit >= b'5')
408    {
409        let mut carry = true;
410
411        for digit in kept.iter_mut().rev().chain(whole.iter_mut().rev()) {
412            if !carry {
413                break;
414            }
415
416            if *digit == 9 {
417                *digit = 0;
418            } else {
419                *digit += 1;
420                carry = false;
421            }
422        }
423
424        if carry {
425            whole.insert(0, 1);
426        }
427    }
428
429    while kept.last() == Some(&0) {
430        kept.pop();
431    }
432
433    let mut out = String::new();
434
435    if negative {
436        out.push('-');
437    }
438
439    for (index, digit) in whole.iter().enumerate() {
440        if index > 0 && (whole.len() - index).is_multiple_of(3) {
441            out.push(',');
442        }
443
444        out.push(char::from(b'0' + digit));
445    }
446
447    if !kept.is_empty() {
448        out.push('.');
449        out.extend(kept.iter().map(|digit| char::from(b'0' + digit)));
450    }
451
452    out
453}
454
455/// Text for a meter's `aria-valuetext`, such as `3 of 5`, or `None` for a continuous meter
456/// without a `value_label` (which keeps the native percentage reading).
457pub fn resolve_meter_value_text(
458    range: MeterRange,
459    segmented: bool,
460    value_label: Option<&str>,
461) -> Option<String> {
462    let label = value_label.filter(|label| !label.trim().is_empty());
463
464    match label {
465        None if !segmented => None,
466        None => Some(fill_template(
467            METER_DEFAULT_VALUE_LABEL,
468            &[
469                ("max", &format_en_number(range.max - range.min)),
470                ("value", &format_en_number(range.value - range.min)),
471            ],
472        )),
473        Some(label) => Some(fill_template(
474            label,
475            &[
476                ("max", &format_en_number(range.max)),
477                ("min", &format_en_number(range.min)),
478                ("value", &format_en_number(range.value)),
479            ],
480        )),
481    }
482}
483
484/// Props for [`Meter`].
485#[derive(Props, Clone, PartialEq)]
486pub struct MeterProps {
487    /// Current value; clamped into `min..=max` for the value text.
488    #[props(default)]
489    pub value: f64,
490    /// Lower bound. Defaults to 0.
491    pub min: Option<f64>,
492    /// Upper bound. Defaults to 100.
493    pub max: Option<f64>,
494    /// Draws one mark per slot, such as 5 for "3 of 5 seats". Whole counts from 2 to 24, normally
495    /// `max - min`; other values render the continuous bar.
496    pub segments: Option<u32>,
497    /// Accessible value text with `{value}`, `{min}`, and `{max}` placeholders. Segmented meters
498    /// default to `{value} of {max}`.
499    #[props(into)]
500    pub value_label: Option<String>,
501    /// Explicit `aria-valuetext`; wins over the computed text.
502    #[props(into)]
503    pub aria_valuetext: Option<String>,
504    /// Extra classes appended after the Lumen classes.
505    #[props(into)]
506    pub class: Option<String>,
507    /// Any other `<meter>` or global attribute, such as `aria_label`, `low`, `high`, or `optimum`.
508    #[props(extends = GlobalAttributes, extends = meter)]
509    pub attributes: Vec<Attribute>,
510    /// Fallback content; defaults to the value text.
511    pub children: Element,
512}
513
514/// A native `<meter>` for a measurement in a known range, with optional quota segments.
515///
516/// Numbers in the value text use English formatting.
517#[component]
518pub fn Meter(props: MeterProps) -> Element {
519    let segments = resolve_meter_segments(props.segments);
520    let range = resolve_meter_range(props.min, props.max, props.value);
521    let value_text =
522        resolve_meter_value_text(range, segments.is_some(), props.value_label.as_deref());
523    let class = compose([
524        Some("ui-meter"),
525        segments.is_some().then_some("ui-meter--segmented"),
526        props.class.as_deref(),
527    ]);
528    let has_children = super::has_content(&props.children);
529    let aria_valuetext = props.aria_valuetext.or_else(|| value_text.clone());
530
531    rsx! {
532        meter {
533            aria_valuetext,
534            class,
535            "data-segments": segments.map(|count| count.to_string()),
536            style: segments.map(|count| format!("--ui-meter-segments:{count}")),
537            max: props.max.map(|max| max.to_string()),
538            min: props.min.map(|min| min.to_string()),
539            value: "{props.value}",
540            ..props.attributes,
541            if has_children {
542                {props.children}
543            } else if let Some(text) = value_text {
544                "{text}"
545            }
546        }
547    }
548}
549
550#[cfg(test)]
551mod tests {
552    use super::{
553        MeterRange, fill_template, format_en_number, resolve_meter_range, resolve_meter_segments,
554        resolve_meter_value_text,
555    };
556
557    #[test]
558    fn english_numbers_match_intl() {
559        assert_eq!(format_en_number(1.0005), "1.001");
560        assert_eq!(format_en_number(0.0625), "0.063");
561        assert_eq!(format_en_number(-1.5), "-1.5");
562        assert_eq!(format_en_number(1_234_567.891_5), "1,234,567.892");
563        assert_eq!(format_en_number(1e21), "1,000,000,000,000,000,000,000");
564        assert_eq!(format_en_number(0.1 + 0.2), "0.3");
565        assert_eq!(format_en_number(-0.0004), "-0");
566        assert_eq!(format_en_number(0.9996), "1");
567        assert_eq!(format_en_number(999.9999), "1,000");
568        assert_eq!(format_en_number(0.0), "0");
569    }
570
571    #[test]
572    fn meter_segments_are_whole_counts_from_two_to_twenty_four() {
573        assert_eq!(resolve_meter_segments(Some(5)), Some(5));
574        assert_eq!(resolve_meter_segments(Some(1)), None);
575        assert_eq!(resolve_meter_segments(Some(25)), None);
576        assert_eq!(resolve_meter_segments(None), None);
577    }
578
579    #[test]
580    fn meter_range_clamps_like_the_native_element() {
581        assert_eq!(
582            resolve_meter_range(None, None, 150.0),
583            MeterRange {
584                min: 0.0,
585                max: 100.0,
586                value: 100.0
587            }
588        );
589        assert_eq!(
590            resolve_meter_range(Some(200.0), Some(10.0), 5.0),
591            MeterRange {
592                min: 200.0,
593                max: 200.0,
594                value: 200.0
595            }
596        );
597        assert_eq!(
598            resolve_meter_range(Some(150.0), None, f64::NAN),
599            MeterRange {
600                min: 150.0,
601                max: 151.0,
602                value: 150.0
603            }
604        );
605    }
606
607    #[test]
608    fn meter_value_text_counts_segments_from_min() {
609        let range = resolve_meter_range(Some(10.0), Some(20.0), 15.0);
610
611        assert_eq!(
612            resolve_meter_value_text(range, true, None).as_deref(),
613            Some("5 of 10")
614        );
615        assert_eq!(resolve_meter_value_text(range, false, None), None);
616        assert_eq!(
617            resolve_meter_value_text(range, false, Some("{value} of {max} ({min})")).as_deref(),
618            Some("15 of 20 (10)")
619        );
620        assert_eq!(resolve_meter_value_text(range, false, Some("  ")), None);
621    }
622
623    #[test]
624    fn templates_keep_unknown_and_unbalanced_placeholders() {
625        assert_eq!(fill_template("{a} {b} {", &[("a", "1")]), "1 {b} {");
626        assert_eq!(fill_template("{{a}", &[("a", "1")]), "{1");
627        let long = "{".repeat(100_000);
628        assert_eq!(fill_template(&long, &[]).len(), 100_000);
629    }
630}