1
//! Numeric input widget that wraps `TextInput` with numeric validation.
2
//!
3
//! Exports `NumberInput`, `NumberInputState`, and callback types
4
//! (`NumberInputOnValueChangeCallbackType`, `NumberInputOnFocusLostCallbackType`).
5
//! Internally delegates to `TextInput` and validates that the entered text
6
//! parses as an `f32` within the configured `min`/`max` range.
7

            
8
use std::string::String;
9

            
10
use azul_core::{
11
    callbacks::{CoreCallbackData, Update},
12
    dom::Dom,
13
    refany::RefAny,
14
};
15
use azul_css::dynamic_selector::OptionCssPropertyWithConditionsVec;
16
#[allow(clippy::wildcard_imports)]
17
// widget/render module pulls in the css property/value types it builds with
18
use azul_css::{
19
    dynamic_selector::CssPropertyWithConditionsVec,
20
    props::{
21
        basic::*,
22
        layout::*,
23
        property::{CssProperty, *},
24
        style::*,
25
    },
26
    OptionString, *,
27
};
28

            
29
use crate::{
30
    callbacks::{Callback, CallbackInfo},
31
    widgets::text_input::{
32
        OnTextInputReturn, TextInput, TextInputOnFocusLostCallback,
33
        TextInputOnFocusLostCallbackType, TextInputOnTextInputCallback,
34
        TextInputOnTextInputCallbackType, TextInputOnVirtualKeyDownCallback,
35
        TextInputOnVirtualKeyDownCallbackType, TextInputState, TextInputValid,
36
    },
37
};
38

            
39
/// Callback type invoked when the numeric value changes.
40
pub type NumberInputOnValueChangeCallbackType =
41
    extern "C" fn(RefAny, CallbackInfo, NumberInputState) -> Update;
42
impl_widget_callback!(
43
    NumberInputOnValueChange,
44
    OptionNumberInputOnValueChange,
45
    NumberInputOnValueChangeCallback,
46
    NumberInputOnValueChangeCallbackType
47
);
48

            
49
azul_core::impl_managed_callback! {
50
    wrapper:        NumberInputOnValueChangeCallback,
51
    info_ty:        CallbackInfo,
52
    return_ty:      Update,
53
    default_ret:    Update::DoNothing,
54
    invoker_static: NUMBER_INPUT_ON_VALUE_CHANGE_INVOKER,
55
    invoker_ty:     AzNumberInputOnValueChangeCallbackInvoker,
56
    thunk_fn:       az_number_input_on_value_change_callback_thunk,
57
    setter_fn:      AzApp_setNumberInputOnValueChangeCallbackInvoker,
58
    from_handle_fn: AzNumberInputOnValueChangeCallback_createFromHostHandle,
59
    extra_args:     [ state: NumberInputState ],
60
}
61

            
62
/// Callback type invoked when the number input loses focus.
63
pub type NumberInputOnFocusLostCallbackType =
64
    extern "C" fn(RefAny, CallbackInfo, NumberInputState) -> Update;
65
impl_widget_callback!(
66
    NumberInputOnFocusLost,
67
    OptionNumberInputOnFocusLost,
68
    NumberInputOnFocusLostCallback,
69
    NumberInputOnFocusLostCallbackType
70
);
71

            
72
azul_core::impl_managed_callback! {
73
    wrapper:        NumberInputOnFocusLostCallback,
74
    info_ty:        CallbackInfo,
75
    return_ty:      Update,
76
    default_ret:    Update::DoNothing,
77
    invoker_static: NUMBER_INPUT_ON_FOCUS_LOST_INVOKER,
78
    invoker_ty:     AzNumberInputOnFocusLostCallbackInvoker,
79
    thunk_fn:       az_number_input_on_focus_lost_callback_thunk,
80
    setter_fn:      AzApp_setNumberInputOnFocusLostCallbackInvoker,
81
    from_handle_fn: AzNumberInputOnFocusLostCallback_createFromHostHandle,
82
    extra_args:     [ state: NumberInputState ],
83
}
84

            
85
/// A numeric input widget that wraps `TextInput` with `f32` validation.
86
#[derive(Debug, Default, Clone, PartialEq)]
87
#[repr(C)]
88
pub struct NumberInput {
89
    pub number_input_state: NumberInputStateWrapper,
90
    pub text_input: TextInput,
91
    /// The widget's own CSS, or `None` for "no opinion".
92
    ///
93
    /// A `NumberInput` draws nothing of its own — the [`TextInput`] it wraps carries
94
    /// the container and label styling — so the resolved default here is empty.
95
    /// The field exists so a caller can style the outer widget, and `None` keeps
96
    /// that distinct from `Some(empty)`, which asks for no properties at all.
97
    pub style: OptionCssPropertyWithConditionsVec,
98
    /// What this control is CALLED, for assistive technology.
99
    ///
100
    /// Carried by the WIDGET so it knows at build time whether it was named;
101
    /// forwarded into the accessibility declaration it already builds.
102
    pub accessibility_name: OptionString,
103
}
104

            
105
/// Wraps `NumberInputState` together with its value-change and focus-lost callbacks.
106
#[derive(Debug, Default, Clone, PartialEq)]
107
#[repr(C)]
108
pub struct NumberInputStateWrapper {
109
    pub inner: NumberInputState,
110
    pub on_value_change: OptionNumberInputOnValueChange,
111
    pub on_focus_lost: OptionNumberInputOnFocusLost,
112
}
113

            
114
/// State of a `NumberInput`: the current and previous value, plus allowed range.
115
#[derive(Copy, Debug, Clone, PartialEq)]
116
#[repr(C)]
117
pub struct NumberInputState {
118
    /// The value before the most recent change.
119
    pub previous: f32,
120
    /// The current numeric value.
121
    pub number: f32,
122
    /// Minimum allowed value (inclusive).
123
    pub min: f32,
124
    /// Maximum allowed value (inclusive).
125
    pub max: f32,
126
}
127

            
128
impl Default for NumberInputState {
129
1616
    fn default() -> Self {
130
1616
        Self {
131
1616
            previous: 0.0,
132
1616
            number: 0.0,
133
1616
            min: core::f32::MIN,
134
1616
            max: core::f32::MAX,
135
1616
        }
136
1616
    }
137
}
138

            
139
impl NumberInput {
140
    /// Creates a new `NumberInput` with the given initial value.
141
    /// Name this control for assistive technology.
142
    #[must_use]
143
420
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
144
420
        self.accessibility_name = Some(name.into()).into();
145
420
        self
146
420
    }
147

            
148
    /// The CSS this widget renders with.
149
    ///
150
    /// Empty unless a caller set one: the styling a `NumberInput` shows comes from
151
    /// its inner [`TextInput`], whose own resolvers answer for it.
152
    #[must_use]
153
2
    pub fn resolved_style(&self) -> CssPropertyWithConditionsVec {
154
2
        self.style.clone().into_option().unwrap_or_default()
155
2
    }
156

            
157
    #[must_use]
158
531
    pub fn create(input: f32) -> Self {
159
531
        Self {
160
531
            number_input_state: NumberInputStateWrapper {
161
531
                inner: NumberInputState {
162
531
                    number: input,
163
531
                    ..Default::default()
164
531
                },
165
531
                ..Default::default()
166
531
            },
167
531
            ..Default::default()
168
531
        }
169
531
    }
170

            
171
3
    pub fn set_on_text_input<C: Into<TextInputOnTextInputCallback>>(
172
3
        &mut self,
173
3
        refany: RefAny,
174
3
        callback: C,
175
3
    ) {
176
3
        self.text_input.set_on_text_input(refany, callback);
177
3
    }
178

            
179
    #[must_use]
180
2
    pub fn with_on_text_input<C: Into<TextInputOnTextInputCallback>>(
181
2
        mut self,
182
2
        refany: RefAny,
183
2
        callback: C,
184
2
    ) -> Self {
185
2
        self.set_on_text_input(refany, callback);
186
2
        self
187
2
    }
188

            
189
3
    pub fn set_on_virtual_key_down<C: Into<TextInputOnVirtualKeyDownCallback>>(
190
3
        &mut self,
191
3
        refany: RefAny,
192
3
        callback: C,
193
3
    ) {
194
3
        self.text_input.set_on_virtual_key_down(refany, callback);
195
3
    }
196

            
197
    #[must_use]
198
2
    pub fn with_on_virtual_key_down<C: Into<TextInputOnVirtualKeyDownCallback>>(
199
2
        mut self,
200
2
        refany: RefAny,
201
2
        callback: C,
202
2
    ) -> Self {
203
2
        self.set_on_virtual_key_down(refany, callback);
204
2
        self
205
2
    }
206

            
207
429
    pub fn set_container_style(&mut self, style: CssPropertyWithConditionsVec) {
208
429
        self.text_input.container_style = OptionCssPropertyWithConditionsVec::Some(style);
209
429
    }
210

            
211
    #[must_use]
212
425
    pub fn with_container_style(mut self, style: CssPropertyWithConditionsVec) -> Self {
213
425
        self.set_container_style(style);
214
425
        self
215
425
    }
