1
//! Radio-group widget — a vertical (or horizontal) group of mutually-exclusive
2
//! options where exactly one is selected. Combines the sibling-navigation +
3
//! `selected_index` state of [`crate::widgets::segmented::Segmented`] with the
4
//! circular filled/empty indicator visual of
5
//! [`crate::widgets::check_box::CheckBox`].
6
//!
7
//! Each option is a row: a circular indicator (an outer ring containing an inner
8
//! dot whose opacity is `100` when selected, `0` otherwise) followed by a text
9
//! label. Clicking any row selects it: the internal handler computes the clicked
10
//! row's index from its position among its siblings, updates `selected_index`,
11
//! invokes the user's `on_change(index)`, and live-restyles every row's dot via
12
//! `set_css_property`.
13
//!
14
//! Key types: [`RadioGroup`], [`RadioGroupState`], [`RadioGroupOnChange`].
15

            
16
use std::vec::Vec;
17

            
18
use azul_core::{
19
    callbacks::{CoreCallbackData, Update},
20
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
21
    refany::RefAny,
22
};
23
use azul_css::{
24
    dynamic_selector::{
25
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
26
    },
27
    impl_option_inner,
28
    props::{
29
        basic::{color::ColorU, StyleFontSize},
30
        layout::{
31
            LayoutAlignItems, LayoutAlignSelf, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow,
32
            LayoutHeight, LayoutJustifyContent, LayoutMarginBottom, LayoutMarginLeft,
33
            LayoutMarginRight, LayoutWidth,
34
        },
35
        property::{CssProperty, *},
36
        style::{
37
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
38
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
39
            StyleBorderBottomColor, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius,
40
            StyleBorderBottomStyle, StyleBorderLeftColor, StyleBorderLeftStyle,
41
            StyleBorderRightColor, StyleBorderRightStyle, StyleBorderTopColor,
42
            StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderTopStyle, StyleCursor,
43
            StyleOpacity, StyleUserSelect,
44
        },
45
    },
46
    AzString, OptionString, StringVec,
47
};
48

            
49
use crate::callbacks::{Callback, CallbackInfo};
50

            
51
static RADIO_GROUP_CLASS: &[IdOrClass] =
52
    &[Class(AzString::from_const_str("__azul-native-radio-group"))];
53
static RADIO_GROUP_ROW_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
54
    "__azul-native-radio-group-row",
55
))];
56
static RADIO_GROUP_CIRCLE_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
57
    "__azul-native-radio-group-circle",
58
))];
59
static RADIO_GROUP_DOT_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
60
    "__azul-native-radio-group-dot",
61
))];
62
static RADIO_GROUP_LABEL_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
63
    "__azul-native-radio-group-label",
64
))];
65

            
66
/// Callback function type invoked when the selected option changes.
67
pub type RadioGroupOnChangeCallbackType =
68
    extern "C" fn(RefAny, CallbackInfo, RadioGroupState) -> Update;
69
impl_widget_callback!(
70
    RadioGroupOnChange,
71
    OptionRadioGroupOnChange,
72
    RadioGroupOnChangeCallback,
73
    RadioGroupOnChangeCallbackType
74
);
75

            
76
azul_core::impl_managed_callback! {
77
    wrapper:        RadioGroupOnChangeCallback,
78
    info_ty:        CallbackInfo,
79
    return_ty:      Update,
80
    default_ret:    Update::DoNothing,
81
    invoker_static: RADIO_GROUP_ON_CHANGE_INVOKER,
82
    invoker_ty:     AzRadioGroupOnChangeCallbackInvoker,
83
    thunk_fn:       az_radio_group_on_change_callback_thunk,
84
    setter_fn:      AzApp_setRadioGroupOnChangeCallbackInvoker,
85
    from_handle_fn: AzRadioGroupOnChangeCallback_createFromHostHandle,
86
    extra_args:     [ state: RadioGroupState ],
87
}
88

            
89
/// A group of mutually-exclusive radio options with a selection callback.
90
#[derive(Debug, Clone, PartialEq, Eq)]
91
#[repr(C)]
92
pub struct RadioGroup {
93
    pub radio_group_state: RadioGroupStateWrapper,
94
    /// The label of each option, in order.
95
    pub options: StringVec,
96
    /// Style for the group container, or `None` for "no opinion" — in which case
97
    /// the style is derived from the horizontal flag at render time.
98
    ///
99
    /// `None` and `Some(empty)` are different answers: the first means the
100
    /// widget picks, the second means the caller asked for no properties at all
101
    /// and gets none.
102
    pub container_style: OptionCssPropertyWithConditionsVec,
103
    /// What this control is CALLED, for assistive technology.
104
    ///
105
    /// Carried by the WIDGET rather than patched onto the finished `Dom`: that
106
    /// is what lets the widget know at build time whether it was named, so its
107
    /// warning fires only when nobody supplied one. Forwarded into the
108
    /// accessibility declaration the widget builds anyway, beside its role and
109
    /// state.
110
    pub accessibility_name: OptionString,
111
}
112

            
113
#[derive(Debug, Default, Clone, PartialEq, Eq)]
114
#[repr(C)]
115
pub struct RadioGroupStateWrapper {
116
    /// The current selection.
117
    pub inner: RadioGroupState,
118
    /// `true` lays the options out in a horizontal row, `false` (default) stacks
119
    /// them vertically.
120
    pub horizontal: bool,
121
    /// Optional: function to call when the selection changes.
122
    pub on_change: OptionRadioGroupOnChange,
123
}
124

            
125
/// State of a [`RadioGroup`]: the index of the currently selected option.
126
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
127
#[repr(C)]
128
pub struct RadioGroupState {
129
    /// Zero-based index of the selected option.
130
    pub selected_index: usize,
131
}
132

            
133
// ---- dimensions (logical px) ----
134
const CIRCLE_SIZE: isize = 16;
135
const CIRCLE_RADIUS: isize = 8;
136
const CIRCLE_BORDER: isize = 1;
137
const DOT_SIZE: isize = 8;
138
const DOT_RADIUS: isize = 4;
139
/// Gap between stacked rows (vertical) / between side-by-side rows (horizontal).
140
const ROW_GAP: isize = 6;
141
/// Gap between the indicator circle and its label.
142
const LABEL_GAP: isize = 8;
143

            
144
// ---- colours ----
145
/// Indicator ring colour (#9b9b9b).
146
const CIRCLE_BORDER_COLOR: ColorU = ColorU {
147
    r: 155,
148
    g: 155,
149
    b: 155,
150
    a: 255,
151
};
152
/// Selected dot fill (#0d6efd, accent blue).
153
const DOT_COLOR: ColorU = ColorU {
154
    r: 13,
155
    g: 110,
156
    b: 253,
157
    a: 255,
158
};
159

            
160
const DOT_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(DOT_COLOR)];
161
const DOT_BG: StyleBackgroundContentVec = StyleBackgroundContentVec::from_const_slice(DOT_BG_ITEMS);
162

            
163
/// Outer ring of one option's indicator (parameter-independent → const slice).
164
/// A flex box that centres its inner dot.
165
static RADIO_GROUP_CIRCLE_STYLE: &[CssPropertyWithConditions] = &[
166
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
167
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
168
    CssPropertyWithConditions::simple(CssProperty::const_justify_content(
169
        LayoutJustifyContent::Center,
170
    )),
171
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
172
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
173
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(CIRCLE_SIZE))),
174
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(
175
        CIRCLE_SIZE,
176
    ))),
177
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
178
        LayoutBorderTopWidth::const_px(CIRCLE_BORDER),
179
    )),
180
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
181
        LayoutBorderBottomWidth::const_px(CIRCLE_BORDER),
182
    )),
183
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
184
        LayoutBorderLeftWidth::const_px(CIRCLE_BORDER),
185
    )),
186
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
187
        LayoutBorderRightWidth::const_px(CIRCLE_BORDER),
188
    )),
189
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
190
        inner: BorderStyle::Solid,
191
    })),
192
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
193
        StyleBorderBottomStyle {
194
            inner: BorderStyle::Solid,
195
        },
196
    )),
197
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
198
        inner: BorderStyle::Solid,
199
    })),
200
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
201
        StyleBorderRightStyle {
202
            inner: BorderStyle::Solid,
203
        },
204
    )),
205
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
206
        inner: CIRCLE_BORDER_COLOR,
207
    })),
208
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
209
        StyleBorderBottomColor {
210
            inner: CIRCLE_BORDER_COLOR,
211
        },
212
    )),
213
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
214
        inner: CIRCLE_BORDER_COLOR,
215
    })),
216
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
217
        StyleBorderRightColor {
218
            inner: CIRCLE_BORDER_COLOR,
219
        },
220
    )),
221
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
222
        StyleBorderTopLeftRadius::const_px(CIRCLE_RADIUS),
223
    )),
224
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
225
        StyleBorderTopRightRadius::const_px(CIRCLE_RADIUS),
226
    )),
227
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
228
        StyleBorderBottomLeftRadius::const_px(CIRCLE_RADIUS),
229
    )),
230
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
231
        StyleBorderBottomRightRadius::const_px(CIRCLE_RADIUS),
232
    )),
233
];
234

            
235
/// Inner filled dot when the option is SELECTED (opacity 100).
236
static RADIO_GROUP_DOT_STYLE_SELECTED: &[CssPropertyWithConditions] = &[
237
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(DOT_SIZE))),
238
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(DOT_SIZE))),
239
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
240
    CssPropertyWithConditions::simple(CssProperty::const_background_content(DOT_BG)),
241
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
242
        StyleBorderTopLeftRadius::const_px(DOT_RADIUS),
243
    )),
244
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
245
        StyleBorderTopRightRadius::const_px(DOT_RADIUS),
246
    )),
247
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
248
        StyleBorderBottomLeftRadius::const_px(DOT_RADIUS),
249
    )),
