lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `FormattedDate` and `FormattedNumber`.
//!
//! Number formatting uses Unicode ICU/CLDR data on every renderer, including Dioxus Native,
//! without a JavaScript runtime. The default English contract retains its existing rounding.

use dioxus::prelude::*;

use super::number_format::{
    FORMATTED_NUMBER_FALLBACK, FormattedDateStyle, FormattedDateTimeStyle,
    FormattedNumberCurrencyDisplay, FormattedNumberCurrencyName, FormattedNumberFormat,
    FormattedNumberNotation, FormattedNumberSignDisplay, FormattedNumberUnitDisplay,
    FormattedNumberValue, NumberFormatOptions, format_lumen_date, format_lumen_number,
};
use crate::class::compose;
use crate::inputs::number_field_host::use_scripting;

/// Props for [`FormattedDate`].
#[derive(Props, Clone, PartialEq)]
pub struct FormattedDateProps {
    /// Machine-readable date for the `datetime` attribute, such as `2026-12-01` or
    /// `2026-12-01T09:30:00Z`.
    #[props(into)]
    pub date_time: Option<String>,
    /// Formats `date_time` in English and renders it instead of `children`.
    pub date_style: Option<FormattedDateStyle>,
    /// Adds the time of day to the formatted text, in UTC.
    pub time_style: Option<FormattedDateTimeStyle>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<time>` or global attribute.
    #[props(extends = GlobalAttributes, extends = time)]
    pub attributes: Vec<Attribute>,
    /// The visible date text. Rendered when no style is set, or when `date_time` does not parse.
    pub children: Element,
}

/// A `<time>` element for display dates.
///
/// Pass the text as children, like lumen-react, or set `date_style` and `time_style` to format
/// `date_time` without `Intl`: the output matches
/// `Intl.DateTimeFormat('en-US', { dateStyle, timeStyle, timeZone: 'UTC' })`.
#[component]
pub fn FormattedDate(props: FormattedDateProps) -> Element {
    let class = compose([Some("ui-formatted-date"), props.class.as_deref()]);
    let formatted = (props.date_style.is_some() || props.time_style.is_some())
        .then(|| {
            props
                .date_time
                .as_deref()
                .and_then(|value| format_lumen_date(value, props.date_style, props.time_style))
        })
        .flatten();

    rsx! {
        time { class, datetime: props.date_time.clone(), ..props.attributes,
            if let Some(text) = formatted {
                {text}
            } else {
                {props.children}
            }
        }
    }
}

/// Props for [`FormattedNumber`].
#[derive(Props, Clone, PartialEq)]
pub struct FormattedNumberProps {
    /// The number, or a plain decimal string such as `"1234.5"` or `"2e3"`.
    #[props(into)]
    pub value: FormattedNumberValue,
    /// Number style.
    #[props(default)]
    pub format: FormattedNumberFormat,
    /// ISO 4217 code such as `USD`. Required by [`FormattedNumberFormat::Currency`].
    #[props(into)]
    pub currency: Option<String>,
    /// How the currency is shown.
    #[props(default)]
    pub currency_display: FormattedNumberCurrencyDisplay,
    /// When the full currency name is read to assistive technology.
    #[props(default)]
    pub currency_name: FormattedNumberCurrencyName,
    /// A sanctioned unit such as `kilobyte` or `kilometer-per-hour`. Required by
    /// [`FormattedNumberFormat::Unit`].
    #[props(into)]
    pub unit: Option<String>,
    /// How the unit is shown.
    #[props(default)]
    pub unit_display: FormattedNumberUnitDisplay,
    /// Standard, scientific, engineering, or compact notation.
    #[props(default)]
    pub notation: FormattedNumberNotation,
    /// When to show the sign.
    #[props(default)]
    pub sign_display: FormattedNumberSignDisplay,
    /// Minimum fraction digits, clamped to 0 through 20.
    pub minimum_fraction_digits: Option<f64>,
    /// Maximum fraction digits, clamped to 0 through 20 and never below the minimum.
    pub maximum_fraction_digits: Option<f64>,
    /// BCP 47 locale, including a Unicode numbering-system extension. Defaults to English;
    /// malformed or unsupported language tags also use English.
    #[props(into)]
    pub locale: Option<String>,
    /// Text shown when `value` is not a finite number.
    #[props(default = FORMATTED_NUMBER_FALLBACK.to_string(), into)]
    pub fallback: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute.
    #[props(extends = GlobalAttributes)]
    pub attributes: Vec<Attribute>,
}

/// A display-only number. Renders `<data value>` with the machine-readable number; compact
/// numbers, units, and ambiguous currency symbols add a screen-reader-only long reading, such as
/// "1.2 thousand US dollars" for a visible "$1.2K".
#[component]
pub fn FormattedNumber(props: FormattedNumberProps) -> Element {
    let options = NumberFormatOptions {
        format: props.format,
        notation: props.notation,
        sign_display: props.sign_display,
        currency: props.currency.clone(),
        currency_display: props.currency_display,
        currency_name: props.currency_name,
        unit: props.unit.clone(),
        unit_display: props.unit_display,
        locale: props.locale.clone(),
        minimum_fraction_digits: props.minimum_fraction_digits,
        maximum_fraction_digits: props.maximum_fraction_digits,
    };
    let formatted = format_lumen_number(&props.value, &options, &props.fallback);
    // Blitz does not apply the legacy clip rectangle used by ui-sr-only. Its opacity-zero
    // paint path keeps this text in the accessibility tree without drawing it over another row.
    let accessible_style = (use_scripting() == Some(false)).then_some("opacity: 0;");
    let class = compose([Some("ui-formatted-number"), props.class.as_deref()]);
    let content = match formatted.accessible_text {
        Some(accessible) => rsx! {
            span { aria_hidden: "true", "data-slot": "formatted-number-text", {formatted.text} }
            span { class: "ui-sr-only", style: accessible_style, {accessible} }
        },
        None => rsx! {
            {formatted.text}
        },
    };

    match formatted.value {
        Some(value) if formatted.valid => rsx! {
            data { class, "data-slot": "formatted-number", value, ..props.attributes, {content} }
        },
        _ => rsx! {
            span {
                class,
                "data-invalid": "",
                "data-slot": "formatted-number",
                ..props.attributes,
                {content}
            }
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::inputs::number_field_host::set_scripting_for_tests;

    fn currency(value: f64) -> Element {
        rsx! {
            FormattedNumber {
                value,
                locale: "es-CO",
                format: FormattedNumberFormat::Currency,
                currency: "COP",
            }
        }
    }

    #[test]
    fn native_long_reading_stays_present_without_being_painted() {
        set_scripting_for_tests(Some(false));
        let html = dioxus_ssr::render_element(rsx! { {currency(1234.5)} });
        set_scripting_for_tests(None);

        assert!(html.contains("value=\"1234.5\""), "{html}");
        assert!(html.contains("$\u{a0}1.235"), "{html}");
        assert!(
            html.contains(
                "<span class=\"ui-sr-only\" style=\"opacity: 0;\">1.235 pesos colombianos</span>"
            ),
            "{html}"
        );
        assert_eq!(
            html.matches("aria-hidden=\"true\"").count(),
            1,
            "only the visible reading is aria-hidden: {html}"
        );
        assert!(
            !html.contains(" hidden")
                && !html.contains("display: none")
                && !html.contains("visibility: hidden"),
            "{html}"
        );
    }

    #[test]
    fn web_and_ssr_preserve_the_shared_long_reading_markup() {
        for scripting in [None, Some(true)] {
            set_scripting_for_tests(scripting);
            let html = dioxus_ssr::render_element(rsx! { {currency(1234.5)} });
            set_scripting_for_tests(None);
            assert!(
                html.contains("<span class=\"ui-sr-only\">1.235 pesos colombianos</span>"),
                "{html}"
            );
            assert!(!html.contains("opacity:"), "{html}");
        }
    }

    fn reactive_currency() -> Element {
        let value = use_context::<Signal<f64>>();
        currency(value())
    }

    #[test]
    fn native_value_changes_update_both_readings() {
        set_scripting_for_tests(Some(false));
        let mut dom = VirtualDom::new(reactive_currency);
        let mut value = dom.in_scope(ScopeId::ROOT, || Signal::new(1234.5));
        dom.provide_root_context(value);
        dom.rebuild_in_place();
        let before = dioxus_ssr::render(&dom);
        dom.in_scope(ScopeId::ROOT, || value.set(12345.0));
        dom.render_immediate_to_vec();
        let after = dioxus_ssr::render(&dom);
        set_scripting_for_tests(None);

        assert!(before.contains("1.235 pesos colombianos"), "{before}");
        assert!(after.contains("$\u{a0}12.345"), "{after}");
        assert!(
            after.contains(
                "<span class=\"ui-sr-only\" style=\"opacity: 0;\">12.345 pesos colombianos</span>"
            ),
            "{after}"
        );
        assert!(!after.contains("1.235 pesos colombianos"), "{after}");
    }
}