1
//! Combobox widget — an editable text field with a click-toggled drop-down list
2
//! of options. A blend of [`crate::widgets::drop_down::DropDown`] (the list of
3
//! options + click-to-select-by-index + `on_select` callback) and
4
//! [`crate::widgets::text_input::TextInput`] (the editable text field on top: the
5
//! user may type a free value, with `get_text_changeset` insertion + backspace
6
//! deletion). The open/close show-hide mirrors
7
//! [`crate::widgets::popover::Popover`] (an absolutely-positioned panel toggled
8
//! via `set_css_property(display)`), but the panel here holds a list of clickable
9
//! options rather than a single native menu popup.
10
//!
11
//! Structure: a `position: relative` wrapper containing a focusable *input field*
12
//! (a text node + a drop-down arrow) followed by an absolutely-positioned
13
//! *options list*, hidden by default (`display: none`). A single shared
14
//! [`RefAny`] holding the [`ComboBoxStateWrapper`] is attached to every callback
15
//! (the field's toggle/text-input/key-down handlers and each option's click
16
//! handler) so all of them read and mutate the *same* state — clicking the field
17
//! flips `open` and shows/hides the list; clicking an option fills the field with
18
//! the option's label (`change_node_text`), sets `selected`, closes the list, and
19
//! invokes the optional user `on_select(state)` with the new [`ComboBoxState`].
20
//! The clicked option's index is derived from its position (counting previous
21
//! siblings), exactly like the index-by-position approach used elsewhere.
22
//!
23
//! TODO2 — type-to-filter is NOT implemented. Live "filter-as-you-type" requires
24
//! the option list to be RE-RENDERED (a DOM rebuild) from the typed text on every
25
//! keystroke. Azul widget handlers can only patch *live* state through
26
//! `info.set_css_property` / `info.change_node_text` (show/hide/restyle/retext an
27
//! existing node) — they cannot add/remove DOM nodes, so the visible option set
28
//! cannot be re-filtered from a handler with the tools the other widgets use. The
29
//! field is therefore genuinely *editable* (you can type a free value, which is
30
//! reported in [`ComboBoxState::text`]), and selecting from the *full* list works
31
//! — but the list does not shrink as you type. A future revision could rebuild
32
//! the list via a full relayout (`Update::RefreshDom`) driven by a user callback
33
//! that owns the items, once that is runtime-verifiable.
34
//!
35
//! TODO2 — like [`Popover`], the list is placed at a fixed offset below the field
36
//! (it does not measure the field's height, flip near a screen edge, escape an
37
//! `overflow: hidden` ancestor, or raise its z-order — it relies on being the
38
//! later sibling to paint on top). There is no click-outside / blur dismissal
39
//! (closing on focus-lost races the option click and could swallow the
40
//! selection); the list closes on selection or on clicking the field again.
41
//!
42
//! Key types: [`ComboBox`], [`ComboBoxState`], [`ComboBoxOnSelect`].
43

            
44
use alloc::{string::String, vec::Vec};
45

            
46
use azul_core::{
47
    callbacks::{CoreCallback, CoreCallbackData, Update},
48
    dom::{
49
        ComponentEventFilter, Dom, DomVec, EventFilter, FocusEventFilter, HoverEventFilter,
50
        IdOrClass, IdOrClass::Class, IdOrClassVec, NodeData, NodeType, TabIndex,
51
    },
52
    refany::{OptionRefAny, RefAny},
53
    transient::{TransientAnchor, TransientDismiss, TransientWindowConfig},
54
    window::VirtualKeyCode,
55
};
56
use azul_css::{
57
    dynamic_selector::{
58
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
59
    },
60
    impl_option_inner,
61
    props::{
62
        basic::{
63
            color::ColorU,
64
            font::{StyleFontFamily, StyleFontFamilyVec},
65
            StyleFontSize,
66
        },
67
        layout::{
68
            LayoutAlignItems, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow, LayoutLeft,
69
            LayoutMinWidth, LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight,
70
            LayoutPaddingTop, LayoutPosition, LayoutTop,
71
        },
72
        property::{CssProperty, *},
73
        style::{
74
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
75
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
76
            StyleBorderBottomColor, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius,
77
            StyleBorderBottomStyle, StyleBorderLeftColor, StyleBorderLeftStyle,
78
            StyleBorderRightColor, StyleBorderRightStyle, StyleBorderTopColor,
79
            StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderTopStyle, StyleCursor,
80
            StyleTextAlign, StyleTextColor, StyleUserSelect,
81
        },
82
    },
83
    AzString, OptionString, StringVec,
84
};
85

            
86
use crate::callbacks::{Callback, CallbackInfo};
87

            
88
static COMBOBOX_WRAPPER_CLASS: &[IdOrClass] =
89
    &[Class(AzString::from_const_str("__azul-native-combobox"))];
90
static COMBOBOX_INPUT_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
91
    "__azul-native-combobox-input",
92
))];
93
static COMBOBOX_TEXT_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
94
    "__azul-native-combobox-text",
95
))];
96
static COMBOBOX_ARROW_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
97
    "__azul-native-combobox-arrow",
98
))];
99
static COMBOBOX_LIST_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
100
    "__azul-native-combobox-list",
101
))];
102
static COMBOBOX_OPTION_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
103
    "__azul-native-combobox-option",
104
))];
105

            
106
const SYSTEM_UI_STR: AzString = AzString::from_const_str("system:ui");
107
const SYSTEM_UI_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SYSTEM_UI_STR)];
108
const SYSTEM_UI_FAMILY: StyleFontFamilyVec =
109
    StyleFontFamilyVec::from_const_slice(SYSTEM_UI_FAMILIES);
110

            
111
// ---- layout (logical px) ----
112
/// Fixed vertical offset of the list below the wrapper's top edge (a
113
/// simplification - see the module-level `TODO2`; the field is ~26px tall).
114
const LIST_OFFSET_Y: isize = 28;
115
/// Minimum width of the field and the list.
116
const MIN_WIDTH: isize = 160;
117
const RADIUS: isize = 4;
118
const ARROW_FONT_SIZE_PX: isize = 18;
119

            
120
// ---- colours ----
121
const WHITE: ColorU = ColorU {
122
    r: 255,
123
    g: 255,
124
    b: 255,
125
    a: 255,
126
};
127
const BORDER_COLOR: ColorU = ColorU {
128
    r: 172,
129
    g: 172,
130
    b: 172,
131
    a: 255,
132
}; // #acacac
133
const TEXT_COLOR: ColorU = ColorU {
134
    r: 51,
135
    g: 51,
136
    b: 51,
137
    a: 255,
138
}; // #333333
139

            
140
const WHITE_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(WHITE)];
141
const WHITE_BG_VEC: StyleBackgroundContentVec =
142
    StyleBackgroundContentVec::from_const_slice(WHITE_BG_ITEMS);
143

            
144
/// Callback invoked when an option is chosen. The [`ComboBoxState`] carries the
145
/// new `selected` index and the field `text` (set to the chosen label).
146
pub type ComboBoxOnSelectCallbackType =
147
    extern "C" fn(RefAny, CallbackInfo, ComboBoxState) -> Update;
148
impl_widget_callback!(
149
    ComboBoxOnSelect,
150
    OptionComboBoxOnSelect,
151
    ComboBoxOnSelectCallback,
152
    ComboBoxOnSelectCallbackType
153
);
154

            
155
azul_core::impl_managed_callback! {
156
    wrapper:        ComboBoxOnSelectCallback,
157
    info_ty:        CallbackInfo,
158
    return_ty:      Update,
159
    default_ret:    Update::DoNothing,
160
    invoker_static: COMBOBOX_ON_SELECT_INVOKER,
161
    invoker_ty:     AzComboBoxOnSelectCallbackInvoker,
162
    thunk_fn:       az_combobox_on_select_callback_thunk,
163
    setter_fn:      AzApp_setComboBoxOnSelectCallbackInvoker,
164
    from_handle_fn: AzComboBoxOnSelectCallback_createFromHostHandle,
165
    extra_args:     [ state: ComboBoxState ],
166
}
167

            
168
/// An editable filtered-select widget: a text field plus a click-toggled list of
169
/// options.
170
#[derive(Debug, Clone, PartialEq, Eq)]
171
#[repr(C)]
172
pub struct ComboBox {
173
    /// Runtime state (`open`/`selected`/`text`) plus the item list and the
174
    /// optional select callback.
175
    pub combo_state: ComboBoxStateWrapper,
176
    /// Greyed text shown in the field when no value has been typed/selected.
177
    pub placeholder: AzString,
178
    /// Style of the outer wrapper (the `position: relative` context), or `None`
179
    /// for "no opinion" — in which case the widget's default applies.
180
    ///
181
    /// `None` and `Some(empty)` are different answers: the first means the
182
    /// widget picks, the second means the caller asked for no properties at all
183
    /// and gets none.
184
    pub wrapper_style: OptionCssPropertyWithConditionsVec,
185
    /// Style of the clickable, focusable, editable input field, or `None` for
186
    /// "no opinion" — in which case the widget's default applies.
187
    ///
188
    /// `None` and `Some(empty)` are different answers: the first means the
189
    /// widget picks, the second means the caller asked for no properties at all
190
    /// and gets none.
191
    pub field_style: OptionCssPropertyWithConditionsVec,
192
    /// Style of the text inside the field, or `None` for "no opinion" — in which
193
    /// case the widget's default applies.
194
    ///
195
    /// `None` and `Some(empty)` are different answers: the first means the
196
    /// widget picks, the second means the caller asked for no properties at all
197
    /// and gets none.
198
    pub text_style: OptionCssPropertyWithConditionsVec,
199
    /// Style of the drop-down arrow icon on the right of the field, or `None` for
200
    /// "no opinion" — in which case the widget's default applies.
201
    ///
202
    /// `None` and `Some(empty)` are different answers: the first means the
203
    /// widget picks, the second means the caller asked for no properties at all
204
    /// and gets none.
205
    pub arrow_style: OptionCssPropertyWithConditionsVec,
206
    /// Style of each option row inside the list panel, or `None` for "no opinion"
207
    /// — in which case the widget's default applies.
208
    ///
209
    /// `None` and `Some(empty)` are different answers: the first means the
210
    /// widget picks, the second means the caller asked for no properties at all
211
    /// and gets none.
212
    pub option_style: OptionCssPropertyWithConditionsVec,
213
    /// EXTRA properties appended to the options-list panel style, or `None` for
214
    /// "no extras". The open/close `display` toggle stays widget-managed;
215
    /// anything here wins over it (inline properties resolve last-wins).
216
    ///
217
    /// The one field on this widget where `Some` MERGES rather than replaces:
218
    /// the panel's `display` is what opens and closes the list, so a caller
219
    /// cannot be allowed to drop it. An empty vec used to mean "no extras",
220
    /// which is why this needed the option most — the widget could not tell a
221
    /// caller asking for nothing from a caller who had not spoken.
222
    pub list_style: OptionCssPropertyWithConditionsVec,
223
    /// What this control is CALLED, for assistive technology.
224
    ///
225
    /// Carried by the WIDGET so it knows at build time whether it was named;
226
    /// forwarded into the accessibility declaration it already builds.
227
    pub accessibility_name: OptionString,
228
}
229

            
230
#[derive(Debug, Clone, PartialEq, Eq)]
231
#[repr(C)]
232
pub struct ComboBoxStateWrapper {
233
    /// The mutable per-interaction state passed to `on_select`.
234
    pub inner: ComboBoxState,
235
    /// The full set of selectable options (rendered into the list).
236
    pub items: StringVec,
237
    /// Optional: function to call when an option is selected.
238
    pub on_select: OptionComboBoxOnSelect,
239
}
240

            
241
impl Default for ComboBoxStateWrapper {
242
    fn default() -> Self {
243
        Self {
244
            inner: ComboBoxState::default(),
245
            items: StringVec::from_const_slice(&[]),
246
            on_select: None.into(),
247
        }
248
    }
249
}
250

            
251
/// The live state of a [`ComboBox`]: whether the list is open, the currently
252
/// selected index, and the current (editable) field text.
253
#[derive(Debug, Clone, PartialEq, Eq)]
254
#[repr(C)]
255
pub struct ComboBoxState {
256
    /// `true` = list shown, `false` (default) = list hidden.
257
    pub open: bool,
258
    /// Zero-based index of the most recently selected option.
259
    pub selected: usize,
260
    /// The current text shown in the field (typed or set from a selection).
261
    pub text: AzString,
262
}
263

            
264
impl Default for ComboBoxState {
265
107
    fn default() -> Self {
266
107
        Self {
267
107
            open: false,
268
107
            selected: 0,
269
107
            text: AzString::from_const_str(""),
270
107
        }
271
107
    }
272
}
273

            
274
// ---- styles ----
275

            
276
/// Wrapper: an inline-block positioning context so the absolutely-positioned list
277
/// is placed relative to it.
278
static COMBOBOX_WRAPPER_STYLE: &[CssPropertyWithConditions] = &[
279
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::InlineBlock)),
280
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
281
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
282
    CssPropertyWithConditions::simple(CssProperty::const_min_width(LayoutMinWidth::const_px(
283
        MIN_WIDTH,
284
    ))),
