1
//! Modal / dialog widget — an in-app overlay dialog (NOT the native OS file/
2
//! message dialogs, which live in the `dialog` module; this is the custom in-app
3
//! variant). A blend of [`crate::widgets::frame::Frame`] (the bordered, elevated
4
//! content panel) and [`crate::widgets::popover::Popover`] (overlay show/hide via
5
//! `set_css_property(display)` driven by a toggled state).
6
//!
7
//! Structure: a full-area *backdrop* (`position: absolute`, covering its parent,
8
//! semi-transparent black) that centres a *panel* holding an optional title, an
9
//! optional "x" close button (absolutely positioned in the panel's top-right
10
//! corner), and the arbitrary `content: Dom`. The whole thing is hidden by
11
//! default (`display: none`) and shown by building it with `with_open(true)` (or
12
//! by the host flipping it). Clicking the close button flips `open` to `false`,
13
//! invokes the optional user `on_close(state)`, and hides the backdrop via
14
//! `set_css_property(display: none)` (mirroring popover's live restyle).
15
//!
16
//! TODO2 — several "real modal" behaviours are NOT reachable from a widget
17
//! handler and are deliberately omitted (be honest rather than fake them):
18
//!   * **Focus-trap** (confining keyboard focus to the dialog while open) depends on the focus
19
//!     model and is not controllable from a widget handler.
20
//!   * **Escape-to-close** depends on a global key handler the widget does not own (the
21
//!     panel/backdrop are not keyboard-focused), so it is not wired.
22
//!   * **Backdrop-click-to-close** is NOT wired: with `currentTarget` hit semantics (see
23
//!     `popover`), a click handler on the backdrop reports the backdrop as the hit node even when
24
//!     the *panel* (a descendant) was clicked, so it cannot distinguish an outside click from an
25
//!     inside click — wiring it would close the dialog when clicking its own content. Only the
26
//!     explicit "x" closes it.
27
//!   * **Covering sibling widgets**: the backdrop is `position: absolute` and relies on paint order
28
//!     (being a later sibling) to overlay other content; there is no real stacking-context /
29
//!     z-index. Place the modal as the LAST child of a positioned, full-size container for a
30
//!     correct overlay.
31
//!   * The `display:none/flex` relayout itself is not GUI-verified in this build.
32
//!
33
//! Key types: [`Modal`], [`ModalState`], [`ModalOnClose`].
34

            
35
use azul_core::{
36
    callbacks::{CoreCallback, CoreCallbackData, Update},
37
    dom::{Dom, DomVec, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
38
    refany::RefAny,
39
};
40
use azul_css::{
41
    dynamic_selector::{
42
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
43
    },
44
    impl_option_inner,
45
    props::{
46
        basic::{
47
            color::ColorU,
48
            font::{StyleFontFamily, StyleFontFamilyVec},
49
            PixelValue, StyleFontSize,
50
        },
51
        layout::{
52
            LayoutAlignItems, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow, LayoutHeight,
53
            LayoutJustifyContent, LayoutLeft, LayoutMaxWidth, LayoutMinWidth, LayoutPaddingBottom,
54
            LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop, LayoutPosition, LayoutRight,
55
            LayoutTop, LayoutWidth,
56
        },
57
        property::{CssProperty, *},
58
        style::{
59
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
60
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
61
            StyleBorderBottomColor, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius,
62
            StyleBorderBottomStyle, StyleBorderLeftColor, StyleBorderLeftStyle,
63
            StyleBorderRightColor, StyleBorderRightStyle, StyleBorderTopColor,
64
            StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderTopStyle, StyleCursor,
65
            StyleTextAlign, StyleTextColor, StyleUserSelect,
66
        },
67
    },
68
    AzString,
69
};
70

            
71
use crate::callbacks::{Callback, CallbackInfo};
72

            
73
static MODAL_BACKDROP_CLASS: &[IdOrClass] =
74
    &[Class(AzString::from_const_str("__azul-native-modal"))];
75
static MODAL_PANEL_CLASS: &[IdOrClass] =
76
    &[Class(AzString::from_const_str("__azul-native-modal-panel"))];
77
static MODAL_TITLE_CLASS: &[IdOrClass] =
78
    &[Class(AzString::from_const_str("__azul-native-modal-title"))];
79
static MODAL_CLOSE_CLASS: &[IdOrClass] =
80
    &[Class(AzString::from_const_str("__azul-native-modal-close"))];
81
static MODAL_CONTENT_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
82
    "__azul-native-modal-content",
83
))];
84

            
85
const SYSTEM_UI_STR: AzString = AzString::from_const_str("system:ui");
86
const SYSTEM_UI_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SYSTEM_UI_STR)];
87
const SYSTEM_UI_FAMILY: StyleFontFamilyVec =
88
    StyleFontFamilyVec::from_const_slice(SYSTEM_UI_FAMILIES);
89

            
90
// ---- layout (logical px) ----
91
const PANEL_MIN_WIDTH: isize = 280;
92
const PANEL_MAX_WIDTH: isize = 520;
93
const PANEL_RADIUS: isize = 8;
94

            
95
// ---- colours ----
96
/// Semi-transparent black backdrop (rgba(0,0,0,0.5)).
97
const BACKDROP_COLOR: ColorU = ColorU {
98
    r: 0,
99
    g: 0,
100
    b: 0,
101
    a: 128,
102
};
103
const PANEL_BG_COLOR: ColorU = ColorU {
104
    r: 255,
105
    g: 255,
106
    b: 255,
107
    a: 255,
108
};
109
const PANEL_BORDER_COLOR: ColorU = ColorU {
110
    r: 204,
111
    g: 204,
112
    b: 204,
113
    a: 255,
114
}; // #cccccc
115
const TITLE_COLOR: ColorU = ColorU {
116
    r: 33,
117
    g: 37,
118
    b: 41,
119
    a: 255,
120
}; // #212529
121
const CLOSE_COLOR: ColorU = ColorU {
122
    r: 108,
123
    g: 117,
124
    b: 125,
125
    a: 255,
126
}; // #6c757d
127

            
128
/// Callback invoked when the modal's "x" close button is clicked. The
129
/// [`ModalState`] carries the *new* (`false`) open value.
130
pub type ModalOnCloseCallbackType = extern "C" fn(RefAny, CallbackInfo, ModalState) -> Update;
131
impl_widget_callback!(
132
    ModalOnClose,
133
    OptionModalOnClose,
134
    ModalOnCloseCallback,
135
    ModalOnCloseCallbackType
136
);
137

            
138
azul_core::impl_managed_callback! {
139
    wrapper:        ModalOnCloseCallback,
140
    info_ty:        CallbackInfo,
141
    return_ty:      Update,
142
    default_ret:    Update::DoNothing,
143
    invoker_static: MODAL_ON_CLOSE_INVOKER,
144
    invoker_ty:     AzModalOnCloseCallbackInvoker,
145
    thunk_fn:       az_modal_on_close_callback_thunk,
146
    setter_fn:      AzApp_setModalOnCloseCallbackInvoker,
147
    from_handle_fn: AzModalOnCloseCallback_createFromHostHandle,
148
    extra_args:     [ state: ModalState ],
149
}
150

            
151
/// An in-app overlay dialog holding arbitrary content, with an optional title and
152
/// close button.
153
#[derive(Debug, Clone, PartialEq, Eq)]
154
#[repr(C)]
155
pub struct Modal {
156
    /// Runtime state (`open`) plus the optional close callback.
157
    pub modal_state: ModalStateWrapper,
158
    /// The dialog title (empty = no title bar).
159
    pub title: AzString,
160
    /// The arbitrary content shown inside the panel.
161
    pub content: Dom,
162
    /// Whether to render the "x" close button.
163
    pub show_close_button: bool,
164
    /// Style of the full-area backdrop (includes its current `display`).
165
    pub backdrop_style: OptionCssPropertyWithConditionsVec,
166
}
167

            
168
#[derive(Debug, Default, Clone, PartialEq, Eq)]
169
#[repr(C)]
170
pub struct ModalStateWrapper {
171
    /// Whether the dialog is currently open (shown).
172
    pub inner: ModalState,
173
    /// Optional: function to call when the dialog is closed.
174
    pub on_close: OptionModalOnClose,
175
}
176

            
177
/// The open/closed state of a [`Modal`].
178
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
179
#[repr(C)]
180
pub struct ModalState {
181
    /// `true` = dialog shown, `false` (default) = dialog hidden.
182
    pub open: bool,
183
}
184

            
185
/// Builds the backdrop style. Only the `display` (open vs closed) differs; all
186
/// other props are present in both so the runtime `set_css_property(display)`
187
/// toggle has everything it needs (mirroring popover/accordion).
188
84
fn build_backdrop_style(open: bool) -> CssPropertyWithConditionsVec {
189
84
    let display = if open {
190
33
        LayoutDisplay::Flex
191
    } else {
192
51
        LayoutDisplay::None
193
    };
194
84
    let bg_vec = StyleBackgroundContentVec::from_vec(alloc::vec![StyleBackgroundContent::Color(
195
84
        BACKDROP_COLOR
196
84
    )]);
197
84
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
198
84
        CssPropertyWithConditions::simple(CssProperty::const_display(display)),
199
84
        CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Absolute)),
