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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! Exact amount presentation for `AmountField`: formatting, parsing, range state, and the editing
//! rules of `createLumenAmountFieldController`, ported from `@santi020k/lumen-core/amount-field`.
//!
//! Drafts are ASCII decimal strings (`-1234.50`); formatting groups them with the locale's
//! separators and digits without ever converting to a floating-point number.

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

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

/// The longest draft or source text (in UTF-16 code units) that is accepted.
const AMOUNT_LIMIT: usize = 1024;

/// Locale and precision of an amount, like lumen-core's `LumenAmountOptions`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AmountFieldOptions {
    /// BCP 47 locale of the separators and digits. Defaults to `en-US`.
    pub locale: String,
    /// Allowed fraction digits, from 0 to 20. Defaults to 2.
    pub fraction_digits: u8,
    /// Whether negative amounts are accepted. Defaults to `false`.
    pub allow_negative: bool,
}

impl Default for AmountFieldOptions {
    fn default() -> Self {
        Self {
            locale: "en-US".to_string(),
            fraction_digits: 2,
            allow_negative: false,
        }
    }
}

/// Why an amount operation failed (lumen-core throws a `RangeError`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AmountFieldError {
    /// `fraction_digits` is above 20.
    FractionDigits,
    /// The draft is not an ASCII decimal draft within the configured precision and sign.
    Draft,
    /// A `min` or `max` bound is not a complete ASCII decimal string.
    Bound,
}

impl fmt::Display for AmountFieldError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::FractionDigits => "Amount fractionDigits must be an integer from 0 to 20.",
            Self::Draft => {
                "Amount value must be an ASCII decimal draft within the configured precision."
            }
            Self::Bound => "Amount bounds must be complete ASCII decimal strings.",
        })
    }
}

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

/// Whether a complete amount is outside its bounds, like lumen-core's `LumenAmountRangeState`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AmountFieldRangeState {
    /// Below `min`.
    RangeUnderflow,
    /// Above `max`.
    RangeOverflow,
}

/// What [`AmountField`](crate::AmountField) reports after an accepted edit, like lumen-core's
/// `LumenAmountChangeDetail`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AmountFieldChange {
    /// The editable ASCII draft; intermediate `-` and trailing decimal points are kept.
    pub draft: String,
    /// The complete decimal string, or `None` for an empty or intermediate draft.
    pub value: Option<String>,
}

impl AmountFieldChange {
    /// The change detail of a draft.
    pub fn new(draft: impl Into<String>) -> Self {
        let draft = draft.into();
        let value = amount_field_value(&draft).map(str::to_string);

        Self { draft, value }
    }
}

/// Resolved separators and precision.
#[derive(Clone, Copy, Debug)]
pub(crate) struct AmountFormat {
    pub symbols: LocaleSymbols,
    pub fraction_digits: usize,
}

impl AmountFieldOptions {
    fn resolve(&self) -> Result<AmountFormat, AmountFieldError> {
        if self.fraction_digits > 20 {
            return Err(AmountFieldError::FractionDigits);
        }

        Ok(AmountFormat {
            symbols: locale_symbols(&self.locale),
            fraction_digits: usize::from(self.fraction_digits),
        })
    }

    /// Whether `draft` is an ASCII decimal draft (`""`, `-`, `12.`, `-0.5`) within the precision
    /// and sign rules.
    fn valid_draft(&self, draft: &str) -> Result<bool, AmountFieldError> {
        if utf16_len_capped(draft, AMOUNT_LIMIT) > AMOUNT_LIMIT {
            return Ok(false);
        }

        let format = self.resolve()?;

        let negative = draft.starts_with('-');

        if negative && !self.allow_negative {
            return Ok(false);
        }

        let unsigned = if negative { &draft[1..] } else { draft };
        let mut pieces = unsigned.split('.');
        let integer = pieces.next().unwrap_or_default();
        let fraction = pieces.next();

        if pieces.next().is_some() || (fraction.is_some() && format.fraction_digits == 0) {
            return Ok(false);
        }

        let fraction = fraction.unwrap_or_default();

        Ok(integer.bytes().all(|byte| byte.is_ascii_digit())
            && fraction.bytes().all(|byte| byte.is_ascii_digit())
            && fraction.len() <= format.fraction_digits)
    }

