1
//! Native drop-down / select widget.
2
//!
3
//! Renders a clickable trigger (label + arrow icon) that opens a native
4
//! menu popup for item selection.  Depends on [`azul_core::menu`] for
5
//! popup rendering.
6

            
7
use azul_core::{
8
    callbacks::{CoreCallback, CoreCallbackData, Update},
9
    dom::{
10
        Dom, DomVec, EventFilter, FocusEventFilter, IdOrClass, IdOrClass::Class, IdOrClassVec,
11
        TabIndex,
12
    },
13
    menu::{Menu, MenuItem, MenuPopupPosition, StringMenuItem},
14
    refany::RefAny,
15
    window::ContextMenuMouseButton,
16
};
17
#[allow(clippy::wildcard_imports)]
18
// widget/render module pulls in the css property/value types it builds with
19
use azul_css::{
20
    dynamic_selector::{
21
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
22
    },
23
    props::{
24
        basic::{
25
            color::{ColorOrSystem, ColorU},
26
            font::{StyleFontFamily, StyleFontFamilyVec},
27
            *,
28
        },
29
        layout::*,
30
        property::CssProperty,
31
        style::*,
32
    },
33
    OptionString, *,
34
};
35

            
36
use crate::callbacks::{Callback, CallbackInfo};
37

            
38
// -- Callback type via macro --
39

            
40
/// Callback signature invoked when the user selects a new choice.
41
///
42
/// The `usize` argument is the zero-based index of the chosen item.
43
pub type DropDownOnChoiceChangeCallbackType = extern "C" fn(RefAny, CallbackInfo, usize) -> Update;
44
impl_widget_callback!(
45
    DropDownOnChoiceChange,
46
    OptionDropDownOnChoiceChange,
47
    DropDownOnChoiceChangeCallback,
48
    DropDownOnChoiceChangeCallbackType
49
);
50

            
51
azul_core::impl_managed_callback! {
52
    wrapper:        DropDownOnChoiceChangeCallback,
53
    info_ty:        CallbackInfo,
54
    return_ty:      Update,
55
    default_ret:    Update::DoNothing,
56
    invoker_static: DROP_DOWN_ON_CHOICE_CHANGE_INVOKER,
57
    invoker_ty:     AzDropDownOnChoiceChangeCallbackInvoker,
58
    thunk_fn:       az_drop_down_on_choice_change_callback_thunk,
59
    setter_fn:      AzApp_setDropDownOnChoiceChangeCallbackInvoker,
60
    from_handle_fn: AzDropDownOnChoiceChangeCallback_createFromHostHandle,
61
    extra_args:     [ choice_index: usize ],
62
}
63

            
64
// ============================================================================
65
// Widget struct and API
66
// ============================================================================
67

            
68
/// A drop-down / select widget that displays the currently selected item
69
/// and opens a native menu popup when focused.
70
#[derive(Debug, Clone, PartialEq, Eq)]
71
#[repr(C)]
72
pub struct DropDown {
73
    /// The list of choices presented in the popup menu.
74
    pub choices: StringVec,
75
    /// Zero-based index of the currently selected choice.
76
    pub selected: usize,
77
    /// Optional callback invoked when the user picks a different choice.
78
    pub on_choice_change: OptionDropDownOnChoiceChange,
79
    /// Style of the clickable trigger wrapper.
80
    pub wrapper_style: OptionCssPropertyWithConditionsVec,
81
    /// Style of the selected-choice label.
82
    pub label_style: OptionCssPropertyWithConditionsVec,
83
    /// Style of the drop-down arrow icon.
84
    pub arrow_style: OptionCssPropertyWithConditionsVec,
85
    /// What this control is CALLED, for assistive technology.
86
    ///
87
    /// Carried by the WIDGET so it knows at build time whether it was named;
88
    /// forwarded into the accessibility declaration it already builds.
89
    pub accessibility_name: OptionString,
90
    pub theme: crate::widgets::themes::OptionUiTheme,
91
}
92

            
93
impl Default for DropDown {
94
78
    fn default() -> Self {
95
78
        Self {
96
78
            choices: StringVec::from_const_slice(&[]),
97
78
            selected: 0,
98
78
            on_choice_change: None.into(),
99
78
            wrapper_style: OptionCssPropertyWithConditionsVec::None,
100
78
            label_style: OptionCssPropertyWithConditionsVec::None,
101
78
            arrow_style: OptionCssPropertyWithConditionsVec::None,
102
78
            accessibility_name: OptionString::None,
103
78
            theme: crate::widgets::themes::OptionUiTheme::Some(
104
78
                crate::widgets::themes::UiTheme::Flat,
105
78
            ),
106
78
        }
107
78
    }
108
}
109

            
110
impl DropDown {
111
    /// Creates a new `DropDown` with the given choices and no callback.
112
    /// Name this control for assistive technology.
113
    #[must_use]
114
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
115
        self.accessibility_name = Some(name.into()).into();
116
        self
117
    }
118

            
119
    #[must_use]
120
67
    pub fn new(choices: StringVec) -> Self {
121
67
        Self {
122
67
            choices,
123
67
            ..Self::default()
124
67
        }
125
67
    }
126

            
127
    /// Selects the choice at `index` - what the trigger DISPLAYS.
128
    ///
129
    /// A drop-down is rebuilt from the host's state on every layout, so the
130
    /// host must write the index its `on_choice_change` callback was handed
131
    /// back here; otherwise the trigger keeps showing choice 0 no matter what
132
    /// the user picks (there was no setter at all, so this was the only
133
    /// possible outcome). An out-of-range index displays the empty string
134
    /// rather than panicking, the same as an empty choice list.
135
6
    pub const fn set_selected(&mut self, index: usize) {
136
6
        self.selected = index;
137
6
    }
138

            
139
    /// Builder variant of [`Self::set_selected`].
140
    #[must_use]
141
5
    pub const fn with_selected(mut self, index: usize) -> Self {
142
5
        self.set_selected(index);
143
5
        self
144
5
    }
145

            
146
    /// Pick the widget theme. Unset (`None`), the widget renders in the
147
    /// default theme (`crate::widgets::themes::UiTheme::default()`).
148
    pub const fn set_theme(&mut self, theme: crate::widgets::themes::UiTheme) {
149
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
150
    }
151

            
152
    /// [`Self::set_theme`] for the builder chain.
153
    #[must_use]
154
    pub const fn with_theme(mut self, theme: crate::widgets::themes::UiTheme) -> Self {
155
        self.set_theme(theme);
156
        self
157
    }
158

            
159
    /// Sets the callback invoked when the user selects a different choice.
160
14
    pub fn set_on_choice_change<C: Into<DropDownOnChoiceChangeCallback>>(
161
14
        &mut self,
162
14
        data: RefAny,
163
14
        callback: C,
164
14
    ) {
165
14
        self.on_choice_change = Some(DropDownOnChoiceChange {
166
14
            callback: callback.into(),
167
14
            refany: data,
168
14
        })
169
14
        .into();
170
14
    }
171

            
172
    /// Builder variant of [`Self::set_on_choice_change`].
