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
//! Locale number symbols and Unicode decimal digits shared by `NumberField`, `AmountField`, and
//! `InputOTP`.
//!
//! lumen-core reads separators from `Intl.NumberFormat`. Rust has no Intl, so this module keeps a
//! small table of the separators, minus signs, digit sets, and grouping patterns that
//! `Intl.NumberFormat` (ICU 76, Node 22) produces for common locales. Tags resolve by exact
//! `language-REGION` match, then by language, then to `en-US`. Unicode extension keys such as
//! `-u-nu-hanidec` are ignored, so a numbering-system override keeps the locale's default digits.

// cspell:words FEFF

/// Inclusive code point ranges of Unicode decimal digits (general category `Nd`, Unicode 17.0).
/// Every range holds whole `0`-`9` runs, so a digit's value is its offset modulo 10.
const DECIMAL_DIGIT_RANGES: &[(u32, u32)] = &[
    (0x30, 0x39),
    (0x660, 0x669),
    (0x6F0, 0x6F9),
    (0x7C0, 0x7C9),
    (0x966, 0x96F),
    (0x9E6, 0x9EF),
    (0xA66, 0xA6F),
    (0xAE6, 0xAEF),
    (0xB66, 0xB6F),
    (0xBE6, 0xBEF),
    (0xC66, 0xC6F),
    (0xCE6, 0xCEF),
    (0xD66, 0xD6F),
    (0xDE6, 0xDEF),
    (0xE50, 0xE59),
    (0xED0, 0xED9),
    (0xF20, 0xF29),
    (0x1040, 0x1049),
    (0x1090, 0x1099),
    (0x17E0, 0x17E9),
    (0x1810, 0x1819),
    (0x1946, 0x194F),
    (0x19D0, 0x19D9),
    (0x1A80, 0x1A89),
    (0x1A90, 0x1A99),
    (0x1B50, 0x1B59),
    (0x1BB0, 0x1BB9),
    (0x1C40, 0x1C49),
    (0x1C50, 0x1C59),
    (0xA620, 0xA629),
    (0xA8D0, 0xA8D9),
    (0xA900, 0xA909),
    (0xA9D0, 0xA9D9),
    (0xA9F0, 0xA9F9),
    (0xAA50, 0xAA59),
    (0xABF0, 0xABF9),
    (0xFF10, 0xFF19),
    (0x104A0, 0x104A9),
    (0x10D30, 0x10D39),
    (0x10D40, 0x10D49),
    (0x11066, 0x1106F),
    (0x110F0, 0x110F9),
    (0x11136, 0x1113F),
    (0x111D0, 0x111D9),
    (0x112F0, 0x112F9),
    (0x11450, 0x11459),
    (0x114D0, 0x114D9),
    (0x11650, 0x11659),
    (0x116C0, 0x116C9),
    (0x116D0, 0x116E3),
    (0x11730, 0x11739),
    (0x118E0, 0x118E9),
    (0x11950, 0x11959),
    (0x11BF0, 0x11BF9),
    (0x11C50, 0x11C59),
    (0x11D50, 0x11D59),
    (0x11DA0, 0x11DA9),
    (0x11DE0, 0x11DE9),
    (0x11F50, 0x11F59),
    (0x16130, 0x16139),
    (0x16A60, 0x16A69),
    (0x16AC0, 0x16AC9),
    (0x16B50, 0x16B59),
    (0x16D70, 0x16D79),
    (0x1CCF0, 0x1CCF9),
    (0x1D7CE, 0x1D7FF),
    (0x1E140, 0x1E149),
    (0x1E2F0, 0x1E2F9),
    (0x1E4F0, 0x1E4F9),
    (0x1E5F1, 0x1E5FA),
    (0x1E950, 0x1E959),
    (0x1FBF0, 0x1FBF9),
];

/// The value of a Unicode decimal digit in any script, like `numericDigit` in lumen-core.
pub(crate) fn numeric_digit(character: char) -> Option<u8> {
    let code = u32::from(character);
    let index = DECIMAL_DIGIT_RANGES.partition_point(|&(start, _)| start <= code);
    let (start, end) = *DECIMAL_DIGIT_RANGES.get(index.checked_sub(1)?)?;

    if code > end {
        return None;
    }

    u8::try_from((code - start) % 10).ok()
}