    /// Formats an ASCII draft for display, like `formatLumenAmountDraft`: the integer is grouped
    /// with the locale's separators and digits, leading integer zeros are dropped, and fraction
    /// digits (including trailing zeros) are kept exactly.
    ///
    /// # Errors
    ///
    /// [`AmountFieldError::FractionDigits`] for invalid options and [`AmountFieldError::Draft`]
    /// when the draft is not a valid draft for them.
    pub fn format_draft(&self, draft: &str) -> Result<String, AmountFieldError> {
        if !self.valid_draft(draft)? {
            return Err(AmountFieldError::Draft);
        }

        Ok(format_valid_draft(draft, &self.resolve()?.symbols))
    }

    /// Parses displayed or pasted text back to an ASCII draft, like `parseLumenAmountDraft`.
    ///
    /// Accepts the locale's digits and ASCII digits, its decimal separator, `-` or the locale's
    /// minus sign, group separators, and bidirectional marks. With `strict_grouping` (pasted
    /// text), group separators must sit exactly where the locale puts them. A leading decimal
    /// separator gains a zero (`.5` becomes `0.5`). Returns `None` for anything else, including
    /// text longer than 1024 UTF-16 code units and invalid options.
    pub fn parse_draft(&self, source: &str, strict_grouping: bool) -> Option<String> {
        if utf16_len_capped(source, AMOUNT_LIMIT) > AMOUNT_LIMIT {
            return None;
        }

        let format = self.resolve().ok()?;
        let translated = translate(source, &format.symbols)?;

        if !self.valid_draft(&translated).ok()? {
            return None;
        }

        let draft = normalize_leading_decimal(&translated);

        if strict_grouping && !self.valid_grouping(source, &draft, &format.symbols) {
            return None;
        }

        Some(draft)
    }

    fn valid_grouping(&self, source: &str, draft: &str, symbols: &LocaleSymbols) -> bool {
        if !source.contains(symbols.group) {
            return true;
        }

        let mut pieces = js_trim(source).split(symbols.decimal);
        let integer = pieces.next().unwrap_or_default();
        let fraction = pieces.next().unwrap_or_default();

        if fraction.contains(symbols.group) {
            return false;
        }

        let Ok(formatted) = self.format_draft(draft) else {
            return false;
        };
        let formatted_integer = formatted.split(symbols.decimal).next().unwrap_or_default();

        normalize_grouping_integer(integer, symbols) == formatted_integer
    }

    /// The display form of a bound in validation messages: formatted with negative amounts
    /// allowed and enough fraction digits for the bound, or the bound itself when it cannot be
    /// formatted.
    pub(crate) fn display_bound(&self, bound: &str) -> String {
        let fraction = bound.split('.').nth(1).unwrap_or_default();
        let options = Self {
            locale: self.locale.clone(),
            allow_negative: true,
            fraction_digits: self
                .fraction_digits
                .max(u8::try_from(fraction.len()).unwrap_or(u8::MAX)),
        };

        options
            .format_draft(bound)
            .unwrap_or_else(|_| bound.to_string())
    }

    pub(crate) fn symbols(&self) -> LocaleSymbols {
        locale_symbols(&self.locale)
    }
}

fn format_valid_draft(draft: &str, symbols: &LocaleSymbols) -> String {
    if draft.is_empty() {
        return String::new();
    }

    let negative = draft.starts_with('-');
    let unsigned = if negative { &draft[1..] } else { draft };
    let (integer, fraction) = match unsigned.split_once('.') {
        Some((integer, fraction)) => (integer, Some(fraction)),
        None => (unsigned, None),
    };
    let mut out = String::new();

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

    if !integer.is_empty() {
        out.push_str(&symbols.group_integer(integer));
    }

    if let Some(fraction) = fraction {
        out.push(symbols.decimal);
        out.push_str(&symbols.localize_digits(fraction));
    }

    out
}

fn normalize_leading_decimal(draft: &str) -> String {
    if let Some(rest) = draft.strip_prefix('.') {
        return format!("0.{rest}");
    }

    if let Some(rest) = draft.strip_prefix("-.") {
        return format!("-0.{rest}");
    }

    draft.to_string()
}

/// What one accepted display character contributes to the ASCII draft.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AmountChar {
    /// A digit, the decimal separator (`.`), or a minus sign (`-`).
    Draft(char),
    /// A group separator or direction mark, which the draft omits.
    Ignored,
}