200
84
        CssPropertyWithConditions::simple(CssProperty::const_top(LayoutTop::const_px(0))),
201
84
        CssPropertyWithConditions::simple(CssProperty::const_left(LayoutLeft::const_px(0))),
202
        // Cover the full parent (see the z-order TODO2 — depends on a full-size,
203
        // positioned parent).
204
84
        CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::Px(
205
84
            PixelValue::const_percent(100),
206
84
        ))),
207
84
        CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::Px(
208
84
            PixelValue::const_percent(100),
209
84
        ))),
210
        // Centre the panel.
211
84
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
212
84
            LayoutFlexDirection::Row,
213
        )),
214
84
        CssPropertyWithConditions::simple(CssProperty::const_justify_content(
215
84
            LayoutJustifyContent::Center,
216
        )),
217
84
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
218
84
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
219
            0
220
        ))),
221
84
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg_vec)),
222
    ])
223
84
}
224

            
225
/// The centred dialog panel: a bordered, rounded white box (frame-like). Elevation
226
/// is conveyed by the dimmed backdrop behind it + the border/radius; a drop
227
/// `box-shadow` is intentionally omitted (it requires a runtime-heap shadow value
228
/// — see `progressbar.rs` — and is not needed for a clear modal read).
229
static MODAL_PANEL_STYLE: &[CssPropertyWithConditions] = &[
230
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
231
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
232
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
233
        LayoutFlexDirection::Column,
234
    )),
235
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
236
    CssPropertyWithConditions::simple(CssProperty::const_min_width(LayoutMinWidth::const_px(
237
        PANEL_MIN_WIDTH,
238
    ))),
239
    CssPropertyWithConditions::simple(CssProperty::const_max_width(LayoutMaxWidth::const_px(
240
        PANEL_MAX_WIDTH,
241
    ))),
242
    // padding: 20px
243
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
244
        20,
245
    ))),
246
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
247
        LayoutPaddingBottom::const_px(20),
248
    )),
249
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
250
        LayoutPaddingLeft::const_px(20),
251
    )),
252
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
253
        LayoutPaddingRight::const_px(20),
254
    )),
255
    // border: 1px solid #cccccc
256
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
257
        LayoutBorderTopWidth::const_px(1),
258
    )),
259
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
260
        LayoutBorderBottomWidth::const_px(1),
261
    )),
262
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
263
        LayoutBorderLeftWidth::const_px(1),
264
    )),
265
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
266
        LayoutBorderRightWidth::const_px(1),
267
    )),
268
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
269
        inner: BorderStyle::Solid,
270
    })),
271
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
272
        StyleBorderBottomStyle {
273
            inner: BorderStyle::Solid,
274
        },
275
    )),
276
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
277
        inner: BorderStyle::Solid,
278
    })),
279
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
280
        StyleBorderRightStyle {
281
            inner: BorderStyle::Solid,
282
        },
283
    )),
284
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
285
        inner: PANEL_BORDER_COLOR,
286
    })),
287
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
288
        StyleBorderBottomColor {
289
            inner: PANEL_BORDER_COLOR,
290
        },
291
    )),
292
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
293
        inner: PANEL_BORDER_COLOR,
294
    })),
295
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
296
        StyleBorderRightColor {
297
            inner: PANEL_BORDER_COLOR,
298
        },
299
    )),
300
    // border-radius: 8px
301
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
302
        StyleBorderTopLeftRadius::const_px(PANEL_RADIUS),
303
    )),
304
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
305
        StyleBorderTopRightRadius::const_px(PANEL_RADIUS),
306
    )),
307
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
308
        StyleBorderBottomLeftRadius::const_px(PANEL_RADIUS),
309
    )),
310
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
311
        StyleBorderBottomRightRadius::const_px(PANEL_RADIUS),
312
    )),
313
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(14))),
314
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SYSTEM_UI_FAMILY)),
315
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
316
        StyleBackgroundContentVec::from_const_slice(&[StyleBackgroundContent::Color(
317
            PANEL_BG_COLOR,
318
        )]),
319
    )),
320
];
321

            
322
/// Title style: larger, bold-ish dark text with a bottom gap; right padding keeps
323
/// it clear of the absolutely-positioned "x".
324
static MODAL_TITLE_STYLE: &[CssPropertyWithConditions] = &[
325
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
326
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(18))),
327
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
328
        inner: TITLE_COLOR,
329
    })),
330
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
331
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
332
        LayoutPaddingRight::const_px(24),
333
    )),
334
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
335
        LayoutPaddingBottom::const_px(12),
336
    )),
337
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
338
];
339

            
340
/// "x" close-button style: an absolutely-positioned pointer-cursor glyph in the
341
/// panel's top-right corner.
342
static MODAL_CLOSE_STYLE: &[CssPropertyWithConditions] = &[
343
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Absolute)),
344
    CssPropertyWithConditions::simple(CssProperty::const_top(LayoutTop::const_px(8))),
345
    CssPropertyWithConditions::simple(CssProperty::const_right(LayoutRight::const_px(12))),
346
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(22))),
347
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
348
        inner: CLOSE_COLOR,
349
    })),
350
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
351
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
352
];
353

            
354
/// Content-wrapper style: takes the remaining vertical space.
355
static MODAL_CONTENT_STYLE: &[CssPropertyWithConditions] = &[
356
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
357
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
358
];
359

            
360
impl Modal {
361
    /// Creates a new (closed) modal holding `content`, with a "x" close button and
362
    /// no title.
363
    #[must_use]
364
111
    pub fn create(content: Dom) -> Self {
365
111
        Self {
366
111
            modal_state: ModalStateWrapper::default(),
367
111
            title: AzString::from_const_str(""),
368
111
            content,
369
111
            show_close_button: true,
370
111
            backdrop_style: OptionCssPropertyWithConditionsVec::None,
371
111
        }
372
111
    }
373

            
374
    /// The backdrop CSS this modal renders with.
375
    ///
376
    /// `None` means no opinion, so the open state decides — the same answer both
377
    /// themes give, asked in one place so they cannot drift. It is also why
378
    /// `set_open` is a plain field write: there is no cached vec left to keep in
379
    /// step, and therefore no way for a stored `display` to contradict
380
    /// `modal_state.inner.open`.
381
    #[must_use]
382
66
    pub fn resolved_backdrop_style(&self) -> CssPropertyWithConditionsVec {
383
66
        self.backdrop_style
384
66
            .clone()
385
66
            .into_option()
386
66
            .unwrap_or_else(|| build_backdrop_style(self.modal_state.inner.open))
387
66
    }
388

            
389
    /// Sets the dialog title (empty = no title).
390
    #[inline]
391
62
    pub fn set_title(&mut self, title: AzString) {
392
62
        self.title = title;
393
62
    }
394

            
395
    /// Builder-style setter for the title.
396
    #[inline]
397
    #[must_use]
398
44
    pub fn with_title(mut self, title: AzString) -> Self {
399
44
        self.set_title(title);
400
44
        self
401
44
    }
402

            
403
    /// Replaces the content shown inside the panel.
404
    #[inline]
405
3
    pub fn set_content(&mut self, content: Dom) {
406
3
        self.content = content;
407
3
    }
408

            
409
    /// Builder-style setter for the content.
410
    #[inline]
411
    #[must_use]
412
1
    pub fn with_content(mut self, content: Dom) -> Self {
413
1
        self.set_content(content);
414
1
        self
415
1
    }
416

            
417
    /// Sets whether the dialog is currently open.
418
    ///
419
    /// Does not touch `backdrop_style`: the `display` that hides or shows the
420
    /// backdrop is resolved from this flag when the DOM is built.
421
    #[inline]
422
37
    pub const fn set_open(&mut self, open: bool) {
423
37
        self.modal_state.inner.open = open;
424
37
    }
425

            
426
    /// Builder-style setter for the initial open state.
427
    #[inline]
428
    #[must_use]
429
25
    pub const fn with_open(mut self, open: bool) -> Self {
430
25
        self.set_open(open);
431
25
        self
432
25
    }
433

            
434
    /// Sets whether the "x" close button is shown.
435
    #[inline]
436
14
    pub const fn set_close_button(&mut self, show: bool) {
437
14
        self.show_close_button = show;
438
14
    }
439

            
440
    /// Builder-style setter for the close-button flag.
441
    #[inline]
442
    #[must_use]
443
9
    pub const fn with_close_button(mut self, show: bool) -> Self {
444
9
        self.set_close_button(show);
445
9
        self
446
9
    }
447

            
448
    /// Sets the close callback (invoked with the new state when "x" is clicked).
449
    #[inline]
450
7
    pub fn set_on_close<C: Into<ModalOnCloseCallback>>(&mut self, data: RefAny, on_close: C) {
451
7
        self.modal_state.on_close = Some(ModalOnClose {
452
7
            callback: on_close.into(),
453
7
            refany: data,
454
7
        })
455
7
        .into();
456
7
    }
457

            
458
    /// Builder-style setter for the close callback.
459
    #[inline]
460
    #[must_use]
461
4
    pub fn with_on_close<C: Into<ModalOnCloseCallback>>(
462
4
        mut self,
463
4
        data: RefAny,
464
4
        on_close: C,
465
4
    ) -> Self {
466
4
        self.set_on_close(data, on_close);
467
4
        self
468
4
    }
469

            
470
    /// Replaces `self` with a default (empty, closed) modal and returns the original.
471
    #[inline]
472
    #[must_use]
473
4
    pub fn swap_with_default(&mut self) -> Self {
474
4
        let mut s = Self::create(Dom::default());
475
4
        core::mem::swap(&mut s, self);
476
4
        s
477
4
    }
478

            
479
    /// Renders the modal into a [`Dom`] subtree with the `__azul-native-modal`
480
    /// class (the backdrop).
481
    #[must_use]
482
50
    pub fn dom(self) -> Dom {
483
        // Resolved before `self.modal_state` is moved into the close callback.
484
50
        let backdrop_style = self.resolved_backdrop_style();
485

            
486
        // Panel children: [close?, title?, content]. The close button is
487
        // absolutely positioned (top-right), so its document order does not affect
488
        // the title/content stacking.
489
50
        let mut panel_children = Vec::new();
490

            
491
50
        if self.show_close_button {
492
44
            let close = crate::widgets::widget_p_with_text(AzString::from_const_str("\u{00D7}"))
493
44
                .with_ids_and_classes(IdOrClassVec::from_const_slice(MODAL_CLOSE_CLASS))
494
44
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(MODAL_CLOSE_STYLE))
495
44
                .with_tab_index(TabIndex::Auto)
496
44
            // Role so the accessibility tree knows what this IS:
497
44
            // a dialog traps focus and is announced as one. The NAME comes from the widget's own text,
498
44
            // which azul derives when a readable label is present.
499
44
            // This is the CLOSE BUTTON, not the container — the tab stop is on
500
44
            // the dismiss affordance. Its label is a multiplication sign: a
501
44
            // picture of an X, not a name. Hence an explicit name, and
502
44
            // PushButton rather than the container's role.
503
44
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
504
44
                role: azul_core::a11y::AccessibilityRole::PushButton,
505
44
                accessibility_name: Some(AzString::from_const_str("Close")).into(),
506
44
                ..Default::default()
507
44
            })