250
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
251
        StyleBorderBottomRightRadius::const_px(DOT_RADIUS),
252
    )),
253
    CssPropertyWithConditions::simple(CssProperty::const_opacity(StyleOpacity::const_new(100))),
254
];
255

            
256
/// Inner filled dot when the option is UNSELECTED (opacity 0 — hidden but laid out).
257
static RADIO_GROUP_DOT_STYLE_UNSELECTED: &[CssPropertyWithConditions] = &[
258
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(DOT_SIZE))),
259
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(DOT_SIZE))),
260
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
261
    CssPropertyWithConditions::simple(CssProperty::const_background_content(DOT_BG)),
262
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
263
        StyleBorderTopLeftRadius::const_px(DOT_RADIUS),
264
    )),
265
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
266
        StyleBorderTopRightRadius::const_px(DOT_RADIUS),
267
    )),
268
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
269
        StyleBorderBottomLeftRadius::const_px(DOT_RADIUS),
270
    )),
271
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
272
        StyleBorderBottomRightRadius::const_px(DOT_RADIUS),
273
    )),
274
    CssPropertyWithConditions::simple(CssProperty::const_opacity(StyleOpacity::const_new(0))),
275
];
276

            
277
/// Builds the container style. Orientation (row vs column) is the only
278
/// parameter-dependent property, so the style is built at runtime.
279
489
fn build_container_style(horizontal: bool) -> CssPropertyWithConditionsVec {
280
489
    let direction = if horizontal {
281
162
        LayoutFlexDirection::Row
282
    } else {
283
327
        LayoutFlexDirection::Column
284
    };
285
489
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
286
489
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
287
489
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(direction)),
288
489
        CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
289
489
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
290
            0,
291
        ))),
292
    ])
293
489
}
294

            
295
/// Builds one option's row style. The orientation decides whether the inter-row
296
/// gap is applied to the bottom (vertical) or the right (horizontal).
297
178
fn build_row_style(horizontal: bool) -> CssPropertyWithConditionsVec {
298
178
    let mut v: Vec<CssPropertyWithConditions> = alloc::vec![
299
178
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
300
178
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
301
178
            LayoutFlexDirection::Row,
302
        )),
303
178
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
304
178
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
305
            0,
306
        ))),
307
178
        CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
308
178
        CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
309
    ];
310
178
    if horizontal {
311
10
        v.push(CssPropertyWithConditions::simple(
312
10
            CssProperty::const_margin_right(LayoutMarginRight::const_px(ROW_GAP * 2)),
313
10
        ));
314
168
    } else {
315
168
        v.push(CssPropertyWithConditions::simple(
316
168
            CssProperty::const_margin_bottom(LayoutMarginBottom::const_px(ROW_GAP)),
317
168
        ));
318
168
    }
319
178
    CssPropertyWithConditionsVec::from_vec(v)
320
178
}
321

            
322
/// The label-text style: a small left gap from the indicator.
323
static RADIO_GROUP_LABEL_STYLE: &[CssPropertyWithConditions] = &[
324
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
325
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(13))),
326
    CssPropertyWithConditions::simple(CssProperty::const_margin_left(LayoutMarginLeft::const_px(
327
        LABEL_GAP,
328
    ))),
329
];
330

            
331
impl RadioGroup {
332
    /// Creates a radio group from the given options, with the first one selected.
333
    /// Name this control for assistive technology.
334
    #[must_use]
335
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
336
        self.accessibility_name = Some(name.into()).into();
337
        self
338
    }
339

            
340
    #[must_use]
341
171
    pub fn create(options: StringVec) -> Self {
342
171
        Self {
343
171
            radio_group_state: RadioGroupStateWrapper {
344
171
                inner: RadioGroupState { selected_index: 0 },
345
171
                horizontal: false,
346
171
                ..Default::default()
347
171
            },
348
171
            options,
349
171
            container_style: OptionCssPropertyWithConditionsVec::None,
350
171
            accessibility_name: OptionString::None,
351
171
        }
352
171
    }
353

            
354
    /// The container CSS this group renders with.
355
    ///
356
    /// `None` means no opinion, so the horizontal flag decides — the same answer
357
    /// both themes give, asked in one place so they cannot drift. It is also why
358
    /// `set_horizontal` is a plain field write: the flag is the single source of
359
    /// truth for the axis, rather than one of two that have to be kept in step.
360
    #[must_use]
361
375
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
362
375
        self.container_style
363
375
            .clone()
364
375
            .into_option()
365
375
            .unwrap_or_else(|| build_container_style(self.radio_group_state.horizontal))
366
375
    }
367

            
368
    /// Sets the currently selected option index.
369
    #[inline]
370
41
    pub const fn set_selected_index(&mut self, selected_index: usize) {
371
41
        self.radio_group_state.inner.selected_index = selected_index;
372
41
    }
373

            
374
    /// Builder-style setter for the selected option index.
375
    #[inline]
376
    #[must_use]
377
29
    pub const fn with_selected_index(mut self, selected_index: usize) -> Self {
378
29
        self.set_selected_index(selected_index);
379
29
        self
380
29
    }
381

            
382
    /// Lays the options out horizontally (default is vertical).
383
    ///
384
    /// Does not touch `container_style`: the flex direction is resolved from this
385
    /// flag when the DOM is built, so the two can no longer disagree.
386
    #[inline]
387
113
    pub const fn set_horizontal(&mut self, horizontal: bool) {
388
113
        self.radio_group_state.horizontal = horizontal;
389
113
    }
390

            
391
    /// Builder-style setter for the horizontal layout flag.
392
    #[inline]
393
    #[must_use]
394
9
    pub const fn with_horizontal(mut self, horizontal: bool) -> Self {
395
9
        self.set_horizontal(horizontal);
396
9
        self
397
9
    }
398

            
399
    #[inline]
400
    #[must_use]
401
5
    pub fn swap_with_default(&mut self) -> Self {
402
5
        let mut s = Self::create(StringVec::from_const_slice(&[]));
403
5
        core::mem::swap(&mut s, self);
404
5
        s
405
5
    }
406

            
407
    #[inline]
408
11
    pub fn set_on_change<C: Into<RadioGroupOnChangeCallback>>(
409
11
        &mut self,
410
11
        data: RefAny,
411
11
        on_change: C,
412
11
    ) {
413
11
        self.radio_group_state.on_change = Some(RadioGroupOnChange {
414
11
            callback: on_change.into(),
415
11
            refany: data,
416
11
        })
417
11
        .into();
418
11
    }
419

            
420
    #[inline]
421
    #[must_use]
422
8
    pub fn with_on_change<C: Into<RadioGroupOnChangeCallback>>(
423
8
        mut self,
424
8
        data: RefAny,
425
8
        on_change: C,
426
8
    ) -> Self {
427
8
        self.set_on_change(data, on_change);
428
8
        self
429
8
    }
430

            
431
    #[must_use]
432
162
    pub fn dom(self) -> Dom {
433
        // Read before the widget's fields are moved into the DOM below.
434
162
        let rg_name = self.accessibility_name.clone();
435
162
        let container_style = self.resolved_container_style();
436
162
        crate::widgets::warn_widget_needs_a_name("radio_group", rg_name.is_some());
437

            
438
        use azul_core::{
439
            callbacks::CoreCallback,
440
            dom::{EventFilter, HoverEventFilter},
441
            refany::OptionRefAny,
442
        };
443

            
444
162
        let selected = self.radio_group_state.inner.selected_index;
445
162
        let horizontal = self.radio_group_state.horizontal;
446
162
        let count = self.options.as_ref().len();
447

            
448
162
        let row_style = build_row_style(horizontal);
449

            
450
        // One shared RefAny across every row's callback (RefAny::clone shares
451
        // the underlying state — same pattern as segmented/tabs/map).
452
        // Read once, BEFORE the state is moved into the shared RefAny below.
453
162
        let selected_now = self.radio_group_state.inner.selected_index;
454
162
        let state = RefAny::new(self.radio_group_state);
455

            
456
162
        let mut children: Vec<Dom> = Vec::with_capacity(count);
457
1227
        for (i, label) in self.options.as_ref().iter().enumerate() {
458
1227
            let dot_style = if i == selected {
459
151
                CssPropertyWithConditionsVec::from_const_slice(RADIO_GROUP_DOT_STYLE_SELECTED)
460
            } else {
461
1076
                CssPropertyWithConditionsVec::from_const_slice(RADIO_GROUP_DOT_STYLE_UNSELECTED)
462
            };
463

            
464
1227
            let circle = Dom::create_div()
465
1227
                .with_ids_and_classes(IdOrClassVec::from_const_slice(RADIO_GROUP_CIRCLE_CLASS))
466
1227
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
467
1227
                    RADIO_GROUP_CIRCLE_STYLE,
468
                ))
469
1227
                .with_children(
470
1227
                    vec![Dom::create_div()
471
1227
                        .with_ids_and_classes(IdOrClassVec::from_const_slice(RADIO_GROUP_DOT_CLASS))
472
1227
                        .with_css_props(dot_style)]
473
1227
                    .into(),
474
                );
475

            
476
1227
            let label_node = crate::widgets::widget_p_with_text(label.clone())
477
1227
                .with_ids_and_classes(IdOrClassVec::from_const_slice(RADIO_GROUP_LABEL_CLASS))
478
1227
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
479
1227
                    RADIO_GROUP_LABEL_STYLE,
480
                ));