/// How one displayed character maps to the ASCII draft, or `None` for characters the locale does
/// not use (lumen-core's `amountCharacters`).
pub(crate) fn translate_char(character: char, symbols: &LocaleSymbols) -> Option<AmountChar> {
    if is_direction_mark(character) || character == symbols.group {
        return Some(AmountChar::Ignored);
    }

    if character == '-' || character == symbols.minus {
        return Some(AmountChar::Draft('-'));
    }

    if character == symbols.decimal {
        return Some(AmountChar::Draft('.'));
    }

    if character.is_ascii_digit() {
        return Some(AmountChar::Draft(character));
    }

    symbols
        .localized_digit(character)
        .map(|digit| AmountChar::Draft(char::from(b'0' + digit)))
}

/// Whether a display character is part of the draft (digits, sign, decimal separator).
fn is_draft_char(character: char, symbols: &LocaleSymbols) -> bool {
    matches!(
        translate_char(character, symbols),
        Some(AmountChar::Draft(_))
    )
}

/// Translates displayed text to an unchecked ASCII draft, or `None` when it holds a character
/// the locale does not use.
pub(crate) fn translate(source: &str, symbols: &LocaleSymbols) -> Option<String> {
    let mut draft = String::new();

    for character in js_trim(source).chars() {
        if let AmountChar::Draft(ascii) = translate_char(character, symbols)? {
            draft.push(ascii);
        }
    }

    Some(draft)
}

fn normalize_grouping_integer(integer: &str, symbols: &LocaleSymbols) -> String {
    let mut normalized = String::new();

    for character in integer.chars() {
        if is_direction_mark(character) {
            continue;
        }

        if character == '-' {
            normalized.push(symbols.minus);
        } else if let Some(digit) = character.to_digit(10) {
            normalized.push(symbols.digit(u8::try_from(digit).unwrap_or(0)));
        } else {
            normalized.push(character);
        }
    }

    normalized
}

/// The submitted value of a draft, like `getLumenAmountValue`: the draft itself when it is a
/// complete decimal (`-?[0-9]+(\.[0-9]+)?`, at most 1024 characters), otherwise `None`.
pub fn amount_field_value(draft: &str) -> Option<&str> {
    if draft.len() > AMOUNT_LIMIT {
        return None;
    }

    let unsigned = draft.strip_prefix('-').unwrap_or(draft);
    let (integer, fraction) = match unsigned.split_once('.') {
        Some((integer, fraction)) => (integer, Some(fraction)),
        None => (unsigned, None),
    };
    let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());

    (digits(integer) && fraction.is_none_or(digits)).then_some(draft)
}

struct Magnitude<'a> {
    negative: bool,
    integer: &'a str,
    fraction: &'a str,
}

fn magnitude(value: &str) -> Magnitude<'_> {
    let negative = value.starts_with('-');
    let unsigned = if negative { &value[1..] } else { value };
    let (raw_integer, raw_fraction) = unsigned.split_once('.').unwrap_or((unsigned, ""));
    let mut start = 0;

    while start + 1 < raw_integer.len() && raw_integer.as_bytes()[start] == b'0' {
        start += 1;
    }

    let integer = &raw_integer[start..];
    let fraction = raw_fraction.trim_end_matches('0');

    Magnitude {
        negative: negative && (integer != "0" || !fraction.is_empty()),
        integer,
        fraction,
    }
}

/// Compares complete ASCII decimal strings exactly.
fn compare_amounts(left: &str, right: &str) -> Ordering {
    let a = magnitude(left);
    let b = magnitude(right);

    if a.negative != b.negative {
        return if a.negative {
            Ordering::Less
        } else {
            Ordering::Greater
        };
    }

    let magnitude = a
        .integer
        .len()
        .cmp(&b.integer.len())
        .then_with(|| a.integer.cmp(b.integer))
        .then_with(|| {
            let length = a.fraction.len().max(b.fraction.len());
            let left = a
                .fraction
                .bytes()
                .chain(std::iter::repeat(b'0'))
                .take(length);
            let right = b
                .fraction
                .bytes()
                .chain(std::iter::repeat(b'0'))
                .take(length);

            left.cmp(right)
        });

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

fn amount_bound(bound: Option<&str>) -> Result<Option<&str>, AmountFieldError> {
    match bound {
        None | Some("") => Ok(None),
        Some(bound) => amount_field_value(bound)
            .map(Some)
            .ok_or(AmountFieldError::Bound),
    }
}

/// The range state of a complete amount, like `getLumenAmountRangeState`. Empty and incomplete
/// drafts have no range state.
///
/// # Errors
///
/// [`AmountFieldError::Bound`] when `min` or `max` is not a complete ASCII decimal string.
pub fn amount_field_range_state(
    value: Option<&str>,
    min: Option<&str>,
    max: Option<&str>,
) -> Result<Option<AmountFieldRangeState>, AmountFieldError> {
    let min = amount_bound(min)?;
    let max = amount_bound(max)?;
    let Some(value) = value.and_then(amount_field_value) else {
        return Ok(None);
    };

    if min.is_some_and(|min| compare_amounts(value, min) == Ordering::Less) {
        return Ok(Some(AmountFieldRangeState::RangeUnderflow));
    }

    if max.is_some_and(|max| compare_amounts(value, max) == Ordering::Greater) {
        return Ok(Some(AmountFieldRangeState::RangeOverflow));
    }

    Ok(None)
}

/// How an edit changed the control, inferred from keyboard and clipboard events because Dioxus
/// form events carry no `inputType`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AmountInputKind {
    /// Typed text.
    Insert,
    /// Pasted text; group separators must be exact.
    Paste,
    /// Backspace.
    DeleteBackward,
    /// Delete.
    DeleteForward,
}

