1
//! Segmented control / button-group widget — a joined row of mutually-exclusive
2
//! buttons where exactly one is selected. A blend of the `tabs::TabHeader` row of
3
//! clickable labels and `button.rs`'s styling, with the stateful 3-type split
4
//! (state / state-wrapper / widget) of the other interactive widgets.
5
//!
6
//! Clicking a segment selects it: the internal handler computes the clicked
7
//! segment's index from its position among its siblings, updates the
8
//! `selected_index`, invokes the user's `on_change(index)`, and live-restyles
9
//! every segment (selected vs unselected) via `set_css_property`.
10
//!
11
//! Key types: [`Segmented`], [`SegmentedState`], [`SegmentedOnChange`].
12

            
13
use std::vec::Vec;
14

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

            
46
use crate::callbacks::{Callback, CallbackInfo};
47

            
48
static SEGMENTED_CLASS: &[IdOrClass] =
49
    &[Class(AzString::from_const_str("__azul-native-segmented"))];
50
static SEGMENT_ITEM_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
51
    "__azul-native-segmented-item",
52
))];
53

            
54
/// Callback function type invoked when the selected segment changes.
55
pub type SegmentedOnChangeCallbackType =
56
    extern "C" fn(RefAny, CallbackInfo, SegmentedState) -> Update;
57
impl_widget_callback!(
58
    SegmentedOnChange,
59
    OptionSegmentedOnChange,
60
    SegmentedOnChangeCallback,
61
    SegmentedOnChangeCallbackType
62
);
63

            
64
azul_core::impl_managed_callback! {
65
    wrapper:        SegmentedOnChangeCallback,
66
    info_ty:        CallbackInfo,
67
    return_ty:      Update,
68
    default_ret:    Update::DoNothing,
69
    invoker_static: SEGMENTED_ON_CHANGE_INVOKER,
70
    invoker_ty:     AzSegmentedOnChangeCallbackInvoker,
71
    thunk_fn:       az_segmented_on_change_callback_thunk,
72
    setter_fn:      AzApp_setSegmentedOnChangeCallbackInvoker,
73
    from_handle_fn: AzSegmentedOnChangeCallback_createFromHostHandle,
74
    extra_args:     [ state: SegmentedState ],
75
}
76

            
77
/// A joined row of mutually-exclusive segments with a selection callback.
78
#[derive(Debug, Clone, PartialEq, Eq)]
79
#[repr(C)]
80
pub struct Segmented {
81
    pub segmented_state: SegmentedStateWrapper,
82
    /// The label of each segment, in order.
83
    pub labels: StringVec,
84
    /// Style for the row container, or `None` for "no opinion" — in which case the
85
    /// widget's default applies.
86
    ///
87
    /// `None` and `Some(empty)` are different answers: the first means the
88
    /// widget picks, the second means the caller asked for no properties at all
89
    /// and gets none.
90
    pub container_style: OptionCssPropertyWithConditionsVec,
91
}
92

            
93
#[derive(Debug, Default, Clone, PartialEq, Eq)]
94
#[repr(C)]
95
pub struct SegmentedStateWrapper {
96
    /// The current selection.
97
    pub inner: SegmentedState,
98
    /// Optional: function to call when the selection changes.
99
    pub on_change: OptionSegmentedOnChange,
100
}
101

            
102
/// State of a [`Segmented`]: the index of the currently selected segment.
103
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
104
#[repr(C)]
105
pub struct SegmentedState {
106
    /// Zero-based index of the selected segment.
107
    pub selected_index: usize,
108
}
109

            
110
// ---- colours ----
111
/// Segment border colour (#ced4da).
112
const SEG_BORDER_COLOR: ColorU = ColorU {
113
    r: 206,
114
    g: 212,
115
    b: 218,
116
    a: 255,
117
};
118
/// Selected-segment background (#0d6efd, accent blue).
119
const SEG_SELECTED_BG_COLOR: ColorU = ColorU {
120
    r: 13,
121
    g: 110,
122
    b: 253,
123
    a: 255,
124
};
125
/// Unselected-segment background (white).
126
const SEG_UNSELECTED_BG_COLOR: ColorU = ColorU {
127
    r: 255,
128
    g: 255,
129
    b: 255,
130
    a: 255,
131
};
132
/// Selected-segment text colour (white).
133
const SEG_SELECTED_TEXT: ColorU = ColorU {
134
    r: 255,
135
    g: 255,
136
    b: 255,
137
    a: 255,
138
};
139
/// Unselected-segment text colour (#212529, dark).
140
const SEG_UNSELECTED_TEXT: ColorU = ColorU {
141
    r: 33,
142
    g: 37,
143
    b: 41,
144
    a: 255,
145
};
146

            
147
const SEG_SELECTED_BG_ITEMS: &[StyleBackgroundContent] =
148
    &[StyleBackgroundContent::Color(SEG_SELECTED_BG_COLOR)];
149
const SEG_SELECTED_BG: StyleBackgroundContentVec =
150
    StyleBackgroundContentVec::from_const_slice(SEG_SELECTED_BG_ITEMS);
151
const SEG_UNSELECTED_BG_ITEMS: &[StyleBackgroundContent] =
152
    &[StyleBackgroundContent::Color(SEG_UNSELECTED_BG_COLOR)];
153
const SEG_UNSELECTED_BG: StyleBackgroundContentVec =
154
    StyleBackgroundContentVec::from_const_slice(SEG_UNSELECTED_BG_ITEMS);
155

            
156
const SEG_RADIUS: isize = 6;
157

            
158
/// Row container: a horizontal flex row that hugs its content.
159
static SEGMENTED_CONTAINER_STYLE: &[CssPropertyWithConditions] = &[
160
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
161
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
162
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
163
    CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
164
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
165
];
166

            
167
/// Builds the style for one segment. The selected/unselected colours and the
168
/// rounding of the outer corners (only the first segment is rounded on the left,
169
/// only the last on the right) are the position-dependent properties, so the
170
/// style is built at runtime.
171
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
172
                                 // (one branch per case)
173
1329
fn build_segment_style(
174
1329
    selected: bool,
175
1329
    is_first: bool,
176
1329
    is_last: bool,
177
1329
) -> CssPropertyWithConditionsVec {
178
1329
    let (bg, text) = if selected {
179
137
        (SEG_SELECTED_BG, SEG_SELECTED_TEXT)
180
    } else {
181
1192
        (SEG_UNSELECTED_BG, SEG_UNSELECTED_TEXT)
182
    };
183

            
184
1329
    let mut v: Vec<CssPropertyWithConditions> = alloc::vec![
185
1329
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
186
1329
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
187
1329
            LayoutFlexDirection::Row,
188
        )),
189
1329
        CssPropertyWithConditions::simple(CssProperty::const_justify_content(
190
1329
            LayoutJustifyContent::Center,
191
        )),
192
1329
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
193
1329
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
194
            0,
195
        ))),
196
        // padding: 6px 12px
197
1329
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(
198
1329
            LayoutPaddingTop::const_px(6,)
199
        )),
200
1329
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
201
1329
            LayoutPaddingBottom::const_px(6),
202
        )),
203
1329
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
204
1329
            LayoutPaddingLeft::const_px(12),
205
        )),
206
1329
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
207
1329
            LayoutPaddingRight::const_px(12),
208
        )),
209
        // top/bottom/right borders (the left border is added only for the first segment,
210
        // so adjacent segments share a single 1px separator)
211
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
212
1329
            LayoutBorderTopWidth::const_px(1),
213
        )),
214
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
215
1329
            LayoutBorderBottomWidth::const_px(1),
216
        )),
217
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
218
1329
            LayoutBorderRightWidth::const_px(1),
219
        )),
220
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_top_style(
221
1329
            StyleBorderTopStyle {
222
1329
                inner: BorderStyle::Solid,
223
1329
            }
224
        )),
225
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
226
1329
            StyleBorderBottomStyle {
227
1329
                inner: BorderStyle::Solid,
228
1329
            },
229
        )),
230
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
231
1329
            StyleBorderRightStyle {
232
1329
                inner: BorderStyle::Solid,
233
1329
            },
234
        )),
235
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_top_color(
236
1329
            StyleBorderTopColor {
237
1329
                inner: SEG_BORDER_COLOR,
238
1329
            }
239
        )),
240
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
241
1329
            StyleBorderBottomColor {
242
1329
                inner: SEG_BORDER_COLOR,
243
1329
            },
244
        )),
245
1329
        CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
246
1329
            StyleBorderRightColor {
247
1329
                inner: SEG_BORDER_COLOR,
248
1329
            },
249
        )),
250
1329
        CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
251
1329
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
252
            13
253
        ))),
254
1329
        CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Center)),
255
1329
        CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
256
1329
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg)),
257
1329
        CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
258
1329
            inner: text,
259
1329
        })),
260
    ];
261

            
262
1329
    if is_first {
263
142
        v.push(CssPropertyWithConditions::simple(
264
142
            CssProperty::const_border_left_width(LayoutBorderLeftWidth::const_px(1)),
265
142
        ));
266
142
        v.push(CssPropertyWithConditions::simple(
267
142
            CssProperty::const_border_left_style(StyleBorderLeftStyle {
268
142
                inner: BorderStyle::Solid,
269
142
            }),
270
142
        ));
271
142
        v.push(CssPropertyWithConditions::simple(
272
142
            CssProperty::const_border_left_color(StyleBorderLeftColor {
273
142
                inner: SEG_BORDER_COLOR,
274
142
            }),
275
142
        ));
276
142
        v.push(CssPropertyWithConditions::simple(
277
142
            CssProperty::const_border_top_left_radius(StyleBorderTopLeftRadius::const_px(
278
142
                SEG_RADIUS,
279
142
            )),
280
142
        ));
281
142
        v.push(CssPropertyWithConditions::simple(
282
142
            CssProperty::const_border_bottom_left_radius(StyleBorderBottomLeftRadius::const_px(
283
142
                SEG_RADIUS,
284
142
            )),
285
142
        ));
286
1187
    }
