1
//! Checkbox widget with toggle callback support and default native-like styling.
2
//!
3
//! Key types: [`CheckBox`], [`CheckBoxState`], [`CheckBoxOnToggle`].
4

            
5
use azul_core::{
6
    callbacks::{CoreCallbackData, Update},
7
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
8
    refany::RefAny,
9
};
10
use azul_css::dynamic_selector::{
11
    CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
12
};
13
#[allow(clippy::wildcard_imports)]
14
// widget/render module pulls in the css property/value types it builds with
15
use azul_css::{
16
    props::{
17
        basic::{color::ColorU, *},
18
        layout::*,
19
        property::{CssProperty, *},
20
        style::*,
21
    },
22
    OptionString, *,
23
};
24

            
25
use crate::{
26
    callbacks::{Callback, CallbackInfo},
27
    widgets::themes::{OptionUiTheme, UiTheme},
28
};
29

            
30
pub static CHECKBOX_CONTAINER_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
31
    "__azul-native-checkbox-container",
32
))];
33
pub static CHECKBOX_CONTENT_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
34
    "__azul-native-checkbox-content",
35
))];
36

            
37
/// Callback function type invoked when the checkbox is toggled.
38
pub type CheckBoxOnToggleCallbackType =
39
    extern "C" fn(RefAny, CallbackInfo, CheckBoxState) -> Update;
40
impl_widget_callback!(
41
    CheckBoxOnToggle,
42
    OptionCheckBoxOnToggle,
43
    CheckBoxOnToggleCallback,
44
    CheckBoxOnToggleCallbackType
45
);
46

            
47
azul_core::impl_managed_callback! {
48
    wrapper:        CheckBoxOnToggleCallback,
49
    info_ty:        CallbackInfo,
50
    return_ty:      Update,
51
    default_ret:    Update::DoNothing,
52
    invoker_static: CHECK_BOX_ON_TOGGLE_INVOKER,
53
    invoker_ty:     AzCheckBoxOnToggleCallbackInvoker,
54
    thunk_fn:       az_check_box_on_toggle_callback_thunk,
55
    setter_fn:      AzApp_setCheckBoxOnToggleCallbackInvoker,
56
    from_handle_fn: AzCheckBoxOnToggleCallback_createFromHostHandle,
57
    extra_args:     [ state: CheckBoxState ],
58
}
59

            
60
/// A toggleable checkbox widget with customizable styling and toggle callback.
61
#[derive(Debug, Clone, PartialEq, Eq)]
62
#[repr(C)]
63
pub struct CheckBox {
64
    pub check_box_state: CheckBoxStateWrapper,
65
    pub theme: OptionUiTheme,
66
    /// Style for the checkbox container
67
    pub container_style: OptionCssPropertyWithConditionsVec,
68
    /// Style for the checkbox content
69
    pub content_style: OptionCssPropertyWithConditionsVec,
70
    /// What this control is CALLED, for assistive technology.
71
    ///
72
    /// Carried by the WIDGET rather than patched onto the finished `Dom`: that
73
    /// is what lets the widget know at build time whether it was named, so its
74
    /// warning fires only when nobody supplied one. Forwarded into the
75
    /// accessibility declaration the widget builds anyway, beside its role and
76
    /// state.
77
    pub accessibility_name: OptionString,
78
}
79

            
80
#[derive(Debug, Default, Clone, PartialEq, Eq)]
81
#[repr(C)]
82
pub struct CheckBoxStateWrapper {
83
    /// Content (image or text) of this `CheckBox`, centered by default
84
    pub inner: CheckBoxState,
85
    /// Optional: Function to call when the `CheckBox` is toggled
86
    pub on_toggle: OptionCheckBoxOnToggle,
87
}
88

            
89
/// The checked/unchecked state of a [`CheckBox`].
90
#[derive(Copy, Debug, Default, Clone, PartialEq, Eq)]
91
#[repr(C)]
92
pub struct CheckBoxState {
93
    pub checked: bool,
94
}
95

            
96
const BACKGROUND_COLOR: ColorU = ColorU {
97
    r: 255,
98
    g: 255,
99
    b: 255,
100
    a: 255,
101
}; // white
102
const BACKGROUND_THEME_LIGHT: &[StyleBackgroundContent] =
103
    &[StyleBackgroundContent::Color(BACKGROUND_COLOR)];
104
const BACKGROUND_COLOR_LIGHT: StyleBackgroundContentVec =
105
    StyleBackgroundContentVec::from_const_slice(BACKGROUND_THEME_LIGHT);
106
const COLOR_9B9B9B: ColorU = ColorU {
107
    r: 155,
108
    g: 155,
109
    b: 155,
110
    a: 255,
111
}; // #9b9b9b
112

            
113
const FILL_THEME: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(COLOR_9B9B9B)];
114
const FILL_COLOR_BACKGROUND: StyleBackgroundContentVec =
115
    StyleBackgroundContentVec::from_const_slice(FILL_THEME);
116

            
117
pub static DEFAULT_CHECKBOX_CONTAINER_STYLE: &[CssPropertyWithConditions] = &[
118
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
119
        BACKGROUND_COLOR_LIGHT,
120
    )),
121
    // A flex box that CENTRES the mark, like the RadioGroup's ring. As a
122
    // `display: block` the 8 px mark sat in the top-left of the 14 px content
123
    // box (demo test 2026-08-21: "CheckBox not centered").
124
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
125
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
126
    CssPropertyWithConditions::simple(CssProperty::const_justify_content(
127
        LayoutJustifyContent::Center,
128
    )),
129
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
130
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
131
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(14))),
132
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(14))),
133
    // padding: 2px
134
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
135
        LayoutPaddingLeft::const_px(2),
136
    )),
137
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
138
        LayoutPaddingRight::const_px(2),
139
    )),
140
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
141
        2,
142
    ))),
143
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
144
        LayoutPaddingBottom::const_px(2),
145
    )),
146
    // border: 1px solid #484c52;
147
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
148
        LayoutBorderTopWidth::const_px(1),
149
    )),
150
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
151
        LayoutBorderBottomWidth::const_px(1),
152
    )),
153
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
154
        LayoutBorderLeftWidth::const_px(1),
155
    )),
156
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
157
        LayoutBorderRightWidth::const_px(1),
158
    )),
159
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
160
        inner: BorderStyle::Inset,
161
    })),
162
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
163
        StyleBorderBottomStyle {
164
            inner: BorderStyle::Inset,
165
        },
166
    )),
167
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
168
        inner: BorderStyle::Inset,
169
    })),