508
44
                .with_callbacks(
509
44
                    alloc::vec![CoreCallbackData {
510
44
                        event: azul_core::dom::EventFilter::Hover(
511
44
                            azul_core::dom::HoverEventFilter::Click,
512
44
                        ),
513
44
                        callback: CoreCallback {
514
44
                            cb: on_modal_close as usize,
515
44
                            ctx: azul_core::refany::OptionRefAny::None,
516
44
                        },
517
44
                        refany: RefAny::new(self.modal_state),
518
44
                    }]
519
44
                    .into(),
520
44
                );
521
44
            panel_children.push(close);
522
44
        }
523

            
524
50
        if !self.title.as_str().is_empty() {
525
22
            let title = crate::widgets::widget_p_with_text(self.title)
526
22
                .with_ids_and_classes(IdOrClassVec::from_const_slice(MODAL_TITLE_CLASS))
527
22
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
528
22
                    MODAL_TITLE_STYLE,
529
22
                ));
530
22
            panel_children.push(title);
531
28
        }
532

            
533
50
        let content = Dom::create_div()
534
50
            .with_ids_and_classes(IdOrClassVec::from_const_slice(MODAL_CONTENT_CLASS))
535
50
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
536
50
                MODAL_CONTENT_STYLE,
537
            ))
538
50
            .with_children(DomVec::from_vec(alloc::vec![self.content]));
539
50
        panel_children.push(content);
540

            
541
50
        let panel = Dom::create_div()
542
50
            .with_ids_and_classes(IdOrClassVec::from_const_slice(MODAL_PANEL_CLASS))
543
50
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
544
50
                MODAL_PANEL_STYLE,
545
            ))
546
50
            .with_children(DomVec::from_vec(panel_children));
547

            
548
50
        Dom::create_div()
549
50
            .with_ids_and_classes(IdOrClassVec::from_const_slice(MODAL_BACKDROP_CLASS))
550
50
            .with_css_props(backdrop_style)
551
50
            .with_children(DomVec::from_vec(alloc::vec![panel]))
552
50
    }
553
}
554

            
555
impl Default for Modal {
556
7
    fn default() -> Self {
557
7
        Self::create(Dom::default())
558
7
    }
559
}
560

            
561
/// "x" close-button click handler. The hit node is the close button (the
562
/// callback-bearing node, per `currentTarget` semantics — see `popover`); its
563
/// parent is the panel and the panel's parent is the backdrop. Flips `open` to
564
/// `false`, invokes the optional user callback, then hides the backdrop via
565
/// `display: none`.
566
15
extern "C" fn on_modal_close(mut data: RefAny, mut info: CallbackInfo) -> Update {
567
15
    let close_node = info.get_hit_node();
568
15
    let Some(panel) = info.get_parent(close_node) else {
569
3
        return Update::DoNothing;
570
    };
571
12
    let Some(backdrop) = info.get_parent(panel) else {
572
1
        return Update::DoNothing;
573
    };
574

            
575
9
    let result = {
576
11
        let Some(mut modal) = data.downcast_mut::<ModalStateWrapper>() else {
577
2
            return Update::DoNothing;
578
        };
579
9
        modal.inner.open = false;
580
9
        let inner = modal.inner;
581
9
        let modal = &mut *modal;
582
9
        match modal.on_close.as_mut() {
583
5
            Some(ModalOnClose { callback, refany }) => (callback.cb)(refany.clone(), info, inner),
584
4
            None => Update::DoNothing,
585
        }
586
    };
587

            
588
    // TODO2: hides the whole dialog by toggling `display: none` via
589
    // set_css_property (the proven live-restyle pattern of popover/alert); the
590
    // relayout itself is not GUI-verified in this build.
591
9
    info.set_css_property(backdrop, CssProperty::const_display(LayoutDisplay::None));
592

            
593
9
    result
594
15
}
595

            
596
impl From<Modal> for Dom {
597
1
    fn from(m: Modal) -> Self {
598
1
        m.dom()
599
1
    }
600
}
601

            
602
#[cfg(test)]
603
mod autotest_generated {
604
    use std::{
605
        collections::{BTreeMap, HashMap},
606
        sync::{Arc, Mutex},
607
    };
608

            
609
    use azul_core::{
610
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
611
        geom::{LogicalRect, OptionLogicalPosition},
612
        gl::OptionGlContextPtr,
613
        hit_test::ScrollPosition,
614
        refany::OptionRefAny,
615
        resources::RendererResources,
616
        styled_dom::{NodeHierarchyItemId, StyledDom},
617
        window::{MonitorVec, RawWindowHandle},
618
    };
619
    use azul_css::system::SystemStyle;
620
    use rust_fontconfig::FcFontCache;
621

            
622
    use super::*;
623
    #[cfg(feature = "icu")]
624
    use crate::icu::IcuLocalizerHandle;
625
    use crate::{
626
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
627
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
628
        window::{DomLayoutResult, LayoutWindow},
629
        window_state::FullWindowState,
630
    };
631

            
632
    // ------------------------------------------------------------------
633
    // Helpers
634
    // ------------------------------------------------------------------
635

            
636
    /// Titles a caller can realistically hand to a modal. The widget never parses
637
    /// or normalises its title — every one of these has to reach the DOM
638
    /// byte-for-byte, and every *non-empty* one has to produce a title node (the
639
    /// `is_empty()` gate is byte-length based, so a zero-width space counts).
640
    const ADVERSARIAL_TEXT: [&str; 8] = [
641
        "",
642
        " ",
643
        "a\0b",
644
        "e\u{0301}\u{0301}\u{0301}",
645
        "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}",
646
        "\u{202E}gnirts desrever\u{202C}",
647
        "\u{FFFD}\u{FEFF}\t\n",
648
        "\u{200B}",
649
    ];
650

            
651
    /// True if `node` carries the CSS class `name`.
652
    fn has_class(node: &Dom, name: &str) -> bool {
653
        node.root
654
            .get_ids_and_classes()
655
            .as_ref()
656
            .iter()
657
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
658
    }
659

            
660
    /// The text of a text node, looking through the `<p>` block wrapper the
661
    /// label convention mandates (`p > text`).
662
    fn text_of(node: &Dom) -> Option<&str> {
663
        match node.root.get_node_type() {
664
            NodeType::Text(s) => Some(s.as_ref().as_str()),
665
            NodeType::P => match node.children.as_ref() {
666
                [only] => match only.root.get_node_type() {
667
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
668
                    _ => None,
669
                },
670
                _ => None,
671
            },
672
            _ => None,
673
        }
674
    }
675

            
676
    /// The properties of a style vec, in declaration order.
677
    fn style_props(style: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
678
        style.as_ref().iter().map(|p| p.property.clone()).collect()
679
    }
680

            
681
    /// The *kind* of every declared property, in order (ignores the values).
682
    fn property_types(
683
        style: &CssPropertyWithConditionsVec,
684
    ) -> Vec<core::mem::Discriminant<CssProperty>> {
685
        style
686
            .as_ref()
687
            .iter()
688
            .map(|p| core::mem::discriminant(&p.property))
689
            .collect()
690
    }
691

            
692
    /// A node's *inline* style properties, in declaration order.
693
    fn inline_props(node: &Dom) -> Vec<CssProperty> {
694
        node.root
695
            .style
696
            .iter_inline_properties()
697
            .map(|(p, _)| p.clone())
698
            .collect()
699
    }
700

            
701
    /// The `display` value declared in a style vec.
702
    fn display_of(style: &CssPropertyWithConditionsVec) -> Option<LayoutDisplay> {
703
        style.as_ref().iter().find_map(|p| match &p.property {
704
            CssProperty::Display(v) => v.get_property().copied(),
705
            _ => None,
706
        })
707
    }
708

            
709
    /// The `display` value in a node's *inline* style.
710
    fn inline_display(node: &Dom) -> Option<LayoutDisplay> {
711
        node.root
712
            .style
713
            .iter_inline_properties()
714
            .find_map(|(p, _)| match p {
715
                CssProperty::Display(v) => v.get_property().copied(),
716
                _ => None,
717
            })
718
    }
719

            
720
    /// The `background-color` of a style vec (first background layer only).
721
    fn background_color(style: &CssPropertyWithConditionsVec) -> Option<ColorU> {
722
        style.as_ref().iter().find_map(|p| match &p.property {
723
            CssProperty::BackgroundContent(v) => match v.get_property()?.as_ref().first()? {
724
                StyleBackgroundContent::Color(c) => Some(*c),
725
                _ => None,
726
            },
727
            _ => None,
728
        })
729
    }
730

            
731
    /// The one and only child of the backdrop: the panel.
732
    fn panel(dom: &Dom) -> &Dom {
733
        let kids = dom.children.as_ref();
734
        assert_eq!(kids.len(), 1, "the backdrop must have exactly one child");
735
        assert!(
736
            has_class(&kids[0], "__azul-native-modal-panel"),
737
            "the backdrop's only child must be the panel"
738
        );
739
        &kids[0]
740
    }
741

            
742
    fn panel_kids(dom: &Dom) -> &[Dom] {
743
        panel(dom).children.as_ref()
744
    }
745

            
746
    /// The first node in the tree carrying `class` (pre-order).
747
    fn find_class<'a>(dom: &'a Dom, class: &str) -> Option<&'a Dom> {
