1
//! Popover widget — wraps an arbitrary anchor [`Dom`] and shows an
2
//! absolutely-positioned floating panel holding arbitrary `content: Dom` when
3
//! the anchor is **clicked** (toggling open/closed). A click-triggered sibling
4
//! of [`crate::widgets::tooltip::Tooltip`] (which is hover-triggered and
5
//! text-only): the CSS show/hide popup mechanism is identical, but the panel
6
//! holds a whole [`Dom`] and is toggled by an internal click handler that flips
7
//! a [`PopoverState`].
8
//!
9
//! Structure: a `position: relative` wrapper containing a clickable *trigger*
10
//! (which holds the anchor) followed by the absolutely-positioned *content*
11
//! panel, hidden by default (`display: none`). Clicking the trigger flips
12
//! `open`, invokes the optional user `on_toggle(state)`, and shows/hides the
13
//! panel via `set_css_property(display)` (mirroring the live-restyle pattern of
14
//! check_box / accordion).
15
//!
16
//! TODO2: like [`Tooltip`], this is a CSS simplification of a "real" floating
17
//! popover. The panel is placed at a fixed offset below the trigger (it does not
18
//! measure the trigger's height, flip when near a screen edge, escape an
19
//! `overflow: hidden` ancestor, or raise its z-order — it relies on being the
20
//! later sibling to paint on top). There is also no "click-outside to dismiss"
21
//! and no `Escape` handling — clicking the trigger again is the only way to
22
//! close it (clicking *inside* the panel does not close it, since the handler is
23
//! on the trigger, not the wrapper). A future revision could route through the
24
//! window-popup / menu popup path for true screen-anchored positioning and
25
//! outside-click dismissal once that is runtime-verifiable.
26
//!
27
//! Key types: [`Popover`], [`PopoverState`], [`PopoverOnToggle`].
28

            
29
use azul_core::{
30
    callbacks::{CoreCallbackData, Update},
31
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
32
    refany::RefAny,
33
};
34
use azul_css::{
35
    dynamic_selector::{
36
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
37
    },
38
    impl_option_inner,
39
    props::{
40
        basic::{color::ColorU, *},
41
        layout::{
42
            LayoutDisplay, LayoutFlexGrow, LayoutLeft, LayoutMinWidth, LayoutPaddingBottom,
43
            LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop, LayoutPosition, LayoutTop,
44
        },
45
        property::{CssProperty, *},
46
        style::{
47
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
48
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
49
            StyleBorderBottomColor, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius,
50
            StyleBorderBottomStyle, StyleBorderLeftColor, StyleBorderLeftStyle,
51
            StyleBorderRightColor, StyleBorderRightStyle, StyleBorderTopColor,
52
            StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderTopStyle, StyleCursor,
53
        },
54
    },
55
    AzString,
56
};
57

            
58
use crate::callbacks::{Callback, CallbackInfo};
59

            
60
static POPOVER_WRAPPER_CLASS: &[IdOrClass] =
61
    &[Class(AzString::from_const_str("__azul-native-popover"))];
62
static POPOVER_TRIGGER_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
63
    "__azul-native-popover-trigger",
64
))];
65
static POPOVER_CONTENT_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
66
    "__azul-native-popover-content",
67
))];
68

            
69
// ---- layout (logical px) ----
70
/// Fixed vertical offset of the panel below the wrapper's top edge. A
71
/// simplification — see the module-level `TODO2`.
72
const CONTENT_OFFSET_Y: isize = 32;
73
/// Minimum width of the floating panel.
74
const CONTENT_MIN_WIDTH: isize = 160;
75
const CONTENT_RADIUS: isize = 6;
76

            
77
// ---- colours ----
78
/// Panel background (white).
79
const CONTENT_BG_COLOR: ColorU = ColorU {
80
    r: 255,
81
    g: 255,
82
    b: 255,
83
    a: 255,
84
};
85
/// Panel border (#cccccc).
86
const CONTENT_BORDER_COLOR: ColorU = ColorU {
87
    r: 204,
88
    g: 204,
89
    b: 204,
90
    a: 255,
91
};
92

            
93
/// Callback function type invoked when a popover is toggled. The [`PopoverState`]
94
/// carries the *new* open/closed value.
95
pub type PopoverOnToggleCallbackType = extern "C" fn(RefAny, CallbackInfo, PopoverState) -> Update;
96
impl_widget_callback!(
97
    PopoverOnToggle,
98
    OptionPopoverOnToggle,
99
    PopoverOnToggleCallback,
100
    PopoverOnToggleCallbackType
101
);
102

            
103
azul_core::impl_managed_callback! {
104
    wrapper:        PopoverOnToggleCallback,
105
    info_ty:        CallbackInfo,
106
    return_ty:      Update,
107
    default_ret:    Update::DoNothing,
108
    invoker_static: POPOVER_ON_TOGGLE_INVOKER,
109
    invoker_ty:     AzPopoverOnToggleCallbackInvoker,
110
    thunk_fn:       az_popover_on_toggle_callback_thunk,
111
    setter_fn:      AzApp_setPopoverOnToggleCallbackInvoker,
112
    from_handle_fn: AzPopoverOnToggleCallback_createFromHostHandle,
113
    extra_args:     [ state: PopoverState ],
114
}
115

            
116
/// A click-triggered floating panel anchored to an arbitrary [`Dom`].
117
#[derive(Debug, Clone, PartialEq, Eq)]
118
#[repr(C)]
119
pub struct Popover {
120
    /// Runtime state (`open`) plus the optional toggle callback.
121
    pub popover_state: PopoverStateWrapper,
122
    /// The element that, when clicked, toggles the panel.
123
    pub anchor: Dom,
124
    /// The content shown inside the floating panel.
125
    pub content: Dom,
126
    /// Style of the positioning wrapper around the trigger + panel.
127
    /// Style for the positioning wrapper, or `None` for "no opinion" — in which
128
    /// case the widget's default applies.
129
    ///
130
    /// `None` and `Some(empty)` are different answers: the first means the
131
    /// widget picks, the second means the caller asked for no properties at all
132
    /// and gets none.
133
    pub wrapper_style: OptionCssPropertyWithConditionsVec,
134
    /// Style of the floating content panel (includes its current `display`).
135
    /// Style for the panel, or `None` for "no opinion" — in which case the style
136
    /// is derived from the open flag at render time.
137
    ///
138
    /// `None` and `Some(empty)` are different answers: the first means the
139
    /// widget picks, the second means the caller asked for no properties at all
140
    /// and gets none.
141
    pub content_style: OptionCssPropertyWithConditionsVec,
142
}
143

            
144
#[derive(Debug, Default, Clone, PartialEq, Eq)]
145
#[repr(C)]
146
pub struct PopoverStateWrapper {
147
    /// Whether the panel is currently open.
148
    pub inner: PopoverState,
149
    /// Optional: function to call when the popover is toggled.
150
    pub on_toggle: OptionPopoverOnToggle,
151
}
152

            
153
/// The open/closed state of a [`Popover`].
154
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
155
#[repr(C)]
156
pub struct PopoverState {
157
    /// `true` = panel shown, `false` (default) = panel hidden.
158
    pub open: bool,
159
}
160

            
161
/// Wrapper around the trigger + panel: an inline-block positioning context so
162
/// the absolutely-positioned panel is placed relative to it.
163
static POPOVER_WRAPPER_STYLE: &[CssPropertyWithConditions] = &[
164
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::InlineBlock)),
165
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
166
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
167
];
168

            
169
/// The clickable trigger holding the anchor.
170
static POPOVER_TRIGGER_STYLE: &[CssPropertyWithConditions] = &[
171
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::InlineBlock)),
172
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
173
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
174
];
175

            
176
/// Builds the floating-panel style. Only the `display` (open vs closed) differs
177
/// between states; all the positioning/visual props are present in both so the
178
/// runtime `set_css_property(display)` toggle has everything it needs (mirroring
179
/// the accordion body-style approach).
180
66
fn build_content_style(open: bool) -> CssPropertyWithConditionsVec {
181
66
    let display = if open {
182
32
        LayoutDisplay::Block
183
    } else {
184
34
        LayoutDisplay::None
185
    };
186
66
    let bg_vec = StyleBackgroundContentVec::from_vec(alloc::vec![StyleBackgroundContent::Color(
187
66
        CONTENT_BG_COLOR
188
66
    )]);
189
66
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
190
66
        CssPropertyWithConditions::simple(CssProperty::const_display(display)),
191
66
        CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Absolute)),
