1
//! Switch (toggle) widget — a boolean on/off control rendered as a rounded,
2
//! pill-shaped "track" with a sliding circular "knob". A near-clone of
3
//! [`crate::widgets::check_box::CheckBox`] (boolean state + an `on_toggle`
4
//! callback) restyled as a switch: toggling flips the knob's horizontal
5
//! position (via `margin-left`) and the track's background colour.
6
//!
7
//! Key types: [`Switch`], [`SwitchState`], [`SwitchOnToggle`].
8

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

            
36
use crate::{
37
    callbacks::{Callback, CallbackInfo},
38
    widgets::themes::{OptionUiTheme, UiTheme},
39
};
40

            
41
pub static SWITCH_TRACK_CLASS: &[IdOrClass] =
42
    &[Class(AzString::from_const_str("__azul-native-switch"))];
43
pub static SWITCH_KNOB_CLASS: &[IdOrClass] =
44
    &[Class(AzString::from_const_str("__azul-native-switch-knob"))];
45

            
46
/// Callback function type invoked when the switch is toggled.
47
pub type SwitchOnToggleCallbackType = extern "C" fn(RefAny, CallbackInfo, SwitchState) -> Update;
48
impl_widget_callback!(
49
    SwitchOnToggle,
50
    OptionSwitchOnToggle,
51
    SwitchOnToggleCallback,
52
    SwitchOnToggleCallbackType
53
);
54

            
55
azul_core::impl_managed_callback! {
56
    wrapper:        SwitchOnToggleCallback,
57
    info_ty:        CallbackInfo,
58
    return_ty:      Update,
59
    default_ret:    Update::DoNothing,
60
    invoker_static: SWITCH_ON_TOGGLE_INVOKER,
61
    invoker_ty:     AzSwitchOnToggleCallbackInvoker,
62
    thunk_fn:       az_switch_on_toggle_callback_thunk,
63
    setter_fn:      AzApp_setSwitchOnToggleCallbackInvoker,
64
    from_handle_fn: AzSwitchOnToggleCallback_createFromHostHandle,
65
    extra_args:     [ state: SwitchState ],
66
}
67

            
68
/// A toggleable on/off switch widget with a sliding knob and toggle callback.
69
#[derive(Debug, Clone, PartialEq, Eq)]
70
#[repr(C)]
71
pub struct Switch {
72
    pub switch_state: SwitchStateWrapper,
73
    /// Style for the switch track (the pill-shaped container)
74
    pub theme: OptionUiTheme,
75
    pub track_style: OptionCssPropertyWithConditionsVec,
76
    /// Style for the sliding knob
77
    pub knob_style: OptionCssPropertyWithConditionsVec,
78
    /// What this control is CALLED, for assistive technology.
79
    ///
80
    /// Carried by the WIDGET rather than patched onto the finished `Dom`: that
81
    /// is what lets the widget know at build time whether it was named, so its
82
    /// warning fires only when nobody supplied one. Forwarded into the
83
    /// accessibility declaration the widget builds anyway, beside its role and
84
    /// state.
85
    pub accessibility_name: OptionString,
86
}
87

            
88
#[derive(Debug, Default, Clone, PartialEq, Eq)]
89
#[repr(C)]
90
pub struct SwitchStateWrapper {
91
    /// On/off state of this Switch
92
    pub inner: SwitchState,
93
    /// Optional: function to call when the Switch is toggled
94
    pub on_toggle: OptionSwitchOnToggle,
95
}
96

            
97
/// The on/off state of a [`Switch`].
98
#[derive(Copy, Debug, Default, Clone, PartialEq, Eq)]
99
#[repr(C)]
100
pub struct SwitchState {
101
    /// `true` = on (knob slid right), `false` = off (knob at left)
102
    pub checked: bool,
103
}
104

            
105
// ---- dimensions ----
106
const TRACK_WIDTH: isize = 36;
107
const TRACK_HEIGHT: isize = 20;
108
const TRACK_PADDING: isize = 2;
109
const TRACK_RADIUS: isize = 10;
110
const KNOB_SIZE: isize = 16;
111
const KNOB_RADIUS: isize = 8;
112
/// Horizontal travel of the knob = `track_width` − 2·padding − `knob_size`.
113
const KNOB_TRAVEL: isize = TRACK_WIDTH - (2 * TRACK_PADDING) - KNOB_SIZE;
114

            
115
// ---- colours ----
116
const TRACK_OFF_COLOR: ColorU = ColorU {
117
    r: 204,
118
    g: 204,
119
    b: 204,
120
    a: 255,
121
}; // #cccccc
122
const TRACK_ON_COLOR: ColorU = ColorU {
123
    r: 76,
124
    g: 217,
125
    b: 100,
126
    a: 255,
127
}; // #4cd964
128
const KNOB_COLOR: ColorU = ColorU {
129
    r: 255,
130
    g: 255,
131
    b: 255,
132
    a: 255,
133
}; // white
134

            
135
const TRACK_OFF_BG_ITEMS: &[StyleBackgroundContent] =
136
    &[StyleBackgroundContent::Color(TRACK_OFF_COLOR)];
137
const TRACK_OFF_BG: StyleBackgroundContentVec =
138
    StyleBackgroundContentVec::from_const_slice(TRACK_OFF_BG_ITEMS);
139
const TRACK_ON_BG_ITEMS: &[StyleBackgroundContent] =
140
    &[StyleBackgroundContent::Color(TRACK_ON_COLOR)];
141
const TRACK_ON_BG: StyleBackgroundContentVec =
142
    StyleBackgroundContentVec::from_const_slice(TRACK_ON_BG_ITEMS);
143
const KNOB_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(KNOB_COLOR)];
144
const KNOB_BG: StyleBackgroundContentVec =
145
    StyleBackgroundContentVec::from_const_slice(KNOB_BG_ITEMS);
146

            
147
/// What the switch declares so its two state changes TWEEN instead of
148
/// snapping: the knob's `margin-left` travel and the track's colour.
149
///
150
/// The click handler writes both imperatively, and an imperative write now
151
/// honours a declared `animation` the same way a change found by the DOM diff
152
/// does — so this declaration is the whole animation. A spring is the engine's
153
/// default for a move; the duration is the retarget time base springs use.
154
312
fn switch_animation(property: &'static str) -> CssPropertyWithConditions {
155
    use azul_css::props::basic::{
156
        animation::{AnimationIterationCount, AnimationTiming, StyleAnimation, StyleAnimationVec},
157
        time::CssDuration,
158
    };
159
312
    CssPropertyWithConditions::simple(CssProperty::Animation(
160
312
        azul_css::props::property::StyleAnimationVecValue::Exact(StyleAnimationVec::from_vec(
161
312
            alloc::vec![StyleAnimation {
162
312
                name: AzString::from_const_str(property),
163
312
                duration: CssDuration::from_millis(150),
164
312
                delay: CssDuration::from_millis(0),
165
312
                iterations: AnimationIterationCount::Count(1),
166
312
                timing: AnimationTiming::Spring,
167
312
                clip: true,
168
312
            }],
169
312
        )),
170
312
    ))
171
312
}
172

            
173
/// Build the track (pill container) style. Background colour is the only
174
/// state-dependent property, so the style is built at runtime per the recipe's
175
/// "runtime vec if param-dependent" path.
176
#[must_use]
177
155
pub fn build_track_style(checked: bool) -> CssPropertyWithConditionsVec {
178
155
    let bg = if checked { TRACK_ON_BG } else { TRACK_OFF_BG };
179
155
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
180
155
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
181
155
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
182
155
            LayoutFlexDirection::Row,
183
        )),
184
155
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
185
155
        CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Center)),
186
155
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
187
            0,
188
        ))),
189
155
        CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(
190
            TRACK_WIDTH,
191
        ))),
192
155
        CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(
193
            TRACK_HEIGHT,
194
        ))),
195
155
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
196
155
            LayoutPaddingLeft::const_px(TRACK_PADDING),
197
        )),
198
155
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
199
155
            LayoutPaddingRight::const_px(TRACK_PADDING),
200
        )),
201
155
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(
202
155
            LayoutPaddingTop::const_px(TRACK_PADDING),
203
        )),
204
155
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
205
155
            LayoutPaddingBottom::const_px(TRACK_PADDING),
206
        )),
207
155
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
208
155
            StyleBorderTopLeftRadius::const_px(TRACK_RADIUS),
209
        )),
210
155
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
211
155
            StyleBorderTopRightRadius::const_px(TRACK_RADIUS),
212
        )),
213
155
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
214
155
            StyleBorderBottomLeftRadius::const_px(TRACK_RADIUS),
215
        )),
216
155
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
217
155
            StyleBorderBottomRightRadius::const_px(TRACK_RADIUS),
218
        )),
219
155
        CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
220
155
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg)),
221
155
        switch_animation("background"),
222
    ])
223
155
}
224

            
225
/// Build the knob style. The knob's `margin-left` is the state-dependent
226
/// property that slides it between the off (left) and on (right) positions.
227
#[must_use]
228
157
pub fn build_knob_style(checked: bool) -> CssPropertyWithConditionsVec {
229
157
    let margin = if checked { KNOB_TRAVEL } else { 0 };
230
157
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
231
157
        switch_animation("margin-left"),
232
157
        CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(
233
            KNOB_SIZE,
234
        ))),
235
157
        CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(
236
            KNOB_SIZE,
237
        ))),
238
157
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
239
            0,
240
        ))),
241
157
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
242
157
            StyleBorderTopLeftRadius::const_px(KNOB_RADIUS),
243
        )),
244
157
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
245
157
            StyleBorderTopRightRadius::const_px(KNOB_RADIUS),
246
        )),
247
157
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
248
157
            StyleBorderBottomLeftRadius::const_px(KNOB_RADIUS),
249
        )),