748
        if has_class(dom, class) {
749
            return Some(dom);
750
        }
751
        dom.children
752
            .as_ref()
753
            .iter()
754
            .find_map(|c| find_class(c, class))
755
    }
756

            
757
    /// Total number of nodes in a `Dom` tree.
758
    fn node_count(dom: &Dom) -> usize {
759
        1 + dom.children.as_ref().iter().map(node_count).sum::<usize>()
760
    }
761

            
762
    /// Total number of callbacks registered anywhere in a `Dom` tree.
763
    fn count_callbacks(dom: &Dom) -> usize {
764
        dom.root.get_callbacks().as_ref().len()
765
            + dom
766
                .children
767
                .as_ref()
768
                .iter()
769
                .map(count_callbacks)
770
                .sum::<usize>()
771
    }
772

            
773
    /// A `depth`-deep chain of nested divs (adversarial content).
774
    fn nested_content(depth: usize) -> Dom {
775
        let mut d = Dom::create_div();
776
        for _ in 0..depth {
777
            d = Dom::create_div().with_child(d);
778
        }
779
        d
780
    }
781

            
782
    /// The exact backdrop style the widget documents, for a given `display`.
783
    fn expected_backdrop(display: LayoutDisplay) -> Vec<CssProperty> {
784
        alloc::vec![
785
            CssProperty::const_display(display),
786
            CssProperty::const_position(LayoutPosition::Absolute),
787
            CssProperty::const_top(LayoutTop::const_px(0)),
788
            CssProperty::const_left(LayoutLeft::const_px(0)),
789
            CssProperty::const_width(LayoutWidth::Px(PixelValue::const_percent(100))),
790
            CssProperty::const_height(LayoutHeight::Px(PixelValue::const_percent(100))),
791
            CssProperty::const_flex_direction(LayoutFlexDirection::Row),
792
            CssProperty::const_justify_content(LayoutJustifyContent::Center),
793
            CssProperty::const_align_items(LayoutAlignItems::Center),
794
            CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0)),
795
            CssProperty::const_background_content(StyleBackgroundContentVec::from_vec(
796
                alloc::vec![StyleBackgroundContent::Color(BACKDROP_COLOR)]
797
            )),
798
        ]
799
    }
800

            
801
    /// A `RefAny` payload recording every `ModalState` a user `on_close` sees.
802
    struct CloseLog {
803
        calls: Vec<bool>,
804
    }
805

            
806
    extern "C" fn record_close(mut data: RefAny, _: CallbackInfo, state: ModalState) -> Update {
807
        if let Some(mut log) = data.downcast_mut::<CloseLog>() {
808
            log.calls.push(state.open);
809
        }
810
        Update::RefreshDom
811
    }
812

            
813
    extern "C" fn close_do_nothing(_: RefAny, _: CallbackInfo, _: ModalState) -> Update {
814
        Update::DoNothing
815
    }
816

            
817
    fn close_cb(f: ModalOnCloseCallbackType) -> ModalOnCloseCallback {
818
        f.into()
819
    }
820

            
821
    /// `open` of a `ModalStateWrapper` payload.
822
    fn wrapper_open(data: &mut RefAny) -> bool {
823
        data.downcast_ref::<ModalStateWrapper>()
824
            .expect("payload must still be a ModalStateWrapper")
825
            .inner
826
            .open
827
    }
828

            
829
    /// The `open` flags recorded by a `CloseLog` payload.
830
    fn log_calls(data: &mut RefAny) -> Vec<bool> {
831
        data.downcast_ref::<CloseLog>()
832
            .expect("payload must still be a CloseLog")
833
            .calls
834
            .clone()
835
    }
836

            
837
    /// A `DomLayoutResult` with an *empty* layout tree: the close handler only
838
    /// walks `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
839
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
840
        DomLayoutResult {
841
            styled_dom,
842
            layout_tree: LayoutTree {
843
                nodes: Vec::new(),
844
                warm: Vec::new(),
845
                cold: Vec::new(),
846
                root: 0,
847
                dom_to_layout: BTreeMap::new(),
848
                children_arena: Vec::new(),
849
                children_offsets: Vec::new(),
850
                subtree_needs_intrinsic: Vec::new(),
851
            },
852
            calculated_positions: Vec::new(),
853
            viewport: LogicalRect::zero(),
854
            display_list: Arc::new(DisplayList::default()),
855
            scroll_ids: HashMap::new(),
856
            scroll_id_to_node_id: HashMap::new(),
857
        }
858
    }
859

            
860
    /// The flattened DOM of a default modal: `backdrop(0)`, `panel(1)`,
861
    /// `close <p>(2)`, `close text(3)`, `content-wrapper(4)`, `content(5)` —
862
    /// i.e. exactly the hierarchy `on_modal_close` walks (hit node -> parent ->
863
    /// parent). The callback lives on the `<p>`, never on the text node.
864
    fn modal_styled_dom() -> StyledDom {
865
        let styled = StyledDom::create_from_dom(Modal::create(Dom::create_div()).dom());
866
        assert_eq!(
867
            styled.node_hierarchy.as_ref().len(),
868
            6,
869
            "fixture must flatten to backdrop/panel/close <p> + text/wrapper/content"
870
        );
871
        styled
872
    }
873

            
874
    /// Invokes `on_modal_close` against a `LayoutWindow` holding `styled` (or
875
    /// nothing at all, when `styled` is `None`), with `hit` as the hit node.
876
    /// Returns the `Update` plus every recorded `CallbackChange`.
877
    fn run_close(
878
        styled: Option<StyledDom>,
879
        hit: usize,
880
        data: RefAny,
881
    ) -> (Update, Vec<CallbackChange>) {
882
        let mut layout_window =
883
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
884
        if let Some(sd) = styled {
885
            layout_window
886
                .layout_results
887
                .insert(DomId::ROOT_ID, layout_result(sd));
888
        }
889

            
890
        let renderer_resources = RendererResources::default();
891
        let previous_window_state: Option<FullWindowState> = None;
892
        let current_window_state = FullWindowState::default();
893
        let gl_context = OptionGlContextPtr::None;
894
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
895
            BTreeMap::new();
896
        let window_handle = RawWindowHandle::Unsupported;
897
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
898

            
899
        let ref_data = CallbackInfoRefData {
900
            layout_window: &layout_window,
901
            renderer_resources: &renderer_resources,
902
            previous_window_state: &previous_window_state,
903
            current_window_state: &current_window_state,
904
            gl_context: &gl_context,
905
            current_scroll_manager: &scroll_states,
906
            current_window_handle: &window_handle,
907
            system_callbacks: &system_callbacks,
908
            system_style: Arc::new(SystemStyle::default()),
909
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
910
            #[cfg(feature = "icu")]
911
            icu_localizer: IcuLocalizerHandle::default(),
912
            ctx: OptionRefAny::None,
913
        };
914

            
915
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
916

            
917
        let info = CallbackInfo::new(
918
            &ref_data,
919
            &changes,
920
            DomNodeId {
921
                dom: DomId::ROOT_ID,
922
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
923
            },
924
            OptionLogicalPosition::None,
925
            OptionLogicalPosition::None,
926
        );
927

            
928
        let update = on_modal_close(data, info);
929
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
930
        (update, recorded)
931
    }