287
1329
    if is_last {
288
142
        v.push(CssPropertyWithConditions::simple(
289
142
            CssProperty::const_border_top_right_radius(StyleBorderTopRightRadius::const_px(
290
142
                SEG_RADIUS,
291
142
            )),
292
142
        ));
293
142
        v.push(CssPropertyWithConditions::simple(
294
142
            CssProperty::const_border_bottom_right_radius(StyleBorderBottomRightRadius::const_px(
295
142
                SEG_RADIUS,
296
142
            )),
297
142
        ));
298
1187
    }
299

            
300
1329
    CssPropertyWithConditionsVec::from_vec(v)
301
1329
}
302

            
303
impl Segmented {
304
    /// Creates a segmented control from the given labels, with the first segment selected.
305
    #[must_use]
306
157
    pub fn create(labels: StringVec) -> Self {
307
157
        Self {
308
157
            segmented_state: SegmentedStateWrapper {
309
157
                inner: SegmentedState { selected_index: 0 },
310
157
                ..Default::default()
311
157
            },
312
157
            labels,
313
157
            container_style: OptionCssPropertyWithConditionsVec::None,
314
157
        }
315
157
    }
316

            
317
    /// The container CSS this segmented row renders with.
318
    ///
319
    /// `None` means no opinion, so the widget's default applies — the same
320
    /// answer both themes give, asked in one place so they cannot drift.
321
    #[must_use]
322
81
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
323
81
        self.container_style
324
81
            .clone()
325
81
            .into_option()
326
81
            .unwrap_or_else(|| {
327
81
                CssPropertyWithConditionsVec::from_const_slice(SEGMENTED_CONTAINER_STYLE)
328
81
            })
329
81
    }
330

            
331
    /// Sets the currently selected segment index.
332
    #[inline]
333
78
    pub const fn set_selected_index(&mut self, selected_index: usize) {
334
78
        self.segmented_state.inner.selected_index = selected_index;
335
78
    }
336

            
337
    /// Builder-style setter for the selected segment index.
338
    #[inline]
339
    #[must_use]
340
46
    pub const fn with_selected_index(mut self, selected_index: usize) -> Self {
341
46
        self.set_selected_index(selected_index);
342
46
        self
343
46
    }
344

            
345
    #[inline]
346
    #[must_use]
347
6
    pub fn swap_with_default(&mut self) -> Self {
348
6
        let mut s = Self::create(StringVec::from_const_slice(&[]));
349
6
        core::mem::swap(&mut s, self);
350
6
        s
351
6
    }
352

            
353
    #[inline]
354
15
    pub fn set_on_change<C: Into<SegmentedOnChangeCallback>>(
355
15
        &mut self,
356
15
        data: RefAny,
357
15
        on_change: C,
358
15
    ) {
359
15
        self.segmented_state.on_change = Some(SegmentedOnChange {
360
15
            callback: on_change.into(),
361
15
            refany: data,
362
15
        })
363
15
        .into();
364
15
    }
365

            
366
    #[inline]
367
    #[must_use]
368
10
    pub fn with_on_change<C: Into<SegmentedOnChangeCallback>>(
369
10
        mut self,
370
10
        data: RefAny,
371
10
        on_change: C,
372
10
    ) -> Self {
373
10
        self.set_on_change(data, on_change);
374
10
        self
375
10
    }
376

            
377
    #[must_use]
378
73
    pub fn dom(self) -> Dom {
379
        use azul_core::{
380
            callbacks::CoreCallback,
381
            dom::{EventFilter, HoverEventFilter},
382
            refany::OptionRefAny,
383
        };
384

            
385
73
        let selected = self.segmented_state.inner.selected_index;
386
73
        let count = self.labels.as_ref().len();
387
        // Resolved before `self.segmented_state` is moved out below.
388
73
        let container_style = self.resolved_container_style();
389

            
390
        // One shared RefAny across every segment's callback (RefAny::clone shares
391
        // the underlying state — same pattern as tabs/map).
392
73
        let state = RefAny::new(self.segmented_state);
393

            
394
73
        let mut children: Vec<Dom> = Vec::with_capacity(count);
395
1147
        for (i, label) in self.labels.as_ref().iter().enumerate() {
396
1147
            let is_first = i == 0;
397
1147
            let is_last = i + 1 == count;
398
1147
            let seg_style = build_segment_style(i == selected, is_first, is_last);
399
1147

            
400
1147
            children.push(
401
1147
                crate::widgets::widget_p_with_text(label.clone())
402
1147
                    .with_ids_and_classes(IdOrClassVec::from_const_slice(SEGMENT_ITEM_CLASS))
403
1147
                    .with_css_props(seg_style)
404
1147
                    .with_callbacks(
405
1147
                        vec![CoreCallbackData {
406
1147
                            event: EventFilter::Hover(HoverEventFilter::Click),
407
1147
                            callback: CoreCallback {
408
1147
                                cb: on_segment_click as usize,
409
1147
                                ctx: OptionRefAny::None,
410
1147
                            },
411
1147
                            refany: state.clone(),
412
1147
                        }]
413
1147
                        .into(),
414
1147
                    )
415
1147
                    .with_tab_index(TabIndex::Auto)
416
1147
            // Role so the accessibility tree knows what this IS:
417
1147
            // a row of mutually exclusive choices. The NAME comes from the widget's own text,
418
1147
            // which azul derives when a readable label is present.
419
1147
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
420
1147
                role: azul_core::a11y::AccessibilityRole::PageTabList,
421
1147
                ..Default::default()
422
1147
            }),
423
1147
            );
424
1147
        }
425

            
426
73
        Dom::create_div()
427
73
            .with_ids_and_classes(IdOrClassVec::from_const_slice(SEGMENTED_CLASS))
428
73
            .with_css_props(container_style)
429
73
            .with_children(children.into())
430
73
    }
431
}
432

            
433
impl Default for Segmented {
434
8
    fn default() -> Self {
435
8
        Self::create(StringVec::from_const_slice(&[]))
436
8
    }
437
}
438

            
439
/// Click handler shared by all segments. Determines the clicked segment's index
440
/// from its position among its siblings, updates the selection, invokes the user
441
/// callback, and live-restyles every segment.
442
26
extern "C" fn on_segment_click(mut data: RefAny, mut info: CallbackInfo) -> Update {
443
    use azul_core::dom::DomNodeId;
444

            
445
26
    let clicked = info.get_hit_node();
446
26
    let Some(parent) = info.get_parent(clicked) else {
447
3
        return Update::DoNothing;
448
    };
449

            
450
    // Collect the segment siblings in document order.
451
23
    let mut segments: Vec<DomNodeId> = Vec::new();
452
23
    let mut cur = info.get_first_child(parent);
453
719
    while let Some(node) = cur {
454
696
        segments.push(node);
455
696
        cur = info.get_next_sibling(node);
456
696
    }
457

            
458
358
    let Some(selected) = segments.iter().position(|n| *n == clicked) else {
459
        return Update::DoNothing;
460
    };
461

            
462
21
    let result = {
463
23
        let Some(mut seg) = data.downcast_mut::<SegmentedStateWrapper>() else {
464
2
            return Update::DoNothing;
465
        };
466
21
        seg.inner.selected_index = selected;
467
21
        let inner = seg.inner;
468
21
        let seg = &mut *seg;
469
21
        match seg.on_change.as_mut() {
470
5
            Some(SegmentedOnChange { callback, refany }) => {
471
5
                (callback.cb)(refany.clone(), info, inner)
472
            }
473
16
            None => Update::DoNothing,
474
        }
475
    };
476

            
477
    // Live-restyle: selected segment gets the accent fill + light text,
478
    // the rest get the neutral fill + dark text.
479
692
    for (i, node) in segments.iter().enumerate() {
480
692
        if i == selected {
481
21
            info.set_css_property(
482
21
                *node,
483
21
                CssProperty::const_background_content(SEG_SELECTED_BG),
484
21
            );
485
21
            info.set_css_property(
486
21
                *node,
487
21
                CssProperty::const_text_color(StyleTextColor {
488
21
                    inner: SEG_SELECTED_TEXT,
489
21
                }),
490
21
            );
491
671
        } else {
492
671
            info.set_css_property(
493
671
                *node,
494
671
                CssProperty::const_background_content(SEG_UNSELECTED_BG),
495
671
            );
496
671
            info.set_css_property(
497
671
                *node,
498
671
                CssProperty::const_text_color(StyleTextColor {
499
671
                    inner: SEG_UNSELECTED_TEXT,
500
671
                }),
501
671
            );
502
671
        }
503
    }
504

            
505
21
    result
506
26
}
507

            
508
impl From<Segmented> for Dom {
509
1
    fn from(s: Segmented) -> Self {
510
1
        s.dom()
511
1
    }
512
}
513

            
514
#[cfg(test)]
515
mod autotest_generated {
516
    use std::{
517
        collections::{BTreeMap, HashMap, HashSet},
518
        sync::{Arc, Mutex},
519
    };
520

            
521
    use azul_core::{
522
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
523
        geom::{LogicalRect, OptionLogicalPosition},
524
        gl::OptionGlContextPtr,
525
        hit_test::ScrollPosition,
526
        refany::OptionRefAny,
527
        resources::RendererResources,
528
        styled_dom::{NodeHierarchyItemId, StyledDom},
529
        window::{MonitorVec, RawWindowHandle},
530
    };
531
    use azul_css::{
532
        props::basic::{length::SizeMetric, pixel::PixelValue},
533
        system::SystemStyle,
534
    };
535
    use rust_fontconfig::FcFontCache;
536

            
537
    use super::*;
538
    #[cfg(feature = "icu")]
539
    use crate::icu::IcuLocalizerHandle;
540
    use crate::{
541
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
542
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
543
        window::{DomLayoutResult, LayoutWindow},
544
        window_state::FullWindowState,
545
    };
546

            
547
    // ------------------------------------------------------------------
548
    // Helpers
549
    // ------------------------------------------------------------------
550

            
551
    fn labels(v: &[&str]) -> StringVec {
552
        StringVec::from_vec(v.iter().map(|s| AzString::from(*s)).collect::<Vec<_>>())
553
    }
554

            
555
    /// `n` distinct labels: `s0, s1, … s{n-1}`.
556
    fn n_labels(n: usize) -> StringVec {
557
        StringVec::from_vec(
558
            (0..n)
559
                .map(|i| AzString::from(format!("s{i}")))
560
                .collect::<Vec<_>>(),
561
        )
562
    }
563

            
564
    /// The eight possible `(selected, is_first, is_last)` argument triples —
565
    /// the complete input domain of `build_segment_style`.
566
    const ALL_FLAGS: [(bool, bool, bool); 8] = [
567
        (false, false, false),
568
        (false, false, true),
569
        (false, true, false),
570
        (false, true, true),
571
        (true, false, false),
572
        (true, false, true),
573
        (true, true, false),
574
        (true, true, true),
575
    ];
576

            
577
    /// The declared properties of a style vec, in declaration order.
578
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
579
        v.as_ref().iter().map(|p| p.property.clone()).collect()
580
    }
