1
//! Slider / range widget — a horizontal track with a draggable circular thumb
2
//! that maps a position along the track to a numeric value in `[min, max]`.
3
//! Combines the value/min/max state + `on_value_change` callback shape of
4
//! [`crate::widgets::number_input::NumberInput`] with the pointer-drag handling
5
//! of [`crate::widgets::map`] (cursor-relative-to-node → value), and the
6
//! switch's "track + knob slid via `margin-left`" rendering.
7
//!
8
//! Behaviour: pressing or dragging anywhere on the track sets the value from the
9
//! cursor's X position (relative to the track, in logical px), slides the thumb
10
//! live via `set_css_property`, and invokes the user's `on_value_change`.
11
//!
12
//! Key types: [`Slider`], [`SliderState`], [`SliderOnValueChange`].
13

            
14
use azul_core::{
15
    callbacks::{CoreCallbackData, Update},
16
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
17
    refany::RefAny,
18
};
19
use azul_css::{
20
    dynamic_selector::{
21
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
22
    },
23
    impl_option_inner,
24
    props::{
25
        basic::{color::ColorU, *},
26
        layout::{
27
            LayoutAlignItems, LayoutAlignSelf, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow,
28
            LayoutHeight, LayoutMarginLeft, LayoutWidth,
29
        },
30
        property::{CssProperty, *},
31
        style::{
32
            StyleBackgroundContent, StyleBackgroundContentVec, StyleBorderBottomLeftRadius,
33
            StyleBorderBottomRightRadius, StyleBorderTopLeftRadius, StyleBorderTopRightRadius,
34
            StyleCursor,
35
        },
36
    },
37
    AzString,
38
};
39

            
40
use crate::{
41
    callbacks::{Callback, CallbackInfo},
42
    solver3::layout_tree::LayoutNodeId,
43
};
44

            
45
static SLIDER_TRACK_CLASS: &[IdOrClass] =
46
    &[Class(AzString::from_const_str("__azul-native-slider"))];
47
static SLIDER_THUMB_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
48
    "__azul-native-slider-thumb",
49
))];
50

            
51
/// Callback function type invoked when the slider value changes.
52
pub type SliderOnValueChangeCallbackType =
53
    extern "C" fn(RefAny, CallbackInfo, SliderState) -> Update;
54
impl_widget_callback!(
55
    SliderOnValueChange,
56
    OptionSliderOnValueChange,
57
    SliderOnValueChangeCallback,
58
    SliderOnValueChangeCallbackType
59
);
60

            
61
azul_core::impl_managed_callback! {
62
    wrapper:        SliderOnValueChangeCallback,
63
    info_ty:        CallbackInfo,
64
    return_ty:      Update,
65
    default_ret:    Update::DoNothing,
66
    invoker_static: SLIDER_ON_VALUE_CHANGE_INVOKER,
67
    invoker_ty:     AzSliderOnValueChangeCallbackInvoker,
68
    thunk_fn:       az_slider_on_value_change_callback_thunk,
69
    setter_fn:      AzApp_setSliderOnValueChangeCallbackInvoker,
70
    from_handle_fn: AzSliderOnValueChangeCallback_createFromHostHandle,
71
    extra_args:     [ state: SliderState ],
72
}
73

            
74
/// A horizontal slider with a draggable thumb and a value-change callback.
75
#[derive(Debug, Clone, PartialEq)]
76
#[repr(C)]
77
pub struct Slider {
78
    pub theme: crate::widgets::themes::OptionUiTheme,
79
    pub slider_state: SliderStateWrapper,
80
    /// Style for the slider track (the horizontal rail).
81
    /// Style for the track, or `None` for "no opinion" — in which case the
82
    /// widget's default applies.
83
    ///
84
    /// `None` and `Some(empty)` are different answers: the first means the
85
    /// widget picks, the second means the caller asked for no properties at all
86
    /// and gets none.
87
    pub track_style: OptionCssPropertyWithConditionsVec,
88
    /// Style for the draggable thumb.
89
    /// Style for the thumb, or `None` for "no opinion" — in which case the
90
    /// geometry (including the `margin-left` that positions it) is derived from
91
    /// the current value at render time.
92
    ///
93
    /// `None` and `Some(empty)` are different answers: the first means the
94
    /// widget picks, the second means the caller asked for no properties at all
95
    /// and gets none.
96
    pub thumb_style: OptionCssPropertyWithConditionsVec,
97
    /// What this slider is CALLED, for assistive technology.
98
    ///
99
    /// The widget carries it rather than the caller patching the finished
100
    /// `Dom`, so the slider knows at BUILD time whether it was named and can
101
    /// say so if it was not. A `Dom`-level override cannot give that: by the
102
    /// time it runs, the widget has already finished and a build-time warning
103
    /// would have fired on every correctly-named slider.
104
    ///
105
    /// A slider has no text of its own — it is a track and a thumb — so
106
    /// without this a screen reader announces "slider" and the position, and
107
    /// never which slider.
108
    pub accessibility_name: azul_css::OptionString,
109
}
110

            
111
#[derive(Debug, Default, Clone, PartialEq)]
112
#[repr(C)]
113
pub struct SliderStateWrapper {
114
    /// Optional: function to call when the value changes.
115
    pub on_value_change: OptionSliderOnValueChange,
116
    /// The value/range of this Slider.
117
    pub inner: SliderState,
118
    /// `true` while a pointer-drag is in flight (mirrors `map::MapTileCache::drag_anchor`).
119
    /// Transient; not part of the user-visible [`SliderState`].
120
    pub dragging: bool,
121
}
122

            
123
/// State of a [`Slider`]: the current value and the allowed `[min, max]` range.
124
#[derive(Debug, Copy, Clone, PartialEq)]
125
#[repr(C)]
126
pub struct SliderState {
127
    /// The current value (always within `[min, max]`).
128
    pub value: f32,
129
    /// Minimum allowed value (inclusive) — thumb at the far left.
130
    pub min: f32,
131
    /// Maximum allowed value (inclusive) — thumb at the far right.
132
    pub max: f32,
133
}
134

            
135
impl Default for SliderState {
136
442
    fn default() -> Self {
137
442
        Self {
138
442
            value: 0.0,
139
442
            min: 0.0,
140
442
            max: 100.0,
141
442
        }
142
442
    }
143
}
144

            
145
// ---- dimensions (logical px) ----
146
const TRACK_WIDTH: isize = 200;
147
const TRACK_HEIGHT: isize = 16;
148
const TRACK_RADIUS: isize = 8;
149
const THUMB_SIZE: isize = 16;
150
const THUMB_RADIUS: isize = 8;
151

            
152
// ---- colours ----
153
/// Rail colour (#cccccc).
154
const RAIL_COLOR: ColorU = ColorU {
155
    r: 204,
156
    g: 204,
157
    b: 204,
158
    a: 255,
159
};
160
/// Thumb colour (#0d6efd, accent blue).
161
const THUMB_COLOR: ColorU = ColorU {
162
    r: 13,
163
    g: 110,
164
    b: 253,
165
    a: 255,
166
};
167

            
168
const RAIL_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(RAIL_COLOR)];
169
const RAIL_BG: StyleBackgroundContentVec =
170
    StyleBackgroundContentVec::from_const_slice(RAIL_BG_ITEMS);
171
const THUMB_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(THUMB_COLOR)];
172
const THUMB_BG: StyleBackgroundContentVec =
173
    StyleBackgroundContentVec::from_const_slice(THUMB_BG_ITEMS);
174

            
175
/// The track (rail) style is parameter-independent, so it lives in a const slice.
176
static SLIDER_TRACK_STYLE: &[CssPropertyWithConditions] = &[
177
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
178
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
179
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
180
    CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Center)),
181
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
182
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(TRACK_WIDTH))),
183
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(
184
        TRACK_HEIGHT,
185
    ))),
186
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
187
        StyleBorderTopLeftRadius::const_px(TRACK_RADIUS),
188
    )),
189
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
190
        StyleBorderTopRightRadius::const_px(TRACK_RADIUS),
191
    )),
192
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
193
        StyleBorderBottomLeftRadius::const_px(TRACK_RADIUS),
194
    )),
195
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
196
        StyleBorderBottomRightRadius::const_px(TRACK_RADIUS),
197
    )),
198
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
199
    CssPropertyWithConditions::simple(CssProperty::const_background_content(RAIL_BG)),
200
];
201

            
202
/// Maps a value to a `[0, 1]` fraction along the track.
203
2524
fn value_to_fraction(value: f32, min: f32, max: f32) -> f32 {
204
2524
    if max <= min {
205
842
        0.0
206
    } else {
207
1682
        ((value - min) / (max - min)).clamp(0.0, 1.0)
208
    }
209
2524
}
210

            
211
/// Builds the thumb style; the `margin-left` is the only position-dependent
212
/// property and slides the thumb between the left (`min`) and right (`max`) ends.
213
#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // bounded layout/render
214
                                                                        // numeric cast
215
1555
fn build_thumb_style(fraction: f32) -> CssPropertyWithConditionsVec {
216
    // `fraction` is a bare `f32` with no type-level guard. Its only caller feeds
217
    // it `value_to_fraction`'s already-clamped output, but the helper must be
218
    // safe on its own terms: `const_px` encodes the margin as `isize * 1000`
219
    // (`FloatValue::const_new`), so any |margin| above `isize::MAX / 1000`
220
    // overflows that multiply — a panic in an overflow-checked build, a wrapped
221
    // and wildly-wrong margin in release. `as isize` already saturates NaN to 0
222
    // and ±inf to isize::MIN/MAX, so the only thing missing is the clamp into
223
    // what the fixed-point encoding can actually hold. Clamping the ENCODED px
224
    // rather than the fraction keeps every in-contract and out-of-contract-but-
225
    // representable result (including negative fractions) bit-for-bit unchanged.
226
    const MAX_ENCODABLE_PX: isize = isize::MAX / 1000;
227
1555
    let margin = ((fraction * (TRACK_WIDTH - THUMB_SIZE) as f32).round() as isize)
228
1555
        .clamp(-MAX_ENCODABLE_PX, MAX_ENCODABLE_PX);
229
1555
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
230
1555
        CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(
231
            THUMB_SIZE,
232
        ))),
233
1555
        CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(
234
            THUMB_SIZE,
235
        ))),
236
1555
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
237
            0,
238
        ))),
239
1555
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
240
1555
            StyleBorderTopLeftRadius::const_px(THUMB_RADIUS),
241
        )),
242
1555
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
243
1555
            StyleBorderTopRightRadius::const_px(THUMB_RADIUS),
244
        )),
245
1555
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
246
1555
            StyleBorderBottomLeftRadius::const_px(THUMB_RADIUS),
247
        )),
248
1555
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
249
1555
            StyleBorderBottomRightRadius::const_px(THUMB_RADIUS),
250
        )),
251
1555
        CssPropertyWithConditions::simple(CssProperty::const_background_content(THUMB_BG)),
252
1555
        CssPropertyWithConditions::simple(CssProperty::const_margin_left(
253
1555
            LayoutMarginLeft::const_px(margin),
254
        )),
255
    ])
256
1555
}
257

            
258
/// Clamps `value` into `[min, max]`, tolerating the degenerate bounds that
259
/// `f32::clamp` panics on: an inverted range (`min > max`) is swapped, and a NaN
260
/// bound is dropped (if both are NaN the value is returned untouched). `min`/`max`
261
/// are `pub` fields on a `#[repr(C)]` `SliderState` that crosses the C/FFI
262
/// boundary, so a caller can supply either — and unwinding across FFI is UB.
263
537
fn clamp_to_range(value: f32, min: f32, max: f32) -> f32 {
264
537
    let (lo, hi) = match (min.is_nan(), max.is_nan()) {
265
2
        (true, true) => return value,
266
2
        (true, false) => (max, max),
267
2
        (false, true) => (min, min),
268
531
        (false, false) if min <= max => (min, max),
269
6
        (false, false) => (max, min),
270
    };
271
535
    value.clamp(lo, hi)
272
537
}
273

            
274
impl Slider {
275
    /// Creates a slider with the given current value and `[min, max]` range.
276
    /// Name this slider for assistive technology.
277
    ///
278
    /// ```ignore
279
    /// Slider::create(vol, 0.0, 100.0).with_accessibility_name("Volume").dom()
280
    /// ```
281
    ///
282
    /// Prefer this over patching the finished `Dom`: the widget forwards it
283
    /// into the accessibility declaration it builds anyway, alongside the role
284
    /// and the live value, and knowing the name at build time is what lets the
285
    /// widget tell you when it is missing without crying wolf.
286
    #[must_use]
287
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
288
        self.accessibility_name = Some(name.into()).into();
289
        self
290
    }
291

            
292
    #[must_use]
293
379
    pub fn create(value: f32, min: f32, max: f32) -> Self {
294
379
        let value = clamp_to_range(value, min, max);
295
379
        Self {
296
379
            theme: crate::widgets::themes::OptionUiTheme::Some(
297
379
                crate::widgets::themes::UiTheme::Flat,
298
379
            ),
299
379
            slider_state: SliderStateWrapper {
300
379
                inner: SliderState { value, min, max },
301
379
                ..Default::default()
302
379
            },
303
379
            track_style: OptionCssPropertyWithConditionsVec::None,
304
379
            thumb_style: OptionCssPropertyWithConditionsVec::None,
305
379
            // Unnamed by default; the caller supplies it with
306
379
            // `.with_accessibility_name(..)`, and the widget warns if nobody does.
307
379
            accessibility_name: azul_css::OptionString::None,
308
379
        }
309
379
    }
310

            
311
    /// The track CSS this slider renders with.
312
    ///
313
    /// `None` means no opinion, so the widget's default applies — the same
314
    /// answer both themes give, asked in one place so they cannot drift.
