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
//! A number that counts up when it scrolls into view.
// cspell:words onvisible subtags

use std::time::Duration;

use dioxus::core::Task;
use dioxus::prelude::*;

use super::shared::{MotionDuration, use_motion_support};
use crate::class::compose;
use crate::time::sleep;

/// Separators and grouping of one locale, a small table in place of `Intl.NumberFormat`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct NumberSymbols {
    group: &'static str,
    decimal: &'static str,
    minus: &'static str,
    /// Digits the integer part needs before it is grouped at all, beyond the first group.
    min_grouping: usize,
    /// Indian grouping: the last three digits, then pairs.
    indian: bool,
}

const EN: NumberSymbols = NumberSymbols {
    group: ",",
    decimal: ".",
    minus: "-",
    min_grouping: 1,
    indian: false,
};

const fn symbols(group: &'static str, decimal: &'static str) -> NumberSymbols {
    NumberSymbols {
        group,
        decimal,
        minus: "-",
        min_grouping: 1,
        indian: false,
    }
}

const NBSP: &str = "\u{a0}";

/// Picks the separators for a BCP 47 locale. Unknown or missing locales use en-US, the default
/// of lumen-react's server rendering.
fn number_symbols(locale: Option<&str>) -> NumberSymbols {
    let Some(locale) = locale else {
        return EN;
    };
    let lower = locale.trim().to_ascii_lowercase();
    let mut subtags = lower.split(['-', '_']);
    let language = subtags.next().unwrap_or_default();
    let region = subtags
        .find(|tag| tag.len() == 2 || (tag.len() == 3 && tag.chars().all(|c| c.is_ascii_digit())))
        .unwrap_or_default();
    let american_spanish = language == "es" && matches!(region, "mx" | "us");

    match (language, region) {
        ("en", "in") | ("hi", _) => NumberSymbols { indian: true, ..EN },
        ("de", "at") | ("fr", "ca") | ("ru" | "uk" | "cs" | "sk", _) => symbols(NBSP, ","),
        ("de", "ch" | "li") => symbols("'", "."),
        ("pt", "pt") | ("pl" | "hu" | "bg", _) => NumberSymbols {
            min_grouping: 2,
            ..symbols(NBSP, ",")
        },
        // Spanish in Mexico and the United States groups like en-US.
        ("es" | "it", _) if !american_spanish => NumberSymbols {
            min_grouping: 2,
            ..symbols(".", ",")
        },
        ("de" | "nl" | "pt" | "id" | "da" | "tr" | "el" | "ro" | "vi", _) => symbols(".", ","),
        ("fr", "ch") => symbols("'", ","),
        ("fr", _) => symbols("\u{202f}", ","),
        ("sv" | "fi" | "nb" | "no", _) => NumberSymbols {
            minus: "\u{2212}",
            ..symbols(NBSP, ",")
        },
        ("he" | "ar", _) => NumberSymbols {
            minus: "\u{200e}-",
            ..EN
        },
        _ => EN,
    }
}