173
    #[must_use]
174
7
    pub fn with_on_choice_change<C: Into<DropDownOnChoiceChangeCallback>>(
175
7
        mut self,
176
7
        data: RefAny,
177
7
        callback: C,
178
7
    ) -> Self {
179
7
        self.set_on_choice_change(data, callback);
180
7
        self
181
7
    }
182

            
183
    /// Replaces `self` with the default value and returns the original.
184
    #[must_use]
185
4
    pub fn swap_with_default(&mut self) -> Self {
186
4
        let mut m = Self::default();
187
4
        core::mem::swap(&mut m, self);
188
4
        m
189
4
    }
190

            
191
    /// Builds the DOM tree for this drop-down widget.
192
    #[must_use]
193
53
    pub fn dom(self) -> Dom {
194
53
        match self.theme {
195
            crate::widgets::themes::OptionUiTheme::None => Dom::create_div(),
196
            crate::widgets::themes::OptionUiTheme::Some(crate::widgets::themes::UiTheme::Flat) => {
197
53
                crate::widgets::themes::flat::drop_down(self)
198
            }
199
            crate::widgets::themes::OptionUiTheme::Some(crate::widgets::themes::UiTheme::Flora) => {
200
                crate::widgets::themes::flora::drop_down(self)
201
            }
202
        }
203
53
    }
204
}
205

            
206
// ============================================================================
207
// Internal callback data types
208
// ============================================================================
209

            
210
struct ChoiceCallbackData {
211
    choice_id: usize,
212
    on_choice_change: OptionDropDownOnChoiceChange,
213
}
214

            
215
// ============================================================================
216
// Callbacks
217
// ============================================================================
218

            
219
#[must_use]
220
11
pub extern "C" fn on_dropdown_click(mut refany: RefAny, mut info: CallbackInfo) -> Update {
221
11
    let Some(refany) = refany.downcast_ref::<DropDown>() else {
222
1
        return Update::DoNothing;
223
    };
224

            
225
10
    let menu_items: Vec<MenuItem> = refany
226
10
        .choices
227
10
        .iter()
228
10
        .enumerate()
229
22
        .map(|(idx, choice)| {
230
22
            MenuItem::String(StringMenuItem::create(choice.clone()).with_callback(
231
22
                RefAny::new(ChoiceCallbackData {
232
22
                    choice_id: idx,
233
22
                    on_choice_change: refany.on_choice_change.clone(),
234
22
                }),
235
22
                on_choice_selected as usize,
236
22
            ))
237
22
        })
238
10
        .collect();
239

            
240
10
    let menu = Menu {
241
10
        items: menu_items.into(),
242
10
        position: MenuPopupPosition::BottomOfHitRect,
243
10
        context_mouse_btn: ContextMenuMouseButton::Right,
244
10
    };
245

            
246
10
    info.open_menu_for_hit_node(menu);
247
10
    Update::DoNothing
248
11
}
249

            
250
13
extern "C" fn on_choice_selected(mut refany: RefAny, info: CallbackInfo) -> Update {
251
13
    let Some(mut refany) = refany.downcast_mut::<ChoiceCallbackData>() else {
252
1
        return Update::DoNothing;
253
    };
254

            
255
12
    let choice_id = refany.choice_id;
256

            
257
12
    match refany.on_choice_change.as_mut() {
258
11
        Some(DropDownOnChoiceChange { refany, callback }) => {
259
11
            (callback.cb)(refany.clone(), info, choice_id)
260
        }
261
1
        None => Update::DoNothing,
262
    }
263
13
}
264

            
265
impl From<DropDown> for Dom {
266
1
    fn from(b: DropDown) -> Self {
267
1
        b.dom()
268
1
    }
269
}
270

            
271
#[cfg(test)]
272
mod autotest_generated {
273
    use std::{
274
        collections::{BTreeMap, HashMap},
275
        sync::{Arc, Mutex},
276
    };
277

            
278
    use azul_core::{
279
        dom::{DomId, DomNodeId, NodeId, NodeType},
280
        geom::{LogicalPosition, LogicalRect, LogicalSize, OptionLogicalPosition},
281
        gl::OptionGlContextPtr,
282
        hit_test::ScrollPosition,
283
        refany::OptionRefAny,
284
        resources::RendererResources,
285
        styled_dom::{NodeHierarchyItemId, StyledDom},
286
        window::{MonitorVec, RawWindowHandle},
287
    };
288
    use rust_fontconfig::FcFontCache;
289

            
290
    use super::*;
291
    #[cfg(feature = "icu")]
292
    use crate::icu::IcuLocalizerHandle;
293
    use crate::{
294
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
295
        solver3::{
296
            display_list::{DisplayList, DisplayListItem, WindowLogicalRect},
297
            layout_tree::LayoutTree,
298
        },
299
        window::{DomLayoutResult, LayoutWindow},
300
        window_state::FullWindowState,
301
    };
302

            
303
    // ------------------------------------------------------------------
304
    // Fixtures
305
    // ------------------------------------------------------------------
306

            
307
    /// Where every user callback records the index it was handed. Passed through
308
    /// the widget as a `RefAny`, so the assertions exercise the real data plumbing
309
    /// (`RefAny::new` -> clone -> `downcast_ref`) rather than a side channel.
310
    type ChoiceLog = Arc<Mutex<Vec<usize>>>;
311

            
312
    /// Offset added by `reject_choice` so the two recorders below stay
313
    /// distinguishable in the log.
314
    const SENTINEL: usize = 1_000_000;
315

            
316
    extern "C" fn record_choice(
317
        mut data: RefAny,
318
        _info: CallbackInfo,
319
        choice_index: usize,
320
    ) -> Update {
321
        if let Some(log) = data.downcast_ref::<ChoiceLog>() {
322
            log.lock().expect("choice log poisoned").push(choice_index);
323
        }
324
        Update::RefreshDom
325
    }
326

            
327
    /// A second callback with a *deliberately different body*: two identical
328
    /// `extern "C"` bodies are legal prey for identical-code folding, which would
329
    /// merge their addresses and make the "last write wins" assertion vacuous.
330
    extern "C" fn reject_choice(
331
        mut data: RefAny,
332
        _info: CallbackInfo,
333
        choice_index: usize,
334
    ) -> Update {
335
        if let Some(log) = data.downcast_ref::<ChoiceLog>() {
336
            log.lock()
337
                .expect("choice log poisoned")
338
                .push(choice_index.wrapping_add(SENTINEL));
339
        }
340
        Update::RefreshDomAllWindows
341
    }
342

            
343
    fn log() -> ChoiceLog {
344
        Arc::new(Mutex::new(Vec::new()))
345
    }
346

            
347
    fn entries(log: &ChoiceLog) -> Vec<usize> {
348
        log.lock().expect("choice log poisoned").clone()
349
    }
350

            
351
    fn cb(f: DropDownOnChoiceChangeCallbackType) -> DropDownOnChoiceChangeCallback {
352
        DropDownOnChoiceChangeCallback::from(f)
353
    }
354

            
355
    fn choices(items: &[&str]) -> StringVec {
356
        StringVec::from_vec(
357
            items
358
                .iter()
359
                .map(|s| AzString::from_string((*s).to_string()))
360
                .collect(),
361
        )
362
    }
363

            
364
    /// Adversarial choice labels: empty, whitespace, combining marks, ZWJ emoji,
365
    /// RTL, embedded NULs (`AzString` is length-based, so a NUL must not
366
    /// truncate), bidi overrides, control characters, and strings that collide
367
    /// with the widget's own class / icon names.
368
    fn adversarial_choices() -> Vec<String> {
369
        let mut v: Vec<String> = [
370
            "",
371
            " ",
372
            "OK",
373
            "e\u{0301}",                                   // e + combining acute
374
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}", // ZWJ family emoji
375
            "\u{5E9}\u{5DC}\u{5D5}\u{5DD}",                // RTL Hebrew
376
            "\0",                                          // a lone NUL
377
            "a\0b",                                        // embedded NUL
378
            "\u{FFFD}\u{202E}\u{200B}",                    // replacement, RTL override, ZWSP
379
            "…\t\r\n",                                     // control chars in a label
380
            "__azul-native-dropdown",                      // looks like the widget's own class
381
            "arrow_drop_down",                             // looks like the widget's own icon
382
        ]
383
        .iter()
384
        .map(|s| (*s).to_string())
385
        .collect();
386
        v.push("x".repeat(100_000));
387
        v
388
    }