285
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(13))),
286
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SYSTEM_UI_FAMILY)),
287
];
288

            
289
/// The clickable, focusable, editable input field (text + arrow).
290
static COMBOBOX_INPUT_STYLE: &[CssPropertyWithConditions] = &[
291
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
292
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
293
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
294
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
295
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Text)),
296
    // padding: 3px 4px
297
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
298
        3,
299
    ))),
300
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
301
        LayoutPaddingBottom::const_px(3),
302
    )),
303
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
304
        LayoutPaddingLeft::const_px(4),
305
    )),
306
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
307
        LayoutPaddingRight::const_px(4),
308
    )),
309
    // border: 1px solid #acacac
310
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
311
        LayoutBorderTopWidth::const_px(1),
312
    )),
313
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
314
        LayoutBorderBottomWidth::const_px(1),
315
    )),
316
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
317
        LayoutBorderLeftWidth::const_px(1),
318
    )),
319
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
320
        LayoutBorderRightWidth::const_px(1),
321
    )),
322
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
323
        inner: BorderStyle::Solid,
324
    })),
325
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
326
        StyleBorderBottomStyle {
327
            inner: BorderStyle::Solid,
328
        },
329
    )),
330
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
331
        inner: BorderStyle::Solid,
332
    })),
333
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
334
        StyleBorderRightStyle {
335
            inner: BorderStyle::Solid,
336
        },
337
    )),
338
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
339
        inner: BORDER_COLOR,
340
    })),
341
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
342
        StyleBorderBottomColor {
343
            inner: BORDER_COLOR,
344
        },
345
    )),
346
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
347
        inner: BORDER_COLOR,
348
    })),
349
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
350
        StyleBorderRightColor {
351
            inner: BORDER_COLOR,
352
        },
353
    )),
354
    // border-radius: 4px
355
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
356
        StyleBorderTopLeftRadius::const_px(RADIUS),
357
    )),
358
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
359
        StyleBorderTopRightRadius::const_px(RADIUS),
360
    )),
361
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
362
        StyleBorderBottomLeftRadius::const_px(RADIUS),
363
    )),
364
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
365
        StyleBorderBottomRightRadius::const_px(RADIUS),
366
    )),
367
    CssPropertyWithConditions::simple(CssProperty::const_background_content(WHITE_BG_VEC)),
368
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
369
        inner: TEXT_COLOR,
370
    })),
371
    // Focus ring, light and dark. Declared in the theme module — see
372
    // `themes::flat::FOCUS_BORDER_TOP` — because the dark half needs the
373
    // palette's `DARK_ACC`, which this file cannot see. All four edges, because
374
    // a ring that sets only some leaves the rest at their resting colour.
375
    crate::widgets::themes::flat::FOCUS_BORDER_TOP,
376
    crate::widgets::themes::flat::FOCUS_BORDER_BOTTOM,
377
    crate::widgets::themes::flat::FOCUS_BORDER_LEFT,
378
    crate::widgets::themes::flat::FOCUS_BORDER_RIGHT,
379
    crate::widgets::themes::flat::FOCUS_BORDER_TOP_DARK,
380
    crate::widgets::themes::flat::FOCUS_BORDER_BOTTOM_DARK,
381
    crate::widgets::themes::flat::FOCUS_BORDER_LEFT_DARK,
382
    crate::widgets::themes::flat::FOCUS_BORDER_RIGHT_DARK,
383
];
384

            
385
/// The editable text inside the field - takes the remaining horizontal space.
386
static COMBOBOX_TEXT_STYLE: &[CssPropertyWithConditions] = &[
387
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
388
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
389
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
390
        LayoutPaddingRight::const_px(4),
391
    )),
392
];
393

            
394
/// The drop-down arrow icon on the right of the field.
395
static COMBOBOX_ARROW_STYLE: &[CssPropertyWithConditions] = &[
396
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
397
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
398
        ARROW_FONT_SIZE_PX,
399
    ))),
400
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
401
];
402

            
403
/// Builds the options-list panel style.
404
///
405
/// The list lives inside a `<transient-window>` — a REAL OS popup — so it is
406
/// laid out at the origin of its own window, NOT absolutely-positioned inside
407
/// the parent DOM. It used to be an `position: absolute` sibling toggled with
408
/// `set_css_property(display)`, which is why it collided with everything
409
/// painted after it: an in-DOM panel is bound by its stacking context and
410
/// clipped by the window, so no z-index could lift it above later siblings.
411
/// The popup window has no such ceiling.
412
///
413
/// `open` therefore no longer selects `display` — the WINDOW opens and closes —
414
/// but the parameter stays so the caller keeps one entry point, and the panel
415
/// is explicitly `display: block` in both states.
416
71
fn build_list_style(_open: bool) -> CssPropertyWithConditionsVec {
417
71
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
418
71
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
419
71
        CssPropertyWithConditions::simple(CssProperty::const_min_width(LayoutMinWidth::const_px(
420
            MIN_WIDTH,
421
        ))),
422
        // border: 1px solid #acacac
423
71
        CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
424
71
            LayoutBorderTopWidth::const_px(1),
425
        )),
426
71
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
427
71
            LayoutBorderBottomWidth::const_px(1),
428
        )),
429
71
        CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
430
71
            LayoutBorderLeftWidth::const_px(1),
431
        )),
432
71
        CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
433
71
            LayoutBorderRightWidth::const_px(1),
434
        )),
435
71
        CssPropertyWithConditions::simple(CssProperty::const_border_top_style(
436
71
            StyleBorderTopStyle {
437
71
                inner: BorderStyle::Solid,
438
71
            }
439
        )),
440
71
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
441
71
            StyleBorderBottomStyle {
442
71
                inner: BorderStyle::Solid,
443
71
            },
444
        )),
445
71
        CssPropertyWithConditions::simple(CssProperty::const_border_left_style(
446
71
            StyleBorderLeftStyle {
447
71
                inner: BorderStyle::Solid,
448
71
            }
449
        )),
450
71
        CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
451
71
            StyleBorderRightStyle {
452
71
                inner: BorderStyle::Solid,
453
71
            },
454
        )),
455
71
        CssPropertyWithConditions::simple(CssProperty::const_border_top_color(
456
71
            StyleBorderTopColor {
457
71
                inner: BORDER_COLOR,
458
71
            }
459
        )),
460
71
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
461
71
            StyleBorderBottomColor {
462
71
                inner: BORDER_COLOR,
463
71
            },
464
        )),
465
71
        CssPropertyWithConditions::simple(CssProperty::const_border_left_color(
466
71
            StyleBorderLeftColor {
467
71
                inner: BORDER_COLOR,
468
71
            }
469
        )),
470
71
        CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
471
71
            StyleBorderRightColor {
472
71
                inner: BORDER_COLOR,
473
71
            },
474
        )),
475
        // border-radius: 4px
476
71
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
477
71
            StyleBorderBottomLeftRadius::const_px(RADIUS),
478
        )),
479
71
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
480
71
            StyleBorderBottomRightRadius::const_px(RADIUS),
481
        )),
482
71
        CssPropertyWithConditions::simple(CssProperty::const_background_content(WHITE_BG_VEC)),
483
    ])
484
71
}
485

            
486
/// Per-option row style: a padded, pointer-cursor block highlighted on hover.
487
static COMBOBOX_OPTION_STYLE: &[CssPropertyWithConditions] = &[
488
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
489
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
490
        6,
491
    ))),
492
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
493
        LayoutPaddingBottom::const_px(6),
494
    )),
495
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
496
        LayoutPaddingLeft::const_px(10),
497
    )),
498
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
499
        LayoutPaddingRight::const_px(10),
500
    )),
501
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
502
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
503
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
504
        inner: TEXT_COLOR,
505
    })),
506
    // Option-row hover, light and dark — see `themes::flat::OPTION_HOVER`.
507
    crate::widgets::themes::flat::OPTION_HOVER,
508
    crate::widgets::themes::flat::OPTION_HOVER_DARK,
509
];
510

            
511
impl ComboBox {
512
    /// Creates a new combobox with the given options (no callback, nothing typed).
513
    /// Name this control for assistive technology.
514
    #[must_use]
515
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
516
        self.accessibility_name = Some(name.into()).into();
517
        self
518
    }
519

            
520
    #[must_use]
521
103
    pub fn new(items: StringVec) -> Self {
522
103
        Self {
523
103
            combo_state: ComboBoxStateWrapper {
524
103
                inner: ComboBoxState::default(),
525
103
                items,
526
103
                on_select: None.into(),
527
103
            },
528
103
            placeholder: AzString::from_const_str(""),
529
103
            wrapper_style: OptionCssPropertyWithConditionsVec::None,
530
103
            field_style: OptionCssPropertyWithConditionsVec::None,
531
103
            text_style: OptionCssPropertyWithConditionsVec::None,
532
103
            arrow_style: OptionCssPropertyWithConditionsVec::None,
533
103
            option_style: OptionCssPropertyWithConditionsVec::None,
534
103
            list_style: OptionCssPropertyWithConditionsVec::None,
535
103
            accessibility_name: OptionString::None,
536
103
        }
537
103
    }
538

            
539
    /// Creates an empty combobox.
540
    #[must_use]
541
25
    pub fn create() -> Self {
542
25
        Self::new(StringVec::from_const_slice(&[]))
543
25
    }
544

            
545
    /// Sets the initially-selected option index.
546
    #[inline]
547
20
    pub const fn set_selected(&mut self, selected: usize) {
548
20
        self.combo_state.inner.selected = selected;
549
20
    }
550

            
551
    /// Builder-style setter for the initially-selected index.
552
    #[inline]
553
    #[must_use]
554
8
    pub const fn with_selected(mut self, selected: usize) -> Self {
555
8
        self.set_selected(selected);
556
8
        self
557
8
    }
558

            
559
    /// Sets the initial (editable) field text.
560
    #[inline]
561
18
    pub fn set_text(&mut self, text: AzString) {
562
18
        self.combo_state.inner.text = text;
563
18
    }
564

            
565
    /// Builder-style setter for the initial field text.
566
    #[inline]
567
    #[must_use]
568
9
    pub fn with_text(mut self, text: AzString) -> Self {
569
9
        self.set_text(text);
570
9
        self
571
9
    }
572

            
573
    /// Sets the greyed placeholder shown when the field is empty.
574
    #[inline]
575
8
    pub fn set_placeholder(&mut self, placeholder: AzString) {
576
8
        self.placeholder = placeholder;
577
8
    }
578

            
579
    /// Builder-style setter for the placeholder.
580
    #[inline]
581
    #[must_use]
582
7
    pub fn with_placeholder(mut self, placeholder: AzString) -> Self {
583
7
        self.set_placeholder(placeholder);
584
7
        self
585
7
    }
586

            
587
    /// Sets the callback invoked when an option is selected.
588
    #[inline]
589
5
    pub fn set_on_select<C: Into<ComboBoxOnSelectCallback>>(&mut self, data: RefAny, on_select: C) {
590
5
        self.combo_state.on_select = Some(ComboBoxOnSelect {
591
5
            callback: on_select.into(),
592
5
            refany: data,
593
5
        })
594
5
        .into();
595
5
    }
596

            
597
    /// Builder-style setter for the select callback.
598
    #[inline]
599
    #[must_use]
600
2
    pub fn with_on_select<C: Into<ComboBoxOnSelectCallback>>(
601
2
        mut self,
602
2
        data: RefAny,
603
2
        on_select: C,
604
2
    ) -> Self {
605
2
        self.set_on_select(data, on_select);
606
2
        self
607
2
    }
608

            
609
    /// The wrapper CSS this combobox renders with.
610
    ///
611
    /// `None` means no opinion, so the widget's default applies — the same
612
    /// answer both themes give, asked in one place so they cannot drift. The
613
    /// five resolvers below follow the same rule.
614
    #[must_use]
615
64
    pub fn resolved_wrapper_style(&self) -> CssPropertyWithConditionsVec {
616
64
        self.wrapper_style.clone().into_option().unwrap_or_else(|| {
617
63
            CssPropertyWithConditionsVec::from_const_slice(COMBOBOX_WRAPPER_STYLE)
618
63
        })
619
64
    }
620

            
621
    /// The input-field CSS this combobox renders with.
622
    #[must_use]