170
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
171
        StyleBorderRightStyle {
172
            inner: BorderStyle::Inset,
173
        },
174
    )),
175
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
176
        inner: COLOR_9B9B9B,
177
    })),
178
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
179
        StyleBorderBottomColor {
180
            inner: COLOR_9B9B9B,
181
        },
182
    )),
183
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
184
        inner: COLOR_9B9B9B,
185
    })),
186
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
187
        StyleBorderRightColor {
188
            inner: COLOR_9B9B9B,
189
        },
190
    )),
191
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
192
];
193

            
194
pub static DEFAULT_CHECKBOX_CONTENT_STYLE_CHECKED: &[CssPropertyWithConditions] = &[
195
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(8))),
196
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(8))),
197
    CssPropertyWithConditions::simple(CssProperty::const_background_content(FILL_COLOR_BACKGROUND)),
198
    CssPropertyWithConditions::simple(CssProperty::const_opacity(StyleOpacity::const_new(100))),
199
];
200

            
201
pub static DEFAULT_CHECKBOX_CONTENT_STYLE_UNCHECKED: &[CssPropertyWithConditions] = &[
202
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(8))),
203
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(8))),
204
    CssPropertyWithConditions::simple(CssProperty::const_background_content(FILL_COLOR_BACKGROUND)),
205
    CssPropertyWithConditions::simple(CssProperty::const_opacity(StyleOpacity::const_new(0))),
206
];
207

            
208
impl CheckBox {
209
    /// Name this control for assistive technology.
210
    #[must_use]
211
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
212
        self.accessibility_name = Some(name.into()).into();
213
        self
214
    }
215

            
216
    #[must_use]
217
196
    pub fn create(checked: bool) -> Self {
218
196
        Self {
219
196
            theme: OptionUiTheme::None,
220
196
            check_box_state: CheckBoxStateWrapper {
221
196
                inner: CheckBoxState { checked },
222
196
                ..Default::default()
223
196
            },
224
196
            // No opinion: the theme resolves these. Pre-filling them here
225
196
            // would make every checkbox look like it had been styled by hand,
226
196
            // leaving a theme no way to tell "the caller wants exactly this"
227
196
            // from "nobody said".
228
196
            container_style: OptionCssPropertyWithConditionsVec::None,
229
196
            content_style: OptionCssPropertyWithConditionsVec::None,
230
196
            accessibility_name: OptionString::None,
231
196
        }
232
196
    }
233

            
234
    /// The container CSS this checkbox renders with.
235
    ///
236
    /// `None` means "no opinion", so the widget's own default applies. Both
237
    /// themes asked this question with their own copy of the same `match`;
238
    /// asking it here keeps the two from drifting apart, and gives the tests
239
    /// the value that is actually painted rather than the field behind it.
240
    #[must_use]
241
175
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
242
175
        self.container_style
243
175
            .clone()
244
175
            .into_option()
245
175
            .unwrap_or_else(|| {
246
175
                CssPropertyWithConditionsVec::from_const_slice(DEFAULT_CHECKBOX_CONTAINER_STYLE)
247
175
            })
248
175
    }
249

            
250
    /// The checkmark CSS this checkbox renders with; see
251
    /// [`Self::resolved_container_style`]. The default depends on the checked
252
    /// flag, which is why it is resolved late rather than at construction.
253
    #[must_use]
254
172
    pub fn resolved_content_style(&self) -> CssPropertyWithConditionsVec {
255
172
        self.content_style.clone().into_option().unwrap_or_else(|| {
256
172
            if self.check_box_state.inner.checked {
257
31
                CssPropertyWithConditionsVec::from_const_slice(
258
31
                    DEFAULT_CHECKBOX_CONTENT_STYLE_CHECKED,
259
                )
260
            } else {
261
141
                CssPropertyWithConditionsVec::from_const_slice(
262
141
                    DEFAULT_CHECKBOX_CONTENT_STYLE_UNCHECKED,
263
                )
264
            }
265
172
        })
266
172
    }
267

            
268
    #[inline]
269
    #[must_use]
270
5
    pub fn swap_with_default(&mut self) -> Self {
271
5
        let mut s = Self::create(false);
272
5
        core::mem::swap(&mut s, self);
273
5
        s
274
5
    }
275

            
276
    /// Pick the widget theme. Unset (`None`), the widget renders in the
277
    /// default theme (`UiTheme::default()`).
278
    pub const fn set_theme(&mut self, theme: UiTheme) {
279
        self.theme = OptionUiTheme::Some(theme);
280
    }
281

            
282
    /// [`Self::set_theme`] for the builder chain.
283
    #[must_use]
284
    pub const fn with_theme(mut self, theme: UiTheme) -> Self {
285
        self.set_theme(theme);
286
        self
287
    }
288

            
289
    #[inline]
290
31
    pub fn set_on_toggle<C: Into<CheckBoxOnToggleCallback>>(&mut self, data: RefAny, on_toggle: C) {
291
31
        self.check_box_state.on_toggle = Some(CheckBoxOnToggle {
292
31
            callback: on_toggle.into(),
293
31
            refany: data,
294
31
        })
295
31
        .into();
296
31
    }
297

            
298
    #[inline]
299
    #[must_use]
300
25
    pub fn with_on_toggle<C: Into<CheckBoxOnToggleCallback>>(
301
25
        mut self,
302
25
        data: RefAny,
303
25
        on_toggle: C,
304
25
    ) -> Self {
305
25
        self.set_on_toggle(data, on_toggle);
306
25
        self
307
25
    }
308

            
309
    #[inline]
310
    #[must_use]
311
153
    pub fn dom(self) -> Dom {
312
153
        let theme = match self.theme {
313
            OptionUiTheme::Some(theme) => theme,
314
153
            OptionUiTheme::None => UiTheme::Flat,
315
        };
316
153
        match theme {
317
153
            UiTheme::Flat => crate::widgets::themes::flat::check_box(self),
318
            UiTheme::Flora => crate::widgets::themes::flora::check_box(self),
319
        }
320
153
    }