315
    #[must_use]
316
234
    pub fn resolved_track_style(&self) -> CssPropertyWithConditionsVec {
317
234
        self.track_style
318
234
            .clone()
319
234
            .into_option()
320
234
            .unwrap_or_else(|| CssPropertyWithConditionsVec::from_const_slice(SLIDER_TRACK_STYLE))
321
234
    }
322

            
323
    /// The thumb CSS this slider renders with, including the `margin-left` that
324
    /// puts the thumb at the current value.
325
    ///
326
    /// `None` means no opinion, so the value decides — the same answer both
327
    /// themes give, asked in one place so they cannot drift. It is also why
328
    /// `set_value` no longer rebuilds a style: the thumb's position was cached
329
    /// beside the value it is computed from, so a setter that updated one and
330
    /// not the other drew the thumb at the wrong place.
331
    #[must_use]
332
430
    pub fn resolved_thumb_style(&self) -> CssPropertyWithConditionsVec {
333
430
        self.thumb_style.clone().into_option().unwrap_or_else(|| {
334
426
            let inner = &self.slider_state.inner;
335
426
            build_thumb_style(value_to_fraction(inner.value, inner.min, inner.max))
336
426
        })
337
430
    }
338

            
339
    /// Pick the widget theme. Unset (`None`), the widget renders in the
340
    /// default theme (`crate::widgets::themes::UiTheme::default()`).
341
    pub const fn set_theme(&mut self, theme: crate::widgets::themes::UiTheme) {
342
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
343
    }
344

            
345
    /// Sets the current value (clamped to the range).
346
    ///
347
    /// Does not touch `thumb_style`: the thumb's `margin-left` is resolved from
348
    /// the value when the DOM is built.
349
    #[inline]
350
151
    pub fn set_value(&mut self, value: f32) {
351
151
        let min = self.slider_state.inner.min;
352
151
        let max = self.slider_state.inner.max;
353
151
        self.slider_state.inner.value = clamp_to_range(value, min, max);
354
151
    }
355

            
356
    /// Builder-style setter for the current value.
357
    #[inline]
358
    #[must_use]
359
10
    pub fn with_value(mut self, value: f32) -> Self {
360
10
        self.set_value(value);
361
10
        self
362
10
    }
363

            
364
    #[inline]
365
    #[must_use]
366
6
    pub fn swap_with_default(&mut self) -> Self {
367
6
        let mut s = Self::create(0.0, 0.0, 100.0);
368
6
        core::mem::swap(&mut s, self);
369
6
        s
370
6
    }
371

            
372
    #[inline]
373
18
    pub fn set_on_value_change<C: Into<SliderOnValueChangeCallback>>(
374
18
        &mut self,
375
18
        data: RefAny,
376
18
        on_value_change: C,
377
18
    ) {
378
18
        self.slider_state.on_value_change = Some(SliderOnValueChange {
379
18
            callback: on_value_change.into(),
380
18
            refany: data,
381
18
        })
382
18
        .into();
383
18
    }
384

            
385
    #[inline]
386
    #[must_use]
387
13
    pub fn with_on_value_change<C: Into<SliderOnValueChangeCallback>>(
388
13
        mut self,
389
13
        data: RefAny,
390
13
        on_value_change: C,
391
13
    ) -> Self {
392
13
        self.set_on_value_change(data, on_value_change);
393
13
        self
394
13
    }
395

            
396
    #[inline]
397
    #[must_use]
398
    pub const fn with_theme(mut self, theme: crate::widgets::themes::UiTheme) -> Self {
399
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
400
        self
401
    }
402

            
403
    #[must_use]
404
217
    pub fn dom(self) -> Dom {
405
217
        match self.theme {
406
            crate::widgets::themes::OptionUiTheme::Some(crate::widgets::themes::UiTheme::Flat) => {
407
217
                crate::widgets::themes::flat::slider(self)
408
            }
409
            crate::widgets::themes::OptionUiTheme::Some(crate::widgets::themes::UiTheme::Flora) => {
410
                crate::widgets::themes::flora::slider(self)
411
            }
412
            _ => Dom::create_div(),
413
        }
414
217
    }
415
}
416

            
417
impl Default for Slider {
418
6
    fn default() -> Self {
419
6
        Self::create(0.0, 0.0, 100.0)
420
6
    }
421
}
422

            
423
/// Shared logic for press + drag: compute the value from the cursor's X position
424
/// relative to the track, slide the thumb live, and invoke the user callback.
425
#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // bounded layout/render
426
                                                                        // numeric cast
427
110
fn apply_cursor_value(slider: &mut SliderStateWrapper, info: &mut CallbackInfo) -> Update {
428
110
    let Some(pos) = info.get_cursor_relative_to_node().into_option() else {
429
5
        return Update::DoNothing;
430
    };
431
    // Track width in LOGICAL px (falls back to the design width before first layout).
432
105
    let width = info
433
105
        .get_hit_node_rect()
434
105
        .map(|r| r.size.width)
435
105
        .filter(|w| *w > 0.0)
436
105
        .unwrap_or(TRACK_WIDTH as f32);
437

            
438
105
    let fraction = (pos.x / width).clamp(0.0, 1.0);
439
105
    let min = slider.inner.min;
440
105
    let max = slider.inner.max;
441
105
    slider.inner.value = fraction.mul_add(max - min, min);
442

            
443
105
    commit_value(slider, info, fraction, width)
444
110
}
445

            
446
/// Move the thumb and tell the app - the ONE commit path, shared by the drag
447
/// and the arrow keys so the two can never diverge.
448
105
fn commit_value(
449
105
    slider: &mut SliderStateWrapper,
450
105
    info: &mut CallbackInfo,
451
105
    fraction: f32,
452
105
    width: f32,
453
105
) -> Update {
454
105
    let track_id = info.get_hit_node();
455
105
    if let Some(thumb_id) = info.get_first_child(track_id) {
456
102
        let margin = (fraction * (width - THUMB_SIZE as f32)).round() as isize;
457
102
        info.set_css_property(
458
102
            thumb_id,
459
102
            CssProperty::const_margin_left(LayoutMarginLeft::const_px(margin)),
460
102
        );
461
102
    }
462
105
    let inner = slider.inner;
463
105
    match slider.on_value_change.as_mut() {
464
4
        Some(SliderOnValueChange { callback, refany }) => {
465
4
            (callback.cb)(refany.clone(), *info, inner)
466
        }
467
101
        None => Update::DoNothing,
468
    }
469
105
}
470

            
471
#[must_use]
472
/// Arrow-key control, so a slider is usable without a mouse: Left/Down step
473
/// DOWN and Right/Up step UP, by 1% of the range - or 10% with Ctrl (Cmd on
474
/// macOS), the same fine/coarse pair the colour picker uses.
475
///
476
/// Commits through `commit_value`, exactly like a drag.
477
pub extern "C" fn on_slider_key(mut data: RefAny, mut info: CallbackInfo) -> Update {
478
    use azul_core::window::VirtualKeyCode as K;
479

            
480
    let Some(mut slider) = data.downcast_mut::<SliderStateWrapper>() else {
481
        return Update::DoNothing;
482
    };
483
    let ks = info.get_current_keyboard_state();
484
    let Some(key) = ks.current_virtual_keycode.into_option() else {
485
        return Update::DoNothing;
486
    };
487
    let dir = match key {
488
        K::Left | K::Down => -1.0_f32,
489
        K::Right | K::Up => 1.0,
490
        // Everything else keeps its default (Tab moves on, Escape clears).
491
        _ => return Update::DoNothing,
492
    };
493
    let step_fraction = if ks.ctrl_down() || ks.super_down() {
494
        0.10
495
    } else {
496
        0.01
497
    };
498

            
499
    let (min, max) = (slider.inner.min, slider.inner.max);
500
    let span = max - min;
501
    if !span.is_finite() || span <= 0.0 {
502
        return Update::DoNothing;
503
    }
504
    let next = dir.mul_add(step_fraction * span, slider.inner.value);
505
    slider.inner.value = clamp_to_range(next, min, max);
506
    let fraction = value_to_fraction(slider.inner.value, min, max);
507

            
508
    let width = info
509
        .get_hit_node_rect()
510
        .map(|r| r.size.width)
511
        .filter(|w| *w > 0.0)
512
        .unwrap_or(TRACK_WIDTH as f32);
513

            
514
    // The arrow must not also scroll the page under the slider.
515
    info.prevent_default();
516
    commit_value(&mut slider, &mut info, fraction, width)
517
}
518

            
519
#[must_use]
520
/// Pointer down → begin a drag and set the value from the press position.
521
53
pub extern "C" fn on_slider_pointer_down(mut data: RefAny, mut info: CallbackInfo) -> Update {
522
53
    let Some(mut slider) = data.downcast_mut::<SliderStateWrapper>() else {
523
1
        return Update::DoNothing;
524
    };
525
52
    slider.dragging = true;
526
52
    apply_cursor_value(&mut slider, &mut info)
527
53
}
528

            
529
#[must_use]
530
/// Pointer move → if a drag is active, track the value to the cursor.
531
18
pub extern "C" fn on_slider_pointer_move(mut data: RefAny, mut info: CallbackInfo) -> Update {
532
18
    let Some(mut slider) = data.downcast_mut::<SliderStateWrapper>() else {
533
1
        return Update::DoNothing;
534
    };
535
17
    if !slider.dragging {
536
16
        return Update::DoNothing;
537
1
    }
538
1
    apply_cursor_value(&mut slider, &mut info)
539
18
}
540

            
541
#[must_use]
542
/// Pointer up → end the drag.
543
20
pub extern "C" fn on_slider_pointer_up(mut data: RefAny, _info: CallbackInfo) -> Update {
544
20
    if let Some(mut slider) = data.downcast_mut::<SliderStateWrapper>() {
545
19
        slider.dragging = false;
546
19
    }
547
20
    Update::DoNothing
548
20
}
549

            
550
#[must_use]
551
/// Pointer leave → end the drag, but only when the pointer left the TRACK.
552
///
553
/// Every event bubbles here (`W3C` `mouseleave` does not), so the thumb's own
554
/// `MouseLeave` reaches this handler too — and the first real drag motion
555
/// leaves the thumb, because the thumb is slid to the cursor only by the
556
/// `MouseOver` handler that runs before the leave is delivered. Ending the
557
/// drag on that made the slider follow the pointer for exactly one move.
558
/// The callback sees its own node (the track), not the event's origin, so
559
/// the cursor decides: still inside the track's rect means the pointer only
560
/// left a child.
561
pub extern "C" fn on_slider_pointer_leave(mut data: RefAny, info: CallbackInfo) -> Update {
562
    let still_inside = match (
563
        info.get_cursor_relative_to_node().into_option(),
564
        info.get_hit_node_rect(),
565
    ) {
566
        (Some(pos), Some(rect)) => {
567
            pos.x >= 0.0 && pos.y >= 0.0 && pos.x < rect.size.width && pos.y < rect.size.height
568
        }
569
        _ => false,
570
    };
571
    if still_inside {
572
        return Update::DoNothing;
573
    }
574
    if let Some(mut slider) = data.downcast_mut::<SliderStateWrapper>() {
575
        slider.dragging = false;
576
    }
577
    Update::DoNothing
578
}
579

            
580
#[must_use]
581
/// Carry the interaction state across a parent rebuild.
582
///
583
/// A callback that returns `RefreshDom` — the `AzWidgets` demo does, on every
584
/// `on_value_change` — rebuilds the slider from the app's state. Without this,
585
/// the rebuilt slider started with `dragging = false` and the app's (possibly
586
/// stale) value: the SECOND pointer move of every drag found no drag in
587
/// flight and did nothing, so the slider could only be clicked, never
588
/// dragged, in any app that refreshes on change — and the thumb snapped back
589
/// to wherever the app last stored it between the two.
590
///
591
/// Rule: the pointer wins while it is down. `dragging` always carries over;
592
/// the live value carries over only mid-drag (the app was told the new value
593
/// through `on_value_change`; an app that stores it gets the same number, one
594
/// that does not would otherwise yank the thumb from under the finger). Once
595
/// the pointer is up the app's value is the truth again, as for any
596
/// controlled widget. The `on_value_change` hook is taken from the FRESH
597
/// build so a rebuilt closure/data is honoured.
598
3
pub extern "C" fn merge_slider_state(mut new_data: RefAny, mut old_data: RefAny) -> RefAny {
599
    {
600
3
        let new_guard = new_data.downcast_mut::<SliderStateWrapper>();
601
3
        let old_guard = old_data.downcast_ref::<SliderStateWrapper>();
602
3
        if let (Some(mut new_g), Some(old_g)) = (new_guard, old_guard) {
603
3
            new_g.dragging = old_g.dragging;
604
3
            if old_g.dragging {
605
2
                // Verbatim (no clamp: `f32::clamp` panics on NaN bounds, which
606
2
                // an FFI caller can write). The next pointer move re-derives
607
2
                // the value from the cursor against the fresh range anyway.
608
2
                new_g.inner.value = old_g.inner.value;
609
2
            }
610
        }
611
    }
612
3
    new_data
613
3
}
614

            
615
impl From<Slider> for Dom {
616
1
    fn from(s: Slider) -> Self {
617
1
        s.dom()
618
1
    }
619
}
620

            
621
// ────────── Adversarial autotest coverage ────────────────────────────
622
//
623
// The slider is a pure `f32 -> fraction -> whole-pixel margin` pipeline wrapped
624
// in three pointer callbacks. Everything below feeds it values a real app (or an
625
// FFI caller writing the `#[repr(C)]` `pub` fields directly) can produce — an
626
// inverted `[min, max]`, a NaN bound, an infinite range, a cursor outside the
627
// track, a zero-width track, a foreign payload — and asserts the widget
628
// *contains* them instead of panicking or sliding the thumb off the rail.
629
#[cfg(all(test, feature = "std"))]
630
#[allow(
631
    clippy::float_cmp,