216

            
217
10
    pub fn set_label_style(&mut self, style: CssPropertyWithConditionsVec) {
218
10
        self.text_input.label_style = OptionCssPropertyWithConditionsVec::Some(style);
219
10
    }
220

            
221
    #[must_use]
222
6
    pub fn with_label_style(mut self, style: CssPropertyWithConditionsVec) -> Self {
223
6
        self.set_label_style(style);
224
6
        self
225
6
    }
226

            
227
    // Function called when the input has been parsed as a number
228
426
    pub fn set_on_value_change<C: Into<NumberInputOnValueChangeCallback>>(
229
426
        &mut self,
230
426
        refany: RefAny,
231
426
        callback: C,
232
426
    ) {
233
426
        self.number_input_state.on_value_change = Some(NumberInputOnValueChange {
234
426
            callback: callback.into(),
235
426
            refany,
236
426
        })
237
426
        .into();
238
426
    }
239

            
240
    #[must_use]
241
423
    pub fn with_on_value_change<C: Into<NumberInputOnValueChangeCallback>>(
242
423
        mut self,
243
423
        refany: RefAny,
244
423
        callback: C,
245
423
    ) -> Self {
246
423
        self.set_on_value_change(refany, callback);
247
423
        self
248
423
    }
249

            
250
7
    pub fn set_on_focus_lost<C: Into<NumberInputOnFocusLostCallback>>(
251
7
        &mut self,
252
7
        refany: RefAny,
253
7
        callback: C,
254
7
    ) {
255
7
        self.number_input_state.on_focus_lost = Some(NumberInputOnFocusLost {
256
7
            callback: callback.into(),
257
7
            refany,
258
7
        })
259
7
        .into();
260
7
    }
261

            
262
    #[must_use]
263
6
    pub fn with_on_focus_lost<C: Into<NumberInputOnFocusLostCallback>>(
264
6
        mut self,
265
6
        refany: RefAny,
266
6
        callback: C,
267
6
    ) -> Self {
268
6
        self.set_on_focus_lost(refany, callback);
269
6
        self
270
6
    }
271

            
272
    #[must_use]
273
2
    pub fn swap_with_default(&mut self) -> Self {
274
2
        let mut s = Self::create(0.0);
275
2
        core::mem::swap(&mut s, self);
276
2
        s
277
2
    }
278

            
279
    #[must_use]
280
479
    pub fn dom(mut self) -> Dom {
281
479
        let number_string = format!("{}", self.number_input_state.inner.number);
282
479
        self.text_input.text_input_state.inner.text = number_string
283
479
            .chars()
284
1381
            .map(|s| s as u32)
285
479
            .collect::<Vec<_>>()
286
479
            .into();
287
        // The caret goes with the value it belongs to.
288
        //
289
        // This rewrites the buffer from `number` on EVERY rebuild but used to
290
        // leave `cursor_pos` untouched — and a freshly built `TextInputState`
291
        // has `cursor_pos: 0`. So a rebuild left the caret claiming offset 0
292
        // over a value it had never seen, and the next keystroke was mirrored
293
        // in at the FRONT: clearing "42" and typing "33" produced "3342".
294
        // End-of-value is what a programmatic assignment means (it is where a
295
        // browser leaves the caret after setting `input.value`), and it is
296
        // where `default_on_focus_received` seeds it too.
297
479
        self.text_input.text_input_state.inner.cursor_pos =
298
479
            self.text_input.text_input_state.inner.text.len();
299

            
300
479
        let state = RefAny::new(self.number_input_state);
301

            
302
479
        let validate: TextInputOnTextInputCallbackType = validate_text_input;
303
479
        self.text_input.set_on_text_input(state.clone(), validate);
304
479
        let focus_lost: TextInputOnFocusLostCallbackType = on_focus_lost;
305
479
        self.text_input.set_on_focus_lost(state, focus_lost);
306
479
        self.text_input.dom()
307
479
    }
308
}
309

            
310
12
extern "C" fn on_focus_lost(
311
12
    mut refany: RefAny,
312
12
    info: CallbackInfo,
313
12
    _state: TextInputState,
314
12
) -> Update {
315
12
    let Some(mut refany) = refany.downcast_mut::<NumberInputStateWrapper>() else {
316
1
        return Update::DoNothing;
317
    };
318

            
319
11
    let number_input = &mut *refany;
320
11
    let onfocuslost = &mut number_input.on_focus_lost;
321
11
    let inner = number_input.inner;
322

            
323
11
    match onfocuslost.as_mut() {
324
10
        Some(NumberInputOnFocusLost { callback, refany }) => {
325
10
            (callback.cb)(refany.clone(), info, inner)
326
        }
327
1
        None => Update::DoNothing,
328
    }
329
12
}
330

            
331
/// Is `s` a PREFIX of some string `<f32 as FromStr>` accepts — i.e.
332
///
333
/// can it
334
/// still become a number with more characters? Grammar:
335
/// `[+-]? digits* ('.' digits*)? ([eE] [+-]? digits*)?`, with the exponent
336
/// allowed only after at least one mantissa digit (`e`, `.e` can never
337
/// become numbers, `1e` can). The empty buffer is a prefix of everything.
338
/// Deliberately NOT `str::parse` (which rejects every prefix) and
339
/// deliberately not accepting `inf` / `nan`, which the widget never wants.
340
104
fn is_float_prefix(s: &str) -> bool {
341
104
    let b = s.as_bytes();
342
104
    let mut i = 0;
343
104
    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
344
15
        i += 1;
345
89
    }
346
104
    let mut mantissa_digits = 0usize;
347
143
    while i < b.len() && b[i].is_ascii_digit() {
348
39
        i += 1;
349
39
        mantissa_digits += 1;
350
39
    }
351
104
    if i < b.len() && b[i] == b'.' {
352
23
        i += 1;
353
33
        while i < b.len() && b[i].is_ascii_digit() {
354
10
            i += 1;
355
10
            mantissa_digits += 1;
356
10
        }
357
81
    }
358
104
    if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
359
21
        if mantissa_digits == 0 {
360
9
            return false;
361
12
        }
362
12
        i += 1;
363
12
        if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
364
9
            i += 1;
365
9
        }
366
12
        while i < b.len() && b[i].is_ascii_digit() {
367
            i += 1;
368
        }
369
83
    }
370
95
    i == b.len()