321
}
322

            
323
// handle input events for the checkbox
324
pub mod input {
325

            
326
    use azul_core::{callbacks::Update, refany::RefAny};
327
    use azul_css::props::{property::CssProperty, style::effects::StyleOpacity};
328

            
329
    use super::{CheckBoxOnToggle, CheckBoxStateWrapper};
330
    use crate::callbacks::CallbackInfo;
331

            
332
    #[must_use]
333
114
    pub extern "C" fn default_on_checkbox_clicked(
334
114
        mut check_box: RefAny,
335
114
        mut info: CallbackInfo,
336
114
    ) -> Update {
337
114
        let Some(mut check_box) = check_box.downcast_mut::<CheckBoxStateWrapper>() else {
338
1
            return Update::DoNothing;
339
        };
340

            
341
113
        let Some(checkbox_content_id) = info.get_first_child(info.get_hit_node()) else {
342
5
            return Update::DoNothing;
343
        };
344

            
345
108
        check_box.inner.checked = !check_box.inner.checked;
346

            
347
108
        let result = {
348
            // rustc doesn't understand the borrowing lifetime here
349
108
            let check_box = &mut *check_box;
350
108
            let ontoggle = &mut check_box.on_toggle;
351
108
            let inner = check_box.inner;
352

            
353
108
            match ontoggle.as_mut() {
354
                Some(CheckBoxOnToggle {
355
3
                    callback,
356
3
                    refany: data,
357
3
                }) => (callback.cb)(data.clone(), info, inner),
358
105
                None => Update::DoNothing,
359
            }
360
        };
361

            
362
        // Keep the announced state in step with the rendered one: this handler
363
        // changes opacity and returns Update::DoNothing, so nothing rebuilds and
364
        // the build-time CheckedTrue/False would go stale on the first click.
365
108
        info.set_accessibility_state(
366
108
            info.get_hit_node(),
367
108
            azul_core::a11y::AccessibilityStateVec::from_const_slice(if check_box.inner.checked {
368
55
                &[azul_core::a11y::AccessibilityState::CheckedTrue]
369
            } else {
370
53
                &[azul_core::a11y::AccessibilityState::CheckedFalse]
371
            }),
372
        );
373

            
374
108
        if check_box.inner.checked {
375
55
            info.set_css_property(
376
55
                checkbox_content_id,
377
55
                CssProperty::const_opacity(StyleOpacity::const_new(100)),
378
55
            );
379
55
        } else {
380
53
            info.set_css_property(
381
53
                checkbox_content_id,
382
53
                CssProperty::const_opacity(StyleOpacity::const_new(0)),
383
53
            );
384
53
        }
385

            
386
108
        result
387
114
    }
388
}
389

            
390
impl From<CheckBox> for Dom {
391
2
    fn from(b: CheckBox) -> Self {
392
2
        b.dom()
393
2
    }
394
}
395

            
396
#[cfg(all(test, feature = "std"))]
397
#[allow(clippy::float_cmp, clippy::too_many_lines)]
398
mod autotest_generated {
399
    use std::{
400
        collections::{BTreeMap, HashMap},
401
        mem::discriminant,
402
        sync::{Arc, Mutex},
403
    };
404

            
405
    use azul_core::{
406
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
407
        geom::{LogicalRect, OptionLogicalPosition},
408
        gl::OptionGlContextPtr,
409
        hit_test::ScrollPosition,
410
        refany::OptionRefAny,
411
        resources::RendererResources,
412
        styled_dom::{NodeHierarchyItemId, StyledDom},
413
        window::{MonitorVec, RawWindowHandle},
414
    };
415
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
416
    use rust_fontconfig::FcFontCache;
417

            
418
    use super::*;
419
    #[cfg(feature = "icu")]
420
    use crate::icu::IcuLocalizerHandle;
421
    use crate::{
422
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
423
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
424
        widgets::theme_probe,
425
        window::{DomLayoutResult, LayoutWindow},
426
        window_state::FullWindowState,
427
    };
428

            
429
    // ------------------------------------------------------------------
430
    // Harness
431
    // ------------------------------------------------------------------
432

            
433
    /// The container is `14px` wide with `2px` padding and a `1px` border on each
434
    /// side; the checkmark is `8px`. These four numbers are the entire geometry of
435
    /// the widget, and `8 == 14 - 2*2 - 2*1` is the relation that makes the mark
436
    /// fill the padding box exactly (see `content_exactly_fills_the_containers_padding_box`).
437
    const CONTAINER_SIDE: f32 = 14.0;
438
    const PADDING: f32 = 2.0;
439
    const BORDER: f32 = 1.0;
440
    const CONTENT_SIDE: f32 = 8.0;
441

            
442
    /// Flattened node ids of `CheckBox::dom()` (pre-order).
443
    const CONTAINER: usize = 0;
444
    const CONTENT: usize = 1;
445

            
446
    /// A `DomNodeId` in the root DOM pointing at flattened node `idx`.
447
    fn node(idx: usize) -> DomNodeId {
448
        DomNodeId {
449
            dom: DomId::ROOT_ID,
450
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
451
        }
452
    }
453

            
454
    /// A `DomNodeId` whose node component is `None` — the "no concrete node was hit"
455
    /// case. `CallbackInfo::set_css_property` *panics* on such an id, so the handler
456
    /// must bail out before ever reaching it.
457
    fn node_none() -> DomNodeId {
458
        DomNodeId {
459
            dom: DomId::ROOT_ID,
460
            node: NodeHierarchyItemId::NONE,
461
        }
462
    }
463

            
464
    /// A `DomLayoutResult` carrying only a `styled_dom`: the checkbox handler reaches
465
    /// exactly two `CallbackInfo` queries (`get_hit_node`, `get_first_child`), and
466
    /// both read the node hierarchy only — no real layout (and no font) is needed.
467
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
468
        DomLayoutResult {
469
            styled_dom,
470
            layout_tree: LayoutTree {
471
                nodes: Vec::new(),
472
                warm: Vec::new(),
473
                cold: Vec::new(),
474
                root: 0,
475
                dom_to_layout: BTreeMap::new(),
476
                children_arena: Vec::new(),
477
                children_offsets: Vec::new(),
478
                subtree_needs_intrinsic: Vec::new(),
479
            },
480
            calculated_positions: Vec::new(),
481
            viewport: LogicalRect::zero(),
482
            display_list: Arc::new(DisplayList::default()),
483
            scroll_ids: HashMap::new(),
484
            scroll_id_to_node_id: HashMap::new(),
485
        }
486
    }
487

            
488
    /// Runs `f` with a `CallbackInfo` whose window holds `styled_dom` as the root DOM
489
    /// and whose hit node is `hit`. Returns `f`'s value plus every change the callback
490
    /// pushed onto the transaction log.