481

            
482
1227
            children.push(
483
1227
                Dom::create_div()
484
1227
                    .with_ids_and_classes(IdOrClassVec::from_const_slice(RADIO_GROUP_ROW_CLASS))
485
1227
                    .with_css_props(row_style.clone())
486
1227
                    .with_callbacks(
487
1227
                        vec![CoreCallbackData {
488
1227
                            event: EventFilter::Hover(HoverEventFilter::Click),
489
1227
                            callback: CoreCallback {
490
1227
                                cb: on_radio_row_click as usize,
491
1227
                                ctx: OptionRefAny::None,
492
1227
                            },
493
1227
                            refany: state.clone(),
494
1227
                        }]
495
1227
                        .into(),
496
                    )
497
1227
                    .with_tab_index(TabIndex::Auto)
498
                    // Each row is its own radio button and must say whether IT
499
                    // is the chosen one. A group where every row announces the
500
                    // same thing is unusable: the user cannot tell which is
501
                    // selected without seeing the dot.
502
1227
                    .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
503
1227
                        role: azul_core::a11y::AccessibilityRole::RadioButton,
504
1227
                        states: azul_core::a11y::AccessibilityStateVec::from_vec(vec![
505
1227
                            if i == selected_now {
506
151
                                azul_core::a11y::AccessibilityState::CheckedTrue
507
                            } else {
508
1076
                                azul_core::a11y::AccessibilityState::CheckedFalse
509
                            },
510
                        ]),
511
1227
                        ..Default::default()
512
                    })
513
1227
                    .with_children(vec![circle, label_node].into()),
514
            );
515
        }
516

            
517
162
        Dom::create_div()
518
162
            .with_ids_and_classes(IdOrClassVec::from_const_slice(RADIO_GROUP_CLASS))
519
162
            .with_css_props(container_style)
520
            // The name belongs to the GROUP, not to each row. Every row already
521
            // has its own option text, which azul derives a name from; stamping
522
            // the group's name onto all of them would make them announce
523
            // identically and hide the very thing the user is choosing between.
524
162
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
525
162
                role: azul_core::a11y::AccessibilityRole::Grouping,
526
162
                accessibility_name: rg_name,
527
162
                ..Default::default()
528
162
            })
529
162
            .with_children(children.into())
530
162
    }
531
}
532

            
533
impl Default for RadioGroup {
534
10
    fn default() -> Self {
535
10
        Self::create(StringVec::from_const_slice(&[]))
536
10
    }
537
}
538

            
539
/// Click handler shared by all rows. Determines the clicked row's index from its
540
/// position among its siblings (the hit node resolves to the row the callback is
541
/// registered on — currentTarget semantics — regardless of whether the dot,
542
/// circle or label was clicked), updates the selection, invokes the user
543
/// callback, and live-restyles every row's indicator dot.
544
89
extern "C" fn on_radio_row_click(mut data: RefAny, mut info: CallbackInfo) -> Update {
545
    use azul_core::dom::DomNodeId;
546

            
547
89
    let clicked = info.get_hit_node();
548
89
    let Some(parent) = info.get_parent(clicked) else {
549
5
        return Update::DoNothing;
550
    };
551

            
552
    // Collect the option rows in document order.
553
84
    let mut rows: Vec<DomNodeId> = Vec::new();
554
84
    let mut cur = info.get_first_child(parent);
555
591
    while let Some(node) = cur {
556
507
        rows.push(node);
557
507
        cur = info.get_next_sibling(node);
558
507
    }
559

            
560
301
    let Some(selected) = rows.iter().position(|n| *n == clicked) else {
561
        return Update::DoNothing;
562
    };
563

            
564
82
    let result = {
565
84
        let Some(mut rg) = data.downcast_mut::<RadioGroupStateWrapper>() else {
566
2
            return Update::DoNothing;
567
        };
568
82
        rg.inner.selected_index = selected;
569
82
        let inner = rg.inner;
570
82
        let rg = &mut *rg;
571
82
        match rg.on_change.as_mut() {
572
6
            Some(RadioGroupOnChange { callback, refany }) => {
573
6
                (callback.cb)(refany.clone(), info, inner)
574
            }
575
76
            None => Update::DoNothing,
576
        }
577
    };
578

            
579
    // Live-restyle every row's dot: the selected option's dot becomes visible
580
    // (opacity 100), the rest are hidden (opacity 0). Each row is
581
    // `row → circle (first child) → dot (first child)`.
582
503
    for (i, row) in rows.iter().enumerate() {
583
503
        let Some(circle) = info.get_first_child(*row) else {
584
2
            continue;
585
        };
586
501
        let Some(dot) = info.get_first_child(circle) else {
587
4
            continue;
588
        };
589
497
        let opacity = if i == selected { 100 } else { 0 };
590
497
        info.set_css_property(
591
497
            dot,
592
497
            CssProperty::const_opacity(StyleOpacity::const_new(opacity)),
593
        );
594
    }
595

            
596
82
    result
597
89
}
598

            
599
impl From<RadioGroup> for Dom {
600
    fn from(r: RadioGroup) -> Self {
601
        r.dom()
602
    }
603
}
604

            
605
#[cfg(test)]
606
#[allow(clippy::float_cmp, clippy::too_many_lines)]
607
// `assertions_on_constants`: these are deliberate invariant guards over sibling
608
// `const`s in this module. They are const-foldable *today*, which is exactly the
609
// point — they must go red the moment someone edits one of those constants into an
610
// inconsistent value. Deleting them (clippy's suggestion) would delete the check.
611
#[allow(clippy::assertions_on_constants)]
612
mod autotest_generated {
613
    use std::{
614
        collections::{BTreeMap, HashMap},
615
        mem::discriminant,
616
        sync::{Arc, Mutex},
617
    };
618

            
619
    use azul_core::{
620
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
621
        geom::{LogicalRect, OptionLogicalPosition},
622
        gl::OptionGlContextPtr,
623
        hit_test::ScrollPosition,
624
        refany::OptionRefAny,
625
        resources::RendererResources,
626
        styled_dom::{NodeHierarchyItemId, StyledDom},
627
        window::{MonitorVec, RawWindowHandle},
628
    };
629
    use azul_css::{
630
        props::basic::{length::SizeMetric, pixel::PixelValue},
631
        system::SystemStyle,
632
    };
633
    use rust_fontconfig::FcFontCache;
634

            
635
    use super::*;
636
    #[cfg(feature = "icu")]
637
    use crate::icu::IcuLocalizerHandle;
638
    use crate::{
639
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
640
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
641
        window::{DomLayoutResult, LayoutWindow},
642
        window_state::FullWindowState,
643
    };
644

            
645
    // ------------------------------------------------------------------
646
    // Fixtures
647
    // ------------------------------------------------------------------
648

            
649
    fn labels(v: &[&str]) -> StringVec {
650
        StringVec::from_vec(v.iter().map(|s| AzString::from(*s)).collect::<Vec<_>>())
651
    }
652

            
653
    /// `n` distinct labels: `o0, o1, … o{n-1}`.
654
    fn n_labels(n: usize) -> StringVec {
655
        StringVec::from_vec(
656
            (0..n)
657
                .map(|i| AzString::from(format!("o{i}")))
658
                .collect::<Vec<_>>(),
659
        )
660
    }
661

            
662
    fn group(v: &[&str]) -> RadioGroup {
663
        RadioGroup::create(labels(v))
664
    }
665

            
666
    // ------------------------------------------------------------------
667
    // Style probes
668
    // ------------------------------------------------------------------
669

            
670
    fn props(style: &[CssPropertyWithConditions]) -> Vec<CssProperty> {
671
        style.iter().map(|p| p.property.clone()).collect()
672
    }
673

            
674
    fn has_property(style: &[CssPropertyWithConditions], wanted: &CssProperty) -> bool {
675
        style.iter().any(|p| p.property == *wanted)
676
    }
677

            
678
    /// Every style in this file is unconditional — a stray `@media`/`:hover`
679
    /// condition would make the property silently not apply.
680
    fn all_unconditional(style: &[CssPropertyWithConditions]) -> bool {
681
        style.iter().all(|p| p.apply_if.as_ref().is_empty())
682
    }
683

            
684
    fn no_duplicate_properties(name: &str, style: &[CssPropertyWithConditions]) {
685
        let mut seen = Vec::new();
686
        for p in style {
687
            let d = discriminant(&p.property);
688
            assert!(
689
                !seen.contains(&d),
690
                "{name} declares {:?} twice — the later declaration silently wins",
691
                p.property,
692
            );
693
            seen.push(d);
694
        }
695
    }
696

            
697
    /// The opacity declared by a property list, normalized to `0.0..=1.0`.
698
    /// `StyleOpacity::const_new` takes a *percentage*, so `const_new(1)` would be
699
    /// 1% — a dot that is technically there but invisible.
700
    fn opacity_of(properties: &[CssProperty]) -> Option<f32> {
701
        properties.iter().find_map(|p| match p {
702
            CssProperty::Opacity(o) => o.get_property().map(|o| o.inner.normalized()),
703
            _ => None,
704
        })
705
    }
706

            
707
    fn flex_direction(properties: &[CssProperty]) -> Option<LayoutFlexDirection> {
708
        properties.iter().find_map(|p| match p {
709
            CssProperty::FlexDirection(d) => d.get_property().copied(),
710
            _ => None,
711
        })
712
    }
713

            
714
    fn cursor(properties: &[CssProperty]) -> Option<StyleCursor> {
715
        properties.iter().find_map(|p| match p {
716
            CssProperty::Cursor(c) => c.get_property().copied(),
717
            _ => None,
718
        })
719
    }
720

            
721
    fn user_select(properties: &[CssProperty]) -> Option<StyleUserSelect> {
722
        properties.iter().find_map(|p| match p {
723
            CssProperty::UserSelect(u) => u.get_property().copied(),
724
            _ => None,
725
        })
726
    }
727

            
728
    fn margin_bottom(properties: &[CssProperty]) -> Option<PixelValue> {
729
        properties.iter().find_map(|p| match p {
730
            CssProperty::MarginBottom(m) => m.get_property().map(|m| m.inner),
731
            _ => None,
732
        })
733
    }
734

            
735
    fn margin_right(properties: &[CssProperty]) -> Option<PixelValue> {
736
        properties.iter().find_map(|p| match p {
737
            CssProperty::MarginRight(m) => m.get_property().map(|m| m.inner),
738
            _ => None,
739
        })
740
    }
741

            
742
    fn margin_left(properties: &[CssProperty]) -> Option<PixelValue> {
743
        properties.iter().find_map(|p| match p {
744
            CssProperty::MarginLeft(m) => m.get_property().map(|m| m.inner),
745
            _ => None,
746
        })
747
    }
748

            
749
    fn width(properties: &[CssProperty]) -> Option<PixelValue> {
750
        properties.iter().find_map(|p| match p {
751
            CssProperty::Width(w) => match w.get_property() {
752
                Some(LayoutWidth::Px(pv)) => Some(*pv),
753
                _ => None,
754
            },
755
            _ => None,
756
        })
757
    }
758

            
759
    fn height(properties: &[CssProperty]) -> Option<PixelValue> {
760
        properties.iter().find_map(|p| match p {
761
            CssProperty::Height(h) => match h.get_property() {
762
                Some(LayoutHeight::Px(pv)) => Some(*pv),
763
                _ => None,
764
            },
765
            _ => None,
766
        })
767
    }
768

            
769
    fn border_top_left_radius(properties: &[CssProperty]) -> Option<PixelValue> {
770
        properties.iter().find_map(|p| match p {
771
            CssProperty::BorderTopLeftRadius(r) => r.get_property().map(|r| r.inner),
772
            _ => None,
773
        })
774
    }
775

            
776
    /// Asserts the length is an absolute `px` and returns its magnitude. An `em`
777
    /// or `%` slipping into this widget's geometry would resolve against the
778
    /// parent font/box, so a 16px indicator could render at any size at all.
779
    fn px(pv: PixelValue) -> f32 {
780
        assert_eq!(
781
            pv.metric,
782
            SizeMetric::Px,
783
            "radio-group geometry must be absolute px, got {:?}",
784
            pv.metric,
785
        );
786
        pv.number.get()
787
    }
788

            
789
    // ------------------------------------------------------------------
790
    // Dom probes
791
    // ------------------------------------------------------------------
792

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

            
805
    /// The properties of a rendered node's *inline* style, in declaration order.
806
    fn inline_props(node: &Dom) -> Vec<CssProperty> {
807
        node.root
808
            .style
809
            .iter_inline_properties()
810
            .map(|(p, _)| p.clone())
811
            .collect()
812
    }
813

            
814
    /// The text of a text node, looking through the `<p>` block wrapper the
815
    /// label convention mandates (`p > text`).
816
    fn text_of(node: &Dom) -> Option<&str> {
817
        match node.root.get_node_type() {
818
            NodeType::Text(s) => Some(s.as_ref().as_str()),
819
            NodeType::P => match node.children.as_ref() {
820
                [only] => match only.root.get_node_type() {
821
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
822
                    _ => None,
823
                },
824
                _ => None,
825
            },
826
            _ => None,
827
        }
828
    }
829

            
830
    fn row_of(dom: &Dom, i: usize) -> &Dom {
831
        &dom.children.as_ref()[i]
832
    }
833

            
834
    /// `row → circle (first child) → dot (first child)` — the path the click
835
    /// handler itself walks.
836
    fn dot_of(dom: &Dom, i: usize) -> &Dom {
837
        &row_of(dom, i).children.as_ref()[0].children.as_ref()[0]
838
    }
839

            
840
    fn label_of(dom: &Dom, i: usize) -> &Dom {
841
        &row_of(dom, i).children.as_ref()[1]
842
    }
843

            
844
    /// The `RefAny` row `i`'s click callback carries.
845
    fn row_state(dom: &Dom, i: usize) -> RefAny {
846
        row_of(dom, i)
847
            .root
848
            .get_callbacks()
849
            .as_ref()
850
            .first()
851
            .expect("every option row must carry the click callback")
852
            .refany
853
            .clone()
854
    }
855

            
856
    // ------------------------------------------------------------------
857
    // Callback harness
858
    // ------------------------------------------------------------------
859

            
860
    /// Flattened (pre-order) node id of option row `i`: the tree is
861
    /// `root, [row, circle, dot, label <p>, label text] * n` — the label is a
862
    /// `<p>` wrapping a bare text node, per the widget label convention.
863
    fn row_node(i: usize) -> DomNodeId {
864
        node(1 + 5 * i)
865
    }
866

            
867
    /// Flattened node id of option `i`'s indicator dot.
868
    fn dot_node(i: usize) -> NodeId {
869
        NodeId::new(3 + 5 * i)
870
    }
871

            
872
    fn node(idx: usize) -> DomNodeId {
873
        DomNodeId {
874
            dom: DomId::ROOT_ID,
875
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
876
        }
877
    }
878

            
879
    /// A `DomNodeId` whose node component is `None` — the "no concrete node was
880
    /// hit" case. `CallbackInfo::set_css_property` *panics* on such an id, so the
881
    /// handler must bail out long before reaching it.
882
    fn node_none() -> DomNodeId {
883
        DomNodeId {
884
            dom: DomId::ROOT_ID,
885
            node: NodeHierarchyItemId::NONE,
886
        }
887
    }
888

            
889
    /// A `DomLayoutResult` with an *empty* layout tree: `on_radio_row_click` only
890
    /// walks `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
891
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
892
        DomLayoutResult {
893
            styled_dom,
894
            layout_tree: LayoutTree {
895
                nodes: Vec::new(),
896
                warm: Vec::new(),
897
                cold: Vec::new(),
898
                root: 0,
899
                dom_to_layout: BTreeMap::new(),
900
                children_arena: Vec::new(),
901
                children_offsets: Vec::new(),
902
                subtree_needs_intrinsic: Vec::new(),
903
            },
904
            calculated_positions: Vec::new(),
905
            viewport: LogicalRect::zero(),
906
            display_list: Arc::new(DisplayList::default()),
907
            scroll_ids: HashMap::new(),
908
            scroll_id_to_node_id: HashMap::new(),
909
        }
910
    }