371
104
}
372

            
373
/// Clamps `value` into `[min, max]`, tolerating the degenerate bounds that
374
/// `f32::clamp` panics on: an inverted range (`min > max`) is swapped and a NaN
375
/// bound is dropped (both NaN → value untouched). `min`/`max` are `pub` fields on
376
/// a `#[repr(C)]` `NumberInputState` reachable across the C/FFI boundary, so a
377
/// caller can invert or NaN them; a panic here would unwind across that boundary.
378
80
fn clamp_to_range(value: f32, min: f32, max: f32) -> f32 {
379
80
    let (lo, hi) = match (min.is_nan(), max.is_nan()) {
380
1
        (true, true) => return value,
381
1
        (true, false) => (max, max),
382
1
        (false, true) => (min, min),
383
77
        (false, false) if min <= max => (min, max),
384
2
        (false, false) => (max, min),
385
    };
386
79
    value.clamp(lo, hi)
387
80
}
388

            
389
155
extern "C" fn validate_text_input(
390
155
    mut refany: RefAny,
391
155
    info: CallbackInfo,
392
155
    state: TextInputState,
393
155
) -> OnTextInputReturn {
394
155
    let Some(mut refany) = refany.downcast_mut::<NumberInputStateWrapper>() else {
395
1
        return OnTextInputReturn {
396
1
            update: Update::DoNothing,
397
1
            valid: TextInputValid::Yes,
398
1
        };
399
    };
400

            
401
154
    let validated_input: String = state
402
154
        .text
403
154
        .iter()
404
40656
        .filter_map(|c| core::char::from_u32(*c))
405
40652
        .map(|c| if c == ',' { '.' } else { c })
406
154
        .collect();
407

            
408
154
    let Ok(validated_f32) = validated_input.parse::<f32>() else {
409
        // A buffer that is not a number YET but can become one — `-`, `.`,
410
        // `-.`, `1e-`, the empty buffer — must be allowed to exist in the
411
        // field: a number is typed one character at a time, and `-5` or `.5`
412
        // starts with a character that does not parse. Vetoing those
413
        // keystrokes made it impossible to enter a negative or fractional
414
        // number from scratch. The value stays what it was; the hook waits
415
        // for a complete number. A buffer that can never become a number
416
        // (`abc`, `1.2.3`, ` 1`) is still vetoed.
417
74
        if is_float_prefix(&validated_input) {
418
22
            return OnTextInputReturn {
419
22
                update: Update::DoNothing,
420
22
                valid: TextInputValid::Yes,
421
22
            };
422
52
        }
423
        // do not re-layout the entire screen,
424
        // but don't handle the character
425
52
        return OnTextInputReturn {
426
52
            update: Update::DoNothing,
427
52
            valid: TextInputValid::No,
428
52
        };
429
    };
430

            
431
80
    let number_input = &mut *refany;
432
80
    let onvaluechange = &mut number_input.on_value_change;
433
80
    let inner = &mut number_input.inner;
434

            
435
80
    inner.previous = inner.number;
436
80
    let clamped = clamp_to_range(validated_f32, inner.min, inner.max);
437
80
    inner.number = clamped;
438
80
    let inner_clone = *inner;
439

            
440
80
    let update = match onvaluechange.as_mut() {
441
3
        Some(NumberInputOnValueChange { callback, refany }) => {
442
3
            (callback.cb)(refany.clone(), info, inner_clone)
443
        }
444
77
        None => Update::DoNothing,
445
    };
446

            
447
80
    OnTextInputReturn {
448
80
        update,
449
80
        valid: TextInputValid::Yes,
450
80
    }
451
155
}
452

            
453
#[cfg(all(test, feature = "std"))]
454
#[allow(clippy::float_cmp, clippy::too_many_lines)]
455
mod autotest_generated {
456
    use std::{
457
        collections::BTreeMap,
458
        panic::{catch_unwind, AssertUnwindSafe},
459
        sync::{Arc, Mutex},
460
    };
461

            
462
    use azul_core::{
463
        dom::{DomId, DomNodeId},
464
        geom::OptionLogicalPosition,
465
        gl::OptionGlContextPtr,
466
        hit_test::ScrollPosition,
467
        refany::OptionRefAny,
468
        resources::RendererResources,
469
        styled_dom::NodeHierarchyItemId,
470
        window::{MonitorVec, RawWindowHandle},
471
    };
472
    use azul_css::dynamic_selector::CssPropertyWithConditions;
473
    use rust_fontconfig::FcFontCache;
474

            
475
    use super::*;
476
    #[cfg(feature = "icu")]
477
    use crate::icu::IcuLocalizerHandle;
478
    use crate::{
479
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
480
        widgets::text_input::TextInputStateWrapper,
481
        window::LayoutWindow,
482
        window_state::FullWindowState,
483
    };
484

            
485
    // ------------------------------------------------------------------
486
    // Sample values
487
    // ------------------------------------------------------------------
488

            
489
    /// Every finite `f32` the widget has to survive a format/parse round-trip on:
490
    /// both zeros (the sign of `-0.0` is the classic casualty), both ends of the
491
    /// range, the smallest normal, the smallest and largest subnormals, and `2^24`
492
    /// — the point where `f32` stops being able to count.
493
    fn finite_samples() -> [f32; 16] {
494
        [
495
            0.0,
496
            -0.0,
497
            1.0,
498
            -1.0,
499
            0.5,
500
            -0.5,
501
            42.25,
502
            -2.5,
503
            0.1,
504
            16_777_216.0,
505
            f32::MIN,
506
            f32::MAX,
507
            f32::MIN_POSITIVE,
508
            -f32::MIN_POSITIVE,
509
            f32::EPSILON,
510
            // smallest positive subnormal (~1.4e-45); written as bits so no float
511
            // literal in this file is ever out of range for `f32`.
512
            f32::from_bits(1),
513
        ]
514
    }
515

            
516
    /// Strings `<f32 as FromStr>` rejects outright AND that can never become a
517
    /// number however the user continues typing. None of them contains a
518
    /// comma, so the widget's `,` -> `.` rewrite cannot rescue any of them
519
    /// either. (Buffers that are merely incomplete live in `TRANSIENT_PREFIXES`.)
520
    const MALFORMED: [&str; 20] = [
521
        " ", // `from_str` does not trim
522
        " 1",
523
        "1 ",
524
        "\t1",
525
        "\n",
526
        "abc",
527
        "e",
528
        "e5",
529
        "E",
530
        "..",
531
        "--1",
532
        "1.2.3",
533
        "0x10", // hex is not float syntax
534
        "0b1",
535
        "1_000", // Rust *literal* syntax is not *parse* syntax
536
        "1/2",
537
        "1%",
538
        "½",          // vulgar fraction
539
        "∞",          // the symbol is not the word "inf"
540
        "1\u{200b}0", // zero-width space wedged between two digits
541
    ];
542

            
543
    /// Buffers `from_str` rejects that are PREFIXES of a number: the states a
544
    /// field passes through while `-5`, `.5`, `1e-3` or a replacement are
545
    /// typed. The widget must let them exist (keystroke accepted, value
546
    /// unchanged, hook silent) or a negative / fractional number can never be
547
    /// entered from scratch.
548
    const TRANSIENT_PREFIXES: [&str; 10] = [
549
        "", // the empty buffer: select-all + delete, then type
550
        "+", "-", ".", "-.", "+.", "1e", "1e+", "1e-", "1.5e-",
551
    ];
552

            
553
    /// Digits that are digits to a human but not to `from_str`.
554
    const NON_ASCII_DIGITS: [&str; 6] = [
555
        "١٢٣",    // Arabic-Indic
556
        "١٫٥",    // Arabic-Indic + the Arabic decimal separator
557
        "123", // fullwidth
558
        "𝟏",      // MATHEMATICAL BOLD DIGIT ONE
559
        "٣.5",    // mixed script
560
        "Ⅻ",      // roman numeral twelve
561
    ];
562

            
563
    /// Every spelling the Rust float parser accepts, paired with the value the widget
564
    /// must end up storing under the default range. `inf` / `-inf` are listed with
565
    /// their *clamped* results — saturating them is the widget's job, not the parser's.
566
    const ACCEPTED: [(&str, f32); 17] = [
567
        ("0", 0.0),
568
        ("-0", -0.0),
569
        ("+1", 1.0),
570
        ("1.", 1.0),
571
        (".5", 0.5),
572
        ("-.5", -0.5),
573
        ("1e3", 1000.0),
574
        ("1E3", 1000.0),
575
        ("1e+3", 1000.0),
576
        ("1e-3", 0.001),
577
        ("00042.2500", 42.25),
578
        ("inf", f32::MAX),
579
        ("infinity", f32::MAX),
580
        ("-inf", f32::MIN),
581
        ("nan", f32::NAN),
582
        ("NaN", f32::NAN),
583
        ("NAN", f32::NAN),
584
    ];
585

            
586
    // ------------------------------------------------------------------
587
    // Fixtures
588
    // ------------------------------------------------------------------
589

            
590
    /// Bit-exact float comparison — `-0.0 != 0.0` here, because losing the sign of a
591
    /// zero is exactly the kind of round-trip damage these tests are looking for.
592
    /// NaNs compare equal to each other: the widget renders every NaN as `"NaN"`, so
593
    /// the payload and sign cannot survive anyway.
594
    fn same(a: f32, b: f32) -> bool {
595
        if a.is_nan() || b.is_nan() {
596
            a.is_nan() && b.is_nan()
597
        } else {
598
            a.to_bits() == b.to_bits()
599
        }
600
    }
601

            
602
    /// A `NumberInputStateWrapper` with no hooks: `previous` starts at `0.0` so any
603
    /// write to it is visible.
604
    fn wrapper(number: f32, min: f32, max: f32) -> NumberInputStateWrapper {
605
        NumberInputStateWrapper {
606
            inner: NumberInputState {
607
                previous: 0.0,
608
                number,
609
                min,
610
                max,
611
            },
612
            on_value_change: OptionNumberInputOnValueChange::None,
613
            on_focus_lost: OptionNumberInputOnFocusLost::None,
614
        }
615
    }
616

            
617
    /// The widget's edit buffer, built from a `&str` the way `TextInput` builds it.
618
    fn text_state(text: &str) -> TextInputState {
619
        TextInputState {
620
            text: text.chars().map(|c| c as u32).collect::<Vec<_>>().into(),
621
            ..TextInputState::default()
622
        }
623
    }
624

            
625
    /// An edit buffer built from *raw* `u32` code units — the buffer is a `U32Vec`,
626
    /// so it can hold values that are not Unicode scalars at all.
627
    fn raw_text_state(units: &[u32]) -> TextInputState {
628
        TextInputState {
629
            text: units.to_vec().into(),
630
            ..TextInputState::default()
631
        }
632
    }
633

            
634
    /// The state currently stored behind a `NumberInputStateWrapper` payload.
635
    fn read(state: &RefAny) -> NumberInputState {
636
        let mut state = state.clone();
637
        let wrapper = state
638
            .downcast_ref::<NumberInputStateWrapper>()
639
            .expect("the payload must still be a NumberInputStateWrapper");
640
        wrapper.inner
641
    }
642

            
643
    /// Overwrites the stored value and clears the history, so one `LayoutWindow` can
644
    /// serve a whole table of cases.
645
    fn reset(state: &RefAny, number: f32) {
646
        let mut state = state.clone();
647
        let mut wrapper = state
648
            .downcast_mut::<NumberInputStateWrapper>()
649
            .expect("the payload must still be a NumberInputStateWrapper");
650
        wrapper.inner.number = number;
651
        wrapper.inner.previous = 0.0;
652
    }
653

            
654
    /// `n` properties lifted off the default container style — an easy way to mint
655
    /// style vectors that are pairwise distinct without hard-coding CSS.
656
    fn style(n: usize) -> CssPropertyWithConditionsVec {
657
        let all: Vec<CssPropertyWithConditions> = TextInput::default()
658
            .resolved_container_style()
659
            .as_slice()
660
            .to_vec();
661
        assert!(n <= all.len(), "not enough default properties to slice");
662
        CssPropertyWithConditionsVec::from_vec(all.into_iter().take(n).collect())
663
    }
664

            
665
    // ---- recording hooks --------------------------------------------------
666

            
667
    /// Records every `NumberInputState` a hook is handed, and answers with `ret`.
668
    struct Recorder {
669
        seen: Vec<NumberInputState>,
670
        ret: Update,
671
    }
672

            
673
    impl Recorder {
674
        fn new(ret: Update) -> Self {
675
            Self {
676
                seen: Vec::new(),
677
                ret,
678
            }
679
        }
680
    }
681

            
682
    extern "C" fn record_value_change(
683
        mut data: RefAny,
684
        _: CallbackInfo,
685
        state: NumberInputState,
686
    ) -> Update {
687
        let Some(mut log) = data.downcast_mut::<Recorder>() else {
688
            return Update::DoNothing;
689
        };
690
        log.seen.push(state);
691
        log.ret
692
    }
693

            
694
    // Deliberately *not* the same body as `record_value_change`: two hooks with
695
    // identical bodies can be folded onto one symbol, and these two have to stay
696
    // distinguishable.
697
    extern "C" fn record_focus_lost(
698
        mut data: RefAny,
699
        _: CallbackInfo,
700
        state: NumberInputState,
701
    ) -> Update {
702
        match data.downcast_mut::<Recorder>() {
703
            Some(mut log) => {
704
                log.seen.push(state);
705
                log.ret
706
            }
707
            None => Update::DoNothing,
708
        }
709
    }
710

            
711
    /// A user-supplied text-input hook that accepts *everything*: if `dom()` kept it,
712
    /// `"abc"` would come back as `TextInputValid::Yes`.
713
    extern "C" fn accept_everything(
714
        _: RefAny,
715
        _: CallbackInfo,
716
        _: TextInputState,
717
    ) -> OnTextInputReturn {
718
        OnTextInputReturn {
719
            update: Update::RefreshDomAllWindows,
720
            valid: TextInputValid::Yes,
721
        }
722
    }
723

            
724
    /// A user-supplied virtual-key hook with a signature no other hook here returns.
725
    extern "C" fn reject_everything(
726
        _: RefAny,
727
        _: CallbackInfo,
728
        _: TextInputState,
729
    ) -> OnTextInputReturn {
730
        OnTextInputReturn {
731
            update: Update::RefreshDomAllWindows,
732
            valid: TextInputValid::No,
733
        }
734
    }
735

            
736
    fn recorded(recorder: &RefAny) -> Vec<NumberInputState> {
737
        let mut recorder = recorder.clone();
738
        let log = recorder
739
            .downcast_ref::<Recorder>()
740
            .expect("the payload must still be a Recorder");
741
        log.seen.clone()
742
    }
743

            
744
    fn wrapper_with_value_hook(
745
        number: f32,
746
        min: f32,
747
        max: f32,
748
        recorder: &RefAny,
749
    ) -> NumberInputStateWrapper {
750
        NumberInputStateWrapper {
751
            on_value_change: Some(NumberInputOnValueChange {
752
                refany: recorder.clone(),
753
                callback: (record_value_change as NumberInputOnValueChangeCallbackType).into(),
754
            })
755
            .into(),
756
            ..wrapper(number, min, max)
757
        }
758
    }
759

            
760
    fn wrapper_with_focus_hook(
761
        number: f32,
762
        min: f32,
763
        max: f32,
764
        recorder: &RefAny,
765
    ) -> NumberInputStateWrapper {
766
        NumberInputStateWrapper {
767
            on_focus_lost: Some(NumberInputOnFocusLost {
768
                refany: recorder.clone(),
769
                callback: (record_focus_lost as NumberInputOnFocusLostCallbackType).into(),
770
            })
771
            .into(),
772
            ..wrapper(number, min, max)
773
        }
774
    }
775

            
776
    // ---- CallbackInfo harness --------------------------------------------
777

            
778
    /// Runs `f` with a real `CallbackInfo` over an empty `LayoutWindow`. Neither
779
    /// `validate_text_input` nor `on_focus_lost` queries the DOM through it — they
780
    /// only hand it to the user's hook — so an empty window is enough. `CallbackInfo`
781
    /// is `Copy`, so a whole table of cases can share one window (building one per
782
    /// case would dominate the runtime).
783
    fn with_info<R>(f: impl FnOnce(CallbackInfo) -> R) -> R {
784
        let layout_window =
785
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
786
        let renderer_resources = RendererResources::default();
787
        let previous_window_state: Option<FullWindowState> = None;
788
        let current_window_state = FullWindowState::default();
789
        let gl_context = OptionGlContextPtr::None;
790
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
791
            BTreeMap::new();
792
        let window_handle = RawWindowHandle::Unsupported;
793
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
794

            
795
        let ref_data = CallbackInfoRefData {
796
            layout_window: &layout_window,
797
            renderer_resources: &renderer_resources,
798
            previous_window_state: &previous_window_state,
799
            current_window_state: &current_window_state,
800
            gl_context: &gl_context,
801
            current_scroll_manager: &scroll_states,
802
            current_window_handle: &window_handle,
803
            system_callbacks: &system_callbacks,
804
            system_style: Arc::new(system::SystemStyle::default()),
805
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
806
            #[cfg(feature = "icu")]
807
            icu_localizer: IcuLocalizerHandle::default(),
808
            ctx: OptionRefAny::None,
809
        };
810

            
811
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
812

            
813
        let info = CallbackInfo::new(
814
            &ref_data,
815
            &changes,
816
            DomNodeId {
817
                dom: DomId::ROOT_ID,
818
                node: NodeHierarchyItemId::NONE,
819
            },
820
            OptionLogicalPosition::None,
821
            OptionLogicalPosition::None,
822
        );
823

            
824
        f(info)
825
    }
826

            
827
    /// One edit delivered to `validate_text_input`; returns its answer plus the state
828
    /// it left behind.
829
    fn validate_one(state: &RefAny, text: &str) -> (OnTextInputReturn, NumberInputState) {
830
        with_info(|info| {
831
            let r = validate_text_input(state.clone(), info, text_state(text));
832
            (r, read(state))
833
        })
834
    }
835

            
836
    /// One edit made of raw code units (which need not be Unicode scalars).
837
    fn validate_raw(state: &RefAny, units: &[u32]) -> (OnTextInputReturn, NumberInputState) {
838
        with_info(|info| {
839
            let r = validate_text_input(state.clone(), info, raw_text_state(units));
840
            (r, read(state))
841
        })
842
    }
843

            
844
    fn focus_lost(state: &RefAny, text: &str) -> Update {
845
        with_info(|info| on_focus_lost(state.clone(), info, text_state(text)))
846
    }
847

            
848
    // ---- DOM probes -------------------------------------------------------
849

            
850
    /// Flattened child indices of `TextInput::dom()`.
851
    const PLACEHOLDER: usize = 0;
852
    /// The value block is the TextInput container's ONLY child now.
853
    const LABEL: usize = 0;
854

            
855
    fn dataset_of(dom: &Dom) -> RefAny {
856
        dom.root
857
            .get_dataset()
858
            .cloned()
859
            .expect("TextInput::dom must attach its state as the node's dataset")
860
    }
861

            
862
    /// The text sitting in the widget's *edit buffer*.
863
    fn buffer_text(dom: &Dom) -> String {
864
        let mut dataset = dataset_of(dom);
865
        let wrapper = dataset
866
            .downcast_ref::<TextInputStateWrapper>()
867
            .expect("the dataset must be a TextInputStateWrapper");
868
        wrapper.inner.get_text()
869
    }
870

            
871
    /// The text actually *rendered* into the label node (a styled `<p>`
872
    /// wrapping its bare text leaf per the label convention).
873
    fn displayed_text(dom: &Dom) -> String {
874
        let label = &dom.children.as_ref()[LABEL];
875
        label
876
            .root
877
            .get_node_type()
878
            .format()
879
            .or_else(|| {
880
                label
881
                    .children
882
                    .as_ref()
883
                    .first()
884
                    .and_then(|c| c.root.get_node_type().format())
885
            })
886
            .expect("the label child must wrap a text node")
887
    }
888

            
889
    fn cursor_pos(dom: &Dom) -> usize {
890
        let mut dataset = dataset_of(dom);
891
        let wrapper = dataset
892
            .downcast_ref::<TextInputStateWrapper>()
893
            .expect("the dataset must be a TextInputStateWrapper");
894
        wrapper.inner.cursor_pos
895
    }
896

            
897
    /// The `NumberInputStateWrapper` the rendered widget actually validates against —
898
    /// pulled out of the hook `dom()` installed, so nothing about the wiring is
899
    /// re-created by hand.
900
    fn number_state_of(dom: &Dom) -> RefAny {
901
        let mut dataset = dataset_of(dom);
902
        let wrapper = dataset
903
            .downcast_ref::<TextInputStateWrapper>()
904
            .expect("the dataset must be a TextInputStateWrapper");
905
        wrapper
906
            .on_text_input
907
            .as_ref()
908
            .expect("NumberInput::dom must install a text-input hook")
909
            .refany
910
            .clone()
911
    }
912

            
913
    /// Delivers `text` to whichever text-input hook the rendered widget registered.
914
    fn drive_text_input(dom: &Dom, text: &str) -> OnTextInputReturn {
915
        let mut dataset = dataset_of(dom);
916
        let hook = dataset
917
            .downcast_ref::<TextInputStateWrapper>()
918
            .expect("the dataset must be a TextInputStateWrapper")
919
            .on_text_input
920
            .as_ref()
921
            .expect("NumberInput::dom must install a text-input hook")
922
            .clone();
923
        with_info(|info| (hook.callback.cb)(hook.refany.clone(), info, text_state(text)))
924
    }
925

            
926
    /// Delivers a key-down to whichever virtual-key hook survived rendering, if any.
927
    fn drive_virtual_key_down(dom: &Dom) -> Option<OnTextInputReturn> {
928
        let mut dataset = dataset_of(dom);
929
        let hook = dataset
930
            .downcast_ref::<TextInputStateWrapper>()
931
            .expect("the dataset must be a TextInputStateWrapper")
932
            .on_virtual_key_down
933
            .as_ref()
934
            .cloned()?;
935
        Some(with_info(|info| {
936
            (hook.callback.cb)(hook.refany.clone(), info, text_state(""))
937
        }))
938
    }
939

            
940
    // ==================================================================
941
    // NumberInput::create — numeric limits
942
    // ==================================================================
943

            
944
    #[test]
945
    fn create_zero_is_exactly_the_default_widget() {
946
        assert_eq!(
947
            NumberInput::create(0.0),
948
            NumberInput::default(),
949
            "create(0.0) must not perturb anything Default already set",
950
        );
951
    }
952

            
953
    #[test]
954
    fn create_preserves_every_sample_value_bit_exactly() {
955
        for v in finite_samples() {
956
            let state = NumberInput::create(v).number_input_state.inner;
957
            assert!(
958
                same(state.number, v),
959
                "create({v:?}) stored {:?}",
960
                state.number,
961
            );
962
            assert!(
963
                same(state.previous, 0.0),
964
                "create({v:?}) must start with no history, got previous = {:?}",
965
                state.previous,
966
            );
967
            assert!(
968
                same(state.min, f32::MIN) && same(state.max, f32::MAX),
969
                "create({v:?}) must leave the range wide open, got [{}, {}]",
970
                state.min,
971
                state.max,
972
            );
973
        }
974
    }
975

            
976
    #[test]
977
    fn create_accepts_nan_and_infinities_without_panicking() {
978
        for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
979
            let state = NumberInput::create(v).number_input_state.inner;
980
            assert!(
981
                same(state.number, v),
982
                "create({v:?}) stored {:?}",
983
                state.number,
984
            );
985
        }
986
        assert!(NumberInput::create(f32::NAN)
987
            .number_input_state
988
            .inner
989
            .number
990
            .is_nan());
991
    }