491
    fn with_info<R>(
492
        styled_dom: StyledDom,
493
        hit: DomNodeId,
494
        f: impl FnOnce(&mut CallbackInfo) -> R,
495
    ) -> (R, Vec<CallbackChange>) {
496
        let mut layout_window =
497
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
498
        layout_window
499
            .layout_results
500
            .insert(DomId::ROOT_ID, layout_result(styled_dom));
501

            
502
        let renderer_resources = RendererResources::default();
503
        let previous_window_state: Option<FullWindowState> = None;
504
        let current_window_state = FullWindowState::default();
505
        let gl_context = OptionGlContextPtr::None;
506
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
507
            BTreeMap::new();
508
        let window_handle = RawWindowHandle::Unsupported;
509
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
510

            
511
        let ref_data = CallbackInfoRefData {
512
            layout_window: &layout_window,
513
            renderer_resources: &renderer_resources,
514
            previous_window_state: &previous_window_state,
515
            current_window_state: &current_window_state,
516
            gl_context: &gl_context,
517
            current_scroll_manager: &scroll_states,
518
            current_window_handle: &window_handle,
519
            system_callbacks: &system_callbacks,
520
            system_style: Arc::new(system::SystemStyle::default()),
521
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
522
            #[cfg(feature = "icu")]
523
            icu_localizer: IcuLocalizerHandle::default(),
524
            ctx: OptionRefAny::None,
525
        };
526

            
527
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
528

            
529
        let mut info = CallbackInfo::new(
530
            &ref_data,
531
            &changes,
532
            hit,
533
            OptionLogicalPosition::None,
534
            OptionLogicalPosition::None,
535
        );
536

            
537
        let r = f(&mut info);
538
        let pushed = info.take_changes();
539
        (r, pushed)
540
    }
541

            
542
    /// Renders `check_box`, then hands back both the laid-out DOM *and* the very
543
    /// `RefAny` the widget registered on its own mouse-up callback. Driving the
544
    /// handler with these two is the real wiring — nothing is re-created by hand,
545
    /// so a mismatch between what `dom()` stores and what the handler expects
546
    /// cannot hide behind the fixture.
547
    fn laid_out(check_box: CheckBox) -> (StyledDom, RefAny) {
548
        let dom = check_box.dom();
549
        let state = dom.root.callbacks.as_ref()[0].refany.clone();
550
        (StyledDom::create_from_dom(dom), state)
551
    }
552

            
553
    /// One "mouse-up on `hit`" delivered to the widget's own registered handler.
554
    fn click(
555
        styled_dom: StyledDom,
556
        state: &RefAny,
557
        hit: DomNodeId,
558
    ) -> (Update, Vec<CallbackChange>) {
559
        with_info(styled_dom, hit, |info| {
560
            input::default_on_checkbox_clicked(state.clone(), *info)
561
        })
562
    }
563

            
564
    fn is_checked(state: &RefAny) -> bool {
565
        let mut state = state.clone();
566
        let wrapper = state
567
            .downcast_ref::<CheckBoxStateWrapper>()
568
            .expect("the widget state changed type");
569
        wrapper.inner.checked
570
    }
571

            
572
    /// The opacity overrides pushed onto the content node, in push order.
573
    fn pushed_opacities(changes: &[CallbackChange]) -> Vec<(NodeId, f32)> {
574
        changes
575
            .iter()
576
            .filter_map(|c| match c {
577
                CallbackChange::ChangeNodeCssProperties {
578
                    node_id,
579
                    properties,
580
                    ..
581
                } => {
582
                    let o = properties.as_ref().iter().find_map(|p| match p {
583
                        CssProperty::Opacity(o) => o.get_property().map(|o| o.inner.normalized()),
584
                        _ => None,
585
                    })?;
586
                    Some((*node_id, o))
587
                }
588
                _ => None,
589
            })
590
            .collect()
591
    }
592

            
593
    // ------------------------------------------------------------------
594
    // Style-vec probes
595
    // ------------------------------------------------------------------
596

            
597
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
598
        v.as_ref().iter().map(|p| p.property.clone()).collect()
599
    }
600

            
601
    fn find<T>(
602
        v: &CssPropertyWithConditionsVec,
603
        f: impl Fn(&CssProperty) -> Option<T>,
604
    ) -> Option<T> {
605
        v.as_ref().iter().find_map(|p| f(&p.property))
606
    }
607

            
608
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length. An `em`
609
    /// or `%` slipping into the checkbox geometry would resolve against the parent
610
    /// font/box, so a 14px box could render at any size at all.
611
    fn px(pv: &PixelValue) -> f32 {
612
        assert_eq!(
613
            pv.metric,
614
            SizeMetric::Px,
615
            "checkbox geometry must be absolute px, got {:?}",
616
            pv.metric,
617
        );
618
        pv.number.get()
619
    }
620

            
621
    fn width_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
622
        find(v, |p| match p {
623
            CssProperty::Width(w) => match w.get_property() {
624
                Some(LayoutWidth::Px(pv)) => Some(px(pv)),
625
                _ => None,
626
            },
627
            _ => None,
628
        })
629
    }
630

            
631
    fn height_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
632
        find(v, |p| match p {
633
            CssProperty::Height(h) => match h.get_property() {
634
                Some(LayoutHeight::Px(pv)) => Some(px(pv)),
635
                _ => None,
636
            },
637
            _ => None,
638
        })
639
    }
640

            
641
    /// The declared opacity, normalized to 0.0..=1.0. `StyleOpacity::const_new` takes
642
    /// a *percentage*, so a `const_new(1)` typo yields 1% — a checkmark that is there
643
    /// but invisible. This is the only property that distinguishes the two states.
644
    fn opacity(v: &CssPropertyWithConditionsVec) -> Option<f32> {
645
        find(v, |p| match p {
646
            CssProperty::Opacity(o) => o.get_property().map(|o| o.inner.normalized()),
647
            _ => None,
648
        })
649
    }
650

            
651
    fn classes(dom: &Dom) -> Vec<String> {
652
        dom.root
653
            .get_ids_and_classes()
654
            .as_ref()
655
            .iter()
656
            .filter_map(|c| match c {
657
                Class(s) => Some(s.as_str().to_string()),
658
                IdOrClass::Id(_) => None,
659
            })
660
            .collect()
661
    }
662

            
663
    /// The properties of a rendered node's *inline* style, in declaration order.
664
    fn inline_properties(dom: &Dom) -> Vec<CssProperty> {
665
        dom.root
666
            .style
667
            .iter_inline_properties()
668
            .map(|(p, _)| p.clone())
669
            .collect()
670
    }
671

            
672
    // ------------------------------------------------------------------
673
    // Toggle callbacks
674
    // ------------------------------------------------------------------
675

            
676
    /// A payload the toggle callback writes into. It arrives as the `data: RefAny`
677
    /// argument — a *shared* clone of what the test still holds — so the test can
678
    /// read back exactly what the widget passed, without any global state.