250
157
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
251
157
            StyleBorderBottomRightRadius::const_px(KNOB_RADIUS),
252
        )),
253
157
        CssPropertyWithConditions::simple(CssProperty::const_background_content(KNOB_BG)),
254
157
        CssPropertyWithConditions::simple(CssProperty::const_margin_left(
255
157
            LayoutMarginLeft::const_px(margin),
256
        )),
257
    ])
258
157
}
259

            
260
impl Switch {
261
    /// Creates a new switch in the given on/off state with default styling.
262
    /// Name this control for assistive technology.
263
    #[must_use]
264
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
265
        self.accessibility_name = Some(name.into()).into();
266
        self
267
    }
268

            
269
    #[must_use]
270
133
    pub fn create(checked: bool) -> Self {
271
133
        Self {
272
133
            theme: OptionUiTheme::None,
273
133
            switch_state: SwitchStateWrapper {
274
133
                inner: SwitchState { checked },
275
133
                ..Default::default()
276
133
            },
277
133
            // No opinion: `resolved_track_style` / `resolved_knob_style`
278
133
            // derive these from the checked flag when the DOM is built, so a
279
133
            // toggle still styles itself and a caller who sets one is not
280
133
            // overwritten by the next state change.
281
133
            track_style: OptionCssPropertyWithConditionsVec::None,
282
133
            knob_style: OptionCssPropertyWithConditionsVec::None,
283
133

            
284
133
            accessibility_name: OptionString::None,
285
133
        }
286
133
    }
287

            
288
    /// The track CSS this switch renders with.
289
    ///
290
    /// `None` means no opinion, so the default for the current checked state
291
    /// applies. Resolved late rather than at construction because the default
292
    /// depends on that state: writing it into the field on every toggle would
293
    /// also clobber a caller's explicit style.
294
    #[must_use]
295
133
    pub fn resolved_track_style(&self) -> CssPropertyWithConditionsVec {
296
133
        self.track_style
297
133
            .clone()
298
133
            .into_option()
299
133
            .unwrap_or_else(|| build_track_style(self.switch_state.inner.checked))
300
133
    }
301

            
302
    /// The knob CSS this switch renders with; see [`Self::resolved_track_style`].
303
    #[must_use]
304
133
    pub fn resolved_knob_style(&self) -> CssPropertyWithConditionsVec {
305
133
        self.knob_style
306
133
            .clone()
307
133
            .into_option()
308
133
            .unwrap_or_else(|| build_knob_style(self.switch_state.inner.checked))
309
133
    }
310

            
311
    #[inline]
312
    #[must_use]
313
5
    pub fn swap_with_default(&mut self) -> Self {
314
5
        let mut s = Self::create(false);
315
5
        core::mem::swap(&mut s, self);
316
5
        s
317
5
    }
318

            
319
    /// Pick the widget theme. Unset (`None`), the widget renders in the
320
    /// default theme (`UiTheme::default()`).
321
    pub const fn set_theme(&mut self, theme: UiTheme) {
322
        self.theme = OptionUiTheme::Some(theme);
323
    }
324

            
325
    /// [`Self::set_theme`] for the builder chain.
326
    #[must_use]
327
    pub const fn with_theme(mut self, theme: UiTheme) -> Self {
328
        self.set_theme(theme);
329
        self
330
    }
331

            
332
    #[inline]
333
15
    pub fn set_on_toggle<C: Into<SwitchOnToggleCallback>>(&mut self, data: RefAny, on_toggle: C) {
334
15
        self.switch_state.on_toggle = Some(SwitchOnToggle {
335
15
            callback: on_toggle.into(),
336
15
            refany: data,
337
15
        })
338
15
        .into();
339
15
    }
340

            
341
    #[inline]
342
    #[must_use]
343
9
    pub fn with_on_toggle<C: Into<SwitchOnToggleCallback>>(
344
9
        mut self,
345
9
        data: RefAny,
346
9
        on_toggle: C,
347
9
    ) -> Self {
348
9
        self.set_on_toggle(data, on_toggle);
349
9
        self
350
9
    }
351

            
352
    #[inline]
353
    #[must_use]
354
119
    pub fn dom(self) -> Dom {
355
119
        let theme = match self.theme {
356
            OptionUiTheme::Some(theme) => theme,
357
119
            OptionUiTheme::None => UiTheme::Flat,
358
        };
359
119
        match theme {
360
119
            UiTheme::Flat => crate::widgets::themes::flat::switch(self),
361
            UiTheme::Flora => crate::widgets::themes::flora::switch(self),
362
        }
363
119
    }
364
}
365

            
366
impl Default for Switch {
367
2
    fn default() -> Self {
368
2
        Self::create(false)
369
2
    }
370
}
371

            
372
// handle input events for the switch
373
pub mod input {
374

            
375
    use azul_core::{callbacks::Update, refany::RefAny};
376
    use azul_css::props::{layout::LayoutMarginLeft, property::CssProperty};
377

            
378
    use super::{SwitchOnToggle, SwitchStateWrapper, KNOB_TRAVEL, TRACK_OFF_BG, TRACK_ON_BG};
379
    use crate::callbacks::CallbackInfo;
380

            
381
    #[must_use]
382
68
    pub extern "C" fn default_on_switch_clicked(
383
68
        mut switch: RefAny,
384
68
        mut info: CallbackInfo,
385
68
    ) -> Update {
386
68
        let Some(mut switch) = switch.downcast_mut::<SwitchStateWrapper>() else {
387
1
            return Update::DoNothing;
388
        };
389

            
390
67
        let track_id = info.get_hit_node();
391
67
        let Some(knob_id) = info.get_first_child(track_id) else {
392
6
            return Update::DoNothing;
393
        };
394

            
395
61
        switch.inner.checked = !switch.inner.checked;
396

            
397
61
        let result = {
398
            // rustc doesn't understand the borrowing lifetime here
399
61
            let switch = &mut *switch;
400
61
            let on_toggle = &mut switch.on_toggle;
401
61
            let inner = switch.inner;
402

            
403
61
            match on_toggle.as_mut() {
404
                Some(SwitchOnToggle {
405
3
                    callback,
406
3
                    refany: data,
407
3
                }) => (callback.cb)(data.clone(), info, inner),
408
58
                None => Update::DoNothing,
409
            }
410
        };
411

            
412
        // The ANNOUNCED state must follow the rendered one. This handler flips
413
        // css properties and returns Update::DoNothing — no rebuild — so the
414
        // CheckedTrue/False published at build time would freeze at whatever it
415
        // was then, and a screen reader would keep reporting the old position.
416
61
        info.set_accessibility_state(
417
61
            info.get_hit_node(),
418
61
            azul_core::a11y::AccessibilityStateVec::from_const_slice(if switch.inner.checked {
419
32
                &[azul_core::a11y::AccessibilityState::CheckedTrue]
420
            } else {
421
29
                &[azul_core::a11y::AccessibilityState::CheckedFalse]
422
            }),
423
        );
424

            
425
        // CallbackInfo is Copy, so `info` is still usable after the call above.
426
61
        if switch.inner.checked {
427
32
            info.set_css_property(track_id, CssProperty::const_background_content(TRACK_ON_BG));
428
32
            info.set_css_property(
429
32
                knob_id,
430
32
                CssProperty::const_margin_left(LayoutMarginLeft::const_px(KNOB_TRAVEL)),
431
32
            );
432
32
        } else {
433
29
            info.set_css_property(
434
29
                track_id,
435
29
                CssProperty::const_background_content(TRACK_OFF_BG),
436
29
            );
437
29
            info.set_css_property(
438
29
                knob_id,
439
29
                CssProperty::const_margin_left(LayoutMarginLeft::const_px(0)),
440
29
            );
441
29
        }
442

            
443
61
        result
444
68
    }
445
}
446

            
447
impl From<Switch> for Dom {
448
2
    fn from(s: Switch) -> Self {
449
2
        s.dom()
450
2
    }
451
}
452

            
453
#[cfg(test)]
454
#[allow(clippy::float_cmp)]
455
// every float here is an exact, integral px constant
456
// `assertions_on_constants`: these are deliberate invariant guards over sibling
457
// `const`s in this module. They are const-foldable *today*, which is exactly the
458
// point — they must go red the moment someone edits one of those constants into an
459
// inconsistent value. Deleting them (clippy's suggestion) would delete the check.
460
#[allow(clippy::assertions_on_constants)]
461
mod autotest_generated {
462
    use std::{
463
        collections::{BTreeMap, HashMap},
464
        mem::discriminant,
465
        sync::{Arc, Mutex},
466
    };
467

            
468
    use azul_core::{
469
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
470
        geom::{LogicalRect, OptionLogicalPosition},
471
        gl::OptionGlContextPtr,
472
        hit_test::ScrollPosition,
473
        refany::OptionRefAny,
474
        resources::RendererResources,
475
        styled_dom::{NodeHierarchyItemId, StyledDom},
476
        window::{MonitorVec, RawWindowHandle},
477
    };
478
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
479
    use rust_fontconfig::FcFontCache;
480

            
481
    use super::*;
482
    #[cfg(feature = "icu")]
483
    use crate::icu::IcuLocalizerHandle;
484
    use crate::{
485
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
486
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
487
        window::{DomLayoutResult, LayoutWindow},
488
        window_state::FullWindowState,
489
    };
490

            
491
    // ------------------------------------------------------------------
492
    // Geometry, spelled out independently of the module's own constants
493
    // ------------------------------------------------------------------
494
    //
495
    // These literals are deliberately *not* derived from `TRACK_WIDTH` & friends:
496
    // they are the numbers a designer signed off on. If a constant upstream drifts,
497
    // the relation tests below fail instead of silently re-deriving themselves.
498

            
499
    const TRACK_W: f32 = 36.0;
500
    const TRACK_H: f32 = 20.0;
501
    const PAD: f32 = 2.0;
502
    const TRACK_R: f32 = 10.0;
503
    const KNOB: f32 = 16.0;
504
    const KNOB_R: f32 = 8.0;
505
    /// `36 - 2*2 - 16`
506
    const TRAVEL: f32 = 16.0;
507

            
508
    /// Flattened node ids of `Switch::dom()` (pre-order).
509
    const TRACK: usize = 0;
510
    const KNOB_NODE: usize = 1;
511

            
512
    // ------------------------------------------------------------------
513
    // Callback harness
514
    // ------------------------------------------------------------------
515

            
516
    /// A `DomNodeId` in the root DOM pointing at flattened node `idx`.
517
    fn node(idx: usize) -> DomNodeId {
518
        DomNodeId {
519
            dom: DomId::ROOT_ID,
520
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
521
        }
522
    }
523

            
524
    /// A `DomNodeId` whose node component is `None` — the "no concrete node was hit"
525
    /// case. `CallbackInfo::set_css_property` *panics* on such an id, so the handler
526
    /// must bail out before ever reaching it.
527
    fn node_none() -> DomNodeId {
528
        DomNodeId {
529
            dom: DomId::ROOT_ID,
530
            node: NodeHierarchyItemId::NONE,
531
        }
532
    }
533

            
534
    /// A `DomLayoutResult` carrying only a `styled_dom`: the switch handler reaches
535
    /// exactly two `CallbackInfo` queries (`get_hit_node`, `get_first_child`), and both
536
    /// read the node hierarchy only — no real layout (and no font) is needed.
537
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
538
        DomLayoutResult {
539
            styled_dom,
540
            layout_tree: LayoutTree {
541
                nodes: Vec::new(),
542
                warm: Vec::new(),
543
                cold: Vec::new(),
544
                root: 0,
545
                dom_to_layout: BTreeMap::new(),
546
                children_arena: Vec::new(),
547
                children_offsets: Vec::new(),
548
                subtree_needs_intrinsic: Vec::new(),
549
            },
550
            calculated_positions: Vec::new(),
551
            viewport: LogicalRect::zero(),
552
            display_list: Arc::new(DisplayList::default()),
553
            scroll_ids: HashMap::new(),
554
            scroll_id_to_node_id: HashMap::new(),
555
        }
556
    }
