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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Exact decimal drafts for `NumberField`: parsing, bounds, and stepping without floating point.
//!
//! A port of `parseLumenDecimalDraft`, `isLumenDecimalInBounds`, and `stepLumenDecimalDraft`
//! from `@santi020k/lumen-core/native-input`. Coefficients are digit strings instead of `BigInt`,
//! so arithmetic stays exact far beyond `f64` precision.

use std::cmp::Ordering;
use std::fmt;

use super::number_field_locale::{
    LocaleSymbols, is_direction_mark, locale_symbols, numeric_digit, utf16_len_capped,
};

/// The longest draft (in UTF-16 code units, like JavaScript's `length`) that is parsed.
const DRAFT_LIMIT: usize = 128;

/// An exact, ungrouped decimal number: a coefficient and a scale (`coefficient / 10^scale`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NumberFieldDecimal {
    negative: bool,
    /// Magnitude digits without leading zeros (`"0"` for zero).
    digits: String,
    scale: usize,
}

impl NumberFieldDecimal {
    fn new(negative: bool, digits: &str, scale: usize) -> Self {
        let trimmed = digits.trim_start_matches('0');
        let digits = if trimmed.is_empty() { "0" } else { trimmed };

        Self {
            negative: negative && digits != "0",
            digits: digits.to_string(),
            scale,
        }
    }

    fn zero() -> Self {
        Self::new(false, "0", 0)
    }

    /// The signed integer coefficient as ASCII digits, such as `"-123"` for `-12.3`.
    pub fn coefficient(&self) -> String {
        if self.negative {
            format!("-{}", self.digits)
        } else {
            self.digits.clone()
        }
    }

    /// How many coefficient digits are fractional.
    pub fn scale(&self) -> usize {
        self.scale
    }

    /// Whether the number is below zero.
    pub fn is_negative(&self) -> bool {
        self.negative
    }

    /// The magnitude digits padded with zeros to `scale`.
    fn digits_at(&self, scale: usize) -> String {
        let mut digits = self.digits.clone();

        if self.digits != "0" {
            digits.extend(std::iter::repeat_n('0', scale.saturating_sub(self.scale)));
        }

        digits
    }

    /// Formats the number with a locale's digits, dropping trailing fraction zeros.
    fn format(&self, symbols: &LocaleSymbols) -> String {
        let digits = format!("{:0>width$}", self.digits, width = self.scale + 1);
        let split = digits.len() - self.scale;
        let (integer, fraction) = digits.split_at(split);
        let fraction = fraction.trim_end_matches('0');
        let mut out = String::new();

        if self.negative {
            out.push(symbols.minus);
        }

        out.push_str(&symbols.localize_digits(integer));

        if !fraction.is_empty() {
            out.push(symbols.decimal);
            out.push_str(&symbols.localize_digits(fraction));
        }

        out
    }
}

impl fmt::Display for NumberFieldDecimal {
    /// The plain ASCII form, such as `-12.30`.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let digits = format!("{:0>width$}", self.digits, width = self.scale + 1);
        let (integer, fraction) = digits.split_at(digits.len() - self.scale);
        let sign = if self.negative { "-" } else { "" };

        if fraction.is_empty() {
            write!(formatter, "{sign}{integer}")
        } else {
            write!(formatter, "{sign}{integer}.{fraction}")
        }
    }
}

/// A parsed `NumberField` draft, like lumen-core's `LumenDecimalDraft`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum NumberFieldDraft {
    /// Nothing typed.
    Empty,
    /// A draft that can still become a number, such as `-`, `.`, or `12.`.
    Incomplete,
    /// Text that is not an ungrouped decimal in the locale.
    Invalid,
    /// A complete decimal.
    Valid(NumberFieldDecimal),
}

/// Bounds, step, and locale for [`number_field_in_bounds`] and [`number_field_step_draft`], like
/// lumen-core's `LumenDecimalOptions`.
///
/// `min`, `max`, and `step` are complete, ungrouped ASCII decimals such as `"0.25"`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NumberFieldOptions {
    /// Locale of the draft's digits and separators; `en-US` when unset.
    pub locale: Option<String>,
    /// Inclusive lower bound.
    pub min: Option<String>,
    /// Inclusive upper bound.
    pub max: Option<String>,
    /// Step size; `1` when unset. Must be positive.
    pub step: Option<String>,
}