679
    #[derive(Debug, Clone, PartialEq, Eq)]
680
    struct ToggleLog {
681
        seen: Vec<bool>,
682
        payload: u32,
683
    }
684

            
685
    extern "C" fn record_toggle(
686
        mut data: RefAny,
687
        _info: CallbackInfo,
688
        state: CheckBoxState,
689
    ) -> Update {
690
        if let Some(mut log) = data.downcast_mut::<ToggleLog>() {
691
            log.seen.push(state.checked);
692
        }
693
        Update::RefreshDom
694
    }
695

            
696
    extern "C" fn toggle_do_nothing(
697
        _data: RefAny,
698
        _info: CallbackInfo,
699
        _state: CheckBoxState,
700
    ) -> Update {
701
        Update::DoNothing
702
    }
703

            
704
    extern "C" fn toggle_refresh_all(
705
        _data: RefAny,
706
        _info: CallbackInfo,
707
        _state: CheckBoxState,
708
    ) -> Update {
709
        Update::RefreshDomAllWindows
710
    }
711

            
712
    /// A `Callback`-shaped (2-arg) function — the shape FFI bindings hand in, which the
713
    /// `From<Callback>` arm *transmutes* into the 3-arg checkbox slot. Never called.
714
    extern "C" fn generic_shaped(_data: RefAny, _info: CallbackInfo) -> Update {
715
        Update::DoNothing
716
    }
717

            
718
    fn log_refany() -> RefAny {
719
        RefAny::new(ToggleLog {
720
            seen: Vec::new(),
721
            payload: 0xDEAD_BEEF,
722
        })
723
    }
724

            
725
    fn read_log(probe: &RefAny) -> ToggleLog {
726
        let mut probe = probe.clone();
727
        let log = probe
728
            .downcast_ref::<ToggleLog>()
729
            .expect("the user payload changed type");
730
        log.clone()
731
    }
732

            
733
    // ==================================================================
734
    // CheckBox::create
735
    // ==================================================================
736

            
737
    #[test]
738
    fn create_stores_the_checked_flag_and_installs_no_callback() {
739
        for checked in [false, true] {
740
            let c = CheckBox::create(checked);
741
            assert_eq!(
742
                c.check_box_state.inner.checked, checked,
743
                "create({checked}) did not store the flag it was given",
744
            );
745
            assert!(
746
                c.check_box_state.on_toggle.as_ref().is_none(),
747
                "create({checked}) invented a toggle callback out of nowhere",
748
            );
749
        }
750
    }
751

            
752
    #[test]
753
    fn create_is_pure_and_its_two_states_are_distinguishable() {
754
        // Same input -> same widget (the const style tables are shared, not rebuilt),
755
        // and the checked/unchecked widgets must not compare equal — if they did, the
756
        // two states would render identically.
757
        assert_eq!(CheckBox::create(true), CheckBox::create(true));
758
        assert_eq!(CheckBox::create(false), CheckBox::create(false));
759
        assert_ne!(
760
            CheckBox::create(true),
761
            CheckBox::create(false),
762
            "a checked and an unchecked checkbox are indistinguishable",
763
        );
764
    }
765

            
766
    #[test]
767
    fn create_only_the_checkmark_opacity_depends_on_the_checked_flag() {
768
        // The container chrome must be byte-for-byte identical in both states: a box
769
        // that changed size/colour when ticked would reflow its neighbours.
770
        let checked = CheckBox::create(true);
771
        let unchecked = CheckBox::create(false);
772
        assert_eq!(
773
            properties(&checked.resolved_container_style()),
774
            properties(&unchecked.resolved_container_style()),
775
            "the container style differs between the checked and unchecked state",
776
        );
777

            
778
        // ... and the *content* styles differ in opacity and nothing else.
779
        let a = properties(&checked.resolved_content_style());
780
        let b = properties(&unchecked.resolved_content_style());
781
        assert_eq!(
782
            a.len(),
783
            b.len(),
784
            "the two content styles declare a different number of properties"
785
        );
786
        let differing: Vec<_> = a
787
            .iter()
788
            .zip(b.iter())
789
            .filter(|(x, y)| x != y)
790
            .map(|(x, _)| discriminant(x))
791
            .collect();
792
        assert_eq!(
793
            differing,
794
            vec![discriminant(&CssProperty::const_opacity(
795
                StyleOpacity::const_new(0)
796
            ))],
797
            "the checked/unchecked content styles differ in something other than opacity",
798
        );
799
    }
800

            
801
    #[test]
802
    fn create_maps_checked_to_a_fully_opaque_mark_and_unchecked_to_a_fully_transparent_one() {
803
        // `StyleOpacity::const_new` takes a percentage: 100 -> 1.0, 0 -> 0.0. A swapped
804
        // branch (or a `const_new(1)` typo) yields a checkbox that is permanently ticked
805
        // or permanently blank — both of which still *type*-check.
806
        assert_eq!(
807
            opacity(&CheckBox::create(true).resolved_content_style()),
808
            Some(1.0),
809
            "a checked checkbox does not show its checkmark",
810
        );
811
        assert_eq!(
812
            opacity(&CheckBox::create(false).resolved_content_style()),
813
            Some(0.0),
814
            "an unchecked checkbox still shows its checkmark",
815
        );
816
    }
817

            
818
    #[test]
819
    fn create_geometry_is_absolute_px_in_both_states() {
820
        for checked in [false, true] {
821
            let c = CheckBox::create(checked);
822
            // `px()` asserts SizeMetric::Px — an em/% here would scale with the parent.
823
            assert_eq!(
824
                width_px(&c.resolved_container_style()),
825
                Some(CONTAINER_SIDE)
826
            );
827
            assert_eq!(
828
                height_px(&c.resolved_container_style()),
829
                Some(CONTAINER_SIDE)
830
            );
831
            assert_eq!(width_px(&c.resolved_content_style()), Some(CONTENT_SIDE));
832
            assert_eq!(height_px(&c.resolved_content_style()), Some(CONTENT_SIDE));
833
        }
834
    }
835

            
836
    #[test]