192
66
        CssPropertyWithConditions::simple(CssProperty::const_top(LayoutTop::const_px(
193
            CONTENT_OFFSET_Y,
194
        ))),
195
66
        CssPropertyWithConditions::simple(CssProperty::const_left(LayoutLeft::const_px(0))),
196
66
        CssPropertyWithConditions::simple(CssProperty::const_min_width(LayoutMinWidth::const_px(
197
            CONTENT_MIN_WIDTH,
198
        ))),
199
        // padding: 8px
200
66
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(
201
66
            LayoutPaddingTop::const_px(8,)
202
        )),
203
66
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
204
66
            LayoutPaddingBottom::const_px(8),
205
        )),
206
66
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
207
66
            LayoutPaddingLeft::const_px(8),
208
        )),
209
66
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
210
66
            LayoutPaddingRight::const_px(8),
211
        )),
212
        // border: 1px solid #cccccc
213
66
        CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
214
66
            LayoutBorderTopWidth::const_px(1),
215
        )),
216
66
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
217
66
            LayoutBorderBottomWidth::const_px(1),
218
        )),
219
66
        CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
220
66
            LayoutBorderLeftWidth::const_px(1),
221
        )),
222
66
        CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
223
66
            LayoutBorderRightWidth::const_px(1),
224
        )),
225
66
        CssPropertyWithConditions::simple(CssProperty::const_border_top_style(
226
66
            StyleBorderTopStyle {
227
66
                inner: BorderStyle::Solid,
228
66
            }
229
        )),
230
66
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
231
66
            StyleBorderBottomStyle {
232
66
                inner: BorderStyle::Solid,
233
66
            },
234
        )),
235
66
        CssPropertyWithConditions::simple(CssProperty::const_border_left_style(
236
66
            StyleBorderLeftStyle {
237
66
                inner: BorderStyle::Solid,
238
66
            }
239
        )),
240
66
        CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
241
66
            StyleBorderRightStyle {
242
66
                inner: BorderStyle::Solid,
243
66
            },
244
        )),
245
66
        CssPropertyWithConditions::simple(CssProperty::const_border_top_color(
246
66
            StyleBorderTopColor {
247
66
                inner: CONTENT_BORDER_COLOR,
248
66
            }
249
        )),
250
66
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
251
66
            StyleBorderBottomColor {
252
66
                inner: CONTENT_BORDER_COLOR,
253
66
            },
254
        )),
255
66
        CssPropertyWithConditions::simple(CssProperty::const_border_left_color(
256
66
            StyleBorderLeftColor {
257
66
                inner: CONTENT_BORDER_COLOR,
258
66
            }
259
        )),
260
66
        CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
261
66
            StyleBorderRightColor {
262
66
                inner: CONTENT_BORDER_COLOR,
263
66
            },
264
        )),
265
        // border-radius: 6px
266
66
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
267
66
            StyleBorderTopLeftRadius::const_px(CONTENT_RADIUS),
268
        )),
269
66
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
270
66
            StyleBorderTopRightRadius::const_px(CONTENT_RADIUS),
271
        )),
272
66
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
273
66
            StyleBorderBottomLeftRadius::const_px(CONTENT_RADIUS),
274
        )),
275
66
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
276
66
            StyleBorderBottomRightRadius::const_px(CONTENT_RADIUS),
277
        )),
278
66
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg_vec)),
279
    ])
