Skip to main content

adam_web_ui/components/numeric_editor/
component.rs

1//! Controlled numeric controls without model ownership.
2//!
3//! Pass canonical strings and handle aspirations in `on_value`; the host's
4//! validation remains authoritative. Wrap controls in [`crate::components::Theme`].
5use crate::components::numeric_events::{SourceChannel, SourceFrame};
6use crate::components::{
7    button::{Button, ButtonVariant},
8    input::Input,
9    label::Label,
10    number::*,
11    slider::Slider,
12};
13use crate::input::{InputError, NumberKind, NumericRange};
14use dioxus::prelude::*;
15use std::{
16    cell::{Cell, RefCell},
17    rc::Rc,
18};
19
20include!(concat!(env!("OUT_DIR"), "/numeric_editor-styles.rs"));
21
22thread_local! {
23    /// Allocates distinct increasing identities across roots on the UI thread.
24    static GENERATION: Cell<u64> = const { Cell::new(0) };
25}
26
27/// Returns a fresh instance identity without wrapping.
28fn next_generation() -> u64 {
29    GENERATION.with(|counter| {
30        let next = counter
31            .get()
32            .checked_add(1)
33            .expect("numeric instance identities exhausted");
34        counter.set(next);
35        next
36    })
37}
38
39/// Supplies controlled canonical values and model-independent numeric callbacks.
40///
41/// `range` guides the slider and limits nudges; the host validates typed aspirations.
42/// Required blanks remain local; optional blanks submit `None`. Locale and
43/// transport failures reach `on_error`. Programmatic updates never call `on_value`.
44///
45/// # Examples
46/// ```
47/// use adam_web_ui::{components::NumericEditor, input::NumberKind};
48/// use dioxus::prelude::*;
49/// fn app() -> Element {
50///     let mut value = use_signal(|| Some("12".to_string()));
51///     let range = use_signal(|| None);
52///     let flags = use_signal(|| false);
53///     rsx! { NumericEditor {
54///         id: "amount", label: "Amount", value, range, kind: NumberKind::Signed(32),
55///         step: "1", disabled: flags, readonly: flags, invalid: flags,
56///         locale: None, optional: false,
57///         on_value: move |v| value.set(v), on_error: |_| {},
58///     } }
59/// }
60/// ```
61#[derive(Props, Clone, PartialEq)]
62pub struct NumericEditorProps {
63    /// Names the native input and its help/error associations.
64    pub id: String,
65    /// Supplies the accessible visible name.
66    pub label: String,
67    /// Contains the effective canonical model value, not the draft.
68    pub value: ReadSignal<Option<String>>,
69    /// Preserves the concrete primitive width.
70    pub kind: NumberKind,
71    /// Supplies inclusive slider and nudge bounds without clamping typed aspirations.
72    pub range: ReadSignal<Option<NumericRange>>,
73    /// Supplies a positive canonical step.
74    pub step: String,
75    /// Disables every editing affordance.
76    pub disabled: ReadSignal<bool>,
77    /// Prevents edits while preserving readable, selectable content; the editor
78    /// then renders a frameless value without nudges or stepping help.
79    pub readonly: ReadSignal<bool>,
80    /// Exposes model validation independently of lexical input errors.
81    pub invalid: ReadSignal<bool>,
82    /// Selects an Intl locale; absence requests the host default.
83    pub locale: Option<String>,
84    /// Accepts a cleared property as `None` when true.
85    pub optional: bool,
86    /// Receives only user aspirations, never programmatic synchronization.
87    pub on_value: EventHandler<Option<String>>,
88    /// Receives explicit lexical, type, support, and locale errors.
89    pub on_error: EventHandler<InputError>,
90}
91
92/// Renders an exact, localized controlled numeric editor.
93///
94/// Focus retains the originating locale and equivalent spelling. Blur restores
95/// the latest effective value without submitting. Blur clears discarded lexical/range
96/// errors, but retains unresolved locale, support, and event-source failures.
97/// Replacing `id` or `kind` retires
98/// the old instance; use a different key when replacing the underlying model.
99///
100/// Native capture supports selected/collapsed composition spans and expansions
101/// exposed by synchronous `beforeinput` selection. A native mutation outside
102/// that span without authoritative range metadata reports `InputError::EventSource`
103/// without guessing a write (range generalization: issue #280). Native composition
104/// terminal echoes use composition input metadata, not text equality alone.
105///
106/// - Complexity: O(value + draft + locale bytes) per transition.
107///
108/// # Examples
109/// ```
110/// use adam_web_ui::{components::NumericEditor, input::NumberKind};
111/// use dioxus::prelude::*;
112/// fn app() -> Element {
113///     let mut value = use_signal(|| Some("12".to_string()));
114///     let range = use_signal(|| None);
115///     let flags = use_signal(|| false);
116///     rsx! { NumericEditor {
117///         id: "amount", label: "Amount", value, range, kind: NumberKind::Signed(32),
118///         step: "1", disabled: flags, readonly: flags, invalid: flags,
119///         locale: None, optional: false,
120///         on_value: move |v| value.set(v), on_error: |_| {},
121///     } }
122/// }
123/// ```
124#[component]
125pub fn NumericEditor(props: NumericEditorProps) -> Element {
126    rsx! {
127        EditorInstance { key: "{props.id}:{props.kind:?}", ..props }
128    }
129}
130
131/// Owns the reducer, locale request epoch, and optional-clear composition state.
132struct EditorState {
133    draft: NumberDraft,
134    generation: u64,
135    epoch: u64,
136    locale: Option<NumberLocale>,
137    model: Option<(bool, bool)>,
138    composing: bool,
139    retired: bool,
140}
141
142impl EditorState {
143    /// Creates a uniquely identified uninitialized editor.
144    fn new() -> Self {
145        Self {
146            draft: NumberDraft::default(),
147            generation: next_generation(),
148            epoch: 0,
149            locale: None,
150            model: None,
151            composing: false,
152            retired: false,
153        }
154    }
155
156    /// Accepts asynchronous work only for the current live model/edit and locale.
157    fn accepts(&self, generation: u64, revision: u64, epoch: u64) -> bool {
158        !self.retired
159            && self.epoch == epoch
160            && self.draft.generation() == generation
161            && self.draft.revision() == revision
162    }
163
164    /// Permanently retires this mounted instance and its delayed work.
165    ///
166    /// - Complexity: O(latest display bytes) time and space.
167    fn retire(&mut self) {
168        self.retired = true;
169        self.draft.retire();
170    }
171
172    /// Retires a failed locale session before allowing a future resolution to recover.
173    ///
174    /// - Complexity: O(latest display bytes) time and space.
175    fn lose_locale(&mut self) {
176        self.draft.retire();
177        self.draft = NumberDraft::default();
178        self.generation = next_generation();
179        self.locale = None;
180        self.model = None;
181        self.composing = false;
182    }
183
184    /// Synchronizes changed model state and reports whether it discards a forced draft.
185    ///
186    /// - Complexity: O(canonical + locale bytes) time and space.
187    fn sync(&mut self, canonical: &str, disabled: bool, readonly: bool, kind: NumberKind) -> bool {
188        if self.retired
189            || self.model.as_ref().is_some_and(|(d, r)| {
190                self.draft.canonical() == canonical && *d == disabled && *r == readonly
191            })
192        {
193            return false;
194        }
195        let Some(locale) = &self.locale else {
196            return false;
197        };
198        self.draft.reduce(
199            DraftEvent::ModelUpdate {
200                canonical: canonical.to_string(),
201                disabled,
202                readonly,
203                generation: self.generation,
204            },
205            locale,
206            kind,
207        );
208        self.model = Some((disabled, readonly));
209        if disabled || readonly {
210            self.composing = false;
211        }
212        disabled || readonly
213    }
214
215    /// Applies a stamped native transition and derives the optional-clear callback.
216    ///
217    /// - Complexity: O(draft + locale bytes) time and space.
218    fn event(&mut self, event: DraftEvent, kind: NumberKind, optional: bool) -> UiEffect {
219        if self.retired {
220            return UiEffect::None;
221        }
222        let Some(locale) = &self.locale else {
223            return UiEffect::None;
224        };
225        let blocked = self.model.as_ref().is_none_or(|(d, r)| *d || *r);
226        let clear = match &event {
227            DraftEvent::Input(text) => optional && text.is_empty() && !self.composing,
228            DraftEvent::CompositionStart => {
229                self.composing = true;
230                false
231            }
232            DraftEvent::CompositionEnd(text) => {
233                let was_composing = std::mem::take(&mut self.composing);
234                optional && text.is_empty() && was_composing
235            }
236            DraftEvent::Blur | DraftEvent::CompositionCancel => {
237                self.composing = false;
238                false
239            }
240            _ => false,
241        };
242        let effect =
243            self.draft
244                .reduce_stamped(self.generation, self.draft.revision(), event, locale, kind);
245        if clear && !blocked {
246            return UiEffect::Submit(None);
247        }
248        match effect {
249            DraftEffect::Submit(value) => UiEffect::Submit(Some(value)),
250            DraftEffect::Report(error) => UiEffect::Report(error),
251            DraftEffect::None => UiEffect::None,
252        }
253    }
254}
255
256/// Separates reducer decisions from framework callback delivery.
257#[derive(Debug, PartialEq, Eq)]
258enum UiEffect {
259    None,
260    Submit(Option<String>),
261    Report(InputError),
262}
263
264/// Updates the native value only when its text actually changes.
265///
266/// - Complexity: O(text bytes) time and space.
267fn publish(state: &EditorState, mut visible: Signal<String>) {
268    if visible.peek().as_str() != state.draft.text() {
269        visible.set(state.draft.text().to_string());
270    }
271}
272
273/// Delivers one transition after releasing reducer borrows.
274fn deliver(
275    effect: UiEffect,
276    mut error: Signal<Option<InputError>>,
277    on_value: EventHandler<Option<String>>,
278    on_error: EventHandler<InputError>,
279) {
280    match effect {
281        UiEffect::None => {}
282        UiEffect::Submit(value) => {
283            error.set(None);
284            on_value.call(value);
285        }
286        UiEffect::Report(failure) => {
287            error.set(Some(failure.clone()));
288            on_error.call(failure);
289        }
290    }
291}
292
293/// Receives the explicit locale transport envelope, including eval execution failures.
294///
295/// # Errors
296/// Returns `Locale` for any eval/transport failure.
297async fn eval_reply(script: &str) -> Result<String, InputError> {
298    // Web evaluators cannot serialize an implicit undefined completion.
299    let mut eval = document::eval(&format!("{script}\nreturn null;"));
300    let reply: serde_json::Value = eval
301        .recv()
302        .await
303        .map_err(|error| InputError::Locale(error.to_string()))?;
304    eval.join::<serde_json::Value>()
305        .await
306        .map_err(|error| InputError::Locale(error.to_string()))?;
307    serde_json::to_string(&reply).map_err(|error| InputError::Locale(error.to_string()))
308}
309
310/// Formats the latest effective model with Rust-owned generation/revision/locale guards.
311///
312/// - Complexity: O(canonical + locale bytes) time and space, plus Intl formatting.
313fn format_model(
314    state: Rc<RefCell<EditorState>>,
315    visible: Signal<String>,
316    mut error: Signal<Option<InputError>>,
317    kind: NumberKind,
318    on_error: EventHandler<InputError>,
319) {
320    let (canonical, locale, generation, revision, epoch) = {
321        let state = state.borrow();
322        let Some(locale) = &state.locale else { return };
323        let canonical = state.draft.canonical();
324        if canonical.is_empty()
325            || matches!(canonical, "NaN" | "inf" | "-inf" | "Infinity" | "-Infinity")
326        {
327            return;
328        }
329        (
330            canonical.to_string(),
331            state.draft.display_locale(locale).resolved.clone(),
332            state.generation,
333            state.draft.revision(),
334            state.epoch,
335        )
336    };
337    spawn(async move {
338        let result = async {
339            let script = format_number_script(&canonical, kind, &locale, &serde_json::json!({}))?;
340            decode_format_reply(&eval_reply(&script).await?, generation, revision)
341        }
342        .await;
343        let effect = {
344            let mut state = state.borrow_mut();
345            if !state.accepts(generation, revision, epoch) {
346                return;
347            }
348            match result {
349                Ok(event) => {
350                    let EditorState { draft, locale, .. } = &mut *state;
351                    if let Some(locale) = locale.as_ref() {
352                        draft.reduce_stamped(generation, revision, event, locale, kind);
353                        publish(&state, visible);
354                    }
355                    None
356                }
357                Err(failure) => Some(failure),
358            }
359        };
360        if let Some(failure) = effect {
361            error.set(Some(failure.clone()));
362            on_error.call(failure);
363        }
364    });
365}
366
367/// Owns one mounted numeric draft and its scope-cancelled locale tasks.
368///
369/// - Complexity: O(value + draft + locale bytes) per transition.
370#[component]
371fn EditorInstance(props: NumericEditorProps) -> Element {
372    crate::components::styles::use_control_styles();
373    let (value, disabled, readonly, kind, optional, on_value, on_error) = (
374        props.value,
375        props.disabled,
376        props.readonly,
377        props.kind,
378        props.optional,
379        props.on_value,
380        props.on_error,
381    );
382    let state = use_hook(|| Rc::new(RefCell::new(EditorState::new())));
383    let mut visible = use_signal(|| props.value.peek().clone().unwrap_or_default());
384    let mut error = use_signal(|| None::<InputError>);
385    let mut ready = use_signal(|| false);
386    let mut source_failed = use_signal(|| false);
387    let source_token = use_hook(|| state.borrow().generation);
388    let source = use_hook(|| Rc::new(RefCell::new(None::<SourceChannel>)));
389    let closing = source.clone();
390    let dropped = state.clone();
391    use_drop(move || {
392        dropped.borrow_mut().retire();
393        closing.borrow_mut().take();
394    });
395    let failed_locale_state = state.clone();
396    let failed_locale_source = source.clone();
397    let locale_failure = use_callback(move |failure: InputError| {
398        failed_locale_state.borrow_mut().lose_locale();
399        visible.set(value.peek().clone().unwrap_or_default());
400        ready.set(false);
401        let reset_error = failed_locale_source
402            .borrow_mut()
403            .as_mut()
404            .and_then(|source| {
405                source
406                    .reset(value.peek().as_deref().unwrap_or_default(), true, false)
407                    .err()
408            });
409        deliver(UiEffect::Report(failure), error, on_value, on_error);
410        if let Some(message) = reset_error {
411            deliver(
412                UiEffect::Report(InputError::EventSource(message)),
413                error,
414                on_value,
415                on_error,
416            );
417        }
418    });
419
420    let locale = props.locale.clone();
421    let locale_source = source.clone();
422    let resolving = state.clone();
423    use_effect(use_reactive!(|locale| {
424        let state = resolving.clone();
425        let locale_source = locale_source.clone();
426        let epoch = {
427            let mut state = state.borrow_mut();
428            state.epoch = state.epoch.checked_add(1).expect("locale epochs exhausted");
429            state.epoch
430        };
431        spawn(async move {
432            let result = async {
433                let script = number_locale_script(locale.as_deref())?;
434                decode_locale_reply(&eval_reply(&script).await?)
435            }
436            .await;
437            let failure = {
438                let mut state = state.borrow_mut();
439                if state.retired || state.epoch != epoch {
440                    return;
441                }
442                match result {
443                    Ok(locale) => {
444                        state.locale = Some(locale);
445                        state.sync(
446                            value.peek().as_deref().unwrap_or_default(),
447                            *disabled.peek(),
448                            *readonly.peek(),
449                            kind,
450                        );
451                        publish(&state, visible);
452                        ready.set(true);
453                        None
454                    }
455                    Err(failure) => {
456                        state.lose_locale();
457                        visible.set(value.peek().clone().unwrap_or_default());
458                        if let Some(source) = locale_source.borrow_mut().as_mut()
459                            && let Err(message) = source.reset(
460                                value.peek().as_deref().unwrap_or_default(),
461                                true,
462                                false,
463                            )
464                        {
465                            on_error.call(InputError::EventSource(message));
466                        }
467                        Some(failure)
468                    }
469                }
470            };
471            if let Some(failure) = failure {
472                ready.set(false);
473                error.set(Some(failure.clone()));
474                on_error.call(failure);
475            } else {
476                if matches!(*error.peek(), Some(InputError::Locale(_))) {
477                    error.set(None);
478                }
479                format_model(state, visible, error, kind, locale_failure);
480            }
481        });
482    }));
483
484    let updating = state.clone();
485    let resetting = source.clone();
486    let source_flags = use_hook(|| Rc::new(RefCell::new(None)));
487    use_effect(move || {
488        let canonical = value.read();
489        let disabled = disabled();
490        let readonly = readonly();
491        {
492            let mut state = updating.borrow_mut();
493            let discarded = state.sync(
494                canonical.as_deref().unwrap_or_default(),
495                disabled,
496                readonly,
497                kind,
498            );
499            if discard_error(discarded, error.peek().as_ref()) {
500                error.set(None);
501            }
502            if state.locale.is_some() {
503                publish(&state, visible);
504            } else {
505                visible.set(canonical.clone().unwrap_or_default());
506            }
507        }
508        let flags = (disabled, readonly, ready());
509        if source_flags.borrow().as_ref() != Some(&flags) {
510            *source_flags.borrow_mut() = Some(flags);
511            if let Some(source) = resetting.borrow_mut().as_mut()
512                && let Err(message) = source.reset(&visible.peek(), disabled || !flags.2, readonly)
513            {
514                let failure = InputError::EventSource(message);
515                error.set(Some(failure.clone()));
516                on_error.call(failure);
517            }
518        }
519        format_model(updating.clone(), visible, error, kind, locale_failure);
520    });
521
522    let event_state = state.clone();
523    let native = use_callback(move |event: DraftEvent| {
524        if *disabled.peek() || *readonly.peek() || !*ready.peek() {
525            return;
526        }
527        let blur = matches!(event, DraftEvent::Blur);
528        let effect = {
529            let mut state = event_state.borrow_mut();
530            let effect = state.event(event, kind, optional);
531            publish(&state, visible);
532            effect
533        };
534        deliver(effect, error, on_value, on_error);
535        if blur {
536            if discard_error(true, error.peek().as_ref()) {
537                error.set(None);
538            }
539            format_model(event_state.clone(), visible, error, kind, locale_failure);
540        }
541    });
542    let step_state = state.clone();
543    let step = props.step.clone();
544    let range = props.range;
545    let stepping = use_callback(move |increase: bool| {
546        if !*ready.peek() || *source_failed.peek() {
547            return;
548        }
549        let mut state = step_state.borrow_mut();
550        state.sync(
551            value.peek().as_deref().unwrap_or_default(),
552            *disabled.peek(),
553            *readonly.peek(),
554            kind,
555        );
556        let effect = step_effect(
557            &state,
558            kind,
559            &step,
560            increase,
561            *disabled.peek(),
562            *readonly.peek(),
563            range.peek().as_ref(),
564        );
565        drop(state);
566        deliver(effect, error, on_value, on_error);
567    });
568    let receiving = source.clone();
569    let source_state = state.clone();
570    let receive = use_callback(move |result: Result<SourceFrame, String>| {
571        let frame = match result {
572            Ok(frame) if frame.action != "fatal" => frame,
573            result => {
574                let message = match result {
575                    Ok(frame) => frame.message,
576                    Err(message) => message,
577                };
578                source_failed.set(true);
579                receiving.borrow_mut().take();
580                deliver(
581                    UiEffect::Report(InputError::EventSource(message)),
582                    error,
583                    on_value,
584                    on_error,
585                );
586                return;
587            }
588        };
589        let accepted = receiving
590            .borrow_mut()
591            .as_mut()
592            .is_some_and(|source| source.accept(&frame, source_token));
593        if !accepted {
594            return;
595        }
596        match frame.action.as_str() {
597            "error" => deliver(
598                UiEffect::Report(InputError::EventSource(frame.message)),
599                error,
600                on_value,
601                on_error,
602            ),
603            "ready" => {}
604            "focus" => native.call(DraftEvent::Focus),
605            "blur" => native.call(DraftEvent::Blur),
606            "start" => native.call(DraftEvent::CompositionStart),
607            "draft" | "input" => native.call(DraftEvent::Input(frame.value)),
608            "end" => native.call(DraftEvent::CompositionEnd(frame.value)),
609            "cancel" => native.call(DraftEvent::CompositionCancel),
610            "up" | "down" if !source_state.borrow().composing => {
611                stepping.call(frame.action == "up")
612            }
613            "up" | "down" => {}
614            _ => deliver(
615                UiEffect::Report(InputError::EventSource(
616                    "Unknown numeric source action".into(),
617                )),
618                error,
619                on_value,
620                on_error,
621            ),
622        }
623        // Retirement must restore native text even when the reactive display is unchanged.
624        if matches!(frame.action.as_str(), "ready" | "blur" | "cancel" | "error")
625            && let Some(source) = receiving.borrow().as_ref()
626            && let Err(message) = source.display(&visible.peek())
627        {
628            deliver(
629                UiEffect::Report(InputError::EventSource(message)),
630                error,
631                on_value,
632                on_error,
633            );
634        }
635    });
636    let starting = source.clone();
637    use_effect(move || {
638        if starting.borrow().is_none() && !*source_failed.peek() {
639            *starting.borrow_mut() = Some(SourceChannel::start(source_token, receive));
640        }
641    });
642    let displaying = source.clone();
643    use_effect(move || {
644        let text = visible.read();
645        if let Some(source) = displaying.borrow().as_ref()
646            && let Err(message) = source.display(&text)
647        {
648            deliver(
649                UiEffect::Report(InputError::EventSource(message)),
650                error,
651                on_value,
652                on_error,
653            );
654        }
655    });
656    let error_text = error.read().as_ref().map(error_message);
657    let invalid = (props.invalid)() || error_text.is_some();
658    let blocked = (props.disabled)() || (props.readonly)() || !ready() || source_failed();
659    let current = props.value.read();
660    let range = props.range.read();
661    let at_bound = |increase| {
662        current.as_deref().is_some_and(|current| {
663            matches!(
664                bounded_step(current, kind, &props.step, increase, range.as_ref()),
665                Ok(None)
666            )
667        })
668    };
669    let up_blocked = blocked || at_bound(true);
670    let down_blocked = blocked || at_bound(false);
671    let readonly = (props.readonly)();
672    let controls = if readonly {
673        format!("{} {}", Styles::controls, Styles::readonly)
674    } else {
675        Styles::controls.to_string()
676    };
677    let described_by = if readonly {
678        format!("{}-error", props.id)
679    } else {
680        format!("{0}-help {0}-error", props.id)
681    };
682    rsx! {
683        div { class: Styles::editor,
684            Label { html_for: props.id.clone(), "{props.label}" }
685            div { class: controls,
686                Input {
687                    id: props.id.clone(), r#type: "text", inputmode: "decimal",
688                    // The native source owns text; volatile value attributes overwrite local drafts.
689                    disabled: (props.disabled)() || !ready() || source_failed(), readonly,
690                    "data-adam-number-source": "{source_token}",
691                    "aria-invalid": "{invalid}",
692                    "aria-describedby": described_by,
693                }
694                if !readonly { div { class: Styles::stepper,
695                    Button {
696                        r#type: "button", variant: ButtonVariant::Ghost, disabled: up_blocked,
697                        "aria-label": "Increase {props.label}", onclick: move |_| stepping.call(true),
698                        "+"
699                    }
700                    Button {
701                        r#type: "button", variant: ButtonVariant::Ghost, disabled: down_blocked,
702                        "aria-label": "Decrease {props.label}", onclick: move |_| stepping.call(false),
703                        "−"
704                    }
705                } }
706            }
707            if !readonly {
708                small { id: "{props.id}-help", class: Styles::visually_hidden,
709                    "Enter a number. Arrow Up and Arrow Down move to the next multiple of {props.step}."
710                }
711            }
712            small { id: "{props.id}-error", role: "status",
713                if let Some(message) = error_text { "{message}" }
714                else if (props.invalid)() { "The model rejected this value." }
715            }
716        }
717    }
718}
719
720/// Computes checked stepping without submitting nonfinite or blocked values.
721///
722/// The inclusive range blocks nudges, while model filters validate submissions.
723/// - Complexity: O(value + step + range bytes) time and space.
724fn step_effect(
725    state: &EditorState,
726    kind: NumberKind,
727    step: &str,
728    increase: bool,
729    disabled: bool,
730    readonly: bool,
731    range: Option<&NumericRange>,
732) -> UiEffect {
733    if state.retired || disabled || readonly || state.composing {
734        return UiEffect::None;
735    }
736    if state.locale.is_none() {
737        return UiEffect::None;
738    }
739    match bounded_step(state.draft.canonical(), kind, step, increase, range) {
740        Ok(Some(value)) => UiEffect::Submit(Some(value)),
741        Ok(None) => UiEffect::None,
742        Err(failure) => UiEffect::Report(failure),
743    }
744}
745
746/// Computes the next step if it lies within the inclusive range.
747///
748/// - Complexity: O(value + step + range bytes) time and space.
749///
750/// # Errors
751/// Returns numeric input errors for invalid steps, transitions, or bounds.
752fn bounded_step(
753    current: &str,
754    kind: NumberKind,
755    step: &str,
756    increase: bool,
757    range: Option<&NumericRange>,
758) -> Result<Option<String>, InputError> {
759    let Some(range) = range else {
760        return step_number(current, kind, step, increase).map(Some);
761    };
762    validate_canonical_number(&range.min, kind)?;
763    validate_canonical_number(&range.max, kind)?;
764    let stepped = step_number(current, kind, step, increase);
765    if matches!(stepped, Err(InputError::TypeRange { .. })) {
766        validate_canonical_number(current, kind)?;
767        step_number("0", kind, step, true)?;
768    }
769    let text = stepped.as_deref().unwrap_or(current);
770    macro_rules! compare {
771        ($ty:ty) => {{
772            let parse = |text: &str| -> Result<$ty, InputError> {
773                text.parse::<$ty>().map_err(|_| InputError::TypeRange {
774                    kind,
775                    value: text.into(),
776                })
777            };
778            let min = parse(&range.min)?;
779            let max = parse(&range.max)?;
780            if min > max {
781                return Err(InputError::Lexical(
782                    "numeric range minimum exceeds maximum".into(),
783                ));
784            }
785            let value = parse(text)?;
786            (
787                value >= min && value <= max,
788                if increase { value >= max } else { value <= min },
789            )
790        }};
791    }
792    let (inside, at_limit) = match kind {
793        NumberKind::Signed(_) => compare!(i128),
794        NumberKind::Unsigned(_) => compare!(u128),
795        NumberKind::F32 => compare!(f32),
796        NumberKind::F64 => compare!(f64),
797    };
798    match stepped {
799        Ok(candidate) => Ok(inside.then_some(candidate)),
800        Err(InputError::TypeRange { .. })
801            if matches!(kind, NumberKind::Signed(_) | NumberKind::Unsigned(_)) || at_limit =>
802        {
803            Ok(None)
804        }
805        Err(error) => Err(error),
806    }
807}
808
809/// Returns a readable input diagnostic without hiding its category.
810///
811/// - Complexity: O(diagnostic bytes) time and space.
812fn error_message(error: &InputError) -> String {
813    match error {
814        InputError::Lexical(value) => format!("Invalid number: {value}"),
815        InputError::TypeRange { kind, value } => format!("{value} is outside {kind:?}."),
816        InputError::UnsupportedEditor(message) => message.clone(),
817        InputError::Locale(message) => format!("Number locale error: {message}"),
818        InputError::EventSource(message) => format!("Number event source error: {message}"),
819    }
820}
821
822/// Clears only errors belonging to a discarded draft, retaining locale/support diagnostics.
823fn discard_error(discarded: bool, error: Option<&InputError>) -> bool {
824    discarded
825        && matches!(
826            error,
827            Some(InputError::Lexical(_) | InputError::TypeRange { .. })
828        )
829}
830
831/// Contains a finite, representable official slider domain and controlled handle.
832#[derive(Clone, Copy, PartialEq)]
833struct SliderDomain {
834    value: f64,
835    min: f64,
836    max: f64,
837    step: f64,
838}
839
840/// Selects only float or at-most-32-bit integer domains that the official slider represents.
841///
842/// Out-of-range and nonfinite model values keep the exact editor, never a clamped handle.
843/// - Complexity: O(value + range + step bytes) time and O(1) space.
844fn slider_domain(
845    kind: NumberKind,
846    value: Option<&str>,
847    range: Option<&NumericRange>,
848    step: &str,
849) -> Option<SliderDomain> {
850    if !matches!(
851        kind,
852        NumberKind::F32
853            | NumberKind::F64
854            | NumberKind::Signed(8 | 16 | 32)
855            | NumberKind::Unsigned(8 | 16 | 32)
856    ) {
857        return None;
858    }
859    let range = range?;
860    let domain = SliderDomain {
861        value: value?.parse().ok()?,
862        min: range.min.parse().ok()?,
863        max: range.max.parse().ok()?,
864        step: step.parse().ok()?,
865    };
866    (domain.value.is_finite()
867        && domain.min.is_finite()
868        && domain.max.is_finite()
869        && (domain.max - domain.min).is_finite()
870        && domain.step.is_finite()
871        && domain.step > 0.0
872        && domain.min < domain.max
873        && domain.value >= domain.min
874        && domain.value <= domain.max)
875        .then_some(domain)
876}
877
878/// Validates an official slider aspiration without clamping or admitting non-numbers.
879///
880/// - Complexity: O(canonical bytes) time and space.
881fn slider_effect(value: f64, kind: NumberKind, blocked: bool) -> UiEffect {
882    if blocked {
883        return UiEffect::None;
884    }
885    let canonical = value.to_string();
886    if !value.is_finite() {
887        return UiEffect::Report(InputError::Lexical(canonical));
888    }
889    let valid = match kind {
890        NumberKind::F64 => true,
891        NumberKind::F32 => canonical
892            .parse::<f32>()
893            .is_ok_and(|value| value.is_finite()),
894        NumberKind::Signed(8 | 16 | 32) | NumberKind::Unsigned(8 | 16 | 32) => {
895            kind.range().is_ok_and(|range| {
896                value.fract() == 0.0
897                    && value >= range.min.parse::<f64>().unwrap()
898                    && value <= range.max.parse::<f64>().unwrap()
899            })
900        }
901        _ => false,
902    };
903    if valid {
904        UiEffect::Submit(Some(canonical))
905    } else {
906        UiEffect::Report(InputError::TypeRange {
907            kind,
908            value: canonical,
909        })
910    }
911}
912
913/// Composes the official slider with the exact editor and shared canonical callbacks.
914///
915/// Wide integers, absent bounds and values outside the handle domain retain only
916/// the editor. Bounds never rewrite the visible model value.
917///
918/// - Complexity: O(value + draft + range + locale bytes) per transition.
919///
920/// # Examples
921/// ```
922/// use adam_web_ui::{components::NumericSlider, input::{NumberKind, NumericRange}};
923/// use dioxus::prelude::*;
924/// fn app() -> Element {
925///     let mut value = use_signal(|| Some("12".to_string()));
926///     let range = use_signal(|| Some(NumericRange { min: "0".into(), max: "100".into() }));
927///     let flags = use_signal(|| false);
928///     rsx! { NumericSlider {
929///         id: "amount", label: "Amount", value, range, kind: NumberKind::Signed(32),
930///         step: "1", disabled: flags, readonly: flags, invalid: flags,
931///         locale: None, optional: false,
932///         on_value: move |v| value.set(v), on_error: |_| {},
933///     } }
934/// }
935/// ```
936#[component]
937pub fn NumericSlider(props: NumericEditorProps) -> Element {
938    let domain = {
939        let value = props.value.read();
940        let range = props.range.read();
941        slider_domain(props.kind, value.as_deref(), range.as_ref(), &props.step)
942    };
943    let (kind, disabled, readonly, on_value, on_error) = (
944        props.kind,
945        props.disabled,
946        props.readonly,
947        props.on_value,
948        props.on_error,
949    );
950    rsx! {
951        div { class: Styles::slider,
952            if let Some(domain) = domain {
953                Slider {
954                    value: Some(domain.value), min: domain.min, max: domain.max, step: domain.step,
955                    disabled: (props.disabled)() || (props.readonly)(),
956                    label: Some(props.label.clone()),
957                    on_value_change: move |value| {
958                        match slider_effect(value, kind,
959                            *disabled.peek() || *readonly.peek()) {
960                            UiEffect::Submit(value) => on_value.call(value),
961                            UiEffect::Report(error) => on_error.call(error),
962                            UiEffect::None => {}
963                        }
964                    },
965                }
966            }
967            NumericEditor { ..props }
968        }
969    }
970}
971
972#[cfg(test)]
973#[path = "tests.rs"]
974mod tests;