389

            
390
    fn adversarial_dropdown() -> DropDown {
391
        DropDown::new(StringVec::from_vec(
392
            adversarial_choices()
393
                .into_iter()
394
                .map(AzString::from_string)
395
                .collect(),
396
        ))
397
    }
398

            
399
    // ------------------------------------------------------------------
400
    // DOM probes
401
    // ------------------------------------------------------------------
402

            
403
    /// The text the trigger displays: `root > p > text`. Panics loudly (rather
404
    /// than returning `None`) if the shape ever changes, because every label
405
    /// assertion below silently depends on that shape.
406
    fn label_of(dom: &Dom) -> &str {
407
        let p = dom
408
            .children
409
            .as_ref()
410
            .first()
411
            .expect("the trigger must have a label child");
412
        let text = p
413
            .children
414
            .as_ref()
415
            .first()
416
            .expect("the label must wrap a text node");
417
        match text.root.get_node_type() {
418
            NodeType::Text(s) => s.as_ref().as_str(),
419
            other => panic!("expected a text node, got {other:?}"),
420
        }
421
    }
422

            
423
    fn classes(dom: &Dom) -> Vec<String> {
424
        dom.root
425
            .get_ids_and_classes()
426
            .as_ref()
427
            .iter()
428
            .filter_map(|c| match c {
429
                Class(s) => Some(s.as_str().to_string()),
430
                IdOrClass::Id(_) => None,
431
            })
432
            .collect()
433
    }
434

            
435
    /// The recursive descendant count. `Dom::estimated_total_children` is a
436
    /// *cached* value that, if too small, makes `convert_dom_into_compact_dom`
437
    /// under-allocate its arenas and panic on out-of-bounds writes.
438
    fn count_descendants(dom: &Dom) -> usize {
439
        dom.children
440
            .as_ref()
441
            .iter()
442
            .map(|c| 1 + count_descendants(c))
443
            .sum()
444
    }
445

            
446
    /// Renders `dd`, then hands back both the DOM *and* the very `RefAny` the
447
    /// widget registered on its own focus callback. Driving `on_dropdown_click`
448
    /// with that `RefAny` is the real wiring - nothing is re-created by hand, so
449
    /// a mismatch between what `dom()` stores and what the handler expects
450
    /// cannot hide behind the fixture.
451
    fn rendered(dd: DropDown) -> (Dom, RefAny) {
452
        let dom = dd.dom();
453
        let refany = dom.root.callbacks.as_ref()[0].refany.clone();
454
        (dom, refany)
455
    }
456

            
457
    // ------------------------------------------------------------------
458
    // CallbackInfo harness (mirrors the one in `check_box.rs` / `timer.rs`)
459
    // ------------------------------------------------------------------
460

            
461
    struct Env<'a> {
462
        ref_data: &'a CallbackInfoRefData<'a>,
463
        changes: &'a Arc<Mutex<Vec<CallbackChange>>>,
464
        hit: DomNodeId,
465
    }
466

            
467
    impl Env<'_> {
468
        fn info(&self) -> CallbackInfo {
469
            CallbackInfo::new(
470
                self.ref_data,
471
                self.changes,
472
                self.hit,
473
                OptionLogicalPosition::None,
474
                OptionLogicalPosition::None,
475
            )
476
        }
477

            
478
        fn take_changes(&self) -> Vec<CallbackChange> {
479
            self.changes
480
                .lock()
481
                .map(|mut c| core::mem::take(&mut *c))
482
                .unwrap_or_default()
483
        }
484

            
485
        fn take_one(&self) -> CallbackChange {
486
            let mut changes = self.take_changes();
487
            assert_eq!(changes.len(), 1, "expected exactly one change: {changes:?}");
488
            changes.remove(0)
489
        }
490
    }
491

            
492
    /// The tag the hit-tester would use for `node`. `open_menu_for_node` resolves
493
    /// the anchor rect through this mapping, so a forged hit-test area must reuse
494
    /// the id the styling pass actually assigned.
495
    fn tag_of(styled_dom: &StyledDom, node: NodeId) -> u64 {
496
        let nid = NodeHierarchyItemId::from_crate_internal(Some(node));
497
        styled_dom
498
            .tag_ids_to_node_ids
499
            .iter()
500
            .find(|m| m.node_id == nid)
501
            .expect("the dropdown trigger must be hit-testable")
502
            .tag_id
503
            .inner
504
    }
505

            
506
    /// A `DomLayoutResult` carrying only a `styled_dom` plus (optionally) one
507
    /// forged hit-test area. The dropdown handler reaches exactly one geometry
508
    /// query (`get_node_hit_test_bounds`), which reads the display list only -
509
    /// no real layout (and no font) is needed.
510
    fn layout_result(
511
        styled_dom: StyledDom,
512
        anchor: Option<(NodeId, LogicalRect)>,
513
    ) -> DomLayoutResult {
514
        let mut display_list = DisplayList::default();
515
        if let Some((node, rect)) = anchor {
516
            let tag = tag_of(&styled_dom, node);
517
            display_list.items.push(DisplayListItem::HitTestArea {
518
                bounds: WindowLogicalRect::new(rect.origin, rect.size),
519
                // The tag TYPE matters: `get_node_hit_test_bounds` looks for a
520
                // DOM-node area specifically, because `tag.0` is also used by
521
                // text-run cursor areas with a colliding numbering scheme. A
522
                // forged area must therefore carry the same type the display
523
                // list builder stamps.
524
                tag: (tag, azul_core::hit_test::TAG_TYPE_DOM_NODE),
525
            });
526
        }
527

            
528
        DomLayoutResult {
529
            styled_dom,
530
            layout_tree: LayoutTree {
531
                nodes: Vec::new(),
532
                warm: Vec::new(),
533
                cold: Vec::new(),
534
                root: 0,
535
                dom_to_layout: BTreeMap::new(),
536
                children_arena: Vec::new(),
537
                children_offsets: Vec::new(),
538
                subtree_needs_intrinsic: Vec::new(),
539
            },
540
            calculated_positions: Vec::new(),
541
            viewport: LogicalRect::zero(),
542
            display_list: Arc::new(display_list),
543
            scroll_ids: HashMap::new(),
544
            scroll_id_to_node_id: HashMap::new(),
545
        }
546
    }