280
66
}
281

            
282
impl Popover {
283
    /// Creates a popover whose `anchor`, when clicked, toggles a panel holding
284
    /// `content`. The panel starts closed.
285
    #[must_use]
286
45
    pub fn new(anchor: Dom, content: Dom) -> Self {
287
45
        Self {
288
45
            popover_state: PopoverStateWrapper::default(),
289
45
            anchor,
290
45
            content,
291
45
            wrapper_style: OptionCssPropertyWithConditionsVec::None,
292
45
            content_style: OptionCssPropertyWithConditionsVec::None,
293
45
        }
294
45
    }
295

            
296
    /// The wrapper CSS this popover renders with.
297
    ///
298
    /// `None` means no opinion, so the widget's default applies — the same
299
    /// answer both themes give, asked in one place so they cannot drift.
300
    #[must_use]
301
21
    pub fn resolved_wrapper_style(&self) -> CssPropertyWithConditionsVec {
302
21
        self.wrapper_style.clone().into_option().unwrap_or_else(|| {
303
21
            CssPropertyWithConditionsVec::from_const_slice(POPOVER_WRAPPER_STYLE)
304
21
        })
305
21
    }
306

            
307
    /// The panel CSS this popover renders with.
308
    ///
309
    /// `None` means no opinion, so the open state decides — the same answer both
310
    /// themes give, asked in one place so they cannot drift. It is also why
311
    /// `set_open` is a plain field write: the `display` that hides or shows the
312
    /// panel is derived from the flag rather than cached beside it, so the two
313
    /// can no longer disagree.
314
    #[must_use]
315
41
    pub fn resolved_content_style(&self) -> CssPropertyWithConditionsVec {
316
41
        self.content_style
317
41
            .clone()
318
41
            .into_option()
319
41
            .unwrap_or_else(|| build_content_style(self.popover_state.inner.open))
320
41
    }
321

            
322
    /// Sets whether the panel starts open.
323
    ///
324
    /// Does not touch `content_style`: the panel's `display` is resolved from
325
    /// this flag when the DOM is built.
326
    #[inline]
327
32
    pub const fn set_open(&mut self, open: bool) {
328
32
        self.popover_state.inner.open = open;
329
32
    }
330

            
331
    /// Builder-style setter for the initial open state.
332
    #[inline]
333
    #[must_use]
334
23
    pub const fn with_open(mut self, open: bool) -> Self {
335
23
        self.set_open(open);
336
23
        self
337
23
    }
338

            
339
    /// Sets the toggle callback (invoked with the new state on every toggle).
340
    #[inline]
341
8
    pub fn set_on_toggle<C: Into<PopoverOnToggleCallback>>(&mut self, data: RefAny, on_toggle: C) {
342
8
        self.popover_state.on_toggle = Some(PopoverOnToggle {
343
8
            callback: on_toggle.into(),
344
8
            refany: data,
345
8
        })
346
8
        .into();
347
8
    }
348

            
349
    /// Builder-style setter for the toggle callback.
350
    #[inline]
351
    #[must_use]
352
4
    pub fn with_on_toggle<C: Into<PopoverOnToggleCallback>>(
353
4
        mut self,
354
4
        data: RefAny,
355
4
        on_toggle: C,
356
4
    ) -> Self {
357
4
        self.set_on_toggle(data, on_toggle);
358
4
        self
359
4
    }
360

            
361
    /// Replaces `self` with a default (empty) popover and returns the original.
362
    #[inline]
363
    #[must_use]
364
3
    pub fn swap_with_default(&mut self) -> Self {
365
3
        let mut s = Self::new(Dom::default(), Dom::default());
366
3
        core::mem::swap(&mut s, self);
367
3
        s
368
3
    }
369

            
370
    /// Renders the popover into a [`Dom`] subtree with the `__azul-native-popover`
371
    /// class.
372
    #[must_use]
373
20
    pub fn dom(self) -> Dom {
374
        use azul_core::{
375
            callbacks::CoreCallback,
376
            dom::{EventFilter, HoverEventFilter},
377
            refany::OptionRefAny,
378
        };
379

            
380
        // Resolved before `self.popover_state` is moved into the callback below.
381
20
        let wrapper_style = self.resolved_wrapper_style();
382
20
        let content_style = self.resolved_content_style();
383

            
384
        // The trigger carries the click handler + the shared state. Clicking the
385
        // anchor (a descendant of the trigger) bubbles up to it (currentTarget
386
        // semantics — see `radio_group`), so `get_hit_node()` resolves to the
387
        // trigger regardless of what inside the anchor was clicked. Clicking the
388
        // panel does NOT toggle, since the panel is a sibling, not a child.
389
20
        let trigger = Dom::create_div()
390
20
            .with_ids_and_classes(IdOrClassVec::from_const_slice(POPOVER_TRIGGER_CLASS))
391
20
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(POPOVER_TRIGGER_STYLE))
392
20
            .with_tab_index(TabIndex::Auto)
393
            // Role so the accessibility tree knows what this IS:
394
            // supplementary content attached to its anchor. The NAME comes from the widget's own text,
395
            // which azul derives when a readable label is present.
396
20
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
397
20
                role: azul_core::a11y::AccessibilityRole::Tooltip,
398
20
                ..Default::default()
399
20
            })
400
20
            .with_callbacks(
401
20
                vec![CoreCallbackData {
402
20
                    event: EventFilter::Hover(HoverEventFilter::Click),
403
20
                    callback: CoreCallback {
404
20
                        cb: on_popover_toggle as usize,
405
20
                        ctx: OptionRefAny::None,
406
20
                    },
407
20
                    refany: RefAny::new(self.popover_state),
408
20
                }]
409
20
                .into(),
410
            )
411
20
            .with_children(vec![self.anchor].into());
412

            
413
20
        let content = Dom::create_div()
414
20
            .with_ids_and_classes(IdOrClassVec::from_const_slice(POPOVER_CONTENT_CLASS))
415
20
            .with_css_props(content_style)
416
20
            .with_children(vec![self.content].into());
417

            
418
20
        Dom::create_div()
419
20
            .with_ids_and_classes(IdOrClassVec::from_const_slice(POPOVER_WRAPPER_CLASS))
420
20
            .with_css_props(wrapper_style)
421
            // children: [trigger, content] — the panel is the trigger's next sibling.
422
20
            .with_children(vec![trigger, content].into())
423
20
    }