837
    fn content_exactly_fills_the_containers_padding_box() {
838
        // 8 == 14 - 2*2 - 2*1. The mark is sized to fill the box's padding box exactly
839
        // under border-box sizing; if any of the four constants drifts, the checkmark
840
        // either overflows its box or leaves a gap, and nothing else in the file would
841
        // notice.
842
        assert_eq!(
843
            CONTENT_SIDE,
844
            CONTAINER_SIDE - 2.0 * PADDING - 2.0 * BORDER,
845
            "the checkbox geometry constants no longer add up",
846
        );
847

            
848
        let c = CheckBox::create(true);
849
        let padding = |f: fn(&CssProperty) -> Option<f32>| find(&c.resolved_container_style(), f);
850
        let pad_l = padding(|p| match p {
851
            CssProperty::PaddingLeft(v) => v.get_property().map(|v| px(&v.inner)),
852
            _ => None,
853
        });
854
        let pad_r = padding(|p| match p {
855
            CssProperty::PaddingRight(v) => v.get_property().map(|v| px(&v.inner)),
856
            _ => None,
857
        });
858
        let bor_l = padding(|p| match p {
859
            CssProperty::BorderLeftWidth(v) => v.get_property().map(|v| px(&v.inner)),
860
            _ => None,
861
        });
862
        let bor_r = padding(|p| match p {
863
            CssProperty::BorderRightWidth(v) => v.get_property().map(|v| px(&v.inner)),
864
            _ => None,
865
        });
866

            
867
        assert_eq!(pad_l, Some(PADDING));
868
        assert_eq!(pad_r, Some(PADDING));
869
        assert_eq!(bor_l, Some(BORDER));
870
        assert_eq!(bor_r, Some(BORDER));
871

            
872
        let inner =
873
            CONTAINER_SIDE - pad_l.unwrap() - pad_r.unwrap() - bor_l.unwrap() - bor_r.unwrap();
874
        assert_eq!(
875
            width_px(&c.resolved_content_style()),
876
            Some(inner),
877
            "the checkmark no longer fills the container's padding box",
878
        );
879
    }
880

            
881
    #[test]
882
    fn create_declares_no_property_twice() {
883
        // A duplicate declaration means the later one silently wins — a latent
884
        // "why is my override ignored" bug that never surfaces as an error.
885
        for checked in [false, true] {
886
            let c = CheckBox::create(checked);
887
            for (name, v) in [
888
                ("container", &c.resolved_container_style()),
889
                ("content", &c.resolved_content_style()),
890
            ] {
891
                let props = properties(v);
892
                let mut seen = Vec::new();
893
                for p in &props {
894
                    let d = discriminant(p);
895
                    assert!(
896
                        !seen.contains(&d),
897
                        "checked={checked}: the {name} style declares {p:?} twice",
898
                    );
899
                    seen.push(d);
900
                }
901
            }
902
        }
903
    }
904

            
905
    #[test]
906
    fn create_marks_the_container_as_clickable() {
907
        // Without `cursor: pointer` the checkbox looks inert even though it is the
908
        // node that carries the mouse-up handler.
909
        for checked in [false, true] {
910
            let cursor = find(
911
                &CheckBox::create(checked).resolved_container_style(),
912
                |p| match p {
913
                    CssProperty::Cursor(c) => c.get_property().copied(),
914
                    _ => None,
915
                },
916
            );
917
            assert_eq!(
918
                cursor,
919
                Some(StyleCursor::Pointer),
920
                "checked={checked}: the checkbox does not present as clickable",
921
            );
922
        }
923
    }
924

            
925
    // ==================================================================
926
    // CheckBox::swap_with_default
927
    // ==================================================================
928

            
929
    #[test]
930
    fn swap_with_default_returns_the_old_widget_and_leaves_an_unchecked_default_behind() {
931
        let mut c = CheckBox::create(true);
932
        let old = c.swap_with_default();
933

            
934
        assert_eq!(
935
            old,
936
            CheckBox::create(true),
937
            "the old widget was not returned intact"
938
        );
939
        assert_eq!(
940
            c,
941
            CheckBox::create(false),
942
            "what was left behind is not a fresh unchecked checkbox"
943
        );
944
    }
945

            
946
    #[test]
947
    fn swap_with_default_on_an_already_default_widget_is_a_no_op() {
948
        let mut c = CheckBox::create(false);
949
        let old = c.swap_with_default();
950
        assert_eq!(
951
            old, c,
952
            "swapping a default with a default produced two different widgets"
953
        );
954
        assert_eq!(old, CheckBox::create(false));
955
    }
956

            
957
    #[test]
958
    fn swap_with_default_moves_the_toggle_callback_out_rather_than_copying_or_dropping_it() {
959
        let probe = log_refany();
960
        let mut c = CheckBox::create(true)
961
            .with_on_toggle(probe.clone(), record_toggle as CheckBoxOnToggleCallbackType);
962

            
963
        let old = c.swap_with_default();
964

            
965
        // The callback (and its payload) left with the returned value ...
966
        let moved = old
967
            .check_box_state
968
            .on_toggle
969
            .as_ref()
970
            .expect("the toggle callback vanished during the swap");
971
        assert_eq!(
972
            moved.callback.cb as *const () as usize,
973
            record_toggle as CheckBoxOnToggleCallbackType as *const () as usize,
974
            "the fn pointer was mangled by the swap",
975
        );
976

            
977
        // ... and did NOT stay behind: a duplicated callback would fire twice, and a
978
        // duplicated RefAny would double-free its payload.
979
        assert!(
980
            c.check_box_state.on_toggle.as_ref().is_none(),
981
            "the toggle callback was copied instead of moved",
982
        );
983

            
984
        // The payload is still alive and unchanged after the move.
985
        assert_eq!(read_log(&probe).payload, 0xDEAD_BEEF);
986
    }
987

            
988
    #[test]
989
    fn swapping_twice_round_trips_the_original_widget() {
990
        let mut a = CheckBox::create(true);
991
        let mut b = a.swap_with_default(); // a = default, b = checked
992
        let c = b.swap_with_default(); // b = default, c = checked
993

            
994
        assert_eq!(c, CheckBox::create(true));
995
        assert_eq!(a, CheckBox::create(false));
996
        assert_eq!(b, CheckBox::create(false));
997
    }
