Skip to main content

lumen_dioxus/content/
formatted.rs

1//! `FormattedDate` and `FormattedNumber`.
2//!
3//! Number formatting uses Unicode ICU/CLDR data on every renderer, including Dioxus Native,
4//! without a JavaScript runtime. The default English contract retains its existing rounding.
5
6use dioxus::prelude::*;
7
8use super::number_format::{
9    FORMATTED_NUMBER_FALLBACK, FormattedDateStyle, FormattedDateTimeStyle,
10    FormattedNumberCurrencyDisplay, FormattedNumberCurrencyName, FormattedNumberFormat,
11    FormattedNumberNotation, FormattedNumberSignDisplay, FormattedNumberUnitDisplay,
12    FormattedNumberValue, NumberFormatOptions, format_lumen_date, format_lumen_number,
13};
14use crate::class::compose;
15use crate::inputs::number_field_host::use_scripting;
16
17/// Props for [`FormattedDate`].
18#[derive(Props, Clone, PartialEq)]
19pub struct FormattedDateProps {
20    /// Machine-readable date for the `datetime` attribute, such as `2026-12-01` or
21    /// `2026-12-01T09:30:00Z`.
22    #[props(into)]
23    pub date_time: Option<String>,
24    /// Formats `date_time` in English and renders it instead of `children`.
25    pub date_style: Option<FormattedDateStyle>,
26    /// Adds the time of day to the formatted text, in UTC.
27    pub time_style: Option<FormattedDateTimeStyle>,
28    /// Extra classes appended after the Lumen class.
29    #[props(into)]
30    pub class: Option<String>,
31    /// Any other `<time>` or global attribute.
32    #[props(extends = GlobalAttributes, extends = time)]
33    pub attributes: Vec<Attribute>,
34    /// The visible date text. Rendered when no style is set, or when `date_time` does not parse.
35    pub children: Element,
36}
37
38/// A `<time>` element for display dates.
39///
40/// Pass the text as children, like lumen-react, or set `date_style` and `time_style` to format
41/// `date_time` without `Intl`: the output matches
42/// `Intl.DateTimeFormat('en-US', { dateStyle, timeStyle, timeZone: 'UTC' })`.
43#[component]
44pub fn FormattedDate(props: FormattedDateProps) -> Element {
45    let class = compose([Some("ui-formatted-date"), props.class.as_deref()]);
46    let formatted = (props.date_style.is_some() || props.time_style.is_some())
47        .then(|| {
48            props
49                .date_time
50                .as_deref()
51                .and_then(|value| format_lumen_date(value, props.date_style, props.time_style))
52        })
53        .flatten();
54
55    rsx! {
56        time { class, datetime: props.date_time.clone(), ..props.attributes,
57            if let Some(text) = formatted {
58                {text}
59            } else {
60                {props.children}
61            }
62        }
63    }
64}
65
66/// Props for [`FormattedNumber`].
67#[derive(Props, Clone, PartialEq)]
68pub struct FormattedNumberProps {
69    /// The number, or a plain decimal string such as `"1234.5"` or `"2e3"`.
70    #[props(into)]
71    pub value: FormattedNumberValue,
72    /// Number style.
73    #[props(default)]
74    pub format: FormattedNumberFormat,
75    /// ISO 4217 code such as `USD`. Required by [`FormattedNumberFormat::Currency`].
76    #[props(into)]
77    pub currency: Option<String>,
78    /// How the currency is shown.
79    #[props(default)]
80    pub currency_display: FormattedNumberCurrencyDisplay,
81    /// When the full currency name is read to assistive technology.
82    #[props(default)]
83    pub currency_name: FormattedNumberCurrencyName,
84    /// A sanctioned unit such as `kilobyte` or `kilometer-per-hour`. Required by
85    /// [`FormattedNumberFormat::Unit`].
86    #[props(into)]
87    pub unit: Option<String>,
88    /// How the unit is shown.
89    #[props(default)]
90    pub unit_display: FormattedNumberUnitDisplay,
91    /// Standard, scientific, engineering, or compact notation.
92    #[props(default)]
93    pub notation: FormattedNumberNotation,
94    /// When to show the sign.
95    #[props(default)]
96    pub sign_display: FormattedNumberSignDisplay,
97    /// Minimum fraction digits, clamped to 0 through 20.
98    pub minimum_fraction_digits: Option<f64>,
99    /// Maximum fraction digits, clamped to 0 through 20 and never below the minimum.
100    pub maximum_fraction_digits: Option<f64>,
101    /// BCP 47 locale, including a Unicode numbering-system extension. Defaults to English;
102    /// malformed or unsupported language tags also use English.
103    #[props(into)]
104    pub locale: Option<String>,
105    /// Text shown when `value` is not a finite number.
106    #[props(default = FORMATTED_NUMBER_FALLBACK.to_string(), into)]
107    pub fallback: String,
108    /// Extra classes appended after the Lumen class.
109    #[props(into)]
110    pub class: Option<String>,
111    /// Any other global attribute.
112    #[props(extends = GlobalAttributes)]
113    pub attributes: Vec<Attribute>,
114}
115
116/// A display-only number. Renders `<data value>` with the machine-readable number; compact
117/// numbers, units, and ambiguous currency symbols add a screen-reader-only long reading, such as
118/// "1.2 thousand US dollars" for a visible "$1.2K".
119#[component]
120pub fn FormattedNumber(props: FormattedNumberProps) -> Element {
121    let options = NumberFormatOptions {
122        format: props.format,
123        notation: props.notation,
124        sign_display: props.sign_display,
125        currency: props.currency.clone(),
126        currency_display: props.currency_display,
127        currency_name: props.currency_name,
128        unit: props.unit.clone(),
129        unit_display: props.unit_display,
130        locale: props.locale.clone(),
131        minimum_fraction_digits: props.minimum_fraction_digits,
132        maximum_fraction_digits: props.maximum_fraction_digits,
133    };
134    let formatted = format_lumen_number(&props.value, &options, &props.fallback);
135    // Blitz does not apply the legacy clip rectangle used by ui-sr-only. Its opacity-zero
136    // paint path keeps this text in the accessibility tree without drawing it over another row.
137    let accessible_style = (use_scripting() == Some(false)).then_some("opacity: 0;");
138    let class = compose([Some("ui-formatted-number"), props.class.as_deref()]);
139    let content = match formatted.accessible_text {
140        Some(accessible) => rsx! {
141            span { aria_hidden: "true", "data-slot": "formatted-number-text", {formatted.text} }
142            span { class: "ui-sr-only", style: accessible_style, {accessible} }
143        },
144        None => rsx! {
145            {formatted.text}
146        },
147    };
148
149    match formatted.value {
150        Some(value) if formatted.valid => rsx! {
151            data { class, "data-slot": "formatted-number", value, ..props.attributes, {content} }
152        },
153        _ => rsx! {
154            span {
155                class,
156                "data-invalid": "",
157                "data-slot": "formatted-number",
158                ..props.attributes,
159                {content}
160            }
161        },
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::inputs::number_field_host::set_scripting_for_tests;
169
170    fn currency(value: f64) -> Element {
171        rsx! {
172            FormattedNumber {
173                value,
174                locale: "es-CO",
175                format: FormattedNumberFormat::Currency,
176                currency: "COP",
177            }
178        }
179    }
180
181    #[test]
182    fn native_long_reading_stays_present_without_being_painted() {
183        set_scripting_for_tests(Some(false));
184        let html = dioxus_ssr::render_element(rsx! { {currency(1234.5)} });
185        set_scripting_for_tests(None);
186
187        assert!(html.contains("value=\"1234.5\""), "{html}");
188        assert!(html.contains("$\u{a0}1.235"), "{html}");
189        assert!(
190            html.contains(
191                "<span class=\"ui-sr-only\" style=\"opacity: 0;\">1.235 pesos colombianos</span>"
192            ),
193            "{html}"
194        );
195        assert_eq!(
196            html.matches("aria-hidden=\"true\"").count(),
197            1,
198            "only the visible reading is aria-hidden: {html}"
199        );
200        assert!(
201            !html.contains(" hidden")
202                && !html.contains("display: none")
203                && !html.contains("visibility: hidden"),
204            "{html}"
205        );
206    }
207
208    #[test]
209    fn web_and_ssr_preserve_the_shared_long_reading_markup() {
210        for scripting in [None, Some(true)] {
211            set_scripting_for_tests(scripting);
212            let html = dioxus_ssr::render_element(rsx! { {currency(1234.5)} });
213            set_scripting_for_tests(None);
214            assert!(
215                html.contains("<span class=\"ui-sr-only\">1.235 pesos colombianos</span>"),
216                "{html}"
217            );
218            assert!(!html.contains("opacity:"), "{html}");
219        }
220    }
221
222    fn reactive_currency() -> Element {
223        let value = use_context::<Signal<f64>>();
224        currency(value())
225    }
226
227    #[test]
228    fn native_value_changes_update_both_readings() {
229        set_scripting_for_tests(Some(false));
230        let mut dom = VirtualDom::new(reactive_currency);
231        let mut value = dom.in_scope(ScopeId::ROOT, || Signal::new(1234.5));
232        dom.provide_root_context(value);
233        dom.rebuild_in_place();
234        let before = dioxus_ssr::render(&dom);
235        dom.in_scope(ScopeId::ROOT, || value.set(12345.0));
236        dom.render_immediate_to_vec();
237        let after = dioxus_ssr::render(&dom);
238        set_scripting_for_tests(None);
239
240        assert!(before.contains("1.235 pesos colombianos"), "{before}");
241        assert!(after.contains("$\u{a0}12.345"), "{after}");
242        assert!(
243            after.contains(
244                "<span class=\"ui-sr-only\" style=\"opacity: 0;\">12.345 pesos colombianos</span>"
245            ),
246            "{after}"
247        );
248        assert!(!after.contains("1.235 pesos colombianos"), "{after}");
249    }
250}