932

            
933
    /// Every `display` write recorded in the change log, as `(node index, display)`.
934
    fn display_writes(changes: &[CallbackChange]) -> Vec<(usize, LayoutDisplay)> {
935
        let mut out = Vec::new();
936
        for change in changes {
937
            if let CallbackChange::ChangeNodeCssProperties {
938
                node_id,
939
                properties,
940
                ..
941
            } = change
942
            {
943
                for p in properties.as_ref() {
944
                    if let CssProperty::Display(v) = p {
945
                        if let Some(d) = v.get_property() {
946
                            out.push((node_id.index(), *d));
947
                        }
948
                    }
949
                }
950
            }
951
        }
952
        out
953
    }
954

            
955
    // ------------------------------------------------------------------
956
    // build_backdrop_style
957
    // ------------------------------------------------------------------
958

            
959
    #[test]
960
    fn build_backdrop_style_emits_the_documented_property_list() {
961
        assert_eq!(
962
            style_props(&build_backdrop_style(true)),
963
            expected_backdrop(LayoutDisplay::Flex)
964
        );
965
        assert_eq!(
966
            style_props(&build_backdrop_style(false)),
967
            expected_backdrop(LayoutDisplay::None)
968
        );
969
    }
970

            
971
    #[test]
972
    fn build_backdrop_style_differs_only_in_the_display() {
973
        // The doc comment promises the toggle has *everything* it needs: both
974
        // variants must declare the same properties, in the same order, with the
975
        // same values — except `display`.
976
        let open = style_props(&build_backdrop_style(true));
977
        let closed = style_props(&build_backdrop_style(false));
978

            
979
        assert_eq!(open.len(), closed.len());
980
        let diffs: Vec<usize> = (0..open.len()).filter(|i| open[*i] != closed[*i]).collect();
981
        assert_eq!(
982
            diffs,
983
            alloc::vec![0usize],
984
            "only entry 0 (display) may differ"
985
        );
986

            
987
        assert_eq!(
988
            display_of(&build_backdrop_style(true)),
989
            Some(LayoutDisplay::Flex)
990
        );
991
        assert_eq!(
992
            display_of(&build_backdrop_style(false)),
993
            Some(LayoutDisplay::None)
994
        );
995
    }
996

            
997
    #[test]