632
    clippy::cast_precision_loss,
633
    clippy::cast_possible_truncation,
634
    clippy::unreadable_literal,
635
    clippy::too_many_lines
636
)]
637
mod autotest_generated {
638
    use std::{
639
        collections::{BTreeMap, HashMap},
640
        mem::discriminant,
641
        panic::{catch_unwind, AssertUnwindSafe},
642
        sync::{Arc, Mutex},
643
    };
644

            
645
    use azul_core::{
646
        dom::{
647
            DomId, DomNodeId, EventFilter, FormattingContext, HoverEventFilter, NodeId, NodeType,
648
        },
649
        geom::{LogicalPosition, LogicalRect, LogicalSize, OptionLogicalPosition},
650
        gl::OptionGlContextPtr,
651
        hit_test::ScrollPosition,
652
        refany::OptionRefAny,
653
        resources::RendererResources,
654
        styled_dom::{NodeHierarchyItemId, StyledDom},
655
        window::{MonitorVec, RawWindowHandle},
656
    };
657
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
658
    use rust_fontconfig::FcFontCache;
659

            
660
    use super::*;
661
    #[cfg(feature = "icu")]
662
    use crate::icu::IcuLocalizerHandle;
663
    use crate::{
664
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
665
        solver3::{
666
            display_list::DisplayList,
667
            geometry::PackedBoxProps,
668
            layout_tree::{LayoutNodeHot, LayoutTree},
669
        },
670
        widgets::theme_probe,
671
        window::{DomLayoutResult, LayoutWindow},
672
        window_state::FullWindowState,
673
    };
674

            
675
    // ------------------------------------------------------------------
676
    // Fixtures
677
    // ------------------------------------------------------------------
678

            
679
    /// The travel the thumb has along the design-width track: a thumb at
680
    /// `fraction == 1.0` must sit flush against the right end, not past it.
681
    const TRAVEL: f32 = (TRACK_WIDTH - THUMB_SIZE) as f32; // 184.0
682

            
683
    /// The whole design width of the track, as an `f32` — the value
684
    /// `apply_cursor_value` falls back to before the first layout.
685
    const DESIGN_WIDTH: f32 = TRACK_WIDTH as f32; // 200.0
686

            
687
    /// Fractions `value_to_fraction` can actually hand to `build_thumb_style`:
688
    /// the closed unit interval (plus both signed zeroes) and NaN, which is what
689
    /// a NaN value/bound collapses to. Nothing else is reachable through the
690
    /// public API — the out-of-contract extremes get their own probe.
691
    const REACHABLE_FRACTIONS: [f32; 10] = [
692
        0.0,
693
        -0.0,
694
        f32::MIN_POSITIVE,
695
        f32::EPSILON,
696
        0.001,
697
        0.25,
698
        0.5,
699
        0.75,
700
        1.0,
701
        f32::NAN,
702
    ];
703

            
704
    /// `[min, max]` ranges a caller can legally build (`min <= max`, both finite).
705
    const SANE_RANGES: [(f32, f32); 8] = [
706
        (0.0, 100.0),
707
        (0.0, 1.0),
708
        (-100.0, -50.0),
709
        (-50.0, 50.0),
710
        (0.0, 0.0),
711
        (-7.5, 7.5),
712
        (1.0, 1.0e9),
713
        (-1.0e9, 1.0e9),
714
    ];
715

            
716
    /// Ranges that break `f32::clamp`'s `min <= max` precondition. Every one of
717
    /// them is expressible: `SliderState`'s `min`/`max` are `pub` fields on a
718
    /// `#[repr(C)]` struct that crosses the C/FFI boundary.
719
    const DEGENERATE_RANGES: [(f32, f32); 6] = [
720
        (100.0, 0.0),
721
        (1.0, -1.0),
722
        (f32::NAN, 100.0),
723
        (0.0, f32::NAN),
724
        (f32::NAN, f32::NAN),
725
        (f32::INFINITY, f32::NEG_INFINITY),
726
    ];
727

            
728
    // ------------------------------------------------------------------
729
    // Style-vec probes
730
    // ------------------------------------------------------------------
731

            
732
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
733
        v.as_ref().iter().map(|p| p.property.clone()).collect()
734
    }
735

            
736
    /// The `f32` behind a `PixelValue`, asserting it is an absolute `px` length.
737
    /// An `em`/`%` slipping into the thumb offset would resolve against the
738
    /// parent font/box, so "92px along the rail" could land anywhere.
739
    fn px(pv: PixelValue) -> f32 {
740
        assert_eq!(
741
            pv.metric,
742
            SizeMetric::Px,
743
            "slider geometry must be absolute px, got {:?}",
744
            pv.metric,
745
        );
746
        pv.number.get()
747
    }
748

            
749
    /// The declared `margin-left` of a style vec — the thumb's position.
750
    fn margin_left(v: &CssPropertyWithConditionsVec) -> Option<f32> {
751
        v.as_ref().iter().find_map(|p| match &p.property {
752
            CssProperty::MarginLeft(m) => m.get_property().map(|m| px(m.inner)),
753
            _ => None,
754
        })
755
    }
756

            
757
    fn width_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
758
        v.as_ref().iter().find_map(|p| match &p.property {
759
            CssProperty::Width(w) => match w.get_property() {
760
                Some(LayoutWidth::Px(pv)) => Some(px(*pv)),
761
                _ => None,
762
            },
763
            _ => None,
764
        })
765
    }
766

            
767
    fn height_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
768
        v.as_ref().iter().find_map(|p| match &p.property {
769
            CssProperty::Height(h) => match h.get_property() {
770
                Some(LayoutHeight::Px(pv)) => Some(px(*pv)),
771
                _ => None,
772
            },
773
            _ => None,
774
        })
775
    }
776

            
777
    fn background(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
778
        v.as_ref().iter().find_map(|p| match &p.property {
779
            CssProperty::BackgroundContent(b) => match b.get_property()?.as_ref().first()? {
780
                StyleBackgroundContent::Color(c) => Some(*c),
781
                _ => None,
782
            },
783
            _ => None,
784
        })
785
    }
786

            
787
    /// The thumb offset a freshly built widget declares.
788
    fn thumb_margin(s: &Slider) -> f32 {
789
        margin_left(&s.resolved_thumb_style()).expect("the thumb style must declare a margin-left")
790
    }
791

            
792
    fn classes(dom: &Dom) -> Vec<String> {
793
        dom.root
794
            .get_ids_and_classes()
795
            .as_ref()
796
            .iter()
797
            .filter_map(|c| match c {
798
                Class(s) => Some(s.as_str().to_string()),
799
                IdOrClass::Id(_) => None,
800
            })
801
            .collect()
802
    }
803

            
804
    fn inline_properties(dom: &Dom) -> Vec<CssProperty> {
805
        dom.root
806
            .style
807
            .iter_inline_properties()
808
            .map(|(p, _)| p.clone())
809
            .collect()
810
    }
811

            
812
    // ------------------------------------------------------------------
813
    // Callback harness
814
    // ------------------------------------------------------------------
815

            
816
    fn node(idx: usize) -> DomNodeId {
817
        DomNodeId {
818
            dom: DomId::ROOT_ID,
819
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
820
        }
821
    }
822

            
823
    fn node_none() -> DomNodeId {
824
        DomNodeId {
825
            dom: DomId::ROOT_ID,
826
            node: NodeHierarchyItemId::NONE,
827
        }
828
    }
829

            
830
    /// A layout result carrying only the styled DOM: the hierarchy is real (so
831
    /// `get_first_child` resolves the thumb) but nothing is laid out, so
832
    /// `get_hit_node_rect` returns `None` — the pre-first-layout state a widget
833
    /// is in when the very first `MouseDown` arrives.
834
    fn unlaid(styled_dom: StyledDom) -> DomLayoutResult {
835
        DomLayoutResult {
836
            styled_dom,
837
            layout_tree: LayoutTree {
838
                nodes: Vec::new(),
839
                warm: Vec::new(),
840
                cold: Vec::new(),
841
                root: 0,
842
                dom_to_layout: BTreeMap::new(),
843
                children_arena: Vec::new(),
844
                children_offsets: Vec::new(),
845
                subtree_needs_intrinsic: Vec::new(),
846
            },
847
            calculated_positions: Vec::new(),
848
            viewport: LogicalRect::zero(),
849
            display_list: Arc::new(DisplayList::default()),
850
            scroll_ids: HashMap::new(),
851
            scroll_id_to_node_id: HashMap::new(),
852
        }
853
    }
854

            
855
    /// The same DOM, but laid out: node 0 (the track) reports `track` as its
856
    /// used size, so `get_hit_node_rect` yields a real width.
857
    fn laid_out_at(styled_dom: StyledDom, track: LogicalSize) -> DomLayoutResult {
858
        let hot = |dom_node: usize, size: LogicalSize, parent: Option<usize>| LayoutNodeHot {
859
            box_props: PackedBoxProps::default(),
860
            dom_node_id: Some(NodeId::new(dom_node)),
861
            used_size: Some(size),
862
            formatting_context: FormattingContext::Flex,
863
            parent,
864
        };
865
        let mut dom_to_layout = BTreeMap::new();
866
        dom_to_layout.insert(NodeId::new(0), vec![LayoutNodeId::new(0)]);
867
        dom_to_layout.insert(NodeId::new(1), vec![LayoutNodeId::new(1)]);
868

            
869
        let mut result = unlaid(styled_dom);
870
        result.layout_tree.nodes = vec![
871
            hot(0, track, None),
872
            hot(
873
                1,
874
                LogicalSize::new(THUMB_SIZE as f32, THUMB_SIZE as f32),
875
                Some(0),
876
            ),
877
        ];
878
        result.layout_tree.dom_to_layout = dom_to_layout;
879
        result.calculated_positions = vec![LogicalPosition::zero(), LogicalPosition::zero()];
880
        result
881
    }
882

            
883
    /// Runs `f` with a real `CallbackInfo` over `layout`, hitting `hit`, with
884
    /// `cursor` reported as the cursor position relative to the hit node.
885
    /// Returns `f`'s value plus everything the callback pushed onto the log.
886
    fn with_info<R>(
887
        layout: DomLayoutResult,
888
        hit: DomNodeId,
889
        cursor: OptionLogicalPosition,
890
        f: impl FnOnce(&mut CallbackInfo) -> R,
891
    ) -> (R, Vec<CallbackChange>) {
892
        let mut layout_window =
893
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
894
        layout_window.layout_results.insert(DomId::ROOT_ID, layout);
895

            
896
        let renderer_resources = RendererResources::default();
897
        let previous_window_state: Option<FullWindowState> = None;
898
        let current_window_state = FullWindowState::default();
899
        let gl_context = OptionGlContextPtr::None;
900
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
901
            BTreeMap::new();
902
        let window_handle = RawWindowHandle::Unsupported;
903
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
904

            
905
        let ref_data = CallbackInfoRefData {
906
            layout_window: &layout_window,
907
            renderer_resources: &renderer_resources,
908
            previous_window_state: &previous_window_state,
909
            current_window_state: &current_window_state,
910
            gl_context: &gl_context,
911
            current_scroll_manager: &scroll_states,
912
            current_window_handle: &window_handle,
913
            system_callbacks: &system_callbacks,
914
            system_style: Arc::new(azul_css::system::SystemStyle::default()),
915
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
916
            #[cfg(feature = "icu")]
917
            icu_localizer: IcuLocalizerHandle::default(),
918
            ctx: OptionRefAny::None,
919
        };
920

            
921
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
922
        let mut info = CallbackInfo::new(
923
            &ref_data,
924
            &changes,
925
            hit,
926
            cursor,
927
            OptionLogicalPosition::None,
928
        );
929

            
930
        let out = f(&mut info);
931
        let pushed = info.take_changes();
932
        (out, pushed)
933
    }
934

            
935
    /// Renders `slider` and hands back the styled DOM *plus the very `RefAny`
936
    /// the widget registered on its own handlers* — driving the callbacks with
937
    /// these two is the real wiring, so a mismatch between what `dom()` stores
938
    /// and what the handlers expect cannot hide behind the fixture.
939
    fn wired(slider: Slider) -> (StyledDom, RefAny) {
940
        let dom = slider.dom();
941
        let state = dom.root.callbacks.as_ref()[0].refany.clone();
942
        (StyledDom::create_from_dom(dom), state)
943
    }
944

            
945
    fn cursor(x: f32, y: f32) -> OptionLogicalPosition {
946
        OptionLogicalPosition::Some(LogicalPosition::new(x, y))
947
    }
948

            
949
    /// One pointer event of `kind` delivered to the widget's own handler.
950
    fn deliver(
951
        slider: Slider,
952
        state: &RefAny,
953
        hit: DomNodeId,
954
        at: OptionLogicalPosition,
955
        track: Option<LogicalSize>,
956
        kind: extern "C" fn(RefAny, CallbackInfo) -> Update,
957
    ) -> (Update, Vec<CallbackChange>) {
958
        let styled = StyledDom::create_from_dom(slider.dom());
959
        let layout = match track {
960
            Some(t) => laid_out_at(styled, t),
961
            None => unlaid(styled),
962
        };
963
        with_info(layout, hit, at, |info| kind(state.clone(), *info))
964
    }
965

            
966
    /// A press at `x` on a never-laid-out slider — the common path.
967
    fn press_at(slider: Slider, x: f32) -> (Update, Vec<CallbackChange>, SliderStateWrapper) {
968
        let (styled, state) = wired(slider);
969
        let (update, changes) = with_info(unlaid(styled), node(0), cursor(x, 8.0), |info| {
970
            on_slider_pointer_down(state.clone(), *info)
971
        });
972
        (update, changes, read_state(&state))
973
    }