581

            
582
    /// The *kind* of every declared property, in order (ignores the values).
583
    fn property_kinds(
584
        v: &CssPropertyWithConditionsVec,
585
    ) -> Vec<core::mem::Discriminant<CssProperty>> {
586
        v.as_ref()
587
            .iter()
588
            .map(|p| core::mem::discriminant(&p.property))
589
            .collect()
590
    }
591

            
592
    fn declares(v: &CssPropertyWithConditionsVec, pred: impl Fn(&CssProperty) -> bool) -> usize {
593
        v.as_ref().iter().filter(|p| pred(&p.property)).count()
594
    }
595

            
596
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length — an
597
    /// `em`/`%` slipping into the segment geometry would resolve against the
598
    /// parent font/box instead of the intended fixed padding, border or radius.
599
    fn px(pv: &PixelValue) -> f32 {
600
        assert_eq!(
601
            pv.metric,
602
            SizeMetric::Px,
603
            "segment geometry must be absolute px, got {:?}",
604
            pv.metric
605
        );
606
        pv.number.get()
607
    }
608

            
609
    /// The four paddings in `(top, bottom, left, right)` order.
610
    fn padding_px(
611
        v: &CssPropertyWithConditionsVec,
612
    ) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
613
        let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| {
614
            v.as_ref().iter().find_map(|p| f(&p.property))
615
        };
616
        (
617
            find(&|p| match p {
618
                CssProperty::PaddingTop(x) => x.get_property().map(|x| px(&x.inner)),
619
                _ => None,
620
            }),
621
            find(&|p| match p {
622
                CssProperty::PaddingBottom(x) => x.get_property().map(|x| px(&x.inner)),
623
                _ => None,
624
            }),
625
            find(&|p| match p {
626
                CssProperty::PaddingLeft(x) => x.get_property().map(|x| px(&x.inner)),
627
                _ => None,
628
            }),
629
            find(&|p| match p {
630
                CssProperty::PaddingRight(x) => x.get_property().map(|x| px(&x.inner)),
631
                _ => None,
632
            }),
633
        )
634
    }
635

            
636
    /// The four corner radii as `(top_left, top_right, bottom_left, bottom_right)`.
637
    fn radii_px(
638
        v: &CssPropertyWithConditionsVec,
639
    ) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
640
        let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| {
641
            v.as_ref().iter().find_map(|p| f(&p.property))
642
        };
643
        (
644
            find(&|p| match p {
645
                CssProperty::BorderTopLeftRadius(r) => r.get_property().map(|r| px(&r.inner)),
646
                _ => None,
647
            }),
648
            find(&|p| match p {
649
                CssProperty::BorderTopRightRadius(r) => r.get_property().map(|r| px(&r.inner)),
650
                _ => None,
651
            }),
652
            find(&|p| match p {
653
                CssProperty::BorderBottomLeftRadius(r) => r.get_property().map(|r| px(&r.inner)),
654
                _ => None,
655
            }),
656
            find(&|p| match p {
657
                CssProperty::BorderBottomRightRadius(r) => r.get_property().map(|r| px(&r.inner)),
658
                _ => None,
659
            }),
660
        )
661
    }
662

            
663
    /// The four border widths as `(top, bottom, left, right)`.
664
    fn border_widths_px(
665
        v: &CssPropertyWithConditionsVec,
666
    ) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
667
        let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| {
668
            v.as_ref().iter().find_map(|p| f(&p.property))
669
        };
670
        (
671
            find(&|p| match p {
672
                CssProperty::BorderTopWidth(x) => x.get_property().map(|x| px(&x.inner)),
673
                _ => None,
674
            }),
675
            find(&|p| match p {
676
                CssProperty::BorderBottomWidth(x) => x.get_property().map(|x| px(&x.inner)),
677
                _ => None,
678
            }),
679
            find(&|p| match p {
680
                CssProperty::BorderLeftWidth(x) => x.get_property().map(|x| px(&x.inner)),
681
                _ => None,
682
            }),
683
            find(&|p| match p {
684
                CssProperty::BorderRightWidth(x) => x.get_property().map(|x| px(&x.inner)),
685
                _ => None,
686
            }),
687
        )
688
    }
689

            
690
    fn font_size_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
691
        v.as_ref().iter().find_map(|p| match &p.property {
692
            CssProperty::FontSize(f) => f.get_property().map(|f| px(&f.inner)),
693
            _ => None,
694
        })
695
    }
696

            
697
    fn text_color(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
698
        v.as_ref().iter().find_map(|p| match &p.property {
699
            CssProperty::TextColor(c) => c.get_property().map(|c| c.inner),
700
            _ => None,
701
        })
702
    }
703

            
704
    /// The single background layer of a style vec, asserting there is exactly one
705
    /// and that it is a flat colour (a gradient would not be a `Color`).
706
    fn background_color(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
707
        let bg = v.as_ref().iter().find_map(|p| match &p.property {
708
            CssProperty::BackgroundContent(b) => b.get_property(),
709
            _ => None,
710
        })?;
711
        assert_eq!(
712
            bg.as_ref().len(),
713
            1,
714
            "a segment must declare exactly one background layer"
715
        );
716
        match &bg.as_ref()[0] {
717
            StyleBackgroundContent::Color(c) => Some(*c),
718
            other => panic!("segment background is not a flat colour: {other:?}"),
719
        }
720
    }
721

            
722
    /// Perceived brightness (0..=255) of an sRGB colour, Rec.709 weights. Kept to
723
    /// plain `+`/`*` (no gamma expansion) so the readability assertions stay exact
724
    /// and toolchain-independent.
725
    fn luma(c: ColorU) -> f32 {
726
        0.2126 * f32::from(c.r) + 0.7152 * f32::from(c.g) + 0.0722 * f32::from(c.b)
727
    }
728

            
729
    /// The text of a text node, looking through the `<p>` block wrapper the
730
    /// label convention mandates (`p > text`).
731
    fn text_of(node: &Dom) -> Option<&str> {
732
        match node.root.get_node_type() {
733
            NodeType::Text(s) => Some(s.as_ref().as_str()),
734
            NodeType::P => match node.children.as_ref() {
735
                [only] => match only.root.get_node_type() {
736
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
737
                    _ => None,
738
                },
739
                _ => None,
740
            },
741
            _ => None,
742
        }
743
    }
744

            
745
    /// The properties of a rendered node's *inline* style, in declaration order.
746
    fn inline_properties(node: &Dom) -> Vec<CssProperty> {
747
        node.root
748
            .style
749
            .iter_inline_properties()
750
            .map(|(p, _)| p.clone())
751
            .collect()
752
    }
753

            
754
    /// The true recursive descendant count of a `Dom` — what
755
    /// `estimated_total_children` is documented to cache.
756
    fn recursive_descendants(node: &Dom) -> usize {
757
        node.children
758
            .as_ref()
759
            .iter()
760
            .map(|c| 1 + recursive_descendants(c))
761
            .sum()
762
    }
763

            
764
    /// Boundary + "negative" selection indices. `usize` has no negative values, so
765
    /// a `-1` handed in through FFI arrives here as `usize::MAX`; both wrapped
766
    /// forms are included so the setter is exercised at the two's-complement ends.
767
    fn boundary_indices() -> Vec<usize> {
768
        vec![
769
            0,
770
            1,
771
            2,
772
            usize::MAX / 2,
773
            usize::MAX / 2 + 1,
774
            usize::MAX - 1,
775
            usize::MAX,
776
            (-1i64) as usize,
777
            i64::MIN as usize,
778
            u32::MAX as usize,
779
        ]
780
    }
781

            
782
    /// Adversarial segment labels: empty, whitespace, combining marks, ZWJ emoji,
783
    /// RTL, embedded NULs (`AzString` is length-based, so a NUL must not
784
    /// truncate), control characters, and a string far longer than any plausible
785
    /// segment caption.
786
    fn adversarial_strings() -> Vec<String> {
787
        let mut v: Vec<String> = [
788
            "",
789
            "Day",
790
            " ",
791
            "e\u{0301}",                                   // e + combining acute
792
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}", // ZWJ family emoji
793
            "\u{5E9}\u{5DC}\u{5D5}\u{5DD}",                // RTL Hebrew
794
            "\0",                                          // a single NUL
795
            "a\0b",                                        // embedded NUL
796
            "\u{FFFD}\u{202E}\u{200B}",                    // replacement, RTL override, ZWSP
797
            "line\nbreak\ttab",                            // control characters
798
            "-9223372036854775808",                        // i64::MIN as a caption
799
        ]
800
        .iter()
801
        .map(|s| (*s).to_string())
802
        .collect();
803
        v.push("x".repeat(100_000));
804
        v
805
    }
806

            
807
    /// Forces the `fn`-item -> `fn`-pointer coercion the `Into` bound needs.
808
    fn change_cb(f: SegmentedOnChangeCallbackType) -> SegmentedOnChangeCallback {
809
        f.into()
810
    }
811

            
812
    /// A `RefAny` payload recording every index a user `on_change` sees.
813
    struct IndexLog {
814
        seen: Vec<usize>,
815
    }
816

            
817
    extern "C" fn record_index(mut data: RefAny, _: CallbackInfo, state: SegmentedState) -> Update {
818
        if let Some(mut log) = data.downcast_mut::<IndexLog>() {
819
            log.seen.push(state.selected_index);
820
        }
821
        Update::RefreshDom
822
    }
823

            
824
    extern "C" fn change_do_nothing(_: RefAny, _: CallbackInfo, _: SegmentedState) -> Update {
825
        Update::DoNothing
826
    }