/// Validation and bounds configuration for the editor.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct AmountMessages {
    pub min: Option<String>,
    pub max: Option<String>,
    pub invalid: Option<String>,
    pub underflow: Option<String>,
    pub overflow: Option<String>,
}

/// The result of one user edit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AmountEdit {
    /// The draft after the edit (unchanged when rejected).
    pub draft: String,
    /// The text the control should show.
    pub display: String,
    /// Caret position in characters of `display`.
    pub caret: usize,
    /// Whether the edit was accepted (and a change should be reported).
    pub accepted: bool,
    /// The custom validity message for the control (empty when valid).
    pub validity: String,
}

/// Counts draft characters (digits, sign, decimal separator) before `end` in display text.
fn draft_index_before(text: &[char], end: usize, symbols: &LocaleSymbols) -> usize {
    text.iter()
        .take(end)
        .filter(|character| is_draft_char(**character, symbols))
        .count()
}

/// Follows the zero inserted before a leading decimal separator.
fn normalized_draft_index(translated: &str, index: usize) -> usize {
    if translated.starts_with('.') {
        return if index >= 1 { index + 1 } else { index };
    }

    if translated.starts_with("-.") {
        return if index >= 2 { index + 1 } else { index };
    }

    index
}

/// Converts a draft index into the significant-character index of its display, which omits
/// leading integer zeros.
fn display_index(draft: &str, index: usize) -> usize {
    let bytes = draft.as_bytes();
    let sign = usize::from(draft.starts_with('-'));
    let integer_end = draft.find('.').unwrap_or(draft.len());
    let mut zeros = 0;

    while sign + zeros + 1 < integer_end && bytes[sign + zeros] == b'0' {
        zeros += 1;
    }

    index - index.saturating_sub(sign).min(zeros)
}

/// Places a caret after `index` significant display characters.
fn display_caret(formatted: &[char], index: usize, symbols: &LocaleSymbols) -> usize {
    if index == 0 {
        return 0;
    }

    let mut seen = 0;

    for (position, character) in formatted.iter().enumerate() {
        if is_draft_char(*character, symbols) {
            seen += 1;
        }

        if seen == index {
            return position + 1;
        }
    }

    formatted.len()
}

/// Where the caret sits after an edit that turned `previous` into `raw`, and the inserted text,
/// inferred from their common prefix and suffix (exact for any single insertion or deletion).
pub(crate) fn infer_edit(previous: &str, raw: &str) -> (usize, String) {
    let before: Vec<char> = previous.chars().collect();
    let after: Vec<char> = raw.chars().collect();
    let shortest = before.len().min(after.len());
    let mut prefix = 0;

    while prefix < shortest && before[prefix] == after[prefix] {
        prefix += 1;
    }

    let mut suffix = 0;

    while suffix < shortest - prefix
        && before[before.len() - 1 - suffix] == after[after.len() - 1 - suffix]
    {
        suffix += 1;
    }

    let caret = after.len() - suffix;
    let inserted: String = after[prefix..caret].iter().collect();

    (caret, inserted)
}

/// The amount editor: the state machine behind `createLumenAmountFieldController`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AmountEditor {
    pub options: AmountFieldOptions,
    pub messages: AmountMessages,
}

impl AmountEditor {
    /// The display text of a draft, or the draft itself when it cannot be formatted.
    pub(crate) fn display(&self, draft: &str) -> String {
        self.options
            .format_draft(draft)
            .unwrap_or_else(|_| draft.to_string())
    }