424
}
425

            
426
impl Default for Popover {
427
14
    fn default() -> Self {
428
14
        Self::new(Dom::default(), Dom::default())
429
14
    }
430
}
431

            
432
/// Trigger click handler. The hit node is the trigger (the callback-bearing
433
/// node, per `currentTarget` semantics — see `radio_group`); its next sibling is
434
/// the content panel. Flips `open`, invokes the optional user callback with the
435
/// new state, then shows/hides the panel via `display`.
436
20
extern "C" fn on_popover_toggle(mut data: RefAny, mut info: CallbackInfo) -> Update {
437
20
    let trigger = info.get_hit_node();
438
20
    let Some(content) = info.get_next_sibling(trigger) else {
439
4
        return Update::DoNothing;
440
    };
441

            
442
15
    let (now_open, result) = {
443
16
        let Some(mut pop) = data.downcast_mut::<PopoverStateWrapper>() else {
444
1
            return Update::DoNothing;
445
        };
446
15
        pop.inner.open = !pop.inner.open;
447
15
        let now_open = pop.inner.open;
448
15
        let inner = pop.inner;
449
15
        let pop = &mut *pop;
450
15
        let result = match pop.on_toggle.as_mut() {
451
3
            Some(PopoverOnToggle { callback, refany }) => {
452
3
                (callback.cb)(refany.clone(), info, inner)
453
            }
454
12
            None => Update::DoNothing,
455
        };
456
15
        (now_open, result)
457
    };
458

            
459
    // TODO2: shows/hides the panel by toggling `display` via set_css_property.
460
    // This follows the proven live-restyle pattern of accordion/check_box; the
461
    // display:none/block relayout itself is not GUI-verified in this build.
462
15
    let display = if now_open {
463
9
        LayoutDisplay::Block
464
    } else {
465
6
        LayoutDisplay::None
466
    };
467
15
    info.set_css_property(content, CssProperty::const_display(display));
468

            
469
15
    result
470
20
}
471

            
472
impl From<Popover> for Dom {
473
1
    fn from(p: Popover) -> Self {
474
1
        p.dom()
475
1
    }
476
}
477

            
478
#[cfg(test)]
479
mod autotest_generated {
480
    use std::{
481
        collections::{BTreeMap, HashMap},
482
        sync::{Arc, Mutex},
483
    };
484

            
485
    use azul_core::{
486
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
487
        geom::{LogicalRect, OptionLogicalPosition},
488
        gl::OptionGlContextPtr,
489
        hit_test::ScrollPosition,
490
        refany::OptionRefAny,
491
        resources::RendererResources,
492
        styled_dom::{NodeHierarchyItemId, StyledDom},
493
        window::{MonitorVec, RawWindowHandle},
494
    };
495
    use azul_css::{props::property::CssPropertyType, system::SystemStyle};
496
    use rust_fontconfig::FcFontCache;
497

            
498
    use super::*;
499
    #[cfg(feature = "icu")]
500
    use crate::icu::IcuLocalizerHandle;
501
    use crate::{
502
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
503
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
504
        window::{DomLayoutResult, LayoutWindow},
505
        window_state::FullWindowState,
506
    };
507

            
508
    // ------------------------------------------------------------------
509
    // Helpers
510
    // ------------------------------------------------------------------
511

            
512
    /// True if `node` carries the CSS class `name`.
513
    fn has_class(node: &Dom, name: &str) -> bool {
514
        node.root
515
            .get_ids_and_classes()
516
            .as_ref()
517
            .iter()
518
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
519
    }
520

            
521
    /// The text of a `NodeType::Text` node (`None` for any other node type).
522
    fn text_of(node: &Dom) -> Option<&str> {
523
        match node.root.get_node_type() {
524
            NodeType::Text(s) => Some(s.as_ref().as_str()),
525
            _ => None,
526
        }
527
    }
528

            
529
    /// The `display` value in a node's *inline* style, if it sets one.
530
    fn inline_display(node: &Dom) -> Option<LayoutDisplay> {
531
        node.root
532
            .style
533
            .iter_inline_properties()
534
            .find_map(|(p, _)| match p {
535
                CssProperty::Display(v) => v.get_property().copied(),
536
                _ => None,
537
            })
538
    }
539

            
540
    /// The property *types* of a style vec, in declaration order.
541
    fn prop_types(style: &CssPropertyWithConditionsVec) -> Vec<CssPropertyType> {
542
        style
543
            .as_ref()
544
            .iter()
545
            .map(|p| p.property.get_type())
546
            .collect()
547
    }
548

            
549
    /// *Every* `display` value declared in a style vec (order preserved) — a
550
    /// second entry would silently shadow the first.
551
    fn displays_in(style: &CssPropertyWithConditionsVec) -> Vec<LayoutDisplay> {
552
        style
553
            .as_ref()
554
            .iter()
555
            .filter_map(|p| match &p.property {
556
                CssProperty::Display(v) => v.get_property().copied(),
557
                _ => None,
558
            })
559
            .collect()
560
    }
561

            
562
    /// The `CssPropertyType` of `display`, without hard-coding the enum variant.
563
    fn display_ty() -> CssPropertyType {
564
        CssProperty::const_display(LayoutDisplay::None).get_type()
565
    }
566

            
567
    /// A three-node styled DOM — `root(0)` with children `trigger(1)` and
568
    /// `panel(2)` — i.e. the exact hierarchy `on_popover_toggle` walks
569
    /// (`hit node` -> `next sibling`).
570
    fn trigger_panel_dom() -> StyledDom {
571
        let styled = StyledDom::create_from_dom(
572
            Dom::create_div()
573
                .with_child(Dom::create_div())
574
                .with_child(Dom::create_div()),
575
        );
576
        assert_eq!(
577
            styled.node_hierarchy.as_ref().len(),
578
            3,
579
            "fixture must flatten to exactly wrapper/trigger/panel"
580
        );
581
        styled
582
    }
583

            
584
    /// Index of the first node carrying `class` in a flattened `StyledDom`.
585
    fn index_of_class(styled: &StyledDom, class: &str) -> usize {
586
        styled
587
            .node_data
588
            .as_ref()
589
            .iter()
590
            .position(|nd| {
591
                nd.get_ids_and_classes()
592
                    .as_ref()
593
                    .iter()
594
                    .any(|c| matches!(c, Class(s) if s.as_str() == class))
595
            })
596
            .unwrap_or_else(|| panic!("no node with class {class} in the flattened DOM"))
597
    }
598

            
599
    /// A `DomLayoutResult` with an *empty* layout tree: the toggle handler only
600
    /// walks `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
601
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
602
        DomLayoutResult {
603
            styled_dom,
604
            layout_tree: LayoutTree {
605
                nodes: Vec::new(),
606
                warm: Vec::new(),
607
                cold: Vec::new(),
608
                root: 0,
609
                dom_to_layout: BTreeMap::new(),
610
                children_arena: Vec::new(),
611
                children_offsets: Vec::new(),
612
                subtree_needs_intrinsic: Vec::new(),
613
            },
614
            calculated_positions: Vec::new(),
615
            viewport: LogicalRect::zero(),
616
            display_list: Arc::new(DisplayList::default()),
617
            scroll_ids: HashMap::new(),
618
            scroll_id_to_node_id: HashMap::new(),
619
        }
620
    }
621

            
622
    /// Invokes `on_popover_toggle` against a `LayoutWindow` holding `styled` (or
623
    /// nothing at all, when `styled` is `None`), with `hit` as the hit node.
624
    /// Returns the `Update` plus every recorded `CallbackChange`.
625
    fn run_toggle(
626
        styled: Option<StyledDom>,
627
        hit: usize,
628
        data: RefAny,
629
    ) -> (Update, Vec<CallbackChange>) {
630
        let mut layout_window =
631
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
632
        if let Some(sd) = styled {
633
            layout_window
634
                .layout_results
635
                .insert(DomId::ROOT_ID, layout_result(sd));
636
        }
637

            
638
        let renderer_resources = RendererResources::default();
639
        let previous_window_state: Option<FullWindowState> = None;
640
        let current_window_state = FullWindowState::default();
641
        let gl_context = OptionGlContextPtr::None;
642
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
643
            BTreeMap::new();
644
        let window_handle = RawWindowHandle::Unsupported;
645
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
646

            
647
        let ref_data = CallbackInfoRefData {
648
            layout_window: &layout_window,
649
            renderer_resources: &renderer_resources,
650
            previous_window_state: &previous_window_state,
651
            current_window_state: &current_window_state,
652
            gl_context: &gl_context,
653
            current_scroll_manager: &scroll_states,
654
            current_window_handle: &window_handle,
655
            system_callbacks: &system_callbacks,
656
            system_style: Arc::new(SystemStyle::default()),
657
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
658
            #[cfg(feature = "icu")]
659
            icu_localizer: IcuLocalizerHandle::default(),
660
            ctx: OptionRefAny::None,
661
        };
662

            
663
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
664

            
665
        let info = CallbackInfo::new(
666
            &ref_data,
667
            &changes,
668
            DomNodeId {
669
                dom: DomId::ROOT_ID,
670
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
671
            },
672
            OptionLogicalPosition::None,
673
            OptionLogicalPosition::None,
674
        );
675

            
676
        let update = on_popover_toggle(data, info);
677
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
678
        (update, recorded)
679
    }
680

            
681
    /// Every `display` write recorded in the change log, as `(node index, display)`.
682
    fn display_writes(changes: &[CallbackChange]) -> Vec<(usize, LayoutDisplay)> {
683
        let mut out = Vec::new();
684
        for change in changes {
685
            if let CallbackChange::ChangeNodeCssProperties {
686
                node_id,
687
                properties,
688
                ..
689
            } = change
690
            {
691
                for p in properties.as_ref() {
692
                    if let CssProperty::Display(v) = p {
693
                        if let Some(d) = v.get_property() {
694
                            out.push((node_id.index(), *d));
695
                        }
696
                    }
697
                }
698
            }
699
        }
700
        out
701
    }
702

            
703
    /// `open` of a `PopoverStateWrapper` payload.
704
    fn payload_open(data: &mut RefAny) -> bool {
705
        data.downcast_ref::<PopoverStateWrapper>()
706
            .expect("payload must still be a PopoverStateWrapper")
707
            .inner
708
            .open
709
    }
710

            
711
    /// Records the states it is invoked with; used as a user `on_toggle`.
712
    struct ToggleLog {
713
        calls: Vec<bool>,
714
    }