827

            
828
    extern "C" fn change_refresh_all(_: RefAny, _: CallbackInfo, state: SegmentedState) -> Update {
829
        // `selected_index` is read (and discarded) purely so this body cannot be
830
        // identical-code-folded onto another handler; the tests below compare
831
        // callback function pointers for equality/inequality.
832
        let _ = state.selected_index;
833
        Update::RefreshDomAllWindows
834
    }
835

            
836
    /// A payload whose callback tries to read the *same* `SegmentedStateWrapper`
837
    /// `RefAny` that the handler is currently holding a mutable borrow on.
838
    struct ReentrantProbe {
839
        /// A clone of the state `RefAny` the handler was invoked with.
840
        state: RefAny,
841
        /// `Some(index)` if the re-entrant read succeeded, `None` if it was
842
        /// refused. Starts as `Some(usize::MAX)` so "never ran" is distinguishable.
843
        saw_index: Option<usize>,
844
        calls: usize,
845
    }
846

            
847
    extern "C" fn probe_state_reentrantly(
848
        mut data: RefAny,
849
        _: CallbackInfo,
850
        _: SegmentedState,
851
    ) -> Update {
852
        if let Some(mut probe) = data.downcast_mut::<ReentrantProbe>() {
853
            probe.calls += 1;
854
            let mut state = probe.state.clone();
855
            probe.saw_index = state
856
                .downcast_ref::<SegmentedStateWrapper>()
857
                .map(|w| w.inner.selected_index);
858
        }
859
        Update::DoNothing
860
    }
861

            
862
    fn log_indices(data: &mut RefAny) -> Vec<usize> {
863
        data.downcast_ref::<IndexLog>()
864
            .expect("payload must still be an IndexLog")
865
            .seen
866
            .clone()
867
    }
868

            
869
    fn selected_index_of(data: &mut RefAny) -> usize {
870
        data.downcast_ref::<SegmentedStateWrapper>()
871
            .expect("payload must still be a SegmentedStateWrapper")
872
            .inner
873
            .selected_index
874
    }
875

            
876
    /// The `RefAny` carried by segment `i`'s click callback.
877
    fn segment_state(dom: &Dom, i: usize) -> RefAny {
878
        let cbs = dom.children.as_ref()[i].root.get_callbacks();
879
        cbs.as_ref()
880
            .first()
881
            .expect("every segment must carry the click callback")
882
            .refany
883
            .clone()
884
    }
885

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

            
909
    /// Flattens `seg.dom()` and hands back the shared state `RefAny` the segment
910
    /// callbacks carry. Requires at least one label.
911
    fn flatten(seg: Segmented) -> (StyledDom, RefAny) {
912
        let dom = seg.dom();
913
        let state = segment_state(&dom, 0);
914
        (StyledDom::create_from_dom(dom), state)
915
    }
916

            
917
    /// Flattened (pre-order) node id of segment `i`. Every segment is a `<p>`
918
    /// wrapping one bare text node, so the tree is
919
    /// `0 root / 1 seg0 <p> / 2 seg0 text / 3 seg1 <p> / …` and the callback
920
    /// sits on the `<p>`.
921
    const fn seg_node(i: usize) -> usize {
922
        2 * i + 1
923
    }
924

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

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

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

            
966
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
967

            
968
        let info = CallbackInfo::new(
969
            &ref_data,
970
            &changes,
971
            DomNodeId {
972
                dom: DomId::ROOT_ID,
973
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
974
            },
975
            OptionLogicalPosition::None,
976
            OptionLogicalPosition::None,
977
        );
978

            
979
        let update = on_segment_click(data, info);
980
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
981
        (update, recorded)
982
    }
983

            
984
    /// Every colour the live restyle wrote, as `(node index, "bg" | "text", colour)`
985
    /// in emission order. Panics on any property other than the two the handler is
986
    /// documented to write.