/// Whether a character is white space for JavaScript's `\s` and `String.prototype.trim`.
pub(crate) fn is_js_whitespace(character: char) -> bool {
    matches!(
        character,
        '\u{9}'..='\u{d}'
            | ' '
            | '\u{a0}'
            | '\u{1680}'
            | '\u{2000}'..='\u{200a}'
            | '\u{2028}'
            | '\u{2029}'
            | '\u{202f}'
            | '\u{205f}'
            | '\u{3000}'
            | '\u{FEFF}'
    )
}

/// `String.prototype.trim` with JavaScript's white space set.
pub(crate) fn js_trim(value: &str) -> &str {
    value.trim_matches(is_js_whitespace)
}

/// Whether a character is one of the bidirectional marks that `Intl.NumberFormat` inserts around
/// signs in right-to-left locales (ALM, LRM, RLM).
pub(crate) fn is_direction_mark(character: char) -> bool {
    matches!(character, '\u{61c}' | '\u{200e}' | '\u{200f}')
}

/// The length of a string in UTF-16 code units, like JavaScript's `length`, counted up to `limit`
/// so adversarial input stops early. Returns `limit + 1` when the string is longer.
pub(crate) fn utf16_len_capped(value: &str, limit: usize) -> usize {
    let mut length = 0;

    for character in value.chars() {
        length += character.len_utf16();

        if length > limit {
            return limit + 1;
        }
    }

    length
}

/// How a locale groups integer digits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Grouping {
    /// Groups of three: `1,234,567`.
    Thousands,
    /// The last three digits, then groups of two: `12,34,567` (Indian numbering).
    Indian,
}

/// Number symbols of one locale.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LocaleSymbols {
    /// Decimal separator.
    pub decimal: char,
    /// Group separator.
    pub group: char,
    /// The `minusSign` part `Intl.NumberFormat` uses (direction marks are separate literal parts).
    pub minus: char,
    /// The locale's digit zero; the other digits follow it.
    pub zero: char,
    /// Integer grouping pattern.
    pub grouping: Grouping,
}

impl LocaleSymbols {
    /// The localized digit for `0..=9`.
    pub(crate) fn digit(&self, value: u8) -> char {
        char::from_u32(u32::from(self.zero) + u32::from(value.min(9))).unwrap_or('0')
    }

    /// The value of a localized digit of this locale.
    pub(crate) fn localized_digit(&self, character: char) -> Option<u8> {
        let offset = u32::from(character).checked_sub(u32::from(self.zero))?;

        (offset < 10).then(|| u8::try_from(offset).unwrap_or(0))
    }

    /// Converts an ASCII digit string to the locale's digits.
    pub(crate) fn localize_digits(&self, ascii: &str) -> String {
        ascii
            .chars()
            .map(|character| {
                character
                    .to_digit(10)
                    .and_then(|digit| u8::try_from(digit).ok())
                    .map_or(character, |digit| self.digit(digit))
            })
            .collect()
    }

    /// Groups an ASCII integer (no sign) with the locale's separator and digits, like
    /// `Intl.NumberFormat(locale, { useGrouping: true }).format(BigInt(integer))`: leading zeros
    /// are dropped and every group is separated, even for four-digit numbers.
    pub(crate) fn group_integer(&self, integer: &str) -> String {
        let trimmed = integer.trim_start_matches('0');
        let digits: Vec<char> = if trimmed.is_empty() {
            vec!['0']
        } else {
            trimmed.chars().collect()
        };
        let length = digits.len();
        let mut out = String::with_capacity(length * 2);

        for (index, digit) in digits.iter().enumerate() {
            let remaining = length - index;

            if index > 0 && self.separates_before(remaining) {
                out.push(self.group);
            }

            let value = digit
                .to_digit(10)
                .and_then(|value| u8::try_from(value).ok())
                .unwrap_or(0);
            out.push(self.digit(value));
        }

        out
    }

    /// Whether a group separator precedes a digit that has `remaining` digits from it to the end.
    fn separates_before(&self, remaining: usize) -> bool {
        match self.grouping {
            Grouping::Thousands => remaining.is_multiple_of(3),
            Grouping::Indian => {
                remaining == 3 || (remaining > 3 && (remaining - 3).is_multiple_of(2))
            }
        }
    }
}