/// Why a [`NumberFieldOptions`] configuration was rejected (lumen-core throws a `RangeError`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum NumberFieldError {
    /// `min`, `max`, or `step` is not a complete ungrouped ASCII decimal of at most 128 characters.
    InvalidConfiguration,
    /// `step` is zero or negative.
    NonPositiveStep,
    /// `min` is greater than `max`.
    MinAboveMax,
}

impl fmt::Display for NumberFieldError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::InvalidConfiguration => {
                "Decimal configuration must be a complete ungrouped ASCII decimal of at most 128 characters."
            }
            Self::NonPositiveStep => "Decimal step must be positive.",
            Self::MinAboveMax => "Decimal minimum must not exceed maximum.",
        })
    }
}

impl std::error::Error for NumberFieldError {}

/// Which way [`number_field_step_draft`] moves.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NumberFieldStepDirection {
    /// Add one step (`ArrowUp`).
    Up,
    /// Subtract one step (`ArrowDown`).
    Down,
}

/// Decimal separator, minus sign, and digits of the ungrouped `Intl.NumberFormat` of a locale.
fn decimal_symbols(locale: Option<&str>) -> LocaleSymbols {
    locale_symbols(locale.unwrap_or("en-US"))
}

/// Parses a draft in a locale's digits and decimal separator. Grouping, exponents, white space,
/// and drafts over 128 UTF-16 code units are invalid. Like `parseLumenDecimalDraft`.
pub fn number_field_parse_draft(value: &str, locale: Option<&str>) -> NumberFieldDraft {
    if value.is_empty() {
        return NumberFieldDraft::Empty;
    }

    if utf16_len_capped(value, DRAFT_LIMIT) > DRAFT_LIMIT {
        return NumberFieldDraft::Invalid;
    }

    let normalized: String = value.chars().filter(|c| !is_direction_mark(*c)).collect();

    if normalized.is_empty() {
        return NumberFieldDraft::Invalid;
    }

    let symbols = decimal_symbols(locale);
    let (negative, unsigned) = match normalized.strip_prefix(symbols.minus) {
        Some(rest) => (true, rest),
        None => match normalized.strip_prefix('-') {
            Some(rest) => (true, rest),
            None => (false, normalized.as_str()),
        },
    };
    let mut digits = String::new();
    let mut decimal_seen = false;
    let mut scale = 0;

    for character in unsigned.chars() {
        let digit = symbols
            .localized_digit(character)
            .or_else(|| numeric_digit(character));

        if let Some(digit) = digit {
            digits.push(char::from(b'0' + digit));

            if decimal_seen {
                scale += 1;
            }
        } else if character == symbols.decimal && !decimal_seen {
            decimal_seen = true;
        } else {
            return NumberFieldDraft::Invalid;
        }
    }

    if digits.is_empty() || unsigned.ends_with(symbols.decimal) {
        return NumberFieldDraft::Incomplete;
    }

    NumberFieldDraft::Valid(NumberFieldDecimal::new(negative, &digits, scale))
}

fn parse_configuration(
    value: Option<&str>,
) -> Result<Option<NumberFieldDecimal>, NumberFieldError> {
    let Some(value) = value else {
        return Ok(None);
    };

    if !value
        .chars()
        .all(|character| character.is_ascii_digit() || character == '.' || character == '-')
    {
        return Err(NumberFieldError::InvalidConfiguration);
    }

    match number_field_parse_draft(value, Some("en-US")) {
        NumberFieldDraft::Valid(decimal) => Ok(Some(decimal)),
        _ => Err(NumberFieldError::InvalidConfiguration),
    }
}

/// Compares two magnitudes given as ASCII digit strings without leading zeros.
fn compare_magnitudes(left: &str, right: &str) -> Ordering {
    left.len().cmp(&right.len()).then_with(|| left.cmp(right))
}

