Skip to main content

adam_web_ui/components/number/
draft.rs

1//! Numeric draft transitions.
2//!
3//! Keep one [`NumberDraft`] per binding instance and retire it on unmount.
4use super::{NormalizedDraft, NumberLocale, normalize_draft};
5use crate::input::{InputError, NumberKind};
6
7/// Carries synchronous native events or revision-tagged formatting replies.
8///
9/// `generation` identifies the binding instance, not a model value revision.
10///
11/// # Examples
12/// ```
13/// use adam_web_ui::components::number::DraftEvent;
14/// let input = DraftEvent::Input("-".into());
15/// ```
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum DraftEvent {
18    /// Replaces the user draft; callers discard native composition echoes before reduction.
19    Input(String),
20    /// Captures the originating locale.
21    Focus,
22    /// Restores latest model display without submitting.
23    Blur,
24    /// Suppresses submissions until composition ends.
25    CompositionStart,
26    /// Processes the final composed draft.
27    CompositionEnd(String),
28    /// Cancels composition without submission or changing the focus session's locale.
29    CompositionCancel,
30    /// Synchronizes model state; a newer generation retires the previous draft.
31    ModelUpdate {
32        /// Contains canonical model text, including explicit NaN/infinity text.
33        canonical: String,
34        /// Disables edits when forced or disconnected.
35        disabled: bool,
36        /// Prohibits edits without treating the cell as disconnected.
37        readonly: bool,
38        /// Identifies the binding instance.
39        generation: u64,
40    },
41    /// Supplies a formatter reply for exactly one generation and revision.
42    Formatted {
43        /// Contains localized model display text.
44        text: String,
45        /// Identifies the binding instance.
46        generation: u64,
47        /// Identifies the edit/model revision being formatted.
48        revision: u64,
49    },
50}
51
52/// Describes the only externally observable side effect of a transition.
53///
54/// # Examples
55/// ```
56/// use adam_web_ui::components::number::DraftEffect;
57/// assert_ne!(DraftEffect::None, DraftEffect::Submit("1".into()));
58/// ```
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub enum DraftEffect {
61    /// Performs no model write or error report.
62    None,
63    /// Submits a complete, concretely representable value.
64    Submit(String),
65    /// Reports invalid input without a model write.
66    Report(InputError),
67}
68
69/// Owns one binding instance's local draft and latest model display.
70///
71/// Hosts assign every replacement binding a unique, increasing generation,
72/// including when constructing a fresh reducer. Revisions never wrap;
73/// exhaustion retires the instance.
74///
75/// # Examples
76/// ```
77/// use adam_web_ui::components::number::NumberDraft;
78/// let draft = NumberDraft::default();
79/// assert_eq!(draft.text(), "");
80/// ```
81#[derive(Debug, Default)]
82pub struct NumberDraft {
83    /// Contains the visible user draft.
84    text: String,
85    /// Contains the latest canonical model value, independently of local edits.
86    canonical: String,
87    /// Contains the latest accepted model display.
88    display: String,
89    /// Retains the locale captured at focus until blur or replacement.
90    origin: Option<NumberLocale>,
91    /// Indicates an active focus session.
92    focused: bool,
93    /// Indicates an input-method composition in progress.
94    composing: bool,
95    /// Indicates incomplete or invalid local text.
96    local: bool,
97    /// Prohibits user input when disabled or readonly.
98    blocked: bool,
99    /// Makes retirement permanent.
100    retired: bool,
101    /// Identifies this binding instance.
102    generation: u64,
103    /// Distinguishes asynchronous work from subsequent edits or model changes.
104    revision: u64,
105    /// Retains the submitted value so acknowledgments preserve equivalent spelling.
106    submitted: Option<String>,
107    /// Allows localization of authoritative model text, never of an entered draft.
108    format_visible: bool,
109}
110
111impl NumberDraft {
112    /// Applies a synchronous event belonging to this binding instance.
113    ///
114    /// Queue asynchronous native events through [`Self::reduce_stamped`].
115    /// Focus retains its locale; composition never submits intermediate text.
116    /// Blur restores the latest display without submitting. Disabled/readonly
117    /// updates discard local drafts. Formatter replies never replace focused
118    /// user edits, and stale generations/revisions have no effect.
119    ///
120    /// - Complexity: O(event text + locale vocabulary bytes) time and space.
121    ///
122    /// # Examples
123    /// ```
124    /// use adam_web_ui::{components::number::*, input::NumberKind};
125    /// fn edit(locale: &NumberLocale) {
126    ///     let mut draft = NumberDraft::default();
127    ///     assert_eq!(draft.reduce(DraftEvent::Input("-".into()), locale,
128    ///         NumberKind::F64), DraftEffect::None);
129    /// }
130    /// ```
131    pub fn reduce(
132        &mut self,
133        event: DraftEvent,
134        locale: &NumberLocale,
135        kind: NumberKind,
136    ) -> DraftEffect {
137        if self.retired {
138            return DraftEffect::None;
139        }
140        match event {
141            DraftEvent::ModelUpdate {
142                canonical,
143                disabled,
144                readonly,
145                generation,
146            } => {
147                if generation < self.generation {
148                    return DraftEffect::None;
149                }
150                if generation != self.generation {
151                    self.focused = false;
152                    self.origin = None;
153                    self.local = false;
154                    self.composing = false;
155                    self.submitted = None;
156                    self.generation = generation;
157                }
158                if !self.advance() {
159                    return DraftEffect::None;
160                }
161                self.blocked = disabled || readonly;
162                if self.blocked {
163                    self.focused = false;
164                    self.origin = None;
165                    self.local = false;
166                    self.composing = false;
167                    self.submitted = None;
168                }
169                let keep = self.focused
170                    && !self.blocked
171                    && (self.local
172                        || self.composing
173                        || self.canonical == canonical
174                        || self
175                            .submitted
176                            .as_ref()
177                            .is_some_and(|value| equivalent(value, &canonical, kind)));
178                self.display.clone_from(&canonical);
179                self.canonical = canonical;
180                if !keep {
181                    self.text.clone_from(&self.display);
182                    self.submitted = None;
183                    self.format_visible = true;
184                }
185            }
186            DraftEvent::Focus => {
187                if !self.blocked && !self.focused {
188                    self.focused = true;
189                    self.origin = Some(locale.clone());
190                }
191            }
192            DraftEvent::Blur => {
193                if !self.advance() {
194                    return DraftEffect::None;
195                }
196                self.focused = false;
197                self.composing = false;
198                self.local = false;
199                self.origin = None;
200                self.submitted = None;
201                self.text.clone_from(&self.display);
202                self.format_visible = true;
203            }
204            DraftEvent::CompositionStart => {
205                if !self.blocked {
206                    if !self.advance() {
207                        return DraftEffect::None;
208                    }
209                    self.composing = true;
210                    self.format_visible = false;
211                }
212            }
213            DraftEvent::CompositionCancel => {
214                if self.advance() {
215                    self.composing = false;
216                    self.local = false;
217                    self.submitted = None;
218                    self.text.clone_from(&self.display);
219                    self.format_visible = true;
220                }
221            }
222            DraftEvent::CompositionEnd(text) => {
223                if self.blocked || !self.composing {
224                    return DraftEffect::None;
225                }
226                self.composing = false;
227                return self.input(text, locale, kind);
228            }
229            DraftEvent::Input(text) => {
230                if self.blocked {
231                    return DraftEffect::None;
232                }
233                return self.input(text, locale, kind);
234            }
235            DraftEvent::Formatted {
236                text,
237                generation,
238                revision,
239            } => {
240                if generation == self.generation
241                    && revision == self.revision
242                    && !matches!(
243                        self.canonical.as_str(),
244                        "NaN" | "inf" | "-inf" | "Infinity" | "-Infinity"
245                    )
246                {
247                    self.display = text;
248                    if !self.focused || self.format_visible {
249                        self.text.clone_from(&self.display);
250                    }
251                    self.format_visible = false;
252                }
253            }
254        }
255        DraftEffect::None
256    }
257
258    /// Ignores delayed native events unless their instance and revision match.
259    ///
260    /// - Complexity: O(event text + locale vocabulary bytes) time and space.
261    ///
262    /// # Examples
263    /// ```
264    /// use adam_web_ui::{components::number::*, input::NumberKind};
265    /// fn delayed_edit(draft: &mut NumberDraft, locale: &NumberLocale) {
266    ///     let generation = draft.generation();
267    ///     let revision = draft.revision();
268    ///     draft.reduce_stamped(generation, revision, DraftEvent::Input("1".into()),
269    ///         locale, NumberKind::F64);
270    /// }
271    /// ```
272    pub fn reduce_stamped(
273        &mut self,
274        generation: u64,
275        revision: u64,
276        event: DraftEvent,
277        locale: &NumberLocale,
278        kind: NumberKind,
279    ) -> DraftEffect {
280        if generation != self.generation || revision != self.revision {
281            return DraftEffect::None;
282        }
283        self.reduce(event, locale, kind)
284    }
285
286    /// Returns the visible draft without allocation.
287    ///
288    /// # Examples
289    /// ```
290    /// use adam_web_ui::components::number::NumberDraft;
291    /// assert_eq!(NumberDraft::default().text(), "");
292    /// ```
293    pub fn text(&self) -> &str {
294        &self.text
295    }
296
297    /// Returns the monotonically increasing edit/model revision.
298    ///
299    /// # Examples
300    /// ```
301    /// use adam_web_ui::components::number::NumberDraft;
302    /// assert_eq!(NumberDraft::default().revision(), 0);
303    /// ```
304    pub fn revision(&self) -> u64 {
305        self.revision
306    }
307
308    /// Returns the current binding generation for delayed-event stamps.
309    ///
310    /// # Examples
311    /// ```
312    /// use adam_web_ui::components::number::NumberDraft;
313    /// assert_eq!(NumberDraft::default().generation(), 0);
314    /// ```
315    pub fn generation(&self) -> u64 {
316        self.generation
317    }
318
319    /// Returns the latest model value independently of the visible draft.
320    ///
321    /// # Examples
322    /// ```
323    /// use adam_web_ui::components::number::NumberDraft;
324    /// assert_eq!(NumberDraft::default().canonical(), "");
325    /// ```
326    pub fn canonical(&self) -> &str {
327        &self.canonical
328    }
329
330    /// Returns the focus session's parsing locale, or the current unfocused locale.
331    ///
332    /// Hosts use this same locale when formatting authoritative model updates so
333    /// the displayed number remains valid input without reinterpreting a draft.
334    ///
335    /// # Examples
336    /// ```
337    /// use adam_web_ui::components::number::{NumberDraft, NumberLocale};
338    /// fn unfocused(current: &NumberLocale) {
339    ///     let draft = NumberDraft::default();
340    ///     assert_eq!(draft.display_locale(current), current);
341    /// }
342    /// ```
343    pub fn display_locale<'a>(&'a self, current: &'a NumberLocale) -> &'a NumberLocale {
344        self.origin.as_ref().unwrap_or(current)
345    }
346
347    /// Discards the local draft and permanently retires this instance.
348    ///
349    /// - Postcondition: No later event submits a value.
350    /// - Complexity: O(latest display bytes) time and space.
351    ///
352    /// # Examples
353    /// ```
354    /// use adam_web_ui::components::number::NumberDraft;
355    /// let mut draft = NumberDraft::default();
356    /// draft.retire();
357    /// ```
358    pub fn retire(&mut self) {
359        self.retired = true;
360        self.focused = false;
361        self.local = false;
362        self.composing = false;
363        self.origin = None;
364        self.submitted = None;
365        self.format_visible = false;
366        self.text.clone_from(&self.display);
367    }
368
369    /// Advances the event revision, retiring instead of wrapping on exhaustion.
370    ///
371    /// - Complexity: O(1), or O(latest display bytes) when retiring.
372    fn advance(&mut self) -> bool {
373        match self.revision.checked_add(1) {
374            Some(revision) => {
375                self.revision = revision;
376                true
377            }
378            None => {
379                self.retire();
380                false
381            }
382        }
383    }
384
385    /// Retains raw input and emits at most one complete numeric submission.
386    ///
387    /// - Complexity: O(text + locale vocabulary bytes) time and space.
388    fn input(&mut self, text: String, locale: &NumberLocale, kind: NumberKind) -> DraftEffect {
389        if !self.advance() {
390            return DraftEffect::None;
391        }
392        self.text = text;
393        self.format_visible = false;
394        self.local = true;
395        self.submitted = None;
396        if self.composing {
397            return DraftEffect::None;
398        }
399        match normalize_draft(&self.text, self.origin.as_ref().unwrap_or(locale), kind) {
400            Ok(NormalizedDraft::Incomplete) => DraftEffect::None,
401            Ok(NormalizedDraft::Complete(canonical)) => {
402                self.local = false;
403                self.submitted = Some(canonical.clone());
404                DraftEffect::Submit(canonical)
405            }
406            Err(error) => DraftEffect::Report(error),
407        }
408    }
409}
410
411/// Compares canonical primitive values without routing integers through floats.
412///
413/// - Complexity: O(left bytes + right bytes) time and O(1) additional space.
414fn equivalent(left: &str, right: &str, kind: NumberKind) -> bool {
415    match kind {
416        NumberKind::Signed(_) => parsed_equal::<i128>(left, right),
417        NumberKind::Unsigned(_) => parsed_equal::<u128>(left, right),
418        NumberKind::F32 => parsed_equal::<f32>(left, right),
419        NumberKind::F64 => parsed_equal::<f64>(left, right),
420    }
421}
422
423/// Compares two successfully parsed values of the same primitive.
424///
425/// - Complexity: O(left bytes + right bytes) time and O(1) additional space.
426fn parsed_equal<T: std::str::FromStr + PartialEq>(left: &str, right: &str) -> bool {
427    matches!((left.parse::<T>(), right.parse::<T>()), (Ok(a), Ok(b)) if a == b)
428}