911

            
912
    /// Renders `rg`, then hands back both the flattened DOM *and* the very
913
    /// `RefAny` the widget registered on row 0's mouse-up callback. Driving the
914
    /// handler with these two is the real wiring — nothing is re-created by hand,
915
    /// so a mismatch between what `dom()` stores and what the handler expects
916
    /// cannot hide behind the fixture. Requires at least one option.
917
    fn flatten(rg: RadioGroup) -> (StyledDom, RefAny) {
918
        let dom = rg.dom();
919
        let state = row_state(&dom, 0);
920
        (StyledDom::create_from_dom(dom), state)
921
    }
922

            
923
    /// Invokes `on_radio_row_click` against a `LayoutWindow` holding `styled` (or
924
    /// nothing at all, when `styled` is `None`), with `hit` as the hit node.
925
    /// Returns the `Update` plus every recorded `CallbackChange`.
926
    fn run_click(
927
        styled: Option<StyledDom>,
928
        hit: DomNodeId,
929
        data: RefAny,
930
    ) -> (Update, Vec<CallbackChange>) {
931
        let mut layout_window =
932
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
933
        if let Some(sd) = styled {
934
            layout_window
935
                .layout_results
936
                .insert(DomId::ROOT_ID, layout_result(sd));
937
        }
938

            
939
        let renderer_resources = RendererResources::default();
940
        let previous_window_state: Option<FullWindowState> = None;
941
        let current_window_state = FullWindowState::default();
942
        let gl_context = OptionGlContextPtr::None;
943
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
944
            BTreeMap::new();
945
        let window_handle = RawWindowHandle::Unsupported;
946
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
947

            
948
        let ref_data = CallbackInfoRefData {
949
            layout_window: &layout_window,
950
            renderer_resources: &renderer_resources,
951
            previous_window_state: &previous_window_state,
952
            current_window_state: &current_window_state,
953
            gl_context: &gl_context,
954
            current_scroll_manager: &scroll_states,
955
            current_window_handle: &window_handle,
956
            system_callbacks: &system_callbacks,
957
            system_style: Arc::new(SystemStyle::default()),
958
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
959
            #[cfg(feature = "icu")]
960
            icu_localizer: IcuLocalizerHandle::default(),
961
            ctx: OptionRefAny::None,
962
        };
963

            
964
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
965

            
966
        let info = CallbackInfo::new(
967
            &ref_data,
968
            &changes,
969
            hit,
970
            OptionLogicalPosition::None,
971
            OptionLogicalPosition::None,
972
        );
973

            
974
        let update = on_radio_row_click(data, info);
975
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
976
        (update, recorded)
977
    }
978

            
979
    /// The opacity overrides pushed onto individual nodes, in push order.
980
    fn pushed_opacities(changes: &[CallbackChange]) -> Vec<(NodeId, f32)> {
981
        changes
982
            .iter()
983
            .filter_map(|c| match c {
984
                CallbackChange::ChangeNodeCssProperties {
985
                    node_id,
986
                    properties,
987
                    ..
988
                } => {
989
                    let o = properties.as_ref().iter().find_map(|p| match p {
990
                        CssProperty::Opacity(o) => o.get_property().map(|o| o.inner.normalized()),
991
                        _ => None,
992
                    })?;
993
                    Some((*node_id, o))
994
                }
995
                _ => None,
996
            })
997
            .collect()
998
    }