557

            
558
    /// Runs `f` with a `CallbackInfo` whose window holds `styled_dom` as the root DOM
559
    /// and whose hit node is `hit`. Returns `f`'s value plus every change the callback
560
    /// pushed onto the transaction log.
561
    fn with_info<R>(
562
        styled_dom: StyledDom,
563
        hit: DomNodeId,
564
        f: impl FnOnce(&mut CallbackInfo) -> R,
565
    ) -> (R, Vec<CallbackChange>) {
566
        let mut layout_window =
567
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
568
        layout_window
569
            .layout_results
570
            .insert(DomId::ROOT_ID, layout_result(styled_dom));
571

            
572
        let renderer_resources = RendererResources::default();
573
        let previous_window_state: Option<FullWindowState> = None;
574
        let current_window_state = FullWindowState::default();
575
        let gl_context = OptionGlContextPtr::None;
576
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
577
            BTreeMap::new();
578
        let window_handle = RawWindowHandle::Unsupported;
579
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
580

            
581
        let ref_data = CallbackInfoRefData {
582
            layout_window: &layout_window,
583
            renderer_resources: &renderer_resources,
584
            previous_window_state: &previous_window_state,
585
            current_window_state: &current_window_state,
586
            gl_context: &gl_context,
587
            current_scroll_manager: &scroll_states,
588
            current_window_handle: &window_handle,
589
            system_callbacks: &system_callbacks,
590
            system_style: Arc::new(azul_css::system::SystemStyle::default()),
591
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
592
            #[cfg(feature = "icu")]
593
            icu_localizer: IcuLocalizerHandle::default(),
594
            ctx: OptionRefAny::None,
595
        };
596

            
597
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
598

            
599
        let mut info = CallbackInfo::new(
600
            &ref_data,
601
            &changes,
602
            hit,
603
            OptionLogicalPosition::None,
604
            OptionLogicalPosition::None,
605
        );
606

            
607
        let r = f(&mut info);
608
        let pushed = info.take_changes();
609
        (r, pushed)
610
    }
611

            
612
    /// Renders `switch`, then hands back both the laid-out DOM *and* the very `RefAny`
613
    /// the widget registered on its own mouse-up callback. Driving the handler with
614
    /// these two is the real wiring — nothing is re-created by hand, so a mismatch
615
    /// between what `dom()` stores and what the handler expects cannot hide behind the
616
    /// fixture.
617
    fn laid_out(switch: Switch) -> (StyledDom, RefAny) {
618
        let dom = switch.dom();
619
        let state = dom.root.callbacks.as_ref()[0].refany.clone();
620
        (StyledDom::create_from_dom(dom), state)
621
    }
622

            
623
    /// One "mouse-up on `hit`" delivered to the widget's own registered handler.
624
    fn click(
625
        styled_dom: StyledDom,
626
        state: &RefAny,
627
        hit: DomNodeId,
628
    ) -> (Update, Vec<CallbackChange>) {
629
        with_info(styled_dom, hit, |info| {
630
            input::default_on_switch_clicked(state.clone(), *info)
631
        })
632
    }
633

            
634
    fn is_checked(state: &RefAny) -> bool {
635
        let mut state = state.clone();
636
        let wrapper = state
637
            .downcast_ref::<SwitchStateWrapper>()
638
            .expect("the widget state changed type");
639
        wrapper.inner.checked
640
    }
641

            
642
    /// Every `(node, property)` pair the handler wrote, flattened and in push order.
643
    fn pushed_pairs(changes: &[CallbackChange]) -> Vec<(NodeId, CssProperty)> {
644
        changes
645
            .iter()
646
            .filter_map(|c| match c {
647
                CallbackChange::ChangeNodeCssProperties {
648
                    node_id,
649
                    properties,
650
                    ..
651
                } => Some((*node_id, properties.as_ref().to_vec())),
652
                _ => None,
653
            })
654
            .flat_map(|(n, ps)| ps.into_iter().map(move |p| (n, p)))
655
            .collect()
656
    }
657

            
658
    fn pushed_backgrounds(changes: &[CallbackChange]) -> Vec<(NodeId, StyleBackgroundContentVec)> {
659
        pushed_pairs(changes)
660
            .into_iter()
661
            .filter_map(|(n, p)| match p {
662
                CssProperty::BackgroundContent(b) => b.get_property().cloned().map(|b| (n, b)),
663
                _ => None,
664
            })
665
            .collect()
666
    }
667

            
668
    fn pushed_margins(changes: &[CallbackChange]) -> Vec<(NodeId, f32)> {
669
        pushed_pairs(changes)
670
            .into_iter()
671
            .filter_map(|(n, p)| match p {
672
                CssProperty::MarginLeft(m) => m.get_property().map(|m| (n, px(&m.inner))),
673
                _ => None,
674
            })
675
            .collect()
676
    }
677

            
678
    // ------------------------------------------------------------------
679
    // Style-vec probes
680
    // ------------------------------------------------------------------
681

            
682
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
683
        v.as_ref().iter().map(|p| p.property.clone()).collect()
684
    }
685

            
686
    fn find<T>(
687
        v: &CssPropertyWithConditionsVec,
688
        f: impl Fn(&CssProperty) -> Option<T>,
689
    ) -> Option<T> {
690
        v.as_ref().iter().find_map(|p| f(&p.property))
691
    }
692

            
693
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length. An `em`
694
    /// or `%` slipping into the switch geometry would resolve against the parent
695
    /// font/box, so a 36px track could render at any size at all — and the knob's
696
    /// travel would no longer line up with it.
697
    fn px(pv: &PixelValue) -> f32 {
698
        assert_eq!(
699
            pv.metric,
700
            SizeMetric::Px,
701
            "switch geometry must be absolute px, got {:?}",
702
            pv.metric,
703
        );
704
        pv.number.get()
705
    }
706

            
707
    fn width_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
708
        find(v, |p| match p {
709
            CssProperty::Width(w) => match w.get_property() {
710
                Some(LayoutWidth::Px(pv)) => Some(px(pv)),
711
                _ => None,
712
            },
713
            _ => None,
714
        })
715
    }
716

            
717
    fn height_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
718
        find(v, |p| match p {
719
            CssProperty::Height(h) => match h.get_property() {
720
                Some(LayoutHeight::Px(pv)) => Some(px(pv)),
721
                _ => None,
722
            },
723
            _ => None,
724
        })
725
    }
726

            
727
    /// The knob's `margin-left` — the single property that encodes "which side is the
728
    /// knob on". This is the only thing distinguishing the two knob styles.
729
    fn margin_left_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
730
        find(v, |p| match p {
731
            CssProperty::MarginLeft(m) => m.get_property().map(|m| px(&m.inner)),
732
            _ => None,
733
        })
734
    }
735

            
736
    /// `(top, right, bottom, left)` padding, each as an absolute px.
737
    fn paddings_px(
738
        v: &CssPropertyWithConditionsVec,
739
    ) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
740
        let get = |f: fn(&CssProperty) -> Option<f32>| find(v, f);
741
        (
742
            get(|p| match p {
743
                CssProperty::PaddingTop(x) => x.get_property().map(|x| px(&x.inner)),
744
                _ => None,
745
            }),
746
            get(|p| match p {
747
                CssProperty::PaddingRight(x) => x.get_property().map(|x| px(&x.inner)),
748
                _ => None,
749
            }),
750
            get(|p| match p {
751
                CssProperty::PaddingBottom(x) => x.get_property().map(|x| px(&x.inner)),
752
                _ => None,
753
            }),
754
            get(|p| match p {
755
                CssProperty::PaddingLeft(x) => x.get_property().map(|x| px(&x.inner)),
756
                _ => None,
757
            }),
758
        )