992

            
993
    #[test]
994
    fn create_never_clamps_its_argument() {
995
        // `create` is documented as "the given initial value" — it does not consult
996
        // min/max, so `+inf` survives even though the default `max` is `f32::MAX`.
997
        // Clamping is the *input* path's job (see `validate_clamps_into_range`).
998
        let state = NumberInput::create(f32::INFINITY).number_input_state.inner;
999
        assert!(
            state.number.is_infinite(),
            "create must store the value verbatim, got {}",
            state.number,
        );
        assert!(state.number > state.max, "…even outside its own range");
    }
    #[test]
    fn the_default_range_leaves_every_finite_value_untouched() {
        let d = NumberInputState::default();
        assert!(
            d.min <= d.max,
            "the default range must be non-empty — f32::clamp panics otherwise",
        );
        assert!(same(d.min, f32::MIN) && same(d.max, f32::MAX));
        assert!(same(d.number, 0.0) && same(d.previous, 0.0));
        for v in finite_samples() {
            assert!(
                same(v.clamp(d.min, d.max), v),
                "{v:?} must pass through the default range untouched",
            );
        }
    }
    #[test]
    fn number_input_state_is_a_value_type() {
        let a = NumberInputState::default();
        let mut b = a;
        b.number = 5.0;
        assert!(
            same(a.number, 0.0),
            "NumberInputState is Copy — mutating a copy must not alias the original",
        );
        assert_ne!(a, b);
    }
    #[test]
    fn a_fresh_wrapper_has_no_hooks() {
        let w = NumberInputStateWrapper::default();
        assert!(w.on_value_change.as_ref().is_none());
        assert!(w.on_focus_lost.as_ref().is_none());
        assert_eq!(w.inner, NumberInputState::default());
    }
    // ==================================================================
    // Builders / setters — invariants
    // ==================================================================
    #[test]
    fn with_and_set_style_pairs_are_equivalent() {
        for n in 0..4 {
            let s = style(n);
            let a = NumberInput::create(1.0).with_container_style(s.clone());
            let mut b = NumberInput::create(1.0);
            b.set_container_style(s.clone());
            assert_eq!(a, b, "with_container_style != set_container_style ({n})");
            let a = NumberInput::create(1.0).with_label_style(s.clone());
            let mut b = NumberInput::create(1.0);
            b.set_label_style(s);
            assert_eq!(a, b, "with_label_style != set_label_style ({n})");
        }
    }
    #[test]
    fn style_setters_write_to_disjoint_fields() {
        let placeholder = style(1);
        let container = style(2);
        let label = style(3);
        assert_ne!(
            placeholder, container,
            "the fixture must be distinguishable"
        );
        assert_ne!(container, label, "the fixture must be distinguishable");
        let input = NumberInput::create(0.0)
            .with_container_style(container.clone())
            .with_label_style(label.clone());
        assert_eq!(input.text_input.resolved_container_style(), container);
        assert_eq!(input.text_input.resolved_label_style(), label);
        assert_eq!(
            input.resolved_style(),
            NumberInput::default().resolved_style(),
            "NumberInput::style is not a dumping ground for the TextInput styles",
        );
    }
    #[test]
    fn with_and_set_callback_pairs_are_equivalent() {
        // The same `RefAny` handle on both sides: `RefAny` equality is identity of the
        // shared allocation, so two independent `RefAny::new(0u32)` would never match.
        let data = RefAny::new(0u32);
        let a = NumberInput::create(1.0).with_on_value_change(
            data.clone(),
            record_value_change as NumberInputOnValueChangeCallbackType,
        );
        let mut b = NumberInput::create(1.0);
        b.set_on_value_change(
            data.clone(),
            record_value_change as NumberInputOnValueChangeCallbackType,
        );
        assert_eq!(a, b, "with_on_value_change != set_on_value_change");
        let a = NumberInput::create(1.0).with_on_focus_lost(
            data.clone(),
            record_focus_lost as NumberInputOnFocusLostCallbackType,
        );
        let mut b = NumberInput::create(1.0);
        b.set_on_focus_lost(
            data.clone(),
            record_focus_lost as NumberInputOnFocusLostCallbackType,
        );
        assert_eq!(a, b, "with_on_focus_lost != set_on_focus_lost");
        let a = NumberInput::create(1.0).with_on_text_input(
            data.clone(),
            accept_everything as TextInputOnTextInputCallbackType,
        );
        let mut b = NumberInput::create(1.0);
        b.set_on_text_input(
            data.clone(),
            accept_everything as TextInputOnTextInputCallbackType,
        );
        assert_eq!(a, b, "with_on_text_input != set_on_text_input");
        let a = NumberInput::create(1.0).with_on_virtual_key_down(
            data.clone(),
            reject_everything as TextInputOnVirtualKeyDownCallbackType,
        );
        let mut b = NumberInput::create(1.0);
        b.set_on_virtual_key_down(
            data,
            reject_everything as TextInputOnVirtualKeyDownCallbackType,
        );
        assert_eq!(a, b, "with_on_virtual_key_down != set_on_virtual_key_down");
    }
    #[test]
    fn setting_a_hook_twice_keeps_the_last_one() {
        let first = RefAny::new(1u32);
        let second = RefAny::new(2u32);
        let mut input = NumberInput::create(0.0);
        input.set_on_value_change(
            first.clone(),
            record_value_change as NumberInputOnValueChangeCallbackType,
        );
        input.set_on_value_change(
            second.clone(),
            record_value_change as NumberInputOnValueChangeCallbackType,
        );
        let stored = input
            .number_input_state
            .on_value_change
            .as_ref()
            .expect("the hook must be set");
        assert_eq!(stored.refany, second, "the last hook must win");
        assert_ne!(stored.refany, first, "the first hook must be released");
    }
    #[test]
    fn swap_with_default_hands_back_the_original_and_leaves_a_fresh_widget() {
        let data = RefAny::new(0u32);
        let mut input = NumberInput::create(7.5)
            .with_on_value_change(
                data,
                record_value_change as NumberInputOnValueChangeCallbackType,
            )
            .with_label_style(style(2));
        let original = input.clone();
        let taken = input.swap_with_default();
        assert_eq!(
            taken, original,
            "swap_with_default must return the original"
        );
        assert_eq!(
            input,
            NumberInput::create(0.0),
            "the receiver must be left as a fresh 0.0 widget",
        );
        assert_eq!(
            input,
            NumberInput::default(),
            "…which is also exactly the Default widget",
        );
        // Idempotent on an already-defaulted receiver.
        let second = input.swap_with_default();
        assert_eq!(second, NumberInput::default());
        assert_eq!(input, NumberInput::default());
    }
    // ==================================================================
    // NumberInput::dom — encode / decode round-trip
    // ==================================================================
    #[test]
    fn dom_wires_the_text_input_and_parks_the_cursor_at_the_end() {
        let dom = NumberInput::create(-12.5).dom();
        assert_eq!(
            dom.children.as_ref().len(),
            1,
            "TextInput renders ONE value block; the prompt is an attribute",
        );
        assert_eq!(
            dom.root.callbacks.as_ref().len(),
            5,
            "focus received/lost, text input, virtual key down, hover",
        );
        assert!(
            dom.children.as_ref()[PLACEHOLDER]
                .children
                .as_ref()
                .first()
                .and_then(|c| c.root.get_node_type().format())
                .is_some(),
            "the placeholder child must wrap a text node",
        );
        assert_eq!(buffer_text(&dom), "-12.5");
        assert_eq!(displayed_text(&dom), "-12.5");
        assert_eq!(
            cursor_pos(&dom),
            "-12.5".chars().count(),
            "the cursor must sit at the end of the rendered number",
        );
    }
    #[test]
    fn dom_text_round_trips_back_to_the_same_f32() {
        for v in finite_samples() {
            let dom = NumberInput::create(v).dom();
            let text = buffer_text(&dom);
            let parsed: f32 = text.parse().unwrap_or_else(|e| {
                panic!("the widget rendered {v:?} as {text:?}, which is not a float: {e}")
            });
            assert!(
                same(parsed, v),
                "{v:?} was rendered as {text:?} and read back as {parsed:?}",
            );
            assert_eq!(
                displayed_text(&dom),
                text,
                "the visible label and the edit buffer must agree for {v:?}",
            );
        }
    }
    #[test]
    fn dom_renders_the_shortest_round_trip_form() {
        for (value, expected) in [
            (0.0f32, "0"),
            (1.0, "1"),
            (-1.5, "-1.5"),
            (42.25, "42.25"),
            (0.5, "0.5"),
        ] {
            assert_eq!(buffer_text(&NumberInput::create(value).dom()), expected);
        }
    }
    #[test]
    fn dom_renders_non_finite_values_as_inf_and_nan() {
        assert_eq!(
            buffer_text(&NumberInput::create(f32::INFINITY).dom()),
            "inf"
        );
        assert_eq!(
            buffer_text(&NumberInput::create(f32::NEG_INFINITY).dom()),
            "-inf",
        );
        assert_eq!(buffer_text(&NumberInput::create(f32::NAN).dom()), "NaN");
        assert_eq!(
            buffer_text(&NumberInput::create(-f32::NAN).dom()),
            "NaN",
            "the sign of a NaN is not rendered, so it cannot round-trip",
        );
    }
    #[test]
    fn every_string_the_widget_renders_is_accepted_by_its_own_validator() {
        let mut values = finite_samples().to_vec();
        values.extend_from_slice(&[f32::INFINITY, f32::NEG_INFINITY, f32::NAN]);
        for v in values {
            let text = buffer_text(&NumberInput::create(v).dom());
            let state = RefAny::new(wrapper(0.0, f32::MIN, f32::MAX));
            let (r, _) = validate_one(&state, &text);
            assert_eq!(
                r.valid,
                TextInputValid::Yes,
                "the widget renders {v:?} as {text:?} but then refuses to parse it back",
            );
        }
    }
    #[test]
    fn dom_renders_a_value_that_is_outside_its_own_range() {
        // Neither `create` nor `dom` consults min/max — only typed input is clamped.
        // A widget constructed out of range therefore *shows* a number it would never
        // accept from the keyboard.
        let mut input = NumberInput::create(1000.0);
        input.number_input_state.inner.min = 0.0;
        input.number_input_state.inner.max = 10.0;
        assert_eq!(buffer_text(&input.dom()), "1000");
    }
    #[test]
    fn dom_replaces_a_user_supplied_text_input_hook_with_the_numeric_validator() {
        // `dom()` unconditionally overwrites `on_text_input`, so a hook installed via
        // `with_on_text_input` never fires. `accept_everything` would answer `Yes` to
        // "abc"; the numeric validator answers `No`.
        let dom = NumberInput::create(1.0)
            .with_on_text_input(
                RefAny::new(0u32),
                accept_everything as TextInputOnTextInputCallbackType,
            )
            .dom();
        let r = drive_text_input(&dom, "abc");
        assert_eq!(
            r.valid,
            TextInputValid::No,
            "the numeric validator must own the text-input hook after dom()",
        );
        assert_eq!(r.update, Update::DoNothing);
    }
    #[test]
    fn dom_keeps_a_user_supplied_virtual_key_hook() {
        let dom = NumberInput::create(1.0)
            .with_on_virtual_key_down(
                RefAny::new(0u32),
                reject_everything as TextInputOnVirtualKeyDownCallbackType,
            )
            .dom();
        let r =
            drive_virtual_key_down(&dom).expect("with_on_virtual_key_down must survive rendering");
        assert_eq!(r.update, Update::RefreshDomAllWindows);
        assert_eq!(r.valid, TextInputValid::No);
    }
    #[test]
    fn dom_wires_the_value_change_hook_through_the_rendered_widget() {
        let recorder = RefAny::new(Recorder::new(Update::RefreshDom));
        let dom = NumberInput::create(0.0)
            .with_on_value_change(
                recorder.clone(),
                record_value_change as NumberInputOnValueChangeCallbackType,
            )
            .dom();
        let r = drive_text_input(&dom, "12,5");
        assert_eq!(r.valid, TextInputValid::Yes);
        assert_eq!(
            r.update,
            Update::RefreshDom,
            "validate must return whatever the user's hook returned",
        );
        let seen = recorded(&recorder);
        assert_eq!(seen.len(), 1, "the hook must fire exactly once per edit");
        assert!(same(seen[0].number, 12.5));
        assert!(same(seen[0].previous, 0.0));
        assert!(
            same(read(&number_state_of(&dom)).number, 12.5),
            "the state behind the rendered DOM must have been updated too",
        );
    }
    // ==================================================================
    // validate_text_input — the parser
    // ==================================================================
    #[test]
    fn validate_rejects_malformed_input_without_touching_the_state() {
        // One state for the whole table: a rejected edit must not accumulate either.
        let state = RefAny::new(wrapper(7.5, -100.0, 100.0));
        with_info(|info| {
            for text in MALFORMED {
                let r = validate_text_input(state.clone(), info, text_state(text));
                assert_eq!(r.valid, TextInputValid::No, "{text:?} must be rejected");
                assert_eq!(
                    r.update,
                    Update::DoNothing,
                    "a rejected edit must not trigger a relayout ({text:?})",
                );
                let after = read(&state);
                assert!(
                    same(after.number, 7.5),
                    "{text:?} changed the value to {}",
                    after.number,
                );
                assert!(
                    same(after.previous, 0.0),
                    "{text:?} touched `previous` ({})",
                    after.previous,
                );
            }
        });
    }
    #[test]
    fn validate_lets_a_transient_prefix_exist_without_touching_the_value() {
        let state = RefAny::new(wrapper(7.5, -100.0, 100.0));
        with_info(|info| {
            for text in TRANSIENT_PREFIXES {
                assert!(is_float_prefix(text), "{text:?} is a prefix of a number");
                let r = validate_text_input(state.clone(), info, text_state(text));
                assert_eq!(
                    r.valid,
                    TextInputValid::Yes,
                    "{text:?} must be allowed to exist in the field — `-5` starts with `-`",
                );
                assert_eq!(
                    r.update,
                    Update::DoNothing,
                    "{text:?}: nothing to relayout yet"
                );
                let after = read(&state);
                assert!(
                    same(after.number, 7.5),
                    "{text:?} changed the value to {}",
                    after.number
                );
                assert!(same(after.previous, 0.0), "{text:?} touched `previous`");
            }
            for text in MALFORMED {
                assert!(!is_float_prefix(text), "{text:?} can never become a number");
            }
            // And the prefix completes into the number it was heading for.
            let r = validate_text_input(state.clone(), info, text_state("-5"));
            assert_eq!(r.valid, TextInputValid::Yes);
            assert!(same(read(&state).number, -5.0));
            let r = validate_text_input(state.clone(), info, text_state(".5"));
            assert_eq!(r.valid, TextInputValid::Yes);
            assert!(same(read(&state).number, 0.5));
        });
    }
    #[test]
    fn a_transient_prefix_does_not_reach_the_users_hook() {
        let recorder = RefAny::new(Recorder::new(Update::RefreshDom));
        let state = RefAny::new(wrapper_with_value_hook(1.0, f32::MIN, f32::MAX, &recorder));
        with_info(|info| {
            for text in TRANSIENT_PREFIXES {
                let _ = validate_text_input(state.clone(), info, text_state(text));
            }
        });
        assert!(
            recorded(&recorder).is_empty(),
            "an incomplete number is not a value change"
        );
    }
    #[test]
    fn validate_rejects_digits_that_are_not_ascii_digits() {
        let state = RefAny::new(wrapper(3.0, f32::MIN, f32::MAX));
        with_info(|info| {
            for text in NON_ASCII_DIGITS {
                let r = validate_text_input(state.clone(), info, text_state(text));
                assert_eq!(r.valid, TextInputValid::No, "{text:?} must be rejected");
                assert!(
                    same(read(&state).number, 3.0),
                    "{text:?} must not change the value",
                );
            }
        });
    }
    #[test]
    fn validate_accepts_every_form_the_rust_float_parser_accepts() {
        let state = RefAny::new(wrapper(-1.0, f32::MIN, f32::MAX));
        with_info(|info| {
            for (text, expected) in ACCEPTED {
                reset(&state, -1.0);
                let r = validate_text_input(state.clone(), info, text_state(text));
                assert_eq!(r.valid, TextInputValid::Yes, "{text:?} must be accepted");
                assert_eq!(
                    r.update,
                    Update::DoNothing,
                    "no hook is installed, so there is nothing to redraw ({text:?})",
                );
                let after = read(&state);
                assert!(
                    same(after.number, expected),
                    "{text:?} stored {} (expected {expected})",
                    after.number,
                );
                assert!(
                    same(after.previous, -1.0),
                    "{text:?} must push the old value into `previous`, got {}",
                    after.previous,
                );
            }
        });
    }
    #[test]
    fn validate_reads_a_comma_as_a_decimal_point() {
        with_info(|info| {
            for (text, expected) in [
                ("1,5", 1.5f32),
                ("-1,5", -1.5),
                (",5", 0.5),
                ("1,", 1.0),
                ("1,25e2", 125.0),
            ] {
                let state = RefAny::new(wrapper(0.0, f32::MIN, f32::MAX));
                let r = validate_text_input(state.clone(), info, text_state(text));
                assert_eq!(r.valid, TextInputValid::Yes, "{text:?} must be accepted");
                assert!(
                    same(read(&state).number, expected),
                    "{text:?} stored {} (expected {expected})",
                    read(&state).number,
                );
            }
            // A comma is rewritten, not deleted: a second one is still a parse error.
            for text in [",,", "1,,5", "1,5,5"] {
                let state = RefAny::new(wrapper(0.0, f32::MIN, f32::MAX));
                let r = validate_text_input(state.clone(), info, text_state(text));
                assert_eq!(r.valid, TextInputValid::No, "{text:?} must be rejected");
            }
            // A lone comma is "." — the first keystroke of ",5" — a transient
            // prefix: it may exist in the field, the value does not move.
            let state = RefAny::new(wrapper(7.0, f32::MIN, f32::MAX));
            let r = validate_text_input(state.clone(), info, text_state(","));
            assert_eq!(r.valid, TextInputValid::Yes, "',' is the start of ',5'");
            assert!(same(read(&state).number, 7.0));
        });
    }
    #[test]
    fn validate_reads_a_thousands_separator_as_a_decimal_point() {
        // The `,` -> `.` rewrite is unconditional, so "1,000" (US grouping for one
        // thousand) is silently read as *one*. That is the price of supporting the
        // European decimal comma, and it is worth pinning down: the value a user
        // typed changes by three orders of magnitude with no rejection.
        let state = RefAny::new(wrapper(0.0, f32::MIN, f32::MAX));
        let (r, after) = validate_one(&state, "1,000");
        assert_eq!(r.valid, TextInputValid::Yes);
        assert!(
            same(after.number, 1.0),
            "\"1,000\" is read as {} (the comma is a decimal point here)",
            after.number,
        );
        let (r, _) = validate_one(&state, "1,000,000");
        assert_eq!(
            r.valid,
            TextInputValid::No,
            "a second group makes it un-parseable rather than ambiguous",
        );
    }
    #[test]
    fn validate_silently_drops_code_units_that_are_not_unicode_scalars() {
        // The edit buffer is a `U32Vec`, so it can hold unpaired surrogates and
        // out-of-range code units. `char::from_u32` returns None for those and the
        // filter *drops* them, so "1<D800>5" is read as the number 15 rather than
        // being rejected as malformed.
        let state = RefAny::new(wrapper(0.0, f32::MIN, f32::MAX));
        let (r, after) = validate_raw(&state, &[0x31, 0xD800, 0x35]);
        assert_eq!(r.valid, TextInputValid::Yes);
        assert!(
            same(after.number, 15.0),
            "a non-scalar code unit between two digits is dropped, got {}",
            after.number,
        );
        // …but a buffer made *only* of non-scalars collapses to the empty string,
        // which is the empty transient prefix: the keystroke may land, the value
        // is neither read as zero nor changed.
        let (r, after) = validate_raw(&state, &[0xD800, 0xDFFF, 0x0011_0000]);
        assert_eq!(r.valid, TextInputValid::Yes);
        assert!(
            same(after.number, 15.0),
            "an empty buffer must not change the value",
        );
    }
    #[test]
    fn validate_survives_pathologically_long_input() {
        let state = RefAny::new(wrapper(0.0, f32::MIN, f32::MAX));
        for (text, expected) in [
            ("9".repeat(10_000), f32::MAX), // overflows to +inf, saturates
            (format!("-{}", "9".repeat(10_000)), f32::MIN),
            (format!("{}1", "0".repeat(10_000)), 1.0), // leading zeros
            (format!("0.{}", "0".repeat(10_000)), 0.0),
            ("1e999999999".to_string(), f32::MAX), // exponent overflow
            ("1e-999999999".to_string(), 0.0),     // exponent underflow
        ] {
            let (r, after) = validate_one(&state, &text);
            assert_eq!(
                r.valid,
                TextInputValid::Yes,
                "a {}-char input must parse, not error",
                text.len(),
            );
            assert!(
                same(after.number, expected),
                "a {}-char input stored {} (expected {expected})",
                text.len(),
                after.number,
            );
        }
    }
    // ==================================================================
    // validate_text_input — numeric limits
    // ==================================================================
    #[test]
    fn validate_saturates_overflow_at_the_configured_bounds() {
        let state = RefAny::new(wrapper(0.0, f32::MIN, f32::MAX));
        // "1e39" is well past f32::MAX, so the parser returns +inf rather than an
        // error — the saturation has to happen here, in the clamp.
        let (r, after) = validate_one(&state, "1e39");
        assert_eq!(r.valid, TextInputValid::Yes);
        assert!(
            same(after.number, f32::MAX),
            "an overflowing value must saturate at `max`, got {}",
            after.number,
        );
        let (_, after) = validate_one(&state, "-1e39");
        assert!(
            same(after.number, f32::MIN),
            "…and at `min` on the negative side, got {}",
            after.number,
        );
    }
    #[test]
    fn validate_underflow_keeps_the_sign_of_zero() {
        let state = RefAny::new(wrapper(1.0, f32::MIN, f32::MAX));
        let (_, after) = validate_one(&state, "1e-46");
        assert!(
            same(after.number, 0.0),
            "a positive underflow must land on +0.0, got {}",
            after.number,
        );
        let (_, after) = validate_one(&state, "-1e-46");
        assert!(
            same(after.number, -0.0),
            "a negative underflow must land on -0.0, got {}",
            after.number,
        );
    }
    #[test]
    fn validate_clamps_into_range() {
        with_info(|info| {
            for (min, max, text, expected) in [
                (-10.0f32, 10.0f32, "1000", 10.0f32),
                (-10.0, 10.0, "-1000", -10.0),
                (-10.0, 10.0, "inf", 10.0),
                (-10.0, 10.0, "-inf", -10.0),
                (-10.0, 10.0, "10", 10.0), // exactly on the bound
                (-10.0, 10.0, "-10", -10.0),
                (-10.0, 10.0, "10.000001", 10.0), // one ulp past the bound
                (-10.0, 10.0, "0", 0.0),
                (0.0, 0.0, "5", 0.0), // a single-point range is legal
                (0.0, 0.0, "-5", 0.0),
                (5.0, 5.0, "0", 5.0),
            ] {
                let state = RefAny::new(wrapper(0.0, min, max));
                let r = validate_text_input(state.clone(), info, text_state(text));
                assert_eq!(r.valid, TextInputValid::Yes, "{text:?} must be accepted");
                let after = read(&state);
                assert!(
                    same(after.number, expected),
                    "{text:?} in [{min}, {max}] stored {} (expected {expected})",
                    after.number,
                );
                assert!(
                    after.number >= min && after.number <= max,
                    "{text:?} escaped [{min}, {max}] as {}",
                    after.number,
                );
            }
        });
    }
    #[test]
    fn validate_stores_nan_unclamped() {
        // `f32::clamp` compares, and every comparison against NaN is false, so a NaN
        // walks straight through the range check. The widget's "number is always in
        // [min, max]" invariant therefore has exactly one hole, and it is reachable
        // by typing "nan" into the field.
        let state = RefAny::new(wrapper(0.0, -1.0, 1.0));
        let (r, after) = validate_one(&state, "NaN");
        assert_eq!(
            r.valid,
            TextInputValid::Yes,
            "the Rust float parser accepts \"NaN\", so the widget does too",
        );
        assert!(
            after.number.is_nan(),
            "NaN survives the clamp untouched, got {}",
            after.number,
        );
    }
    #[test]
    fn validate_tracks_previous_as_the_last_accepted_value() {
        let state = RefAny::new(wrapper(0.0, 0.0, 10.0));
        with_info(|info| {
            for (text, previous, number) in [
                ("1", 0.0f32, 1.0f32),
                ("2", 1.0, 2.0),
                ("100", 2.0, 10.0),  // clamped
                ("200", 10.0, 10.0), // `previous` is the *clamped* old value
                ("abc", 10.0, 10.0), // rejected: neither field moves
                ("-5", 10.0, 0.0),
            ] {
                let _ = validate_text_input(state.clone(), info, text_state(text));
                let after = read(&state);
                assert!(
                    same(after.previous, previous),
                    "after {text:?}: previous = {} (expected {previous})",
                    after.previous,
                );
                assert!(
                    same(after.number, number),
                    "after {text:?}: number = {} (expected {number})",
                    after.number,
                );
            }
        });
    }
    /// `validate_text_input` runs `f32::clamp(min, max)` on every value it parses,
    /// and `f32::clamp` **panics** unless `min <= max` — which a NaN bound also
    /// fails. `min`/`max` are `pub` fields on a `#[repr(C)]` struct that crosses the
    /// C/FFI boundary, so nothing stops a caller from handing the widget an inverted
    /// or NaN-bounded range, and a panic inside a UI callback takes the app with it.
    /// Rejecting the edit (`TextInputValid::No`) or normalising the range would both
    /// be safe; unwinding is not.
    #[test]
    fn validate_with_a_degenerate_range_must_not_panic() {
        let degenerate: [(f32, f32); 5] = [
            (10.0, 5.0),
            (1.0, -1.0),
            (f32::NAN, 10.0),
            (0.0, f32::NAN),
            (f32::NAN, f32::NAN),
        ];
        let panicked: Vec<(f32, f32)> = degenerate
            .iter()
            .copied()
            .filter(|&(min, max)| {
                let state = RefAny::new(wrapper(0.0, min, max));
                catch_unwind(AssertUnwindSafe(|| {
                    let _ = validate_one(&state, "1");
                }))
                .is_err()
            })
            .collect();
        assert!(
            panicked.is_empty(),
            "typing a digit into a NumberInput whose [min, max] range is inverted or NaN-bounded \
             panics (f32::clamp asserts min <= max) instead of rejecting the input; offending \
             ranges: {panicked:?}",
        );
    }
    // ==================================================================
    // validate_text_input — hooks and payload handling
    // ==================================================================
    #[test]
    fn validate_with_a_foreign_payload_accepts_the_edit_unchanged() {
        // The downcast guard bails out *before* parsing, so a mis-wired NumberInput
        // reports arbitrary text as valid instead of rejecting it.
        let state = RefAny::new(0u32);
        let r =
            with_info(|info| validate_text_input(state.clone(), info, text_state("not a number")));
        assert_eq!(r.update, Update::DoNothing);
        assert_eq!(r.valid, TextInputValid::Yes);
        let mut state = state;
        assert_eq!(
            *state
                .downcast_ref::<u32>()
                .expect("the foreign payload must be left alone"),
            0,
        );
    }
    #[test]
    fn validate_does_not_invoke_the_value_change_hook_for_rejected_input() {
        let recorder = RefAny::new(Recorder::new(Update::RefreshDom));
        let state = RefAny::new(wrapper_with_value_hook(1.0, f32::MIN, f32::MAX, &recorder));
        with_info(|info| {
            for text in MALFORMED {
                let _ = validate_text_input(state.clone(), info, text_state(text));
            }
        });
        assert!(
            recorded(&recorder).is_empty(),
            "a rejected edit must not reach the user's hook",
        );
        // Sanity: the hook *is* wired up and does fire for a well-formed edit.
        let (r, _) = validate_one(&state, "2");
        assert_eq!(r.update, Update::RefreshDom);
        assert_eq!(recorded(&recorder).len(), 1);
    }
    #[test]
    fn validate_hands_the_hook_the_clamped_state_and_returns_its_update() {
        let recorder = RefAny::new(Recorder::new(Update::RefreshDomAllWindows));
        let state = RefAny::new(wrapper_with_value_hook(4.0, 0.0, 10.0, &recorder));
        let (r, after) = validate_one(&state, "1000");
        assert_eq!(
            r.update,
            Update::RefreshDomAllWindows,
            "validate must forward the hook's Update verbatim",
        );
        assert_eq!(r.valid, TextInputValid::Yes);
        let seen = recorded(&recorder);
        assert_eq!(seen.len(), 1);
        assert!(
            same(seen[0].number, 10.0),
            "the hook must see the clamped value, not the raw 1000, got {}",
            seen[0].number,
        );
        assert!(same(seen[0].previous, 4.0), "…and the previous value");
        assert_eq!(
            seen[0], after,
            "the hook's copy and the stored state must agree",
        );
    }
    // ==================================================================
    // on_focus_lost
    // ==================================================================
    #[test]
    fn focus_lost_with_a_foreign_payload_does_nothing() {
        let state = RefAny::new(0u32);
        assert_eq!(focus_lost(&state, "123"), Update::DoNothing);
        let mut state = state;
        assert_eq!(
            *state
                .downcast_ref::<u32>()
                .expect("the foreign payload must be left alone"),
            0,
        );
    }
    #[test]
    fn focus_lost_without_a_hook_does_nothing() {
        let state = RefAny::new(wrapper(1.5, 0.0, 10.0));
        assert_eq!(focus_lost(&state, "123"), Update::DoNothing);
        let after = read(&state);
        assert!(same(after.number, 1.5) && same(after.previous, 0.0));
    }
    #[test]
    fn focus_lost_reports_the_stored_number_and_ignores_the_text_buffer() {
        // `on_focus_lost` never looks at the `TextInputState` it is handed: the value
        // it reports is the one the *validator* accepted, not whatever happens to be
        // sitting in the buffer.
        let recorder = RefAny::new(Recorder::new(Update::RefreshDom));
        let state = RefAny::new(wrapper_with_focus_hook(1.5, 0.0, 10.0, &recorder));
        assert_eq!(
            focus_lost(&state, "999"),
            Update::RefreshDom,
            "the hook's Update must be forwarded verbatim",
        );
        let seen = recorded(&recorder);
        assert_eq!(seen.len(), 1, "the hook must fire exactly once");
        assert!(
            same(seen[0].number, 1.5),
            "the hook saw {} — the text buffer must not be re-parsed",
            seen[0].number,
        );
        assert!(same(seen[0].previous, 0.0));
    }
    #[test]
    fn focus_lost_neither_mutates_nor_clamps() {
        // A state built out of range (see `dom_renders_a_value_that_is_outside_its_own_range`)
        // is reported verbatim: focus-lost is a read-only notification.
        let recorder = RefAny::new(Recorder::new(Update::DoNothing));
        let state = RefAny::new(wrapper_with_focus_hook(1000.0, 0.0, 10.0, &recorder));
        assert_eq!(focus_lost(&state, ""), Update::DoNothing);
        let seen = recorded(&recorder);
        assert_eq!(seen.len(), 1);
        assert!(
            same(seen[0].number, 1000.0),
            "focus-lost must not clamp, got {}",
            seen[0].number,
        );
        let after = read(&state);
        assert!(
            same(after.number, 1000.0) && same(after.previous, 0.0),
            "focus-lost must not mutate the state",
        );
    }
    #[test]
    fn focus_lost_is_repeatable() {
        let recorder = RefAny::new(Recorder::new(Update::DoNothing));
        let state = RefAny::new(wrapper_with_focus_hook(2.5, 0.0, 10.0, &recorder));
        for _ in 0..8 {
            assert_eq!(focus_lost(&state, "2.5"), Update::DoNothing);
        }
        let seen = recorded(&recorder);
        assert_eq!(seen.len(), 8, "every focus loss must reach the hook");
        assert!(
            seen.iter().all(|s| same(s.number, 2.5)),
            "repeated focus losses must keep reporting the same value",
        );
    }
}