623
66
    pub fn resolved_field_style(&self) -> CssPropertyWithConditionsVec {
624
66
        self.field_style
625
66
            .clone()
626
66
            .into_option()
627
66
            .unwrap_or_else(|| CssPropertyWithConditionsVec::from_const_slice(COMBOBOX_INPUT_STYLE))
628
66
    }
629

            
630
    /// The field-text CSS this combobox renders with.
631
    #[must_use]
632
63
    pub fn resolved_text_style(&self) -> CssPropertyWithConditionsVec {
633
63
        self.text_style
634
63
            .clone()
635
63
            .into_option()
636
63
            .unwrap_or_else(|| CssPropertyWithConditionsVec::from_const_slice(COMBOBOX_TEXT_STYLE))
637
63
    }
638

            
639
    /// The arrow CSS this combobox renders with.
640
    #[must_use]
641
63
    pub fn resolved_arrow_style(&self) -> CssPropertyWithConditionsVec {
642
63
        self.arrow_style
643
63
            .clone()
644
63
            .into_option()
645
63
            .unwrap_or_else(|| CssPropertyWithConditionsVec::from_const_slice(COMBOBOX_ARROW_STYLE))
646
63
    }
647

            
648
    /// The option-row CSS this combobox renders with.
649
    #[must_use]
650
63
    pub fn resolved_option_style(&self) -> CssPropertyWithConditionsVec {
651
63
        self.option_style.clone().into_option().unwrap_or_else(|| {
652
63
            CssPropertyWithConditionsVec::from_const_slice(COMBOBOX_OPTION_STYLE)
653
63
        })
654
63
    }
655

            
656
    /// The panel CSS this combobox renders with: the widget's own open/closed
657
    /// `display` toggle, with the caller's extras appended so they win.
658
    ///
659
    /// Unlike the others this MERGES rather than replaces — see
660
    /// [`Self::list_style`]. `None` and `Some(empty)` therefore resolve alike
661
    /// here, but they still say different things, and only one of them survives
662
    /// a caller asking a second time.
663
    #[must_use]
664
63
    pub fn resolved_list_style(&self, open: bool) -> CssPropertyWithConditionsVec {
665
63
        let base = build_list_style(open);
666
63
        match self.list_style.as_ref() {
667
63
            None => base,
668
            Some(extra) => {
669
                let mut merged = base.into_library_owned_vec();
670
                merged.extend(extra.as_ref().iter().cloned());
671
                CssPropertyWithConditionsVec::from_vec(merged)
672
            }
673
        }
674
63
    }
675

            
676
    /// Replaces `self` with a default (empty) combobox and returns the original.
677
    #[inline]
678
    #[must_use]
679
2
    pub fn swap_with_default(&mut self) -> Self {
680
2
        let mut s = Self::create();
681
2
        core::mem::swap(&mut s, self);
682
2
        s
683
2
    }
684

            
685
    /// Renders the combobox into a [`Dom`] subtree with the `__azul-native-combobox`
686
    /// class.
687
    #[must_use]
688
63
    pub fn dom(self) -> Dom {
689
        // Initial field text: the typed/selected text if present, else the
690
        // placeholder (a simplification — there is no separate placeholder node,
691
        // so the placeholder is just the initial label and is replaced on the
692
        // first keystroke or selection).
693
63
        let field_text = if self.combo_state.inner.text.as_str().is_empty() {
694
59
            self.placeholder.clone()
695
        } else {
696
4
            self.combo_state.inner.text.clone()
697
        };
698

            
699
63
        let open = self.combo_state.inner.open;
700
63
        let items = self.combo_state.items.clone();
701

            
702
        // Resolved before `self.combo_state` is moved into the shared RefAny
703
        // below; the resolvers borrow `&self`.
704
63
        let wrapper_style = self.resolved_wrapper_style();
705
63
        let field_style = self.resolved_field_style();
706
63
        let text_style = self.resolved_text_style();
707
63
        let arrow_style = self.resolved_arrow_style();
708
63
        let option_style = self.resolved_option_style();
709
63
        let list_style = self.resolved_list_style(open);
710

            
711
        // ONE shared RefAny: the field handlers and every option handler all
712
        // read/mutate the same ComboBoxStateWrapper (the text_input shared-state
713
        // pattern), so open/selected/text stay in sync across interactions.
714
63
        let state_ref = RefAny::new(self.combo_state);
715

            
716
63
        let text_node = crate::widgets::widget_p_with_text(field_text)
717
63
            .with_ids_and_classes(IdOrClassVec::from_const_slice(COMBOBOX_TEXT_CLASS))
718
63
            .with_css_props(text_style);
719

            
720
63
        let arrow = Dom::create_icon(AzString::from_const_str("arrow_drop_down"))
721
63
            .with_ids_and_classes(IdOrClassVec::from_const_slice(COMBOBOX_ARROW_CLASS))
722
63
            .with_css_props(arrow_style);
723

            
724
        // The focusable, editable input field. Clicking it toggles the list
725
        // (Hover::MouseUp) and focuses it; typing edits the text node
726
        // (Focus::TextInput / VirtualKeyDown), mirroring text_input.
727
63
        let field = Dom::create_div()
728
63
            .with_ids_and_classes(IdOrClassVec::from_const_slice(COMBOBOX_INPUT_CLASS))
729
63
            .with_css_props(field_style)
730
63
            .with_tab_index(TabIndex::Auto)
731
            // The field itself: an editable value with a list of choices.
732
63
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
733
63
                role: azul_core::a11y::AccessibilityRole::ComboBox,
734
63
                ..Default::default()
735
63
            })
736
63
            .with_callbacks(
737
63
                alloc::vec![
738
63
                    CoreCallbackData {
739
63
                        event: EventFilter::Hover(HoverEventFilter::Click),
740
63
                        callback: CoreCallback {
741
63
                            cb: on_combobox_toggle as usize,
742
63
                            ctx: OptionRefAny::None,
743
63
                        },
744
63
                        refany: state_ref.clone(),
745
63
                    },
746
63
                    CoreCallbackData {
747
63
                        event: EventFilter::Focus(FocusEventFilter::TextInput),
748
63
                        callback: CoreCallback {
749
63
                            cb: on_combobox_text_input as usize,
750
63
                            ctx: OptionRefAny::None,
751
63
                        },
752
63
                        refany: state_ref.clone(),
753
63
                    },
754
63
                    CoreCallbackData {
755
63
                        event: EventFilter::Focus(FocusEventFilter::VirtualKeyDown),
756
63
                        callback: CoreCallback {
757
63
                            cb: on_combobox_key_down as usize,
758
63
                            ctx: OptionRefAny::None,
759
63
                        },
760
63
                        refany: state_ref.clone(),
761
63
                    },
762
                ]
763
63
                .into(),
764
            )
765
63
            .with_children(DomVec::from_vec(alloc::vec![text_node, arrow]));
766

            
767
        // Build the option rows. Each carries a CLONE of the shared state so its
768
        // click handler can mutate selected/open and read the chosen label.
769
63
        let mut option_doms: Vec<Dom> = Vec::with_capacity(items.as_ref().len());
770
794
        for option in items.as_ref() {
771
794
            option_doms.push(
772
794
                crate::widgets::widget_p_with_text(option.clone())
773
794
                    .with_ids_and_classes(IdOrClassVec::from_const_slice(COMBOBOX_OPTION_CLASS))
774
794
                    .with_css_props(option_style.clone())
775
794
                    .with_tab_index(TabIndex::Auto)
776
794
                    // Each option is an item within the popup list.
777
794
                    .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
778
794
                        role: azul_core::a11y::AccessibilityRole::ListItem,
779
794
                        ..Default::default()
780
794
                    })
781
794
                    .with_callbacks(
782
794
                        alloc::vec![CoreCallbackData {
783
794
                            event: EventFilter::Hover(HoverEventFilter::Click),
784
794
                            callback: CoreCallback {
785
794
                                cb: on_combobox_option_click as usize,
786
794
                                ctx: OptionRefAny::None,
787
794
                            },
788
794
                            refany: state_ref.clone(),
789
794
                        }]
790
794
                        .into(),
791
794
                    ),
792
794
            );
793
794
        }
794

            
795
63
        let list = Dom::create_div()
796
63
            .with_ids_and_classes(IdOrClassVec::from_const_slice(COMBOBOX_LIST_CLASS))
797
63
            .with_css_props(list_style)
798
63
            .with_children(DomVec::from_vec(option_doms));
799

            
800
        // The list is a REAL OS popup anchored under the field, not an
801
        // absolutely-positioned sibling: an in-DOM panel is trapped in its
802
        // stacking context and clipped by the window, so the old one was
803
        // painted under later siblings and cut off at the window edge. The
804
        // popup dismisses itself on an outside click; `Dismissed` syncs the
805
        // widget's own `open` flag so the next field click still toggles
806
        // correctly (without it the state says "open" and the click closes
807
        // nothing).
808
63
        let mut transient = NodeData::create_node(NodeType::TransientWindow(
809
63
            TransientWindowConfig::closed()
810
63
                .with_anchor(TransientAnchor::Bottom)
811
63
                .with_dismiss(TransientDismiss::Outside),
812
63
        ));
813
63
        transient.add_callback(
814
63
            EventFilter::Component(ComponentEventFilter::Dismissed),
815
63
            state_ref,
816
63
            Callback::from_ptr(on_combobox_dismissed).to_core(),
817
        );
818
63
        let popup = Dom::create_from_data(transient).with_child(list);
819

            
820
63
        Dom::create_div()
821
63
            .with_ids_and_classes(IdOrClassVec::from_const_slice(COMBOBOX_WRAPPER_CLASS))
822
63
            .with_css_props(wrapper_style)
823
            // children: [field, popup] — the popup (holding the list) is the
824
            // field's next sibling, so `get_next_sibling(field)` still names it.
825
63
            .with_children(DomVec::from_vec(alloc::vec![field, popup]))
826
63
    }
