Skip to main content

lumen_dioxus/inputs/
amount_field_format.rs

1//! Exact amount presentation for `AmountField`: formatting, parsing, range state, and the editing
2//! rules of `createLumenAmountFieldController`, ported from `@santi020k/lumen-core/amount-field`.
3//!
4//! Drafts are ASCII decimal strings (`-1234.50`); formatting groups them with the locale's
5//! separators and digits without ever converting to a floating-point number.
6
7use std::cmp::Ordering;
8use std::fmt;
9
10use super::number_field_locale::{
11    LocaleSymbols, is_direction_mark, js_trim, locale_symbols, utf16_len_capped,
12};
13
14/// The longest draft or source text (in UTF-16 code units) that is accepted.
15const AMOUNT_LIMIT: usize = 1024;
16
17/// Locale and precision of an amount, like lumen-core's `LumenAmountOptions`.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct AmountFieldOptions {
20    /// BCP 47 locale of the separators and digits. Defaults to `en-US`.
21    pub locale: String,
22    /// Allowed fraction digits, from 0 to 20. Defaults to 2.
23    pub fraction_digits: u8,
24    /// Whether negative amounts are accepted. Defaults to `false`.
25    pub allow_negative: bool,
26}
27
28impl Default for AmountFieldOptions {
29    fn default() -> Self {
30        Self {
31            locale: "en-US".to_string(),
32            fraction_digits: 2,
33            allow_negative: false,
34        }
35    }
36}
37
38/// Why an amount operation failed (lumen-core throws a `RangeError`).
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum AmountFieldError {
42    /// `fraction_digits` is above 20.
43    FractionDigits,
44    /// The draft is not an ASCII decimal draft within the configured precision and sign.
45    Draft,
46    /// A `min` or `max` bound is not a complete ASCII decimal string.
47    Bound,
48}
49
50impl fmt::Display for AmountFieldError {
51    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52        formatter.write_str(match self {
53            Self::FractionDigits => "Amount fractionDigits must be an integer from 0 to 20.",
54            Self::Draft => {
55                "Amount value must be an ASCII decimal draft within the configured precision."
56            }
57            Self::Bound => "Amount bounds must be complete ASCII decimal strings.",
58        })
59    }
60}
61
62impl std::error::Error for AmountFieldError {}
63
64/// Whether a complete amount is outside its bounds, like lumen-core's `LumenAmountRangeState`.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum AmountFieldRangeState {
67    /// Below `min`.
68    RangeUnderflow,
69    /// Above `max`.
70    RangeOverflow,
71}
72
73/// What [`AmountField`](crate::AmountField) reports after an accepted edit, like lumen-core's
74/// `LumenAmountChangeDetail`.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct AmountFieldChange {
77    /// The editable ASCII draft; intermediate `-` and trailing decimal points are kept.
78    pub draft: String,
79    /// The complete decimal string, or `None` for an empty or intermediate draft.
80    pub value: Option<String>,
81}
82
83impl AmountFieldChange {
84    /// The change detail of a draft.
85    pub fn new(draft: impl Into<String>) -> Self {
86        let draft = draft.into();
87        let value = amount_field_value(&draft).map(str::to_string);
88
89        Self { draft, value }
90    }
91}
92
93/// Resolved separators and precision.
94#[derive(Clone, Copy, Debug)]
95pub(crate) struct AmountFormat {
96    pub symbols: LocaleSymbols,
97    pub fraction_digits: usize,
98}
99
100impl AmountFieldOptions {
101    fn resolve(&self) -> Result<AmountFormat, AmountFieldError> {
102        if self.fraction_digits > 20 {
103            return Err(AmountFieldError::FractionDigits);
104        }
105
106        Ok(AmountFormat {
107            symbols: locale_symbols(&self.locale),
108            fraction_digits: usize::from(self.fraction_digits),
109        })
110    }
111
112    /// Whether `draft` is an ASCII decimal draft (`""`, `-`, `12.`, `-0.5`) within the precision
113    /// and sign rules.
114    fn valid_draft(&self, draft: &str) -> Result<bool, AmountFieldError> {
115        if utf16_len_capped(draft, AMOUNT_LIMIT) > AMOUNT_LIMIT {
116            return Ok(false);
117        }
118
119        let format = self.resolve()?;
120
121        let negative = draft.starts_with('-');
122
123        if negative && !self.allow_negative {
124            return Ok(false);
125        }
126
127        let unsigned = if negative { &draft[1..] } else { draft };
128        let mut pieces = unsigned.split('.');
129        let integer = pieces.next().unwrap_or_default();
130        let fraction = pieces.next();
131
132        if pieces.next().is_some() || (fraction.is_some() && format.fraction_digits == 0) {
133            return Ok(false);
134        }
135
136        let fraction = fraction.unwrap_or_default();
137
138        Ok(integer.bytes().all(|byte| byte.is_ascii_digit())
139            && fraction.bytes().all(|byte| byte.is_ascii_digit())
140            && fraction.len() <= format.fraction_digits)
141    }
142
143    /// Formats an ASCII draft for display, like `formatLumenAmountDraft`: the integer is grouped
144    /// with the locale's separators and digits, leading integer zeros are dropped, and fraction
145    /// digits (including trailing zeros) are kept exactly.
146    ///
147    /// # Errors
148    ///
149    /// [`AmountFieldError::FractionDigits`] for invalid options and [`AmountFieldError::Draft`]
150    /// when the draft is not a valid draft for them.
151    pub fn format_draft(&self, draft: &str) -> Result<String, AmountFieldError> {
152        if !self.valid_draft(draft)? {
153            return Err(AmountFieldError::Draft);
154        }
155
156        Ok(format_valid_draft(draft, &self.resolve()?.symbols))
157    }
158
159    /// Parses displayed or pasted text back to an ASCII draft, like `parseLumenAmountDraft`.
160    ///
161    /// Accepts the locale's digits and ASCII digits, its decimal separator, `-` or the locale's
162    /// minus sign, group separators, and bidirectional marks. With `strict_grouping` (pasted
163    /// text), group separators must sit exactly where the locale puts them. A leading decimal
164    /// separator gains a zero (`.5` becomes `0.5`). Returns `None` for anything else, including
165    /// text longer than 1024 UTF-16 code units and invalid options.
166    pub fn parse_draft(&self, source: &str, strict_grouping: bool) -> Option<String> {
167        if utf16_len_capped(source, AMOUNT_LIMIT) > AMOUNT_LIMIT {
168            return None;
169        }
170
171        let format = self.resolve().ok()?;
172        let translated = translate(source, &format.symbols)?;
173
174        if !self.valid_draft(&translated).ok()? {
175            return None;
176        }
177
178        let draft = normalize_leading_decimal(&translated);
179
180        if strict_grouping && !self.valid_grouping(source, &draft, &format.symbols) {
181            return None;
182        }
183
184        Some(draft)
185    }
186
187    fn valid_grouping(&self, source: &str, draft: &str, symbols: &LocaleSymbols) -> bool {
188        if !source.contains(symbols.group) {
189            return true;
190        }
191
192        let mut pieces = js_trim(source).split(symbols.decimal);
193        let integer = pieces.next().unwrap_or_default();
194        let fraction = pieces.next().unwrap_or_default();
195
196        if fraction.contains(symbols.group) {
197            return false;
198        }
199
200        let Ok(formatted) = self.format_draft(draft) else {
201            return false;
202        };
203        let formatted_integer = formatted.split(symbols.decimal).next().unwrap_or_default();
204
205        normalize_grouping_integer(integer, symbols) == formatted_integer
206    }
207
208    /// The display form of a bound in validation messages: formatted with negative amounts
209    /// allowed and enough fraction digits for the bound, or the bound itself when it cannot be
210    /// formatted.
211    pub(crate) fn display_bound(&self, bound: &str) -> String {
212        let fraction = bound.split('.').nth(1).unwrap_or_default();
213        let options = Self {
214            locale: self.locale.clone(),
215            allow_negative: true,
216            fraction_digits: self
217                .fraction_digits
218                .max(u8::try_from(fraction.len()).unwrap_or(u8::MAX)),
219        };
220
221        options
222            .format_draft(bound)
223            .unwrap_or_else(|_| bound.to_string())
224    }
225
226    pub(crate) fn symbols(&self) -> LocaleSymbols {
227        locale_symbols(&self.locale)
228    }
229}
230
231fn format_valid_draft(draft: &str, symbols: &LocaleSymbols) -> String {
232    if draft.is_empty() {
233        return String::new();
234    }
235
236    let negative = draft.starts_with('-');
237    let unsigned = if negative { &draft[1..] } else { draft };
238    let (integer, fraction) = match unsigned.split_once('.') {
239        Some((integer, fraction)) => (integer, Some(fraction)),
240        None => (unsigned, None),
241    };
242    let mut out = String::new();
243
244    if negative {
245        out.push(symbols.minus);
246    }
247
248    if !integer.is_empty() {
249        out.push_str(&symbols.group_integer(integer));
250    }
251
252    if let Some(fraction) = fraction {
253        out.push(symbols.decimal);
254        out.push_str(&symbols.localize_digits(fraction));
255    }
256
257    out
258}
259
260fn normalize_leading_decimal(draft: &str) -> String {
261    if let Some(rest) = draft.strip_prefix('.') {
262        return format!("0.{rest}");
263    }
264
265    if let Some(rest) = draft.strip_prefix("-.") {
266        return format!("-0.{rest}");
267    }
268
269    draft.to_string()
270}
271
272/// What one accepted display character contributes to the ASCII draft.
273#[derive(Clone, Copy, Debug, PartialEq, Eq)]
274pub(crate) enum AmountChar {
275    /// A digit, the decimal separator (`.`), or a minus sign (`-`).
276    Draft(char),
277    /// A group separator or direction mark, which the draft omits.
278    Ignored,
279}
280
281/// How one displayed character maps to the ASCII draft, or `None` for characters the locale does
282/// not use (lumen-core's `amountCharacters`).
283pub(crate) fn translate_char(character: char, symbols: &LocaleSymbols) -> Option<AmountChar> {
284    if is_direction_mark(character) || character == symbols.group {
285        return Some(AmountChar::Ignored);
286    }
287
288    if character == '-' || character == symbols.minus {
289        return Some(AmountChar::Draft('-'));
290    }
291
292    if character == symbols.decimal {
293        return Some(AmountChar::Draft('.'));
294    }
295
296    if character.is_ascii_digit() {
297        return Some(AmountChar::Draft(character));
298    }
299
300    symbols
301        .localized_digit(character)
302        .map(|digit| AmountChar::Draft(char::from(b'0' + digit)))
303}
304
305/// Whether a display character is part of the draft (digits, sign, decimal separator).
306fn is_draft_char(character: char, symbols: &LocaleSymbols) -> bool {
307    matches!(
308        translate_char(character, symbols),
309        Some(AmountChar::Draft(_))
310    )
311}
312
313/// Translates displayed text to an unchecked ASCII draft, or `None` when it holds a character
314/// the locale does not use.
315pub(crate) fn translate(source: &str, symbols: &LocaleSymbols) -> Option<String> {
316    let mut draft = String::new();
317
318    for character in js_trim(source).chars() {
319        if let AmountChar::Draft(ascii) = translate_char(character, symbols)? {
320            draft.push(ascii);
321        }
322    }
323
324    Some(draft)
325}
326
327fn normalize_grouping_integer(integer: &str, symbols: &LocaleSymbols) -> String {
328    let mut normalized = String::new();
329
330    for character in integer.chars() {
331        if is_direction_mark(character) {
332            continue;
333        }
334
335        if character == '-' {
336            normalized.push(symbols.minus);
337        } else if let Some(digit) = character.to_digit(10) {
338            normalized.push(symbols.digit(u8::try_from(digit).unwrap_or(0)));
339        } else {
340            normalized.push(character);
341        }
342    }
343
344    normalized
345}
346
347/// The submitted value of a draft, like `getLumenAmountValue`: the draft itself when it is a
348/// complete decimal (`-?[0-9]+(\.[0-9]+)?`, at most 1024 characters), otherwise `None`.
349pub fn amount_field_value(draft: &str) -> Option<&str> {
350    if draft.len() > AMOUNT_LIMIT {
351        return None;
352    }
353
354    let unsigned = draft.strip_prefix('-').unwrap_or(draft);
355    let (integer, fraction) = match unsigned.split_once('.') {
356        Some((integer, fraction)) => (integer, Some(fraction)),
357        None => (unsigned, None),
358    };
359    let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
360
361    (digits(integer) && fraction.is_none_or(digits)).then_some(draft)
362}
363
364struct Magnitude<'a> {
365    negative: bool,
366    integer: &'a str,
367    fraction: &'a str,
368}
369
370fn magnitude(value: &str) -> Magnitude<'_> {
371    let negative = value.starts_with('-');
372    let unsigned = if negative { &value[1..] } else { value };
373    let (raw_integer, raw_fraction) = unsigned.split_once('.').unwrap_or((unsigned, ""));
374    let mut start = 0;
375
376    while start + 1 < raw_integer.len() && raw_integer.as_bytes()[start] == b'0' {
377        start += 1;
378    }
379
380    let integer = &raw_integer[start..];
381    let fraction = raw_fraction.trim_end_matches('0');
382
383    Magnitude {
384        negative: negative && (integer != "0" || !fraction.is_empty()),
385        integer,
386        fraction,
387    }
388}
389
390/// Compares complete ASCII decimal strings exactly.
391fn compare_amounts(left: &str, right: &str) -> Ordering {
392    let a = magnitude(left);
393    let b = magnitude(right);
394
395    if a.negative != b.negative {
396        return if a.negative {
397            Ordering::Less
398        } else {
399            Ordering::Greater
400        };
401    }
402
403    let magnitude = a
404        .integer
405        .len()
406        .cmp(&b.integer.len())
407        .then_with(|| a.integer.cmp(b.integer))
408        .then_with(|| {
409            let length = a.fraction.len().max(b.fraction.len());
410            let left = a
411                .fraction
412                .bytes()
413                .chain(std::iter::repeat(b'0'))
414                .take(length);
415            let right = b
416                .fraction
417                .bytes()
418                .chain(std::iter::repeat(b'0'))
419                .take(length);
420
421            left.cmp(right)
422        });
423
424    if a.negative {
425        magnitude.reverse()
426    } else {
427        magnitude
428    }
429}
430
431fn amount_bound(bound: Option<&str>) -> Result<Option<&str>, AmountFieldError> {
432    match bound {
433        None | Some("") => Ok(None),
434        Some(bound) => amount_field_value(bound)
435            .map(Some)
436            .ok_or(AmountFieldError::Bound),
437    }
438}
439
440/// The range state of a complete amount, like `getLumenAmountRangeState`. Empty and incomplete
441/// drafts have no range state.
442///
443/// # Errors
444///
445/// [`AmountFieldError::Bound`] when `min` or `max` is not a complete ASCII decimal string.
446pub fn amount_field_range_state(
447    value: Option<&str>,
448    min: Option<&str>,
449    max: Option<&str>,
450) -> Result<Option<AmountFieldRangeState>, AmountFieldError> {
451    let min = amount_bound(min)?;
452    let max = amount_bound(max)?;
453    let Some(value) = value.and_then(amount_field_value) else {
454        return Ok(None);
455    };
456
457    if min.is_some_and(|min| compare_amounts(value, min) == Ordering::Less) {
458        return Ok(Some(AmountFieldRangeState::RangeUnderflow));
459    }
460
461    if max.is_some_and(|max| compare_amounts(value, max) == Ordering::Greater) {
462        return Ok(Some(AmountFieldRangeState::RangeOverflow));
463    }
464
465    Ok(None)
466}
467
468/// How an edit changed the control, inferred from keyboard and clipboard events because Dioxus
469/// form events carry no `inputType`.
470#[derive(Clone, Copy, Debug, PartialEq, Eq)]
471pub(crate) enum AmountInputKind {
472    /// Typed text.
473    Insert,
474    /// Pasted text; group separators must be exact.
475    Paste,
476    /// Backspace.
477    DeleteBackward,
478    /// Delete.
479    DeleteForward,
480}
481
482/// Validation and bounds configuration for the editor.
483#[derive(Clone, Debug, Default, PartialEq, Eq)]
484pub(crate) struct AmountMessages {
485    pub min: Option<String>,
486    pub max: Option<String>,
487    pub invalid: Option<String>,
488    pub underflow: Option<String>,
489    pub overflow: Option<String>,
490}
491
492/// The result of one user edit.
493#[derive(Clone, Debug, PartialEq, Eq)]
494pub(crate) struct AmountEdit {
495    /// The draft after the edit (unchanged when rejected).
496    pub draft: String,
497    /// The text the control should show.
498    pub display: String,
499    /// Caret position in characters of `display`.
500    pub caret: usize,
501    /// Whether the edit was accepted (and a change should be reported).
502    pub accepted: bool,
503    /// The custom validity message for the control (empty when valid).
504    pub validity: String,
505}
506
507/// Counts draft characters (digits, sign, decimal separator) before `end` in display text.
508fn draft_index_before(text: &[char], end: usize, symbols: &LocaleSymbols) -> usize {
509    text.iter()
510        .take(end)
511        .filter(|character| is_draft_char(**character, symbols))
512        .count()
513}
514
515/// Follows the zero inserted before a leading decimal separator.
516fn normalized_draft_index(translated: &str, index: usize) -> usize {
517    if translated.starts_with('.') {
518        return if index >= 1 { index + 1 } else { index };
519    }
520
521    if translated.starts_with("-.") {
522        return if index >= 2 { index + 1 } else { index };
523    }
524
525    index
526}
527
528/// Converts a draft index into the significant-character index of its display, which omits
529/// leading integer zeros.
530fn display_index(draft: &str, index: usize) -> usize {
531    let bytes = draft.as_bytes();
532    let sign = usize::from(draft.starts_with('-'));
533    let integer_end = draft.find('.').unwrap_or(draft.len());
534    let mut zeros = 0;
535
536    while sign + zeros + 1 < integer_end && bytes[sign + zeros] == b'0' {
537        zeros += 1;
538    }
539
540    index - index.saturating_sub(sign).min(zeros)
541}
542
543/// Places a caret after `index` significant display characters.
544fn display_caret(formatted: &[char], index: usize, symbols: &LocaleSymbols) -> usize {
545    if index == 0 {
546        return 0;
547    }
548
549    let mut seen = 0;
550
551    for (position, character) in formatted.iter().enumerate() {
552        if is_draft_char(*character, symbols) {
553            seen += 1;
554        }
555
556        if seen == index {
557            return position + 1;
558        }
559    }
560
561    formatted.len()
562}
563
564/// Where the caret sits after an edit that turned `previous` into `raw`, and the inserted text,
565/// inferred from their common prefix and suffix (exact for any single insertion or deletion).
566pub(crate) fn infer_edit(previous: &str, raw: &str) -> (usize, String) {
567    let before: Vec<char> = previous.chars().collect();
568    let after: Vec<char> = raw.chars().collect();
569    let shortest = before.len().min(after.len());
570    let mut prefix = 0;
571
572    while prefix < shortest && before[prefix] == after[prefix] {
573        prefix += 1;
574    }
575
576    let mut suffix = 0;
577
578    while suffix < shortest - prefix
579        && before[before.len() - 1 - suffix] == after[after.len() - 1 - suffix]
580    {
581        suffix += 1;
582    }
583
584    let caret = after.len() - suffix;
585    let inserted: String = after[prefix..caret].iter().collect();
586
587    (caret, inserted)
588}
589
590/// The amount editor: the state machine behind `createLumenAmountFieldController`.
591#[derive(Clone, Debug, PartialEq, Eq)]
592pub(crate) struct AmountEditor {
593    pub options: AmountFieldOptions,
594    pub messages: AmountMessages,
595}
596
597impl AmountEditor {
598    /// The display text of a draft, or the draft itself when it cannot be formatted.
599    pub(crate) fn display(&self, draft: &str) -> String {
600        self.options
601            .format_draft(draft)
602            .unwrap_or_else(|_| draft.to_string())
603    }
604
605    /// The validity message of a draft: incomplete amounts and range errors.
606    pub(crate) fn validity(&self, draft: &str) -> String {
607        let value = amount_field_value(draft);
608
609        if !draft.is_empty() && value.is_none() {
610            return self
611                .messages
612                .invalid
613                .clone()
614                .unwrap_or_else(|| "Enter a complete amount.".to_string());
615        }
616
617        let min = self.messages.min.as_deref();
618        let max = self.messages.max.as_deref();
619        // Invalid authored bounds are reported once by the component and ignored here.
620        let state = amount_field_range_state(value, min, max).unwrap_or(None);
621
622        match (state, min, max) {
623            (Some(AmountFieldRangeState::RangeUnderflow), Some(min), _) => self
624                .messages
625                .underflow
626                .as_deref()
627                .unwrap_or("Enter an amount of at least {min}.")
628                .replace("{min}", &self.options.display_bound(min)),
629            (Some(AmountFieldRangeState::RangeOverflow), _, Some(max)) => self
630                .messages
631                .overflow
632                .as_deref()
633                .unwrap_or("Enter an amount of at most {max}.")
634                .replace("{max}", &self.options.display_bound(max)),
635            _ => String::new(),
636        }
637    }
638
639    /// Applies a user edit: the control now shows `raw`, it showed `rendered` before, and the
640    /// current draft is `draft`.
641    pub(crate) fn edit(
642        &self,
643        draft: &str,
644        rendered: &str,
645        raw: &str,
646        kind: AmountInputKind,
647    ) -> AmountEdit {
648        let symbols = self.options.symbols();
649        let (caret, inserted) = infer_edit(rendered, raw);
650        let parsed = self
651            .options
652            .parse_draft(raw, kind == AmountInputKind::Paste);
653        let translated = translate(raw, &symbols);
654
655        let (Some(parsed), Some(translated)) = (parsed, translated) else {
656            let mut single = inserted.chars();
657            let typed_decimal = kind == AmountInputKind::Insert
658                && single.next() == Some(symbols.decimal)
659                && single.next().is_none();
660            let growth = raw.chars().count().saturating_sub(rendered.chars().count());
661
662            return self.reject(
663                draft,
664                rendered,
665                caret.saturating_sub(growth),
666                typed_decimal,
667                &symbols,
668            );
669        };
670
671        let raw_chars: Vec<char> = raw.chars().collect();
672        let index =
673            normalized_draft_index(&translated, draft_index_before(&raw_chars, caret, &symbols));
674        let deletion = if parsed == draft && raw != rendered {
675            self.separator_deletion(draft, rendered, raw, kind, index)
676        } else {
677            None
678        };
679        let (next, index) = deletion.unwrap_or((parsed, index));
680        let display = self.display(&next);
681        let display_chars: Vec<char> = display.chars().collect();
682        let caret = display_caret(&display_chars, display_index(&next, index), &symbols);
683        let validity = self.validity(&next);
684
685        AmountEdit {
686            draft: next,
687            display,
688            caret,
689            accepted: true,
690            validity,
691        }
692    }
693
694    /// Keeps the current draft after an edit that does not parse. `restored` is the caret shifted back by
695    /// the inserted length; a repeated decimal separator instead moves past the existing one.
696    fn reject(
697        &self,
698        draft: &str,
699        rendered: &str,
700        restored: usize,
701        typed_decimal: bool,
702        symbols: &LocaleSymbols,
703    ) -> AmountEdit {
704        let display = self.display(draft);
705        let display_length = display.chars().count();
706        let decimal_at = rendered
707            .chars()
708            .position(|character| character == symbols.decimal);
709
710        if let (true, true, Some(decimal_at)) = (typed_decimal, draft.contains('.'), decimal_at) {
711            return AmountEdit {
712                draft: draft.to_string(),
713                display,
714                caret: decimal_at + 1,
715                accepted: false,
716                validity: self.validity(draft),
717            };
718        }
719
720        AmountEdit {
721            draft: draft.to_string(),
722            display,
723            caret: restored.min(display_length),
724            accepted: false,
725            validity: self.messages.invalid.clone().unwrap_or_else(|| {
726                "Enter a valid amount using the displayed locale and precision.".to_string()
727            }),
728        }
729    }
730
731    /// Deleting only a group separator removes the adjacent digit, matching the visible intent of
732    /// the keypress.
733    fn separator_deletion(
734        &self,
735        draft: &str,
736        rendered: &str,
737        raw: &str,
738        kind: AmountInputKind,
739        index: usize,
740    ) -> Option<(String, usize)> {
741        let backward = kind == AmountInputKind::DeleteBackward;
742
743        if (!backward && kind != AmountInputKind::DeleteForward)
744            || raw.chars().count() >= rendered.chars().count()
745        {
746            return None;
747        }
748
749        let clamp = |position: usize| position.min(draft.len());
750        let next = if backward {
751            format!(
752                "{}{}",
753                &draft[..clamp(index.saturating_sub(1))],
754                &draft[clamp(index)..]
755            )
756        } else {
757            format!("{}{}", &draft[..clamp(index)], &draft[clamp(index + 1)..])
758        };
759
760        if next == draft || !self.options.valid_draft(&next).unwrap_or(false) {
761            return None;
762        }
763
764        Some((
765            next,
766            if backward {
767                index.saturating_sub(1)
768            } else {
769                index
770            },
771        ))
772    }
773}
774
775#[cfg(test)]
776mod tests {
777    use super::{AmountEditor, AmountFieldOptions, AmountInputKind, AmountMessages, infer_edit};
778
779    fn editor(locale: &str) -> AmountEditor {
780        AmountEditor {
781            options: AmountFieldOptions {
782                locale: locale.to_string(),
783                ..AmountFieldOptions::default()
784            },
785            messages: AmountMessages::default(),
786        }
787    }
788
789    #[test]
790    fn edits_are_inferred_from_the_previous_display() {
791        assert_eq!(infer_edit("1,234,567", "1,234567"), (5, String::new()));
792        assert_eq!(infer_edit("1,423", "1,4253"), (5, "5".to_string()));
793        assert_eq!(infer_edit("5", "12345"), (4, "1234".to_string()));
794        assert_eq!(infer_edit("", ""), (0, String::new()));
795    }
796
797    #[test]
798    fn caret_follows_typed_digits_across_new_group_separators() {
799        let editor = editor("en-US");
800        let edit = editor.edit("123", "123", "1423", AmountInputKind::Insert);
801
802        assert_eq!((edit.display.as_str(), edit.caret), ("1,423", 3));
803
804        let edit = editor.edit("1423", "1,423", "1,4253", AmountInputKind::Insert);
805
806        assert_eq!((edit.display.as_str(), edit.caret), ("14,253", 5));
807    }
808
809    #[test]
810    fn deleting_a_separator_removes_the_adjacent_digit() {
811        let editor = editor("en-US");
812        let edit = editor.edit(
813            "1234567",
814            "1,234,567",
815            "1,234567",
816            AmountInputKind::DeleteBackward,
817        );
818
819        assert_eq!(
820            (edit.draft.as_str(), edit.display.as_str(), edit.caret),
821            ("123567", "123,567", 3)
822        );
823
824        let edit = editor.edit(
825            "123567",
826            "123,567",
827            "123567",
828            AmountInputKind::DeleteForward,
829        );
830
831        assert_eq!((edit.display.as_str(), edit.caret), ("12,367", 4));
832    }
833
834    #[test]
835    fn leading_zeros_and_rejections_keep_the_caret_in_place() {
836        let editor = editor("en-US");
837        let edit = editor.edit("0", "0", "05", AmountInputKind::Insert);
838
839        assert_eq!((edit.display.as_str(), edit.caret), ("5", 1));
840
841        let edit = editor.edit("5", "5", "12345", AmountInputKind::Paste);
842
843        assert_eq!((edit.display.as_str(), edit.caret), ("12,345", 5));
844
845        let edit = editor.edit("12345", "12,345", "12,3x45", AmountInputKind::Insert);
846
847        assert!(!edit.accepted);
848        assert_eq!((edit.display.as_str(), edit.caret), ("12,345", 4));
849        assert_eq!(
850            edit.validity,
851            "Enter a valid amount using the displayed locale and precision."
852        );
853    }
854
855    #[test]
856    fn a_repeated_decimal_separator_moves_after_the_existing_one() {
857        let editor = editor("es-CO");
858        let edit = editor.edit("1234.50", "1.234,50", "1.2,34,50", AmountInputKind::Insert);
859
860        assert!(!edit.accepted);
861        assert_eq!(
862            (edit.display.as_str(), edit.caret, edit.validity.as_str()),
863            ("1.234,50", 6, "")
864        );
865
866        let edit = editor.edit(
867            "1234.50",
868            "1.234,50",
869            "1.234,5",
870            AmountInputKind::DeleteBackward,
871        );
872
873        assert_eq!((edit.display.as_str(), edit.caret), ("1.234,5", 7));
874    }
875
876    #[test]
877    fn leading_decimals_gain_a_zero_and_place_the_caret_after_it() {
878        let editor = AmountEditor {
879            options: AmountFieldOptions {
880                allow_negative: true,
881                ..AmountFieldOptions::default()
882            },
883            messages: AmountMessages::default(),
884        };
885        let edit = editor.edit("", "", ".", AmountInputKind::Insert);
886
887        assert_eq!((edit.display.as_str(), edit.caret), ("0.", 2));
888
889        let edit = editor.edit("", "", "-.", AmountInputKind::Insert);
890
891        assert_eq!((edit.display.as_str(), edit.caret), ("-0.", 3));
892    }
893}