998

            
999
    // ==================================================================
    // CheckBox::set_on_toggle / with_on_toggle
    // ==================================================================
    #[test]
    fn set_on_toggle_stores_the_function_pointer_and_the_payload_verbatim() {
        let mut c = CheckBox::create(false);
        c.set_on_toggle(
            RefAny::new(0xDEAD_BEEF_u32),
            toggle_do_nothing as CheckBoxOnToggleCallbackType,
        );
        let t = c
            .check_box_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 CheckBoxOnToggleCallbackType 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() {
        // `OptionCheckBoxOnToggle` is a single slot; setting twice must leave the
        // *second* callback installed (and must not leak the first one's RefAny).
        let first = log_refany();
        let mut c = CheckBox::create(false);
        c.set_on_toggle(
            first.clone(),
            toggle_do_nothing as CheckBoxOnToggleCallbackType,
        );
        c.set_on_toggle(
            RefAny::new(1u8),
            toggle_refresh_all as CheckBoxOnToggleCallbackType,
        );
        let t = c
            .check_box_state
            .on_toggle
            .as_ref()
            .expect("the callback vanished");
        assert_eq!(
            t.callback.cb as *const () as usize,
            toggle_refresh_all as CheckBoxOnToggleCallbackType 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 = CheckBox::create(checked);
            let mut c = CheckBox::create(checked);
            c.set_on_toggle(
                RefAny::new(0u8),
                toggle_do_nothing as CheckBoxOnToggleCallbackType,
            );
            assert_eq!(
                c.check_box_state.inner.checked, checked,
                "installing a callback flipped the checked flag",
            );
            assert_eq!(
                properties(&c.resolved_container_style()),
                properties(&pristine.resolved_container_style()),
                "installing a callback rewrote the container style",
            );
            assert_eq!(
                properties(&c.resolved_content_style()),
                properties(&pristine.resolved_content_style()),
                "installing a callback rewrote the content style",
            );
        }
    }
    #[test]
    fn with_on_toggle_is_exactly_set_on_toggle_in_builder_form() {
        let by_builder = CheckBox::create(true).with_on_toggle(
            RefAny::new(7u32),
            toggle_do_nothing as CheckBoxOnToggleCallbackType,
        );
        let mut by_setter = CheckBox::create(true);
        by_setter.set_on_toggle(
            RefAny::new(7u32),
            toggle_do_nothing as CheckBoxOnToggleCallbackType,
        );
        assert_eq!(
            by_builder.check_box_state.inner,
            by_setter.check_box_state.inner,
        );
        assert_eq!(
            properties(&by_builder.resolved_container_style()),
            properties(&by_setter.resolved_container_style()),
        );
        assert_eq!(
            properties(&by_builder.resolved_content_style()),
            properties(&by_setter.resolved_content_style()),
        );
        let a = by_builder
            .check_box_state
            .on_toggle
            .as_ref()
            .expect("builder lost the callback");
        let b = by_setter
            .check_box_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
        // checkbox 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 c = CheckBox::create(false).with_on_toggle(RefAny::new(0u8), generic);
        let t = c
            .check_box_state
            .on_toggle
            .as_ref()
            .expect("the generic callback was dropped");
        assert_eq!(
            t.callback.cb as *const () as usize, expected,
            "the Callback -> CheckBoxOnToggleCallback transmute mangled the pointer",
        );
    }
    // ==================================================================
    // CheckBox::dom
    // ==================================================================
    #[test]
    fn dom_builds_a_focusable_container_with_exactly_one_content_child() {
        for checked in [false, true] {
            let dom = CheckBox::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 checkbox is not keyboard-focusable",
            );
            assert_eq!(
                classes(&dom),
                vec!["__azul-native-checkbox-container".to_string()]
            );
            let children = dom.children.as_ref();
            assert_eq!(
                children.len(),
                1,
                "checked={checked}: the checkbox must have exactly one child"
            );
            assert_eq!(
                classes(&children[0]),
                vec!["__azul-native-checkbox-content".to_string()],
            );
            assert!(
                children[0].children.as_ref().is_empty(),
                "checked={checked}: the checkmark grew children",
            );
        }
    }
    #[test]
    fn dom_puts_the_container_style_on_the_box_and_the_content_style_on_the_mark() {
        // Swapping the two would style the 8px mark like a 14px bordered box (and vice
        // versa) — the widget would still render, just wrong.
        //
        // Compared without the theme-gated declarations: the theme appends a
        // dark background to each node on top of what the widget resolved, and
        // those twins are asserted separately below.
        for checked in [false, true] {
            let c = CheckBox::create(checked);
            let container = properties(&c.resolved_container_style());
            let content = properties(&c.resolved_content_style());
            let dom = c.dom();
            assert_eq!(
                theme_probe::unthemed(&dom),
                container,
                "checked={checked}: the container style did not land on the container",
            );
            assert_eq!(
                theme_probe::unthemed(&dom.children.as_ref()[0]),
                content,
                "checked={checked}: the content style did not land on the checkmark",
            );
        }
    }
    #[test]
    fn dom_gives_the_box_and_the_checked_mark_a_dark_mode_twin() {
        // The counterpart to the test above: the theme's dark declarations are
        // what keeps a light-mode fill off a dark surface, so they have to
        // actually be emitted, not merely tolerated by the comparison there.
        for checked in [false, true] {
            let dom = CheckBox::create(checked).dom();
            assert!(
                theme_probe::dark(&dom)
                    .iter()
                    .any(|p| matches!(p, CssProperty::BackgroundContent(_))),
                "checked={checked}: the box would paint its light fill in dark mode",
            );
            // Only the checked mark is filled, so only it needs a dark fill.
            assert_eq!(
                theme_probe::dark(&dom.children.as_ref()[0]).is_empty(),
                !checked,
                "checked={checked}: the mark's dark fill does not follow the check",
            );
        }
    }
    #[test]
    fn dom_registers_exactly_one_mouse_up_handler_and_it_is_the_widgets_own() {
        for checked in [false, true] {
            let dom = CheckBox::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 checkbox must toggle on mouse-up",
            );
            assert_eq!(
                callbacks[0].callback.cb,
                input::default_on_checkbox_clicked as usize,
                "checked={checked}: the registered handler is not default_on_checkbox_clicked",
            );
            // The mark 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 checkmark registered a handler of its own",
            );
        }
    }
    #[test]
    fn dom_hands_the_widget_state_to_the_handler_not_the_user_payload() {
        // `dom()` moves `check_box_state` (state + on_toggle + user RefAny) into the
        // callback's RefAny. If it stored the *user's* payload instead, the handler's
        // `downcast_mut::<CheckBoxStateWrapper>()` would fail and every click would be
        // a silent no-op.
        for checked in [false, true] {
            let dom = CheckBox::create(checked)
                .with_on_toggle(
                    RefAny::new(9u32),
                    toggle_do_nothing as CheckBoxOnToggleCallbackType,
                )
                .dom();
            let mut state = dom.root.callbacks.as_ref()[0].refany.clone();
            let wrapper = state
                .downcast_ref::<CheckBoxStateWrapper>()
                .expect("the handler's RefAny is not a CheckBoxStateWrapper");
            assert_eq!(
                wrapper.inner.checked, checked,
                "the checked 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_checkbox_still_registers_the_toggle_handler() {
        // Unlike Button (which registers nothing without an on_click), the checkbox must
        // always install its own handler: the box has to tick even with no user callback.
        let dom = CheckBox::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::<CheckBoxStateWrapper>()
            .expect("wrong RefAny type");
        assert!(wrapper.on_toggle.as_ref().is_none());
    }
    #[test]
    fn from_checkbox_for_dom_is_the_same_as_calling_dom() {
        for checked in [false, true] {
            let via_from = Dom::from(CheckBox::create(checked));
            let via_dom = CheckBox::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!(
                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: container (0), content (1).
        let styled = StyledDom::create_from_dom(CheckBox::create(true).dom());
        assert_eq!(
            styled.node_data.as_ref().len(),
            2,
            "the checkbox no longer flattens to a container + a checkmark",
        );
    }
    // ==================================================================
    // input::default_on_checkbox_clicked
    // ==================================================================
    #[test]
    fn clicking_toggles_the_flag_and_pushes_the_matching_opacity_onto_the_checkmark() {
        let (styled, state) = laid_out(CheckBox::create(false));
        assert!(!is_checked(&state));
        let (update, changes) = click(styled, &state, node(CONTAINER));
        assert!(is_checked(&state), "the click did not tick the checkbox");
        assert!(
            matches!(update, Update::DoNothing),
            "with no user callback installed, the handler must report DoNothing",
        );
        assert_eq!(
            pushed_opacities(&changes),
            vec![(NodeId::new(CONTENT), 1.0)],
            "ticking the box did not make the checkmark opaque (on the *content* node)",
        );
    }
    #[test]
    fn clicking_a_checked_box_unticks_it_and_hides_the_checkmark() {
        let (styled, state) = laid_out(CheckBox::create(true));
        let (_, changes) = click(styled, &state, node(CONTAINER));
        assert!(!is_checked(&state), "the click did not untick the checkbox");
        assert_eq!(
            pushed_opacities(&changes),
            vec![(NodeId::new(CONTENT), 0.0)],
            "unticking the box left the checkmark visible",
        );
    }
    #[test]
    fn clicking_twice_returns_to_the_original_state() {
        let (styled, state) = laid_out(CheckBox::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(CheckBox::create(false));
        let (_, first) = click(styled, &state, node(CONTAINER));
        let (_, second) = click(styled2, &state, node(CONTAINER));
        assert!(
            !is_checked(&state),
            "two clicks did not return the checkbox to its original state"
        );
        assert_eq!(pushed_opacities(&first), vec![(NodeId::new(CONTENT), 1.0)]);
        assert_eq!(pushed_opacities(&second), vec![(NodeId::new(CONTENT), 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 CheckBoxStateWrapper.
        let (styled, _) = laid_out(CheckBox::create(false));
        let foreign = RefAny::new(0xDEAD_BEEF_u32);
        let (update, changes) = click(styled, &foreign, node(CONTAINER));
        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_a_childless_node_does_not_half_apply_the_toggle() {
        // The handler needs the content node to sync the checkmark's opacity. If it is
        // not there, it must leave the *state* alone too — a flipped flag with no visual
        // update is a checkbox that renders the opposite of what it reports.
        let (styled, state) = laid_out(CheckBox::create(false));
        // The checkmark (node 1) is a leaf: it has no first child.
        let (update, changes) = click(styled, &state, node(CONTENT));
        assert!(matches!(update, Update::DoNothing));
        assert!(
            changes.is_empty(),
            "a change was pushed for a node the handler could not find"
        );
        assert!(
            !is_checked(&state),
            "the checked flag was flipped even though the checkmark could not be updated",
        );
    }
    #[test]
    fn clicking_a_node_that_is_not_in_the_layout_does_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(99), node(usize::MAX - 1), node_none()] {
            let (styled, state) = laid_out(CheckBox::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 checkbox"
            );
        }
    }
    #[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(
            CheckBox::create(false)
                .with_on_toggle(probe.clone(), record_toggle as CheckBoxOnToggleCallbackType),
        );
        let (update, changes) = click(styled, &state, node(CONTAINER));
        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 opacity sync still happens *after* the user callback returns.
        assert_eq!(
            pushed_opacities(&changes),
            vec![(NodeId::new(CONTENT), 1.0)]
        );
    }
    #[test]
    fn the_toggle_callback_receives_the_user_payload_not_the_widget_state() {
        let probe = log_refany();
        let (styled, state) = laid_out(
            CheckBox::create(true)
                .with_on_toggle(probe.clone(), record_toggle as CheckBoxOnToggleCallbackType),
        );
        click(styled, &state, node(CONTAINER));
        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_checkmark_synced() {
        // A user callback returning DoNothing must not suppress the widget's own visual
        // bookkeeping — otherwise the flag says "checked" and the mark stays invisible.
        let (styled, state) = laid_out(CheckBox::create(false).with_on_toggle(
            RefAny::new(0u8),
            toggle_do_nothing as CheckBoxOnToggleCallbackType,
        ));
        let (update, changes) = click(styled, &state, node(CONTAINER));
        assert!(matches!(update, Update::DoNothing));
        assert!(is_checked(&state));
        assert_eq!(
            pushed_opacities(&changes),
            vec![(NodeId::new(CONTENT), 1.0)],
            "a DoNothing user callback suppressed the checkmark update",
        );
    }
    #[test]
    fn a_toggle_callback_on_a_childless_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(
            CheckBox::create(false)
                .with_on_toggle(probe.clone(), record_toggle as CheckBoxOnToggleCallbackType),
        );
        let (update, changes) = click(styled, &state, node(CONTENT));
        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_state_and_the_pushed_opacity_in_agreement() {
        // 101 clicks starting unchecked -> checked. Every push must agree with the flag
        // it accompanies; a drift between the two is exactly the class of bug that makes
        // a checkbox render inverted after a while.
        let mut state_after = false;
        let start = CheckBox::create(false);
        let (_, state) = laid_out(start);
        for i in 0..101u32 {
            let (styled, _) = laid_out(CheckBox::create(false));
            let (_, changes) = click(styled, &state, node(CONTAINER));
            state_after = !state_after;
            let expected = if state_after { 1.0 } else { 0.0 };
            assert_eq!(
                pushed_opacities(&changes),
                vec![(NodeId::new(CONTENT), expected)],
                "click #{i}: the pushed opacity disagrees with the checked flag",
            );
            assert_eq!(
                is_checked(&state),
                state_after,
                "click #{i}: the flag drifted"
            );
        }
        assert!(
            is_checked(&state),
            "an odd number of clicks left the checkbox unchecked"
        );
    }
}