827
}
828

            
829
impl Default for ComboBox {
830
1
    fn default() -> Self {
831
1
        Self::create()
832
1
    }
833
}
834

            
835
/// Field click handler. The hit node is the field; its next sibling is the
836
/// `<transient-window>` holding the list. Flips `open` and opens/closes that
837
/// popup WINDOW (it used to toggle `display` on an in-DOM panel, which could
838
/// never escape its stacking context).
839
6
extern "C" fn on_combobox_toggle(mut data: RefAny, mut info: CallbackInfo) -> Update {
840
6
    let field = info.get_hit_node();
841
6
    let Some(popup) = info.get_next_sibling(field) else {
842
3
        return Update::DoNothing;
843
    };
844

            
845
2
    let now_open = {
846
3
        let Some(mut combo) = data.downcast_mut::<ComboBoxStateWrapper>() else {
847
1
            return Update::DoNothing;
848
        };
849
2
        combo.inner.open = !combo.inner.open;
850
2
        combo.inner.open
851
    };
852

            
853
2
    info.set_transient_window_open(popup, now_open);
854

            
855
2
    Update::DoNothing
856
6
}
857

            
858
/// The popup dismissed itself (outside click / Escape / an option was picked
859
/// INSIDE the popup window). Clear `open` so the widget's flag matches reality —
860
/// otherwise the next field click would "toggle off" an already-closed list and
861
/// the user would have to click twice.
862
///
863
/// This runs in the PARENT window (the `Dismissed` lifecycle event targets the
864
/// `<transient-window>` node in the parent dom), so it is the one place a
865
/// selection made inside the popup WINDOW can reach the parent's field node:
866
/// [`on_combobox_option_click`] wrote the chosen label into the shared state but
867
/// could not address the field from the popup's dom — apply it here. For a plain
868
/// outside-click dismissal the state text is whatever the field already shows,
869
/// so the write is a no-op (and an empty text is skipped so a never-touched
870
/// field keeps its placeholder).
871
2
extern "C" fn on_combobox_dismissed(mut data: RefAny, mut info: CallbackInfo) -> Update {
872
2
    let text = {
873
2
        let Some(mut combo) = data.downcast_mut::<ComboBoxStateWrapper>() else {
874
            return Update::DoNothing;
875
        };
876
2
        combo.inner.open = false;
877
2
        let text = combo.inner.text.clone();
878
2
        if text.as_str().is_empty() {
879
1
            None
880
        } else {
881
1
            Some(text)
882
        }
883
    };
884

            
885
    // popup (= the event's target, the <transient-window> node) -> wrapper ->
886
    // field -> label <p> -> text leaf, all in the parent dom.
887
2
    if let Some(text) = text {
888
1
        let popup = info.get_hit_node();
889
1
        if let Some(wrapper) = info.get_parent(popup) {
890
1
            if let Some(field) = info.get_first_child(wrapper) {
891
1
                if let Some(text_box) = info.get_first_child(field) {
892
1
                    if let Some(text_node) = info.get_first_child(text_box) {
893
1
                        info.change_node_text(text_node, text);
894
1
                    }
895
                }
896
            }
897
        }
898
1
    }
899
2
    Update::DoNothing
900
2
}
901

            
902
/// Field text-input handler - appends the typed character(s) to the editable
903
/// field text (mirroring `text_input`). Does NOT re-filter the list (see the
904
/// module-level type-to-filter `TODO2`).
905
11
extern "C" fn on_combobox_text_input(data: RefAny, info: CallbackInfo) -> Update {
906
11
    on_combobox_text_input_inner(data, info).unwrap_or(Update::DoNothing)
907
11
}
908

            
909
13
fn on_combobox_text_input_inner(mut data: RefAny, mut info: CallbackInfo) -> Option<Update> {
910
13
    let field = info.get_hit_node();
911
    // field -> label `<p>` -> bare text leaf: the label convention keeps the
912
    // styling on the block box, so the re-textable node is one level deeper.
913
13
    let text_node = info.get_first_child(info.get_first_child(field)?)?;
914

            
915
12
    let changeset = info.get_text_changeset()?;
916
10
    let inserted_text = changeset.inserted_text.as_str().to_string();
917
10
    if inserted_text.is_empty() {
918
1
        return None;
919
9
    }
920

            
921
8
    let new_text = {
922
9
        let mut combo = data.downcast_mut::<ComboBoxStateWrapper>()?;
923
8
        let mut s: String = combo.inner.text.as_str().into();
924
8
        s.push_str(&inserted_text);
925
8
        combo.inner.text = s.clone().into();
926
8
        s
927
    };
928

            
929
8
    info.change_node_text(text_node, new_text.into());
930
8
    Some(Update::DoNothing)
931
13
}
932

            
933
/// Field key-down handler - implements backspace deletion (mirroring `text_input`).
934
13
extern "C" fn on_combobox_key_down(data: RefAny, info: CallbackInfo) -> Update {
935
13
    on_combobox_key_down_inner(data, info).unwrap_or(Update::DoNothing)
936
13
}
937

            
938
15
fn on_combobox_key_down_inner(mut data: RefAny, mut info: CallbackInfo) -> Option<Update> {
939
15
    let field = info.get_hit_node();
940
    // field -> label `<p>` -> bare text leaf (see `on_combobox_text_input_inner`).
941
15
    let text_node = info.get_first_child(info.get_first_child(field)?)?;
942

            
943
14
    let keyboard_state = info.get_current_keyboard_state();
944
14
    let c = keyboard_state.current_virtual_keycode.into_option()?;
945
13
    if c != VirtualKeyCode::Back {
946
6
        return None;
947
7
    }
948

            
949
6
    let new_text = {
950
7
        let mut combo = data.downcast_mut::<ComboBoxStateWrapper>()?;
951
6
        let mut s: String = combo.inner.text.as_str().into();
952
6
        s.pop();
953
6
        combo.inner.text = s.clone().into();
954
6
        s
955
    };
956

            
957
6
    info.change_node_text(text_node, new_text.into());
958
6
    Some(Update::DoNothing)
959
15
}
960

            
961
/// Option click handler. The hit node is the clicked option's `<p>`; its index is
962
/// the number of previous siblings. Fills the field with the option's label, sets
963
/// `selected`, closes the list, and invokes the optional user callback.
964
///
965
/// RUNS IN TWO DIFFERENT DOMS. The options list lives in a `<transient-window>`,
966
/// so on a device this callback fires inside the POPUP's own window, whose DOM is
967
/// the extracted subtree: `root div (the former transient node) > list > options`.
968
/// The wrapper / field / label ancestors DO NOT EXIST there — the old
969
/// walk-all-the-way-up version bailed out at `get_parent(popup) == None` and a
970
/// click on an option did nothing at all. In a harness (or an inline-docked
971
/// panel) the same callback runs against the PARENT dom, where the full chain
972
/// exists. Every step below therefore works from the two ancestors both doms
973
/// share (list, and the node above it), does the state + `on_select` work first,
974
/// and treats the field re-text as best-effort:
975
///
976
///   * parent dom: `popup` is the `<transient-window>` node — closing it releases the engine's
977
///     forced-open latch, and the field text is written directly;
978
///   * popup dom: `popup` is the popup's ROOT — `set_transient_window_open(false)` on it is
979
///     recognised by the shell as "this popup dismisses itself" (it posts `dismissed` to the
980
///     parent's mailbox and closes the window), and the parent applies the field text in its
981
///     `Dismissed` handler, where the parent's field node is addressable
982
///     ([`on_combobox_dismissed`]).
983
16
extern "C" fn on_combobox_option_click(mut data: RefAny, mut info: CallbackInfo) -> Update {
984
16
    let option = info.get_hit_node();
985

            
986
    // index = number of previous siblings.
987
16
    let mut index = 0usize;
988
16
    let mut cursor = option;
989
228
    while let Some(prev) = info.get_previous_sibling(cursor) {
990
212
        index += 1;
991
212
        cursor = prev;
992
212
    }
993

            
994
    // option -> list -> popup. Both exist in the parent dom (popup = the
995
    // `<transient-window>` node) AND in the popup window's dom (popup = root).
996
16
    let Some(list) = info.get_parent(option) else {
997
2
        return Update::DoNothing;
998
    };
999
14
    let Some(popup) = info.get_parent(list) else {
        return Update::DoNothing;
    };
    // State + user callback BEFORE any DOM write, so an `items.get(index)` miss
    // still aborts without a partial write.
11
    let (label, result) = {
14
        let Some(mut combo) = data.downcast_mut::<ComboBoxStateWrapper>() else {
1
            return Update::DoNothing;
        };
13
        let Some(label) = combo.items.as_ref().get(index).cloned() else {
2
            return Update::DoNothing;
        };
11
        combo.inner.selected = index;
11
        combo.inner.text = label.clone();
11
        combo.inner.open = false;
11
        let inner = combo.inner.clone();
11
        let combo = &mut *combo;
11
        let result = match combo.on_select.as_mut() {
3
            Some(ComboBoxOnSelect { callback, refany }) => {
3
                (callback.cb)(refany.clone(), info, inner)
            }
8
            None => Update::DoNothing,
        };
11
        (label, result)
    };
    // Close the popup WINDOW (or, inside it, dismiss ourselves — see above).
11
    info.set_transient_window_open(popup, false);
    // Fill the field with the chosen label — only reachable from the parent dom.
    // Inside the popup this walk stops at `get_parent(root) == None` and the
    // parent's `Dismissed` handler writes the text instead.
11
    if let Some(wrapper) = info.get_parent(popup) {
10
        if let Some(field) = info.get_first_child(wrapper) {
10
            if let Some(text_box) = info.get_first_child(field) {
10
                if let Some(text_node) = info.get_first_child(text_box) {
10
                    info.change_node_text(text_node, label);
10
                }
            }
        }
1
    }
11
    result
16
}
impl From<ComboBox> for Dom {
1
    fn from(c: ComboBox) -> Self {
1
        c.dom()
1
    }
}
#[cfg(all(test, feature = "std"))]
#[allow(clippy::too_many_lines)]
// `redundant_closure`: NOT redundant here. `run()` takes
// `impl FnOnce(RefAny, CallbackInfo) -> R`; `CallbackInfo` carries an elided
// lifetime, so the bound is higher-ranked (`for<'a> FnOnce(_, CallbackInfo<'a>)`).
// The handlers are `extern "C" fn` items, which do NOT satisfy a higher-ranked
// `FnOnce` bound — passing one bare fails to compile with E0277. The `|r, ci| f(r, ci)`
// wrapper is what makes the coercion happen and must stay.
#[allow(clippy::redundant_closure)]
mod autotest_generated {
    use std::{
        cell::{Cell, RefCell},
        collections::{BTreeMap, HashMap},
        sync::{Arc, Mutex},
    };
    use azul_core::{
        dom::{DomId, DomNodeId, NodeId, NodeType},
        geom::{LogicalRect, OptionLogicalPosition},
        gl::OptionGlContextPtr,
        hit_test::ScrollPosition,
        resources::RendererResources,
        styled_dom::{NodeHierarchyItemId, StyledDom},
        window::{MonitorVec, RawWindowHandle},
    };
    use azul_css::system::SystemStyle;
    use rust_fontconfig::FcFontCache;
    use super::*;
    #[cfg(feature = "icu")]
    use crate::icu::IcuLocalizerHandle;
    use crate::{
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
        managers::text_input::PendingTextEdit,
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
        window::{DomLayoutResult, LayoutWindow},
        window_state::FullWindowState,
    };
    // ------------------------------------------------------------------
    // Fixtures / helpers
    // ------------------------------------------------------------------
    /// A `StringVec` of options from string literals.
    fn sv(items: &[&str]) -> StringVec {
        StringVec::from_vec(items.iter().map(|s| AzString::from(*s)).collect())
    }
    /// True if `node` carries the CSS class `name`.
    fn has_class(node: &Dom, name: &str) -> bool {
        node.root
            .get_ids_and_classes()
            .as_ref()
            .iter()
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
    }
    /// The text of a text node, looking through the `<p>` block wrapper the
    /// label convention mandates (`p > text`).
    fn text_of(node: &Dom) -> Option<&str> {
        match node.root.get_node_type() {
            NodeType::Text(s) => Some(s.as_ref().as_str()),
            NodeType::P => match node.children.as_ref() {
                [only] => match only.root.get_node_type() {
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
                    _ => None,
                },
                _ => None,
            },
            _ => None,
        }
    }
    /// The icon name of a `NodeType::Icon` node.
    fn icon_of(node: &Dom) -> Option<&str> {
        match node.root.get_node_type() {
            NodeType::Icon(s) => Some(s.as_ref().as_str()),
            _ => None,
        }
    }
    /// The `display` value in a node's *inline* style, if it sets one.
    fn inline_display(node: &Dom) -> Option<LayoutDisplay> {
        node.root
            .style
            .iter_inline_properties()
            .find_map(|(p, _)| match p {
                CssProperty::Display(v) => v.get_property().copied(),
                _ => None,
            })
    }
    /// The `display` declared in a built style vec.
    fn display_of(props: &CssPropertyWithConditionsVec) -> Option<LayoutDisplay> {
        props.as_ref().iter().find_map(|p| match &p.property {
            CssProperty::Display(v) => v.get_property().copied(),
            _ => None,
        })
    }
    /// The `position` declared in a built style vec.
    fn position_of(props: &CssPropertyWithConditionsVec) -> Option<LayoutPosition> {
        props.as_ref().iter().find_map(|p| match &p.property {
            CssProperty::Position(v) => v.get_property().copied(),
            _ => None,
        })
    }
    /// `(field, list)` of a rendered combobox DOM.
    /// `(field, list)`, descending THROUGH the `<transient-window>`.
    ///
    /// A combobox is `[field, <transient-window> > list]`: the options list is a
    /// real OS popup, not an absolutely-positioned sibling, so the list is the
    /// popup's only child rather than the wrapper's second child.
    fn parts(dom: &Dom) -> (&Dom, &Dom) {
        let children = dom.children.as_ref();
        assert_eq!(
            children.len(),
            2,
            "a combobox is exactly [field, <transient-window>]"
        );
        let popup = &children[1];
        assert!(
            matches!(popup.root.get_node_type(), NodeType::TransientWindow(_)),
            "the list must live in a <transient-window> so it can escape the parent's stacking \
             context and the window bounds",
        );
        let popup_children = popup.children.as_ref();
        assert_eq!(
            popup_children.len(),
            1,
            "the popup holds exactly the options list"
        );
        (&children[0], &popup_children[0])
    }
    /// The `<transient-window>` node itself (the wrapper's second child).
    fn popup_of(dom: &Dom) -> &Dom {
        &dom.children.as_ref()[1]
    }
    /// Flattened indices of every node carrying `class`, in tree order. Used
    /// instead of hard-coded indices so the tests do not encode the DOM
    /// flattening order.
    fn nodes_with_class(styled: &StyledDom, class: &str) -> Vec<usize> {
        styled
            .node_data
            .as_ref()
            .iter()
            .enumerate()
            .filter(|(_, nd)| {
                nd.get_ids_and_classes()
                    .as_ref()
                    .iter()
                    .any(|c| matches!(c, Class(s) if s.as_str() == class))
            })
            .map(|(i, _)| i)
            .collect()
    }
    /// A styled `ComboBox::new(items).dom()` plus the flattened index of every
    /// node the handlers navigate to.
    struct Fixture {
        styled: StyledDom,
        wrapper: usize,
        field: usize,
        text: usize,
        /// The `<transient-window>` node — what the handlers open/close.
        popup: usize,
        list: usize,
        options: Vec<usize>,
    }
    fn fixture(items: &[&str]) -> Fixture {
        let styled = StyledDom::create_from_dom(ComboBox::new(sv(items)).dom());
        fn one(styled: &StyledDom, class: &str) -> usize {
            let found = nodes_with_class(styled, class);
            assert_eq!(found.len(), 1, "expected exactly one `{class}` node");
            found[0]
        }
        let wrapper = one(&styled, "__azul-native-combobox");
        let field = one(&styled, "__azul-native-combobox-input");
        // The class sits on the label `<p>`; the node the handlers re-text is
        // the bare text leaf inside it, which pre-order flattening puts next.
        let text_box = one(&styled, "__azul-native-combobox-text");
        let text = text_box + 1;
        assert!(
            matches!(
                styled.node_data.as_ref()[text].get_node_type(),
                NodeType::Text(_)
            ),
            "the combobox field label must be `p > text`"
        );
        let list = one(&styled, "__azul-native-combobox-list");
        // The popup is the list's PARENT: pre-order flattening puts the
        // `<transient-window>` immediately before the list it wraps.
        let popup = list - 1;
        assert!(
            matches!(
                styled.node_data.as_ref()[popup].get_node_type(),
                NodeType::TransientWindow(_)
            ),
            "the options list must be wrapped in a <transient-window>",
        );
        let options = nodes_with_class(&styled, "__azul-native-combobox-option");
        assert_eq!(options.len(), items.len());
        Fixture {
            styled,
            wrapper,
            field,
            text,
            popup,
            list,
            options,
        }
    }
    /// A `DomNodeId` in the root DOM pointing at flattened node `idx`.
    fn node(idx: usize) -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
        }
    }
    /// A `DomLayoutResult` with an *empty* layout tree: these handlers only walk
    /// `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes: Vec::new(),
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions: Vec::new(),
            viewport: LogicalRect::zero(),
            display_list: Arc::new(DisplayList::default()),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    /// Everything the combobox handlers read out of the window: the styled DOM
    /// they navigate, the pending text changeset, and the pressed key.
    #[derive(Default)]
    struct Env {
        styled: Option<StyledDom>,
        changeset: Option<PendingTextEdit>,
        keycode: Option<VirtualKeyCode>,
    }
    /// Invokes `call` against a `LayoutWindow` built from `env`, with `hit` as the
    /// hit node. Returns the handler's value plus every recorded `CallbackChange`.
    fn run<R>(
        env: Env,
        hit: usize,
        data: RefAny,
        call: impl FnOnce(RefAny, CallbackInfo) -> R,
    ) -> (R, Vec<CallbackChange>) {
        let mut layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        if let Some(sd) = env.styled {
            layout_window
                .layout_results
                .insert(DomId::ROOT_ID, layout_result(sd));
        }
        if let Some(changeset) = env.changeset {
            layout_window.text_input_manager.set_changeset(changeset);
        }
        let renderer_resources = RendererResources::default();
        let previous_window_state: Option<FullWindowState> = None;
        let mut current_window_state = FullWindowState::default();
        current_window_state.keyboard_state.current_virtual_keycode = env.keycode.into();
        let gl_context = OptionGlContextPtr::None;
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
            BTreeMap::new();
        let window_handle = RawWindowHandle::Unsupported;
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
        let ref_data = CallbackInfoRefData {
            layout_window: &layout_window,
            renderer_resources: &renderer_resources,
            previous_window_state: &previous_window_state,
            current_window_state: &current_window_state,
            gl_context: &gl_context,
            current_scroll_manager: &scroll_states,
            current_window_handle: &window_handle,
            system_callbacks: &system_callbacks,
            system_style: Arc::new(SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
        let info = CallbackInfo::new(
            &ref_data,
            &changes,
            node(hit),
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        let out = call(data, info);
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
        (out, recorded)
    }
    /// Every `display` write in the change log, as `(node index, display)`.
    /// Every `SetTransientWindowOpen` a handler pushed, as `(node, open)`.
    /// The open/close of the options list travels this way now — it used to be
    /// a `display` write on an in-DOM panel (see `display_writes`).
    fn transient_writes(changes: &[CallbackChange]) -> Vec<(usize, bool)> {
        changes
            .iter()
            .filter_map(|change| match change {
                CallbackChange::SetTransientWindowOpen { node, open } => {
                    Some((node.node.into_crate_internal()?.index(), *open))
                }
                _ => None,
            })
            .collect()
    }
    #[allow(dead_code)]
    fn display_writes(changes: &[CallbackChange]) -> Vec<(usize, LayoutDisplay)> {
        let mut out = Vec::new();
        for change in changes {
            if let CallbackChange::ChangeNodeCssProperties {
                node_id,
                properties,
                ..
            } = change
            {
                for p in properties.as_ref() {
                    if let CssProperty::Display(v) = p {
                        if let Some(d) = v.get_property() {
                            out.push((node_id.index(), *d));
                        }
                    }
                }
            }
        }
        out
    }
    /// Every text write in the change log, as `(node index, new text)`.
    fn text_writes(changes: &[CallbackChange]) -> Vec<(usize, String)> {
        changes
            .iter()
            .filter_map(|change| match change {
                CallbackChange::ChangeNodeText { node_id, text } => Some((
                    node_id
                        .node
                        .into_crate_internal()
                        .expect("a text write always targets a real node")
                        .index(),
                    text.as_str().to_string(),
                )),
                _ => None,
            })
            .collect()
    }
    /// A `ComboBoxStateWrapper` payload with no user callback.
    fn state(items: &[&str], text: &str, open: bool, selected: usize) -> RefAny {
        RefAny::new(ComboBoxStateWrapper {
            inner: ComboBoxState {
                open,
                selected,
                text: AzString::from(text),
            },
            items: sv(items),
            on_select: None.into(),
        })
    }
    /// Reads the (still shared) `ComboBoxState` back out of a payload.
    fn inner_of(data: &mut RefAny) -> ComboBoxState {
        data.downcast_ref::<ComboBoxStateWrapper>()
            .expect("payload must still be a ComboBoxStateWrapper")
            .inner
            .clone()
    }
    fn on_select_cb(f: ComboBoxOnSelectCallbackType) -> ComboBoxOnSelectCallback {
        f.into()
    }
    /// Records every `ComboBoxState` a user `on_select` was handed.
    struct SelectLog {
        calls: Vec<ComboBoxState>,
    }
    extern "C" fn record_select(mut data: RefAny, _: CallbackInfo, s: ComboBoxState) -> Update {
        if let Some(mut log) = data.downcast_mut::<SelectLog>() {
            log.calls.push(s);
        }
        Update::RefreshDom
    }
    extern "C" fn select_do_nothing(_: RefAny, _: CallbackInfo, _: ComboBoxState) -> Update {
        Update::DoNothing
    }
    thread_local! {
        /// A clone of the shared state handle, smuggled into `probe_reborrow`
        /// without building a self-referential `RefAny` cycle.
        static SHARED_ALIAS: RefCell<Option<RefAny>> = const { RefCell::new(None) };
        /// `Some(true)` once `probe_reborrow` has seen the re-borrow refused.
        static REBORROW_REFUSED: Cell<Option<bool>> = const { Cell::new(None) };
    }
    extern "C" fn probe_reborrow(_: RefAny, _: CallbackInfo, _: ComboBoxState) -> Update {
        let refused = SHARED_ALIAS.with(|alias| {
            alias
                .borrow_mut()
                .as_mut()
                .expect("alias installed by the test")
                .downcast_mut::<ComboBoxStateWrapper>()
                .is_none()
        });
        REBORROW_REFUSED.with(|c| c.set(Some(refused)));
        Update::DoNothing
    }
    // ------------------------------------------------------------------
    // build_list_style
    // ------------------------------------------------------------------
    /// The panel is ALWAYS visible and ALWAYS in normal flow.
    ///
    /// The list now lives inside a `<transient-window>` — a real OS popup — so
    /// the WINDOW opens and closes, not a `display` property, and the panel is
    /// laid out at its own window's origin rather than absolutely-positioned in
    /// the parent DOM. These replace four tests that asserted the opposite
    /// (display flips with `open`, `position: absolute` in both states); that
    /// design is exactly what made the list collide with later siblings and
    /// clip at the window edge, which is the bug this widget was changed to fix.
    #[test]
    fn build_list_style_is_open_state_independent() {
        let closed = build_list_style(false);
        let open = build_list_style(true);
        assert_eq!(
            closed, open,
            "the popup WINDOW carries the open/closed state; the panel style must not",
        );
    }
    #[test]
    fn build_list_style_is_always_displayed_and_never_absolutely_positioned() {
        for open in [false, true] {
            let props = build_list_style(open);
            assert_eq!(
                display_of(&props),
                Some(LayoutDisplay::Block),
                "open={open}: the panel fills its popup window and is always shown",
            );
            assert_ne!(
                position_of(&props),
                Some(LayoutPosition::Absolute),
                "open={open}: absolute positioning belonged to the old in-DOM panel; inside a \
                 popup window it would offset the list away from the window origin",
            );
        }
    }
    #[test]
    fn build_list_style_is_deterministic_and_unshared() {
        // Two calls must be equal, and neither may alias the other (it
        // allocates a fresh vec every call).
        assert_eq!(build_list_style(true), build_list_style(true));
        assert_eq!(build_list_style(false), build_list_style(false));
    }
    // ------------------------------------------------------------------
    // ComboBox::new / create / Default
    // ------------------------------------------------------------------
    #[test]
    fn new_stores_items_and_starts_at_documented_defaults() {
        let combo = ComboBox::new(sv(&["a", "b", "c"]));
        assert_eq!(combo.combo_state.items.as_ref().len(), 3);
        assert_eq!(combo.combo_state.items.as_ref()[2].as_str(), "c");
        assert_eq!(combo.combo_state.inner, ComboBoxState::default());
        assert!(!combo.combo_state.inner.open, "the list starts closed");
        assert_eq!(combo.combo_state.inner.selected, 0);
        assert!(combo.combo_state.inner.text.as_str().is_empty());
        assert!(combo.placeholder.as_str().is_empty());
        assert!(
            combo.combo_state.on_select.is_none(),
            "ComboBox::new sets no callback"
        );
    }
    #[test]
    fn new_survives_extreme_item_lists() {
        let long = "ab".repeat(50_000);
        let cases: Vec<Vec<AzString>> = alloc::vec![
            Vec::new(),
            alloc::vec![AzString::from("")],
            alloc::vec![AzString::from("a\0b"), AzString::from("")],
            alloc::vec![AzString::from("👨‍👩‍👧‍👦 e\u{0301}\u{0327} مرحبا שלום 🇩🇪")],
            alloc::vec![AzString::from("\u{feff}\u{202e}rtl-override")],
            alloc::vec![AzString::from(long.as_str())],
        ];
        for items in cases {
            let combo = ComboBox::new(StringVec::from_vec(items.clone()));
            assert_eq!(combo.combo_state.items.as_ref(), items.as_slice());
            // ...and every option survives the trip through the DOM byte-for-byte
            let dom = combo.dom();
            let (_, list) = parts(&dom);
            assert_eq!(list.children.as_ref().len(), items.len());
            for (i, item) in items.iter().enumerate() {
                assert_eq!(text_of(&list.children.as_ref()[i]), Some(item.as_str()));
            }
        }
    }
    #[test]
    fn new_handles_many_duplicate_items() {
        // Duplicates are legal: selection is by index, not by label.
        let items = sv(&["same"; 512]);
        let combo = ComboBox::new(items);
        assert_eq!(combo.combo_state.items.as_ref().len(), 512);
        let dom = combo.dom();
        let (_, list) = parts(&dom);
        assert_eq!(list.children.as_ref().len(), 512);
    }
    #[test]
    fn create_is_empty_and_equals_default() {
        let combo = ComboBox::create();
        assert!(combo.combo_state.items.as_ref().is_empty());
        assert!(combo.combo_state.on_select.is_none());
        assert_eq!(combo.combo_state.inner, ComboBoxState::default());
        assert_eq!(combo, ComboBox::default());
        // repeated calls are independent, equal values
        assert_eq!(ComboBox::create(), ComboBox::create());
    }
    // ------------------------------------------------------------------
    // set_selected / with_selected  (numeric)
    // ------------------------------------------------------------------
    #[test]
    fn set_selected_stores_every_index_verbatim() {
        // The setter is documented as a plain store: no clamping to items.len(),
        // no saturation, no wrap — assert exactly that at both ends of usize.
        for value in [0usize, 1, 2, usize::MAX - 1, usize::MAX] {
            let mut combo = ComboBox::new(sv(&["a", "b"]));
            combo.set_selected(value);
            assert_eq!(combo.combo_state.inner.selected, value);
            // nothing else moved
            assert!(!combo.combo_state.inner.open);
            assert!(combo.combo_state.inner.text.as_str().is_empty());
            assert_eq!(combo.combo_state.items.as_ref().len(), 2);
        }
    }
    #[test]
    fn set_selected_last_write_wins() {
        let mut combo = ComboBox::create();
        combo.set_selected(usize::MAX);
        combo.set_selected(0);
        assert_eq!(combo.combo_state.inner.selected, 0);
        combo.set_selected(7);
        combo.set_selected(7);
        assert_eq!(combo.combo_state.inner.selected, 7, "idempotent re-set");
    }
    #[test]
    fn with_selected_matches_set_selected() {
        for value in [0usize, 3, usize::MAX] {
            let built = ComboBox::new(sv(&["a"])).with_selected(value);
            let mut mutated = ComboBox::new(sv(&["a"]));
            mutated.set_selected(value);
            assert_eq!(built, mutated);
        }
    }
    #[test]
    fn out_of_range_selected_still_renders_without_panicking() {
        // `dom()` never indexes `items` by `selected`, so an out-of-range index
        // (including usize::MAX on an EMPTY item list) must render fine.
        for (items, selected) in [
            (alloc::vec![], usize::MAX),
            (alloc::vec!["a"], 99),
            (alloc::vec!["a", "b"], usize::MAX - 1),
        ] {
            let combo = ComboBox::new(sv(&items)).with_selected(selected);
            assert_eq!(combo.combo_state.inner.selected, selected);
            let dom = combo.dom();
            let (_, list) = parts(&dom);
            assert_eq!(list.children.as_ref().len(), items.len());
        }
    }
    // ------------------------------------------------------------------
    // set_text / with_text
    // ------------------------------------------------------------------
    #[test]
    fn set_text_stores_every_string_verbatim() {
        let long = "x".repeat(100_000);
        let cases = [
            "",
            " ",
            "a\0b",
            "line\nbreak\ttab",
            "👨‍👩‍👧‍👦 e\u{0301}\u{0327} مرحبا שלום 🇩🇪",
            "\u{feff}\u{202e}rtl",
            long.as_str(),
        ];
        for case in cases {
            let mut combo = ComboBox::create();
            combo.set_text(AzString::from(case));
            assert_eq!(combo.combo_state.inner.text.as_str(), case);
            assert_eq!(
                combo.combo_state.inner.text.as_str().len(),
                case.len(),
                "no truncation at the NUL or anywhere else"
            );
        }
    }
    #[test]
    fn with_text_matches_set_text_and_last_write_wins() {
        let built = ComboBox::create()
            .with_text("a".into())
            .with_text("b".into());
        let mut mutated = ComboBox::create();
        mutated.set_text("a".into());
        mutated.set_text("b".into());
        assert_eq!(built, mutated);
        assert_eq!(built.combo_state.inner.text.as_str(), "b");
    }
    // ------------------------------------------------------------------
    // set_placeholder / with_placeholder
    // ------------------------------------------------------------------
    #[test]
    fn set_placeholder_stores_verbatim_and_does_not_touch_text() {
        let mut combo = ComboBox::new(sv(&["a"]));
        combo.set_placeholder("Pick one…\u{0}".into());
        assert_eq!(combo.placeholder.as_str(), "Pick one…\u{0}");
        assert!(
            combo.combo_state.inner.text.as_str().is_empty(),
            "the placeholder is not the value"
        );
        let built = ComboBox::new(sv(&["a"])).with_placeholder("Pick one…\u{0}".into());
        assert_eq!(built, combo);
    }
    #[test]
    fn placeholder_is_the_field_label_only_while_text_is_empty() {
        // Documented simplification: there is no separate placeholder node, so the
        // field label is `text` if non-empty, else `placeholder`.
        let dom = ComboBox::create().with_placeholder("ph".into()).dom();
        let (field, _) = parts(&dom);
        assert_eq!(text_of(&field.children.as_ref()[0]), Some("ph"));
        // a single SPACE is non-empty, so it must win over the placeholder
        let spaced = ComboBox::create()
            .with_placeholder("ph".into())
            .with_text(" ".into());
        let dom = spaced.dom();
        let (field, _) = parts(&dom);
        assert_eq!(text_of(&field.children.as_ref()[0]), Some(" "));
        // ...and with no placeholder and no text the label is the empty string
        let bare = ComboBox::create().dom();
        let (field, _) = parts(&bare);
        assert_eq!(text_of(&field.children.as_ref()[0]), Some(""));
    }
    // ------------------------------------------------------------------
    // set_on_select / with_on_select
    // ------------------------------------------------------------------
    #[test]
    fn set_on_select_last_call_wins() {
        let mut combo = ComboBox::create();
        combo.set_on_select(RefAny::new(1u8), on_select_cb(select_do_nothing));
        assert!(combo.combo_state.on_select.is_some());
        // a second call must *replace* (not append / leak / panic)
        combo.set_on_select(RefAny::new(9i64), on_select_cb(record_select));
        let set = combo.combo_state.on_select.as_ref().expect("still Some");
        assert_eq!(set.refany.get_type_id(), RefAny::new(0i64).get_type_id());
        assert_eq!(set.callback, on_select_cb(record_select));
        assert_ne!(set.callback, on_select_cb(select_do_nothing));
    }
    #[test]
    fn with_on_select_matches_set_on_select() {
        let built = ComboBox::new(sv(&["a"]))
            .with_on_select(RefAny::new(7u32), on_select_cb(record_select));
        let mut mutated = ComboBox::new(sv(&["a"]));
        mutated.set_on_select(RefAny::new(7u32), on_select_cb(record_select));
        assert_eq!(
            built.combo_state.on_select.as_ref().unwrap().callback,
            mutated.combo_state.on_select.as_ref().unwrap().callback
        );
        // the builder form must not disturb the items or the state
        assert_eq!(built.combo_state.items.as_ref().len(), 1);
        assert_eq!(built.combo_state.inner, ComboBoxState::default());
    }
    // ------------------------------------------------------------------
    // swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_moves_all_state_out() {
        let mut combo = ComboBox::new(sv(&["a", "b"]))
            .with_selected(1)
            .with_text("typed".into())
            .with_placeholder("ph".into())
            .with_on_select(RefAny::new(5u8), on_select_cb(record_select));
        let original = combo.swap_with_default();
        assert_eq!(original.combo_state.items.as_ref().len(), 2);
        assert_eq!(original.combo_state.inner.selected, 1);
        assert_eq!(original.combo_state.inner.text.as_str(), "typed");
        assert_eq!(original.placeholder.as_str(), "ph");
        assert!(original.combo_state.on_select.is_some());
        assert_eq!(combo, ComboBox::create(), "self must be left empty");
        // swapping an already-empty combobox is a no-op, not a panic
        let second = combo.swap_with_default();
        assert_eq!(second, ComboBox::create());
        assert_eq!(combo, ComboBox::create());
    }
    // ------------------------------------------------------------------
    // ComboBox::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_of_empty_combobox_still_has_field_and_empty_list() {
        let dom = ComboBox::create().dom();
        assert!(has_class(&dom, "__azul-native-combobox"));
        let (field, list) = parts(&dom);
        assert!(has_class(field, "__azul-native-combobox-input"));
        assert!(has_class(list, "__azul-native-combobox-list"));
        assert!(
            list.children.as_ref().is_empty(),
            "no items -> no option rows"
        );
        // the field still has its text node + arrow
        assert_eq!(field.children.as_ref().len(), 2);
    }
    #[test]
    fn dom_structure_classes_and_callbacks() {
        let dom = ComboBox::new(sv(&["one", "two"])).dom();
        let (field, list) = parts(&dom);
        let text_node = &field.children.as_ref()[0];
        let arrow = &field.children.as_ref()[1];
        assert!(has_class(text_node, "__azul-native-combobox-text"));
        assert!(has_class(arrow, "__azul-native-combobox-arrow"));
        assert_eq!(icon_of(arrow), Some("arrow_drop_down"));
        // the field is focusable and wires exactly toggle / text-input / key-down
        assert!(matches!(field.root.get_tab_index(), Some(TabIndex::Auto)));
        let cbs = field.root.get_callbacks();
        assert_eq!(cbs.len(), 3);
        assert_eq!(
            cbs.as_ref()[0].event,
            EventFilter::Hover(HoverEventFilter::Click)
        );
        assert_eq!(cbs.as_ref()[0].callback.cb, on_combobox_toggle as usize);
        assert_eq!(
            cbs.as_ref()[1].event,
            EventFilter::Focus(FocusEventFilter::TextInput)
        );
        assert_eq!(cbs.as_ref()[1].callback.cb, on_combobox_text_input as usize);
        assert_eq!(
            cbs.as_ref()[2].event,
            EventFilter::Focus(FocusEventFilter::VirtualKeyDown)
        );
        assert_eq!(cbs.as_ref()[2].callback.cb, on_combobox_key_down as usize);
        // every option is focusable and carries exactly one click handler
        for (i, option) in list.children.as_ref().iter().enumerate() {
            assert!(has_class(option, "__azul-native-combobox-option"));
            assert_eq!(text_of(option), Some(["one", "two"][i]));
            assert!(matches!(option.root.get_tab_index(), Some(TabIndex::Auto)));
            let cbs = option.root.get_callbacks();
            assert_eq!(cbs.len(), 1);
            assert_eq!(
                cbs.as_ref()[0].event,
                EventFilter::Hover(HoverEventFilter::Click)
            );
            assert_eq!(
                cbs.as_ref()[0].callback.cb,
                on_combobox_option_click as usize
            );
        }
    }
    #[test]
    fn dom_list_is_always_displayed_inside_its_popup() {
        // The panel no longer hides itself — the popup WINDOW is what opens and
        // closes, so the list is `display: block` whatever `open` says. (It used
        // to flip between block/none as an in-DOM sibling, which is the design
        // that could not escape the stacking context.)
        for open_flag in [false, true] {
            let mut combo = ComboBox::new(sv(&["a"]));
            combo.combo_state.inner.open = open_flag;
            let dom = combo.dom();
            assert_eq!(
                inline_display(parts(&dom).1),
                Some(LayoutDisplay::Block),
                "open={open_flag}",
            );
            assert!(
                matches!(
                    popup_of(&dom).root.get_node_type(),
                    NodeType::TransientWindow(_)
                ),
                "open={open_flag}: the list must be wrapped in a popup window",
            );
        }
    }
    #[test]
    fn dom_shares_exactly_one_refany_across_every_callback() {
        // The module doc promises ONE shared RefAny: a write through the field's
        // handle must be visible through every option's handle.
        let dom = ComboBox::new(sv(&["a", "b", "c"])).dom();
        let (field, list) = parts(&dom);
        let field_refany = &field.root.get_callbacks().as_ref()[0].refany;
        for cb in field.root.get_callbacks().as_ref() {
            assert_eq!(&cb.refany, field_refany, "field handlers share one state");
        }
        for option in list.children.as_ref() {
            assert_eq!(
                &option.root.get_callbacks().as_ref()[0].refany,
                field_refany,
                "option handlers share the field's state"
            );
        }
        // ...and it is actually the same allocation, not just an equal one
        let mut writer = field_refany.clone();
        {
            let mut w = writer
                .downcast_mut::<ComboBoxStateWrapper>()
                .expect("the shared payload is a ComboBoxStateWrapper");
            w.inner.selected = 2;
            w.inner.open = true;
        }
        let mut reader = list.children.as_ref()[0].root.get_callbacks().as_ref()[0]
            .refany
            .clone();
        let seen = inner_of(&mut reader);
        assert_eq!(seen.selected, 2);
        assert!(seen.open);
    }
    #[test]
    fn dom_round_trips_items_and_state_into_the_shared_payload() {
        let combo = ComboBox::new(sv(&["α", "β", "\0"]))
            .with_selected(2)
            .with_text("typed".into());
        let expected = combo.combo_state.clone();
        let dom = combo.dom();
        let mut shared = parts(&dom).0.root.get_callbacks().as_ref()[0]
            .refany
            .clone();
        let decoded = shared
            .downcast_ref::<ComboBoxStateWrapper>()
            .expect("payload type is preserved");
        assert_eq!(decoded.inner, expected.inner);
        assert_eq!(decoded.items.as_ref(), expected.items.as_ref());
        assert!(decoded.on_select.is_none());
    }
    #[test]
    fn dom_child_count_cache_stays_consistent() {
        // A wrong `estimated_total_children` under-allocates the compact-DOM
        // arena and panics much later.
        for items in [
            alloc::vec![],
            alloc::vec!["a"],
            alloc::vec!["a", "", "\u{1F600}"],
        ] {
            let dom = ComboBox::new(sv(&items))
                .with_placeholder("ph".into())
                .dom();
            assert_eq!(
                dom.estimated_total_children,
                dom.recompute_estimated_total_children(),
                "cached descendant count desynced for {} item(s)",
                items.len()
            );
        }
    }
    #[test]
    fn from_combobox_for_dom_renders_the_same_tree() {
        // `Dom::from` delegates to `dom()`; the trees are structurally identical
        // (they are NOT `==`, because each render mints a fresh shared `RefAny`).
        let combo = ComboBox::new(sv(&["a", "b"])).with_text("t".into());
        let via_from = Dom::from(combo.clone());
        let via_dom = combo.dom();
        assert_eq!(
            via_from.estimated_total_children,
            via_dom.estimated_total_children
        );
        let (ff, fl) = parts(&via_from);
        let (df, dl) = parts(&via_dom);
        assert_eq!(
            text_of(&ff.children.as_ref()[0]),
            text_of(&df.children.as_ref()[0])
        );
        assert_eq!(inline_display(fl), inline_display(dl));
        assert_eq!(fl.children.as_ref().len(), dl.children.as_ref().len());
        assert_ne!(
            ff.root.get_callbacks().as_ref()[0].refany,
            df.root.get_callbacks().as_ref()[0].refany,
            "each render owns its own state allocation"
        );
    }
    // ------------------------------------------------------------------
    // on_combobox_toggle
    // ------------------------------------------------------------------
    #[test]
    fn toggle_without_any_layout_result_is_a_noop() {
        let mut data = state(&["a"], "", false, 0);
        let (update, changes) = run(Env::default(), 0, data.clone(), |r, ci| {
            on_combobox_toggle(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(!inner_of(&mut data).open, "state must not flip");
    }
    #[test]
    fn toggle_with_a_stale_hit_node_is_a_noop() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            9_999,
            data.clone(),
            |r, ci| on_combobox_toggle(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(!inner_of(&mut data).open);
    }
    #[test]
    fn toggle_on_a_node_without_a_next_sibling_does_not_flip_state() {
        // The list is the wrapper's LAST child: hitting it finds no sibling, and
        // crucially `open` must NOT have been toggled on the way out.
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "", true, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.list,
            data.clone(),
            |r, ci| on_combobox_toggle(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(inner_of(&mut data).open, "state must be untouched");
    }
    #[test]
    fn toggle_with_a_foreign_payload_does_not_restyle() {
        let fx = fixture(&["a"]);
        let data = RefAny::new(0xdead_beef_u64);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.field,
            data,
            |r, ci| on_combobox_toggle(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign payload must not show or hide the list"
        );
    }
    #[test]
    fn toggle_flips_open_and_opens_then_closes_the_popup_window() {
        let fx = fixture(&["a", "b"]);
        let mut data = state(&["a", "b"], "", false, 0);
        // closed -> open
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled.clone()),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_toggle(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            transient_writes(&changes),
            alloc::vec![(fx.popup, true)],
            "the field's next sibling (the <transient-window>) is the node that opens"
        );
        assert!(inner_of(&mut data).open);
        // open -> closed (same payload, so the flip must be stateful)
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_toggle(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(transient_writes(&changes), alloc::vec![(fx.popup, false)]);
        assert!(!inner_of(&mut data).open);
    }
    // ------------------------------------------------------------------
    // on_combobox_text_input / on_combobox_text_input_inner
    // ------------------------------------------------------------------
    #[test]
    fn text_input_without_a_changeset_is_a_noop() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "abc", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_text_input(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(inner_of(&mut data).text.as_str(), "abc", "text untouched");
    }
    #[test]
    fn text_input_with_an_empty_insertion_is_a_noop() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "abc", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                changeset: Some(PendingTextEdit {
                    node: node(fx.text),
                    inserted_text: AzString::from(""),
                    old_text: AzString::from("abc"),
                }),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_text_input(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "an empty insertion must not re-text the node"
        );
        assert_eq!(inner_of(&mut data).text.as_str(), "abc");
    }
    #[test]
    fn text_input_on_a_childless_node_is_a_noop() {
        // A bare text leaf has no children of its own: `get_first_child`
        // returns None before any state is touched.
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "abc", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                changeset: Some(PendingTextEdit {
                    node: node(fx.text),
                    inserted_text: AzString::from("z"),
                    old_text: AzString::from("abc"),
                }),
                ..Env::default()
            },
            fx.text,
            data.clone(),
            |r, ci| on_combobox_text_input(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(inner_of(&mut data).text.as_str(), "abc");
    }
    #[test]
    fn text_input_appends_to_state_and_retexts_the_field() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "ab", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                changeset: Some(PendingTextEdit {
                    node: node(fx.text),
                    inserted_text: AzString::from("c"),
                    old_text: AzString::from("ab"),
                }),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_text_input(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::from("abc"))],
            "the text leaf inside the field's label <p> is the node that is re-texted"
        );
        assert_eq!(inner_of(&mut data).text.as_str(), "abc");
        // selection/open state is not disturbed by typing
        assert!(!inner_of(&mut data).open);
        assert_eq!(inner_of(&mut data).selected, 0);
    }
    #[test]
    fn text_input_accumulates_across_keystrokes() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "", false, 0);
        for (i, ch) in ["h", "é", "🌍", "\0"].iter().enumerate() {
            let (update, changes) = run(
                Env {
                    styled: Some(fx.styled.clone()),
                    changeset: Some(PendingTextEdit {
                        node: node(fx.text),
                        inserted_text: AzString::from(*ch),
                        old_text: AzString::from(""),
                    }),
                    ..Env::default()
                },
                fx.field,
                data.clone(),
                |r, ci| on_combobox_text_input(r, ci),
            );
            assert_eq!(update, Update::DoNothing);
            assert_eq!(changes.len(), 1, "keystroke {i} produced one text write");
        }
        assert_eq!(inner_of(&mut data).text.as_str(), "hé🌍\0");
    }
    #[test]
    fn text_input_ignores_the_changesets_own_target_node() {
        // Quirk worth pinning: the handler re-texts the HIT node's first child and
        // never looks at `changeset.node`. A changeset naming a nonexistent node
        // is applied to the field anyway (rather than being dropped or panicking).
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                changeset: Some(PendingTextEdit {
                    // usize::MAX - 1 is the largest index the 1-based
                    // `NodeHierarchyItemId` encoding accepts without overflowing.
                    node: node(usize::MAX - 1),
                    inserted_text: AzString::from("q"),
                    old_text: AzString::from("ignored"),
                }),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_text_input(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::from("q"))]
        );
        assert_eq!(
            inner_of(&mut data).text.as_str(),
            "q",
            "`old_text` is ignored: the append is against the widget's own state"
        );
    }
    #[test]
    fn text_input_with_a_foreign_payload_leaves_the_dom_untouched() {
        let fx = fixture(&["a"]);
        let data = RefAny::new("not a combobox");
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                changeset: Some(PendingTextEdit {
                    node: node(fx.text),
                    inserted_text: AzString::from("x"),
                    old_text: AzString::from(""),
                }),
                ..Env::default()
            },
            fx.field,
            data,
            |r, ci| on_combobox_text_input(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn text_input_survives_a_huge_insertion() {
        let fx = fixture(&["a"]);
        let huge = "y".repeat(100_000);
        let mut data = state(&["a"], "", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                changeset: Some(PendingTextEdit {
                    node: node(fx.text),
                    inserted_text: AzString::from(huge.as_str()),
                    old_text: AzString::from(""),
                }),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_text_input(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(changes.len(), 1);
        assert_eq!(inner_of(&mut data).text.as_str().len(), 100_000);
    }
    #[test]
    fn text_input_inner_reports_none_when_it_does_nothing() {
        // The `_inner` half distinguishes "nothing to do" (None) from "handled"
        // (Some) — the extern wrapper collapses both to DoNothing.
        let fx = fixture(&["a"]);
        let (out, _) = run(
            Env {
                styled: Some(fx.styled.clone()),
                ..Env::default()
            },
            fx.field,
            state(&["a"], "", false, 0),
            on_combobox_text_input_inner,
        );
        assert_eq!(out, None, "no changeset -> None");
        let (out, _) = run(
            Env {
                styled: Some(fx.styled),
                changeset: Some(PendingTextEdit {
                    node: node(fx.text),
                    inserted_text: AzString::from("k"),
                    old_text: AzString::from(""),
                }),
                ..Env::default()
            },
            fx.field,
            state(&["a"], "", false, 0),
            on_combobox_text_input_inner,
        );
        assert_eq!(out, Some(Update::DoNothing), "handled -> Some");
    }
    // ------------------------------------------------------------------
    // on_combobox_key_down / on_combobox_key_down_inner
    // ------------------------------------------------------------------
    #[test]
    fn key_down_without_a_keycode_is_a_noop() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "abc", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_key_down(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(inner_of(&mut data).text.as_str(), "abc");
    }
    #[test]
    fn key_down_ignores_every_key_except_backspace() {
        let fx = fixture(&["a"]);
        for key in [
            VirtualKeyCode::A,
            VirtualKeyCode::Return,
            VirtualKeyCode::Escape,
            VirtualKeyCode::Delete,
            VirtualKeyCode::Space,
        ] {
            let mut data = state(&["a"], "abc", false, 0);
            let (update, changes) = run(
                Env {
                    styled: Some(fx.styled.clone()),
                    keycode: Some(key),
                    ..Env::default()
                },
                fx.field,
                data.clone(),
                |r, ci| on_combobox_key_down(r, ci),
            );
            assert_eq!(update, Update::DoNothing);
            assert!(changes.is_empty(), "{key:?} must not edit the text");
            assert_eq!(inner_of(&mut data).text.as_str(), "abc");
        }
    }
    #[test]
    fn key_down_backspace_pops_one_char_not_one_byte() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "hé🌍", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled.clone()),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_key_down(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::from("hé"))],
            "the 4-byte 🌍 is removed whole — no UTF-8 boundary panic"
        );
        assert_eq!(inner_of(&mut data).text.as_str(), "hé");
        // the two-byte é goes next, still whole
        let (_, changes) = run(
            Env {
                styled: Some(fx.styled),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_key_down(r, ci),
        );
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::from("h"))]
        );
        assert_eq!(inner_of(&mut data).text.as_str(), "h");
    }
    #[test]
    fn key_down_backspace_deletes_by_codepoint_not_by_grapheme() {
        // Documented consequence of `String::pop`: a combining mark and a ZWJ
        // emoji sequence lose ONE codepoint per press, not the whole cluster.
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "e\u{0301}", false, 0);
        let (_, changes) = run(
            Env {
                styled: Some(fx.styled.clone()),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_key_down(r, ci),
        );
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::from("e"))]
        );
        assert_eq!(inner_of(&mut data).text.as_str(), "e");
        // Expected value is derived, not spelled out: the ZWJ joiners the family
        // sequence is built from are invisible in source.
        let family_str = "👨‍👩‍👧";
        let all_but_last: String = {
            let mut s = String::from(family_str);
            s.pop();
            s
        };
        assert_eq!(
            family_str.chars().count(),
            5,
            "man ZWJ woman ZWJ girl — 5 codepoints, 1 grapheme"
        );
        let mut family = state(&["a"], family_str, false, 0);
        let (_, _) = run(
            Env {
                styled: Some(fx.styled),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.field,
            family.clone(),
            |r, ci| on_combobox_key_down(r, ci),
        );
        let after = inner_of(&mut family).text.as_str().to_string();
        assert_eq!(
            after, all_but_last,
            "only the trailing codepoint is dropped, not the whole cluster"
        );
        assert_eq!(
            after.chars().count(),
            4,
            "the cluster is still visually broken — one press removed one codepoint"
        );
    }
    #[test]
    fn key_down_backspace_on_empty_text_is_safe() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.field,
            data.clone(),
            |r, ci| on_combobox_key_down(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::new())],
            "popping an empty string is a no-op write, not a panic"
        );
        assert!(inner_of(&mut data).text.as_str().is_empty());
    }
    #[test]
    fn key_down_on_a_childless_node_is_a_noop() {
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "abc", false, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.options[0],
            data.clone(),
            |r, ci| on_combobox_key_down(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(inner_of(&mut data).text.as_str(), "abc");
    }
    #[test]
    fn key_down_with_a_foreign_payload_is_a_noop() {
        let fx = fixture(&["a"]);
        let data = RefAny::new(7u16);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.field,
            data,
            |r, ci| on_combobox_key_down(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn key_down_inner_reports_none_when_it_does_nothing() {
        let fx = fixture(&["a"]);
        let (out, _) = run(
            Env {
                styled: Some(fx.styled.clone()),
                keycode: Some(VirtualKeyCode::A),
                ..Env::default()
            },
            fx.field,
            state(&["a"], "abc", false, 0),
            on_combobox_key_down_inner,
        );
        assert_eq!(out, None, "a non-backspace key -> None");
        let (out, _) = run(
            Env {
                styled: Some(fx.styled),
                keycode: Some(VirtualKeyCode::Back),
                ..Env::default()
            },
            fx.field,
            state(&["a"], "abc", false, 0),
            on_combobox_key_down_inner,
        );
        assert_eq!(out, Some(Update::DoNothing), "backspace -> Some");
    }
    // ------------------------------------------------------------------
    // on_combobox_option_click
    // ------------------------------------------------------------------
    #[test]
    fn option_click_without_any_layout_result_is_a_noop() {
        let mut data = state(&["a"], "", true, 0);
        let (update, changes) = run(Env::default(), 0, data.clone(), |r, ci| {
            on_combobox_option_click(r, ci)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(inner_of(&mut data).open, "state must not change");
    }
    #[test]
    fn option_click_on_a_parentless_node_is_a_noop() {
        // The wrapper is the root: it has no parent, so the walk bails out.
        let fx = fixture(&["a"]);
        let mut data = state(&["a"], "", true, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.wrapper,
            data.clone(),
            |r, ci| on_combobox_option_click(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(inner_of(&mut data).open);
    }
    #[test]
    fn option_click_selects_by_previous_sibling_count() {
        let labels = ["zero", "one", "two", "three"];
        let fx = fixture(&labels);
        for (i, label) in labels.iter().enumerate() {
            let mut data = state(&labels, "", true, 999);
            let (update, changes) = run(
                Env {
                    styled: Some(fx.styled.clone()),
                    ..Env::default()
                },
                fx.options[i],
                data.clone(),
                |r, ci| on_combobox_option_click(r, ci),
            );
            assert_eq!(update, Update::DoNothing, "no user callback -> DoNothing");
            let inner = inner_of(&mut data);
            assert_eq!(inner.selected, i, "index = number of previous siblings");
            assert_eq!(inner.text.as_str(), *label, "the field takes the label");
            assert!(!inner.open, "selecting closes the list");
            assert_eq!(
                text_writes(&changes),
                alloc::vec![(fx.text, String::from(*label))]
            );
            assert_eq!(
                transient_writes(&changes),
                alloc::vec![(fx.popup, false)],
                "selecting closes the popup WINDOW",
            );
        }
    }
    #[test]
    fn option_click_index_walk_scales_to_a_long_list() {
        // The index is derived by walking previous siblings one at a time; make
        // sure a long list terminates and lands on the right (last) index.
        let labels: Vec<String> = (0..200).map(|i| alloc::format!("item{i}")).collect();
        let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
        let fx = fixture(&refs);
        let mut data = state(&refs, "", true, 0);
        let (update, _) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.options[199],
            data.clone(),
            |r, ci| on_combobox_option_click(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        let inner = inner_of(&mut data);
        assert_eq!(inner.selected, 199);
        assert_eq!(inner.text.as_str(), "item199");
    }
    #[test]
    fn option_click_with_an_out_of_range_index_changes_nothing() {
        // The rendered list has 3 rows but the payload only knows 1 item — the
        // `items.get(index)` miss must abort BEFORE any state or DOM write.
        let fx = fixture(&["a", "b", "c"]);
        let mut data = state(&["only"], "keep", true, 42);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.options[2],
            data.clone(),
            |r, ci| on_combobox_option_click(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty(), "no partial write may escape");
        let inner = inner_of(&mut data);
        assert_eq!(inner.selected, 42, "selected must not move");
        assert_eq!(inner.text.as_str(), "keep");
        assert!(inner.open, "the list must not be closed either");
    }
    #[test]
    fn option_click_with_an_empty_item_list_changes_nothing() {
        // Same miss, taken from the other side: a DOM with rows, a payload with
        // no items at all.
        let fx = fixture(&["a"]);
        let mut data = state(&[], "keep", true, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.options[0],
            data.clone(),
            |r, ci| on_combobox_option_click(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(inner_of(&mut data).text.as_str(), "keep");
    }
    #[test]
    fn option_click_with_a_foreign_payload_is_a_noop() {
        let fx = fixture(&["a"]);
        let data = RefAny::new(1u8);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.options[0],
            data,
            |r, ci| on_combobox_option_click(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn option_click_selects_labels_with_nul_and_emoji_verbatim() {
        let labels = ["a\0b", "👨‍👩‍👧‍👦", ""];
        let fx = fixture(&labels);
        for (i, label) in labels.iter().enumerate() {
            let mut data = state(&labels, "", true, 0);
            let (_, changes) = run(
                Env {
                    styled: Some(fx.styled.clone()),
                    ..Env::default()
                },
                fx.options[i],
                data.clone(),
                |r, ci| on_combobox_option_click(r, ci),
            );
            assert_eq!(inner_of(&mut data).text.as_str(), *label);
            assert_eq!(
                text_writes(&changes),
                alloc::vec![(fx.text, String::from(*label))]
            );
        }
    }
    /// The dom shape an option click ACTUALLY runs against on a device: the
    /// popup window's own dom, i.e. the `<transient-window>` subtree extracted
    /// by `azul_core::transient::extract_subtree_as_dom` — root div (the former
    /// transient node) > list > options, with NO wrapper/field above it.
    /// Returns the styled popup dom plus the flattened option indices.
    fn popup_window_fixture(items: &[&str]) -> (StyledDom, Vec<usize>) {
        let fx = fixture(items);
        let extracted =
            azul_core::transient::extract_subtree_as_dom(&fx.styled, NodeId::new(fx.popup))
                .expect("the popup node is a <transient-window>, extraction must succeed");
        assert!(
            matches!(extracted.root.get_node_type(), NodeType::Div),
            "inside its own window the transient container is a plain div"
        );
        let styled = StyledDom::create_from_dom(extracted);
        let options = nodes_with_class(&styled, "__azul-native-combobox-option");
        assert_eq!(options.len(), items.len());
        // Extraction must carry the click callback AND the same shared RefAny
        // allocation — that sharing is the only channel a popup-side pick has
        // back to the parent's handlers.
        let orig = fx.styled.node_data.as_ref()[fx.options[0]]
            .get_callbacks()
            .as_ref()[0]
            .clone();
        let copy = styled.node_data.as_ref()[options[0]]
            .get_callbacks()
            .as_ref()[0]
            .clone();
        assert_eq!(copy.callback.cb, on_combobox_option_click as usize);
        assert_eq!(
            copy.refany, orig.refany,
            "the extracted option must share the parent's state RefAny"
        );
        (styled, options)
    }
    #[test]
    fn option_click_inside_the_popup_window_selects_and_dismisses() {
        // DEVICE BUG: clicking an option in the real popup window did NOTHING —
        // the handler walked option -> list -> popup -> wrapper, and in the
        // popup's extracted dom `get_parent(popup)` is None (the wrapper lives
        // in the PARENT window's dom), so it bailed before touching the state,
        // before the user callback, and before closing anything. Pin the fixed
        // contract: state + on_select + a close request on the popup ROOT (the
        // shell recognises that as "this popup dismisses itself"), and NO text
        // write (there is no field in this dom to mis-address).
        let labels = ["Apple", "Banana", "Cherry"];
        let (styled, options) = popup_window_fixture(&labels);
        let mut log = RefAny::new(SelectLog { calls: Vec::new() });
        let mut data = RefAny::new(ComboBoxStateWrapper {
            inner: ComboBoxState {
                open: true,
                selected: 0,
                text: AzString::from(""),
            },
            items: sv(&labels),
            on_select: Some(ComboBoxOnSelect {
                callback: on_select_cb(record_select),
                refany: log.clone(),
            })
            .into(),
        });
        let (update, changes) = run(
            Env {
                styled: Some(styled),
                ..Env::default()
            },
            options[1],
            data.clone(),
            |r, ci| on_combobox_option_click(r, ci),
        );
        // The shared state is the SAME RefAny allocation the parent's handlers
        // hold — this is the leg that makes the selection visible to the parent.
        let inner = inner_of(&mut data);
        assert_eq!(inner.selected, 1, "the pick must land in the shared state");
        assert_eq!(inner.text.as_str(), "Banana");
        assert!(!inner.open, "selecting closes the list");
        assert_eq!(update, Update::RefreshDom, "the user callback's verdict");
        let logged = log
            .downcast_ref::<SelectLog>()
            .expect("log payload survived");
        assert_eq!(
            logged.calls.len(),
            1,
            "on_select must fire inside the popup"
        );
        assert_eq!(logged.calls[0].selected, 1);
        // Root of the extracted dom = flattened index 0.
        assert_eq!(
            transient_writes(&changes),
            alloc::vec![(0, false)],
            "the close request names the popup's ROOT — the shell's cue to dismiss the popup \
             window itself",
        );
        assert!(
            text_writes(&changes).is_empty(),
            "no field exists in the popup dom — a text write here would land on an arbitrary node",
        );
    }
    #[test]
    fn dismissed_applies_the_popup_side_selection_to_the_field() {
        // The parent-side half of the popup selection: `Dismissed` targets the
        // <transient-window> node in the PARENT dom, and the handler must copy
        // the shared state's text (written by the popup-side click) into the
        // field's text leaf — the write the popup window could not address.
        let fx = fixture(&["Apple", "Banana"]);
        let mut data = state(&["Apple", "Banana"], "Banana", true, 1);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.popup,
            data.clone(),
            |r, ci| on_combobox_dismissed(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(!inner_of(&mut data).open, "Dismissed resyncs the open flag");
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::from("Banana"))],
            "the parent-side handler is where the popup's pick reaches the field",
        );
    }
    #[test]
    fn dismissed_with_no_text_keeps_the_placeholder() {
        // An open-then-outside-click dismissal with nothing ever picked or
        // typed: the shared text is empty, and writing "" would erase the
        // placeholder the field was built with.
        let fx = fixture(&["Apple"]);
        let mut data = state(&["Apple"], "", true, 0);
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.popup,
            data.clone(),
            |r, ci| on_combobox_dismissed(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert!(!inner_of(&mut data).open);
        assert!(
            changes.is_empty(),
            "an empty shared text must not blank the field's placeholder"
        );
    }
    #[test]
    fn option_click_invokes_the_user_callback_and_propagates_its_update() {
        let fx = fixture(&["a", "b"]);
        let mut log = RefAny::new(SelectLog { calls: Vec::new() });
        let data = RefAny::new(ComboBoxStateWrapper {
            inner: ComboBoxState {
                open: true,
                selected: 0,
                text: AzString::from(""),
            },
            items: sv(&["a", "b"]),
            on_select: Some(ComboBoxOnSelect {
                callback: on_select_cb(record_select),
                refany: log.clone(),
            })
            .into(),
        });
        let (update, changes) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.options[1],
            data,
            |r, ci| on_combobox_option_click(r, ci),
        );
        // the user's return value wins over the internal DoNothing
        assert_eq!(update, Update::RefreshDom);
        // ...and the field/list are still updated, even though the user ran
        assert_eq!(
            text_writes(&changes),
            alloc::vec![(fx.text, String::from("b"))]
        );
        assert_eq!(transient_writes(&changes), alloc::vec![(fx.popup, false)]);
        let logged = log
            .downcast_ref::<SelectLog>()
            .expect("log payload survived");
        assert_eq!(logged.calls.len(), 1);
        assert_eq!(
            logged.calls[0].selected, 1,
            "the callback sees the NEW index"
        );
        assert_eq!(logged.calls[0].text.as_str(), "b", "...and the NEW text");
        assert!(!logged.calls[0].open, "...and an already-closed list");
    }
    #[test]
    fn option_click_holds_the_state_borrow_across_the_user_callback() {
        // The handler invokes `on_select` while its own `downcast_mut` guard is
        // still alive, so a re-entrant borrow of the shared state from inside the
        // user callback is REFUSED (returns None) rather than aliasing or
        // deadlocking. Pinning this documents the constraint on user callbacks.
        let fx = fixture(&["a"]);
        let data = RefAny::new(ComboBoxStateWrapper {
            inner: ComboBoxState::default(),
            items: sv(&["a"]),
            on_select: Some(ComboBoxOnSelect {
                callback: on_select_cb(probe_reborrow),
                refany: RefAny::new(0u8),
            })
            .into(),
        });
        SHARED_ALIAS.with(|a| *a.borrow_mut() = Some(data.clone()));
        REBORROW_REFUSED.with(|c| c.set(None));
        let (update, _) = run(
            Env {
                styled: Some(fx.styled),
                ..Env::default()
            },
            fx.options[0],
            data,
            |r, ci| on_combobox_option_click(r, ci),
        );
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            REBORROW_REFUSED.with(|c| c.get()),
            Some(true),
            "a re-entrant downcast_mut must fail cleanly, not alias or hang"
        );
        SHARED_ALIAS.with(|a| *a.borrow_mut() = None);
    }
}