/// Rounds a plain decimal string half away from zero, the way `Intl.NumberFormat` rounds the
/// shortest decimal form of a number. Returns integer and fraction digits.
fn round_decimal(digits: &str, decimals: usize) -> (Vec<u8>, Vec<u8>) {
    let (integer, fraction) = digits.split_once('.').unwrap_or((digits, ""));
    let mut integer: Vec<u8> = integer.bytes().map(|byte| byte - b'0').collect();
    let mut fraction: Vec<u8> = fraction.bytes().map(|byte| byte - b'0').collect();
    let round_up = fraction.get(decimals).is_some_and(|digit| *digit >= 5);

    fraction.resize(decimals, 0);

    if round_up {
        let mut carry = true;

        for digit in fraction.iter_mut().rev().chain(integer.iter_mut().rev()) {
            if *digit == 9 {
                *digit = 0;
            } else {
                *digit += 1;
                carry = false;
                break;
            }
        }

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

    (integer, fraction)
}

fn group_integer(digits: &[u8], symbols: NumberSymbols) -> String {
    let text: String = digits
        .iter()
        .map(|digit| char::from(b'0' + digit))
        .collect();
    let length = digits.len();

    if length < 4 + symbols.min_grouping - 1 {
        return text;
    }

    let mut groups = Vec::new();
    let mut end = length;
    let mut size = 3;

    while end > size {
        groups.push(&text[end - size..end]);
        end -= size;

        if symbols.indian {
            size = 2;
        }
    }

    groups.push(&text[..end]);
    groups.reverse();
    groups.join(symbols.group)
}

/// Formats a number with exactly `decimals` fraction digits (clamped to 0..=20), like
/// `Intl.NumberFormat(locale, { minimumFractionDigits, maximumFractionDigits })`.
pub(crate) fn format_number(value: f64, decimals: u32, locale: Option<&str>) -> String {
    let symbols = number_symbols(locale);
    let sign = if value.is_sign_negative() && !value.is_nan() {
        symbols.minus
    } else {
        ""
    };

    if value.is_nan() {
        return "NaN".to_string();
    }

    if value.is_infinite() {
        return format!("{sign}\u{221e}");
    }

    let decimals = usize::try_from(decimals.min(20)).unwrap_or(20);
    let (integer, fraction) = round_decimal(&format!("{}", value.abs()), decimals);
    let mut out = format!("{sign}{}", group_integer(&integer, symbols));

    if decimals > 0 {
        out.push_str(symbols.decimal);
        out.extend(fraction.iter().map(|digit| char::from(b'0' + digit)));
    }

    out
}

/// Ease-out cubic, like lumen-react's counter.
fn ease_out(progress: f64) -> f64 {
    1.0 - (1.0 - progress).powi(3)
}

const FRAME: Duration = Duration::from_millis(16);

/// The bits of `number` with every `NaN` alike, so a dependency check sees an unchanged `NaN` as
/// unchanged, like React's `Object.is`. The number itself still shows as given (`NaN`, `∞`), as
/// `Intl.NumberFormat` shows it in lumen-react.
fn dependency_bits(number: f64) -> u64 {
    if number.is_nan() {
        f64::NAN.to_bits()
    } else {
        number.to_bits()
    }
}

/// Counts from `from` to `to` over `duration`, one step per frame, then settles on the exact value.
fn count_up(
    mut display: Signal<Option<f64>>,
    mut task: CopyValue<Option<Task>>,
    mut pending: CopyValue<bool>,
    (from, to): (f64, f64),
    duration: MotionDuration,
) {
    pending.set(false);

    if let Some(previous) = task.write().take() {
        previous.cancel();
    }

    let frames = u32::try_from(duration.milliseconds() / 16)
        .unwrap_or(1)
        .max(1);
    let handle = spawn(async move {
        for frame in 1..=frames {
            sleep(FRAME).await;
            let eased = ease_out(f64::from(frame) / f64::from(frames));
            display.set(Some(from + (to - from) * eased));
        }

        display.set(None);
    });

    task.set(Some(handle));
}

/// Props for [`AnimatedNumber`].
#[derive(Props, Clone, PartialEq)]
pub struct AnimatedNumberProps {
    /// The final value.
    #[props(into)]
    pub value: f64,
    /// Fraction digits, clamped to 0..=20.
    #[props(default)]
    pub decimals: u32,
    /// Count length; uses the token's default milliseconds.
    #[props(default)]
    pub duration: MotionDuration,
    /// The value the count starts from.
    #[props(default, into)]
    pub from: f64,
    /// BCP 47 locale for separators, such as `de-DE`. Defaults to en-US.
    #[props(into)]
    pub locale: Option<String>,
    /// Text before the number, such as a currency symbol.
    #[props(default, into)]
    pub prefix: String,
    /// Text after the number, such as a unit.
    #[props(default, into)]
    pub suffix: String,
    /// 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>,
}

/// A number that counts from `from` to `value` when it scrolls into view. Assistive technology
/// reads the final value once.
///
/// The first render shows the final value. On the web and desktop it resets to `from` after mount
/// and counts up on its first `onvisible` event; under reduced motion, and on Dioxus Native, which
/// has no visibility events, it keeps the final value, like lumen-react without
/// `IntersectionObserver`.
#[component]
pub fn AnimatedNumber(props: AnimatedNumberProps) -> Element {
    let support = use_motion_support();
    let mut display = use_signal(|| None::<f64>);
    let mut in_view = use_hook(|| CopyValue::new(false));
    let mut pending = use_hook(|| CopyValue::new(false));
    let mut task = use_hook(|| CopyValue::new(None::<Task>));
    let animates = support().observes();
    let value = props.value;
    let from = props.from;
    let duration = props.duration;
    let value_bits = dependency_bits(value);
    let from_bits = dependency_bits(from);

    // The numbers go in as bits: `use_reactive!` compares with `!=`, and `NaN != NaN` would re-run
    // the effect, and so re-render, forever.
    use_effect(use_reactive!(|value_bits,
                              from_bits,
                              duration,
                              animates| {
        let value = f64::from_bits(value_bits);
        let from = f64::from_bits(from_bits);

        if let Some(previous) = task.write().take() {
            previous.cancel();
        }

        if !animates {
            pending.set(false);
            display.set(None);
            return;
        }

        display.set(Some(from));
        pending.set(true);

        if *in_view.peek() {
            count_up(display, task, pending, (from, value), duration);
        }
    }));

    let format = |number: f64| {
        format!(
            "{}{}{}",
            props.prefix,
            format_number(number, props.decimals, props.locale.as_deref()),
            props.suffix
        )
    };
    let final_text = format(value);
    let shown = display().map_or_else(|| final_text.clone(), format);
    let duration_class = duration.class();
    let class = compose([
        Some("ui-animated-number"),
        Some(duration_class.as_str()),
        props.class.as_deref(),
    ]);

    rsx! {
        span {
            class,
            "data-ui-animated-number": "true",
            onvisible: move |event| {
                let visible = event.is_intersecting().unwrap_or(false);
                in_view.set(visible);

                if visible && *pending.peek() {
                    count_up(display, task, pending, (from, value), duration);
                }
            },
            ..props.attributes,
            span { aria_hidden: "true", "data-ui-animated-number-output": "true", {shown} }
            span { class: "ui-sr-only", {final_text} }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{dependency_bits, ease_out, format_number};

    #[test]
    fn dependency_bits_treat_every_nan_as_unchanged() {
        assert_eq!(dependency_bits(f64::NAN), dependency_bits(-f64::NAN));
        assert_eq!(
            dependency_bits(f64::NAN),
            dependency_bits(f64::from_bits(0x7ff8_0000_0000_0001))
        );
        assert!(f64::from_bits(dependency_bits(f64::NAN)).is_nan());
        assert_eq!(
            f64::from_bits(dependency_bits(12.5)).to_bits(),
            12.5_f64.to_bits()
        );
        // Like `Object.is`, the two zeros differ.
        assert_ne!(dependency_bits(0.0), dependency_bits(-0.0));
    }

    #[test]
    fn default_locale_matches_intl_en_us() {
        assert_eq!(format_number(1_234_567.125, 2, None), "1,234,567.13");
        assert_eq!(format_number(2.5, 0, None), "3");
        assert_eq!(format_number(-2.5, 0, None), "-3");
        assert_eq!(format_number(1.005, 2, None), "1.01");
        assert_eq!(format_number(999.999, 2, None), "1,000.00");
        assert_eq!(format_number(0.1, 20, None), "0.10000000000000000000");
        assert_eq!(format_number(42.0, 0, None), "42");
        assert_eq!(format_number(7.0, 3, None), "7.000");
    }

    #[test]
    fn signs_and_special_values_match_intl() {
        assert_eq!(format_number(-0.0, 0, None), "-0");
        assert_eq!(format_number(-0.4, 0, None), "-0");
        assert_eq!(format_number(f64::NAN, 2, None), "NaN");
        assert_eq!(format_number(f64::INFINITY, 0, None), "\u{221e}");
        assert_eq!(format_number(f64::NEG_INFINITY, 0, None), "-\u{221e}");
        assert_eq!(
            format_number(1e21, 0, None),
            "1,000,000,000,000,000,000,000"
        );
    }

    #[test]
    fn locales_use_their_separators() {
        assert_eq!(format_number(1_234_567.5, 2, Some("de-DE")), "1.234.567,50");
        assert_eq!(
            format_number(1_234_567.5, 2, Some("fr-FR")),
            "1\u{202f}234\u{202f}567,50"
        );
        assert_eq!(format_number(1234.0, 0, Some("es-ES")), "1234");
        assert_eq!(format_number(12345.0, 0, Some("es")), "12.345");
        assert_eq!(format_number(12_345_678.0, 0, Some("en-IN")), "1,23,45,678");
        assert_eq!(format_number(1_234_567.5, 2, Some("de-CH")), "1'234'567.50");
        assert_eq!(format_number(-1.0, 0, Some("sv")), "\u{2212}1");
        assert_eq!(format_number(1234.0, 0, Some("EN_us")), "1,234");
        assert_eq!(format_number(1234.0, 0, Some("not a locale")), "1,234");
    }

    #[test]
    fn decimals_clamp_to_twenty() {
        assert_eq!(format_number(1.0, 99, None).len(), "1.".len() + 20);
    }

    #[test]
    fn easing_reaches_both_ends() {
        assert!(ease_out(0.0).abs() < f64::EPSILON);
        assert!((ease_out(1.0) - 1.0).abs() < f64::EPSILON);
        assert!(ease_out(0.5) > 0.5);
    }

    #[test]
    fn long_locales_parse_linearly() {
        let locale = "-".repeat(100_000);
        assert_eq!(format_number(1234.0, 0, Some(&locale)), "1,234");
    }
}