    /// The validity message of a draft: incomplete amounts and range errors.
    pub(crate) fn validity(&self, draft: &str) -> String {
        let value = amount_field_value(draft);

        if !draft.is_empty() && value.is_none() {
            return self
                .messages
                .invalid
                .clone()
                .unwrap_or_else(|| "Enter a complete amount.".to_string());
        }

        let min = self.messages.min.as_deref();
        let max = self.messages.max.as_deref();
        // Invalid authored bounds are reported once by the component and ignored here.
        let state = amount_field_range_state(value, min, max).unwrap_or(None);

        match (state, min, max) {
            (Some(AmountFieldRangeState::RangeUnderflow), Some(min), _) => self
                .messages
                .underflow
                .as_deref()
                .unwrap_or("Enter an amount of at least {min}.")
                .replace("{min}", &self.options.display_bound(min)),
            (Some(AmountFieldRangeState::RangeOverflow), _, Some(max)) => self
                .messages
                .overflow
                .as_deref()
                .unwrap_or("Enter an amount of at most {max}.")
                .replace("{max}", &self.options.display_bound(max)),
            _ => String::new(),
        }
    }

    /// Applies a user edit: the control now shows `raw`, it showed `rendered` before, and the
    /// current draft is `draft`.
    pub(crate) fn edit(
        &self,
        draft: &str,
        rendered: &str,
        raw: &str,
        kind: AmountInputKind,
    ) -> AmountEdit {
        let symbols = self.options.symbols();
        let (caret, inserted) = infer_edit(rendered, raw);
        let parsed = self
            .options
            .parse_draft(raw, kind == AmountInputKind::Paste);
        let translated = translate(raw, &symbols);

        let (Some(parsed), Some(translated)) = (parsed, translated) else {
            let mut single = inserted.chars();
            let typed_decimal = kind == AmountInputKind::Insert
                && single.next() == Some(symbols.decimal)
                && single.next().is_none();
            let growth = raw.chars().count().saturating_sub(rendered.chars().count());

            return self.reject(
                draft,
                rendered,
                caret.saturating_sub(growth),
                typed_decimal,
                &symbols,
            );
        };

        let raw_chars: Vec<char> = raw.chars().collect();
        let index =
            normalized_draft_index(&translated, draft_index_before(&raw_chars, caret, &symbols));
        let deletion = if parsed == draft && raw != rendered {
            self.separator_deletion(draft, rendered, raw, kind, index)
        } else {
            None
        };
        let (next, index) = deletion.unwrap_or((parsed, index));
        let display = self.display(&next);
        let display_chars: Vec<char> = display.chars().collect();
        let caret = display_caret(&display_chars, display_index(&next, index), &symbols);
        let validity = self.validity(&next);

        AmountEdit {
            draft: next,
            display,
            caret,
            accepted: true,
            validity,
        }
    }

    /// Keeps the current draft after an edit that does not parse. `restored` is the caret shifted back by
    /// the inserted length; a repeated decimal separator instead moves past the existing one.
    fn reject(
        &self,
        draft: &str,
        rendered: &str,
        restored: usize,
        typed_decimal: bool,
        symbols: &LocaleSymbols,
    ) -> AmountEdit {
        let display = self.display(draft);
        let display_length = display.chars().count();
        let decimal_at = rendered
            .chars()
            .position(|character| character == symbols.decimal);

        if let (true, true, Some(decimal_at)) = (typed_decimal, draft.contains('.'), decimal_at) {
            return AmountEdit {
                draft: draft.to_string(),
                display,
                caret: decimal_at + 1,
                accepted: false,
                validity: self.validity(draft),
            };
        }

        AmountEdit {
            draft: draft.to_string(),
            display,
            caret: restored.min(display_length),
            accepted: false,
            validity: self.messages.invalid.clone().unwrap_or_else(|| {
                "Enter a valid amount using the displayed locale and precision.".to_string()
            }),
        }
    }