759
    }
760

            
761
    /// The four corner radii, in declaration order. (Each corner is its own newtype, so
762
    /// the arms cannot be collapsed into an or-pattern.)
763
    fn radii_px(v: &CssPropertyWithConditionsVec) -> Vec<f32> {
764
        v.as_ref()
765
            .iter()
766
            .filter_map(|p| match &p.property {
767
                CssProperty::BorderTopLeftRadius(r) => r.get_property().map(|r| px(&r.inner)),
768
                CssProperty::BorderTopRightRadius(r) => r.get_property().map(|r| px(&r.inner)),
769
                CssProperty::BorderBottomLeftRadius(r) => r.get_property().map(|r| px(&r.inner)),
770
                CssProperty::BorderBottomRightRadius(r) => r.get_property().map(|r| px(&r.inner)),
771
                _ => None,
772
            })
773
            .collect()
774
    }
775

            
776
    fn flex_grow(v: &CssPropertyWithConditionsVec) -> Option<f32> {
777
        find(v, |p| match p {
778
            CssProperty::FlexGrow(g) => g.get_property().map(|g| g.inner.get()),
779
            _ => None,
780
        })
781
    }
782

            
783
    fn background(v: &CssPropertyWithConditionsVec) -> Option<StyleBackgroundContentVec> {
784
        find(v, |p| match p {
785
            CssProperty::BackgroundContent(b) => b.get_property().cloned(),
786
            _ => None,
787
        })
788
    }
789

            
790
    /// The solid-colour layers of a background, in order. A gradient/image layer is
791
    /// dropped, so `solid_colors(bg).len() != bg.len()` means something non-solid crept in.
792
    fn solid_colors(bg: &StyleBackgroundContentVec) -> Vec<ColorU> {
793
        bg.as_ref()
794
            .iter()
795
            .filter_map(|c| match c {
796
                StyleBackgroundContent::Color(c) => Some(*c),
797
                _ => None,
798
            })
799
            .collect()
800
    }
801

            
802
    /// Every absolute-px number declared by a style vec.
803
    fn px_values(v: &CssPropertyWithConditionsVec) -> Vec<f32> {
804
        v.as_ref()
805
            .iter()
806
            .filter_map(|p| match &p.property {
807
                CssProperty::Width(x) => match x.get_property() {
808
                    Some(LayoutWidth::Px(pv)) => Some(px(pv)),
809
                    _ => None,
810
                },
811
                CssProperty::Height(x) => match x.get_property() {
812
                    Some(LayoutHeight::Px(pv)) => Some(px(pv)),
813
                    _ => None,
814
                },
815
                CssProperty::PaddingTop(x) => x.get_property().map(|x| px(&x.inner)),
816
                CssProperty::PaddingRight(x) => x.get_property().map(|x| px(&x.inner)),
817
                CssProperty::PaddingBottom(x) => x.get_property().map(|x| px(&x.inner)),
818
                CssProperty::PaddingLeft(x) => x.get_property().map(|x| px(&x.inner)),
819
                CssProperty::MarginLeft(x) => x.get_property().map(|x| px(&x.inner)),
820
                CssProperty::BorderTopLeftRadius(x) => x.get_property().map(|x| px(&x.inner)),
821
                CssProperty::BorderTopRightRadius(x) => x.get_property().map(|x| px(&x.inner)),
822
                CssProperty::BorderBottomLeftRadius(x) => x.get_property().map(|x| px(&x.inner)),
823
                CssProperty::BorderBottomRightRadius(x) => x.get_property().map(|x| px(&x.inner)),
824
                _ => None,
825
            })
826
            .collect()
827
    }
828

            
829
    fn classes(dom: &Dom) -> Vec<String> {
830
        dom.root
831
            .get_ids_and_classes()
832
            .as_ref()
833
            .iter()
834
            .filter_map(|c| match c {
835
                Class(s) => Some(s.as_str().to_string()),
836
                IdOrClass::Id(_) => None,
837
            })
838
            .collect()
839
    }
840

            
841
    /// The properties of a rendered node's *inline* style, in declaration order.
842
    fn inline_properties(dom: &Dom) -> Vec<CssProperty> {
843
        dom.root
844
            .style
845
            .iter_inline_properties()
846
            .map(|(p, _)| p.clone())
847
            .collect()
848
    }
849

            
850
    // ------------------------------------------------------------------
851
    // Toggle callbacks
852
    // ------------------------------------------------------------------
853

            
854
    /// A payload the toggle callback writes into. It arrives as the `data: RefAny`
855
    /// argument — a *shared* clone of what the test still holds — so the test can read
856
    /// back exactly what the widget passed, without any global state.
857
    #[derive(Debug, Clone, PartialEq, Eq)]
858
    struct ToggleLog {
859
        seen: Vec<bool>,
860
        payload: u32,
861
    }
862

            
863
    extern "C" fn record_toggle(
864
        mut data: RefAny,
865
        _info: CallbackInfo,
866
        state: SwitchState,
867
    ) -> Update {
868
        if let Some(mut log) = data.downcast_mut::<ToggleLog>() {
869
            log.seen.push(state.checked);
870
        }
871
        Update::RefreshDom
872
    }
873

            
874
    extern "C" fn toggle_do_nothing(
875
        _data: RefAny,
876
        _info: CallbackInfo,
877
        _state: SwitchState,
878
    ) -> Update {
879
        Update::DoNothing
880
    }
881

            
882
    extern "C" fn toggle_refresh_all(
883
        _data: RefAny,
884
        _info: CallbackInfo,
885
        _state: SwitchState,
886
    ) -> Update {
887
        Update::RefreshDomAllWindows
888
    }
889

            
890
    /// A `Callback`-shaped (2-arg) function — the shape FFI bindings hand in, which the
891
    /// `From<Callback>` arm *transmutes* into the 3-arg switch slot. Never called.
892
    extern "C" fn generic_shaped(_data: RefAny, _info: CallbackInfo) -> Update {
893
        Update::DoNothing
894
    }
895

            
896
    fn log_refany() -> RefAny {
897
        RefAny::new(ToggleLog {
898
            seen: Vec::new(),
899
            payload: 0xDEAD_BEEF,
900
        })
901
    }
902

            
903
    fn read_log(probe: &RefAny) -> ToggleLog {
904
        let mut probe = probe.clone();
905
        let log = probe
906
            .downcast_ref::<ToggleLog>()
907
            .expect("the user payload changed type");
908
        log.clone()
909
    }
910

            
911
    // ==================================================================
912
    // Geometry constants — numeric limits / relations
913
    // ==================================================================
914

            
915
    #[test]
916
    fn knob_travel_matches_its_documented_formula_and_is_positive() {
917
        // The doc comment on KNOB_TRAVEL *is* the spec. A negative travel (knob wider
918
        // than the track's content box) would slide the knob left, off the widget.
919
        assert_eq!(
920
            KNOB_TRAVEL,
921
            TRACK_WIDTH - (2 * TRACK_PADDING) - KNOB_SIZE,
922
            "KNOB_TRAVEL no longer matches its own documented formula",
923
        );
924
        assert!(
925
            KNOB_TRAVEL > 0,
926
            "the knob has no room to travel: KNOB_TRAVEL = {KNOB_TRAVEL}",
927
        );
928
        assert_eq!(KNOB_TRAVEL as f32, TRAVEL);
929
    }
930

            
931
    #[test]
932
    fn the_knob_exactly_fills_the_track_from_edge_to_edge_when_on() {
933
        // padding + travel + knob + padding == track width. One px of drift either way
934
        // and the "on" knob either overhangs the pill or leaves a visible gap.
935
        assert_eq!(
936
            TRACK_PADDING + KNOB_TRAVEL + KNOB_SIZE + TRACK_PADDING,
937
            TRACK_WIDTH,
938
            "the switched-on knob does not sit flush against the track's right padding edge",
939
        );
940
    }
941

            
942
    #[test]
943
    fn the_knob_exactly_fills_the_tracks_vertical_padding_box() {
944
        // A knob taller than `track_height - 2*padding` overflows the pill vertically;
945
        // a shorter one floats. 16 == 20 - 2*2.
946
        assert_eq!(
947
            KNOB_SIZE,
948
            TRACK_HEIGHT - (2 * TRACK_PADDING),
949
            "the knob no longer fits the track's vertical padding box",
950
        );
951
    }
952

            
953
    #[test]
954
    fn both_shapes_are_fully_round_not_merely_rounded() {
955
        // radius == half the cross-axis extent is what makes a pill a pill and a knob a
956
        // circle. Anything less renders a rounded rectangle.
957
        assert_eq!(TRACK_RADIUS * 2, TRACK_HEIGHT, "the track is not a pill");
958
        assert_eq!(KNOB_RADIUS * 2, KNOB_SIZE, "the knob is not a circle");
959
    }
960

            
961
    #[test]
962
    fn every_geometry_constant_survives_floatvalues_fixed_point_encoding() {
963
        // `FloatValue::const_new` multiplies by 1000 in *isize* arithmetic with no
964
        // checked path — a constant near isize::MAX/1000 would wrap silently and produce
965
        // a nonsense length. Assert every constant is comfortably representable, and
966
        // that the encode/decode round-trips exactly.
967
        const MULT: isize = 1000;
968
        for (name, v) in [
969
            ("TRACK_WIDTH", TRACK_WIDTH),
970
            ("TRACK_HEIGHT", TRACK_HEIGHT),
971
            ("TRACK_PADDING", TRACK_PADDING),
972
            ("TRACK_RADIUS", TRACK_RADIUS),
973
            ("KNOB_SIZE", KNOB_SIZE),
974
            ("KNOB_RADIUS", KNOB_RADIUS),
975
            ("KNOB_TRAVEL", KNOB_TRAVEL),
976
        ] {
977
            assert!(
978
                v.checked_mul(MULT).is_some(),
979
                "{name} = {v} overflows FloatValue's fixed-point encoding",
980
            );
981
            assert!(v >= 0, "{name} = {v} is negative");
982

            
983
            // encode -> decode must be lossless for these integral px values.
984
            let encoded = LayoutMarginLeft::const_px(v);
985
            assert_eq!(
986
                px(&encoded.inner),
987
                v as f32,
988
                "{name} = {v} does not round-trip through PixelValue",
989
            );
990
        }
991
    }