const EN: LocaleSymbols = LocaleSymbols {
    decimal: '.',
    group: ',',
    minus: '-',
    zero: '0',
    grouping: Grouping::Thousands,
};
const EN_INDIAN: LocaleSymbols = LocaleSymbols {
    grouping: Grouping::Indian,
    ..EN
};
const COMMA_DOT: LocaleSymbols = LocaleSymbols {
    decimal: ',',
    group: '.',
    ..EN
};
const COMMA_DOT_MINUS: LocaleSymbols = LocaleSymbols {
    minus: '\u{2212}',
    ..COMMA_DOT
};
const COMMA_NBSP: LocaleSymbols = LocaleSymbols {
    decimal: ',',
    group: '\u{a0}',
    ..EN
};
const COMMA_NBSP_MINUS: LocaleSymbols = LocaleSymbols {
    minus: '\u{2212}',
    ..COMMA_NBSP
};
const COMMA_NARROW_NBSP: LocaleSymbols = LocaleSymbols {
    decimal: ',',
    group: '\u{202f}',
    ..EN
};
const COMMA_APOSTROPHE: LocaleSymbols = LocaleSymbols {
    decimal: ',',
    group: '\'',
    ..EN
};
const DOT_APOSTROPHE: LocaleSymbols = LocaleSymbols { group: '\'', ..EN };
const ARABIC_INDIC: LocaleSymbols = LocaleSymbols {
    decimal: '\u{66b}',
    group: '\u{66c}',
    minus: '-',
    zero: '\u{660}',
    grouping: Grouping::Thousands,
};
const PERSIAN: LocaleSymbols = LocaleSymbols {
    minus: '\u{2212}',
    zero: '\u{6f0}',
    ..ARABIC_INDIC
};
const BENGALI: LocaleSymbols = LocaleSymbols {
    zero: '\u{9e6}',
    ..EN_INDIAN
};

/// `language-region` overrides, checked before [`LANGUAGES`].
const REGIONS: &[(&str, LocaleSymbols)] = &[
    ("ar-ae", EN),
    ("ar-dz", COMMA_DOT),
    ("ar-eg", ARABIC_INDIC),
    ("ar-iq", ARABIC_INDIC),
    ("ar-ma", COMMA_DOT),
    ("ar-sa", ARABIC_INDIC),
    ("ar-tn", COMMA_DOT),
    ("de-at", COMMA_NBSP),
    ("de-ch", DOT_APOSTROPHE),
    ("en-in", EN_INDIAN),
    ("es-419", EN),
    ("es-mx", EN),
    ("es-us", EN),
    ("fr-ca", COMMA_NBSP),
    ("fr-ch", COMMA_APOSTROPHE),
    ("it-ch", DOT_APOSTROPHE),
    ("pt-pt", COMMA_NBSP),
];

/// Language defaults.
const LANGUAGES: &[(&str, LocaleSymbols)] = &[
    ("ar", EN),
    ("bg", COMMA_NBSP),
    ("bn", BENGALI),
    ("ca", COMMA_DOT),
    ("cs", COMMA_NBSP),
    ("da", COMMA_DOT),
    ("de", COMMA_DOT),
    ("el", COMMA_DOT),
    ("en", EN),
    ("es", COMMA_DOT),
    ("et", COMMA_NBSP_MINUS),
    ("fa", PERSIAN),
    ("fi", COMMA_NBSP_MINUS),
    ("fr", COMMA_NARROW_NBSP),
    ("he", EN),
    ("hi", EN_INDIAN),
    ("hr", COMMA_DOT_MINUS),
    ("hu", COMMA_NBSP),
    ("id", COMMA_DOT),
    ("it", COMMA_DOT),
    ("ja", EN),
    ("ko", EN),
    ("lt", COMMA_NBSP_MINUS),
    ("lv", COMMA_NBSP),
    ("ms", EN),
    ("nb", COMMA_NBSP_MINUS),
    ("nl", COMMA_DOT),
    ("no", COMMA_NBSP_MINUS),
    ("pl", COMMA_NBSP),
    ("pt", COMMA_DOT),
    ("ro", COMMA_DOT),
    ("ru", COMMA_NBSP),
    ("sk", COMMA_NBSP),
    ("sl", COMMA_DOT_MINUS),
    ("sr", COMMA_DOT),
    ("sv", COMMA_NBSP_MINUS),
    ("th", EN),
    ("tr", COMMA_DOT),
    ("uk", COMMA_NBSP),
    ("ur", EN),
    ("vi", COMMA_DOT),
    ("zh", EN),
];