987
    fn restyle_writes(changes: &[CallbackChange]) -> Vec<(usize, &'static str, ColorU)> {
988
        let mut out = Vec::new();
989
        for change in changes {
990
            let CallbackChange::ChangeNodeCssProperties {
991
                node_id,
992
                properties,
993
                ..
994
            } = change
995
            else {
996
                panic!("the restyle must only emit ChangeNodeCssProperties, got {change:?}");
997
            };
998
            for p in properties.as_ref() {
999
                match p {
                    CssProperty::BackgroundContent(v) => {
                        let layers = v
                            .get_property()
                            .expect("restyle must write an exact background");
                        assert_eq!(layers.as_ref().len(), 1, "a segment fill is a single layer");
                        match &layers.as_ref()[0] {
                            StyleBackgroundContent::Color(c) => {
                                out.push((node_id.index(), "bg", *c));
                            }
                            other => panic!("segment background is not a flat colour: {other:?}"),
                        }
                    }
                    CssProperty::TextColor(v) => {
                        let c = v
                            .get_property()
                            .expect("restyle must write an exact text colour");
                        out.push((node_id.index(), "text", c.inner));
                    }
                    other => panic!("unexpected restyle property: {other:?}"),
                }
            }
        }
        out
    }
    // ------------------------------------------------------------------
    // build_segment_style
    // ------------------------------------------------------------------
    #[test]
    fn build_segment_style_handles_all_eight_flag_combinations() {
        // 24 shared declarations, +5 for the first segment (left border triple +
        // the two left radii), +2 for the last (the two right radii).
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            let expected = 24 + if first { 5 } else { 0 } + if last { 2 } else { 0 };
            assert_eq!(
                style.as_ref().len(),
                expected,
                "({selected}, {first}, {last}): unexpected declaration count"
            );
        }
    }
    #[test]
    fn build_segment_style_colours_depend_only_on_selected() {
        // Position must not leak into the palette: a "first" segment and a
        // "middle" segment with the same selection must paint identically.
        for selected in [false, true] {
            let reference = build_segment_style(selected, false, false);
            let bg = background_color(&reference).expect("a segment must declare a background");
            let fg = text_color(&reference).expect("a segment must declare a text colour");
            for (first, last) in [(false, false), (false, true), (true, false), (true, true)] {
                let style = build_segment_style(selected, first, last);
                assert_eq!(
                    background_color(&style),
                    Some(bg),
                    "selected={selected}: background moved with position"
                );
                assert_eq!(
                    text_color(&style),
                    Some(fg),
                    "selected={selected}: text colour moved with position"
                );
            }
        }
        assert_eq!(
            background_color(&build_segment_style(true, false, false)),
            Some(SEG_SELECTED_BG_COLOR)
        );
        assert_eq!(
            text_color(&build_segment_style(true, false, false)),
            Some(SEG_SELECTED_TEXT)
        );
        assert_eq!(
            background_color(&build_segment_style(false, false, false)),
            Some(SEG_UNSELECTED_BG_COLOR)
        );
        assert_eq!(
            text_color(&build_segment_style(false, false, false)),
            Some(SEG_UNSELECTED_TEXT)
        );
    }
    #[test]
    fn build_segment_style_adds_the_left_border_only_to_the_first_segment() {
        // Every segment paints its own right border, so a non-first segment that
        // also painted a left one would render a 2px seam between neighbours.
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            let want = usize::from(first);
            assert_eq!(
                declares(&style, |p| matches!(p, CssProperty::BorderLeftWidth(_))),
                want,
                "({selected}, {first}, {last}): left border width"
            );
            assert_eq!(
                declares(&style, |p| matches!(p, CssProperty::BorderLeftStyle(_))),
                want,
                "({selected}, {first}, {last}): left border style"
            );
            assert_eq!(
                declares(&style, |p| matches!(p, CssProperty::BorderLeftColor(_))),
                want,
                "({selected}, {first}, {last}): left border colour"
            );
        }
    }
    #[test]
    fn build_segment_style_rounds_only_the_outer_corners() {
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            let (tl, tr, bl, br) = radii_px(&style);
            let r = SEG_RADIUS as f32;
            assert_eq!(
                tl,
                first.then_some(r),
                "({selected}, {first}, {last}): top-left radius"
            );
            assert_eq!(
                bl,
                first.then_some(r),
                "({selected}, {first}, {last}): bottom-left radius"
            );
            assert_eq!(
                tr,
                last.then_some(r),
                "({selected}, {first}, {last}): top-right radius"
            );
            assert_eq!(
                br,
                last.then_some(r),
                "({selected}, {first}, {last}): bottom-right radius"
            );
        }
        // A lone segment is a fully rounded pill; an interior segment is square.
        let solo = build_segment_style(true, true, true);
        let r = SEG_RADIUS as f32;
        assert_eq!(radii_px(&solo), (Some(r), Some(r), Some(r), Some(r)));
        let middle = build_segment_style(true, false, false);
        assert_eq!(radii_px(&middle), (None, None, None, None));
    }
    #[test]
    fn build_segment_style_always_paints_the_shared_separator_edges() {
        // Top/bottom/right must be declared unconditionally — dropping the right
        // border on the last segment would leave the group open on one side.
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            let (top, bottom, left, right) = border_widths_px(&style);
            assert_eq!(top, Some(1.0), "({selected}, {first}, {last}): top border");
            assert_eq!(
                bottom,
                Some(1.0),
                "({selected}, {first}, {last}): bottom border"
            );
            assert_eq!(
                right,
                Some(1.0),
                "({selected}, {first}, {last}): right border"
            );
            assert_eq!(
                left,
                first.then_some(1.0),
                "({selected}, {first}, {last}): left border"
            );
            // A width without a matching style/colour renders as no border at all.
            for count in [
                declares(&style, |p| matches!(p, CssProperty::BorderTopStyle(_))),
                declares(&style, |p| matches!(p, CssProperty::BorderBottomStyle(_))),
                declares(&style, |p| matches!(p, CssProperty::BorderRightStyle(_))),
                declares(&style, |p| matches!(p, CssProperty::BorderTopColor(_))),
                declares(&style, |p| matches!(p, CssProperty::BorderBottomColor(_))),
                declares(&style, |p| matches!(p, CssProperty::BorderRightColor(_))),
            ] {
                assert_eq!(
                    count, 1,
                    "({selected}, {first}, {last}): a shared edge lost its style/colour"
                );
            }
        }
    }
    #[test]
    fn build_segment_style_border_colours_are_the_single_neutral_grey() {
        // A width without a matching colour (or a stray second grey) shows up as
        // an inconsistent seam between neighbouring segments.
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            for p in style.as_ref() {
                let found = match &p.property {
                    CssProperty::BorderTopColor(c) => c.get_property().map(|c| c.inner),
                    CssProperty::BorderBottomColor(c) => c.get_property().map(|c| c.inner),
                    CssProperty::BorderLeftColor(c) => c.get_property().map(|c| c.inner),
                    CssProperty::BorderRightColor(c) => c.get_property().map(|c| c.inner),
                    _ => None,
                };
                if let Some(c) = found {
                    assert_eq!(
                        c, SEG_BORDER_COLOR,
                        "({selected}, {first}, {last}): border colour {c:?} is not the shared grey"
                    );
                }
            }
        }
    }
    #[test]
    fn build_segment_style_geometry_is_absolute_and_symmetric() {
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            // padding: 6px 12px — `px()` asserts the metric on every value it reads.
            assert_eq!(
                padding_px(&style),
                (Some(6.0), Some(6.0), Some(12.0), Some(12.0)),
                "({selected}, {first}, {last}): padding is not 6px 12px"
            );
            assert_eq!(
                font_size_px(&style),
                Some(13.0),
                "({selected}, {first}, {last}): font size"
            );
        }
    }
    #[test]
    fn build_segment_style_declares_every_property_unconditionally() {
        // `simple()` means an empty `apply_if`. A stray condition here would make
        // the segment silently unstyled until some selector state happened to match.
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            for p in style.as_ref() {
                assert!(
                    p.apply_if.as_ref().is_empty(),
                    "({selected}, {first}, {last}): {:?} is conditional",
                    p.property
                );
            }
        }
    }
    #[test]
    fn build_segment_style_never_declares_the_same_property_twice() {
        // Duplicates are silently last-wins, so a doubled declaration hides a
        // genuine value conflict instead of failing loudly.
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            let mut seen = HashSet::new();
            for kind in property_kinds(&style) {
                assert!(
                    seen.insert(kind),
                    "({selected}, {first}, {last}): duplicate property kind in the style vec"
                );
            }
            assert_eq!(seen.len(), style.as_ref().len());
        }
    }
    #[test]
    fn build_segment_style_is_pure() {
        // Called once per segment on every `dom()`; a hidden `static mut` cache or
        // an accumulating vec would show up as drift between two identical calls.
        for (selected, first, last) in ALL_FLAGS {
            let a = build_segment_style(selected, first, last);
            let b = build_segment_style(selected, first, last);
            assert_eq!(
                properties(&a),
                properties(&b),
                "({selected}, {first}, {last}): not pure"
            );
        }
    }
    #[test]
    fn build_segment_style_keeps_the_label_readable_and_opaque() {
        for selected in [false, true] {
            let style = build_segment_style(selected, false, false);
            let bg = background_color(&style).expect("background");
            let fg = text_color(&style).expect("text colour");
            assert_eq!(
                bg.a, 255,
                "selected={selected}: a translucent fill lets the page bleed through"
            );
            assert_eq!(fg.a, 255, "selected={selected}: translucent label text");
            assert_ne!(
                bg, fg,
                "selected={selected}: an invisible label is not a segment"
            );
            assert!(
                (luma(bg) - luma(fg)).abs() >= 60.0,
                "selected={selected}: brightness gap {:.1} is too low to read",
                (luma(bg) - luma(fg)).abs()
            );
        }
        // The two states must be visually distinguishable — that is the entire
        // point of a segmented control.
        let sel = build_segment_style(true, false, false);
        let unsel = build_segment_style(false, false, false);
        assert_ne!(background_color(&sel), background_color(&unsel));
        assert_ne!(text_color(&sel), text_color(&unsel));
    }
    #[test]
    fn build_segment_style_declares_the_interaction_affordances() {
        for (selected, first, last) in ALL_FLAGS {
            let style = build_segment_style(selected, first, last);
            let ctx = format!("({selected}, {first}, {last})");
            assert!(
                style.as_ref().iter().any(|p| matches!(
                    &p.property,
                    CssProperty::Cursor(c) if c.get_property() == Some(&StyleCursor::Pointer)
                )),
                "{ctx}: a clickable segment must show the pointer cursor"
            );
            assert!(
                style.as_ref().iter().any(|p| matches!(
                    &p.property,
                    CssProperty::UserSelect(u) if u.get_property() == Some(&StyleUserSelect::None)
                )),
                "{ctx}: click-dragging a segment must not select its caption"
            );
            assert!(
                style.as_ref().iter().any(|p| matches!(
                    &p.property,
                    CssProperty::TextAlign(t) if t.get_property() == Some(&StyleTextAlign::Center)
                )),
                "{ctx}: captions are centred"
            );
            assert!(
                style.as_ref().iter().any(|p| matches!(
                    &p.property,
                    CssProperty::FlexGrow(f) if f.get_property().map(|f| f.inner.get()) == Some(0.0)
                )),
                "{ctx}: segments hug their caption, they do not stretch"
            );
        }
    }
    // ------------------------------------------------------------------
    // Segmented::create
    // ------------------------------------------------------------------
    #[test]
    fn create_preserves_labels_verbatim() {
        for case in [
            vec![],
            vec!["only"],
            vec!["Day", "Week"],
            vec!["Day", "Week", "Month", "Year"],
            vec!["dup", "dup", "dup"],
        ] {
            let seg = Segmented::create(labels(&case));
            let got: Vec<&str> = seg.labels.as_ref().iter().map(AzString::as_str).collect();
            assert_eq!(
                got, case,
                "create must not reorder/drop/dedupe/rewrite labels"
            );
        }
    }
    #[test]
    fn create_preserves_adversarial_labels_byte_for_byte() {
        for s in adversarial_strings() {
            let seg = Segmented::create(labels(&[s.as_str()]));
            let stored = seg.labels.as_ref()[0].as_str();
            assert_eq!(
                stored,
                s.as_str(),
                "the caption changed on its way into the widget"
            );
            assert_eq!(
                seg.labels.as_ref()[0].as_ref().len(),
                s.len(),
                "byte length changed (NUL truncation?)"
            );
        }
    }
    #[test]
    fn create_selects_the_first_segment_and_installs_no_callback() {
        for n in [0usize, 1, 2, 7] {
            let seg = Segmented::create(n_labels(n));
            assert_eq!(
                seg.segmented_state.inner.selected_index, 0,
                "n={n}: a fresh control starts on segment 0"
            );
            assert!(
                seg.segmented_state.on_change.as_ref().is_none(),
                "n={n}: create must not wire a callback"
            );
        }
    }
    #[test]
    fn create_installs_the_shared_container_style() {
        let seg = Segmented::create(labels(&["a", "b"]));
        assert_eq!(
            seg.resolved_container_style().as_ref(),
            SEGMENTED_CONTAINER_STYLE,
            "create must install the shared container style"
        );
        // Decode the semantics too, so a silent edit of the const is caught here
        // rather than only in a screenshot: a horizontal, content-hugging row.
        let style = seg.resolved_container_style();
        let style = &style;
        assert_eq!(
            declares(style, |p| matches!(
                p, CssProperty::Display(d) if d.get_property() == Some(&LayoutDisplay::Flex))),
            1,
            "the row container must be a flex box"
        );
        assert_eq!(
            declares(style, |p| matches!(
                p, CssProperty::FlexDirection(d) if d.get_property() == Some(&LayoutFlexDirection::Row))),
            1,
            "segments are joined horizontally"
        );
        assert_eq!(
            declares(style, |p| matches!(
                p, CssProperty::AlignItems(a) if a.get_property() == Some(&LayoutAlignItems::Center))),
            1
        );
        assert_eq!(
            declares(style, |p| matches!(
                p, CssProperty::AlignSelf(a) if a.get_property() == Some(&LayoutAlignSelf::Start))),
            1
        );
        assert_eq!(
            declares(style, |p| matches!(
                p, CssProperty::FlexGrow(f) if f.get_property().map(|f| f.inner.get()) == Some(0.0))),
            1,
            "the group hugs its segments instead of filling the parent"
        );
        for p in seg.resolved_container_style().as_ref() {
            assert!(
                p.apply_if.as_ref().is_empty(),
                "{:?} is conditional",
                p.property
            );
        }
    }
    #[test]
    fn create_with_no_labels_equals_default() {
        let empty = Segmented::create(StringVec::from_const_slice(&[]));
        assert_eq!(
            empty,
            Segmented::default(),
            "Default must be the empty control"
        );
        assert_eq!(empty.labels.as_ref().len(), 0);
        assert!(Segmented::default()
            .segmented_state
            .on_change
            .as_ref()
            .is_none());
    }
    #[test]
    fn create_scales_to_a_very_long_label_list() {
        let n = 4096;
        let seg = Segmented::create(n_labels(n));
        assert_eq!(seg.labels.as_ref().len(), n);
        assert_eq!(seg.labels.as_ref()[n - 1].as_str(), format!("s{}", n - 1));
        assert_eq!(seg.segmented_state.inner.selected_index, 0);
    }
    // ------------------------------------------------------------------
    // Segmented::set_selected_index  /  with_selected_index
    // ------------------------------------------------------------------
    #[test]
    fn set_selected_index_stores_every_boundary_value_verbatim() {
        // The setter is a plain field write: no clamping, no wrapping, no panic —
        // not even at `usize::MAX` or at a `-1` that arrived through FFI.
        for i in boundary_indices() {
            let mut seg = Segmented::create(labels(&["a", "b", "c"]));
            seg.set_selected_index(i);
            assert_eq!(
                seg.segmented_state.inner.selected_index, i,
                "index {i} was not stored as-is"
            );
        }
    }
    #[test]
    fn set_selected_index_does_not_clamp_to_the_label_count() {
        // Documenting the actual contract: an out-of-range index is *accepted*
        // and simply selects nothing when rendered (see the `dom_` tests below).
        let mut seg = Segmented::create(labels(&["a", "b"]));
        for i in [2usize, 3, 1_000, usize::MAX] {
            seg.set_selected_index(i);
            assert_eq!(seg.segmented_state.inner.selected_index, i);
            assert_eq!(
                seg.labels.as_ref().len(),
                2,
                "the setter must not touch the labels"
            );
        }
    }
    #[test]
    fn set_selected_index_is_idempotent_and_last_write_wins() {
        let mut seg = Segmented::create(labels(&["a", "b", "c"]));
        for i in [1usize, 1, 1] {
            seg.set_selected_index(i);
        }
        assert_eq!(seg.segmented_state.inner.selected_index, 1);
        for i in [0usize, usize::MAX, 2, 0] {
            seg.set_selected_index(i);
        }
        assert_eq!(
            seg.segmented_state.inner.selected_index, 0,
            "the last write must win"
        );
    }
    #[test]
    fn set_selected_index_leaves_every_other_field_alone() {
        let mut seg = Segmented::create(labels(&["a", "b"]))
            .with_on_change(RefAny::new(7u8), change_cb(change_do_nothing));
        let before = seg.clone();
        seg.set_selected_index(usize::MAX);
        assert_eq!(seg.labels, before.labels, "labels changed");
        assert_eq!(
            seg.resolved_container_style(),
            before.resolved_container_style(),
            "container style changed"
        );
        assert_eq!(
            seg.segmented_state.on_change, before.segmented_state.on_change,
            "the callback was disturbed"
        );
    }
    #[test]
    fn with_selected_index_round_trips_through_the_setter() {
        for i in boundary_indices() {
            let via_builder = Segmented::create(labels(&["a", "b"])).with_selected_index(i);
            let mut via_setter = Segmented::create(labels(&["a", "b"]));
            via_setter.set_selected_index(i);
            assert_eq!(
                via_builder, via_setter,
                "index {i}: builder and setter diverge"
            );
            assert_eq!(via_builder.segmented_state.inner.selected_index, i);
        }
    }
    #[test]
    fn with_selected_index_preserves_the_rest_of_the_widget() {
        let base = Segmented::create(labels(&["a", "b", "c"]));
        let built = base.clone().with_selected_index(2);
        assert_eq!(built.labels, base.labels);
        assert_eq!(
            built.resolved_container_style(),
            base.resolved_container_style()
        );
        assert_eq!(
            built.labels.as_ref().len(),
            3,
            "len/contents must stay consistent"
        );
        assert!(built.segmented_state.on_change.as_ref().is_none());
    }
    #[test]
    fn with_selected_index_chains_with_last_wins() {
        let seg = Segmented::create(labels(&["a", "b", "c"]))
            .with_selected_index(usize::MAX)
            .with_selected_index(0)
            .with_selected_index(2);
        assert_eq!(seg.segmented_state.inner.selected_index, 2);
    }
    // ------------------------------------------------------------------
    // Segmented::swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_returns_the_original_and_leaves_a_default_behind() {
        let mut seg = Segmented::create(labels(&["Day", "Week", "Month"])).with_selected_index(2);
        let expected = seg.clone();
        let taken = seg.swap_with_default();
        assert_eq!(
            taken, expected,
            "the caller must get the original widget back"
        );
        assert_eq!(
            seg,
            Segmented::default(),
            "a default must be left in its place"
        );
        assert_eq!(seg.labels.as_ref().len(), 0);
        assert_eq!(seg.segmented_state.inner.selected_index, 0);
    }
    #[test]
    fn swap_with_default_moves_the_callback_out_with_the_widget() {
        let mut seg = Segmented::create(labels(&["a", "b"]))
            .with_on_change(RefAny::new(1u8), change_cb(record_index));
        let taken = seg.swap_with_default();
        assert!(
            taken.segmented_state.on_change.as_ref().is_some(),
            "the callback must travel with the taken widget"
        );
        assert!(
            seg.segmented_state.on_change.as_ref().is_none(),
            "the leftover default must not keep a handle on the callback"
        );
    }
    #[test]
    fn swap_with_default_on_a_default_is_a_no_op() {
        let mut seg = Segmented::default();
        let taken = seg.swap_with_default();
        assert_eq!(taken, Segmented::default());
        assert_eq!(seg, Segmented::default());
    }
    #[test]
    fn swap_with_default_twice_yields_a_default_the_second_time() {
        let mut seg = Segmented::create(labels(&["a", "b"])).with_selected_index(1);
        let first = seg.swap_with_default();
        let second = seg.swap_with_default();
        assert_eq!(first.labels.as_ref().len(), 2);
        assert_eq!(first.segmented_state.inner.selected_index, 1);
        assert_eq!(
            second,
            Segmented::default(),
            "the second take is the default we left behind"
        );
        assert_eq!(seg, Segmented::default());
    }
    #[test]
    fn swap_with_default_does_not_truncate_a_large_label_list() {
        let n = 1024;
        let mut seg = Segmented::create(n_labels(n)).with_selected_index(n - 1);
        let taken = seg.swap_with_default();
        assert_eq!(taken.labels.as_ref().len(), n);
        assert_eq!(taken.labels.as_ref()[n - 1].as_str(), format!("s{}", n - 1));
        assert_eq!(taken.segmented_state.inner.selected_index, n - 1);
    }
    // ------------------------------------------------------------------
    // Segmented::set_on_change  /  with_on_change
    // ------------------------------------------------------------------
    #[test]
    fn set_on_change_installs_the_callback_and_its_payload() {
        let mut seg = Segmented::create(labels(&["a", "b"]));
        let mut payload = RefAny::new(IndexLog { seen: Vec::new() });
        seg.set_on_change(payload.clone(), change_cb(record_index));
        let installed = seg
            .segmented_state
            .on_change
            .as_ref()
            .expect("set_on_change must install a callback");
        assert_eq!(
            installed.callback.cb as usize, record_index as usize,
            "wrong function installed"
        );
        assert!(
            matches!(installed.callback.ctx, OptionRefAny::None),
            "a native Rust callback carries no FFI context"
        );
        // The stored `RefAny` must be a *share* of the caller's, not a copy:
        // writing through the widget's handle must be visible to the caller.
        let mut stored = installed.refany.clone();
        {
            let mut log = stored
                .downcast_mut::<IndexLog>()
                .expect("payload type must survive");
            log.seen.push(42);
        }
        assert_eq!(
            log_indices(&mut payload),
            vec![42],
            "the payload was copied, not shared"
        );
    }
    #[test]
    fn set_on_change_overwrites_a_previously_installed_callback() {
        let mut seg = Segmented::create(labels(&["a", "b"]));
        seg.set_on_change(RefAny::new(1u8), change_cb(record_index));
        seg.set_on_change(RefAny::new(2u8), change_cb(change_refresh_all));
        let installed = seg.segmented_state.on_change.as_ref().expect("callback");
        assert_eq!(
            installed.callback.cb as usize, change_refresh_all as usize,
            "the last setter must win"
        );
        assert_ne!(installed.callback.cb as usize, record_index as usize);
    }
    #[test]
    fn set_on_change_does_not_disturb_labels_or_selection() {
        let mut seg = Segmented::create(labels(&["a", "b", "c"])).with_selected_index(2);
        seg.set_on_change(RefAny::new(0u8), change_cb(change_do_nothing));
        assert_eq!(seg.labels.as_ref().len(), 3);
        assert_eq!(
            seg.segmented_state.inner.selected_index, 2,
            "installing a callback moved the selection"
        );
    }
    #[test]
    fn with_on_change_matches_the_setter_exactly() {
        let payload = RefAny::new(9u8);
        let via_builder = Segmented::create(labels(&["a", "b"]))
            .with_on_change(payload.clone(), change_cb(change_do_nothing));
        let mut via_setter = Segmented::create(labels(&["a", "b"]));
        via_setter.set_on_change(payload, change_cb(change_do_nothing));
        assert_eq!(
            via_builder, via_setter,
            "builder and setter must produce the same widget"
        );
    }
    #[test]
    fn with_on_change_holds_its_invariants_after_construction() {
        let seg = Segmented::create(n_labels(5))
            .with_selected_index(3)
            .with_on_change(RefAny::new(0u8), change_cb(change_refresh_all));
        assert_eq!(
            seg.labels.as_ref().len(),
            5,
            "label count must survive the builder chain"
        );
        assert_eq!(
            seg.segmented_state.inner.selected_index, 3,
            "the selection must survive"
        );
        assert_eq!(
            seg.resolved_container_style().as_ref(),
            SEGMENTED_CONTAINER_STYLE,
            "the container style must survive"
        );
        let installed = seg.segmented_state.on_change.as_ref().expect("callback");
        assert_eq!(installed.callback.cb as usize, change_refresh_all as usize);
    }
    #[test]
    fn with_on_change_chains_with_last_wins() {
        let seg = Segmented::create(labels(&["a"]))
            .with_on_change(RefAny::new(0u8), change_cb(record_index))
            .with_on_change(RefAny::new(0u8), change_cb(change_do_nothing));
        let installed = seg.segmented_state.on_change.as_ref().expect("callback");
        assert_eq!(installed.callback.cb as usize, change_do_nothing as usize);
    }
    // ------------------------------------------------------------------
    // Segmented::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_emits_one_text_child_per_label_in_order() {
        let case = ["Day", "Week", "Month", "Year"];
        let dom = Segmented::create(labels(&case)).dom();
        assert!(
            matches!(dom.root.get_node_type(), NodeType::Div),
            "the group is a div"
        );
        assert!(dom.root.has_class("__azul-native-segmented"));
        assert!(
            dom.root.get_callbacks().as_ref().is_empty(),
            "the container itself is not clickable"
        );
        let children = dom.children.as_ref();
        assert_eq!(children.len(), case.len());
        for (i, child) in children.iter().enumerate() {
            assert_eq!(
                text_of(child),
                Some(case[i]),
                "segment {i} shows the wrong caption"
            );
            assert!(
                child.root.has_class("__azul-native-segmented-item"),
                "segment {i} lost its class"
            );
        }
    }
    #[test]
    fn dom_of_an_empty_control_is_a_childless_container() {
        // `count == 0` must not underflow `i + 1 == count` or emit a stray child.
        let dom = Segmented::create(StringVec::from_const_slice(&[])).dom();
        assert_eq!(dom.children.as_ref().len(), 0);
        assert_eq!(dom.estimated_total_children, 0);
        assert!(dom.root.has_class("__azul-native-segmented"));
        let styled = StyledDom::create_from_dom(dom);
        assert_eq!(
            styled.node_hierarchy.as_ref().len(),
            1,
            "just the container"
        );
    }
    #[test]
    fn dom_styles_each_segment_by_its_position_and_selection() {
        for n in [1usize, 2, 3, 5] {
            for selected in 0..n {
                let dom = Segmented::create(n_labels(n))
                    .with_selected_index(selected)
                    .dom();
                let children = dom.children.as_ref();
                assert_eq!(children.len(), n);
                for (i, child) in children.iter().enumerate() {
                    let expected =
                        properties(&build_segment_style(i == selected, i == 0, i + 1 == n));
                    assert_eq!(
                        inline_properties(child),
                        expected,
                        "n={n} selected={selected}: segment {i} carries the wrong style"
                    );
                }
            }
        }
    }
    #[test]
    fn dom_marks_exactly_one_segment_as_selected() {
        for n in [1usize, 2, 4] {
            for selected in 0..n {
                let dom = Segmented::create(n_labels(n))
                    .with_selected_index(selected)
                    .dom();
                let marked: Vec<usize> = dom
                    .children
                    .as_ref()
                    .iter()
                    .enumerate()
                    .filter(|(_, c)| {
                        inline_properties(c).iter().any(|p| {
                            matches!(
                            p, CssProperty::TextColor(t)
                                if t.get_property().map(|t| t.inner) == Some(SEG_SELECTED_TEXT))
                        })
                    })
                    .map(|(i, _)| i)
                    .collect();
                assert_eq!(marked, vec![selected], "n={n}: mutual exclusivity broken");
            }
        }
    }
    #[test]
    fn dom_with_an_out_of_range_selection_marks_nothing_and_does_not_panic() {
        // `set_selected_index` accepts any `usize`; rendering must degrade to
        // "nothing selected" rather than panicking or wrapping onto a real segment.
        let n = 3;
        for selected in [n, n + 1, 1_000, usize::MAX, usize::MAX - 1] {
            let dom = Segmented::create(n_labels(n))
                .with_selected_index(selected)
                .dom();
            assert_eq!(
                dom.children.as_ref().len(),
                n,
                "selected={selected}: child count changed"
            );
            for (i, child) in dom.children.as_ref().iter().enumerate() {
                let expected = properties(&build_segment_style(false, i == 0, i + 1 == n));
                assert_eq!(
                    inline_properties(child),
                    expected,
                    "selected={selected}: segment {i} must render unselected"
                );
            }
        }
    }
    #[test]
    fn dom_rounds_only_the_two_outer_segments() {
        let n = 4;
        let dom = Segmented::create(n_labels(n)).dom();
        let r = SEG_RADIUS as f32;
        let radii_of = |child: &Dom| -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
            let props = inline_properties(child);
            let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| props.iter().find_map(f);
            (
                find(&|p| match p {
                    CssProperty::BorderTopLeftRadius(x) => x.get_property().map(|x| px(&x.inner)),
                    _ => None,
                }),
                find(&|p| match p {
                    CssProperty::BorderTopRightRadius(x) => x.get_property().map(|x| px(&x.inner)),
                    _ => None,
                }),
                find(&|p| match p {
                    CssProperty::BorderBottomLeftRadius(x) => {
                        x.get_property().map(|x| px(&x.inner))
                    }
                    _ => None,
                }),
                find(&|p| match p {
                    CssProperty::BorderBottomRightRadius(x) => {
                        x.get_property().map(|x| px(&x.inner))
                    }
                    _ => None,
                }),
            )
        };
        let children = dom.children.as_ref();
        assert_eq!(
            radii_of(&children[0]),
            (Some(r), None, Some(r), None),
            "first: left corners only"
        );
        assert_eq!(
            radii_of(&children[1]),
            (None, None, None, None),
            "interior segments are square"
        );
        assert_eq!(
            radii_of(&children[2]),
            (None, None, None, None),
            "interior segments are square"
        );
        assert_eq!(
            radii_of(&children[3]),
            (None, Some(r), None, Some(r)),
            "last: right corners only"
        );
    }
    #[test]
    fn dom_of_a_single_segment_is_rounded_on_both_ends() {
        let dom = Segmented::create(labels(&["only"])).dom();
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 1);
        let expected = properties(&build_segment_style(true, true, true));
        assert_eq!(
            inline_properties(&children[0]),
            expected,
            "a lone segment is simultaneously first and last"
        );
    }
    #[test]
    fn dom_makes_every_segment_clickable_and_keyboard_reachable() {
        let n = 3;
        let dom = Segmented::create(n_labels(n)).dom();
        for (i, child) in dom.children.as_ref().iter().enumerate() {
            let cbs = child.root.get_callbacks();
            assert_eq!(cbs.as_ref().len(), 1, "segment {i}: exactly one handler");
            assert_eq!(
                cbs.as_ref()[0].event,
                EventFilter::Hover(HoverEventFilter::Click)
            );
            assert_eq!(cbs.as_ref()[0].callback.cb, on_segment_click as usize);
            assert!(matches!(cbs.as_ref()[0].callback.ctx, OptionRefAny::None));
            assert_eq!(
                child.root.get_tab_index(),
                Some(TabIndex::Auto),
                "segment {i} must be tab-reachable"
            );
        }
    }
    #[test]
    fn dom_shares_one_state_refany_across_every_segment() {
        // The handler resolves the clicked index from the DOM, so all segments
        // *must* observe the same state — a per-segment copy would let two
        // segments believe they are both selected.
        let dom = Segmented::create(n_labels(4)).dom();
        let mut first = segment_state(&dom, 0);
        {
            let mut w = first
                .downcast_mut::<SegmentedStateWrapper>()
                .expect("segment state must be a SegmentedStateWrapper");
            w.inner.selected_index = 3;
        }
        for i in 1..4 {
            let mut other = segment_state(&dom, i);
            assert_eq!(
                selected_index_of(&mut other),
                3,
                "segment {i} does not share segment 0's state"
            );
        }
    }
    #[test]
    fn dom_carries_the_installed_callback_into_the_shared_state() {
        let dom = Segmented::create(labels(&["a", "b"]))
            .with_on_change(RefAny::new(0u8), change_cb(change_refresh_all))
            .dom();
        let mut state = segment_state(&dom, 0);
        let wrapper = state
            .downcast_ref::<SegmentedStateWrapper>()
            .expect("SegmentedStateWrapper");
        let installed = wrapper
            .on_change
            .as_ref()
            .expect("the user callback must reach the DOM");
        assert_eq!(installed.callback.cb as usize, change_refresh_all as usize);
    }
    #[test]
    fn dom_preserves_adversarial_labels_verbatim() {
        for s in adversarial_strings() {
            let dom = Segmented::create(labels(&[s.as_str(), "other"])).dom();
            let children = dom.children.as_ref();
            assert_eq!(children.len(), 2);
            match children[0].children.as_ref() {
                [only] => match only.root.get_node_type() {
                    NodeType::Text(t) => {
                        assert_eq!(
                            t.as_ref().as_str(),
                            s.as_str(),
                            "the caption changed inside dom()"
                        );
                        assert_eq!(
                            t.as_ref().len(),
                            s.len(),
                            "byte length changed (NUL truncation?)"
                        );
                    }
                    other => panic!("expected a text node, got {other:?}"),
                },
                other => panic!("expected `p > text`, got {} children", other.len()),
            }
        }
    }
    #[test]
    fn dom_keeps_estimated_total_children_in_sync() {
        // `estimated_total_children` is a cached count; if it under-counts,
        // `convert_dom_into_compact_dom` under-allocates and panics.
        for n in [0usize, 1, 2, 3, 5, 64, 257] {
            let dom = Segmented::create(n_labels(n)).dom();
            assert_eq!(dom.children.as_ref().len(), n, "child count for n={n}");
            assert_eq!(
                dom.estimated_total_children,
                recursive_descendants(&dom),
                "cached descendant count desynced for n={n}"
            );
            assert_eq!(
                dom.estimated_total_children,
                2 * n,
                "for n={n} (each segment is a <p> wrapping one text node)"
            );
        }
    }
    #[test]
    fn dom_of_many_segments_flattens_without_panicking() {
        let n = 512;
        let styled = StyledDom::create_from_dom(Segmented::create(n_labels(n)).dom());
        assert_eq!(
            styled.node_hierarchy.as_ref().len(),
            2 * n + 1,
            "root + n segments, each a <p> wrapping one text node"
        );
    }
    #[test]
    fn dom_via_from_matches_dom_exactly() {
        let build = || Segmented::create(n_labels(3)).with_selected_index(1);
        let via_into: Dom = build().into();
        let via_dom = build().dom();
        assert_eq!(
            via_into.children.as_ref().len(),
            via_dom.children.as_ref().len()
        );
        assert_eq!(
            via_into.estimated_total_children,
            via_dom.estimated_total_children
        );
        for i in 0..via_dom.children.as_ref().len() {
            assert_eq!(
                inline_properties(&via_into.children.as_ref()[i]),
                inline_properties(&via_dom.children.as_ref()[i]),
                "`From` diverges from `dom()` at segment {i}"
            );
            assert_eq!(
                text_of(&via_into.children.as_ref()[i]),
                text_of(&via_dom.children.as_ref()[i])
            );
        }
    }
    #[test]
    fn dom_with_duplicate_labels_still_produces_distinct_positional_segments() {
        // Selection is positional, not by caption: three identical captions must
        // still give exactly one selected segment, at the requested position.
        let dom = Segmented::create(labels(&["same", "same", "same"]))
            .with_selected_index(1)
            .dom();
        let children = dom.children.as_ref();
        for (i, child) in children.iter().enumerate() {
            assert_eq!(text_of(child), Some("same"));
            let expected = properties(&build_segment_style(i == 1, i == 0, i == 2));
            assert_eq!(inline_properties(child), expected, "segment {i}");
        }
    }
    // ------------------------------------------------------------------
    // on_segment_click
    // ------------------------------------------------------------------
    #[test]
    fn click_selects_the_segment_at_the_clicked_position() {
        let n = 4;
        let (styled, state) = flatten(Segmented::create(n_labels(n)));
        assert_eq!(
            styled.node_hierarchy.as_ref().len(),
            2 * n + 1,
            "fixture: root + n segments, each a <p> wrapping one text node"
        );
        for i in 0..n {
            let mut state = state.clone();
            let (update, changes) = run_click(Some(styled.clone()), seg_node(i), state.clone());
            assert_eq!(
                update,
                Update::DoNothing,
                "with no on_change installed the handler reports nothing to redraw"
            );
            assert_eq!(
                selected_index_of(&mut state),
                i,
                "node {} must select segment {i}",
                seg_node(i)
            );
            assert_eq!(
                restyle_writes(&changes).len(),
                2 * n,
                "every segment must be restyled"
            );
        }
    }
    #[test]
    fn click_restyle_agrees_with_a_freshly_built_style() {
        // The live restyle and a full rebuild must not drift apart, or a click
        // followed by a `RefreshDom` would visibly change the widget twice.
        let n = 4;
        let (styled, state) = flatten(Segmented::create(n_labels(n)));
        for clicked in 0..n {
            let (_, changes) = run_click(Some(styled.clone()), seg_node(clicked), state.clone());
            let writes = restyle_writes(&changes);
            assert_eq!(writes.len(), 2 * n);
            for i in 0..n {
                let fresh = build_segment_style(i == clicked, i == 0, i + 1 == n);
                assert_eq!(
                    writes[2 * i],
                    (
                        seg_node(i),
                        "bg",
                        background_color(&fresh).expect("background")
                    ),
                    "clicked={clicked}: segment {i} background"
                );
                assert_eq!(
                    writes[2 * i + 1],
                    (
                        seg_node(i),
                        "text",
                        text_color(&fresh).expect("text colour")
                    ),
                    "clicked={clicked}: segment {i} text colour"
                );
            }
        }
    }
    #[test]
    fn click_invokes_the_user_callback_with_the_updated_state() {
        let mut log = RefAny::new(IndexLog { seen: Vec::new() });
        let seg =
            Segmented::create(n_labels(4)).with_on_change(log.clone(), change_cb(record_index));
        let (styled, state) = flatten(seg);
        let (update, changes) = run_click(Some(styled.clone()), seg_node(2), state.clone());
        assert_eq!(
            update,
            Update::RefreshDom,
            "the user's Update must propagate"
        );
        assert_eq!(
            log_indices(&mut log),
            vec![2],
            "the callback sees the *new* index"
        );
        assert_eq!(
            restyle_writes(&changes).len(),
            8,
            "the restyle must still run"
        );
        // A second click updates the shared state again — the index is not sticky.
        let (_, _) = run_click(Some(styled), seg_node(0), state.clone());
        assert_eq!(log_indices(&mut log), vec![2, 0]);
        let mut state = state;
        assert_eq!(
            selected_index_of(&mut state),
            0,
            "the state holds the *last* clicked index"
        );
    }
    #[test]
    fn click_propagates_every_update_variant_unchanged() {
        for (cb, expected) in [
            (change_cb(change_do_nothing), Update::DoNothing),
            (change_cb(change_refresh_all), Update::RefreshDomAllWindows),
        ] {
            let seg = Segmented::create(labels(&["a", "b"])).with_on_change(RefAny::new(0u8), cb);
            let (styled, state) = flatten(seg);
            let (update, changes) = run_click(Some(styled), seg_node(1), state);
            assert_eq!(update, expected);
            assert_eq!(
                restyle_writes(&changes).len(),
                4,
                "the restyle runs regardless of what the user returns"
            );
        }
    }
    #[test]
    fn click_restyles_even_without_a_user_callback() {
        let (styled, state) = flatten(Segmented::create(labels(&["a", "b"])));
        let (update, changes) = run_click(Some(styled), seg_node(0), state);
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            restyle_writes(&changes),
            vec![
                (seg_node(0), "bg", SEG_SELECTED_BG_COLOR),
                (seg_node(0), "text", SEG_SELECTED_TEXT),
                (seg_node(1), "bg", SEG_UNSELECTED_BG_COLOR),
                (seg_node(1), "text", SEG_UNSELECTED_TEXT),
            ],
            "selection feedback must not depend on the user wiring a callback"
        );
    }
    #[test]
    fn click_on_a_single_segment_control_stays_at_zero() {
        let (styled, state) = flatten(Segmented::create(labels(&["only"])));
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), seg_node(0), state);
        assert_eq!(update, Update::DoNothing);
        assert_eq!(selected_index_of(&mut probe), 0);
        assert_eq!(
            restyle_writes(&changes),
            vec![
                (seg_node(0), "bg", SEG_SELECTED_BG_COLOR),
                (seg_node(0), "text", SEG_SELECTED_TEXT)
            ]
        );
    }
    #[test]
    fn click_on_the_root_node_does_nothing() {
        // The container has no parent -> the handler must bail, not index into nothing.
        let (styled, state) = flatten(Segmented::create(labels(&["a", "b"])));
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), 0, state);
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "nothing may be restyled when the click is not on a segment"
        );
        assert_eq!(selected_index_of(&mut probe), 0, "state must be untouched");
    }
    #[test]
    fn click_on_an_out_of_range_node_does_nothing() {
        let (styled, state) = flatten(Segmented::create(labels(&["a", "b"])));
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), 9999, state);
        assert_eq!(
            update,
            Update::DoNothing,
            "a hit node outside the tree must not panic"
        );
        assert!(changes.is_empty());
        assert_eq!(selected_index_of(&mut probe), 0);
    }
    #[test]
    fn click_with_no_layout_result_does_nothing() {
        let dom = Segmented::create(labels(&["a", "b"])).dom();
        let state = segment_state(&dom, 0);
        let (update, changes) = run_click(None, 1, state);
        assert_eq!(
            update,
            Update::DoNothing,
            "an empty LayoutWindow must be handled, not unwrapped"
        );
        assert!(changes.is_empty());
    }
    #[test]
    fn click_with_a_foreign_payload_does_nothing() {
        // Wrong type in the RefAny: the downcast fails, so the handler must bail
        // *before* restyling — otherwise the DOM would show a selection the state
        // never recorded.
        let (styled, _) = flatten(Segmented::create(labels(&["a", "b"])));
        let (update, changes) = run_click(Some(styled), 1, RefAny::new(0u32));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a failed downcast must not leave a half-applied restyle"
        );
    }
    #[test]
    fn click_with_the_state_already_borrowed_does_nothing() {
        let (styled, state) = flatten(Segmented::create(labels(&["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::<SegmentedStateWrapper>()
            .expect("first borrow succeeds");
        let (update, changes) = run_click(Some(styled), 1, state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        drop(guard);
    }
    #[test]
    fn click_holds_the_state_borrow_across_the_user_callback() {
        // The handler invokes the user callback while its own `downcast_mut` on
        // the state is still live. A user callback that re-enters the *same*
        // state `RefAny` is therefore refused — it must get `None` back rather
        // than a second aliasing borrow (or a panic).
        //
        // NOTE: probe <-> state form a RefAny reference cycle, so this fixture
        // leaks. That is deliberate and harmless for a single test.
        let mut probe = RefAny::new(ReentrantProbe {
            state: RefAny::new(0u8),
            saw_index: Some(usize::MAX),
            calls: 0,
        });
        let state = RefAny::new(SegmentedStateWrapper {
            inner: SegmentedState { selected_index: 0 },
            on_change: Some(SegmentedOnChange {
                callback: change_cb(probe_state_reentrantly),
                refany: probe.clone(),
            })
            .into(),
        });
        {
            let mut p = probe
                .downcast_mut::<ReentrantProbe>()
                .expect("ReentrantProbe");
            p.state = state.clone();
        }
        let styled = StyledDom::create_from_dom(Segmented::create(labels(&["a", "b"])).dom());
        let (update, changes) = run_click(Some(styled), seg_node(1), state.clone());
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            restyle_writes(&changes).len(),
            4,
            "the restyle must still run afterwards"
        );
        let p = probe
            .downcast_ref::<ReentrantProbe>()
            .expect("ReentrantProbe");
        assert_eq!(p.calls, 1, "the user callback must have run exactly once");
        assert_eq!(
            p.saw_index, None,
            "a re-entrant read of the state must be refused, not aliased"
        );
    }
    #[test]
    fn click_indices_stay_within_the_label_count() {
        // The index is derived from the sibling position, so it can never address
        // past the last rendered segment however many there are.
        let n = 128;
        let (styled, state) = flatten(Segmented::create(n_labels(n)));
        for i in [0usize, 1, n / 2 - 1, n - 2, n - 1] {
            let mut probe = state.clone();
            let (_, changes) = run_click(Some(styled.clone()), seg_node(i), state.clone());
            let idx = selected_index_of(&mut probe);
            assert_eq!(idx, i, "node {} sits at sibling position {i}", seg_node(i));
            assert!(
                idx < n,
                "the reported index must always address a real label"
            );
            assert_eq!(restyle_writes(&changes).len(), 2 * n);
        }
    }
    #[test]
    fn click_recovers_a_state_left_out_of_range_by_the_setter() {
        // `set_selected_index(usize::MAX)` renders nothing selected; the first
        // click must snap the state back to a real, in-range segment.
        let seg = Segmented::create(n_labels(3)).with_selected_index(usize::MAX);
        let (styled, state) = flatten(seg);
        let mut probe = state.clone();
        let (_, changes) = run_click(Some(styled), seg_node(1), state);
        assert_eq!(selected_index_of(&mut probe), 1);
        assert_eq!(
            restyle_writes(&changes),
            vec![
                (seg_node(0), "bg", SEG_UNSELECTED_BG_COLOR),
                (seg_node(0), "text", SEG_UNSELECTED_TEXT),
                (seg_node(1), "bg", SEG_SELECTED_BG_COLOR),
                (seg_node(1), "text", SEG_SELECTED_TEXT),
                (seg_node(2), "bg", SEG_UNSELECTED_BG_COLOR),
                (seg_node(2), "text", SEG_UNSELECTED_TEXT),
            ]
        );
    }
}