999

            
    /// What a correct restyle of an `n`-option group with option `selected` looks
    /// like: every dot touched exactly once, only the selected one opaque.
    fn expected_opacities(n: usize, selected: usize) -> Vec<(NodeId, f32)> {
        (0..n)
            .map(|i| (dot_node(i), if i == selected { 1.0 } else { 0.0 }))
            .collect()
    }
    fn selected_index_of(data: &mut RefAny) -> usize {
        data.downcast_ref::<RadioGroupStateWrapper>()
            .expect("payload must still be a RadioGroupStateWrapper")
            .inner
            .selected_index
    }
    /// A `RefAny` payload recording every index a user `on_change` sees.
    struct ChangeLog {
        seen: Vec<usize>,
    }
    extern "C" fn record_change(
        mut data: RefAny,
        _: CallbackInfo,
        state: RadioGroupState,
    ) -> Update {
        if let Some(mut log) = data.downcast_mut::<ChangeLog>() {
            log.seen.push(state.selected_index);
        }
        Update::RefreshDom
    }
    extern "C" fn change_do_nothing(_: RefAny, _: CallbackInfo, _: RadioGroupState) -> Update {
        Update::DoNothing
    }
    extern "C" fn change_refresh_all(_: RefAny, _: CallbackInfo, _: RadioGroupState) -> Update {
        Update::RefreshDomAllWindows
    }
    /// Forces the `fn`-item -> `fn`-pointer coercion the `Into` bound needs.
    fn change_cb(f: RadioGroupOnChangeCallbackType) -> RadioGroupOnChangeCallback {
        f.into()
    }
    fn log_refany() -> RefAny {
        RefAny::new(ChangeLog { seen: Vec::new() })
    }
    fn log_indices(data: &mut RefAny) -> Vec<usize> {
        data.downcast_ref::<ChangeLog>()
            .expect("payload must still be a ChangeLog")
            .seen
            .clone()
    }
    // ==================================================================
    // build_container_style
    // ==================================================================
    #[test]
    fn container_style_switches_only_the_flex_direction() {
        // Orientation is the *only* thing this function is allowed to vary; if it
        // also flipped, say, align-self, a horizontal group would stretch across
        // the parent while a vertical one hugs its content.
        let vertical = build_container_style(false);
        let horizontal = build_container_style(true);
        let v = props(vertical.as_ref());
        let h = props(horizontal.as_ref());
        assert_eq!(
            v.len(),
            h.len(),
            "the two orientations declare a different number of properties",
        );
        let differing: Vec<_> = v
            .iter()
            .zip(h.iter())
            .filter(|(a, b)| a != b)
            .map(|(a, _)| discriminant(a))
            .collect();
        assert_eq!(
            differing,
            vec![discriminant(&CssProperty::const_flex_direction(
                LayoutFlexDirection::Row
            ))],
            "the vertical/horizontal container styles differ in more than the flex direction",
        );
        assert_eq!(
            flex_direction(&v),
            Some(LayoutFlexDirection::Column),
            "a vertical radio group must stack its options",
        );
        assert_eq!(
            flex_direction(&h),
            Some(LayoutFlexDirection::Row),
            "a horizontal radio group must lay its options side by side",
        );
    }
    #[test]
    fn container_style_is_pure_unconditional_and_declares_nothing_twice() {
        for horizontal in [false, true] {
            let a = build_container_style(horizontal);
            let b = build_container_style(horizontal);
            assert_eq!(
                a.as_ref(),
                b.as_ref(),
                "build_container_style({horizontal}) is not a pure function",
            );
            no_duplicate_properties("the container style", a.as_ref());
            assert!(
                all_unconditional(a.as_ref()),
                "the container style must apply unconditionally",
            );
        }
    }
    #[test]
    fn container_style_is_a_non_growing_flex_box_in_both_orientations() {
        // `flex-grow: 0` + `align-self: start` is what keeps the group hugging its
        // options instead of being stretched by the parent flex line.
        for horizontal in [false, true] {
            let style = build_container_style(horizontal);
            assert!(
                has_property(
                    style.as_ref(),
                    &CssProperty::const_display(LayoutDisplay::Flex)
                ),
                "horizontal={horizontal}: the container is not a flex box",
            );
            assert!(
                has_property(
                    style.as_ref(),
                    &CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))
                ),
                "horizontal={horizontal}: the container would be stretched by its parent",
            );
            assert!(
                has_property(
                    style.as_ref(),
                    &CssProperty::align_self(LayoutAlignSelf::Start)
                ),
                "horizontal={horizontal}: the container lost its align-self:start",
            );
        }
    }
    // ==================================================================
    // build_row_style
    // ==================================================================
    #[test]
    fn row_style_puts_the_inter_row_gap_on_the_stacking_axis() {
        // Vertical groups stack downwards -> the gap belongs on the bottom;
        // horizontal groups run rightwards -> it belongs on the right. Putting it
        // on the wrong axis leaves the options touching along the axis they are
        // actually laid out on.
        let vertical = props(build_row_style(false).as_ref());
        assert_eq!(
            margin_bottom(&vertical).map(px),
            Some(ROW_GAP as f32),
            "a vertically stacked row must separate itself from the next one",
        );
        assert_eq!(
            margin_right(&vertical),
            None,
            "a vertically stacked row must not push its neighbours sideways",
        );
        let horizontal = props(build_row_style(true).as_ref());
        assert_eq!(
            margin_right(&horizontal).map(px),
            Some((ROW_GAP * 2) as f32),
            "a horizontal row must separate itself from the next one",
        );
        assert_eq!(
            margin_bottom(&horizontal),
            None,
            "a horizontal row must not add vertical spacing",
        );
    }
    #[test]
    fn row_style_is_always_an_inner_row_regardless_of_the_group_orientation() {
        // The *group* orientation must not leak into the row: a row is always
        // `circle | label` left-to-right, even inside a column group. A naive
        // "pass horizontal through" would render the label under the indicator.
        for horizontal in [false, true] {
            let style = props(build_row_style(horizontal).as_ref());
            assert_eq!(
                flex_direction(&style),
                Some(LayoutFlexDirection::Row),
                "horizontal={horizontal}: the indicator/label pair is not laid out in a row",
            );
            assert!(
                has_property(
                    build_row_style(horizontal).as_ref(),
                    &CssProperty::const_align_items(LayoutAlignItems::Center)
                ),
                "horizontal={horizontal}: the label is not vertically centred on the indicator",
            );
        }
    }
    #[test]
    fn row_style_marks_the_whole_row_as_a_click_target() {
        // The row is what carries the mouse-up handler, so it must *look*
        // clickable and must not start a text selection when dragged.
        for horizontal in [false, true] {
            let style = props(build_row_style(horizontal).as_ref());
            assert_eq!(
                cursor(&style),
                Some(StyleCursor::Pointer),
                "horizontal={horizontal}: the row does not look clickable",
            );
            assert_eq!(
                user_select(&style),
                Some(StyleUserSelect::None),
                "horizontal={horizontal}: dragging a row would select its label text",
            );
        }
    }
    #[test]
    fn row_style_is_pure_unconditional_and_declares_nothing_twice() {
        for horizontal in [false, true] {
            let a = build_row_style(horizontal);
            let b = build_row_style(horizontal);
            assert_eq!(
                a.as_ref(),
                b.as_ref(),
                "build_row_style({horizontal}) is not a pure function",
            );
            no_duplicate_properties("the row style", a.as_ref());
            assert!(
                all_unconditional(a.as_ref()),
                "the row style must apply unconditionally",
            );
        }
    }
    // ==================================================================
    // The const style tables
    // ==================================================================
    #[test]
    fn the_const_style_tables_declare_nothing_twice_and_apply_unconditionally() {
        for (name, style) in [
            ("the circle style", RADIO_GROUP_CIRCLE_STYLE),
            ("the selected dot style", RADIO_GROUP_DOT_STYLE_SELECTED),
            ("the unselected dot style", RADIO_GROUP_DOT_STYLE_UNSELECTED),
            ("the label style", RADIO_GROUP_LABEL_STYLE),
        ] {
            no_duplicate_properties(name, style);
            assert!(
                all_unconditional(style),
                "{name} must apply unconditionally"
            );
        }
    }
    #[test]
    fn the_two_dot_styles_differ_in_opacity_and_nothing_else() {
        // Opacity is the *only* thing that may distinguish a selected option from
        // an unselected one: a size or colour difference would reflow (or recolour)
        // the row as the selection moves.
        let selected = props(RADIO_GROUP_DOT_STYLE_SELECTED);
        let unselected = props(RADIO_GROUP_DOT_STYLE_UNSELECTED);
        assert_eq!(
            selected.len(),
            unselected.len(),
            "the two dot styles declare a different number of properties",
        );
        let differing: Vec<_> = selected
            .iter()
            .zip(unselected.iter())
            .filter(|(a, b)| a != b)
            .map(|(a, _)| discriminant(a))
            .collect();
        assert_eq!(
            differing,
            vec![discriminant(&CssProperty::const_opacity(
                StyleOpacity::const_new(0)
            ))],
            "the selected/unselected dot styles differ in something other than opacity",
        );
        assert_eq!(
            opacity_of(&selected),
            Some(1.0),
            "the selected dot is not fully opaque (const_new takes a *percentage*)",
        );
        assert_eq!(
            opacity_of(&unselected),
            Some(0.0),
            "the unselected dot is still visible",
        );
    }
    #[test]
    fn the_indicator_geometry_is_absolute_px_and_actually_circular() {
        // `border-radius = size / 2` on all four corners is what makes the ring and
        // the dot circles rather than rounded squares; and the dot plus the ring's
        // two borders must fit inside the ring.
        assert_eq!(CIRCLE_RADIUS * 2, CIRCLE_SIZE, "the ring is not a circle");
        assert_eq!(DOT_RADIUS * 2, DOT_SIZE, "the dot is not a circle");
        assert!(
            DOT_SIZE + 2 * CIRCLE_BORDER <= CIRCLE_SIZE,
            "the dot ({DOT_SIZE}px) does not fit inside the ring ({CIRCLE_SIZE}px + \
             {CIRCLE_BORDER}px borders)",
        );
        let circle = props(RADIO_GROUP_CIRCLE_STYLE);
        assert_eq!(width(&circle).map(px), Some(CIRCLE_SIZE as f32));
        assert_eq!(height(&circle).map(px), Some(CIRCLE_SIZE as f32));
        assert_eq!(
            border_top_left_radius(&circle).map(px),
            Some(CIRCLE_RADIUS as f32),
        );
        for style in [
            RADIO_GROUP_DOT_STYLE_SELECTED,
            RADIO_GROUP_DOT_STYLE_UNSELECTED,
        ] {
            let dot = props(style);
            assert_eq!(width(&dot).map(px), Some(DOT_SIZE as f32));
            assert_eq!(height(&dot).map(px), Some(DOT_SIZE as f32));
            assert_eq!(
                border_top_left_radius(&dot).map(px),
                Some(DOT_RADIUS as f32),
            );
        }
        assert_eq!(
            margin_left(&props(RADIO_GROUP_LABEL_STYLE)).map(px),
            Some(LABEL_GAP as f32),
            "the label lost its gap from the indicator",
        );
    }
    // ==================================================================
    // RadioGroup::create
    // ==================================================================
    #[test]
    fn create_preserves_the_options_verbatim_and_defaults_the_state() {
        for case in [
            vec![],
            vec!["only"],
            vec!["a", "b"],
            vec!["dup", "dup", "dup"],
            vec!["Yes", "No", "Maybe", "Ask again later"],
        ] {
            let rg = group(&case);
            let got: Vec<&str> = rg.options.as_ref().iter().map(AzString::as_str).collect();
            assert_eq!(got, case, "create must not reorder/drop/rewrite options");
            assert_eq!(
                rg.radio_group_state.inner.selected_index, 0,
                "a fresh radio group selects its first option",
            );
            assert!(
                !rg.radio_group_state.horizontal,
                "a fresh radio group is vertical",
            );
            assert!(
                rg.radio_group_state.on_change.as_ref().is_none(),
                "create must not invent a callback",
            );
            assert_eq!(
                rg.resolved_container_style().as_ref(),
                build_container_style(false).as_ref(),
                "create must build the *vertical* container style",
            );
        }
    }
    #[test]
    fn create_survives_pathological_labels() {
        // empty string, whitespace-only, emoji + ZWJ, RTL, stacked combining marks,
        // an embedded NUL, invisible formatting chars, and a 100k-char label.
        let huge = "x".repeat(100_000);
        let case = vec![
            "",
            "   ",
            "a\u{0}b",
            "👨‍👩‍👧‍👦",
            "مرحبا",
            "e\u{0301}\u{0301}\u{0301}",
            "\u{200b}\u{feff}",
            huge.as_str(),
        ];
        let rg = group(&case);
        let got: Vec<&str> = rg.options.as_ref().iter().map(AzString::as_str).collect();
        assert_eq!(got, case, "options must survive byte-for-byte");
        assert_eq!(rg.options.as_ref()[7].as_str().len(), 100_000);
        // … and they must survive the trip through the DOM unchanged.
        let dom = rg.dom();
        let texts: Vec<&str> = (0..case.len())
            .filter_map(|i| text_of(label_of(&dom, i)))
            .collect();
        assert_eq!(texts, case, "a label was mangled on its way into the DOM");
    }
    #[test]
    fn create_with_a_huge_option_list_does_not_panic() {
        let n = 10_000;
        let rg = RadioGroup::create(n_labels(n));
        assert_eq!(rg.options.as_ref().len(), n);
        assert_eq!(rg.options.as_ref()[n - 1].as_str(), "o9999");
    }
    #[test]
    fn default_equals_create_with_no_options() {
        assert_eq!(
            RadioGroup::default(),
            RadioGroup::create(StringVec::from_const_slice(&[])),
        );
    }
    // ==================================================================
    // set_selected_index / with_selected_index
    // ==================================================================
    #[test]
    fn selected_index_is_stored_verbatim_at_every_boundary() {
        // The setter is documented as a plain store — no clamping to the option
        // count — so the extremes must round-trip exactly rather than saturate,
        // wrap, or panic in a debug build.
        for idx in [0, 1, 2, 3, 1_000, usize::MAX - 1, usize::MAX] {
            let mut rg = group(&["a", "b", "c"]);
            rg.set_selected_index(idx);
            assert_eq!(
                rg.radio_group_state.inner.selected_index, idx,
                "set_selected_index({idx}) did not store what it was given",
            );
            let built = group(&["a", "b", "c"]).with_selected_index(idx);
            assert_eq!(
                built, rg,
                "with_selected_index({idx}) disagrees with the mutating setter",
            );
        }
    }
    #[test]
    fn setting_the_index_repeatedly_keeps_only_the_last_value() {
        let mut rg = group(&["a", "b"]);
        for idx in [1, 0, usize::MAX, 1, 0] {
            rg.set_selected_index(idx);
        }
        assert_eq!(rg.radio_group_state.inner.selected_index, 0);
    }
    #[test]
    fn with_selected_index_touches_nothing_but_the_index() {
        let before = group(&["a", "b", "c"]).with_horizontal(true);
        let after = before.clone().with_selected_index(2);
        assert_eq!(after.options.as_ref(), before.options.as_ref());
        assert_eq!(
            after.resolved_container_style().as_ref(),
            before.resolved_container_style().as_ref()
        );
        assert_eq!(
            after.radio_group_state.horizontal, before.radio_group_state.horizontal,
            "changing the selection must not change the layout direction",
        );
        assert_eq!(after.radio_group_state.inner.selected_index, 2);
    }
    #[test]
    fn an_out_of_range_selection_renders_every_dot_hidden() {
        // Nothing clamps `selected_index`, so `dom()` has to cope with an index no
        // option owns: it must render the full option list with *no* dot lit
        // rather than panicking or highlighting a wrapped-around row.
        for idx in [3, 4, 1_000, usize::MAX - 1, usize::MAX] {
            let dom = group(&["a", "b", "c"]).with_selected_index(idx).dom();
            assert_eq!(
                dom.children.as_ref().len(),
                3,
                "idx={idx}: an out-of-range selection changed the option count",
            );
            for i in 0..3 {
                assert_eq!(
                    opacity_of(&inline_props(dot_of(&dom, i))),
                    Some(0.0),
                    "idx={idx}: option {i} is lit even though nothing is selected",
                );
            }
        }
    }
    #[test]
    fn selecting_an_option_lights_exactly_that_one() {
        for selected in 0..4 {
            let dom = group(&["a", "b", "c", "d"])
                .with_selected_index(selected)
                .dom();
            let lit: Vec<usize> = (0..4)
                .filter(|i| opacity_of(&inline_props(dot_of(&dom, *i))) == Some(1.0))
                .collect();
            assert_eq!(
                lit,
                vec![selected],
                "selecting option {selected} lit {lit:?} instead",
            );
        }
    }
    // ==================================================================
    // set_horizontal / with_horizontal
    // ==================================================================
    #[test]
    fn the_horizontal_flag_and_the_container_style_never_disagree() {
        // There used to be two sources of truth for one fact: the flag drove the
        // rendered rows, a stored vec drove the container, and a setter that
        // updated only one of them left a group stacking vertically while spacing
        // itself horizontally. The flag is the only source now — the container
        // style is resolved from it — so this asks the resolver.
        for horizontal in [false, true] {
            let mut rg = group(&["a", "b"]);
            rg.set_horizontal(horizontal);
            assert_eq!(rg.radio_group_state.horizontal, horizontal);
            assert_eq!(
                rg.resolved_container_style().as_ref(),
                build_container_style(horizontal).as_ref(),
                "horizontal={horizontal}: the resolved style ignores the flag",
            );
            assert_eq!(
                group(&["a", "b"]).with_horizontal(horizontal),
                rg,
                "with_horizontal({horizontal}) disagrees with the mutating setter",
            );
        }
    }
    #[test]
    fn an_explicit_container_style_outranks_the_horizontal_flag() {
        // `Some` is the caller's answer, so it is honoured rather than recomputed
        // from the flag — the distinction a pre-filled field could not express.
        let marker = CssPropertyWithConditionsVec::from_vec(Vec::new());
        let mut rg = group(&["a", "b"]);
        rg.container_style = OptionCssPropertyWithConditionsVec::Some(marker);
        rg.set_horizontal(true);
        assert!(
            rg.resolved_container_style().as_ref().is_empty(),
            "an explicit empty style must survive set_horizontal",
        );
    }
    #[test]
    fn toggling_the_orientation_never_accumulates_properties() {
        // The style used to be stored and rebuilt on every flip, where an
        // append-instead-of-rebuild bug left a four-hundred-property vec whose
        // later duplicates silently overrode the earlier ones. It is resolved
        // now, so the invariant is the resolver's: constant length, and it
        // tracks the flag rather than the call count.
        let mut rg = group(&["a", "b"]);
        let original = rg.clone();
        let len = rg.resolved_container_style().as_ref().len();
        for i in 0..100 {
            let horizontal = i % 2 == 0;
            rg.set_horizontal(horizontal);
            assert_eq!(
                rg.resolved_container_style().as_ref().len(),
                len,
                "toggle #{i}: the resolved style grew",
            );
            assert_eq!(
                rg.resolved_container_style().as_ref(),
                build_container_style(horizontal).as_ref(),
                "toggle #{i}: the resolved style stopped tracking the flag",
            );
        }
        rg.set_horizontal(false);
        assert_eq!(
            rg, original,
            "an even number of toggles did not return the group to its original state",
        );
    }
    #[test]
    fn the_orientation_reaches_the_rendered_container() {
        for (horizontal, expected) in [
            (false, LayoutFlexDirection::Column),
            (true, LayoutFlexDirection::Row),
        ] {
            let dom = group(&["a", "b"]).with_horizontal(horizontal).dom();
            assert_eq!(
                flex_direction(&inline_props(&dom)),
                Some(expected),
                "horizontal={horizontal}: the rendered container flows the wrong way",
            );
        }
    }
    #[test]
    fn the_orientation_reaches_the_rendered_rows() {
        // `dom()` reads the *flag*, not the container style, to build the row gap —
        // so the flag has to be what `set_horizontal` stored.
        for horizontal in [false, true] {
            let dom = group(&["a", "b"]).with_horizontal(horizontal).dom();
            let row = inline_props(row_of(&dom, 0));
            assert_eq!(
                margin_bottom(&row),
                margin_bottom(&props(build_row_style(horizontal).as_ref())),
            );
            assert_eq!(
                margin_right(&row),
                margin_right(&props(build_row_style(horizontal).as_ref())),
            );
        }
    }
    // ==================================================================
    // swap_with_default
    // ==================================================================
    #[test]
    fn swap_with_default_hands_back_the_old_value_and_leaves_a_default_behind() {
        let mut rg = group(&["a", "b", "c"])
            .with_selected_index(2)
            .with_horizontal(true);
        let original = rg.clone();
        let taken = rg.swap_with_default();
        assert_eq!(taken, original, "the caller did not get the old value back");
        assert_eq!(
            rg,
            RadioGroup::default(),
            "the widget was not reset to its default",
        );
        assert!(rg.options.as_ref().is_empty());
        assert_eq!(rg.radio_group_state.inner.selected_index, 0);
        assert!(!rg.radio_group_state.horizontal);
    }
    #[test]
    fn swapping_twice_restores_the_original() {
        let mut rg = group(&["a", "b"]).with_selected_index(1);
        let original = rg.clone();
        let mut taken = rg.swap_with_default();
        let back = taken.swap_with_default();
        assert_eq!(back, original, "swap is not its own inverse");
        assert_eq!(taken, RadioGroup::default());
    }
    #[test]
    fn swapping_a_default_group_is_a_no_op() {
        let mut rg = RadioGroup::default();
        let taken = rg.swap_with_default();
        assert_eq!(taken, RadioGroup::default());
        assert_eq!(rg, RadioGroup::default());
    }
    #[test]
    fn swap_with_default_drops_the_installed_callback_from_the_widget() {
        // The callback belongs to the value that was taken, not to the husk left
        // behind — otherwise the "default" group would still fire the old handler.
        let mut rg = group(&["a"]).with_on_change(RefAny::new(0u8), change_cb(change_do_nothing));
        let taken = rg.swap_with_default();
        assert!(taken.radio_group_state.on_change.as_ref().is_some());
        assert!(
            rg.radio_group_state.on_change.as_ref().is_none(),
            "the emptied widget kept the old on_change callback",
        );
    }
    // ==================================================================
    // set_on_change / with_on_change
    // ==================================================================
    #[test]
    fn with_on_change_installs_the_callback_and_keeps_the_rest_of_the_state() {
        let before = group(&["a", "b", "c"])
            .with_selected_index(2)
            .with_horizontal(true);
        // One shared payload: `RefAny` equality is instance identity, so the
        // builder/setter comparison below only means something with the same one.
        let payload = RefAny::new(7u32);
        let after = before
            .clone()
            .with_on_change(payload.clone(), change_cb(record_change));
        assert!(after.radio_group_state.on_change.as_ref().is_some());
        assert_eq!(after.options.as_ref(), before.options.as_ref());
        assert_eq!(
            after.resolved_container_style().as_ref(),
            before.resolved_container_style().as_ref()
        );
        assert_eq!(
            after.radio_group_state.inner,
            before.radio_group_state.inner
        );
        assert_eq!(
            after.radio_group_state.horizontal,
            before.radio_group_state.horizontal,
        );
        // … and it matches the mutating setter.
        let mut mutated = before;
        mutated.set_on_change(payload, change_cb(record_change));
        assert_eq!(mutated, after);
    }
    #[test]
    fn setting_on_change_twice_replaces_it_rather_than_stacking() {
        let mut rg = group(&["a"]);
        rg.set_on_change(RefAny::new(1u8), change_cb(record_change));
        rg.set_on_change(RefAny::new(2u8), change_cb(change_refresh_all));
        let installed = rg
            .radio_group_state
            .on_change
            .as_ref()
            .expect("a callback must still be installed");
        assert_eq!(
            installed.callback,
            change_cb(change_refresh_all),
            "the first callback survived the second install",
        );
        let mut payload = installed.refany.clone();
        assert_eq!(
            *payload
                .downcast_ref::<u8>()
                .expect("the payload changed type"),
            2,
            "the first payload survived the second install",
        );
    }
    #[test]
    fn installing_a_callback_never_invokes_it() {
        // Building a widget is not a user interaction: nothing may fire until a
        // click actually happens.
        let mut probe = log_refany();
        let rg = group(&["a", "b"]).with_on_change(probe.clone(), change_cb(record_change));
        let dom = rg.dom();
        let _ = StyledDom::create_from_dom(dom);
        assert!(
            log_indices(&mut probe).is_empty(),
            "the on_change callback fired during construction",
        );
    }
    // ==================================================================
    // RadioGroup::dom
    // ==================================================================
    #[test]
    fn dom_renders_one_row_per_option_with_the_documented_structure() {
        let dom = group(&["a", "b", "c"]).dom();
        assert_eq!(classes(&dom), vec!["__azul-native-radio-group"]);
        assert_eq!(dom.children.as_ref().len(), 3, "one row per option");
        for i in 0..3 {
            let row = row_of(&dom, i);
            assert_eq!(classes(row), vec!["__azul-native-radio-group-row"]);
            assert_eq!(
                row.children.as_ref().len(),
                2,
                "row {i} must be `circle, label`",
            );
            assert_eq!(
                row.root.get_tab_index(),
                Some(TabIndex::Auto),
                "row {i} is not keyboard reachable",
            );
            let circle = &row.children.as_ref()[0];
            assert_eq!(classes(circle), vec!["__azul-native-radio-group-circle"]);
            assert_eq!(
                circle.children.as_ref().len(),
                1,
                "the circle holds the dot"
            );
            assert_eq!(
                classes(dot_of(&dom, i)),
                vec!["__azul-native-radio-group-dot"],
            );
            assert_eq!(
                classes(label_of(&dom, i)),
                vec!["__azul-native-radio-group-label"],
            );
            assert_eq!(text_of(label_of(&dom, i)), Some(["a", "b", "c"][i]));
        }
    }
    #[test]
    fn every_row_carries_exactly_one_mouse_up_handler_pointing_at_the_row_handler() {
        let dom = group(&["a", "b", "c"]).dom();
        for i in 0..3 {
            let cbs = row_of(&dom, i).root.get_callbacks();
            assert_eq!(cbs.as_ref().len(), 1, "row {i} must have one callback");
            let cb = &cbs.as_ref()[0];
            assert_eq!(
                cb.event,
                EventFilter::Hover(HoverEventFilter::Click),
                "row {i} listens for the wrong event",
            );
            assert_eq!(
                cb.callback.cb, on_radio_row_click as usize,
                "row {i} is wired to the wrong handler",
            );
        }
        // The inner nodes must stay inert: a handler on the dot or the label would
        // resolve its index against the *wrong* sibling set.
        for i in 0..3 {
            assert!(row_of(&dom, i).children.as_ref()[0]
                .root
                .get_callbacks()
                .as_ref()
                .is_empty());
            assert!(dot_of(&dom, i).root.get_callbacks().as_ref().is_empty());
            assert!(label_of(&dom, i).root.get_callbacks().as_ref().is_empty());
        }
    }
    #[test]
    fn all_rows_share_one_state_refany() {
        // Mutual exclusion depends on it: if each row owned its own copy of the
        // state, clicking row 2 would leave row 0 still believing it is selected.
        let dom = group(&["a", "b", "c", "d"]).dom();
        let first = row_state(&dom, 0);
        for i in 1..4 {
            assert_eq!(
                row_state(&dom, i).get_data_ptr(),
                first.get_data_ptr(),
                "row {i} carries its own state instead of the shared one",
            );
        }
    }
    #[test]
    fn dom_of_an_empty_group_is_an_empty_container() {
        let dom = RadioGroup::default().dom();
        assert!(
            dom.children.as_ref().is_empty(),
            "a group with no options invented a row",
        );
        assert!(dom.root.get_callbacks().as_ref().is_empty());
        assert_eq!(classes(&dom), vec!["__azul-native-radio-group"]);
    }
    #[test]
    fn dom_of_an_empty_group_with_a_selection_does_not_panic() {
        // `create` sets index 0 even with zero options, so the "selected option" is
        // out of range from the start — the render path must not index into it.
        for idx in [0, 1, usize::MAX] {
            let dom = RadioGroup::default().with_selected_index(idx).dom();
            assert!(dom.children.as_ref().is_empty());
        }
    }
    #[test]
    fn dom_flattens_to_five_nodes_per_option() {
        // root + (row, circle, dot, label <p>, label text) per option. The click
        // handler's live restyle walks exactly this shape, and the callback tests
        // below address nodes by this formula.
        for n in [0, 1, 2, 7] {
            let styled = StyledDom::create_from_dom(RadioGroup::create(n_labels(n)).dom());
            assert_eq!(
                styled.node_hierarchy.as_ref().len(),
                1 + 5 * n,
                "an {n}-option group flattened to an unexpected node count",
            );
        }
    }
    #[test]
    fn a_large_group_renders_without_panicking() {
        let n = 500;
        let dom = RadioGroup::create(n_labels(n))
            .with_selected_index(n - 1)
            .dom();
        assert_eq!(dom.children.as_ref().len(), n);
        assert_eq!(text_of(label_of(&dom, n - 1)), Some("o499"));
        assert_eq!(opacity_of(&inline_props(dot_of(&dom, n - 1))), Some(1.0));
        assert_eq!(opacity_of(&inline_props(dot_of(&dom, 0))), Some(0.0));
    }
    // ==================================================================
    // on_radio_row_click
    // ==================================================================
    #[test]
    fn clicking_a_row_selects_it_and_restyles_every_dot() {
        for clicked in 0..4 {
            let (styled, state) = flatten(group(&["a", "b", "c", "d"]));
            let mut state_probe = state.clone();
            let (update, changes) = run_click(Some(styled), row_node(clicked), state);
            assert_eq!(
                update,
                Update::DoNothing,
                "with no on_change installed the handler reports nothing to redraw",
            );
            assert_eq!(
                selected_index_of(&mut state_probe),
                clicked,
                "clicking row {clicked} selected the wrong option",
            );
            assert_eq!(
                pushed_opacities(&changes),
                expected_opacities(4, clicked),
                "clicking row {clicked} did not light exactly that row's dot",
            );
        }
    }
    #[test]
    fn clicking_the_already_selected_row_is_idempotent() {
        let (styled, state) = flatten(group(&["a", "b", "c"]).with_selected_index(1));
        let mut probe = state.clone();
        let (_, changes) = run_click(Some(styled), row_node(1), state);
        assert_eq!(selected_index_of(&mut probe), 1);
        assert_eq!(
            pushed_opacities(&changes),
            expected_opacities(3, 1),
            "a redundant click must still leave every dot in a consistent state",
        );
    }
    #[test]
    fn clicking_repairs_an_out_of_range_selection() {
        // The widget can be handed an index no option owns; the first click must
        // bring it back into range instead of leaving a group with nothing lit.
        let (styled, state) = flatten(group(&["a", "b", "c"]).with_selected_index(usize::MAX));
        let mut probe = state.clone();
        let (_, changes) = run_click(Some(styled), row_node(2), state);
        assert_eq!(selected_index_of(&mut probe), 2);
        assert_eq!(pushed_opacities(&changes), expected_opacities(3, 2));
    }
    #[test]
    fn clicking_a_single_option_group_selects_option_zero() {
        let (styled, state) = flatten(group(&["only"]));
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), row_node(0), state);
        assert_eq!(update, Update::DoNothing);
        assert_eq!(selected_index_of(&mut probe), 0);
        assert_eq!(pushed_opacities(&changes), vec![(dot_node(0), 1.0)]);
    }
    #[test]
    fn the_reported_index_always_addresses_a_real_option() {
        let n = 32;
        for clicked in [0, 1, n / 2, n - 2, n - 1] {
            let (styled, state) = flatten(RadioGroup::create(n_labels(n)));
            let mut probe = state.clone();
            let (_, changes) = run_click(Some(styled), row_node(clicked), state);
            let idx = selected_index_of(&mut probe);
            assert!(idx < n, "row {clicked} reported out-of-range index {idx}");
            assert_eq!(idx, clicked);
            let pushed = pushed_opacities(&changes);
            assert_eq!(pushed.len(), n, "every dot must be restyled exactly once");
            assert_eq!(
                pushed.iter().filter(|(_, o)| *o == 1.0).count(),
                1,
                "exactly one option may be lit at a time",
            );
        }
    }
    #[test]
    fn the_user_callback_sees_the_new_index_and_its_update_is_forwarded() {
        // Order matters: the selection is written *before* the user callback runs,
        // so the callback observes the state the user just asked for.
        let mut probe = log_refany();
        let rg = group(&["a", "b", "c"]).with_on_change(probe.clone(), change_cb(record_change));
        let (styled, state) = flatten(rg);
        let (update, changes) = run_click(Some(styled), row_node(2), state.clone());
        assert_eq!(
            log_indices(&mut probe),
            vec![2],
            "the callback ran once with the new index"
        );
        assert_eq!(
            update,
            Update::RefreshDom,
            "the user's Update was swallowed"
        );
        // … and the restyle still happens *after* the user callback returns.
        assert_eq!(pushed_opacities(&changes), expected_opacities(3, 2));
        // A second click updates the shared state again — the index is not sticky,
        // and the user hears about every click, not just the first.
        let (styled2, _) = flatten(group(&["a", "b", "c"]));
        let (_, _) = run_click(Some(styled2), row_node(0), state.clone());
        assert_eq!(log_indices(&mut probe), vec![2, 0]);
        let mut state = state;
        assert_eq!(
            selected_index_of(&mut state),
            0,
            "the state must hold the *last* clicked index",
        );
    }
    #[test]
    fn a_callback_that_declines_the_update_still_gets_the_dots_restyled() {
        // A user callback returning DoNothing must not suppress the widget's own
        // visual bookkeeping — otherwise the state says "option 1" while option 0
        // stays lit.
        let rg = group(&["a", "b"]).with_on_change(RefAny::new(0u8), change_cb(change_do_nothing));
        let (styled, state) = flatten(rg);
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), row_node(1), state);
        assert_eq!(update, Update::DoNothing);
        assert_eq!(selected_index_of(&mut probe), 1);
        assert_eq!(
            pushed_opacities(&changes),
            expected_opacities(2, 1),
            "a DoNothing user callback suppressed the dot restyle",
        );
    }
    #[test]
    fn every_update_variant_is_propagated_unchanged() {
        for (cb, expected) in [
            (change_cb(change_do_nothing), Update::DoNothing),
            (change_cb(change_refresh_all), Update::RefreshDomAllWindows),
            (change_cb(record_change), Update::RefreshDom),
        ] {
            let rg = group(&["a", "b"]).with_on_change(log_refany(), cb);
            let (styled, state) = flatten(rg);
            let (update, _) = run_click(Some(styled), row_node(1), state);
            assert_eq!(update, expected);
        }
    }
    #[test]
    fn clicking_the_root_container_does_nothing() {
        // The root has no parent -> the handler must bail before indexing into
        // nothing.
        let (styled, state) = flatten(group(&["a", "b"]));
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), node(0), state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty(), "a parentless hit pushed a DOM change");
        assert_eq!(
            selected_index_of(&mut probe),
            0,
            "the state must be untouched"
        );
    }
    #[test]
    fn clicking_a_stale_or_absent_node_does_nothing() {
        // Stale hit ids reach callbacks after a DOM mutation, and
        // `set_css_property` *panics* on a None node id — so the handler has to
        // bail out well before the restyle loop.
        for hit in [node(9999), node(usize::MAX - 1), node_none()] {
            let (styled, state) = flatten(group(&["a", "b"]).with_selected_index(1));
            let mut probe = state.clone();
            let (update, changes) = run_click(Some(styled), hit, state);
            assert_eq!(
                update,
                Update::DoNothing,
                "{hit:?}: a stale hit was acted on"
            );
            assert!(
                changes.is_empty(),
                "{hit:?}: a stale hit pushed a DOM change"
            );
            assert_eq!(
                selected_index_of(&mut probe),
                1,
                "{hit:?}: a stale hit moved the selection",
            );
        }
    }
    #[test]
    fn clicking_with_no_layout_result_does_nothing() {
        let dom = group(&["a", "b"]).dom();
        let state = row_state(&dom, 0);
        let (update, changes) = run_click(None, row_node(0), state);
        assert_eq!(
            update,
            Update::DoNothing,
            "an empty LayoutWindow must be handled, not unwrapped",
        );
        assert!(changes.is_empty());
    }
    #[test]
    fn clicking_with_a_foreign_payload_does_nothing_and_leaves_it_intact() {
        // The handler downcasts blind; a foreign RefAny must bail out, not
        // reinterpret the bytes as a RadioGroupStateWrapper.
        let (styled, _) = flatten(group(&["a", "b"]));
        let foreign = RefAny::new(0xDEAD_BEEF_u32);
        let (update, changes) = run_click(Some(styled), row_node(1), foreign.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "the handler restyled the DOM through a RefAny it could not read",
        );
        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_while_the_state_is_already_borrowed_does_nothing() {
        let (styled, state) = flatten(group(&["a", "b"]));
        // A live mutable borrow on a sibling clone: `downcast_mut` inside the
        // handler must fail (returning DoNothing) instead of aliasing `&mut`.
        let mut held = state.clone();
        let guard = held
            .downcast_mut::<RadioGroupStateWrapper>()
            .expect("first borrow succeeds");
        let (update, changes) = run_click(Some(styled), row_node(1), state);
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "the handler restyled the DOM after failing to update the state",
        );
        drop(guard);
    }
    #[test]
    fn a_hit_inside_a_row_resolves_against_its_own_siblings() {
        // The handler documents `currentTarget` semantics: the hit node is the row
        // the callback is registered on, and only rows carry callbacks. Should an
        // inner node ever reach it anyway, it must stay memory-safe and push no
        // half-finished restyle — the sibling walk simply finds no dots to update.
        // (`dot` is its circle's only child -> position 0; the label `<p>` is its
        // row's second child -> position 1, regardless of which row it belongs to.)
        for (hit, expected) in [
            (node(3), 0usize),
            (node(13), 0),
            (node(4), 1),
            (node(14), 1),
        ] {
            let (styled, state) = flatten(group(&["a", "b", "c"]));
            let mut probe = state.clone();
            let (update, changes) = run_click(Some(styled), hit, state);
            assert_eq!(update, Update::DoNothing);
            assert_eq!(selected_index_of(&mut probe), expected, "{hit:?}");
            assert!(
                changes.is_empty(),
                "{hit:?}: an inner-node hit pushed a partial restyle",
            );
        }
    }
    #[test]
    fn many_clicks_keep_the_state_and_the_pushed_opacities_in_agreement() {
        // A drift between the stored index and the pushed opacity is exactly the
        // class of bug that makes a radio group render a selection it does not
        // hold. 60 clicks cycling through a 5-option group.
        let (_, state) = flatten(group(&["a", "b", "c", "d", "e"]));
        for click in 0..60usize {
            let expected = click % 5;
            let (styled, _) = flatten(group(&["a", "b", "c", "d", "e"]));
            let (_, changes) = run_click(Some(styled), row_node(expected), state.clone());
            let mut probe = state.clone();
            assert_eq!(
                selected_index_of(&mut probe),
                expected,
                "click #{click}: the stored index drifted",
            );
            assert_eq!(
                pushed_opacities(&changes),
                expected_opacities(5, expected),
                "click #{click}: the pushed opacities disagree with the stored index",
            );
        }
    }
}