715

            
716
    extern "C" fn record_toggle(mut data: RefAny, _: CallbackInfo, state: PopoverState) -> Update {
717
        if let Some(mut log) = data.downcast_mut::<ToggleLog>() {
718
            log.calls.push(state.open);
719
        }
720
        Update::RefreshDom
721
    }
722

            
723
    extern "C" fn toggle_do_nothing(_: RefAny, _: CallbackInfo, _: PopoverState) -> Update {
724
        Update::DoNothing
725
    }
726

            
727
    fn toggle_cb(f: PopoverOnToggleCallbackType) -> PopoverOnToggleCallback {
728
        f.into()
729
    }
730

            
731
    // ------------------------------------------------------------------
732
    // build_content_style
733
    // ------------------------------------------------------------------
734

            
735
    #[test]
736
    fn content_style_open_and_closed_differ_only_in_display() {
737
        let closed = build_content_style(false);
738
        let open = build_content_style(true);
739

            
740
        assert_eq!(
741
            closed.len(),
742
            open.len(),
743
            "both states must declare the same props so the runtime display toggle has everything \
744
             it needs"
745
        );
746
        assert_eq!(prop_types(&closed), prop_types(&open));
747

            
748
        let differing: Vec<usize> = closed
749
            .as_ref()
750
            .iter()
751
            .zip(open.as_ref().iter())
752
            .enumerate()
753
            .filter_map(|(i, (c, o))| (c != o).then_some(i))
754
            .collect();
755

            
756
        assert_eq!(
757
            differing.len(),
758
            1,
759
            "exactly one declaration may differ between open and closed"
760
        );
761
        assert_eq!(
762
            closed.as_ref()[differing[0]].property.get_type(),
763
            display_ty(),
764
            "the only difference must be `display`"
765
        );
766
    }
767

            
768
    #[test]
769
    fn content_style_declares_display_exactly_once_and_correctly() {
770
        // A second `display` declaration would shadow the first and make the
771
        // open/closed state unobservable.
772
        assert_eq!(
773
            displays_in(&build_content_style(false)),
774
            alloc::vec![LayoutDisplay::None]
775
        );
776
        assert_eq!(
777
            displays_in(&build_content_style(true)),
778
            alloc::vec![LayoutDisplay::Block]
779
        );
780
    }
781

            
782
    #[test]
783
    fn content_style_has_no_duplicate_property_types() {
784
        for open in [false, true] {
785
            let mut types = prop_types(&build_content_style(open));
786
            let declared = types.len();
787
            assert!(declared > 0, "the panel style must not be empty");
788
            types.sort_unstable();
789
            types.dedup();
790
            assert_eq!(
791
                types.len(),
792
                declared,
793
                "a duplicated property type would make the later declaration silently win (open = \
794
                 {open})"
795
            );
796
        }
797
    }
798

            
799
    #[test]
800
    fn content_style_is_pure_and_unconditional() {
801
        for open in [false, true] {
802
            let a = build_content_style(open);
803
            let b = build_content_style(open);
804
            assert_eq!(
805
                a, b,
806
                "build_content_style must be a pure function of `open`"
807
            );
808
            assert!(
809
                a.as_ref().iter().all(|p| p.apply_if.as_ref().is_empty()),
810
                "the panel style must apply unconditionally — a stray condition would leave the \
811
                 panel unstyled (open = {open})"
812
            );
813
        }
814
    }
815

            
816
    #[test]
817
    fn content_style_carries_the_documented_geometry_in_both_states() {
818
        // The positioning props must be present whether the panel is open or
819
        // closed, otherwise the runtime `set_css_property(display)` toggle would
820
        // reveal an unpositioned panel.
821
        let expected = alloc::vec![
822
            CssPropertyWithConditions::simple(CssProperty::const_position(
823
                LayoutPosition::Absolute
824
            )),
825
            CssPropertyWithConditions::simple(CssProperty::const_top(LayoutTop::const_px(
826
                CONTENT_OFFSET_Y
827
            ))),
828
            CssPropertyWithConditions::simple(CssProperty::const_left(LayoutLeft::const_px(0))),
829
            CssPropertyWithConditions::simple(CssProperty::const_min_width(
830
                LayoutMinWidth::const_px(CONTENT_MIN_WIDTH)
831
            )),
832
        ];
833

            
834
        for open in [false, true] {
835
            let style = build_content_style(open);
836
            for e in &expected {
837
                assert!(
838
                    style.as_ref().contains(e),
839
                    "{:?} missing from the {} panel style",
840
                    e.property.get_type(),
841
                    if open { "open" } else { "closed" }
842
                );
843
            }
844
        }
845
    }
846

            
847
    // ------------------------------------------------------------------
848
    // Popover::new / Default
849
    // ------------------------------------------------------------------
850

            
851
    #[test]
852
    fn new_stores_both_doms_and_starts_closed() {
853
        let anchor = Dom::create_div().with_child(
854
            Dom::create_text_do_not_use_without_block_level_wrapper("anchor"),
855
        );
856
        let content = Dom::create_text_do_not_use_without_block_level_wrapper("panel");
857
        let pop = Popover::new(anchor.clone(), content.clone());
858

            
859
        assert_eq!(pop.anchor, anchor, "the anchor must be stored verbatim");
860
        assert_eq!(pop.content, content, "the content must be stored verbatim");
861
        assert!(
862
            !pop.popover_state.inner.open,
863
            "a fresh popover must start closed"
864
        );
865
        assert!(
866
            pop.popover_state.on_toggle.is_none(),
867
            "Popover::new sets no callback"
868
        );
869
        assert_eq!(
870
            pop.resolved_content_style(),
871
            build_content_style(false),
872
            "content_style must match the closed state it was constructed with"
873
        );
874
        assert_eq!(
875
            pop.resolved_wrapper_style(),
876
            CssPropertyWithConditionsVec::from_const_slice(POPOVER_WRAPPER_STYLE)
877
        );
878
    }
879

            
880
    #[test]
881
    fn default_equals_new_with_empty_doms() {
882
        assert_eq!(
883
            Popover::default(),
884
            Popover::new(Dom::default(), Dom::default())
885
        );
886
        assert!(!Popover::default().popover_state.inner.open);
887
    }
888

            
889
    #[test]
890
    fn new_survives_extreme_doms() {
891
        // a 128-deep anchor and a 2000-sibling panel: nothing may be truncated,
892
        // reordered or recursed into during construction.
893
        let mut deep = Dom::create_text_do_not_use_without_block_level_wrapper("leaf");
894
        for _ in 0..128 {
895
            deep = Dom::create_div().with_child(deep);
896
        }
897
        let wide_children: Vec<Dom> = (0..2000)
898
            .map(|i| Dom::create_text_do_not_use_without_block_level_wrapper(alloc::format!("{i}")))
899
            .collect();
900
        let wide = Dom::create_div().with_children(wide_children.clone().into());
901

            
902
        let pop = Popover::new(deep.clone(), wide.clone());
903

            
904
        assert_eq!(pop.anchor, deep);
905
        assert_eq!(pop.content, wide);
906
        assert_eq!(pop.content.children.as_ref().len(), 2000);
907
        assert!(!pop.popover_state.inner.open);
908
    }