992

            
993
    #[test]
994
    fn no_declared_px_value_is_nan_infinite_or_negative() {
995
        for checked in [false, true] {
996
            for (name, v) in [
997
                ("track", build_track_style(checked)),
998
                ("knob", build_knob_style(checked)),
999
            ] {
                let values = px_values(&v);
                assert!(
                    !values.is_empty(),
                    "checked={checked}: the {name} style declares no px lengths at all",
                );
                for x in values {
                    assert!(
                        x.is_finite(),
                        "checked={checked}: the {name} style declares a non-finite length {x}",
                    );
                    assert!(
                        x >= 0.0,
                        "checked={checked}: the {name} style declares a negative length {x}",
                    );
                }
            }
        }
    }
    // ==================================================================
    // build_track_style
    // ==================================================================
    #[test]
    pub fn build_track_style_is_pure() {
        for checked in [false, true] {
            assert_eq!(
                properties(&build_track_style(checked)),
                properties(&build_track_style(checked)),
                "build_track_style({checked}) is not deterministic",
            );
        }
    }
    #[test]
    pub fn build_track_style_differs_between_the_two_states_only_in_the_background() {
        // Everything but the colour must be byte-for-byte identical: a track that
        // changed size or radius when flipped would reflow its neighbours mid-animation.
        let on = properties(&build_track_style(true));
        let off = properties(&build_track_style(false));
        assert_eq!(
            on.len(),
            off.len(),
            "the two track styles declare a different number of properties",
        );
        let differing: Vec<_> = on
            .iter()
            .zip(off.iter())
            .filter(|(a, b)| a != b)
            .map(|(a, _)| discriminant(a))
            .collect();
        assert_eq!(
            differing,
            vec![discriminant(&CssProperty::const_background_content(
                TRACK_ON_BG
            ))],
            "the on/off track styles differ in something other than the background",
        );
    }
    #[test]
    pub fn build_track_style_maps_on_to_green_and_off_to_grey() {
        // A swapped branch here yields a switch that reads as "on" when it is off —
        // which still type-checks and still animates.
        let on = background(&build_track_style(true)).expect("the on track has no background");
        let off = background(&build_track_style(false)).expect("the off track has no background");
        assert_eq!(solid_colors(&on), vec![TRACK_ON_COLOR]);
        assert_eq!(solid_colors(&off), vec![TRACK_OFF_COLOR]);
        assert_ne!(
            solid_colors(&on),
            solid_colors(&off),
            "the on and off tracks are the same colour — the switch has no visible state",
        );
    }
    #[test]
    fn the_track_background_is_exactly_one_fully_opaque_solid_layer() {
        // A translucent (or multi-layer, or gradient) track would let whatever is behind
        // it show through, so "off grey" would not actually be grey.
        for checked in [false, true] {
            let bg = background(&build_track_style(checked)).expect("no background");
            assert_eq!(
                bg.as_ref().len(),
                1,
                "checked={checked}: the track stacks {} background layers",
                bg.as_ref().len(),
            );
            let colors = solid_colors(&bg);
            assert_eq!(
                colors.len(),
                1,
                "checked={checked}: the track background is not a plain solid colour",
            );
            assert_eq!(
                colors[0].a, 255,
                "checked={checked}: the track background is translucent (a = {})",
                colors[0].a,
            );
        }
    }
    #[test]
    pub fn build_track_style_geometry_is_absolute_px_in_both_states() {
        for checked in [false, true] {
            let v = build_track_style(checked);
            // `px()` asserts SizeMetric::Px — an em/% here would scale with the parent
            // and desynchronise the knob's (absolute px) travel from the track.
            assert_eq!(
                width_px(&v),
                Some(TRACK_W),
                "checked={checked}: track width"
            );
            assert_eq!(
                height_px(&v),
                Some(TRACK_H),
                "checked={checked}: track height"
            );
            assert_eq!(
                paddings_px(&v),
                (Some(PAD), Some(PAD), Some(PAD), Some(PAD)),
                "checked={checked}: the track padding is not uniform",
            );
            assert_eq!(
                radii_px(&v),
                vec![TRACK_R; 4],
                "checked={checked}: the track's four corners are not all {TRACK_R}px",
            );
        }
    }
    #[test]
    pub fn build_track_style_declares_no_property_twice() {
        // A duplicate declaration means the later one silently wins — a latent
        // "why is my override ignored" bug that never surfaces as an error.
        for checked in [false, true] {
            let props = properties(&build_track_style(checked));
            let mut seen = Vec::new();
            for p in &props {
                let d = discriminant(p);
                assert!(
                    !seen.contains(&d),
                    "checked={checked}: the track style declares {p:?} twice",
                );
                seen.push(d);
            }
        }
    }
    #[test]
    pub fn build_track_style_marks_the_track_as_clickable_and_non_growing() {
        for checked in [false, true] {
            let v = build_track_style(checked);
            let cursor = find(&v, |p| match p {
                CssProperty::Cursor(c) => c.get_property().copied(),
                _ => None,
            });
            assert_eq!(
                cursor,
                Some(StyleCursor::Pointer),
                "checked={checked}: the switch does not present as clickable",
            );
            // flex-grow > 0 would let the track stretch past 36px inside a flex row,
            // and the knob's fixed 16px travel would no longer reach the right edge.
            assert_eq!(
                flex_grow(&v),
                Some(0.0),
                "checked={checked}: the track is allowed to grow",
            );
        }
    }
    #[test]
    pub fn build_track_style_lays_the_knob_out_as_a_centred_row() {
        // The knob is positioned by `margin-left` alone, which only behaves as a
        // left-anchored offset inside a row flex container.
        for checked in [false, true] {
            let v = build_track_style(checked);
            assert_eq!(
                find(&v, |p| match p {
                    CssProperty::Display(d) => d.get_property().copied(),
                    _ => None,
                }),
                Some(LayoutDisplay::Flex),
            );
            assert_eq!(
                find(&v, |p| match p {
                    CssProperty::FlexDirection(d) => d.get_property().copied(),
                    _ => None,
                }),
                Some(LayoutFlexDirection::Row),
                "checked={checked}: margin-left only slides the knob in a row container",
            );
            assert_eq!(
                find(&v, |p| match p {
                    CssProperty::AlignItems(a) => a.get_property().copied(),
                    _ => None,
                }),
                Some(LayoutAlignItems::Center),
            );
        }
    }
    // ==================================================================
    // build_knob_style
    // ==================================================================
    #[test]
    pub fn build_knob_style_is_pure() {
        for checked in [false, true] {
            assert_eq!(
                properties(&build_knob_style(checked)),
                properties(&build_knob_style(checked)),
                "build_knob_style({checked}) is not deterministic",
            );
        }
    }
    #[test]
    pub fn build_knob_style_differs_between_the_two_states_only_in_margin_left() {
        let on = properties(&build_knob_style(true));
        let off = properties(&build_knob_style(false));
        assert_eq!(
            on.len(),
            off.len(),
            "the two knob styles declare a different number of properties",
        );
        let differing: Vec<_> = on
            .iter()
            .zip(off.iter())
            .filter(|(a, b)| a != b)
            .map(|(a, _)| discriminant(a))
            .collect();
        assert_eq!(
            differing,
            vec![discriminant(&CssProperty::const_margin_left(
                LayoutMarginLeft::const_px(0)
            ))],
            "the on/off knob styles differ in something other than margin-left",
        );
    }
    #[test]
    pub fn build_knob_style_parks_the_knob_left_when_off_and_right_when_on() {
        assert_eq!(
            margin_left_px(&build_knob_style(false)),
            Some(0.0),
            "the off knob is not flush against the track's left padding edge",
        );
        assert_eq!(
            margin_left_px(&build_knob_style(true)),
            Some(TRAVEL),
            "the on knob does not travel the full width of the track",
        );
    }
    #[test]
    pub fn build_knob_style_geometry_is_a_circle_in_absolute_px() {
        for checked in [false, true] {
            let v = build_knob_style(checked);
            assert_eq!(width_px(&v), Some(KNOB), "checked={checked}: knob width");
            assert_eq!(height_px(&v), Some(KNOB), "checked={checked}: knob height");
            assert_eq!(
                width_px(&v),
                height_px(&v),
                "checked={checked}: the knob is not square, so it cannot be a circle",
            );
            assert_eq!(
                radii_px(&v),
                vec![KNOB_R; 4],
                "checked={checked}: the knob's four corners are not all {KNOB_R}px",
            );
            assert_eq!(
                flex_grow(&v),
                Some(0.0),
                "checked={checked}: the knob is allowed to grow and would fill the track",
            );
        }
    }
    #[test]
    pub fn build_knob_style_declares_no_property_twice() {
        // Two `margin-left` declarations would make the knob's position depend on
        // declaration order rather than on `checked`.
        for checked in [false, true] {
            let props = properties(&build_knob_style(checked));
            let mut seen = Vec::new();
            for p in &props {
                let d = discriminant(p);
                assert!(
                    !seen.contains(&d),
                    "checked={checked}: the knob style declares {p:?} twice",
                );
                seen.push(d);
            }
        }
    }
    #[test]
    fn the_knob_is_opaque_white_in_both_states() {
        // The knob must never inherit or blend with the track colour, or the "off" knob
        // would disappear into the grey.
        for checked in [false, true] {
            let bg = background(&build_knob_style(checked)).expect("the knob has no background");
            assert_eq!(
                bg.as_ref().len(),
                1,
                "checked={checked}: the knob stacks layers"
            );
            assert_eq!(solid_colors(&bg), vec![KNOB_COLOR]);
            assert_eq!(
                KNOB_COLOR.a, 255,
                "the knob is translucent and would tint with the track",
            );
            assert_ne!(
                solid_colors(&bg),
                vec![TRACK_OFF_COLOR],
                "checked={checked}: the knob is the same colour as the off track",
            );
            assert_ne!(
                solid_colors(&bg),
                vec![TRACK_ON_COLOR],
                "checked={checked}: the knob is the same colour as the on track",
            );
        }
    }
    #[test]
    fn the_knob_never_leaves_the_track_in_either_state() {
        // The real safety property, read back out of the *built styles* rather than the
        // constants: left edge >= 0 and right edge <= the track's content width.
        let content_w = TRACK_W - 2.0 * PAD;
        for checked in [false, true] {
            let margin = margin_left_px(&build_knob_style(checked)).expect("no margin-left");
            let size = width_px(&build_knob_style(checked)).expect("no width");
            assert!(
                margin >= 0.0,
                "checked={checked}: the knob is pushed off the left edge"
            );
            assert!(
                margin + size <= content_w,
                "checked={checked}: the knob overhangs the track ({margin} + {size} > {content_w})",
            );
            assert!(
                height_px(&build_knob_style(checked)).expect("no height") <= TRACK_H - 2.0 * PAD,
                "checked={checked}: the knob overflows the track vertically",
            );
        }
    }
    // ==================================================================
    // Switch::create / Default
    // ==================================================================
    #[test]
    fn create_stores_the_flag_and_installs_no_callback() {
        for checked in [false, true] {
            let s = Switch::create(checked);
            assert_eq!(
                s.switch_state.inner.checked, checked,
                "create({checked}) did not store the flag it was given",
            );
            assert!(
                s.switch_state.on_toggle.as_ref().is_none(),
                "create({checked}) invented a toggle callback out of nowhere",
            );
        }
    }
    #[test]
    fn create_is_pure_and_its_two_states_are_distinguishable() {
        assert_eq!(Switch::create(true), Switch::create(true));
        assert_eq!(Switch::create(false), Switch::create(false));
        assert_ne!(
            Switch::create(true),
            Switch::create(false),
            "an on and an off switch are indistinguishable",
        );
    }
    #[test]
    fn create_wires_the_flag_through_to_both_style_builders() {
        // The one way `create` can be wrong without any test noticing: passing the flag
        // to one builder and a literal (or the negation) to the other, so the track says
        // "on" while the knob sits left.
        for checked in [false, true] {
            let s = Switch::create(checked);
            assert_eq!(
                properties(&s.resolved_track_style()),
                properties(&build_track_style(checked)),
                "create({checked}) did not build the track for state {checked}",
            );
            assert_eq!(
                properties(&s.resolved_knob_style()),
                properties(&build_knob_style(checked)),
                "create({checked}) did not build the knob for state {checked}",
            );
        }
    }
    #[test]
    fn the_rendered_colour_and_the_knob_position_always_agree_with_the_stored_flag() {
        for checked in [false, true] {
            let s = Switch::create(checked);
            let bg = background(&s.resolved_track_style()).expect("no track background");
            let margin = margin_left_px(&s.resolved_knob_style()).expect("no knob margin");
            let (expected_color, expected_margin) = if s.switch_state.inner.checked {
                (TRACK_ON_COLOR, TRAVEL)
            } else {
                (TRACK_OFF_COLOR, 0.0)
            };
            assert_eq!(solid_colors(&bg), vec![expected_color]);
            assert_eq!(
                margin, expected_margin,
                "checked={checked}: the knob position contradicts the track colour",
            );
        }
    }
    #[test]
    fn default_is_an_off_switch() {
        assert_eq!(Switch::default(), Switch::create(false));
        assert!(!Switch::default().switch_state.inner.checked);
        assert!(
            !SwitchState::default().checked,
            "the default SwitchState is not off"
        );
        assert!(!SwitchStateWrapper::default().inner.checked);
        assert!(SwitchStateWrapper::default().on_toggle.as_ref().is_none());
    }
    // ==================================================================
    // Switch::swap_with_default
    // ==================================================================
    #[test]
    fn swap_with_default_returns_the_old_widget_and_leaves_an_off_switch_behind() {
        let mut s = Switch::create(true);
        let old = s.swap_with_default();
        assert_eq!(
            old,
            Switch::create(true),
            "the old widget was not returned intact"
        );
        assert_eq!(
            s,
            Switch::create(false),
            "what was left behind is not a fresh off switch"
        );
    }
    #[test]
    fn swap_with_default_on_an_already_default_widget_is_a_no_op() {
        let mut s = Switch::create(false);
        let old = s.swap_with_default();
        assert_eq!(
            old, s,
            "swapping a default with a default produced two different widgets"
        );
        assert_eq!(old, Switch::create(false));
    }
    #[test]
    fn swapping_twice_round_trips_the_original_widget() {
        let mut a = Switch::create(true);
        let mut b = a.swap_with_default(); // a = default, b = on
        let c = b.swap_with_default(); // b = default, c = on
        assert_eq!(c, Switch::create(true));
        assert_eq!(a, Switch::create(false));
        assert_eq!(b, Switch::create(false));
    }
    #[test]
    fn swap_with_default_moves_the_toggle_callback_out_rather_than_copying_or_dropping_it() {
        let probe = log_refany();
        let mut s = Switch::create(true)
            .with_on_toggle(probe.clone(), record_toggle as SwitchOnToggleCallbackType);
        let old = s.swap_with_default();
        // The callback (and its payload) left with the returned value ...
        let moved = old
            .switch_state
            .on_toggle
            .as_ref()
            .expect("the toggle callback vanished during the swap");
        assert_eq!(
            moved.callback.cb as *const () as usize,
            record_toggle as SwitchOnToggleCallbackType as *const () as usize,
            "the fn pointer was mangled by the swap",
        );
        // ... and did NOT stay behind: a duplicated callback would fire twice, and a
        // duplicated RefAny would double-free its payload.
        assert!(
            s.switch_state.on_toggle.as_ref().is_none(),
            "the toggle callback was copied instead of moved",
        );
        // The payload is still alive and unchanged after the move.
        assert_eq!(read_log(&probe).payload, 0xDEAD_BEEF);
    }
    // ==================================================================
    // Switch::set_on_toggle / with_on_toggle
    // ==================================================================
    #[test]
    fn set_on_toggle_stores_the_function_pointer_and_the_payload_verbatim() {
        let mut s = Switch::create(false);
        s.set_on_toggle(
            RefAny::new(0xDEAD_BEEF_u32),
            toggle_do_nothing as SwitchOnToggleCallbackType,
        );
        let t = s
            .switch_state
            .on_toggle
            .as_ref()
            .expect("set_on_toggle did not store anything");
        assert_eq!(
            t.callback.cb as *const () as usize,
            toggle_do_nothing as SwitchOnToggleCallbackType as *const () as usize,
            "the fn pointer was corrupted on the way in",
        );
        let mut data = t.refany.clone();
        assert_eq!(
            *data
                .downcast_ref::<u32>()
                .expect("the payload changed type"),
            0xDEAD_BEEF,
            "the payload was corrupted",
        );
        assert!(
            data.downcast_ref::<u64>().is_none(),
            "downcasting to the wrong type must fail, not reinterpret the bytes",
        );
    }
    #[test]
    fn set_on_toggle_replaces_rather_than_accumulates() {
        // `OptionSwitchOnToggle` is a single slot; setting twice must leave the *second*
        // callback installed (and must not leak or free the first one's RefAny).
        let first = log_refany();
        let mut s = Switch::create(false);
        s.set_on_toggle(
            first.clone(),
            toggle_do_nothing as SwitchOnToggleCallbackType,
        );
        s.set_on_toggle(
            RefAny::new(1u8),
            toggle_refresh_all as SwitchOnToggleCallbackType,
        );
        let t = s
            .switch_state
            .on_toggle
            .as_ref()
            .expect("the callback vanished");
        assert_eq!(
            t.callback.cb as *const () as usize,
            toggle_refresh_all as SwitchOnToggleCallbackType as *const () as usize,
            "the second set_on_toggle did not win",
        );
        // The displaced payload is still a valid, readable RefAny (not freed twice).
        assert_eq!(read_log(&first).payload, 0xDEAD_BEEF);
    }
    #[test]
    fn set_on_toggle_does_not_disturb_the_state_or_the_styles() {
        for checked in [false, true] {
            let pristine = Switch::create(checked);
            let mut s = Switch::create(checked);
            s.set_on_toggle(
                RefAny::new(0u8),
                toggle_do_nothing as SwitchOnToggleCallbackType,
            );
            assert_eq!(
                s.switch_state.inner.checked, checked,
                "installing a callback flipped the switch",
            );
            assert_eq!(
                properties(&s.resolved_track_style()),
                properties(&pristine.resolved_track_style()),
                "installing a callback rewrote the track style",
            );
            assert_eq!(
                properties(&s.resolved_knob_style()),
                properties(&pristine.resolved_knob_style()),
                "installing a callback rewrote the knob style",
            );
        }
    }
    #[test]
    fn with_on_toggle_is_exactly_set_on_toggle_in_builder_form() {
        let by_builder = Switch::create(true).with_on_toggle(
            RefAny::new(7u32),
            toggle_do_nothing as SwitchOnToggleCallbackType,
        );
        let mut by_setter = Switch::create(true);
        by_setter.set_on_toggle(
            RefAny::new(7u32),
            toggle_do_nothing as SwitchOnToggleCallbackType,
        );
        assert_eq!(by_builder.switch_state.inner, by_setter.switch_state.inner);
        assert_eq!(
            properties(&by_builder.resolved_track_style()),
            properties(&by_setter.resolved_track_style()),
        );
        assert_eq!(
            properties(&by_builder.resolved_knob_style()),
            properties(&by_setter.resolved_knob_style()),
        );
        let a = by_builder
            .switch_state
            .on_toggle
            .as_ref()
            .expect("builder lost the callback");
        let b = by_setter
            .switch_state
            .on_toggle
            .as_ref()
            .expect("setter lost the callback");
        assert_eq!(
            a.callback.cb as *const () as usize,
            b.callback.cb as *const () as usize
        );
        let (mut a, mut b) = (a.refany.clone(), b.refany.clone());
        assert_eq!(
            *a.downcast_ref::<u32>()
                .expect("builder payload changed type"),
            *b.downcast_ref::<u32>()
                .expect("setter payload changed type"),
        );
    }
    #[test]
    fn with_on_toggle_accepts_a_generic_callback_without_mangling_the_pointer() {
        // The `From<Callback>` arm *transmutes* a 2-arg fn pointer into the 3-arg switch
        // slot — this is the FFI (Python/C) path. The pointer must come out bit-identical;
        // a mangled one would be called as a wild jump on the first click.
        let generic = Callback {
            cb: generic_shaped,
            ctx: OptionRefAny::None,
        };
        let expected = generic_shaped as *const () as usize;
        let s = Switch::create(false).with_on_toggle(RefAny::new(0u8), generic);
        let t = s
            .switch_state
            .on_toggle
            .as_ref()
            .expect("the generic callback was dropped");
        assert_eq!(
            t.callback.cb as *const () as usize, expected,
            "the Callback -> SwitchOnToggleCallback transmute mangled the pointer",
        );
    }
    // ==================================================================
    // Switch::dom
    // ==================================================================
    #[test]
    fn dom_builds_a_focusable_track_with_exactly_one_knob_child() {
        for checked in [false, true] {
            let dom = Switch::create(checked).dom();
            assert!(matches!(dom.root.get_node_type(), NodeType::Div));
            assert_eq!(
                dom.root.flags.get_tab_index(),
                Some(TabIndex::Auto),
                "checked={checked}: the switch is not keyboard-focusable",
            );
            assert_eq!(classes(&dom), vec!["__azul-native-switch".to_string()]);
            let children = dom.children.as_ref();
            assert_eq!(
                children.len(),
                1,
                "checked={checked}: the switch must have exactly one knob"
            );
            assert_eq!(
                classes(&children[0]),
                vec!["__azul-native-switch-knob".to_string()],
                "checked={checked}: the knob carries the wrong class (external CSS would miss it)",
            );
            assert!(
                children[0].children.as_ref().is_empty(),
                "checked={checked}: the knob grew children",
            );
            assert_eq!(
                children[0].root.flags.get_tab_index(),
                None,
                "checked={checked}: the knob is separately focusable, so Tab stops twice",
            );
        }
    }
    #[test]
    fn dom_puts_the_track_style_on_the_track_and_the_knob_style_on_the_knob() {
        // Swapping the two would style the 16px knob like a 36px pill (and vice versa) —
        // the widget would still render, just wrong.
        for checked in [false, true] {
            let s = Switch::create(checked);
            let track = properties(&s.resolved_track_style());
            let knob = properties(&s.resolved_knob_style());
            let dom = s.dom();
            assert_eq!(
                inline_properties(&dom),
                track,
                "checked={checked}: the track style did not land on the track",
            );
            assert_eq!(
                inline_properties(&dom.children.as_ref()[0]),
                knob,
                "checked={checked}: the knob style did not land on the knob",
            );
        }
    }
    #[test]
    fn dom_registers_exactly_one_mouse_up_handler_and_it_is_the_widgets_own() {
        for checked in [false, true] {
            let dom = Switch::create(checked).dom();
            let callbacks = dom.root.callbacks.as_ref();
            assert_eq!(
                callbacks.len(),
                1,
                "checked={checked}: expected exactly one callback"
            );
            assert_eq!(
                callbacks[0].event,
                EventFilter::Hover(HoverEventFilter::Click),
                "checked={checked}: the switch must toggle on mouse-up",
            );
            assert_eq!(
                callbacks[0].callback.cb,
                input::default_on_switch_clicked as usize,
                "checked={checked}: the registered handler is not default_on_switch_clicked",
            );
            // The knob itself must stay inert — a second handler there would toggle twice
            // per click (the event bubbles).
            assert!(
                dom.children.as_ref()[0].root.callbacks.as_ref().is_empty(),
                "checked={checked}: the knob registered a handler of its own",
            );
        }
    }
    #[test]
    fn dom_hands_the_widget_state_to_the_handler_not_the_user_payload() {
        // `dom()` moves `switch_state` (state + on_toggle + user RefAny) into the
        // callback's RefAny. If it stored the *user's* payload instead, the handler's
        // `downcast_mut::<SwitchStateWrapper>()` would fail and every click would be a
        // silent no-op.
        for checked in [false, true] {
            let dom = Switch::create(checked)
                .with_on_toggle(
                    RefAny::new(9u32),
                    toggle_do_nothing as SwitchOnToggleCallbackType,
                )
                .dom();
            let mut state = dom.root.callbacks.as_ref()[0].refany.clone();
            let wrapper = state
                .downcast_ref::<SwitchStateWrapper>()
                .expect("the handler's RefAny is not a SwitchStateWrapper");
            assert_eq!(
                wrapper.inner.checked, checked,
                "the on/off flag was lost on the way into the DOM",
            );
            assert!(
                wrapper.on_toggle.as_ref().is_some(),
                "the user's toggle callback was lost on the way into the DOM",
            );
        }
    }
    #[test]
    fn dom_of_a_callback_less_switch_still_registers_the_toggle_handler() {
        // The switch must always install its own handler: the knob has to slide even
        // with no user callback.
        let dom = Switch::create(false).dom();
        assert_eq!(dom.root.callbacks.as_ref().len(), 1);
        let mut state = dom.root.callbacks.as_ref()[0].refany.clone();
        let wrapper = state
            .downcast_ref::<SwitchStateWrapper>()
            .expect("wrong RefAny type");
        assert!(wrapper.on_toggle.as_ref().is_none());
    }
    #[test]
    fn from_switch_for_dom_is_the_same_as_calling_dom() {
        for checked in [false, true] {
            let via_from = Dom::from(Switch::create(checked));
            let via_dom = Switch::create(checked).dom();
            assert_eq!(classes(&via_from), classes(&via_dom));
            assert_eq!(inline_properties(&via_from), inline_properties(&via_dom));
            assert_eq!(
                via_from.children.as_ref().len(),
                via_dom.children.as_ref().len()
            );
            assert_eq!(
                inline_properties(&via_from.children.as_ref()[0]),
                inline_properties(&via_dom.children.as_ref()[0]),
            );
            assert_eq!(
                via_from.root.callbacks.as_ref().len(),
                via_dom.root.callbacks.as_ref().len(),
            );
            assert_eq!(
                via_from.root.flags.get_tab_index(),
                via_dom.root.flags.get_tab_index()
            );
        }
    }
    #[test]
    fn the_rendered_dom_flattens_to_exactly_two_nodes() {
        // `Dom::estimated_total_children` is a *cached* count; if it under-reports, the
        // flatten under-allocates its arenas. Two nodes: track (0), knob (1).
        for checked in [false, true] {
            let styled = StyledDom::create_from_dom(Switch::create(checked).dom());
            assert_eq!(
                styled.node_data.as_ref().len(),
                2,
                "checked={checked}: the switch no longer flattens to a track + a knob",
            );
        }
    }
    // ==================================================================
    // input::default_on_switch_clicked
    // ==================================================================
    #[test]
    fn clicking_an_off_switch_turns_it_on_and_pushes_the_on_visuals() {
        let (styled, state) = laid_out(Switch::create(false));
        assert!(!is_checked(&state));
        let (update, changes) = click(styled, &state, node(TRACK));
        assert!(is_checked(&state), "the click did not turn the switch on");
        assert!(
            matches!(update, Update::DoNothing),
            "with no user callback installed, the handler must report DoNothing",
        );
        assert_eq!(
            pushed_backgrounds(&changes)
                .iter()
                .map(|(n, b)| (*n, solid_colors(b)))
                .collect::<Vec<_>>(),
            vec![(NodeId::new(TRACK), vec![TRACK_ON_COLOR])],
            "turning the switch on did not repaint the *track* green",
        );
        assert_eq!(
            pushed_margins(&changes),
            vec![(NodeId::new(KNOB_NODE), TRAVEL)],
            "turning the switch on did not slide the *knob* right",
        );
    }
    #[test]
    fn clicking_an_on_switch_turns_it_off_and_pushes_the_off_visuals() {
        let (styled, state) = laid_out(Switch::create(true));
        let (_, changes) = click(styled, &state, node(TRACK));
        assert!(!is_checked(&state), "the click did not turn the switch off");
        assert_eq!(
            pushed_backgrounds(&changes)
                .iter()
                .map(|(n, b)| (*n, solid_colors(b)))
                .collect::<Vec<_>>(),
            vec![(NodeId::new(TRACK), vec![TRACK_OFF_COLOR])],
        );
        assert_eq!(
            pushed_margins(&changes),
            vec![(NodeId::new(KNOB_NODE), 0.0)]
        );
    }
    #[test]
    fn a_click_pushes_exactly_what_a_freshly_created_switch_would_render() {
        // The handler re-derives the visuals by hand instead of calling
        // `build_track_style`/`build_knob_style`. That duplication is the bug surface:
        // a colour or a travel distance can drift in one place and not the other, and
        // the switch then renders differently after a click than it did on mount.
        for start in [false, true] {
            let (styled, state) = laid_out(Switch::create(start));
            let (_, changes) = click(styled, &state, node(TRACK));
            let expected = Switch::create(!start);
            assert_eq!(
                pushed_backgrounds(&changes)
                    .into_iter()
                    .map(|(_, b)| b)
                    .collect::<Vec<_>>(),
                vec![background(&expected.resolved_track_style()).expect("no background")],
                "start={start}: the clicked track colour differs from a freshly built one",
            );
            assert_eq!(
                pushed_margins(&changes)
                    .into_iter()
                    .map(|(_, m)| m)
                    .collect::<Vec<_>>(),
                vec![margin_left_px(&expected.resolved_knob_style()).expect("no margin")],
                "start={start}: the clicked knob offset differs from a freshly built one",
            );
        }
    }
    #[test]
    fn clicking_twice_returns_to_the_original_state() {
        let (styled, state) = laid_out(Switch::create(false));
        // Two independent deliveries against the same widget state — the styled DOM is
        // rebuilt each time because the harness consumes it, but the RefAny is shared,
        // which is exactly how the real event loop drives it.
        let (styled2, _) = laid_out(Switch::create(false));
        let (_, first) = click(styled, &state, node(TRACK));
        let (_, second) = click(styled2, &state, node(TRACK));
        assert!(
            !is_checked(&state),
            "two clicks did not return the switch to its original state"
        );
        assert_eq!(
            pushed_margins(&first),
            vec![(NodeId::new(KNOB_NODE), TRAVEL)]
        );
        assert_eq!(pushed_margins(&second), vec![(NodeId::new(KNOB_NODE), 0.0)]);
    }
    #[test]
    fn clicking_with_a_refany_of_the_wrong_type_is_a_silent_no_op() {
        // The handler downcasts blind; a foreign RefAny must bail out, not reinterpret
        // the bytes as a SwitchStateWrapper.
        let (styled, _) = laid_out(Switch::create(false));
        let foreign = RefAny::new(0xDEAD_BEEF_u32);
        let (update, changes) = click(styled, &foreign, node(TRACK));
        assert!(matches!(update, Update::DoNothing));
        assert!(
            changes.is_empty(),
            "the handler wrote to the DOM through a foreign RefAny"
        );
        let mut foreign = foreign;
        assert_eq!(
            *foreign
                .downcast_ref::<u32>()
                .expect("the foreign payload was reinterpreted"),
            0xDEAD_BEEF,
            "the handler corrupted a RefAny it did not understand",
        );
    }
    #[test]
    fn clicking_the_knob_itself_does_not_half_apply_the_toggle() {
        // The knob is the child that sits under the cursor for most of the track's area,
        // and it has no first child of its own. The handler needs that child to slide the
        // knob, so it must leave the *flag* alone too — a flipped flag with no visual
        // update is a switch that renders the opposite of what it reports.
        let (styled, state) = laid_out(Switch::create(false));
        let (update, changes) = click(styled, &state, node(KNOB_NODE));
        assert!(matches!(update, Update::DoNothing));
        assert!(
            changes.is_empty(),
            "a change was pushed for a node the handler could not resolve"
        );
        assert!(
            !is_checked(&state),
            "the flag was flipped even though the knob could not be moved",
        );
    }
    #[test]
    fn stale_or_missing_hit_ids_do_not_panic_or_toggle() {
        // Stale hit ids reach callbacks after a DOM mutation. `set_css_property` *panics*
        // on a None node id, so the handler has to bail out before that point.
        // usize::MAX is unencodable by NodeId's 1-based scheme and would overflow while
        // building this fixture, before `click()` is even called; usize::MAX - 1 is the
        // repo's MAX_ENCODABLE_NODE and still absent from the layout.
        for hit in [node(2), node(99), node(usize::MAX - 1), node_none()] {
            let (styled, state) = laid_out(Switch::create(true));
            let (update, changes) = click(styled, &state, hit);
            assert!(
                matches!(update, Update::DoNothing),
                "{hit:?}: a stale hit was acted on"
            );
            assert!(
                changes.is_empty(),
                "{hit:?}: a stale hit pushed a DOM change"
            );
            assert!(
                is_checked(&state),
                "{hit:?}: a stale hit toggled the switch"
            );
        }
    }
    #[test]
    fn the_toggle_callback_sees_the_new_state_and_its_verdict_is_forwarded() {
        // Order matters: the flag is flipped *before* the user callback runs, so the
        // callback observes the state the user just asked for — not the stale one.
        let probe = log_refany();
        let (styled, state) = laid_out(
            Switch::create(false)
                .with_on_toggle(probe.clone(), record_toggle as SwitchOnToggleCallbackType),
        );
        let (update, changes) = click(styled, &state, node(TRACK));
        assert_eq!(
            read_log(&probe).seen,
            vec![true],
            "the toggle callback was not called exactly once with the NEW state",
        );
        assert!(
            matches!(update, Update::RefreshDom),
            "the user callback's Update was swallowed instead of forwarded",
        );
        // ... and the visual sync still happens *after* the user callback returns.
        assert_eq!(
            pushed_margins(&changes),
            vec![(NodeId::new(KNOB_NODE), TRAVEL)]
        );
    }
    #[test]
    fn the_toggle_callback_receives_the_user_payload_not_the_widget_state() {
        let probe = log_refany();
        let (styled, state) = laid_out(
            Switch::create(true)
                .with_on_toggle(probe.clone(), record_toggle as SwitchOnToggleCallbackType),
        );
        click(styled, &state, node(TRACK));
        let log = read_log(&probe);
        assert_eq!(
            log.payload, 0xDEAD_BEEF,
            "the callback was handed something other than the user's own RefAny",
        );
        // create(true) -> clicked once -> the callback must have seen `false`.
        assert_eq!(log.seen, vec![false]);
    }
    #[test]
    fn a_toggle_callback_that_declines_the_update_still_gets_the_visuals_synced() {
        // A user callback returning DoNothing must not suppress the widget's own visual
        // bookkeeping — otherwise the flag says "on" and the knob stays parked left.
        let (styled, state) = laid_out(Switch::create(false).with_on_toggle(
            RefAny::new(0u8),
            toggle_do_nothing as SwitchOnToggleCallbackType,
        ));
        let (update, changes) = click(styled, &state, node(TRACK));
        assert!(matches!(update, Update::DoNothing));
        assert!(is_checked(&state));
        assert_eq!(
            pushed_margins(&changes),
            vec![(NodeId::new(KNOB_NODE), TRAVEL)],
            "a DoNothing user callback suppressed the knob slide",
        );
    }
    #[test]
    fn a_toggle_callback_on_an_unresolvable_node_is_never_called_at_all() {
        // The bail-out happens before the flip *and* before the user callback: a click
        // that cannot be rendered must not be reported to the app either.
        let probe = log_refany();
        let (styled, state) = laid_out(
            Switch::create(false)
                .with_on_toggle(probe.clone(), record_toggle as SwitchOnToggleCallbackType),
        );
        let (update, changes) = click(styled, &state, node(KNOB_NODE));
        assert!(matches!(update, Update::DoNothing));
        assert!(changes.is_empty());
        assert!(!is_checked(&state));
        assert!(
            read_log(&probe).seen.is_empty(),
            "the user was notified of a toggle that never happened",
        );
    }
    #[test]
    fn many_clicks_leave_the_flag_the_colour_and_the_knob_in_agreement() {
        // 51 clicks starting off -> on. Every push must agree with the flag it
        // accompanies; a drift between the three is exactly the class of bug that makes
        // a switch render inverted after a while.
        let mut expected_on = false;
        let (_, state) = laid_out(Switch::create(false));
        for i in 0..51u32 {
            let (styled, _) = laid_out(Switch::create(false));
            let (_, changes) = click(styled, &state, node(TRACK));
            expected_on = !expected_on;
            let (color, margin) = if expected_on {
                (TRACK_ON_COLOR, TRAVEL)
            } else {
                (TRACK_OFF_COLOR, 0.0)
            };
            assert_eq!(
                pushed_backgrounds(&changes)
                    .iter()
                    .map(|(n, b)| (*n, solid_colors(b)))
                    .collect::<Vec<_>>(),
                vec![(NodeId::new(TRACK), vec![color])],
                "click #{i}: the pushed track colour disagrees with the flag",
            );
            assert_eq!(
                pushed_margins(&changes),
                vec![(NodeId::new(KNOB_NODE), margin)],
                "click #{i}: the pushed knob offset disagrees with the flag",
            );
            assert_eq!(
                is_checked(&state),
                expected_on,
                "click #{i}: the flag drifted"
            );
        }
        assert!(
            is_checked(&state),
            "an odd number of clicks left the switch off"
        );
    }
    #[test]
    fn a_click_writes_to_two_distinct_nodes_and_never_to_the_wrong_one() {
        // The track gets the colour, the knob gets the offset — never the other way
        // round, and never both onto the same node.
        let (styled, state) = laid_out(Switch::create(false));
        let (_, changes) = click(styled, &state, node(TRACK));
        let bg_nodes: Vec<_> = pushed_backgrounds(&changes)
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        let margin_nodes: Vec<_> = pushed_margins(&changes)
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        assert_eq!(bg_nodes, vec![NodeId::new(TRACK)]);
        assert_eq!(margin_nodes, vec![NodeId::new(KNOB_NODE)]);
        assert_ne!(
            bg_nodes, margin_nodes,
            "the colour and the knob offset landed on the same node",
        );
    }
}