998
    fn build_backdrop_style_declares_no_property_twice() {
999
        // a duplicated property would silently shadow the earlier declaration —
        // and would make the runtime `display` toggle ambiguous
        for open in [true, false] {
            let types = property_types(&build_backdrop_style(open));
            for (i, a) in types.iter().enumerate() {
                for b in &types[i + 1..] {
                    assert_ne!(
                        a, b,
                        "open={open}: the backdrop declares the same property twice"
                    );
                }
            }
        }
    }
    #[test]
    fn build_backdrop_style_is_unconditional() {
        // nothing may be gated behind :hover/@media/... or the closed modal could
        // become visible under the wrong conditions
        for open in [true, false] {
            for p in build_backdrop_style(open).as_ref() {
                assert!(
                    p.apply_if.as_ref().is_empty(),
                    "open={open}: {:?} must be unconditional",
                    p.property
                );
            }
        }
    }
    #[test]
    fn build_backdrop_style_is_pure_and_repeatable() {
        for open in [true, false] {
            assert_eq!(build_backdrop_style(open), build_backdrop_style(open));
        }
        assert_ne!(build_backdrop_style(true), build_backdrop_style(false));
    }
    #[test]
    fn build_backdrop_style_dims_with_half_transparent_black() {
        for open in [true, false] {
            let style = build_backdrop_style(open);
            assert_eq!(
                background_color(&style),
                Some(ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 128
                }),
                "the backdrop must stay rgba(0,0,0,0.5) in both states"
            );
        }
        // a fully opaque or fully transparent backdrop would be a regression
        let alpha = BACKDROP_COLOR.a;
        assert!(
            alpha > 0 && alpha < 255,
            "backdrop alpha {alpha} must dim, not erase"
        );
    }
    // ------------------------------------------------------------------
    // Modal::create / Default
    // ------------------------------------------------------------------
    #[test]
    fn create_is_a_closed_modal_with_a_close_button_and_no_title() {
        let content = Dom::create_div().with_child(
            Dom::create_text_do_not_use_without_block_level_wrapper("hi"),
        );
        let m = Modal::create(content.clone());
        assert!(!m.modal_state.inner.open, "a fresh modal must start closed");
        assert!(m.modal_state.on_close.is_none());
        assert_eq!(m.title.as_str(), "");
        assert_eq!(m.content, content);
        assert!(m.show_close_button, "the 'x' is on by default");
        assert_eq!(
            display_of(&m.resolved_backdrop_style()),
            Some(LayoutDisplay::None)
        );
    }
    #[test]
    fn default_equals_create_with_a_default_dom() {
        assert_eq!(Modal::default(), Modal::create(Dom::default()));
        assert_eq!(Modal::default(), Modal::default());
        assert!(!Modal::default().modal_state.inner.open);
    }
    #[test]
    fn create_survives_extreme_content() {
        // deeply nested, very wide, and empty content must all be stored verbatim
        assert_eq!(node_count(&Modal::create(nested_content(200)).content), 201);
        let wide = Dom::create_div().with_children(DomVec::from_vec(
            (0..5_000).map(|_| Dom::create_div()).collect::<Vec<_>>(),
        ));
        assert_eq!(node_count(&Modal::create(wide).content), 5_001);
        // a modal whose content is *another* modal's DOM
        let inner = Modal::create(Dom::create_div()).with_title(AzString::from("inner"));
        let nested = Modal::create(inner.dom());
        assert_eq!(nested.content.children.as_ref().len(), 1);
    }
    #[test]
    fn create_is_clone_and_value_comparable() {
        let m = Modal::create(Dom::create_div()).with_title(AzString::from("t"));
        assert_eq!(m.clone(), m);
        assert_ne!(m, Modal::create(Dom::create_div()));
    }
    // ------------------------------------------------------------------
    // Modal::set_title / with_title
    // ------------------------------------------------------------------
    #[test]
    fn set_title_stores_every_adversarial_string_byte_for_byte() {
        for s in ADVERSARIAL_TEXT {
            let mut m = Modal::create(Dom::create_div());
            m.set_title(AzString::from(s));
            assert_eq!(m.title.as_str(), s, "title {s:?} must round-trip unchanged");
            assert_eq!(
                m.title.as_str().len(),
                s.len(),
                "no normalisation may happen"
            );
        }
    }
    #[test]
    fn set_title_survives_a_100k_char_title() {
        let long = "ä\u{0301}".repeat(50_000);
        let mut m = Modal::create(Dom::create_div());
        m.set_title(AzString::from(long.as_str()));
        assert_eq!(m.title.as_str(), long);
        let dom = m.dom();
        assert_eq!(
            text_of(&panel_kids(&dom)[1]),
            Some(long.as_str()),
            "the huge title must reach the DOM intact"
        );
    }
    #[test]
    fn with_title_matches_set_title_and_last_write_wins() {
        for s in ADVERSARIAL_TEXT {
            let built = Modal::create(Dom::create_div()).with_title(AzString::from(s));
            let mut mutated = Modal::create(Dom::create_div());
            mutated.set_title(AzString::from(s));
            assert_eq!(built, mutated);
        }
        let m = Modal::create(Dom::create_div())
            .with_title(AzString::from("first"))
            .with_title(AzString::from("second"))
            .with_title(AzString::from(""));
        assert_eq!(
            m.title.as_str(),
            "",
            "the last write must win, even an empty one"
        );
    }
    #[test]
    fn set_title_touches_nothing_else() {
        let content = Dom::create_div().with_child(
            Dom::create_text_do_not_use_without_block_level_wrapper("body"),
        );
        let mut m = Modal::create(content.clone()).with_open(true);
        let before = m.resolved_backdrop_style();
        m.set_title(AzString::from("Title"));
        assert!(
            m.modal_state.inner.open,
            "the title must not close the dialog"
        );
        assert_eq!(
            m.resolved_backdrop_style(),
            before,
            "the title must not rebuild the backdrop"
        );
        assert_eq!(m.content, content);
        assert!(m.show_close_button);
    }
    #[test]
    fn only_a_byte_empty_title_suppresses_the_title_node() {
        for s in ADVERSARIAL_TEXT {
            let dom = Modal::create(Dom::create_div())
                .with_title(AzString::from(s))
                .dom();
            let title = find_class(&dom, "__azul-native-modal-title");
            if s.is_empty() {
                assert!(title.is_none(), "an empty title must emit no title node");
            } else {
                let title = title.expect("a non-empty title must emit a title node");
                assert_eq!(
                    text_of(title),
                    Some(s),
                    "the title node must carry the string verbatim"
                );
            }
        }
        // documented consequence: a zero-width space is "non-empty", so it emits a
        // title node that renders as nothing but still consumes the title slot
        let zwsp = Modal::create(Dom::create_div())
            .with_title(AzString::from("\u{200B}"))
            .dom();
        assert!(find_class(&zwsp, "__azul-native-modal-title").is_some());
        assert_eq!(
            panel_kids(&zwsp).len(),
            3,
            "close + (invisible) title + content"
        );
    }
    // ------------------------------------------------------------------
    // Modal::set_content / with_content
    // ------------------------------------------------------------------
    #[test]
    fn set_content_replaces_and_last_write_wins() {
        let a = Dom::create_div()
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("a"));
        let b = Dom::create_text_do_not_use_without_block_level_wrapper("b");
        let mut m = Modal::create(a.clone());
        assert_eq!(m.content, a);
        m.set_content(b.clone());
        assert_eq!(m.content, b, "content must be replaced, not merged");
        assert_eq!(node_count(&m.content), 1);
    }
    #[test]
    fn with_content_matches_set_content_and_keeps_everything_else() {
        let content = nested_content(32);
        let built = Modal::create(Dom::create_div())
            .with_title(AzString::from("t"))
            .with_open(true)
            .with_close_button(false)
            .with_content(content.clone());
        let mut mutated = Modal::create(Dom::create_div())
            .with_title(AzString::from("t"))
            .with_open(true)
            .with_close_button(false);
        mutated.set_content(content.clone());
        assert_eq!(built, mutated);
        assert_eq!(built.content, content);
        assert_eq!(built.title.as_str(), "t");
        assert!(built.modal_state.inner.open);
        assert!(!built.show_close_button);
    }
    #[test]
    fn content_reaches_the_dom_under_the_content_wrapper() {
        let content = nested_content(64);
        let dom = Modal::create(content.clone()).dom();
        let wrapper = find_class(&dom, "__azul-native-modal-content")
            .expect("the content wrapper must exist");
        let kids = wrapper.children.as_ref();
        assert_eq!(kids.len(), 1, "the wrapper holds exactly the user content");
        assert_eq!(
            kids[0], content,
            "the content must be handed through untouched"
        );
    }
    // ------------------------------------------------------------------
    // Modal::set_open / with_open
    // ------------------------------------------------------------------
    #[test]
    fn set_open_flips_the_state_and_the_backdrop_display_together() {
        let mut m = Modal::create(Dom::create_div());
        m.set_open(true);
        assert!(m.modal_state.inner.open);
        assert_eq!(
            display_of(&m.resolved_backdrop_style()),
            Some(LayoutDisplay::Flex)
        );
        m.set_open(false);
        assert!(!m.modal_state.inner.open);
        assert_eq!(
            display_of(&m.resolved_backdrop_style()),
            Some(LayoutDisplay::None)
        );
    }
    #[test]
    fn set_open_never_leaves_two_display_declarations() {
        // The style used to be stored and rebuilt on every `set_open`, where an
        // append-instead-of-rebuild bug would grow the vec and leave two
        // conflicting `display` declarations to fight over the cascade. It is
        // resolved from `open` now, so the invariant belongs to the resolver:
        // one `display`, and it agrees with the flag.
        let mut m = Modal::create(Dom::create_div());
        let len = m.resolved_backdrop_style().as_ref().len();
        for open in [true, true, false, false, true] {
            m.set_open(open);
            let style = m.resolved_backdrop_style();
            assert_eq!(
                style.as_ref().len(),
                len,
                "the resolved style changed length with the open state"
            );
            let displays: Vec<_> = style
                .as_ref()
                .iter()
                .filter(|p| matches!(p.property, CssProperty::Display(_)))
                .collect();
            assert_eq!(displays.len(), 1, "exactly one `display` may be declared");
            assert_eq!(
                display_of(&style),
                Some(if open {
                    LayoutDisplay::Flex
                } else {
                    LayoutDisplay::None
                }),
                "the resolved `display` must follow `open`"
            );
        }
        assert!(m.modal_state.inner.open, "the last write must win");
    }
    #[test]
    fn set_open_is_idempotent() {
        let mut once = Modal::create(Dom::create_div());
        once.set_open(true);
        let mut twice = Modal::create(Dom::create_div());
        twice.set_open(true);
        twice.set_open(true);
        assert_eq!(once, twice);
    }
    #[test]
    fn with_open_matches_set_open_and_keeps_the_other_fields() {
        for open in [true, false] {
            let built = Modal::create(Dom::create_div())
                .with_title(AzString::from("t"))
                .with_open(open);
            let mut mutated = Modal::create(Dom::create_div()).with_title(AzString::from("t"));
            mutated.set_open(open);
            assert_eq!(built, mutated);
            assert_eq!(built.title.as_str(), "t");
            assert!(built.show_close_button);
        }
    }
    #[test]
    fn open_state_reaches_the_rendered_backdrop() {
        for open in [true, false] {
            let dom = Modal::create(Dom::create_div()).with_open(open).dom();
            assert_eq!(
                inline_display(&dom),
                Some(if open {
                    LayoutDisplay::Flex
                } else {
                    LayoutDisplay::None
                }),
                "open={open}: the backdrop's inline display must match"
            );
            assert!(has_class(&dom, "__azul-native-modal"));
        }
    }
    // ------------------------------------------------------------------
    // Modal::set_close_button / with_close_button
    // ------------------------------------------------------------------
    #[test]
    fn set_close_button_last_write_wins_and_touches_nothing_else() {
        let mut m = Modal::create(Dom::create_div())
            .with_title(AzString::from("t"))
            .with_open(true);
        let before = m.resolved_backdrop_style();
        for show in [false, true, false] {
            m.set_close_button(show);
            assert_eq!(m.show_close_button, show);
        }
        assert!(!m.show_close_button);
        assert_eq!(m.title.as_str(), "t");
        assert!(m.modal_state.inner.open);
        assert_eq!(m.resolved_backdrop_style(), before);
    }
    #[test]
    fn with_close_button_matches_set_close_button() {
        for show in [true, false] {
            let built = Modal::create(Dom::create_div()).with_close_button(show);
            let mut mutated = Modal::create(Dom::create_div());
            mutated.set_close_button(show);
            assert_eq!(built, mutated);
        }
    }
    #[test]
    fn hiding_the_close_button_leaves_the_modal_with_no_way_to_close_itself() {
        // TODO2 in the module docs: only the explicit "x" closes the dialog. With
        // the button off there is no callback in the whole tree at all.
        let dom = Modal::create(Dom::create_div())
            .with_close_button(false)
            .with_title(AzString::from("stuck"))
            .dom();
        assert!(find_class(&dom, "__azul-native-modal-close").is_none());
        assert_eq!(count_callbacks(&dom), 0, "no handler is wired anywhere");
        assert_eq!(panel_kids(&dom).len(), 2, "panel is [title, content] only");
    }
    // ------------------------------------------------------------------
    // Modal::set_on_close / with_on_close
    // ------------------------------------------------------------------
    #[test]
    fn set_on_close_stores_the_callback_and_replaces_rather_than_appends() {
        let mut m = Modal::create(Dom::create_div());
        assert!(m.modal_state.on_close.is_none());
        let first = RefAny::new(1u32);
        m.set_on_close(first.clone(), close_cb(record_close));
        assert!(m.modal_state.on_close.is_some());
        assert_eq!(
            m.modal_state.on_close.as_ref().unwrap().callback,
            close_cb(record_close)
        );
        let second = RefAny::new(2u32);
        m.set_on_close(second.clone(), close_cb(close_do_nothing));
        let stored = m.modal_state.on_close.as_ref().expect("still set");
        assert_eq!(
            stored.callback,
            close_cb(close_do_nothing),
            "last write wins"
        );
        assert_eq!(stored.refany, second, "the payload is replaced too");
        assert_ne!(stored.refany, first);
    }
    #[test]
    fn with_on_close_matches_set_on_close_and_keeps_everything_else() {
        let data = RefAny::new(7u64);
        let built = Modal::create(Dom::create_div())
            .with_title(AzString::from("t"))
            .with_open(true)
            .with_on_close(data.clone(), close_cb(record_close));
        let mut mutated = Modal::create(Dom::create_div())
            .with_title(AzString::from("t"))
            .with_open(true);
        mutated.set_on_close(data.clone(), close_cb(record_close));
        assert_eq!(built, mutated);
        assert_eq!(built.title.as_str(), "t");
        assert!(built.modal_state.inner.open);
        assert!(built.show_close_button);
    }
    #[test]
    fn set_on_close_does_not_switch_the_close_button_on() {
        // Unlike `Alert::set_on_dismiss`, this setter does NOT imply a close
        // button — a caller that turned the "x" off gets a callback that can
        // never fire, and `dom()` silently drops it.
        let data = RefAny::new(CloseLog { calls: Vec::new() });
        let m = Modal::create(Dom::create_div())
            .with_close_button(false)
            .with_on_close(data.clone(), close_cb(record_close));
        assert!(m.modal_state.on_close.is_some(), "the callback is stored");
        assert!(!m.show_close_button, "but the button stays off");
        assert_eq!(
            count_callbacks(&m.dom()),
            0,
            "so nothing is wired into the DOM"
        );
    }
    // ------------------------------------------------------------------
    // Modal::swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_returns_the_original_and_resets_self() {
        let content = Dom::create_div().with_child(
            Dom::create_text_do_not_use_without_block_level_wrapper("body"),
        );
        let mut m = Modal::create(content.clone())
            .with_title(AzString::from("Title"))
            .with_open(true)
            .with_close_button(false);
        let old = m.swap_with_default();
        assert_eq!(old.title.as_str(), "Title");
        assert_eq!(old.content, content);
        assert!(old.modal_state.inner.open);
        assert!(!old.show_close_button);
        assert_eq!(m, Modal::default(), "self must be a pristine modal");
        assert_eq!(m.title.as_str(), "");
        assert!(!m.modal_state.inner.open);
        assert!(m.show_close_button);
        assert_eq!(
            display_of(&m.resolved_backdrop_style()),
            Some(LayoutDisplay::None)
        );
    }
    #[test]
    fn swap_with_default_is_stable_when_repeated() {
        let mut m = Modal::create(Dom::create_div()).with_title(AzString::from("t"));
        let _first = m.swap_with_default();
        let second = m.swap_with_default();
        assert_eq!(second, Modal::default());
        assert_eq!(m, Modal::default());
    }
    #[test]
    fn swap_with_default_moves_the_callback_out_of_self() {
        let data = RefAny::new(0u8);
        let mut m =
            Modal::create(Dom::create_div()).with_on_close(data.clone(), close_cb(record_close));
        let old = m.swap_with_default();
        assert!(old.modal_state.on_close.is_some(), "the callback moves out");
        assert!(m.modal_state.on_close.is_none(), "and must not stay behind");
    }
    // ------------------------------------------------------------------
    // Modal::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_shape_is_backdrop_panel_close_content() {
        let dom = Modal::create(Dom::create_div()).dom();
        assert!(has_class(&dom, "__azul-native-modal"));
        let kids = panel_kids(&dom);
        assert_eq!(kids.len(), 2, "no title -> [close, content]");
        assert!(has_class(&kids[0], "__azul-native-modal-close"));
        assert!(has_class(&kids[1], "__azul-native-modal-content"));
        assert_eq!(node_count(&dom), 6); // close "x" is a <p> + its text leaf
    }
    #[test]
    fn dom_with_a_title_puts_the_close_button_first() {
        // document order is [close, title, content]: the "x" is absolutely
        // positioned, so it may come first without affecting the layout.
        let dom = Modal::create(Dom::create_div())
            .with_title(AzString::from("Title"))
            .dom();
        let kids = panel_kids(&dom);
        assert_eq!(kids.len(), 3);
        assert!(has_class(&kids[0], "__azul-native-modal-close"));
        assert!(has_class(&kids[1], "__azul-native-modal-title"));
        assert!(has_class(&kids[2], "__azul-native-modal-content"));
        assert_eq!(text_of(&kids[1]), Some("Title"));
        assert_eq!(node_count(&dom), 8); // close + title each: <p> + text leaf
    }
    #[test]
    fn dom_close_button_is_a_focusable_multiplication_sign_with_one_mouseup_handler() {
        let dom = Modal::create(Dom::create_div()).dom();
        let close = find_class(&dom, "__azul-native-modal-close").expect("close node");
        assert_eq!(
            text_of(close),
            Some("\u{00D7}"),
            "the glyph must be U+00D7 MULTIPLICATION SIGN, not ASCII 'x'"
        );
        assert_eq!(close.root.get_tab_index(), Some(TabIndex::Auto));
        let cbs = close.root.get_callbacks();
        assert_eq!(cbs.as_ref().len(), 1, "exactly one handler on the 'x'");
        let entry = &cbs.as_ref()[0];
        assert_eq!(
            entry.event,
            EventFilter::Hover(HoverEventFilter::Click),
            "the modal closes on mouse-up, not mouse-down"
        );
        assert_eq!(entry.callback.cb, on_modal_close as usize);
        assert_eq!(count_callbacks(&dom), 1, "and nowhere else in the tree");
    }
    #[test]
    fn dom_hands_a_snapshot_of_the_modal_state_to_the_close_button() {
        for open in [true, false] {
            let dom = Modal::create(Dom::create_div()).with_open(open).dom();
            let close = find_class(&dom, "__azul-native-modal-close").expect("close node");
            let mut payload = close.root.get_callbacks().as_ref()[0].refany.clone();
            assert_eq!(
                wrapper_open(&mut payload),
                open,
                "the payload must carry the open state at build time"
            );
        }
    }
    #[test]
    fn dom_payloads_of_two_clones_are_independent() {
        // the payload is a *snapshot*: flipping one rendered modal's state must
        // not reach through to another render of the same builder
        let m = Modal::create(Dom::create_div()).with_open(true);
        let a = m.clone().dom();
        let b = m.dom();
        let mut pa = find_class(&a, "__azul-native-modal-close")
            .expect("close")
            .root
            .get_callbacks()
            .as_ref()[0]
            .refany
            .clone();
        let mut pb = find_class(&b, "__azul-native-modal-close")
            .expect("close")
            .root
            .get_callbacks()
            .as_ref()[0]
            .refany
            .clone();
        assert_ne!(pa, pb, "two renders must not share one RefAny allocation");
        let (_update, _changes) = run_close(Some(StyledDom::create_from_dom(a)), 2, pa.clone());
        assert!(!wrapper_open(&mut pa));
        assert!(wrapper_open(&mut pb), "the other render must be untouched");
    }
    #[test]
    fn dom_applies_the_static_styles_verbatim() {
        let dom = Modal::create(Dom::create_div())
            .with_title(AzString::from("t"))
            .dom();
        let kids = panel_kids(&dom);
        let want = |s: &[CssPropertyWithConditions]| {
            s.iter().map(|p| p.property.clone()).collect::<Vec<_>>()
        };
        assert_eq!(inline_props(panel(&dom)), want(MODAL_PANEL_STYLE));
        assert_eq!(inline_props(&kids[0]), want(MODAL_CLOSE_STYLE));
        assert_eq!(inline_props(&kids[1]), want(MODAL_TITLE_STYLE));
        assert_eq!(inline_props(&kids[2]), want(MODAL_CONTENT_STYLE));
    }
    #[test]
    fn dom_backdrop_style_is_exactly_the_builders_backdrop_style() {
        for open in [true, false] {
            let m = Modal::create(Dom::create_div()).with_open(open);
            let expected = style_props(&m.resolved_backdrop_style());
            assert_eq!(inline_props(&m.dom()), expected);
        }
    }
    #[test]
    fn panel_geometry_matches_the_documented_constants() {
        let props = style_props(&CssPropertyWithConditionsVec::from_const_slice(
            MODAL_PANEL_STYLE,
        ));
        for want in [
            CssProperty::const_min_width(LayoutMinWidth::const_px(PANEL_MIN_WIDTH)),
            CssProperty::const_max_width(LayoutMaxWidth::const_px(PANEL_MAX_WIDTH)),
            CssProperty::const_border_top_left_radius(StyleBorderTopLeftRadius::const_px(
                PANEL_RADIUS,
            )),
            CssProperty::const_position(LayoutPosition::Relative),
            CssProperty::const_display(LayoutDisplay::Flex),
        ] {
            assert!(props.contains(&want), "panel style is missing {want:?}");
        }
        let (min, max) = (PANEL_MIN_WIDTH, PANEL_MAX_WIDTH);
        assert!(
            min <= max,
            "min-width {min} must not exceed max-width {max}"
        );
    }
    #[test]
    fn every_static_style_declares_each_property_at_most_once() {
        for (name, style) in [
            ("panel", MODAL_PANEL_STYLE),
            ("title", MODAL_TITLE_STYLE),
            ("close", MODAL_CLOSE_STYLE),
            ("content", MODAL_CONTENT_STYLE),
        ] {
            let types = property_types(&CssPropertyWithConditionsVec::from_const_slice(style));
            for (i, a) in types.iter().enumerate() {
                for b in &types[i + 1..] {
                    assert_ne!(a, b, "{name}: the same property is declared twice");
                }
            }
            for p in style {
                assert!(
                    p.apply_if.as_ref().is_empty(),
                    "{name}: {:?} must be unconditional",
                    p.property
                );
            }
        }
    }
    #[test]
    fn dom_survives_extreme_content_and_titles() {
        // deep nesting, a huge sibling list and an adversarial title at once
        let content = Dom::create_div().with_children(DomVec::from_vec(
            (0..2_000).map(|_| nested_content(4)).collect::<Vec<_>>(),
        ));
        let dom = Modal::create(content)
            .with_title(AzString::from("\u{202E}\u{1F469}\u{200D}\u{1F467}\0"))
            .with_open(true)
            .dom();
        // backdrop + panel + close(<p>+text) + title(<p>+text) + wrapper +
        // content root + 2000*5
        assert_eq!(node_count(&dom), 8 + 2_000 * 5);
        assert_eq!(count_callbacks(&dom), 1);
    }
    #[test]
    fn from_modal_for_dom_equals_dom() {
        // no RefAny is involved once the close button is off, so the two renders
        // are value-comparable
        let m = Modal::create(Dom::create_div())
            .with_title(AzString::from("t"))
            .with_close_button(false)
            .with_open(true);
        assert_eq!(Dom::from(m.clone()), m.dom());
    }
    #[test]
    fn two_renders_with_a_close_button_differ_only_in_the_refany_identity() {
        // RefAny equality is allocation identity, so two renders of the *same*
        // modal are NOT equal — but they are once the button (and its payload)
        // is gone.
        let m = Modal::create(Dom::create_div());
        assert_ne!(m.clone().dom(), m.clone().dom());
        let q = m.with_close_button(false);
        assert_eq!(q.clone().dom(), q.dom());
    }
    // ------------------------------------------------------------------
    // on_modal_close
    // ------------------------------------------------------------------
    #[test]
    fn close_hides_the_backdrop_and_flips_open() {
        let mut data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: OptionModalOnClose::None,
        });
        // node 2 == the close button; its parent is the panel(1), whose parent is
        // the backdrop(0)
        let (update, changes) = run_close(Some(modal_styled_dom()), 2, data.clone());
        assert_eq!(update, Update::DoNothing, "no user callback -> DoNothing");
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)],
            "the *backdrop* (not the panel or the button) must be hidden"
        );
        assert!(!wrapper_open(&mut data), "state must flip to closed");
    }
    #[test]
    fn close_invokes_the_user_callback_with_the_already_flipped_state() {
        let mut log = RefAny::new(CloseLog { calls: Vec::new() });
        let mut data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: Some(ModalOnClose {
                callback: close_cb(record_close),
                refany: log.clone(),
            })
            .into(),
        });
        let (update, changes) = run_close(Some(modal_styled_dom()), 2, data.clone());
        assert_eq!(
            update,
            Update::RefreshDom,
            "the user callback's Update is returned"
        );
        assert_eq!(
            log_calls(&mut log),
            alloc::vec![false],
            "the callback must see `open == false` (already closed)"
        );
        assert!(!wrapper_open(&mut data));
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)],
            "the backdrop is hidden even after a user callback ran"
        );
    }
    #[test]
    fn close_hides_the_backdrop_even_when_the_user_callback_does_nothing() {
        let data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: Some(ModalOnClose {
                callback: close_cb(close_do_nothing),
                refany: RefAny::new(0u8),
            })
            .into(),
        });
        let (update, changes) = run_close(Some(modal_styled_dom()), 2, data);
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)]
        );
    }
    #[test]
    fn close_twice_is_idempotent() {
        let mut log = RefAny::new(CloseLog { calls: Vec::new() });
        let mut data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: Some(ModalOnClose {
                callback: close_cb(record_close),
                refany: log.clone(),
            })
            .into(),
        });
        for _ in 0..2 {
            let (update, changes) = run_close(Some(modal_styled_dom()), 2, data.clone());
            assert_eq!(update, Update::RefreshDom);
            assert_eq!(
                display_writes(&changes),
                alloc::vec![(0usize, LayoutDisplay::None)]
            );
        }
        assert!(!wrapper_open(&mut data), "a second close must not re-open");
        assert_eq!(
            log_calls(&mut log),
            alloc::vec![false, false],
            "each click fires the callback exactly once, always with open == false"
        );
    }
    #[test]
    fn close_on_the_panel_is_a_noop_because_the_backdrop_has_no_parent() {
        // hit node 1 == the panel: parent is the backdrop(0), which has no parent
        // of its own, so the handler bails *before* touching the state
        let mut data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: OptionModalOnClose::None,
        });
        let (update, changes) = run_close(Some(modal_styled_dom()), 1, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "nothing may be restyled without a grandparent"
        );
        assert!(wrapper_open(&mut data), "state must not flip");
    }
    #[test]
    fn close_on_the_root_is_a_noop() {
        let mut data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: OptionModalOnClose::None,
        });
        let (update, changes) = run_close(Some(modal_styled_dom()), 0, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(wrapper_open(&mut data));
    }
    #[test]
    fn close_with_a_stale_hit_node_is_a_noop() {
        // node 999 does not exist in the 6-node fixture
        let mut data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: OptionModalOnClose::None,
        });
        let (update, changes) = run_close(Some(modal_styled_dom()), 999, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(wrapper_open(&mut data));
    }
    #[test]
    fn close_without_any_layout_result_is_a_noop() {
        let mut data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: OptionModalOnClose::None,
        });
        let (update, changes) = run_close(None, 2, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(wrapper_open(&mut data), "state must not flip");
    }
    #[test]
    fn close_with_a_foreign_payload_is_a_noop() {
        // the callback-bearing node carries a RefAny of the *wrong* type: the
        // downcast fails before the restyle, so nothing is hidden
        let data = RefAny::new(0xdead_beef_u64);
        let (update, changes) = run_close(Some(modal_styled_dom()), 2, data);
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign payload must not hide the backdrop"
        );
    }
    #[test]
    fn close_with_a_plain_modal_state_payload_is_a_noop() {
        // `ModalState` and `ModalStateWrapper` are different types — handing the
        // inner state alone must not be silently accepted
        let data = RefAny::new(ModalState { open: true });
        let (update, changes) = run_close(Some(modal_styled_dom()), 2, data);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn close_hides_the_grandparent_whatever_it_is() {
        // The handler hides `parent(parent(hit))` unconditionally. On a deeper
        // tree that is NOT the root — documenting why the close button has to
        // stay a direct child of the panel.
        let deep = StyledDom::create_from_dom(nested_content(3));
        assert_eq!(deep.node_hierarchy.as_ref().len(), 4);
        let data = RefAny::new(ModalStateWrapper {
            inner: ModalState { open: true },
            on_close: OptionModalOnClose::None,
        });
        let (update, changes) = run_close(Some(deep), 3, data);
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(1usize, LayoutDisplay::None)],
            "node 1 (the grandparent), not the root, gets hidden"
        );
    }
    #[test]
    fn close_end_to_end_through_the_real_dom_payload() {
        // Take the *actual* RefAny the widget wired into its close button and
        // drive the *actual* handler the widget registered against it.
        let modal = Modal::create(Dom::create_text_do_not_use_without_block_level_wrapper(
            "body",
        ))
        .with_title(AzString::from("Title"))
        .with_open(true);
        let dom = modal.dom();
        let close = find_class(&dom, "__azul-native-modal-close").expect("close node");
        let entry = &close.root.get_callbacks().as_ref()[0];
        assert_eq!(entry.callback.cb, on_modal_close as usize);
        let mut payload = entry.refany.clone();
        assert!(wrapper_open(&mut payload), "the snapshot starts open");
        let styled = StyledDom::create_from_dom(dom);
        // backdrop(0), panel(1), close <p>(2) + text(3), title <p>(4) + text(5),
        // wrapper(6), content(7)
        assert_eq!(styled.node_hierarchy.as_ref().len(), 8);
        let (update, changes) = run_close(Some(styled), 2, payload.clone());
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)]
        );
        assert!(
            !wrapper_open(&mut payload),
            "the state living in the DOM must be flipped to closed"
        );
    }
    #[test]
    fn close_end_to_end_invokes_a_user_callback_wired_through_the_builder() {
        let mut log = RefAny::new(CloseLog { calls: Vec::new() });
        let dom = Modal::create(Dom::create_div())
            .with_open(true)
            .with_on_close(log.clone(), close_cb(record_close))
            .dom();
        let payload = find_class(&dom, "__azul-native-modal-close")
            .expect("close node")
            .root
            .get_callbacks()
            .as_ref()[0]
            .refany
            .clone();
        let (update, changes) = run_close(Some(StyledDom::create_from_dom(dom)), 2, payload);
        assert_eq!(update, Update::RefreshDom);
        assert_eq!(log_calls(&mut log), alloc::vec![false]);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)]
        );
    }
    // ------------------------------------------------------------------
    // ModalState / ModalStateWrapper invariants
    // ------------------------------------------------------------------
    #[test]
    fn modal_state_defaults_to_closed_with_no_callback() {
        assert!(!ModalState::default().open);
        let w = ModalStateWrapper::default();
        assert!(!w.inner.open);
        assert!(w.on_close.is_none());
        assert_eq!(w, ModalStateWrapper::default());
    }
    #[test]
    fn modal_state_is_copy_and_value_comparable() {
        let a = ModalState { open: true };
        let b = a; // Copy
        assert_eq!(a, b);
        assert_ne!(a, ModalState { open: false });
    }
}