fn compare_decimals(left: &NumberFieldDecimal, right: &NumberFieldDecimal) -> Ordering {
    match (left.negative, right.negative) {
        (true, false) => Ordering::Less,
        (false, true) => Ordering::Greater,
        (negative, _) => {
            let scale = left.scale.max(right.scale);
            let magnitude = compare_magnitudes(
                strip_zeros(&left.digits_at(scale)),
                strip_zeros(&right.digits_at(scale)),
            );

            if negative {
                magnitude.reverse()
            } else {
                magnitude
            }
        }
    }
}

fn strip_zeros(digits: &str) -> &str {
    let trimmed = digits.trim_start_matches('0');

    if trimmed.is_empty() { "0" } else { trimmed }
}

/// Adds two magnitudes of ASCII digits.
fn add_magnitudes(left: &str, right: &str) -> String {
    let (left, right) = (left.as_bytes(), right.as_bytes());
    let mut out = Vec::with_capacity(left.len().max(right.len()) + 1);
    let mut carry = 0;
    let (mut i, mut j) = (left.len(), right.len());

    while i > 0 || j > 0 || carry > 0 {
        let a = if i > 0 {
            i -= 1;
            left[i] - b'0'
        } else {
            0
        };
        let b = if j > 0 {
            j -= 1;
            right[j] - b'0'
        } else {
            0
        };
        let sum = a + b + carry;
        out.push(b'0' + sum % 10);
        carry = sum / 10;
    }

    out.reverse();
    String::from_utf8(out).unwrap_or_default()
}

/// Subtracts the smaller magnitude `right` from `left` (`left >= right`).
fn subtract_magnitudes(left: &str, right: &str) -> String {
    let (left, right) = (left.as_bytes(), right.as_bytes());
    let mut out = Vec::with_capacity(left.len());
    let mut borrow = 0;
    let (mut i, mut j) = (left.len(), right.len());

    while i > 0 {
        i -= 1;
        let a = i16::from(left[i] - b'0');
        let b = if j > 0 {
            j -= 1;
            i16::from(right[j] - b'0')
        } else {
            0
        };
        let mut difference = a - b - borrow;

        if difference < 0 {
            difference += 10;
            borrow = 1;
        } else {
            borrow = 0;
        }

        out.push(b'0' + u8::try_from(difference).unwrap_or(0));
    }

    out.reverse();
    String::from_utf8(out).unwrap_or_default()
}

/// `left + right` for signed decimals.
fn add_decimals(left: &NumberFieldDecimal, right: &NumberFieldDecimal) -> NumberFieldDecimal {
    let scale = left.scale.max(right.scale);
    let a = left.digits_at(scale);
    let b = right.digits_at(scale);
    let (a, b) = (strip_zeros(&a), strip_zeros(&b));

    if left.negative == right.negative {
        return NumberFieldDecimal::new(left.negative, &add_magnitudes(a, b), scale);
    }

    match compare_magnitudes(a, b) {
        Ordering::Less => {
            NumberFieldDecimal::new(right.negative, &subtract_magnitudes(b, a), scale)
        }
        _ => NumberFieldDecimal::new(left.negative, &subtract_magnitudes(a, b), scale),
    }
}

struct Configuration {
    min: Option<NumberFieldDecimal>,
    max: Option<NumberFieldDecimal>,
    step: NumberFieldDecimal,
}

fn decimal_configuration(options: &NumberFieldOptions) -> Result<Configuration, NumberFieldError> {
    let min = parse_configuration(options.min.as_deref())?;
    let max = parse_configuration(options.max.as_deref())?;
    let step = parse_configuration(Some(options.step.as_deref().unwrap_or("1")))?
        .ok_or(NumberFieldError::InvalidConfiguration)?;

    if step.negative || step.digits == "0" {
        return Err(NumberFieldError::NonPositiveStep);
    }

    if let (Some(min), Some(max)) = (&min, &max)
        && compare_decimals(min, max) == Ordering::Greater
    {
        return Err(NumberFieldError::MinAboveMax);
    }

    Ok(Configuration { min, max, step })
}