fn lookup(table: &[(&str, LocaleSymbols)], key: &str) -> Option<LocaleSymbols> {
    table
        .iter()
        .find(|(tag, _)| *tag == key)
        .map(|(_, symbols)| *symbols)
}

/// The number symbols of a BCP 47 locale tag, falling back to `en-US` for unknown or malformed
/// tags (lumen-core falls back the same way when `Intl.NumberFormat` rejects a tag).
pub(crate) fn locale_symbols(locale: &str) -> LocaleSymbols {
    let tag = locale.trim();

    if tag.is_empty()
        || tag.len() > 64
        || !tag
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || character == '-')
    {
        return EN;
    }

    let lower = tag.to_ascii_lowercase();
    let mut parts = lower.split('-');
    let language = parts.next().unwrap_or_default();

    if language.is_empty() {
        return EN;
    }

    // The first two-letter or three-digit part after the language is the region; scripts and
    // variants are skipped, and extensions (`-u-`, `-x-`) end the scan.
    let region = parts.take_while(|part| part.len() > 1).find(|part| {
        (part.len() == 2 && part.chars().all(|c| c.is_ascii_alphabetic()))
            || (part.len() == 3 && part.chars().all(|c| c.is_ascii_digit()))
    });

    region
        .and_then(|region| lookup(REGIONS, &format!("{language}-{region}")))
        .or_else(|| lookup(LANGUAGES, language))
        .unwrap_or(EN)
}

#[cfg(test)]
mod tests {
    use super::{
        Grouping, is_js_whitespace, js_trim, locale_symbols, numeric_digit, utf16_len_capped,
    };

    #[test]
    fn decimal_digits_resolve_in_every_script() {
        assert_eq!(numeric_digit('7'), Some(7));
        assert_eq!(numeric_digit('\u{663}'), Some(3));
        assert_eq!(numeric_digit('\u{ff15}'), Some(5));
        assert_eq!(numeric_digit('\u{1d7ff}'), Some(9));
        assert_eq!(numeric_digit('\u{1d7d8}'), Some(0));
        assert_eq!(numeric_digit('a'), None);
        assert_eq!(numeric_digit('\u{216b}'), None);
        assert_eq!(numeric_digit('\u{4e00}'), None);
    }

    #[test]
    fn locales_resolve_by_region_then_language_then_english() {
        assert_eq!(locale_symbols("es-CO").decimal, ',');
        assert_eq!(locale_symbols("es-MX").decimal, '.');
        assert_eq!(locale_symbols("de-CH").group, '\'');
        assert_eq!(locale_symbols("zh-Hant-TW").decimal, '.');
        assert_eq!(locale_symbols("ar-EG").zero, '\u{660}');
        assert_eq!(locale_symbols("en-IN").grouping, Grouping::Indian);
        assert_eq!(locale_symbols("sv-SE").minus, '\u{2212}');
        assert_eq!(locale_symbols("en-US-u-nu-hanidec").zero, '0');

        for malformed in ["", "en_US", "en--US", "\u{1f4a5}", "-", "xx"] {
            assert_eq!(
                locale_symbols(malformed),
                locale_symbols("en-US"),
                "{malformed}"
            );
        }
    }

    #[test]
    fn grouping_follows_intl_patterns() {
        assert_eq!(
            locale_symbols("en-US").group_integer("1234567"),
            "1,234,567"
        );
        assert_eq!(locale_symbols("en-US").group_integer("0012"), "12");
        assert_eq!(locale_symbols("en-US").group_integer("000"), "0");
        assert_eq!(
            locale_symbols("hi-IN").group_integer("1234567890"),
            "1,23,45,67,890"
        );
        assert_eq!(locale_symbols("es-CO").group_integer("1234"), "1.234");
        assert_eq!(
            locale_symbols("ar-EG").group_integer("1234"),
            "\u{661}\u{66c}\u{662}\u{663}\u{664}"
        );
    }

    #[test]
    fn javascript_white_space_and_lengths() {
        assert!(is_js_whitespace('\u{FEFF}'));
        assert!(!is_js_whitespace('\u{85}'));
        assert_eq!(js_trim("\u{a0} 12 \n"), "12");
        assert_eq!(utf16_len_capped("\u{1f4a5}a", 10), 3);
        assert_eq!(utf16_len_capped(&"9".repeat(100_000), 128), 129);
    }
}