909

            
910
    #[test]
911
    fn new_accepts_the_same_dom_as_anchor_and_content() {
912
        // aliasing the two arguments must produce two independent subtrees, not
913
        // one shared (and later doubly-mounted) node.
914
        let shared = Dom::create_div()
915
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("x"));
916
        let pop = Popover::new(shared.clone(), shared.clone());
917

            
918
        assert_eq!(pop.anchor, shared);
919
        assert_eq!(pop.content, shared);
920

            
921
        let dom = pop.dom();
922
        let children = dom.children.as_ref();
923
        assert_eq!(
924
            text_of(&children[0].children.as_ref()[0].children.as_ref()[0]),
925
            Some("x")
926
        );
927
        assert_eq!(
928
            text_of(&children[1].children.as_ref()[0].children.as_ref()[0]),
929
            Some("x")
930
        );
931
    }
932

            
933
    // ------------------------------------------------------------------
934
    // set_open / with_open
935
    // ------------------------------------------------------------------
936

            
937
    #[test]
938
    fn set_open_round_trips_state_and_style() {
939
        // The panel style used to be stored beside the flag and rebuilt on every
940
        // write, so a setter that updated one and not the other left the panel
941
        // visible while the flag said closed. It is resolved from the flag now;
942
        // this asks the resolver, which is where the invariant lives.
943
        let mut pop = Popover::new(
944
            Dom::create_text_do_not_use_without_block_level_wrapper("a"),
945
            Dom::create_text_do_not_use_without_block_level_wrapper("c"),
946
        );
947

            
948
        // repeats and flips: the style must follow the flag on every write,
949
        // including redundant ones.
950
        for open in [true, false, false, true, true, false, true] {
951
            pop.set_open(open);
952
            assert_eq!(pop.popover_state.inner.open, open);
953
            assert_eq!(
954
                pop.resolved_content_style(),
955
                build_content_style(open),
956
                "content_style desynced from the open flag"
957
            );
958
            assert_eq!(
959
                displays_in(&pop.resolved_content_style()),
960
                alloc::vec![if open {
961
                    LayoutDisplay::Block
962
                } else {
963
                    LayoutDisplay::None
964
                }]
965
            );
966
        }
967

            
968
        // the restyle must not touch the payload doms
969
        assert_eq!(
970
            pop.anchor,
971
            Dom::create_text_do_not_use_without_block_level_wrapper("a")
972
        );
973
        assert_eq!(
974
            pop.content,
975
            Dom::create_text_do_not_use_without_block_level_wrapper("c")
976
        );
977
    }
978

            
979
    #[test]
980
    fn with_open_matches_set_open() {
981
        for open in [false, true] {
982
            let mut mutated = Popover::new(
983
                Dom::create_text_do_not_use_without_block_level_wrapper("a"),
984
                Dom::create_text_do_not_use_without_block_level_wrapper("c"),
985
            );
986
            mutated.set_open(open);
987
            let built = Popover::new(
988
                Dom::create_text_do_not_use_without_block_level_wrapper("a"),
989
                Dom::create_text_do_not_use_without_block_level_wrapper("c"),
990
            )
991
            .with_open(open);
992
            assert_eq!(
993
                built, mutated,
994
                "builder and setter must agree (open = {open})"
995
            );
996
        }
997
    }