/// Whether a draft is a complete number inside the inclusive bounds, like
/// `isLumenDecimalInBounds`.
///
/// # Errors
///
/// Returns a [`NumberFieldError`] when the bounds or step are not valid decimals.
pub fn number_field_in_bounds(
    value: &str,
    options: &NumberFieldOptions,
) -> Result<bool, NumberFieldError> {
    let configuration = decimal_configuration(options)?;
    let NumberFieldDraft::Valid(draft) = number_field_parse_draft(value, options.locale.as_deref())
    else {
        return Ok(false);
    };

    Ok(configuration
        .min
        .as_ref()
        .is_none_or(|min| compare_decimals(&draft, min) != Ordering::Less)
        && configuration
            .max
            .as_ref()
            .is_none_or(|max| compare_decimals(&draft, max) != Ordering::Greater))
}

/// Adds or subtracts one step from a draft and clamps it to the inclusive bounds, like
/// `stepLumenDecimalDraft`. An empty draft starts from `min`, a negative `max`, or zero.
///
/// Returns `Ok(None)` for incomplete or invalid drafts and for results longer than 128 UTF-16
/// code units. The result uses the locale's digits and decimal separator, without trailing
/// fraction zeros.
///
/// # Errors
///
/// Returns a [`NumberFieldError`] when the bounds or step are not valid decimals.
pub fn number_field_step_draft(
    value: &str,
    direction: NumberFieldStepDirection,
    options: &NumberFieldOptions,
) -> Result<Option<String>, NumberFieldError> {
    let Configuration { min, max, step } = decimal_configuration(options)?;
    let start = match number_field_parse_draft(value, options.locale.as_deref()) {
        NumberFieldDraft::Valid(draft) => draft,
        NumberFieldDraft::Empty => match (&min, &max) {
            (Some(min), _) => min.clone(),
            (None, Some(max)) if max.negative => max.clone(),
            _ => NumberFieldDecimal::zero(),
        },
        NumberFieldDraft::Incomplete | NumberFieldDraft::Invalid => return Ok(None),
    };
    let delta = NumberFieldDecimal {
        negative: direction == NumberFieldStepDirection::Down,
        ..step
    };
    let mut result = add_decimals(&start, &delta);

    if let Some(min) = &min
        && compare_decimals(&result, min) == Ordering::Less
    {
        result = min.clone();
    }

    if let Some(max) = &max
        && compare_decimals(&result, max) == Ordering::Greater
    {
        result = max.clone();
    }

    let formatted = result.format(&decimal_symbols(options.locale.as_deref()));

    Ok((utf16_len_capped(&formatted, DRAFT_LIMIT) <= DRAFT_LIMIT).then_some(formatted))
}

#[cfg(test)]
mod tests {
    use super::{NumberFieldDraft, add_decimals, compare_decimals, number_field_parse_draft};
    use std::cmp::Ordering;

    fn valid(value: &str) -> super::NumberFieldDecimal {
        match number_field_parse_draft(value, None) {
            NumberFieldDraft::Valid(decimal) => decimal,
            other => panic!("{value} parsed as {other:?}"),
        }
    }

    #[test]
    fn arithmetic_is_exact_across_signs_and_scales() {
        let sum = add_decimals(&valid("9007199254740993.1"), &valid("0.2"));
        assert_eq!(sum.to_string(), "9007199254740993.3");
        assert_eq!(
            add_decimals(&valid("-0.1"), &valid("0.1")).to_string(),
            "0.0"
        );
        assert_eq!(
            add_decimals(&valid("1"), &valid("-2.5")).to_string(),
            "-1.5"
        );
        assert_eq!(
            add_decimals(&valid("-1"), &valid("-2.5")).to_string(),
            "-3.5"
        );
        assert_eq!(
            compare_decimals(&valid("-2"), &valid("-1.5")),
            Ordering::Less
        );
        assert_eq!(
            compare_decimals(&valid("10.00"), &valid("10")),
            Ordering::Equal
        );
        assert_eq!(compare_decimals(&valid("-0"), &valid("0")), Ordering::Equal);
    }
}