547

            
548
    /// Runs `f` with a callback environment over an empty `LayoutWindow` and no
549
    /// hit node - the "nothing to anchor to" case.
550
    fn with_env<R>(f: impl FnOnce(&Env<'_>) -> R) -> R {
551
        with_env_cfg(None, f)
552
    }
553

            
554
    /// Runs `f` with a callback environment whose root DOM is `styled_dom`, whose
555
    /// node `node` has the hit-test rect `rect`, and whose hit node is `node`.
556
    fn with_anchored_env<R>(
557
        styled_dom: StyledDom,
558
        node: NodeId,
559
        rect: LogicalRect,
560
        f: impl FnOnce(&Env<'_>) -> R,
561
    ) -> R {
562
        with_env_cfg(Some((styled_dom, node, rect)), f)
563
    }
564

            
565
    fn with_env_cfg<R>(
566
        anchored: Option<(StyledDom, NodeId, LogicalRect)>,
567
        f: impl FnOnce(&Env<'_>) -> R,
568
    ) -> R {
569
        let mut layout_window =
570
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
571

            
572
        let hit = match anchored {
573
            Some((styled_dom, node, rect)) => {
574
                layout_window.layout_results.insert(
575
                    DomId::ROOT_ID,
576
                    layout_result(styled_dom, Some((node, rect))),
577
                );
578
                DomNodeId {
579
                    dom: DomId::ROOT_ID,
580
                    node: NodeHierarchyItemId::from_crate_internal(Some(node)),
581
                }
582
            }
583
            None => DomNodeId {
584
                dom: DomId::ROOT_ID,
585
                node: NodeHierarchyItemId::NONE,
586
            },
587
        };
588

            
589
        let renderer_resources = RendererResources::default();
590
        let previous_window_state: Option<FullWindowState> = None;
591
        let current_window_state = FullWindowState::default();
592
        let gl_context = OptionGlContextPtr::None;
593
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
594
            BTreeMap::new();
595
        let window_handle = RawWindowHandle::Unsupported;
596
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
597

            
598
        let ref_data = CallbackInfoRefData {
599
            layout_window: &layout_window,
600
            renderer_resources: &renderer_resources,
601
            previous_window_state: &previous_window_state,
602
            current_window_state: &current_window_state,
603
            gl_context: &gl_context,
604
            current_scroll_manager: &scroll_states,
605
            current_window_handle: &window_handle,
606
            system_callbacks: &system_callbacks,
607
            system_style: Arc::new(system::SystemStyle::default()),
608
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
609
            #[cfg(feature = "icu")]
610
            icu_localizer: IcuLocalizerHandle::default(),
611
            ctx: OptionRefAny::None,
612
        };
613

            
614
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
615
        let env = Env {
616
            ref_data: &ref_data,
617
            changes: &changes,
618
            hit,
619
        };
620
        f(&env)
621
    }
622

            
623
    /// The labels of a queued `OpenMenu` change's items, in menu order.
624
    fn menu_labels(menu: &Menu) -> Vec<String> {
625
        menu.items
626
            .as_ref()
627
            .iter()
628
            .map(|i| match i {
629
                MenuItem::String(s) => s.label.as_str().to_string(),
630
                other => panic!("the dropdown must only emit string items, got {other:?}"),
631
            })
632
            .collect()
633
    }
634

            
635
    // ==================================================================
636
    // DropDown::new / Default  (constructor invariants)
637
    // ==================================================================
638

            
639
    #[test]
640
    fn new_keeps_the_choices_and_starts_unselected_without_a_callback() {
641
        let dd = DropDown::new(choices(&["a", "b", "c"]));
642

            
643
        assert_eq!(dd.choices.len(), 3);
644
        assert_eq!(
645
            dd.choices
646
                .as_slice()
647
                .iter()
648
                .map(AzString::as_str)
649
                .collect::<Vec<_>>(),
650
            vec!["a", "b", "c"],
651
            "choices must be stored verbatim, in order",
652
        );
653
        assert_eq!(dd.selected, 0, "a fresh dropdown selects the first item");
654
        assert!(
655
            dd.on_choice_change.as_ref().is_none(),
656
            "`new` must not invent a callback",
657
        );
658
    }
659

            
660
    #[test]
661
    fn new_preserves_every_adversarial_choice_byte_for_byte() {
662
        let originals = adversarial_choices();
663
        let dd = DropDown::new(StringVec::from_vec(
664
            originals
665
                .iter()
666
                .cloned()
667
                .map(AzString::from_string)
668
                .collect(),
669
        ));
670

            
671
        assert_eq!(
672
            dd.choices.len(),
673
            originals.len(),
674
            "no choice may be dropped"
675
        );
676
        for (stored, original) in dd.choices.as_slice().iter().zip(&originals) {
677
            assert_eq!(
678
                stored.as_str(),
679
                original.as_str(),
680
                "a NUL / bidi / astral label must survive the StringVec round-trip",
681
            );
682
            assert_eq!(
683
                stored.as_str().len(),
684
                original.len(),
685
                "byte length must be preserved — an embedded NUL must not truncate",
686
            );
687
        }
688
    }
689

            
690
    #[test]
691
    fn new_on_an_empty_choice_list_still_reports_index_zero() {
692
        // `selected == 0` points *past the end* of an empty list. That is the
693
        // documented starting state, so every consumer (notably `dom()`) has to
694
        // tolerate an out-of-range selection from the very first frame.
695
        let dd = DropDown::new(StringVec::from_const_slice(&[]));
696
        assert!(dd.choices.is_empty());
697
        assert_eq!(dd.selected, 0);
698
        assert!(dd.choices.as_slice().get(dd.selected).is_none());
699
    }
700

            
701
    #[test]
702
    fn new_with_ten_thousand_choices_keeps_len_and_capacity_consistent() {
703
        let n = 10_000;
704
        let dd = DropDown::new(StringVec::from_vec(
705
            (0..n)
706
                .map(|i| AzString::from_string(i.to_string()))
707
                .collect(),
708
        ));
709

            
710
        assert_eq!(dd.choices.len(), n);
711
        assert!(
712
            dd.choices.capacity() >= dd.choices.len(),
713
            "capacity must never be smaller than len",
714
        );
715
        assert_eq!(
716
            dd.choices.as_slice().len(),
717
            n,
718
            "the C slice view must agree with len"
719
        );
720
        assert_eq!(dd.choices.as_slice()[n - 1].as_str(), (n - 1).to_string());
721
    }
722

            
723
    #[test]
724
    fn default_is_the_empty_unselected_dropdown() {
725
        let dd = DropDown::default();
726
        assert!(dd.choices.is_empty());
727
        assert_eq!(dd.selected, 0);
728
        assert!(dd.on_choice_change.as_ref().is_none());
729
        assert_eq!(dd, DropDown::new(StringVec::from_const_slice(&[])));
730
    }
731

            
732
    // ==================================================================
733
    // set_on_choice_change / with_on_choice_change
734
    // ==================================================================
735

            
736
    #[test]
737
    fn set_on_choice_change_stores_the_exact_refany_and_function_pointer() {
738
        let l = log();
739
        let data = RefAny::new(l);
740
        let mut dd = DropDown::new(choices(&["a"]));
741
        dd.set_on_choice_change(data.clone(), cb(record_choice));
742

            
743
        let stored = dd
744
            .on_choice_change
745
            .as_ref()
746
            .expect("the callback must be stored");
747
        assert_eq!(
748
            stored.refany, data,
749
            "the widget must hold the caller's allocation, not a copy",
750
        );
751
        assert_eq!(
752
            stored.callback.cb as usize, record_choice as usize,
753
            "the function pointer must round-trip unchanged",
754
        );
755
        assert!(
756
            stored.callback.ctx.as_ref().is_none(),
757
            "a native Rust callback has no FFI context",
758
        );
759
    }
760

            
761
    #[test]
762
    fn set_on_choice_change_is_last_write_wins() {
763
        let mut dd = DropDown::new(choices(&["a"]));
764
        dd.set_on_choice_change(RefAny::new(log()), cb(record_choice));
765
        let second = RefAny::new(log());
766
        dd.set_on_choice_change(second.clone(), cb(reject_choice));
767

            
768
        let stored = dd
769
            .on_choice_change
770
            .as_ref()
771
            .expect("still exactly one callback");
772
        assert_eq!(stored.callback.cb as usize, reject_choice as usize);
773
        assert_eq!(
774
            stored.refany, second,
775
            "the second registration must replace the first"
776
        );
777
        assert_ne!(
778
            record_choice as usize, reject_choice as usize,
779
            "the two probes must not have been folded into one symbol",
780
        );
781
    }
782

            
783
    /// The trigger must DISPLAY the selected choice, and `set_selected` /
784
    /// `with_selected` must be the way a host says which one that is.
785
    ///
786
    /// `selected` was a public field with no setter, so a host had no supported
787
    /// way to feed back the index its `on_choice_change` callback was handed —
788
    /// and since the widget is rebuilt from host state every layout, the trigger
789
    /// showed choice 0 forever no matter what the user picked.
790
    #[test]
791
    fn selecting_a_choice_changes_what_the_trigger_displays() {
792
        let items = choices(&["Alpha", "Beta", "Gamma"]);
793

            
794
        // Default: the first choice.
795
        assert_eq!(label_of(&DropDown::new(items.clone()).dom()), "Alpha");
796

            
797
        // Every index round-trips into the rendered label.
798
        for (i, expected) in ["Alpha", "Beta", "Gamma"].iter().enumerate() {
799
            let dd = DropDown::new(items.clone()).with_selected(i);
800
            assert_eq!(dd.selected, i, "with_selected must store the index");
801
            assert_eq!(
802
                label_of(&dd.dom()),
803
                *expected,
804
                "the trigger must display choice {i}",
805
            );
806
        }
807

            
808
        // The setter and the builder agree.
809
        let mut a = DropDown::new(items.clone());
810
        a.set_selected(2);
811
        assert_eq!(a, DropDown::new(items.clone()).with_selected(2));
812

            
813
        // Out of range renders empty rather than panicking (same as no choices).
814
        assert_eq!(label_of(&DropDown::new(items).with_selected(99).dom()), "");
815
    }
816

            
817
    #[test]
818
    fn set_on_choice_change_does_not_disturb_the_choices_or_the_selection() {
819
        let mut dd = adversarial_dropdown();
820
        dd.selected = usize::MAX;
821
        let before = dd.choices.clone();
822

            
823
        dd.set_on_choice_change(RefAny::new(log()), cb(record_choice));
824

            
825
        assert_eq!(
826
            dd.choices, before,
827
            "registering a callback must not touch the model"
828
        );
829
        assert_eq!(
830
            dd.selected,
831
            usize::MAX,
832
            "…nor the selection, however out of range"
833
        );
834
    }
835

            
836
    #[test]
837
    fn with_on_choice_change_is_the_setter_plus_a_move() {
838
        let data = RefAny::new(log());
839
        let built = DropDown::new(choices(&["a", "b"]))
840
            .with_on_choice_change(data.clone(), cb(record_choice));
841

            
842
        let mut expected = DropDown::new(choices(&["a", "b"]));
843
        expected.set_on_choice_change(data, cb(record_choice));
844

            
845
        assert_eq!(
846
            built, expected,
847
            "the builder must not differ from the setter"
848
        );
849
    }
850

            
851
    #[test]
852
    fn with_on_choice_change_preserves_an_out_of_range_selection() {
853
        let mut dd = DropDown::new(choices(&["a"]));
854
        dd.selected = usize::MAX;
855
        let dd = dd.with_on_choice_change(RefAny::new(log()), cb(record_choice));
856

            
857
        assert_eq!(
858
            dd.selected,
859
            usize::MAX,
860
            "the builder must not silently clamp"
861
        );
862
        assert_eq!(dd.choices.len(), 1);
863
    }
864

            
865
    #[test]
866
    fn with_on_choice_change_accepts_a_zero_choice_dropdown() {
867
        let dd = DropDown::default().with_on_choice_change(RefAny::new(log()), cb(record_choice));
868
        assert!(dd.choices.is_empty());
869
        assert!(
870
            dd.on_choice_change.as_ref().is_some(),
871
            "a callback on an empty dropdown is legal — it just can never fire",
872
        );
873
    }
874

            
875
    // ==================================================================
876
    // swap_with_default
877
    // ==================================================================
878

            
879
    #[test]
880
    fn swap_with_default_moves_the_original_out_and_leaves_a_default() {
881
        let data = RefAny::new(log());
882
        let mut dd = DropDown::new(choices(&["a", "b"]))
883
            .with_on_choice_change(data.clone(), cb(record_choice));
884
        dd.selected = 1;
885

            
886
        let taken = dd.swap_with_default();
887

            
888
        assert_eq!(taken.choices.len(), 2);
889
        assert_eq!(taken.selected, 1);
890
        assert_eq!(
891
            taken
892
                .on_choice_change
893
                .as_ref()
894
                .expect("callback moved out")
895
                .refany,
896
            data,
897
        );
898
        assert_eq!(
899
            dd,
900
            DropDown::default(),
901
            "what stays behind must be the default"
902
        );
903
    }
904

            
905
    #[test]
906
    fn swap_with_default_is_idempotent_after_the_first_call() {
907
        let mut dd = adversarial_dropdown();
908
        let _first = dd.swap_with_default();
909
        let second = dd.swap_with_default();
910

            
911
        assert_eq!(
912
            second,
913
            DropDown::default(),
914
            "the second take yields a default"
915
        );
916
        assert_eq!(
917
            dd,
918
            DropDown::default(),
919
            "…and leaves another default behind"
920
        );
921
    }
922

            
923
    #[test]
924
    fn swap_with_default_preserves_an_out_of_range_selection_and_huge_labels() {
925
        let mut dd = adversarial_dropdown();
926
        dd.selected = usize::MAX;
927
        let n = dd.choices.len();
928

            
929
        let taken = dd.swap_with_default();
930

            
931
        assert_eq!(
932
            taken.selected,
933
            usize::MAX,
934
            "swap must not normalise anything"
935
        );
936
        assert_eq!(taken.choices.len(), n);
937
        assert_eq!(dd.selected, 0);
938
        assert!(dd.choices.is_empty());
939
    }
940

            
941
    // ==================================================================
942
    // DropDown::dom
943
    // ==================================================================
944

            
945
    #[test]
946
    fn dom_labels_the_selected_choice() {
947
        for (idx, expected) in [(0, "alpha"), (1, "beta"), (2, "gamma")] {
948
            let mut dd = DropDown::new(choices(&["alpha", "beta", "gamma"]));
949
            dd.selected = idx;
950
            let dom = dd.dom();
951
            assert_eq!(
952
                label_of(&dom),
953
                expected,
954
                "index {idx} must label the trigger"
955
            );
956
        }
957
    }
958

            
959
    #[test]
960
    fn dom_falls_back_to_an_empty_label_for_an_out_of_range_selection() {
961
        // len, len+1 and the arithmetic limit: `.get()` returns None for all of
962
        // them, and the documented fallback is the empty string — never a panic
963
        // and never a stale neighbour.
964
        for idx in [3_usize, 4, usize::MAX - 1, usize::MAX] {
965
            let mut dd = DropDown::new(choices(&["a", "b", "c"]));
966
            dd.selected = idx;
967
            let dom = dd.dom();
968
            assert_eq!(
969
                label_of(&dom),
970
                "",
971
                "selected = {idx} must render an empty label"
972
            );
973
        }
974
    }
975

            
976
    #[test]
977
    fn dom_on_an_empty_dropdown_renders_an_empty_label() {
978
        let dom = DropDown::default().dom();
979
        assert_eq!(label_of(&dom), "");
980
        assert_eq!(
981
            dom.children.len(),
982
            2,
983
            "label + arrow are rendered regardless"
984
        );
985
    }
986

            
987
    #[test]
988
    fn dom_label_survives_unicode_embedded_nuls_and_huge_strings() {
989
        let originals = adversarial_choices();
990
        for (idx, original) in originals.iter().enumerate() {
991
            let mut dd = DropDown::new(StringVec::from_vec(
992
                originals
993
                    .iter()
994
                    .cloned()
995
                    .map(AzString::from_string)
996
                    .collect(),
997
            ));
998
            dd.selected = idx;
999
            let dom = dd.dom();
            assert_eq!(
                label_of(&dom),
                original.as_str(),
                "label {idx} must reach the text node byte-for-byte",
            );
        }
    }
    #[test]
    fn dom_shape_is_a_trigger_with_a_wrapped_label_and_an_arrow_icon() {
        let dom = DropDown::new(choices(&["a"])).dom();
        assert!(
            matches!(dom.root.get_node_type(), NodeType::Div),
            "the trigger is a div"
        );
        assert_eq!(dom.children.len(), 2, "exactly a label and an arrow");
        let kids = dom.children.as_ref();
        assert!(
            matches!(kids[0].root.get_node_type(), NodeType::P),
            "the label is block-formatted"
        );
        assert_eq!(
            kids[0].children.len(),
            1,
            "the <p> wraps exactly one text node"
        );
        match kids[1].root.get_node_type() {
            NodeType::Icon(s) => assert_eq!(s.as_ref().as_str(), "arrow_drop_down"),
            other => panic!("expected the arrow icon, got {other:?}"),
        }
        assert_eq!(
            kids[1].children.len(),
            1,
            "the icon carries its glyph slot (a text leaf)"
        );
    }
    #[test]
    fn dom_child_count_cache_is_honest_for_every_selection() {
        for idx in [0_usize, 1, 2, 99, usize::MAX] {
            let mut dd = DropDown::new(choices(&["a", "b"]));
            dd.selected = idx;
            let dom = dd.dom();
            assert_eq!(
                dom.estimated_total_children,
                count_descendants(&dom),
                "selected = {idx}: a stale cache makes the compact-DOM arena under-allocate",
            );
            assert_eq!(
                dom.estimated_total_children, 4,
                "p + text + icon + its glyph slot"
            );
        }
    }
    #[test]
    fn dom_marks_the_trigger_focusable_and_gives_it_the_widget_class() {
        let dom = DropDown::new(choices(&["a"])).dom();
        assert_eq!(
            dom.root.get_tab_index(),
            Some(TabIndex::Auto),
            "the popup opens on focus, so the trigger must be reachable by keyboard",
        );
        assert_eq!(classes(&dom), vec!["__azul-native-dropdown".to_string()]);
    }
    #[test]
    fn dom_registers_exactly_one_focus_received_callback() {
        let dom = DropDown::new(choices(&["a", "b"])).dom();
        let cbs = dom.root.callbacks.as_ref();
        assert_eq!(
            cbs.len(),
            1,
            "one handler — a duplicate would open two popups"
        );
        assert_eq!(
            cbs[0].event,
            EventFilter::Focus(FocusEventFilter::FocusReceived)
        );
        assert_eq!(cbs[0].callback.cb, on_dropdown_click as usize);
        assert!(cbs[0].callback.ctx.as_ref().is_none());
    }
    #[test]
    fn dom_hands_the_whole_widget_to_the_callback_refany() {
        let mut dd = adversarial_dropdown();
        dd.selected = 4;
        let expected: Vec<String> = dd
            .choices
            .as_slice()
            .iter()
            .map(|c| c.as_str().to_string())
            .collect();
        let (_dom, mut refany) = rendered(dd);
        let stored = refany
            .downcast_ref::<DropDown>()
            .expect("dom() must store the DropDown itself, unwrapped");
        assert_eq!(stored.selected, 4);
        assert_eq!(
            stored
                .choices
                .as_slice()
                .iter()
                .map(|c| c.as_str().to_string())
                .collect::<Vec<_>>(),
            expected,
            "the handler must see the same choices the label was built from",
        );
    }
    #[test]
    fn from_dropdown_for_dom_renders_the_same_trigger_as_dom() {
        let mut dd = DropDown::new(choices(&["a", "b", "c"]));
        dd.selected = 2;
        let direct = dd.clone().dom();
        let converted = Dom::from(dd);
        assert_eq!(label_of(&direct), label_of(&converted));
        assert_eq!(direct.children.len(), converted.children.len());
        assert_eq!(classes(&direct), classes(&converted));
        assert_eq!(
            direct.estimated_total_children,
            converted.estimated_total_children
        );
    }
    #[test]
    fn dom_with_ten_thousand_choices_renders_only_the_selected_one() {
        let n = 10_000;
        let mut dd = DropDown::new(StringVec::from_vec(
            (0..n)
                .map(|i| AzString::from_string(i.to_string()))
                .collect(),
        ));
        dd.selected = n - 1;
        let dom = dd.dom();
        assert_eq!(label_of(&dom), (n - 1).to_string());
        assert_eq!(
            dom.estimated_total_children, 4,
            "the trigger must not materialise one node per choice",
        );
    }
    #[test]
    fn dom_does_not_mutate_the_selection_it_was_given() {
        // The widget is stateless w.r.t. selection: `dom()` reads `selected` and
        // never writes it. Anything that changes the label has to go through the
        // caller's own state, updated from the choice-change callback.
        let mut dd = DropDown::new(choices(&["a", "b"]));
        dd.selected = 1;
        let (_dom, mut refany) = rendered(dd);
        assert_eq!(
            refany
                .downcast_ref::<DropDown>()
                .expect("stored widget")
                .selected,
            1
        );
    }
    // ==================================================================
    // on_dropdown_click
    // ==================================================================
    #[test]
    fn on_dropdown_click_ignores_a_refany_of_the_wrong_type() {
        with_env(|env| {
            let update = on_dropdown_click(RefAny::new(0_usize), env.info());
            assert_eq!(update, Update::DoNothing);
            assert!(
                env.take_changes().is_empty(),
                "a type mismatch must be a silent no-op, not a half-built menu",
            );
        });
    }
    #[test]
    fn on_dropdown_click_without_a_hit_node_opens_nothing() {
        let (_dom, refany) = rendered(DropDown::new(choices(&["a", "b"])));
        with_env(|env| {
            // The hit node is NONE and the window has no layout results, so the
            // popup has nothing to anchor to.
            let update = on_dropdown_click(refany.clone(), env.info());
            assert_eq!(update, Update::DoNothing);
            assert!(
                env.take_changes().is_empty(),
                "a failed anchor must not queue a half-open menu",
            );
        });
    }
    #[test]
    fn on_dropdown_click_opens_one_menu_item_per_choice_in_order() {
        let labels = ["a", "", "\u{5E9}\u{5DC}\u{5D5}\u{5DD}", "a\0b"];
        let (dom, refany) = rendered(DropDown::new(choices(&labels)));
        let styled_dom = StyledDom::create_from_dom(dom);
        let rect = LogicalRect::new(
            LogicalPosition::new(10.0, 20.0),
            LogicalSize::new(100.0, 30.0),
        );
        with_anchored_env(styled_dom, NodeId::new(0), rect, |env| {
            let update = on_dropdown_click(refany.clone(), env.info());
            assert_eq!(
                update,
                Update::DoNothing,
                "opening the popup is not a re-layout"
            );
            let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                panic!("expected exactly one OpenMenu change");
            };
            assert_eq!(
                menu_labels(&menu),
                labels.iter().map(|s| (*s).to_string()).collect::<Vec<_>>(),
                "menu order must mirror choice order, NULs and RTL included",
            );
        });
    }
    #[test]
    fn on_dropdown_click_on_an_empty_dropdown_opens_an_empty_menu() {
        let (dom, refany) = rendered(DropDown::default());
        let styled_dom = StyledDom::create_from_dom(dom);
        let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), LogicalSize::new(1.0, 1.0));
        with_anchored_env(styled_dom, NodeId::new(0), rect, |env| {
            assert_eq!(
                on_dropdown_click(refany.clone(), env.info()),
                Update::DoNothing
            );
            let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                panic!("expected an OpenMenu change");
            };
            assert!(
                menu.items.is_empty(),
                "no choices means no items — not a panic"
            );
        });
    }
    #[test]
    fn on_dropdown_click_anchors_the_menu_below_the_trigger() {
        let (dom, refany) = rendered(DropDown::new(choices(&["a"])));
        let styled_dom = StyledDom::create_from_dom(dom);
        let rect = LogicalRect::new(
            LogicalPosition::new(10.0, 20.0),
            LogicalSize::new(100.0, 30.0),
        );
        with_anchored_env(styled_dom, NodeId::new(0), rect, |env| {
            let _ = on_dropdown_click(refany.clone(), env.info());
            let CallbackChange::OpenMenu {
                menu,
                position,
                anchor,
            } = env.take_one()
            else {
                panic!("expected an OpenMenu change");
            };
            let p = position.expect("the popup must be pinned to the trigger");
            assert_eq!((p.x, p.y), (10.0, 50.0), "bottom-left of the trigger rect");
            // THE WHOLE TRIGGER RECT travels with the request, not just its
            // bottom-left corner: a backend needs the WIDTH to make the menu at
            // least as wide as the control, the way a `<select>` does, and the
            // rect to edge-flip against (2026-09-01 request). Dropping it here
            // is what left every drop-down menu item-width and looking like a
            // stray context menu.
            let a = anchor.expect("a menu opened FOR a node carries that node's rect");
            assert_eq!(
                (a.origin.x, a.origin.y, a.size.width, a.size.height),
                (10.0, 20.0, 100.0, 30.0),
                "the anchor is the trigger rect itself",
            );
            assert!(matches!(menu.position, MenuPopupPosition::BottomOfHitRect));
            assert!(matches!(
                menu.context_mouse_btn,
                ContextMenuMouseButton::Right
            ));
        });
    }
    #[test]
    fn on_dropdown_click_is_repeatable_and_does_not_consume_the_widget() {
        let (dom, refany) = rendered(DropDown::new(choices(&["a", "b"])));
        let styled_dom = StyledDom::create_from_dom(dom);
        let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), LogicalSize::new(4.0, 8.0));
        with_anchored_env(styled_dom, NodeId::new(0), rect, |env| {
            for round in 0..3 {
                let _ = on_dropdown_click(refany.clone(), env.info());
                let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                    panic!("round {round}: expected an OpenMenu change");
                };
                assert_eq!(menu_labels(&menu), vec!["a".to_string(), "b".to_string()]);
            }
        });
    }
    #[test]
    fn on_dropdown_click_tags_every_item_with_its_own_index_and_handler() {
        let l = log();
        let dd = DropDown::new(choices(&["a", "b", "c"]))
            .with_on_choice_change(RefAny::new(l), cb(record_choice));
        let (dom, refany) = rendered(dd);
        let styled_dom = StyledDom::create_from_dom(dom);
        let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), LogicalSize::new(4.0, 8.0));
        with_anchored_env(styled_dom, NodeId::new(0), rect, |env| {
            let _ = on_dropdown_click(refany.clone(), env.info());
            let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                panic!("expected an OpenMenu change");
            };
            for (idx, item) in menu.items.as_ref().iter().enumerate() {
                let MenuItem::String(s) = item else {
                    panic!("item {idx} is not a string item");
                };
                let menu_cb = s.callback.as_ref().expect("every item must be clickable");
                assert_eq!(
                    menu_cb.callback.cb, on_choice_selected as usize,
                    "item {idx} must route through the widget's own handler",
                );
                let mut data = menu_cb.refany.clone();
                let payload = data
                    .downcast_ref::<ChoiceCallbackData>()
                    .expect("the item payload must be a ChoiceCallbackData");
                assert_eq!(payload.choice_id, idx, "item {idx} carries the wrong index");
                assert!(
                    payload.on_choice_change.as_ref().is_some(),
                    "item {idx} lost the user callback on the way into the menu",
                );
            }
        });
    }
    // ==================================================================
    // on_choice_selected
    // ==================================================================
    #[test]
    fn on_choice_selected_ignores_a_refany_of_the_wrong_type() {
        with_env(|env| {
            let update = on_choice_selected(RefAny::new(0_usize), env.info());
            assert_eq!(update, Update::DoNothing);
            assert!(env.take_changes().is_empty());
        });
    }
    #[test]
    fn on_choice_selected_without_a_registered_callback_does_nothing() {
        let data = RefAny::new(ChoiceCallbackData {
            choice_id: 7,
            on_choice_change: None.into(),
        });
        with_env(|env| {
            let update = on_choice_selected(data.clone(), env.info());
            assert_eq!(
                update,
                Update::DoNothing,
                "an unwired dropdown must stay silent"
            );
            assert!(env.take_changes().is_empty());
        });
    }
    #[test]
    fn on_choice_selected_forwards_the_index_and_propagates_the_return_value() {
        let l = log();
        let data = RefAny::new(ChoiceCallbackData {
            choice_id: 2,
            on_choice_change: Some(DropDownOnChoiceChange {
                refany: RefAny::new(l.clone()),
                callback: cb(record_choice),
            })
            .into(),
        });
        with_env(|env| {
            let update = on_choice_selected(data.clone(), env.info());
            assert_eq!(
                update,
                Update::RefreshDom,
                "the user's Update must not be swallowed"
            );
        });
        assert_eq!(entries(&l), vec![2], "the callback must see its own index");
    }
    #[test]
    fn on_choice_selected_forwards_usize_max_unchanged() {
        // `choice_id` is a plain index with no upper bound: the limit value must
        // pass through untouched rather than wrap, saturate or panic.
        let l = log();
        let data = RefAny::new(ChoiceCallbackData {
            choice_id: usize::MAX,
            on_choice_change: Some(DropDownOnChoiceChange {
                refany: RefAny::new(l.clone()),
                callback: cb(record_choice),
            })
            .into(),
        });
        with_env(|env| {
            assert_eq!(
                on_choice_selected(data.clone(), env.info()),
                Update::RefreshDom
            );
        });
        assert_eq!(entries(&l), vec![usize::MAX]);
    }
    #[test]
    fn on_choice_selected_is_repeatable_on_the_same_payload() {
        let l = log();
        let data = RefAny::new(ChoiceCallbackData {
            choice_id: 1,
            on_choice_change: Some(DropDownOnChoiceChange {
                refany: RefAny::new(l.clone()),
                callback: cb(record_choice),
            })
            .into(),
        });
        with_env(|env| {
            // The handler takes an *exclusive* borrow of the payload; if it were
            // ever leaked, the second call would fail to downcast and silently
            // return DoNothing.
            for _ in 0..3 {
                assert_eq!(
                    on_choice_selected(data.clone(), env.info()),
                    Update::RefreshDom
                );
            }
        });
        assert_eq!(
            entries(&l),
            vec![1, 1, 1],
            "the borrow must be released each time"
        );
    }
    #[test]
    fn on_choice_selected_uses_the_callback_that_was_registered_last() {
        let l = log();
        let mut dd = DropDown::new(choices(&["a", "b"]));
        dd.set_on_choice_change(RefAny::new(l.clone()), cb(record_choice));
        dd.set_on_choice_change(RefAny::new(l.clone()), cb(reject_choice));
        let data = RefAny::new(ChoiceCallbackData {
            choice_id: 1,
            on_choice_change: dd.on_choice_change.clone(),
        });
        with_env(|env| {
            assert_eq!(
                on_choice_selected(data.clone(), env.info()),
                Update::RefreshDomAllWindows
            );
        });
        assert_eq!(
            entries(&l),
            vec![1 + SENTINEL],
            "the replaced callback must not fire"
        );
    }
    // ==================================================================
    // End-to-end: focus -> popup -> pick an item
    // ==================================================================
    #[test]
    fn picking_a_menu_item_delivers_exactly_that_index_to_the_user_callback() {
        let l = log();
        let dd = DropDown::new(choices(&["a", "b", "c", "d"]))
            .with_on_choice_change(RefAny::new(l.clone()), cb(record_choice));
        let (dom, refany) = rendered(dd);
        let styled_dom = StyledDom::create_from_dom(dom);
        let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), LogicalSize::new(4.0, 8.0));
        with_anchored_env(styled_dom, NodeId::new(0), rect, |env| {
            let _ = on_dropdown_click(refany.clone(), env.info());
            let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                panic!("expected an OpenMenu change");
            };
            // Deliberately out of order: the index must come from the item, not
            // from the order in which items happen to be clicked.
            for idx in [3_usize, 0, 2, 1] {
                let MenuItem::String(s) = &menu.items.as_ref()[idx] else {
                    panic!("item {idx} is not a string item");
                };
                let payload = s.callback.as_ref().expect("clickable").refany.clone();
                assert_eq!(
                    on_choice_selected(payload, env.info()),
                    Update::RefreshDom,
                    "item {idx} must reach the user callback",
                );
            }
        });
        assert_eq!(entries(&l), vec![3, 0, 2, 1]);
    }
    #[test]
    fn picking_an_item_does_not_move_the_widgets_own_selection() {
        // NOTE (documented behaviour, not an accident): `DropDown` never updates
        // its own `selected` field. Selection state lives with the caller, which
        // is why the trigger label only changes once the caller re-renders. If
        // this ever starts self-updating, this assertion is the tripwire.
        let l = log();
        let dd = DropDown::new(choices(&["a", "b"]))
            .with_on_choice_change(RefAny::new(l.clone()), cb(record_choice));
        let (dom, mut refany) = rendered(dd);
        let styled_dom = StyledDom::create_from_dom(dom);
        let rect = LogicalRect::new(LogicalPosition::new(0.0, 0.0), LogicalSize::new(4.0, 8.0));
        with_anchored_env(styled_dom, NodeId::new(0), rect, |env| {
            let _ = on_dropdown_click(refany.clone(), env.info());
            let CallbackChange::OpenMenu { menu, .. } = env.take_one() else {
                panic!("expected an OpenMenu change");
            };
            let MenuItem::String(s) = &menu.items.as_ref()[1] else {
                panic!("item 1 is not a string item");
            };
            let payload = s.callback.as_ref().expect("clickable").refany.clone();
            on_choice_selected(payload, env.info());
        });
        assert_eq!(entries(&l), vec![1], "the pick was delivered");
        assert_eq!(
            refany
                .downcast_ref::<DropDown>()
                .expect("stored widget")
                .selected,
            0,
            "the widget's own `selected` stays where the caller put it",
        );
    }
}