998

            
999
    #[test]
    fn with_open_last_write_wins() {
        let base = Popover::new(Dom::create_div(), Dom::create_div());
        assert!(
            !base
                .clone()
                .with_open(true)
                .with_open(false)
                .popover_state
                .inner
                .open
        );
        assert!(
            base.clone()
                .with_open(false)
                .with_open(true)
                .popover_state
                .inner
                .open
        );
        assert!(
            base.clone()
                .with_open(true)
                .with_open(true)
                .popover_state
                .inner
                .open,
            "applying the same value twice must be idempotent"
        );
        // the *style* must follow the last write too, not the first
        assert_eq!(
            base.with_open(true)
                .with_open(false)
                .resolved_content_style(),
            build_content_style(false)
        );
    }
    // ------------------------------------------------------------------
    // set_on_toggle / with_on_toggle
    // ------------------------------------------------------------------
    #[test]
    fn set_on_toggle_last_call_wins() {
        let mut pop = Popover::default();
        pop.set_on_toggle(RefAny::new(1u8), toggle_cb(toggle_do_nothing));
        assert!(pop.popover_state.on_toggle.is_some());
        // a second call must *replace* (not append / leak / panic)
        pop.set_on_toggle(RefAny::new(9i64), toggle_cb(record_toggle));
        let set = pop.popover_state.on_toggle.as_ref().expect("still Some");
        assert_eq!(set.refany.get_type_id(), RefAny::new(0i64).get_type_id());
        assert_eq!(set.callback, toggle_cb(record_toggle));
        assert_ne!(set.callback, toggle_cb(toggle_do_nothing));
    }
    #[test]
    fn set_on_toggle_does_not_disturb_state_style_or_doms() {
        let mut pop = Popover::new(
            Dom::create_text_do_not_use_without_block_level_wrapper("a"),
            Dom::create_text_do_not_use_without_block_level_wrapper("c"),
        )
        .with_open(true);
        let style_before = pop.resolved_content_style().clone();
        pop.set_on_toggle(RefAny::new(0u8), toggle_cb(toggle_do_nothing));
        assert!(pop.popover_state.inner.open, "open flag must survive");
        assert_eq!(
            pop.resolved_content_style(),
            style_before,
            "style must survive"
        );
        assert_eq!(
            pop.anchor,
            Dom::create_text_do_not_use_without_block_level_wrapper("a")
        );
        assert_eq!(
            pop.content,
            Dom::create_text_do_not_use_without_block_level_wrapper("c")
        );
    }
    #[test]
    fn with_on_toggle_matches_set_on_toggle() {
        let built = Popover::default().with_on_toggle(RefAny::new(7u32), toggle_cb(record_toggle));
        let mut mutated = Popover::default();
        mutated.set_on_toggle(RefAny::new(7u32), toggle_cb(record_toggle));
        assert!(built.popover_state.on_toggle.is_some());
        assert_eq!(
            built.popover_state.on_toggle.as_ref().unwrap().callback,
            mutated.popover_state.on_toggle.as_ref().unwrap().callback
        );
        // the builder form must not disturb the rest of the widget
        assert_eq!(built.anchor, Dom::default());
        assert!(!built.popover_state.inner.open);
        assert_eq!(built.resolved_content_style(), build_content_style(false));
    }
    #[test]
    fn on_toggle_refany_is_shared_not_copied() {
        let mut shared = RefAny::new(ToggleLog { calls: Vec::new() });
        let pop = Popover::default().with_on_toggle(shared.clone(), toggle_cb(record_toggle));
        // a write through the widget's handle is visible through the caller's
        {
            let stored = pop.popover_state.on_toggle.as_ref().unwrap();
            let mut handle = stored.refany.clone();
            handle
                .downcast_mut::<ToggleLog>()
                .expect("payload type preserved")
                .calls
                .push(true);
        }
        assert_eq!(
            shared.downcast_ref::<ToggleLog>().unwrap().calls.as_slice(),
            &[true]
        );
    }
    // ------------------------------------------------------------------
    // swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_moves_all_state_out() {
        let mut pop = Popover::new(
            Dom::create_text_do_not_use_without_block_level_wrapper("a"),
            Dom::create_text_do_not_use_without_block_level_wrapper("c"),
        )
        .with_open(true)
        .with_on_toggle(RefAny::new(5u8), toggle_cb(record_toggle));
        let original = pop.swap_with_default();
        assert_eq!(
            original.anchor,
            Dom::create_text_do_not_use_without_block_level_wrapper("a")
        );
        assert_eq!(
            original.content,
            Dom::create_text_do_not_use_without_block_level_wrapper("c")
        );
        assert!(original.popover_state.inner.open);
        assert!(original.popover_state.on_toggle.is_some());
        assert_eq!(original.resolved_content_style(), build_content_style(true));
        assert_eq!(
            pop,
            Popover::default(),
            "self must be left as a default popover"
        );
        assert!(
            pop.popover_state.on_toggle.is_none(),
            "self must lose the callback"
        );
        assert!(!pop.popover_state.inner.open, "self must be re-closed");
        assert_eq!(pop.resolved_content_style(), build_content_style(false));
    }
    #[test]
    fn swap_with_default_twice_is_a_noop() {
        let mut pop = Popover::default();
        let first = pop.swap_with_default();
        assert_eq!(first, Popover::default());
        let second = pop.swap_with_default();
        assert_eq!(second, Popover::default());
        assert_eq!(pop, Popover::default());
    }
    // ------------------------------------------------------------------
    // Popover::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_structure_classes_and_callback() {
        let dom = Popover::new(
            Dom::create_text_do_not_use_without_block_level_wrapper("anchor"),
            Dom::create_text_do_not_use_without_block_level_wrapper("panel"),
        )
        .dom();
        assert!(has_class(&dom, "__azul-native-popover"));
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 2, "the wrapper is exactly [trigger, panel]");
        let (trigger, panel) = (&children[0], &children[1]);
        assert!(has_class(trigger, "__azul-native-popover-trigger"));
        assert!(has_class(panel, "__azul-native-popover-content"));
        // the caller's doms are wrapped, not rewritten
        assert_eq!(text_of(&trigger.children.as_ref()[0]), Some("anchor"));
        assert_eq!(text_of(&panel.children.as_ref()[0]), Some("panel"));
        // the trigger is focusable and carries exactly one MouseUp handler
        assert!(matches!(trigger.root.get_tab_index(), Some(TabIndex::Auto)));
        let cbs = trigger.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_popover_toggle as usize);
        // the panel must NOT be clickable — the documented behaviour is that
        // clicking *inside* the panel does not close it.
        assert!(
            panel.root.get_callbacks().as_ref().is_empty(),
            "the panel must carry no callbacks"
        );
    }
    #[test]
    fn dom_panel_display_follows_open_state() {
        for open in [false, true] {
            let dom = Popover::new(Dom::create_div(), Dom::create_div())
                .with_open(open)
                .dom();
            let panel = &dom.children.as_ref()[1];
            assert_eq!(
                inline_display(panel),
                Some(if open {
                    LayoutDisplay::Block
                } else {
                    LayoutDisplay::None
                }),
                "the rendered panel's display must match the open flag"
            );
        }
    }
    #[test]
    fn dom_payload_is_the_popover_state() {
        for open in [false, true] {
            let dom = Popover::new(Dom::create_div(), Dom::create_div())
                .with_open(open)
                .dom();
            let mut payload = dom.children.as_ref()[0].root.get_callbacks().as_ref()[0]
                .refany
                .clone();
            let state = payload
                .downcast_ref::<PopoverStateWrapper>()
                .expect("the trigger payload must be a PopoverStateWrapper");
            assert_eq!(
                state.inner.open, open,
                "the trigger's payload must agree with the panel's display"
            );
            assert!(state.on_toggle.is_none(), "no user callback was set");
        }
    }
    #[test]
    fn dom_keeps_the_user_callback_payload_alive() {
        let log = RefAny::new(ToggleLog { calls: Vec::new() });
        let mut kept = log.clone();
        let dom = Popover::new(Dom::create_div(), Dom::create_div())
            .with_on_toggle(log, toggle_cb(record_toggle))
            .dom();
        let mut payload = dom.children.as_ref()[0].root.get_callbacks().as_ref()[0]
            .refany
            .clone();
        assert!(
            payload
                .downcast_ref::<PopoverStateWrapper>()
                .unwrap()
                .on_toggle
                .is_some(),
            "the user callback must survive the move into the trigger payload"
        );
        // ...and the caller's handle to the shared payload is still valid (no free)
        assert!(kept.downcast_ref::<ToggleLog>().unwrap().calls.is_empty());
    }
    #[test]
    fn each_dom_gets_its_own_state_refany() {
        let a = Popover::default().dom();
        let b = Popover::default().dom();
        let ra = a.children.as_ref()[0].root.get_callbacks().as_ref()[0]
            .refany
            .clone();
        let rb = b.children.as_ref()[0].root.get_callbacks().as_ref()[0]
            .refany
            .clone();
        assert_ne!(ra, rb, "two popovers must not share toggle state");
    }
    #[test]
    fn dom_child_count_cache_stays_consistent() {
        // deep + wide payloads: `estimated_total_children` must still equal the
        // real descendant count, otherwise the compact-DOM arena under-allocates
        // and panics later.
        let mut deep = Dom::create_text_do_not_use_without_block_level_wrapper("leaf");
        for _ in 0..64 {
            deep = Dom::create_div().with_child(deep);
        }
        let wide_children: Vec<Dom> = (0..256).map(|_| Dom::create_div()).collect();
        let wide = Dom::create_div().with_children(wide_children.into());
        let dom = Popover::new(deep, wide).dom();
        assert_eq!(
            dom.estimated_total_children,
            dom.recompute_estimated_total_children(),
            "cached descendant count desynced from the real tree"
        );
    }
    #[test]
    fn dom_of_default_popover_is_well_formed() {
        let dom = Popover::default().dom();
        assert!(has_class(&dom, "__azul-native-popover"));
        assert_eq!(dom.children.as_ref().len(), 2);
        assert_eq!(
            inline_display(&dom.children.as_ref()[1]),
            Some(LayoutDisplay::None),
            "a default popover renders a hidden panel"
        );
        assert_eq!(
            dom.estimated_total_children,
            dom.recompute_estimated_total_children()
        );
    }
    #[test]
    fn from_popover_for_dom_matches_dom_structurally() {
        // `Dom::from(p) == p.dom()` cannot be asserted directly: every `dom()`
        // call mints a fresh `RefAny` for the trigger payload, and two distinct
        // `RefAny`s never compare equal. Compare the observable structure.
        let make = || {
            Popover::new(
                Dom::create_text_do_not_use_without_block_level_wrapper("a"),
                Dom::create_text_do_not_use_without_block_level_wrapper("c"),
            )
            .with_open(true)
        };
        let via_from = Dom::from(make());
        let via_dom = make().dom();
        assert!(has_class(&via_from, "__azul-native-popover"));
        assert_eq!(via_from.children.as_ref().len(), 2);
        assert!(has_class(
            &via_from.children.as_ref()[0],
            "__azul-native-popover-trigger"
        ));
        assert!(has_class(
            &via_from.children.as_ref()[1],
            "__azul-native-popover-content"
        ));
        assert_eq!(
            inline_display(&via_from.children.as_ref()[1]),
            inline_display(&via_dom.children.as_ref()[1])
        );
        assert_eq!(
            via_from.children.as_ref()[1].children,
            via_dom.children.as_ref()[1].children
        );
        assert_eq!(
            via_from.estimated_total_children,
            via_dom.estimated_total_children
        );
    }
    // ------------------------------------------------------------------
    // on_popover_toggle
    // ------------------------------------------------------------------
    #[test]
    fn toggle_without_any_layout_result_is_a_noop() {
        let mut data = RefAny::new(PopoverStateWrapper::default());
        let (update, changes) = run_toggle(None, 0, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "nothing may be restyled without a panel"
        );
        assert!(!payload_open(&mut data), "state must not flip");
    }
    #[test]
    fn toggle_without_next_sibling_does_not_flip_state() {
        // node 2 is the *last* child -> no next sibling -> early return, and
        // crucially `open` must NOT have been toggled.
        let mut data = RefAny::new(PopoverStateWrapper {
            inner: PopoverState { open: true },
            on_toggle: None.into(),
        });
        let (update, changes) = run_toggle(Some(trigger_panel_dom()), 2, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(payload_open(&mut data), "state must be untouched");
    }
    #[test]
    fn toggle_with_stale_hit_node_is_a_noop() {
        let mut data = RefAny::new(PopoverStateWrapper::default());
        // node 999 does not exist in the 3-node fixture
        let (update, changes) = run_toggle(Some(trigger_panel_dom()), 999, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(!payload_open(&mut data));
    }
    #[test]
    fn toggle_with_foreign_payload_is_a_noop() {
        // the callback-bearing node carries a RefAny of the *wrong* type
        let data = RefAny::new(0xdead_beef_u64);
        let (update, changes) = run_toggle(Some(trigger_panel_dom()), 1, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign payload must not restyle the panel"
        );
    }
    #[test]
    fn toggle_flips_state_and_panel_display() {
        let mut data = RefAny::new(PopoverStateWrapper::default());
        // closed -> open
        let (update, changes) = run_toggle(Some(trigger_panel_dom()), 1, data.clone());
        assert_eq!(update, Update::DoNothing, "no user callback -> DoNothing");
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(2usize, LayoutDisplay::Block)]
        );
        assert!(payload_open(&mut data));
        // open -> closed (same payload, so the flip must be stateful)
        let (update, changes) = run_toggle(Some(trigger_panel_dom()), 1, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(2usize, LayoutDisplay::None)]
        );
        assert!(!payload_open(&mut data));
    }
    #[test]
    fn toggle_is_an_involution_over_many_clicks() {
        let mut data = RefAny::new(PopoverStateWrapper::default());
        for i in 0..8u32 {
            let (_, changes) = run_toggle(Some(trigger_panel_dom()), 1, data.clone());
            let expected_open = i % 2 == 0;
            assert_eq!(
                display_writes(&changes),
                alloc::vec![(
                    2usize,
                    if expected_open {
                        LayoutDisplay::Block
                    } else {
                        LayoutDisplay::None
                    }
                )],
                "click {i} wrote the wrong display"
            );
            assert_eq!(payload_open(&mut data), expected_open);
        }
        // an even number of clicks returns to the initial state
        assert!(!payload_open(&mut data));
    }
    #[test]
    fn toggle_display_agrees_with_build_content_style() {
        // the runtime override and the static style must not disagree, otherwise
        // a rebuild would flip the panel back.
        let data = RefAny::new(PopoverStateWrapper::default());
        let (_, changes) = run_toggle(Some(trigger_panel_dom()), 1, data);
        assert_eq!(
            display_writes(&changes)
                .into_iter()
                .map(|(_, d)| d)
                .collect::<Vec<_>>(),
            displays_in(&build_content_style(true))
        );
    }
    #[test]
    fn toggle_invokes_user_callback_with_the_new_state() {
        let mut log = RefAny::new(ToggleLog { calls: Vec::new() });
        let data = RefAny::new(PopoverStateWrapper {
            inner: PopoverState { open: false },
            on_toggle: Some(PopoverOnToggle {
                callback: toggle_cb(record_toggle),
                refany: log.clone(),
            })
            .into(),
        });
        let (update, changes) = run_toggle(Some(trigger_panel_dom()), 1, data.clone());
        // the user's return value wins over the internal DoNothing
        assert_eq!(update, Update::RefreshDom);
        // ...and the panel is still restyled, even though the user callback ran
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(2usize, LayoutDisplay::Block)]
        );
        assert_eq!(
            log.downcast_ref::<ToggleLog>().unwrap().calls.as_slice(),
            &[true],
            "the callback must receive the *new* (post-flip) state"
        );
        // a second click reports the closed state
        let (_, _) = run_toggle(Some(trigger_panel_dom()), 1, data);
        assert_eq!(
            log.downcast_ref::<ToggleLog>().unwrap().calls.as_slice(),
            &[true, false]
        );
    }
    #[test]
    fn toggle_still_restyles_when_the_user_callback_does_nothing() {
        let data = RefAny::new(PopoverStateWrapper {
            inner: PopoverState { open: false },
            on_toggle: Some(PopoverOnToggle {
                callback: toggle_cb(toggle_do_nothing),
                refany: RefAny::new(0u8),
            })
            .into(),
        });
        let (update, changes) = run_toggle(Some(trigger_panel_dom()), 1, data);
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(2usize, LayoutDisplay::Block)],
            "the panel must be shown regardless of what the user callback returns"
        );
    }
    #[test]
    fn toggle_targets_the_panel_in_a_really_rendered_popover() {
        // End-to-end: the handler assumes "the hit trigger's next sibling is the
        // panel". Verify that against the DOM `Popover::dom()` actually builds,
        // rather than against a hand-made fixture.
        let styled =
            StyledDom::create_from_dom(Popover::new(Dom::create_div(), Dom::create_div()).dom());
        let trigger_idx = index_of_class(&styled, "__azul-native-popover-trigger");
        let panel_idx = index_of_class(&styled, "__azul-native-popover-content");
        let data = RefAny::new(PopoverStateWrapper::default());
        let (_, changes) = run_toggle(Some(styled), trigger_idx, data);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(panel_idx, LayoutDisplay::Block)],
            "the toggle must restyle the popover's own panel, not a stray sibling"
        );
    }
    #[test]
    fn toggle_on_the_wrapper_node_does_not_touch_the_panel() {
        // Clicking the *wrapper* (node 0, the root) must not flip anything: the
        // root has no next sibling.
        let styled =
            StyledDom::create_from_dom(Popover::new(Dom::create_div(), Dom::create_div()).dom());
        let wrapper_idx = index_of_class(&styled, "__azul-native-popover");
        let mut data = RefAny::new(PopoverStateWrapper::default());
        let (update, changes) = run_toggle(Some(styled), wrapper_idx, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(!payload_open(&mut data));
    }
}