974

            
975
    fn read_state(state: &RefAny) -> SliderStateWrapper {
976
        let mut state = state.clone();
977
        let wrapper = state
978
            .downcast_ref::<SliderStateWrapper>()
979
            .expect("the widget state changed type");
980
        wrapper.clone()
981
    }
982

            
983
    /// Every `(node, margin-left)` pair a callback pushed onto the change log.
984
    fn pushed_margins(changes: &[CallbackChange]) -> Vec<(NodeId, f32)> {
985
        changes
986
            .iter()
987
            .filter_map(|c| match c {
988
                CallbackChange::ChangeNodeCssProperties {
989
                    node_id,
990
                    properties,
991
                    ..
992
                } => properties
993
                    .as_ref()
994
                    .iter()
995
                    .find_map(|p| match p {
996
                        CssProperty::MarginLeft(m) => m.get_property().map(|m| px(m.inner)),
997
                        _ => None,
998
                    })
999
                    .map(|m| (*node_id, m)),
                _ => None,
            })
            .collect()
    }
    /// What `apply_cursor_value` is documented to compute: the cursor fraction
    /// of the track, mapped onto `[min, max]`. `mul_add` (not `a * b + c`) so
    /// the expectation is bit-identical to the implementation.
    fn expected_value(x: f32, width: f32, min: f32, max: f32) -> f32 {
        (x / width).clamp(0.0, 1.0).mul_add(max - min, min)
    }
    // ------------------------------------------------------------------
    // User-hook probes
    // ------------------------------------------------------------------
    /// A payload the value-change hook writes into. It arrives as the `data`
    /// argument — a *shared* clone of what the test still holds — so the test
    /// reads back exactly what the widget passed, with no global state.
    #[derive(Debug, Clone, Default, PartialEq)]
    struct ValueLog {
        seen: Vec<SliderState>,
    }
    extern "C" fn record_value(mut data: RefAny, _: CallbackInfo, state: SliderState) -> Update {
        if let Some(mut log) = data.downcast_mut::<ValueLog>() {
            log.seen.push(state);
        }
        Update::RefreshDom
    }
    extern "C" fn value_do_nothing(_: RefAny, _: CallbackInfo, _: SliderState) -> Update {
        Update::DoNothing
    }
    extern "C" fn value_refresh_all(_: RefAny, _: CallbackInfo, _: SliderState) -> Update {
        Update::RefreshDomAllWindows
    }
    /// A `Callback`-shaped (2-arg) function — the shape FFI bindings hand in,
    /// which the `From<Callback>` arm *transmutes* into the 3-arg slider slot.
    extern "C" fn generic_shaped(_: RefAny, _: CallbackInfo) -> Update {
        Update::DoNothing
    }
    fn log_refany() -> RefAny {
        RefAny::new(ValueLog::default())
    }
    fn read_log(probe: &RefAny) -> ValueLog {
        let mut probe = probe.clone();
        let log = probe
            .downcast_ref::<ValueLog>()
            .expect("the user payload changed type");
        log.clone()
    }
    fn hook_ptr(s: &Slider) -> Option<usize> {
        s.slider_state
            .on_value_change
            .as_ref()
            .map(|h| h.callback.cb as *const () as usize)
    }
    // ==================================================================
    // value_to_fraction  (numeric)
    // ==================================================================
    #[test]
    fn value_to_fraction_maps_the_endpoints_and_the_midpoint_exactly() {
        assert_eq!(value_to_fraction(0.0, 0.0, 100.0), 0.0);
        assert_eq!(value_to_fraction(100.0, 0.0, 100.0), 1.0);
        assert_eq!(value_to_fraction(50.0, 0.0, 100.0), 0.5);
        assert_eq!(value_to_fraction(25.0, 0.0, 100.0), 0.25);
        // A range that does not start at zero catches a `value / max` shortcut.
        assert_eq!(value_to_fraction(150.0, 100.0, 200.0), 0.5);
        assert_eq!(value_to_fraction(-75.0, -100.0, -50.0), 0.5);
    }
    #[test]
    fn value_to_fraction_clamps_instead_of_letting_the_thumb_leave_the_rail() {
        for (value, min, max) in [
            (200.0_f32, 0.0_f32, 100.0_f32),
            (-1.0, 0.0, 100.0),
            (1.0e30, 0.0, 1.0),
            (-1.0e30, 0.0, 1.0),
            (f32::MAX, -1.0, 1.0),
            (f32::MIN, -1.0, 1.0),
        ] {
            let f = value_to_fraction(value, min, max);
            assert!(
                (0.0..=1.0).contains(&f),
                "value_to_fraction({value}, {min}, {max}) = {f} is outside [0, 1]",
            );
        }
        assert_eq!(value_to_fraction(200.0, 0.0, 100.0), 1.0);
        assert_eq!(value_to_fraction(-1.0, 0.0, 100.0), 0.0);
    }
    #[test]
    fn value_to_fraction_guards_the_zero_width_and_inverted_range() {
        // `max <= min` is the documented guard: a zero-width range would be a
        // division by zero (0/0 = NaN, x/0 = ±inf) and an inverted one would
        // run the fraction backwards.
        for (value, min, max) in [
            (0.0_f32, 0.0_f32, 0.0_f32),
            (5.0, 5.0, 5.0),
            (-5.0, -5.0, -5.0),
            (1.0e9, 7.0, 7.0),
            (50.0, 100.0, 0.0),
            (50.0, 1.0, -1.0),
        ] {
            assert_eq!(
                value_to_fraction(value, min, max),
                0.0,
                "a degenerate range [{min}, {max}] must pin the thumb left",
            );
        }
    }
    #[test]
    fn value_to_fraction_is_monotonic_across_the_whole_range() {
        // A sign slip in `(value - min) / (max - min)` still returns values in
        // [0, 1] — only the ordering catches a reversed rail.
        let mut previous = f32::NEG_INFINITY;
        for i in -50..=150 {
            let f = value_to_fraction(i as f32, 0.0, 100.0);
            assert!(
                f >= previous,
                "the fraction went backwards at value = {i} ({f} < {previous})",
            );
            previous = f;
        }
        assert_eq!(previous, 1.0);
    }
    #[test]
    fn value_to_fraction_nan_inputs_do_not_panic_and_stay_nan() {
        // `f32::clamp` only asserts on its *bounds* (0.0/1.0 here), so a NaN
        // `self` propagates rather than panicking. Downstream,
        // `build_thumb_style` turns that NaN into a zero margin.
        assert!(value_to_fraction(f32::NAN, 0.0, 100.0).is_nan());
        // A NaN bound makes `max <= min` false, so the guard does *not* fire and
        // the arithmetic produces NaN — still no panic.
        assert!(value_to_fraction(50.0, f32::NAN, 100.0).is_nan());
        assert!(value_to_fraction(50.0, 0.0, f32::NAN).is_nan());
        assert!(value_to_fraction(f32::NAN, f32::NAN, f32::NAN).is_nan());
    }
    #[test]
    fn value_to_fraction_never_escapes_the_unit_interval_for_any_input() {
        // The only contract that matters downstream: the result is either NaN
        // (which `build_thumb_style` casts to a 0 margin) or a real fraction.
        // Anything else slides the thumb off the track.
        let interesting = [
            0.0_f32,
            -0.0,
            1.0,
            -1.0,
            50.0,
            f32::MIN_POSITIVE,
            f32::EPSILON,
            f32::MAX,
            f32::MIN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::NAN,
        ];
        for value in interesting {
            for min in interesting {
                for max in interesting {
                    let f = value_to_fraction(value, min, max);
                    assert!(
                        f.is_nan() || (0.0..=1.0).contains(&f),
                        "value_to_fraction({value}, {min}, {max}) = {f} escaped [0, 1]",
                    );
                }
            }
        }
    }
    #[test]
    fn value_to_fraction_infinite_bounds_produce_a_defined_result() {
        // An unbounded range has no meaningful fraction: `inf / inf` is NaN, and
        // the widget must treat that as "pin the thumb", not as a panic.
        assert!(value_to_fraction(0.0, f32::NEG_INFINITY, f32::INFINITY).is_nan());
        assert!(value_to_fraction(-50.0, f32::NEG_INFINITY, 0.0).is_nan());
        // A half-open range collapses every finite value onto the closed end.
        assert_eq!(value_to_fraction(50.0, 0.0, f32::INFINITY), 0.0);
        // An infinite *value* inside a finite range saturates instead of wrapping.
        assert_eq!(value_to_fraction(f32::INFINITY, 0.0, 100.0), 1.0);
        assert_eq!(value_to_fraction(f32::NEG_INFINITY, 0.0, 100.0), 0.0);
    }
    #[test]
    fn value_to_fraction_survives_a_range_whose_width_overflows_f32() {
        // `f32::MAX - f32::MIN` overflows to +inf, so the fraction degenerates:
        // every finite value divides down to 0.0 (the thumb pins left instead of
        // tracking the value) and the very top of the range becomes inf/inf =
        // NaN. Neither escapes [0, 1] and neither panics — downstream both park
        // the thumb at the left end, because a NaN margin casts to 0.
        for value in [f32::MIN, -1.0e30, 0.0, 1.0e30] {
            assert_eq!(
                value_to_fraction(value, f32::MIN, f32::MAX),
                0.0,
                "an f32-wide range should collapse {value} onto the left end",
            );
        }
        assert!(value_to_fraction(f32::MAX, f32::MIN, f32::MAX).is_nan());
        assert_eq!(margin_left(&build_thumb_style(f32::NAN)), Some(0.0));
    }
    #[test]
    fn value_to_fraction_is_pure() {
        for (min, max) in SANE_RANGES {
            for value in [min, max, 0.0, -1.0, 1.0e9] {
                let a = value_to_fraction(value, min, max);
                let b = value_to_fraction(value, min, max);
                assert!(
                    a == b || (a.is_nan() && b.is_nan()),
                    "value_to_fraction({value}, {min}, {max}) is not deterministic",
                );
            }
        }
    }
    // ==================================================================
    // build_thumb_style  (numeric)
    // ==================================================================
    #[test]
    fn build_thumb_style_endpoints_keep_the_thumb_inside_the_track() {
        assert_eq!(margin_left(&build_thumb_style(0.0)), Some(0.0));
        assert_eq!(margin_left(&build_thumb_style(1.0)), Some(TRAVEL));
        // The right end must leave exactly one thumb-width of room, otherwise
        // the thumb overhangs the rail it is supposed to sit on.
        assert_eq!(TRAVEL + THUMB_SIZE as f32, DESIGN_WIDTH);
    }
    #[test]
    fn build_thumb_style_rounds_to_whole_pixels() {
        // The margin is an `isize` of logical px: fractional positions must round
        // (not truncate), else the thumb drifts left by up to a pixel.
        for (fraction, expected) in [
            (0.5_f32, 92.0_f32),
            (0.25, 46.0),
            (0.75, 138.0),
            (0.1, 18.0),  // 18.4 -> 18
            (0.9, 166.0), // 165.6 -> 166
            (0.001, 0.0), // 0.184 -> 0
        ] {
            assert_eq!(
                margin_left(&build_thumb_style(fraction)),
                Some(expected),
                "fraction {fraction} landed on the wrong pixel",
            );
        }
    }
    #[test]
    fn build_thumb_style_is_monotonic_and_bounded_over_the_unit_interval() {
        let mut previous = f32::NEG_INFINITY;
        for i in 0..=1000 {
            let m = margin_left(&build_thumb_style(i as f32 / 1000.0))
                .expect("every thumb style declares a margin-left");
            assert!(m >= previous, "the thumb moved backwards at {i}/1000");
            assert!(
                (0.0..=TRAVEL).contains(&m),
                "the thumb left the rail at {i}/1000 (margin {m})",
            );
            previous = m;
        }
    }
    #[test]
    fn build_thumb_style_nan_fraction_pins_the_thumb_left_instead_of_panicking() {
        // `NaN as isize` saturates to 0 in Rust (it has been a defined saturating
        // cast since 1.45, not UB), so a NaN value/bound leaves the thumb parked
        // at the left end rather than at a garbage offset.
        assert_eq!(margin_left(&build_thumb_style(f32::NAN)), Some(0.0));
    }
    #[test]
    fn build_thumb_style_negative_and_signed_zero_fractions_are_deterministic() {
        assert_eq!(margin_left(&build_thumb_style(-0.0)), Some(0.0));
        assert_eq!(margin_left(&build_thumb_style(-1.0)), Some(-TRAVEL));
        assert_eq!(margin_left(&build_thumb_style(-0.5)), Some(-92.0));
    }
    #[test]
    fn build_thumb_style_declares_the_full_thumb_geometry_exactly_once() {
        let props = properties(&build_thumb_style(0.5));
        assert_eq!(props.len(), 9, "the thumb style changed shape: {props:?}");
        let mut seen = Vec::new();
        for p in &props {
            let d = discriminant(p);
            assert!(!seen.contains(&d), "the thumb style declares {p:?} twice");
            seen.push(d);
        }
        // A duplicate declaration would silently let the later one win; a missing
        // margin-left would freeze the thumb at the left end forever.
        assert!(
            matches!(props.last(), Some(CssProperty::MarginLeft(_))),
            "margin-left must be the last (position-dependent) declaration",
        );
    }
    #[test]
    fn build_thumb_style_geometry_is_absolute_px_and_independent_of_the_fraction() {
        for fraction in REACHABLE_FRACTIONS {
            let v = build_thumb_style(fraction);
            assert_eq!(width_px(&v), Some(THUMB_SIZE as f32), "fraction {fraction}");
            assert_eq!(
                height_px(&v),
                Some(THUMB_SIZE as f32),
                "fraction {fraction}"
            );
            assert_eq!(background(&v), Some(THUMB_COLOR), "fraction {fraction}");
        }
    }
    #[test]
    fn build_thumb_style_only_the_margin_depends_on_the_fraction() {
        // Everything but `margin-left` must be byte-identical across fractions —
        // otherwise dragging the thumb would restyle the whole knob every frame.
        let strip = |f: f32| -> Vec<CssProperty> {
            properties(&build_thumb_style(f))
                .into_iter()
                .filter(|p| !matches!(p, CssProperty::MarginLeft(_)))
                .collect()
        };
        let reference = strip(0.0);
        for fraction in REACHABLE_FRACTIONS {
            assert_eq!(
                strip(fraction),
                reference,
                "fraction {fraction} restyled the thumb"
            );
        }
    }
    #[test]
    fn build_thumb_style_is_pure_for_every_reachable_fraction() {
        for fraction in REACHABLE_FRACTIONS {
            assert_eq!(
                build_thumb_style(fraction),
                build_thumb_style(fraction),
                "build_thumb_style({fraction}) is not deterministic",
            );
        }
    }
    #[test]
    fn build_thumb_style_handles_every_fraction_value_to_fraction_can_produce() {
        // The full reachable domain, end to end: nothing here may panic and the
        // thumb may never leave the rail.
        for fraction in REACHABLE_FRACTIONS {
            let m = margin_left(&build_thumb_style(fraction))
                .expect("every thumb style declares a margin-left");
            assert!(
                (0.0..=TRAVEL).contains(&m),
                "fraction {fraction} put the thumb at {m}, off a {TRAVEL}px rail",
            );
        }
    }
    #[test]
    fn build_thumb_style_out_of_contract_fractions_must_not_panic() {
        // `build_thumb_style` takes a bare `f32` with no guard. Its only caller
        // feeds it `value_to_fraction`'s clamped output, so these are currently
        // unreachable — but the margin is encoded as `isize * 1000`
        // (`FloatValue::const_new`), so any |fraction| above ~5e13 overflows that
        // multiply and *panics* in an overflow-checked build instead of
        // saturating. A clamp inside `build_thumb_style` (or a saturating
        // `const_px`) would make the helper safe on its own terms.
        let hostile: [f32; 6] = [
            1.0e14,
            -1.0e14,
            1.0e30,
            f32::MAX,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ];
        let panicked: Vec<f32> = hostile
            .iter()
            .copied()
            .filter(|&f| catch_unwind(AssertUnwindSafe(|| build_thumb_style(f))).is_err())
            .collect();
        assert!(
            panicked.is_empty(),
            "build_thumb_style overflows the isize fixed-point encoding and panics instead of \
             saturating for: {panicked:?}",
        );
    }
    // ==================================================================
    // Slider::create  (numeric)
    // ==================================================================
    #[test]
    fn create_clamps_the_value_into_the_range() {
        assert_eq!(
            Slider::create(150.0, 0.0, 100.0).slider_state.inner.value,
            100.0
        );
        assert_eq!(
            Slider::create(-50.0, 0.0, 100.0).slider_state.inner.value,
            0.0
        );
        assert_eq!(
            Slider::create(50.0, 0.0, 100.0).slider_state.inner.value,
            50.0
        );
        assert_eq!(
            Slider::create(f32::MAX, -1.0, 1.0).slider_state.inner.value,
            1.0
        );
        assert_eq!(
            Slider::create(f32::MIN, -1.0, 1.0).slider_state.inner.value,
            -1.0
        );
    }
    #[test]
    fn create_stores_the_bounds_verbatim() {
        for (min, max) in SANE_RANGES {
            let s = Slider::create(min, min, max);
            assert_eq!(s.slider_state.inner.min, min, "min was rewritten");
            assert_eq!(s.slider_state.inner.max, max, "max was rewritten");
        }
    }
    #[test]
    fn create_places_the_thumb_where_the_pure_helpers_say_it_belongs() {
        // The composition `create -> value_to_fraction -> build_thumb_style` is
        // the whole widget: a mismatch means the rendered thumb and the stored
        // value disagree.
        for (min, max) in SANE_RANGES {
            for value in [min, max, (min + max) / 2.0, min - 1.0, max + 1.0, 0.0] {
                let s = Slider::create(value, min, max);
                let expected = margin_left(&build_thumb_style(value_to_fraction(
                    value.clamp(min, max),
                    min,
                    max,
                )));
                assert_eq!(
                    margin_left(&s.resolved_thumb_style()),
                    expected,
                    "create({value}, {min}, {max}) put the thumb in the wrong place",
                );
            }
        }
    }
    #[test]
    fn create_leaves_the_thumb_on_the_rail_for_every_sane_range() {
        for (min, max) in SANE_RANGES {
            for value in [min, max, (min + max) / 2.0, min - 1.0e9, max + 1.0e9] {
                let m = thumb_margin(&Slider::create(value, min, max));
                assert!(
                    (0.0..=TRAVEL).contains(&m),
                    "create({value}, {min}, {max}) parked the thumb at {m}",
                );
            }
        }
    }
    #[test]
    fn create_with_a_zero_width_range_pins_the_thumb_left() {
        for bound in [0.0_f32, 5.0, -5.0, 1.0e9] {
            let s = Slider::create(bound, bound, bound);
            assert_eq!(s.slider_state.inner.value, bound);
            assert_eq!(
                thumb_margin(&s),
                0.0,
                "a [{bound}, {bound}] range must pin left"
            );
        }
    }
    #[test]
    fn create_with_a_nan_value_keeps_the_nan_but_still_parks_the_thumb() {
        // `f32::clamp` only asserts on its bounds, so a NaN *value* passes
        // straight through — and the NaN fraction has to degrade to a 0 margin
        // rather than an arbitrary offset.
        let s = Slider::create(f32::NAN, 0.0, 100.0);
        assert!(
            s.slider_state.inner.value.is_nan(),
            "the NaN value was silently rewritten"
        );
        assert_eq!(thumb_margin(&s), 0.0);
    }
    #[test]
    fn create_with_infinite_bounds_does_not_panic() {
        // `min <= max` holds for these, so `clamp` is happy; the fraction is NaN
        // (inf / inf) and must degrade to a parked thumb.
        for (value, min, max) in [
            (0.0_f32, f32::NEG_INFINITY, f32::INFINITY),
            (f32::INFINITY, 0.0, f32::INFINITY),
            (f32::NEG_INFINITY, f32::NEG_INFINITY, 0.0),
            (50.0, 0.0, f32::INFINITY),
        ] {
            let s = Slider::create(value, min, max);
            let m = thumb_margin(&s);
            assert!(
                m.is_finite() && (0.0..=TRAVEL).contains(&m),
                "create({value}, {min}, {max}) put the thumb at {m}",
            );
        }
    }
    #[test]
    fn create_with_a_degenerate_range_must_not_panic() {
        // `create` runs `value.clamp(min, max)`, and `f32::clamp` **panics**
        // unless `min <= max` — a NaN bound fails that too. `min`/`max` are `pub`
        // fields on a `#[repr(C)]` struct that crosses the C/FFI boundary, so
        // nothing stops a caller from asking for an inverted or NaN-bounded
        // slider, and a panic here takes the whole app with it. Normalising the
        // range (swap, or fall back to the default) would be safe; unwinding is
        // not. Note `apply_cursor_value` already tolerates these ranges — only
        // the constructor and `set_value` do not.
        let panicked: Vec<(f32, f32)> = DEGENERATE_RANGES
            .iter()
            .copied()
            .filter(|&(min, max)| {
                catch_unwind(AssertUnwindSafe(|| Slider::create(0.0, min, max))).is_err()
            })
            .collect();
        assert!(
            panicked.is_empty(),
            "Slider::create panics (f32::clamp asserts min <= max) instead of normalising these \
             ranges: {panicked:?}",
        );
    }
    #[test]
    fn create_is_deterministic_and_distinguishes_distinct_values() {
        for (min, max) in SANE_RANGES {
            assert_eq!(Slider::create(min, min, max), Slider::create(min, min, max));
        }
        assert_ne!(
            Slider::create(0.0, 0.0, 100.0),
            Slider::create(100.0, 0.0, 100.0)
        );
        // Same value, different range: the states differ even though the thumb
        // ends up in the same place.
        assert_ne!(
            Slider::create(0.0, 0.0, 100.0),
            Slider::create(0.0, 0.0, 200.0)
        );
    }
    #[test]
    fn create_installs_no_hook_and_starts_undragged() {
        let s = Slider::create(50.0, 0.0, 100.0);
        assert!(
            s.slider_state.on_value_change.as_ref().is_none(),
            "create invented a value-change hook out of nowhere",
        );
        assert!(
            !s.slider_state.dragging,
            "a fresh slider must not be mid-drag"
        );
    }
    #[test]
    fn create_track_style_is_shared_and_value_independent() {
        // The rail is parameter-free, so every slider must hand out the very same
        // const table — a per-instance copy would allocate on every rebuild.
        let reference = properties(&Slider::create(0.0, 0.0, 100.0).resolved_track_style());
        for (min, max) in SANE_RANGES {
            assert_eq!(
                properties(&Slider::create(max, min, max).resolved_track_style()),
                reference,
                "the track style leaked a dependency on [{min}, {max}]",
            );
        }
        assert_eq!(reference.len(), 13, "the track style changed shape");
    }
    #[test]
    fn create_track_geometry_is_absolute_px_and_declared_once() {
        let s = Slider::create(50.0, 0.0, 100.0);
        assert_eq!(width_px(&s.resolved_track_style()), Some(DESIGN_WIDTH));
        assert_eq!(
            height_px(&s.resolved_track_style()),
            Some(TRACK_HEIGHT as f32)
        );
        assert_eq!(background(&s.resolved_track_style()), Some(RAIL_COLOR));
        let props = properties(&s.resolved_track_style());
        let mut seen = Vec::new();
        for p in &props {
            let d = discriminant(p);
            assert!(!seen.contains(&d), "the track style declares {p:?} twice");
            seen.push(d);
        }
        // Without `cursor: pointer` the rail looks inert even though it carries
        // every pointer handler; with `flex-grow != 0` it would stretch and stop
        // being the 200px box the fallback width assumes.
        assert!(props.contains(&CssProperty::const_cursor(StyleCursor::Pointer)));
        assert!(props.contains(&CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))));
    }
    #[test]
    fn default_is_exactly_create_0_0_100() {
        assert_eq!(Slider::default(), Slider::create(0.0, 0.0, 100.0));
        assert_eq!(Slider::default().slider_state.inner, SliderState::default());
        assert_eq!(SliderState::default().min, 0.0);
        assert_eq!(SliderState::default().max, 100.0);
        assert_eq!(SliderState::default().value, 0.0);
    }
    // ==================================================================
    // Slider::set_value / with_value
    // ==================================================================
    #[test]
    fn set_value_clamps_and_moves_the_thumb_together() {
        // The thumb's `margin-left` used to be cached in `thumb_style` and
        // rebuilt by `set_value`, so the position and the value it is computed
        // from were two facts that could disagree. It is resolved from the value
        // now — `thumb_margin` asks the resolver — which is why this still reads
        // as one assertion about two things.
        let mut s = Slider::create(0.0, 0.0, 100.0);
        for (input, expected_value) in [
            (50.0_f32, 50.0_f32),
            (100.0, 100.0),
            (150.0, 100.0),
            (-1.0, 0.0),
            (f32::INFINITY, 100.0),
            (f32::NEG_INFINITY, 0.0),
            (0.0, 0.0),
        ] {
            s.set_value(input);
            assert_eq!(
                s.slider_state.inner.value, expected_value,
                "set_value({input})"
            );
            assert_eq!(
                thumb_margin(&s),
                margin_left(&build_thumb_style(value_to_fraction(
                    expected_value,
                    0.0,
                    100.0
                )))
                .expect("margin"),
                "set_value({input}) did not move the thumb with the value",
            );
        }
    }
    #[test]
    fn set_value_never_touches_the_bounds() {
        for (min, max) in SANE_RANGES {
            let mut s = Slider::create(min, min, max);
            s.set_value(1.0e9);
            s.set_value(-1.0e9);
            assert_eq!(s.slider_state.inner.min, min);
            assert_eq!(s.slider_state.inner.max, max);
        }
    }
    #[test]
    fn set_value_round_trips_every_value_inside_the_range() {
        // value -> (clamp, fraction, margin) -> value: the stored value must come
        // back bit-identical for anything already inside the range.
        let mut s = Slider::create(0.0, 0.0, 100.0);
        for i in 0..=100 {
            let v = i as f32;
            s.set_value(v);
            assert_eq!(
                s.slider_state.inner.value, v,
                "{v} did not survive set_value"
            );
            assert_eq!(
                thumb_margin(&s),
                (v / 100.0 * TRAVEL).round(),
                "{v} landed on the wrong pixel",
            );
        }
    }
    #[test]
    fn an_explicit_thumb_style_outranks_the_value() {
        // `Some` is the caller's answer: a slider handed its own thumb style
        // keeps it when the value moves, which is the distinction a pre-filled
        // field could not express.
        let mut s = Slider::create(0.0, 0.0, 100.0);
        s.thumb_style = OptionCssPropertyWithConditionsVec::Some(build_thumb_style(0.5));
        let pinned = margin_left(&build_thumb_style(0.5)).expect("margin");
        s.set_value(100.0);
        assert_eq!(
            s.slider_state.inner.value, 100.0,
            "the value must still move"
        );
        assert_eq!(
            thumb_margin(&s),
            pinned,
            "an explicit thumb style must not be recomputed from the value",
        );
    }
    #[test]
    fn set_value_is_idempotent() {
        let mut s = Slider::create(0.0, 0.0, 100.0);
        s.set_value(37.5);
        let once = s.clone();
        s.set_value(37.5);
        assert_eq!(s, once, "re-setting the same value changed the widget");
    }
    #[test]
    fn set_value_with_nan_parks_the_thumb_without_panicking() {
        let mut s = Slider::create(50.0, 0.0, 100.0);
        s.set_value(f32::NAN);
        assert!(s.slider_state.inner.value.is_nan());
        assert_eq!(thumb_margin(&s), 0.0);
        // ...and the widget still recovers on the next sane write.
        s.set_value(25.0);
        assert_eq!(s.slider_state.inner.value, 25.0);
        assert_eq!(thumb_margin(&s), 46.0);
    }
    #[test]
    fn set_value_on_a_degenerate_range_must_not_panic() {
        // Same `f32::clamp` precondition as `create`, but reachable *without*
        // ever calling `create` with a bad range: the bounds are `pub`, so an FFI
        // caller (or a Rust caller doing `s.slider_state.inner.max = ...`) can
        // invert them between construction and the next `set_value`.
        let panicked: Vec<(f32, f32)> = DEGENERATE_RANGES
            .iter()
            .copied()
            .filter(|&(min, max)| {
                let mut s = Slider::create(0.0, 0.0, 100.0);
                s.slider_state.inner.min = min;
                s.slider_state.inner.max = max;
                catch_unwind(AssertUnwindSafe(move || s.set_value(1.0))).is_err()
            })
            .collect();
        assert!(
            panicked.is_empty(),
            "Slider::set_value panics (f32::clamp asserts min <= max) on these externally-set \
             ranges: {panicked:?}",
        );
    }
    #[test]
    fn with_value_is_exactly_set_value() {
        for v in [0.0_f32, 50.0, 100.0, 150.0, -1.0, f32::INFINITY] {
            let mut expected = Slider::create(0.0, 0.0, 100.0);
            expected.set_value(v);
            assert_eq!(
                Slider::create(0.0, 0.0, 100.0).with_value(v),
                expected,
                "with_value({v}) diverged from set_value({v})",
            );
        }
    }
    #[test]
    fn with_value_keeps_the_hook_it_was_handed() {
        // The builder moves `self`; dropping the callback on the way through
        // would silently disconnect a slider that still looks correct.
        let s = Slider::create(0.0, 0.0, 100.0)
            .with_on_value_change(
                log_refany(),
                record_value as SliderOnValueChangeCallbackType,
            )
            .with_value(80.0);
        assert_eq!(hook_ptr(&s), Some(record_value as *const () as usize));
        assert_eq!(s.slider_state.inner.value, 80.0);
    }
    #[test]
    fn with_value_chains_to_the_last_write() {
        let s = Slider::create(0.0, 0.0, 100.0)
            .with_value(10.0)
            .with_value(90.0)
            .with_value(45.0);
        assert_eq!(s.slider_state.inner.value, 45.0);
        assert_eq!(thumb_margin(&s), (0.45 * TRAVEL).round());
    }
    // ==================================================================
    // Slider::swap_with_default
    // ==================================================================
    #[test]
    fn swap_with_default_returns_the_old_widget_and_leaves_a_default_behind() {
        let mut s = Slider::create(75.0, 50.0, 200.0);
        let old = s.swap_with_default();
        assert_eq!(old.slider_state.inner.value, 75.0);
        assert_eq!(old.slider_state.inner.min, 50.0);
        assert_eq!(old.slider_state.inner.max, 200.0);
        assert_eq!(
            s,
            Slider::default(),
            "the hole was not filled with a default"
        );
    }
    #[test]
    fn swap_with_default_moves_the_hook_out_with_the_old_widget() {
        let mut s = Slider::create(10.0, 0.0, 100.0).with_on_value_change(
            log_refany(),
            record_value as SliderOnValueChangeCallbackType,
        );
        let old = s.swap_with_default();
        assert_eq!(hook_ptr(&old), Some(record_value as *const () as usize));
        assert_eq!(hook_ptr(&s), None, "the hook survived the swap");
    }
    #[test]
    fn swap_with_default_is_an_involution_when_chained() {
        let original = Slider::create(33.0, 0.0, 100.0);
        let mut s = original.clone();
        let first = s.swap_with_default();
        s = first;
        assert_eq!(s, original, "swap-then-restore lost state");
    }
    #[test]
    fn swap_with_default_does_not_panic_for_hostile_widgets() {
        // The replacement is always `create(0, 0, 100)`, so the swap itself is
        // safe even when the outgoing widget holds NaN/infinite state.
        for (value, min, max) in [
            (f32::NAN, 0.0_f32, 100.0_f32),
            (0.0, f32::NEG_INFINITY, f32::INFINITY),
            (5.0, 5.0, 5.0),
        ] {
            let mut s = Slider::create(value, min, max);
            let old = s.swap_with_default();
            assert_eq!(s, Slider::default());
            assert_eq!(old.slider_state.inner.min, min);
        }
    }
    // ==================================================================
    // Slider::set_on_value_change / with_on_value_change
    // ==================================================================
    #[test]
    fn set_on_value_change_stores_the_pointer_and_the_payload() {
        let probe = RefAny::new(0xDEAD_BEEF_u32);
        let mut s = Slider::create(0.0, 0.0, 100.0);
        s.set_on_value_change(
            probe.clone(),
            record_value as SliderOnValueChangeCallbackType,
        );
        let hook = s
            .slider_state
            .on_value_change
            .as_ref()
            .expect("the hook was dropped");
        assert_eq!(
            hook.callback.cb as *const () as usize,
            record_value as *const () as usize
        );
        let mut stored = hook.refany.clone();
        assert_eq!(
            *stored
                .downcast_ref::<u32>()
                .expect("the payload changed type"),
            0xDEAD_BEEF,
        );
    }
    #[test]
    fn set_on_value_change_replaces_a_previous_hook() {
        // The setter writes `Some(..)` unconditionally; a caller re-registering
        // must end up with exactly one (the newest) hook, not the first one.
        let mut s = Slider::create(0.0, 0.0, 100.0);
        s.set_on_value_change(
            RefAny::new(1u8),
            record_value as SliderOnValueChangeCallbackType,
        );
        s.set_on_value_change(
            RefAny::new(2u8),
            value_refresh_all as SliderOnValueChangeCallbackType,
        );
        assert_eq!(hook_ptr(&s), Some(value_refresh_all as *const () as usize));
        let mut stored = s
            .slider_state
            .on_value_change
            .as_ref()
            .expect("hook")
            .refany
            .clone();
        assert_eq!(*stored.downcast_ref::<u8>().expect("payload"), 2);
    }
    #[test]
    fn set_on_value_change_leaves_the_value_and_both_styles_untouched() {
        let before = Slider::create(60.0, 0.0, 100.0);
        let mut after = before.clone();
        after.set_on_value_change(
            log_refany(),
            record_value as SliderOnValueChangeCallbackType,
        );
        assert_eq!(after.slider_state.inner, before.slider_state.inner);
        assert_eq!(after.resolved_track_style(), before.resolved_track_style());
        assert_eq!(after.resolved_thumb_style(), before.resolved_thumb_style());
    }
    #[test]
    fn with_on_value_change_matches_the_setter() {
        let a = Slider::create(60.0, 0.0, 100.0).with_on_value_change(
            RefAny::new(9u8),
            record_value as SliderOnValueChangeCallbackType,
        );
        let mut b = Slider::create(60.0, 0.0, 100.0);
        b.set_on_value_change(
            RefAny::new(9u8),
            record_value as SliderOnValueChangeCallbackType,
        );
        assert_eq!(hook_ptr(&a), hook_ptr(&b));
        assert_eq!(a.slider_state.inner, b.slider_state.inner);
    }
    #[test]
    fn with_on_value_change_accepts_a_generic_callback_without_mangling_the_pointer() {
        // The `From<Callback>` arm *transmutes* a 2-arg fn pointer into the 3-arg
        // slider slot — this is the FFI (Python/C) path. The pointer must come
        // out bit-identical; a mangled one is a wild jump on the first drag.
        let generic = Callback {
            cb: generic_shaped,
            ctx: OptionRefAny::None,
        };
        let s = Slider::create(0.0, 0.0, 100.0).with_on_value_change(RefAny::new(0u8), generic);
        assert_eq!(
            hook_ptr(&s),
            Some(generic_shaped as *const () as usize),
            "the Callback -> SliderOnValueChangeCallback transmute mangled the pointer",
        );
    }
    #[test]
    fn with_on_value_change_does_not_panic_for_hostile_widgets() {
        for (value, min, max) in [
            (f32::NAN, 0.0_f32, 100.0_f32),
            (0.0, f32::NEG_INFINITY, f32::INFINITY),
            (7.0, 7.0, 7.0),
        ] {
            let s = Slider::create(value, min, max).with_on_value_change(
                log_refany(),
                record_value as SliderOnValueChangeCallbackType,
            );
            assert!(s.slider_state.on_value_change.as_ref().is_some());
        }
    }
    // ==================================================================
    // Slider::dom
    // ==================================================================
    #[test]
    fn dom_renders_a_classed_track_with_exactly_one_thumb_child() {
        let dom = Slider::create(50.0, 0.0, 100.0).dom();
        assert_eq!(classes(&dom), vec!["__azul-native-slider".to_string()]);
        assert!(matches!(dom.root.get_node_type(), NodeType::Div));
        let kids = dom.children.as_ref();
        assert_eq!(
            kids.len(),
            1,
            "the track must have exactly one child (the thumb)"
        );
        assert_eq!(
            classes(&kids[0]),
            vec!["__azul-native-slider-thumb".to_string()]
        );
        assert!(
            kids[0].children.as_ref().is_empty(),
            "the thumb must be a leaf"
        );
    }
    #[test]
    fn dom_is_keyboard_reachable() {
        // A slider that cannot take focus is unusable without a mouse.
        let dom = Slider::create(0.0, 0.0, 100.0).dom();
        assert_eq!(dom.root.get_tab_index(), Some(TabIndex::Auto));
    }
    #[test]
    fn dom_registers_every_input_filter_exactly_once_in_order() {
        let dom = Slider::create(0.0, 0.0, 100.0).dom();
        let expected: [(EventFilter, usize); 8] = [
            (
                EventFilter::Hover(HoverEventFilter::MouseDown),
                on_slider_pointer_down as usize,
            ),
            (
                EventFilter::Hover(HoverEventFilter::MouseMove),
                on_slider_pointer_move as usize,
            ),
            (
                EventFilter::Hover(HoverEventFilter::MouseUp),
                on_slider_pointer_up as usize,
            ),
            // A control you can DRAG must also be drivable from the keyboard
            // (2026-09-01): arrows step 1% of the range, Ctrl/Cmd+arrows 10%.
            (
                EventFilter::Focus(azul_core::events::FocusEventFilter::VirtualKeyDown),
                on_slider_key as usize,
            ),
            (
                EventFilter::Hover(HoverEventFilter::MouseLeave),
                on_slider_pointer_leave as usize,
            ),
            (
                EventFilter::Hover(HoverEventFilter::TouchStart),
                on_slider_pointer_down as usize,
            ),
            (
                EventFilter::Hover(HoverEventFilter::TouchMove),
                on_slider_pointer_move as usize,
            ),
            (
                EventFilter::Hover(HoverEventFilter::TouchEnd),
                on_slider_pointer_up as usize,
            ),
        ];
        let got: Vec<(EventFilter, usize)> = dom
            .root
            .callbacks
            .as_ref()
            .iter()
            .map(|c| (c.event, c.callback.cb))
            .collect();
        assert_eq!(got, expected.to_vec(), "the input wiring changed");
        // Touch must not be dropped: without TouchStart/Move/End the slider is
        // dead on a touchscreen even though it looks fine under a mouse - and
        // without VirtualKeyDown it is dead for a keyboard user.
        assert_eq!(got.len(), 8);
    }
    #[test]
    fn dom_shares_one_state_refany_across_every_handler() {
        // The transient `dragging` flag set by MouseDown must be visible to the
        // MouseOver/MouseUp handlers — a per-callback `RefAny::new` would give
        // each handler its own copy and the slider would never drag.
        let dom = Slider::create(0.0, 0.0, 100.0).dom();
        let cbs = dom.root.callbacks.as_ref();
        {
            let mut first = cbs[0].refany.clone();
            let mut guard = first
                .downcast_mut::<SliderStateWrapper>()
                .expect("the state changed type");
            guard.dragging = true;
        }
        for (i, cb) in cbs.iter().enumerate() {
            let mut other = cb.refany.clone();
            let guard = other
                .downcast_ref::<SliderStateWrapper>()
                .expect("the state changed type");
            assert!(guard.dragging, "handler {i} does not share the drag state");
        }
    }
    /// The dataset the reconciler merges across rebuilds IS the callbacks'
    /// state (one allocation), and the merge keeps a drag alive: `dragging`
    /// and, mid-drag, the live value carry over; after the pointer is up the
    /// app's value from the fresh build wins.
    #[test]
    fn dom_registers_its_state_as_a_mergeable_dataset_that_keeps_a_drag_alive() {
        let dom = Slider::create(40.0, 0.0, 100.0).dom();
        let dataset = dom
            .root
            .get_dataset()
            .expect("the track carries its state as a dataset, or no merge can happen");
        let cb_state = &dom.root.callbacks.as_ref()[0].refany;
        assert_eq!(
            dataset.sharing_info.ptr as usize, cb_state.sharing_info.ptr as usize,
            "dataset and callbacks must share ONE allocation, or the reconciler cannot re-point \
             the fresh callbacks at the merged state"
        );
        assert!(
            dom.root.get_merge_callback().is_some(),
            "no merge callback registered"
        );
        // Old build: a drag in flight at 73. New build: the app re-rendered
        // with its stored (stale) 40.
        let old = RefAny::new(SliderStateWrapper {
            inner: SliderState {
                value: 73.0,
                min: 0.0,
                max: 100.0,
            },
            dragging: true,
            ..Default::default()
        });
        let fresh = RefAny::new(SliderStateWrapper {
            inner: SliderState {
                value: 40.0,
                min: 0.0,
                max: 100.0,
            },
            dragging: false,
            ..Default::default()
        });
        let mut merged = merge_slider_state(fresh, old);
        let w = merged
            .downcast_ref::<SliderStateWrapper>()
            .expect("type kept");
        assert!(w.dragging, "the drag must survive the rebuild");
        assert_eq!(
            w.inner.value, 73.0,
            "mid-drag the pointer's value wins over the app's"
        );
        drop(w);
        // Pointer up: the app's value is the truth again.
        let old_idle = RefAny::new(SliderStateWrapper {
            inner: SliderState {
                value: 73.0,
                min: 0.0,
                max: 100.0,
            },
            dragging: false,
            ..Default::default()
        });
        let fresh2 = RefAny::new(SliderStateWrapper {
            inner: SliderState {
                value: 40.0,
                min: 0.0,
                max: 100.0,
            },
            dragging: false,
            ..Default::default()
        });
        let mut merged2 = merge_slider_state(fresh2, old_idle);
        let w2 = merged2
            .downcast_ref::<SliderStateWrapper>()
            .expect("type kept");
        assert!(!w2.dragging);
        assert_eq!(
            w2.inner.value, 40.0,
            "idle: the fresh build's (app's) value is kept"
        );
    }
    /// End-to-end through the reconciler: a slider mid-drag in the OLD DOM,
    /// rebuilt by the app in the NEW DOM (the way a `RefreshDom` from
    /// `on_value_change` does), must still be dragging afterwards — read
    /// from the NEW DOM's callback state, which is what the next pointer
    /// move will see.
    #[test]
    fn a_drag_survives_reconciliation_of_a_parent_rebuild() {
        use azul_core::{
            diff::{reconcile_dom, transfer_states},
            dom::{DomId, NodeData},
            styled_dom::{NodeHierarchyItem, StyledDom},
            task::Instant,
            OrderedMap,
        };
        fn app_dom(value: f32, caption: &str) -> StyledDom {
            StyledDom::create_from_dom(
                Dom::create_body()
                    .with_child(Dom::create_div().with_child(
                        Dom::create_text_do_not_use_without_block_level_wrapper(caption),
                    ))
                    .with_child(Slider::create(value, 0.0, 100.0).dom()),
            )
        }
        fn track_state(data: &[NodeData]) -> SliderStateWrapper {
            let track = data
                .iter()
                .find(|nd| nd.get_merge_callback().is_some())
                .expect("a slider track with a merge callback");
            let mut r = track.callbacks.as_ref()[0].refany.clone();
            let w = r
                .downcast_ref::<SliderStateWrapper>()
                .expect("slider state");
            w.clone()
        }
        // Frame 1: the press set `dragging` and moved the value to 73.
        let old = app_dom(40.0, "callbacks: 0");
        {
            let track = old
                .node_data
                .as_ref()
                .iter()
                .find(|nd| nd.get_merge_callback().is_some())
                .expect("track");
            let mut r = track.callbacks.as_ref()[0].refany.clone();
            let mut w = r
                .downcast_mut::<SliderStateWrapper>()
                .expect("slider state");
            w.dragging = true;
            w.inner.value = 73.0;
        }
        // Frame 2: the app refreshed with its stored (stale) value.
        let new = app_dom(40.0, "callbacks: 1");
        let mut old_data: Vec<NodeData> = old.node_data.as_ref().to_vec();
        let mut new_data: Vec<NodeData> = new.node_data.as_ref().to_vec();
        let old_h: Vec<NodeHierarchyItem> = old.node_hierarchy.as_ref().to_vec();
        let new_h: Vec<NodeHierarchyItem> = new.node_hierarchy.as_ref().to_vec();
        let diff = reconcile_dom(
            &old_data,
            &new_data,
            &old_h,
            &new_h,
            &OrderedMap::default(),
            &OrderedMap::default(),
            DomId::ROOT_ID,
            Instant::now(),
        );
        assert!(
            diff.node_moves.iter().any(|m| {
                old_data[m.old_node_id.index()]
                    .get_merge_callback()
                    .is_some()
                    && new_data[m.new_node_id.index()]
                        .get_merge_callback()
                        .is_some()
            }),
            "the reconciler must match the old track to the new track: {:?}",
            diff.node_moves
        );
        transfer_states(&mut old_data, &mut new_data, &diff.node_moves);
        let after = track_state(&new_data);
        assert!(after.dragging, "the drag must survive the rebuild");
        assert_eq!(after.inner.value, 73.0, "mid-drag the pointer's value wins");
    }
    #[test]
    fn dom_carries_the_widgets_own_state_not_a_default() {
        let mut state = Slider::create(42.0, -10.0, 90.0)
            .dom()
            .root
            .callbacks
            .as_ref()[0]
            .refany
            .clone();
        let wrapper = state
            .downcast_ref::<SliderStateWrapper>()
            .expect("the state changed type");
        assert_eq!(wrapper.inner.value, 42.0);
        assert_eq!(wrapper.inner.min, -10.0);
        assert_eq!(wrapper.inner.max, 90.0);
        assert!(
            !wrapper.dragging,
            "a freshly rendered slider must not be mid-drag"
        );
    }
    #[test]
    fn dom_inlines_the_track_and_thumb_styles_verbatim() {
        // "Verbatim" up to the theme: on top of what the widget declares, the
        // theme appends the declarations only it can write — here a dark fill
        // for each of the two nodes, asserted by the test below. Comparing the
        // theme-independent half is what isolates the widget's own styling.
        let s = Slider::create(75.0, 0.0, 100.0);
        let (track_props, thumb_props) = (
            properties(&s.resolved_track_style()),
            properties(&s.resolved_thumb_style()),
        );
        let dom = s.dom();
        assert_eq!(theme_probe::unthemed(&dom), track_props);
        assert_eq!(
            theme_probe::unthemed(&dom.children.as_ref()[0]),
            thumb_props
        );
    }
    #[test]
    fn dom_gives_the_track_and_the_thumb_a_dark_mode_fill() {
        // Without these the slider paints its light grey track and white thumb
        // straight onto a dark surface.
        let dom = Slider::create(75.0, 0.0, 100.0).dom();
        for (what, node) in [("track", &dom), ("thumb", &dom.children.as_ref()[0])] {
            assert!(
                theme_probe::dark(node)
                    .iter()
                    .any(|p| matches!(p, CssProperty::BackgroundContent(_))),
                "the {what} has no dark fill, so it keeps its light one",
            );
        }
    }
    #[test]
    fn dom_does_not_panic_for_hostile_widgets() {
        for (value, min, max) in [
            (f32::NAN, 0.0_f32, 100.0_f32),
            (0.0, f32::NEG_INFINITY, f32::INFINITY),
            (3.0, 3.0, 3.0),
            (f32::MAX, f32::MIN, f32::MAX),
        ] {
            let dom = Slider::create(value, min, max).dom();
            assert_eq!(dom.children.as_ref().len(), 1, "({value}, {min}, {max})");
        }
    }
    #[test]
    fn from_slider_for_dom_is_exactly_dom() {
        let s = Slider::create(25.0, 0.0, 100.0);
        let via_impl: Dom = s.clone().into();
        assert_eq!(inline_properties(&via_impl), inline_properties(&s.dom()));
    }
    // ==================================================================
    // apply_cursor_value + the pointer handlers
    // ==================================================================
    #[test]
    fn a_press_maps_the_cursor_x_onto_the_range_using_the_design_width() {
        // Before the first layout there is no node rect, so the track falls back
        // to its 200px design width. Anything else silently rescales the value.
        for (x, expected) in [
            (0.0_f32, 0.0_f32),
            (50.0, 25.0),
            (100.0, 50.0),
            (200.0, 100.0),
        ] {
            let (_, _, state) = press_at(Slider::create(0.0, 0.0, 100.0), x);
            assert_eq!(
                state.inner.value, expected,
                "a press at x = {x} produced the wrong value",
            );
            assert_eq!(
                state.inner.value,
                expected_value(x, DESIGN_WIDTH, 0.0, 100.0)
            );
        }
    }
    #[test]
    fn a_press_outside_the_track_clamps_instead_of_overshooting() {
        for (x, expected) in [
            (-1.0_f32, 0.0_f32),
            (-1.0e9, 0.0),
            (201.0, 100.0),
            (1.0e9, 100.0),
            (f32::INFINITY, 100.0),
            (f32::NEG_INFINITY, 0.0),
        ] {
            let (_, _, state) = press_at(Slider::create(50.0, 0.0, 100.0), x);
            assert_eq!(
                state.inner.value, expected,
                "a press at x = {x} escaped the range"
            );
        }
    }
    #[test]
    fn a_press_maps_onto_a_negative_range_too() {
        let (_, _, state) = press_at(Slider::create(-100.0, -100.0, -50.0), 100.0);
        assert_eq!(
            state.inner.value, -75.0,
            "the midpoint of [-100, -50] is -75"
        );
    }
    #[test]
    fn a_press_slides_the_thumb_by_writing_margin_left_on_the_first_child() {
        let (update, changes, _) = press_at(Slider::create(0.0, 0.0, 100.0), 100.0);
        assert_eq!(
            update,
            Update::DoNothing,
            "no hook is installed, so nothing to redraw"
        );
        let margins = pushed_margins(&changes);
        assert_eq!(
            margins.len(),
            1,
            "exactly one thumb move per press, got {changes:?}",
        );
        let (node_id, margin) = margins[0];
        assert_eq!(
            node_id,
            NodeId::new(1),
            "the margin landed on the track, not the thumb"
        );
        assert_eq!(
            margin,
            (0.5 * TRAVEL).round(),
            "the thumb went to the wrong pixel"
        );
    }
    #[test]
    fn a_press_never_slides_the_thumb_off_the_rail() {
        for x in [
            -1.0e9_f32,
            -1.0,
            0.0,
            37.0,
            199.0,
            200.0,
            1.0e9,
            f32::INFINITY,
        ] {
            let (_, changes, _) = press_at(Slider::create(0.0, 0.0, 100.0), x);
            for (_, margin) in pushed_margins(&changes) {
                assert!(
                    (0.0..=TRAVEL).contains(&margin),
                    "a press at x = {x} put the thumb at {margin}, off a {TRAVEL}px rail",
                );
            }
        }
    }
    #[test]
    fn a_press_uses_the_real_track_width_once_the_node_is_laid_out() {
        // A slider stretched (or shrunk) by its container must map the cursor
        // against the *laid-out* width, not the 200px design width — otherwise
        // the value jumps as soon as the layout differs from the design.
        for (width, x, expected) in [
            (400.0_f32, 100.0_f32, 25.0_f32),
            (400.0, 400.0, 100.0),
            (100.0, 50.0, 50.0),
            (50.0, 200.0, 100.0), // clamped: cursor past the (short) track
        ] {
            let (styled, state) = wired(Slider::create(0.0, 0.0, 100.0));
            let layout = laid_out_at(styled, LogicalSize::new(width, TRACK_HEIGHT as f32));
            let (_, _) = with_info(layout, node(0), cursor(x, 8.0), |info| {
                on_slider_pointer_down(state.clone(), *info)
            });
            assert_eq!(
                read_state(&state).inner.value,
                expected,
                "a {width}px-wide track mapped x = {x} wrongly",
            );
        }
    }
    #[test]
    fn a_zero_width_track_falls_back_to_the_design_width_instead_of_dividing_by_zero() {
        // A collapsed track would make `pos.x / 0.0` = ±inf (or NaN at x = 0);
        // the `> 0.0` filter is what keeps the value finite.
        let (styled, state) = wired(Slider::create(0.0, 0.0, 100.0));
        let layout = laid_out_at(styled, LogicalSize::new(0.0, TRACK_HEIGHT as f32));
        with_info(layout, node(0), cursor(100.0, 8.0), |info| {
            on_slider_pointer_down(state.clone(), *info)
        });
        let value = read_state(&state).inner.value;
        assert!(value.is_finite(), "a zero-width track produced {value}");
        assert_eq!(value, 50.0, "the fallback must be the 200px design width");
    }
    #[test]
    fn a_press_without_a_cursor_latches_the_drag_but_changes_nothing() {
        // Touch/synthetic events can arrive with no cursor position at all.
        let (styled, state) = wired(Slider::create(60.0, 0.0, 100.0));
        let (update, changes) = with_info(
            unlaid(styled),
            node(0),
            OptionLogicalPosition::None,
            |info| on_slider_pointer_down(state.clone(), *info),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "the thumb moved without a cursor: {changes:?}"
        );
        let s = read_state(&state);
        assert_eq!(s.inner.value, 60.0, "the value changed without a cursor");
        assert!(s.dragging, "the press must still arm the drag");
    }
    #[test]
    fn a_nan_cursor_does_not_panic_and_leaves_the_thumb_parked() {
        let (styled, state) = wired(Slider::create(10.0, 0.0, 100.0));
        let (update, changes) = with_info(
            unlaid(styled),
            node(0),
            cursor(f32::NAN, f32::NAN),
            |info| on_slider_pointer_down(state.clone(), *info),
        );
        assert_eq!(update, Update::DoNothing);
        // NaN survives the clamp, so the value goes NaN — but the *pixel* margin
        // saturates to 0 rather than becoming a garbage offset.
        assert!(read_state(&state).inner.value.is_nan());
        assert_eq!(pushed_margins(&changes), vec![(NodeId::new(1), 0.0)]);
    }
    #[test]
    fn a_press_on_an_unknown_node_still_updates_the_value_but_moves_no_thumb() {
        // Hit nodes come from hit-testing, which can name a node this DOM does
        // not have (stale frame) or no node at all.
        for hit in [node_none(), node(99), node(usize::MAX - 1)] {
            let (styled, state) = wired(Slider::create(0.0, 0.0, 100.0));
            let (update, changes) = with_info(unlaid(styled), hit, cursor(100.0, 8.0), |info| {
                on_slider_pointer_down(state.clone(), *info)
            });
            assert_eq!(update, Update::DoNothing);
            assert_eq!(read_state(&state).inner.value, 50.0, "hit {hit:?}");
            assert!(
                pushed_margins(&changes).is_empty(),
                "a thumb was moved for a node that does not exist: {changes:?}",
            );
        }
    }
    #[test]
    fn a_move_is_ignored_until_a_press_starts_the_drag() {
        // Hover fires constantly; without the `dragging` latch the slider would
        // follow the cursor across a hover with no button held.
        let (styled, state) = wired(Slider::create(10.0, 0.0, 100.0));
        let (update, changes) = with_info(unlaid(styled), node(0), cursor(200.0, 8.0), |info| {
            on_slider_pointer_move(state.clone(), *info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty(), "a hover moved the thumb: {changes:?}");
        assert_eq!(
            read_state(&state).inner.value,
            10.0,
            "a hover changed the value"
        );
    }
    #[test]
    fn a_move_tracks_the_cursor_once_the_press_armed_the_drag() {
        let slider = Slider::create(0.0, 0.0, 100.0);
        let (styled, state) = wired(slider.clone());
        with_info(unlaid(styled), node(0), cursor(0.0, 8.0), |info| {
            on_slider_pointer_down(state.clone(), *info)
        });
        assert!(
            read_state(&state).dragging,
            "the press did not arm the drag"
        );
        let styled2 = StyledDom::create_from_dom(slider.dom());
        let (update, changes) = with_info(unlaid(styled2), node(0), cursor(150.0, 8.0), |info| {
            on_slider_pointer_move(state.clone(), *info)
        });
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            read_state(&state).inner.value,
            75.0,
            "the drag did not track the cursor"
        );
        assert_eq!(
            pushed_margins(&changes),
            vec![(NodeId::new(1), (0.75 * TRAVEL).round())]
        );
    }
    #[test]
    fn a_release_ends_the_drag_and_records_nothing() {
        let (styled, state) = wired(Slider::create(0.0, 0.0, 100.0));
        with_info(unlaid(styled), node(0), cursor(100.0, 8.0), |info| {
            on_slider_pointer_down(state.clone(), *info)
        });
        assert!(read_state(&state).dragging);
        let styled2 = StyledDom::create_from_dom(Slider::create(0.0, 0.0, 100.0).dom());
        let (update, changes) = with_info(unlaid(styled2), node(0), cursor(0.0, 8.0), |info| {
            on_slider_pointer_up(state.clone(), *info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "the release moved the thumb: {changes:?}"
        );
        let s = read_state(&state);
        assert!(!s.dragging, "the drag outlived the release");
        assert_eq!(s.inner.value, 50.0, "the release rewrote the value");
    }
    #[test]
    fn a_release_is_idempotent_and_safe_before_any_press() {
        let (styled, state) = wired(Slider::create(0.0, 0.0, 100.0));
        with_info(
            unlaid(styled),
            node(0),
            OptionLogicalPosition::None,
            |info| on_slider_pointer_up(state.clone(), *info),
        );
        assert!(!read_state(&state).dragging);
        let styled2 = StyledDom::create_from_dom(Slider::create(0.0, 0.0, 100.0).dom());
        with_info(
            unlaid(styled2),
            node(0),
            OptionLogicalPosition::None,
            |info| on_slider_pointer_up(state.clone(), *info),
        );
        assert!(!read_state(&state).dragging);
    }
    #[test]
    fn every_pointer_handler_ignores_a_foreign_payload() {
        // A mis-wired DOM (or an FFI caller passing the wrong `RefAny`) must be
        // a no-op, not a downcast panic.
        for handler in [
            on_slider_pointer_down as extern "C" fn(RefAny, CallbackInfo) -> Update,
            on_slider_pointer_move,
            on_slider_pointer_up,
        ] {
            let foreign = RefAny::new(0xABCD_u32);
            let styled = StyledDom::create_from_dom(Slider::create(0.0, 0.0, 100.0).dom());
            let (update, changes) =
                with_info(unlaid(styled), node(0), cursor(100.0, 8.0), |info| {
                    handler(foreign.clone(), *info)
                });
            assert_eq!(update, Update::DoNothing);
            assert!(
                changes.is_empty(),
                "a foreign payload still mutated the DOM: {changes:?}"
            );
            let mut foreign = foreign;
            assert_eq!(
                *foreign
                    .downcast_ref::<u32>()
                    .expect("the payload was replaced"),
                0xABCD,
            );
        }
    }
    #[test]
    fn a_press_forwards_the_hooks_update_verbatim() {
        for (cb, expected) in [
            (
                value_do_nothing as SliderOnValueChangeCallbackType,
                Update::DoNothing,
            ),
            (
                record_value as SliderOnValueChangeCallbackType,
                Update::RefreshDom,
            ),
            (
                value_refresh_all as SliderOnValueChangeCallbackType,
                Update::RefreshDomAllWindows,
            ),
        ] {
            let (styled, state) =
                wired(Slider::create(0.0, 0.0, 100.0).with_on_value_change(log_refany(), cb));
            let (update, _) = with_info(unlaid(styled), node(0), cursor(100.0, 8.0), |info| {
                on_slider_pointer_down(state.clone(), *info)
            });
            assert_eq!(update, expected, "the handler swallowed {expected:?}");
        }
    }
    #[test]
    fn the_hook_is_told_the_new_value_not_the_old_one() {
        // Passing `SliderState::default()` (or the pre-press value) would
        // type-check and would look right for exactly one press position.
        let probe = log_refany();
        let (styled, state) = wired(Slider::create(0.0, -10.0, 90.0).with_on_value_change(
            probe.clone(),
            record_value as SliderOnValueChangeCallbackType,
        ));
        let (update, _) = with_info(unlaid(styled), node(0), cursor(50.0, 8.0), |info| {
            on_slider_pointer_down(state.clone(), *info)
        });
        assert_eq!(update, Update::RefreshDom);
        assert_eq!(
            read_log(&probe).seen,
            vec![SliderState {
                value: expected_value(50.0, DESIGN_WIDTH, -10.0, 90.0),
                min: -10.0,
                max: 90.0,
            }],
        );
    }
    #[test]
    fn the_hook_is_not_called_when_there_is_no_cursor() {
        let probe = log_refany();
        let (styled, state) = wired(Slider::create(0.0, 0.0, 100.0).with_on_value_change(
            probe.clone(),
            record_value as SliderOnValueChangeCallbackType,
        ));
        with_info(
            unlaid(styled),
            node(0),
            OptionLogicalPosition::None,
            |info| on_slider_pointer_down(state.clone(), *info),
        );
        assert!(
            read_log(&probe).seen.is_empty(),
            "the hook fired without a cursor"
        );
    }
    #[test]
    fn the_hook_is_not_called_on_release() {
        let probe = log_refany();
        let (styled, state) = wired(Slider::create(0.0, 0.0, 100.0).with_on_value_change(
            probe.clone(),
            record_value as SliderOnValueChangeCallbackType,
        ));
        with_info(unlaid(styled), node(0), cursor(100.0, 8.0), |info| {
            on_slider_pointer_up(state.clone(), *info)
        });
        assert!(
            read_log(&probe).seen.is_empty(),
            "the release reported a value change"
        );
    }
    #[test]
    fn apply_cursor_value_tolerates_a_degenerate_range_without_panicking() {
        // Unlike `create`/`set_value`, this path never calls `f32::clamp` on the
        // bounds — it interpolates. That means an inverted range is survivable
        // here (the value just runs backwards), which is exactly why the panic in
        // the constructor is worth fixing rather than accepting.
        for (min, max) in DEGENERATE_RANGES {
            let mut wrapper = SliderStateWrapper {
                inner: SliderState {
                    value: 0.0,
                    min,
                    max,
                },
                ..Default::default()
            };
            let styled = StyledDom::create_from_dom(Slider::create(0.0, 0.0, 100.0).dom());
            let (update, changes) =
                with_info(unlaid(styled), node(0), cursor(100.0, 8.0), |info| {
                    apply_cursor_value(&mut wrapper, info)
                });
            assert_eq!(update, Update::DoNothing);
            let v = wrapper.inner.value;
            assert!(
                v.is_nan() || (v >= min.min(max) && v <= min.max(max)),
                "[{min}, {max}] interpolated to {v}, outside the bounds in either order",
            );
            // The thumb still stays on the rail whatever the bounds say — the
            // margin depends only on the cursor fraction, not on the range.
            for (_, margin) in pushed_margins(&changes) {
                assert!(
                    (0.0..=TRAVEL).contains(&margin),
                    "[{min}, {max}] slid the thumb to {margin}",
                );
            }
        }
    }
    #[test]
    fn apply_cursor_value_keeps_the_value_inside_any_sane_range() {
        // The documented invariant on `SliderState::value`: "always within
        // [min, max]". `apply_cursor_value` writes it without a clamp, relying
        // purely on the cursor fraction being in [0, 1].
        for (min, max) in SANE_RANGES {
            for x in [-1.0e9_f32, -1.0, 0.0, 73.0, 200.0, 1.0e9] {
                let mut wrapper = SliderStateWrapper {
                    inner: SliderState {
                        value: min,
                        min,
                        max,
                    },
                    ..Default::default()
                };
                let styled = StyledDom::create_from_dom(Slider::create(0.0, 0.0, 100.0).dom());
                with_info(unlaid(styled), node(0), cursor(x, 8.0), |info| {
                    apply_cursor_value(&mut wrapper, info)
                });
                let v = wrapper.inner.value;
                assert!(
                    (min..=max).contains(&v),
                    "a press at x = {x} put the value at {v}, outside [{min}, {max}]",
                );
            }
        }
    }
    #[test]
    fn apply_cursor_value_is_idempotent_for_a_stationary_cursor() {
        let mut wrapper = SliderStateWrapper {
            inner: SliderState {
                value: 0.0,
                min: 0.0,
                max: 100.0,
            },
            ..Default::default()
        };
        for _ in 0..3 {
            let styled = StyledDom::create_from_dom(Slider::create(0.0, 0.0, 100.0).dom());
            with_info(unlaid(styled), node(0), cursor(100.0, 8.0), |info| {
                apply_cursor_value(&mut wrapper, info)
            });
            assert_eq!(wrapper.inner.value, 50.0);
        }
    }
    #[test]
    fn deliver_smoke_test_covers_every_handler_and_layout_combination() {
        // A last sweep: every handler x {laid out, not laid out} x hostile
        // cursors, asserting only that nothing unwinds and the state stays a
        // `SliderStateWrapper`.
        for handler in [
            on_slider_pointer_down as extern "C" fn(RefAny, CallbackInfo) -> Update,
            on_slider_pointer_move,
            on_slider_pointer_up,
        ] {
            for track in [
                None,
                Some(LogicalSize::new(0.0, 0.0)),
                Some(LogicalSize::new(1.0e9, 16.0)),
            ] {
                for at in [
                    OptionLogicalPosition::None,
                    cursor(0.0, 0.0),
                    cursor(-1.0e9, 0.0),
                    cursor(f32::NAN, 0.0),
                    cursor(f32::INFINITY, 0.0),
                ] {
                    let slider = Slider::create(0.0, 0.0, 100.0);
                    let (_, state) = wired(slider.clone());
                    let (_, changes) = deliver(slider, &state, node(0), at, track, handler);
                    // Whatever happened, the shared state must still be readable.
                    let _ = read_state(&state);
                    for (_, margin) in pushed_margins(&changes) {
                        assert!(
                            margin.is_finite(),
                            "a non-finite thumb offset ({margin}) reached the DOM",
                        );
                    }
                }
            }
        }
    }
    /// KEYBOARD CONTROL (2026-09-01 request): the slider takes the same
    /// arrow-key semantics as the colour picker - 1% of the range per arrow,
    /// 10% with Ctrl/Cmd - and clamps at both ends.
    #[test]
    fn arrow_keys_step_one_percent_of_the_range_and_ctrl_steps_ten() {
        let step = |value: f32, min: f32, max: f32, dir: f32, coarse: bool| -> f32 {
            let span = max - min;
            let f = if coarse { 0.10 } else { 0.01 };
            clamp_to_range(dir.mul_add(f * span, value), min, max)
        };
        // A 0..100 range: 1% is one unit, 10% is ten.
        assert!((step(50.0, 0.0, 100.0, 1.0, false) - 51.0).abs() < 1e-4);
        assert!((step(50.0, 0.0, 100.0, -1.0, false) - 49.0).abs() < 1e-4);
        assert!((step(50.0, 0.0, 100.0, 1.0, true) - 60.0).abs() < 1e-4);
        assert!((step(50.0, 0.0, 100.0, -1.0, true) - 40.0).abs() < 1e-4);
        // The step is a fraction of the RANGE, not an absolute unit.
        assert!((step(0.5, 0.0, 1.0, 1.0, false) - 0.51).abs() < 1e-4);
        // Clamped at both ends, so holding an arrow cannot leave the range.
        assert!((step(100.0, 0.0, 100.0, 1.0, true) - 100.0).abs() < 1e-4);
        assert!((step(0.0, 0.0, 100.0, -1.0, true) - 0.0).abs() < 1e-4);
    }
}