    /// Deleting only a group separator removes the adjacent digit, matching the visible intent of
    /// the keypress.
    fn separator_deletion(
        &self,
        draft: &str,
        rendered: &str,
        raw: &str,
        kind: AmountInputKind,
        index: usize,
    ) -> Option<(String, usize)> {
        let backward = kind == AmountInputKind::DeleteBackward;

        if (!backward && kind != AmountInputKind::DeleteForward)
            || raw.chars().count() >= rendered.chars().count()
        {
            return None;
        }

        let clamp = |position: usize| position.min(draft.len());
        let next = if backward {
            format!(
                "{}{}",
                &draft[..clamp(index.saturating_sub(1))],
                &draft[clamp(index)..]
            )
        } else {
            format!("{}{}", &draft[..clamp(index)], &draft[clamp(index + 1)..])
        };

        if next == draft || !self.options.valid_draft(&next).unwrap_or(false) {
            return None;
        }

        Some((
            next,
            if backward {
                index.saturating_sub(1)
            } else {
                index
            },
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::{AmountEditor, AmountFieldOptions, AmountInputKind, AmountMessages, infer_edit};

    fn editor(locale: &str) -> AmountEditor {
        AmountEditor {
            options: AmountFieldOptions {
                locale: locale.to_string(),
                ..AmountFieldOptions::default()
            },
            messages: AmountMessages::default(),
        }
    }

    #[test]
    fn edits_are_inferred_from_the_previous_display() {
        assert_eq!(infer_edit("1,234,567", "1,234567"), (5, String::new()));
        assert_eq!(infer_edit("1,423", "1,4253"), (5, "5".to_string()));
        assert_eq!(infer_edit("5", "12345"), (4, "1234".to_string()));
        assert_eq!(infer_edit("", ""), (0, String::new()));
    }

    #[test]
    fn caret_follows_typed_digits_across_new_group_separators() {
        let editor = editor("en-US");
        let edit = editor.edit("123", "123", "1423", AmountInputKind::Insert);

        assert_eq!((edit.display.as_str(), edit.caret), ("1,423", 3));

        let edit = editor.edit("1423", "1,423", "1,4253", AmountInputKind::Insert);

        assert_eq!((edit.display.as_str(), edit.caret), ("14,253", 5));
    }

    #[test]
    fn deleting_a_separator_removes_the_adjacent_digit() {
        let editor = editor("en-US");
        let edit = editor.edit(
            "1234567",
            "1,234,567",
            "1,234567",
            AmountInputKind::DeleteBackward,
        );

        assert_eq!(
            (edit.draft.as_str(), edit.display.as_str(), edit.caret),
            ("123567", "123,567", 3)
        );

        let edit = editor.edit(
            "123567",
            "123,567",
            "123567",
            AmountInputKind::DeleteForward,
        );

        assert_eq!((edit.display.as_str(), edit.caret), ("12,367", 4));
    }

    #[test]
    fn leading_zeros_and_rejections_keep_the_caret_in_place() {
        let editor = editor("en-US");
        let edit = editor.edit("0", "0", "05", AmountInputKind::Insert);

        assert_eq!((edit.display.as_str(), edit.caret), ("5", 1));

        let edit = editor.edit("5", "5", "12345", AmountInputKind::Paste);

        assert_eq!((edit.display.as_str(), edit.caret), ("12,345", 5));

        let edit = editor.edit("12345", "12,345", "12,3x45", AmountInputKind::Insert);

        assert!(!edit.accepted);
        assert_eq!((edit.display.as_str(), edit.caret), ("12,345", 4));
        assert_eq!(
            edit.validity,
            "Enter a valid amount using the displayed locale and precision."
        );
    }

    #[test]
    fn a_repeated_decimal_separator_moves_after_the_existing_one() {
        let editor = editor("es-CO");
        let edit = editor.edit("1234.50", "1.234,50", "1.2,34,50", AmountInputKind::Insert);

        assert!(!edit.accepted);
        assert_eq!(
            (edit.display.as_str(), edit.caret, edit.validity.as_str()),
            ("1.234,50", 6, "")
        );

        let edit = editor.edit(
            "1234.50",
            "1.234,50",
            "1.234,5",
            AmountInputKind::DeleteBackward,
        );

        assert_eq!((edit.display.as_str(), edit.caret), ("1.234,5", 7));
    }

    #[test]
    fn leading_decimals_gain_a_zero_and_place_the_caret_after_it() {
        let editor = AmountEditor {
            options: AmountFieldOptions {
                allow_negative: true,
                ..AmountFieldOptions::default()
            },
            messages: AmountMessages::default(),
        };
        let edit = editor.edit("", "", ".", AmountInputKind::Insert);

        assert_eq!((edit.display.as_str(), edit.caret), ("0.", 2));

        let edit = editor.edit("", "", "-.", AmountInputKind::Insert);

        assert_eq!((edit.display.as_str(), edit.caret), ("-0.", 3));
    }
}