1
//! Toast / snackbar widget — a transient notification banner. A near-clone of
2
//! [`crate::widgets::alert::Alert`] (a coloured message box with a "x" dismiss
3
//! affordance and a `visible` state) that, instead of sitting inline, floats as
4
//! an overlay pinned to a corner of its positioned parent
5
//! (`position: absolute; bottom; right`).
6
//!
7
//! Like [`crate::widgets::alert::Alert`] / [`crate::widgets::check_box::CheckBox`]
8
//! it is stateful: it carries a [`ToastStateWrapper`] (`{ visible } + on_dismiss`)
9
//! in a [`RefAny`] attached to the "x" close button. Clicking "x" flips `visible`
10
//! to `false`, invokes the optional user `on_dismiss`, and hides the whole toast
11
//! by setting `display: none` on the container via `set_css_property` (mirroring
12
//! alert's / check_box's live restyle).
13
//!
14
//! TODO2 — **auto-dismiss is intentionally NOT implemented (be honest, don't fake
15
//! it).** A real toast disappears on its own after N seconds. That requires a
16
//! host-driven `Timer`/`Update` loop that re-enters the event loop on a clock
17
//! tick and flips `visible` to `false` — a widget handler cannot *start* such a
18
//! timer (it only runs in response to an input event, with no access to schedule
19
//! a future wakeup). This is the same limitation the spinner hit with CSS
20
//! animation: there is no widget-local timer. So this widget ships a **manually**
21
//! dismissable toast (the "x"); a host that wants auto-timeout must register a
22
//! `Timer` itself and call `set_css_property(display: none)` (or rebuild without
23
//! the toast) when it fires.
24
//!
25
//! TODO2 — covering sibling widgets relies on paint order (being a later sibling)
26
//! because there is no real stacking-context / z-index, and a drop `box-shadow`
27
//! elevation is omitted (it needs a runtime-heap shadow value — see
28
//! `progressbar.rs`); the border + radius over the page convey the floating card.
29
//! The `display:none` relayout itself is not GUI-verified in this build.
30
//!
31
//! Key types: [`Toast`], [`ToastKind`], [`ToastState`], [`ToastOnDismiss`].
32

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

            
68
use crate::callbacks::{Callback, CallbackInfo};
69

            
70
static TOAST_CONTAINER_CLASS: &[IdOrClass] =
71
    &[Class(AzString::from_const_str("__azul-native-toast"))];
72
static TOAST_MESSAGE_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
73
    "__azul-native-toast-message",
74
))];
75
static TOAST_CLOSE_CLASS: &[IdOrClass] =
76
    &[Class(AzString::from_const_str("__azul-native-toast-close"))];
77

            
78
const SYSTEM_UI_STR: AzString = AzString::from_const_str("system:ui");
79
const SYSTEM_UI_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SYSTEM_UI_STR)];
80
const SYSTEM_UI_FAMILY: StyleFontFamilyVec =
81
    StyleFontFamilyVec::from_const_slice(SYSTEM_UI_FAMILIES);
82

            
83
/// Distance (logical px) of the toast from the bottom / right edges of its parent.
84
const TOAST_INSET: isize = 24;
85
/// Maximum width (logical px) of the toast card.
86
const TOAST_MAX_WIDTH: isize = 360;
87

            
88
/// Callback function type invoked when a toast's "x" close button is clicked.
89
pub type ToastOnDismissCallbackType = extern "C" fn(RefAny, CallbackInfo, ToastState) -> Update;
90
impl_widget_callback!(
91
    ToastOnDismiss,
92
    OptionToastOnDismiss,
93
    ToastOnDismissCallback,
94
    ToastOnDismissCallbackType
95
);
96

            
97
azul_core::impl_managed_callback! {
98
    wrapper:        ToastOnDismissCallback,
99
    info_ty:        CallbackInfo,
100
    return_ty:      Update,
101
    default_ret:    Update::DoNothing,
102
    invoker_static: TOAST_ON_DISMISS_INVOKER,
103
    invoker_ty:     AzToastOnDismissCallbackInvoker,
104
    thunk_fn:       az_toast_on_dismiss_callback_thunk,
105
    setter_fn:      AzApp_setToastOnDismissCallbackInvoker,
106
    from_handle_fn: AzToastOnDismissCallback_createFromHostHandle,
107
    extra_args:     [ state: ToastState ],
108
}
109

            
110
/// The semantic colour variant of a [`Toast`] (Bootstrap alert palette, mirroring
111
/// [`crate::widgets::alert::AlertKind`]).
112
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
113
#[repr(C)]
114
pub enum ToastKind {
115
    /// Blue informational toast — the default.
116
    #[default]
117
    Info,
118
    /// Green success toast.
119
    Success,
120
    /// Yellow warning toast.
121
    Warning,
122
    /// Red danger/error toast.
123
    Danger,
124
}
125

            
126
impl ToastKind {
127
    /// Returns the `(background, border, text)` colours for this toast kind.
128
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
129
                                                 // pixel/coord path or to avoid churning call sites
130
                                                 // for a perf-neutral change)
131
139
    const fn colors(&self) -> (ColorU, ColorU, ColorU) {
132
139
        match self {
133
60
            Self::Info => (
134
60
                ColorU {
135
60
                    r: 207,
136
60
                    g: 244,
137
60
                    b: 252,
138
60
                    a: 255,
139
60
                }, // #cff4fc
140
60
                ColorU {
141
60
                    r: 182,
142
60
                    g: 239,
143
60
                    b: 251,
144
60
                    a: 255,
145
60
                }, // #b6effb
146
60
                ColorU {
147
60
                    r: 5,
148
60
                    g: 81,
149
60
                    b: 96,
150
60
                    a: 255,
151
60
                }, // #055160
152
60
            ),
153
26
            Self::Success => (
154
26
                ColorU {
155
26
                    r: 209,
156
26
                    g: 231,
157
26
                    b: 221,
158
26
                    a: 255,
159
26
                }, // #d1e7dd
160
26
                ColorU {
161
26
                    r: 186,
162
26
                    g: 219,
163
26
                    b: 204,
164
26
                    a: 255,
165
26
                }, // #badbcc
166
26
                ColorU {
167
26
                    r: 15,
168
26
                    g: 81,
169
26
                    b: 50,
170
26
                    a: 255,
171
26
                }, // #0f5132
172
26
            ),
173
24
            Self::Warning => (
174
24
                ColorU {
175
24
                    r: 255,
176
24
                    g: 243,
177
24
                    b: 205,
178
24
                    a: 255,
179
24
                }, // #fff3cd
180
24
                ColorU {
181
24
                    r: 255,
182
24
                    g: 236,
183
24
                    b: 181,
184
24
                    a: 255,
185
24
                }, // #ffecb5
186
24
                ColorU {
187
24
                    r: 102,
188
24
                    g: 77,
189
24
                    b: 3,
190
24
                    a: 255,
191
24
                }, // #664d03
192
24
            ),
193
29
            Self::Danger => (
194
29
                ColorU {
195
29
                    r: 248,
196
29
                    g: 215,
197
29
                    b: 218,
198
29
                    a: 255,
199
29
                }, // #f8d7da
200
29
                ColorU {
201
29
                    r: 245,
202
29
                    g: 194,
203
29
                    b: 199,
204
29
                    a: 255,
205
29
                }, // #f5c2c7
206
29
                ColorU {
207
29
                    r: 132,
208
29
                    g: 32,
209
29
                    b: 41,
210
29
                    a: 255,
211
29
                }, // #842029
212
29
            ),
213
        }
214
139
    }
215

            
216
    /// CSS class name for this toast kind (mirrors `AlertKind::class_name`).
217
    #[must_use]
218
32
    pub const fn class_name(&self) -> &'static str {
219
32
        match self {
220
8
            Self::Info => "__azul-toast-info",
221
8
            Self::Success => "__azul-toast-success",
222
8
            Self::Warning => "__azul-toast-warning",
223
8
            Self::Danger => "__azul-toast-danger",
224
        }
225
32
    }
226
}
227

            
228
/// A transient, floating notification banner with a "x" dismiss button.
229
#[derive(Debug, Clone, PartialEq, Eq)]
230
#[repr(C)]
231
pub struct Toast {
232
    /// Runtime state (`visible`) plus the optional dismiss callback.
233
    pub toast_state: ToastStateWrapper,
234
    /// The message text shown inside the toast.
235
    pub message: AzString,
236
    /// The colour variant.
237
    pub kind: ToastKind,
238
    /// Whether to render the "x" close button (default `true` — the only way to
239
    /// dismiss; see the module-level auto-dismiss TODO2).
240
    pub dismissible: bool,
241
    /// The computed inline style for the (absolutely-positioned) container.
242
    /// The container's CSS, or `None` for "no opinion" — in which case the style
243
    /// is derived from `kind` at render time.
244
    ///
245
    /// `None` and `Some(empty)` are different answers: the first means the
246
    /// widget picks, the second means the caller asked for no properties at all
247
    /// and gets none.
248
    pub container_style: OptionCssPropertyWithConditionsVec,
249
}
250

            
251
#[derive(Debug, Default, Clone, PartialEq, Eq)]
252
#[repr(C)]
253
pub struct ToastStateWrapper {
254
    /// Whether the toast is currently visible.
255
    pub inner: ToastState,
256
    /// Optional: function to call when the toast is dismissed.
257
    pub on_dismiss: OptionToastOnDismiss,
258
}
259

            
260
/// The visible/hidden state of a [`Toast`].
261
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
262
#[repr(C)]
263
pub struct ToastState {
264
    /// `true` (default) = shown, `false` = dismissed/hidden.
265
    pub visible: bool,
266
}
267

            
268
impl Default for ToastState {
269
105
    fn default() -> Self {
270
105
        Self { visible: true }
271
105
    }
272
}
273

            
274
/// Builds the container style for a given [`ToastKind`]. Mirrors
275
/// `alert::build_alert_style` but pins the box to the bottom-right corner of its
276
/// positioned parent (`position: absolute`) and caps its width instead of
277
/// stretching to fill a flex column.
278
109
fn build_toast_style(kind: ToastKind) -> CssPropertyWithConditionsVec {
279
109
    let (bg, border, text) = kind.colors();
280
109
    let bg_vec =
281
109
        StyleBackgroundContentVec::from_vec(alloc::vec![StyleBackgroundContent::Color(bg)]);
282
109
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
283
109
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
284
109
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
285
109
            LayoutFlexDirection::Row,
286
        )),
287
109
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Start)),
288
109
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
289
            0,
290
        ))),
291
        // Float pinned to the bottom-right corner of the positioned parent.
292
109
        CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Absolute)),
293
109
        CssPropertyWithConditions::simple(CssProperty::const_bottom(LayoutInsetBottom::const_px(
294
            TOAST_INSET,
295
        ))),
296
109
        CssPropertyWithConditions::simple(CssProperty::const_right(LayoutRight::const_px(
297
            TOAST_INSET,
298
        ))),
299
        // Cap the width so the toast hugs its content rather than spanning the page.
300
109
        CssPropertyWithConditions::simple(CssProperty::const_max_width(LayoutMaxWidth::const_px(
301
            TOAST_MAX_WIDTH,
302
        ))),
303
        // padding: 12px
304
109
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(
305
109
            LayoutPaddingTop::const_px(12,)
306
        )),
307
109
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
308
109
            LayoutPaddingBottom::const_px(12),
309
        )),
310
109
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
311
109
            LayoutPaddingLeft::const_px(12),
312
        )),
313
109
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
314
109
            LayoutPaddingRight::const_px(12),
315
        )),
316
        // border: 1px solid <border>
317
109
        CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
318
109
            LayoutBorderTopWidth::const_px(1),
319
        )),
320
109
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
321
109
            LayoutBorderBottomWidth::const_px(1),
322
        )),
323
109
        CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
324
109
            LayoutBorderLeftWidth::const_px(1),
325
        )),
326
109
        CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
327
109
            LayoutBorderRightWidth::const_px(1),
328
        )),
329
109
        CssPropertyWithConditions::simple(CssProperty::const_border_top_style(
330
109
            StyleBorderTopStyle {
331
109
                inner: BorderStyle::Solid,
332
109
            }
333
        )),
334
109
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
335
109
            StyleBorderBottomStyle {
336
109
                inner: BorderStyle::Solid,
337
109
            },
338
        )),
339
109
        CssPropertyWithConditions::simple(CssProperty::const_border_left_style(
340
109
            StyleBorderLeftStyle {
341
109
                inner: BorderStyle::Solid,
342
109
            },
343
        )),
344
109
        CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
345
109
            StyleBorderRightStyle {
346
109
                inner: BorderStyle::Solid,
347
109
            },
348
        )),
349
109
        CssPropertyWithConditions::simple(CssProperty::const_border_top_color(
350
109
            StyleBorderTopColor { inner: border }
351
        )),
352
109
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
353
109
            StyleBorderBottomColor { inner: border },
354
        )),
355
109
        CssPropertyWithConditions::simple(CssProperty::const_border_left_color(
356
109
            StyleBorderLeftColor { inner: border },
357
        )),
358
109
        CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
359
109
            StyleBorderRightColor { inner: border },
360
        )),
361
        // border-radius: 6px
362
109
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
363
109
            StyleBorderTopLeftRadius::const_px(6),
364
        )),
365
109
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
366
109
            StyleBorderTopRightRadius::const_px(6),
367
        )),
368
109
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
369
109
            StyleBorderBottomLeftRadius::const_px(6),
370
        )),
371
109
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
372
109
            StyleBorderBottomRightRadius::const_px(6),
373
        )),
374
109
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
375
            14
376
        ))),
377
109
        CssPropertyWithConditions::simple(CssProperty::const_font_family(SYSTEM_UI_FAMILY)),
378
        // Text colour is inherited by the message + close children.
379
109
        CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
380
109
            inner: text,
381
109
        })),
382
109
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg_vec)),
383
    ])
384
109
}
385

            
386
/// Message-text style: takes the remaining horizontal space, left-aligned.
387
static TOAST_MESSAGE_STYLE: &[CssPropertyWithConditions] = &[
388
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
389
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
390
];
391

            
392
/// Close-button ("x") style: a small pointer-cursor box on the right.
393
static TOAST_CLOSE_STYLE: &[CssPropertyWithConditions] = &[
394
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
395
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(18))),
396
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
397
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
398
    CssPropertyWithConditions::simple(CssProperty::const_margin_left(LayoutMarginLeft::const_px(
399
        12,
400
    ))),
401
];
402

            
403
impl Toast {
404
    /// Creates a new informational (blue) toast with the given message (visible,
405
    /// with a "x" close button).
406
    #[inline]
407
    #[must_use]
408
80
    pub fn create(message: AzString) -> Self {
409
80
        Self::with_kind(message, ToastKind::Info)
410
80
    }
411

            
412
    /// Creates a new toast with the given message and colour variant.
413
    #[inline]
414
    #[must_use]
415
96
    pub fn with_kind(message: AzString, kind: ToastKind) -> Self {
416
96
        Self {
417
96
            toast_state: ToastStateWrapper::default(),
418
96
            message,
419
96
            kind,
420
96
            dismissible: true,
421
96
            container_style: OptionCssPropertyWithConditionsVec::None,
422
96
        }
423
96
    }
424

            
425
    /// The container CSS this toast renders with.
426
    ///
427
    /// `None` means no opinion, so the kind's default applies — the same answer
428
    /// both themes give, asked in one place so they cannot drift.
429
    #[must_use]
430
64
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
431
64
        self.container_style
432
64
            .clone()
433
64
            .into_option()
434
64
            .unwrap_or_else(|| build_toast_style(self.kind))
435
64
    }
436

            
437
    /// Sets the colour variant.
438
    ///
439
    /// Does not touch `container_style`: the style is resolved from `kind` when
440
    /// the DOM is built, so changing the kind is enough. Writing it here would
441
    /// also overwrite a caller's explicit style.
442
    #[inline]
443
24
    pub const fn set_kind(&mut self, kind: ToastKind) {
444
24
        self.kind = kind;
445
24
    }
446

            
447
    /// Builder-style setter for the colour variant.
448
    #[inline]
449
    #[must_use]
450
6
    pub const fn with_toast_kind(mut self, kind: ToastKind) -> Self {
451
6
        self.set_kind(kind);
452
6
        self
453
6
    }
454

            
455
    /// Sets whether the toast shows a "x" close button.
456
    #[inline]
457
21
    pub const fn set_dismissible(&mut self, dismissible: bool) {
458
21
        self.dismissible = dismissible;
459
21
    }
460

            
461
    /// Builder-style setter for the dismissible flag.
462
    #[inline]
463
    #[must_use]
464
13
    pub const fn with_dismissible(mut self, dismissible: bool) -> Self {
465
13
        self.set_dismissible(dismissible);
466
13
        self
467
13
    }
468

            
469
    /// Sets the dismiss callback. Implies `dismissible = true` so the close
470
    /// button is rendered.
471
    #[inline]
472
9
    pub fn set_on_dismiss<C: Into<ToastOnDismissCallback>>(&mut self, data: RefAny, on_dismiss: C) {
473
9
        self.dismissible = true;
474
9
        self.toast_state.on_dismiss = Some(ToastOnDismiss {
475
9
            callback: on_dismiss.into(),
476
9
            refany: data,
477
9
        })
478
9
        .into();
479
9
    }
480

            
481
    /// Builder-style setter for the dismiss callback (implies dismissible).
482
    #[inline]
483
    #[must_use]
484
4
    pub fn with_on_dismiss<C: Into<ToastOnDismissCallback>>(
485
4
        mut self,
486
4
        data: RefAny,
487
4
        on_dismiss: C,
488
4
    ) -> Self {
489
4
        self.set_on_dismiss(data, on_dismiss);
490
4
        self
491
4
    }
492

            
493
    /// Replaces `self` with a default (empty info) toast and returns the original.
494
    #[inline]
495
    #[must_use]
496
6
    pub fn swap_with_default(&mut self) -> Self {
497
6
        let mut s = Self::create(AzString::from_const_str(""));
498
6
        core::mem::swap(&mut s, self);
499
6
        s
500
6
    }
501

            
502
    /// Converts this toast into a DOM subtree with the `__azul-native-toast` class.
503
    #[inline]
504
    #[must_use]
505
38
    pub fn dom(self) -> Dom {
506
        use azul_core::{
507
            callbacks::CoreCallback,
508
            dom::{EventFilter, HoverEventFilter},
509
            refany::OptionRefAny,
510
        };
511

            
512
        // Resolved before `self.message` is moved out below.
513
38
        let container_style = self.resolved_container_style();
514

            
515
38
        let message = crate::widgets::widget_p_with_text(self.message)
516
38
            .with_ids_and_classes(IdOrClassVec::from_const_slice(TOAST_MESSAGE_CLASS))
517
38
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
518
38
                TOAST_MESSAGE_STYLE,
519
            ));
520

            
521
38
        let mut children = alloc::vec![message];
522

            
523
38
        if self.dismissible {
524
34
            let close = crate::widgets::widget_p_with_text(AzString::from_const_str("\u{00D7}"))
525
34
                .with_ids_and_classes(IdOrClassVec::from_const_slice(TOAST_CLOSE_CLASS))
526
34
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(TOAST_CLOSE_STYLE))
527
34
                .with_tab_index(TabIndex::Auto)
528
34
            // Role so the accessibility tree knows what this IS:
529
34
            // a transient announcement. The NAME comes from the widget's own text,
530
34
            // which azul derives when a readable label is present.
531
34
            // This is the CLOSE BUTTON, not the container — the tab stop is on
532
34
            // the dismiss affordance. Its label is a multiplication sign: a
533
34
            // picture of an X, not a name. Hence an explicit name, and
534
34
            // PushButton rather than the container's role.
535
34
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
536
34
                role: azul_core::a11y::AccessibilityRole::PushButton,
537
34
                accessibility_name: Some(AzString::from_const_str("Close")).into(),
538
34
                ..Default::default()
539
34
            })
540
34
                .with_callbacks(
541
34
                    alloc::vec![CoreCallbackData {
542
34
                        event: EventFilter::Hover(HoverEventFilter::Click),
543
34
                        callback: CoreCallback {
544
34
                            cb: default_on_toast_dismiss as usize,
545
34
                            ctx: OptionRefAny::None,
546
34
                        },
547
34
                        refany: RefAny::new(self.toast_state),
548
34
                    }]
549
34
                    .into(),
550
34
                );
551
34
            children.push(close);
552
34
        }
553

            
554
38
        Dom::create_div()
555
38
            .with_ids_and_classes(IdOrClassVec::from_const_slice(TOAST_CONTAINER_CLASS))
556
38
            .with_css_props(container_style)
557
38
            .with_children(children.into())
558
38
    }
559
}
560

            
561
impl Default for Toast {
562
18
    fn default() -> Self {
563
18
        Self::create(AzString::from_const_str(""))
564
18
    }
565
}
566

            
567
/// Close-button click handler. The hit node is the close button (the
568
/// callback-bearing node, per `currentTarget` semantics — see `alert`); its
569
/// parent is the toast container. Flips `visible` to `false`, invokes the
570
/// optional user callback, then hides the whole toast via `display: none`.
571
12
extern "C" fn default_on_toast_dismiss(mut data: RefAny, mut info: CallbackInfo) -> Update {
572
12
    let close_node = info.get_hit_node();
573
12
    let Some(container) = info.get_parent(close_node) else {
574
4
        return Update::DoNothing;
575
    };
576

            
577
7
    let result = {
578
8
        let Some(mut toast) = data.downcast_mut::<ToastStateWrapper>() else {
579
1
            return Update::DoNothing;
580
        };
581
7
        toast.inner.visible = false;
582
7
        let inner = toast.inner;
583
7
        let toast = &mut *toast;
584
7
        match toast.on_dismiss.as_mut() {
585
4
            Some(ToastOnDismiss { callback, refany }) => (callback.cb)(refany.clone(), info, inner),
586
3
            None => Update::DoNothing,
587
        }
588
    };
589

            
590
    // TODO2: hides the toast by toggling `display: none` via set_css_property.
591
    // This follows the proven live-restyle pattern of alert/check_box (which
592
    // toggle display/opacity/background); the display:none relayout itself is not
593
    // GUI-verified in this build. (Auto-timeout dismissal is a host-driven Timer —
594
    // see the module-level TODO2 — and is intentionally not attempted here.)
595
7
    info.set_css_property(container, CssProperty::const_display(LayoutDisplay::None));
596

            
597
7
    result
598
12
}
599

            
600
impl From<Toast> for Dom {
601
1
    fn from(t: Toast) -> Self {
602
1
        t.dom()
603
1
    }
604
}
605

            
606
#[cfg(test)]
607
// `assertions_on_constants`: these are deliberate invariant guards over sibling
608
// `const`s in this module. They are const-foldable *today*, which is exactly the
609
// point — they must go red the moment someone edits one of those constants into an
610
// inconsistent value. Deleting them (clippy's suggestion) would delete the check.
611
#[allow(clippy::assertions_on_constants)]
612
mod autotest_generated {
613
    use std::{
614
        collections::{BTreeMap, HashMap},
615
        sync::{Arc, Mutex},
616
    };
617

            
618
    use azul_core::{
619
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
620
        geom::{LogicalRect, OptionLogicalPosition},
621
        gl::OptionGlContextPtr,
622
        hit_test::ScrollPosition,
623
        refany::OptionRefAny,
624
        resources::RendererResources,
625
        styled_dom::{NodeHierarchyItemId, StyledDom},
626
        window::{MonitorVec, RawWindowHandle},
627
    };
628
    use azul_css::{
629
        props::basic::{length::SizeMetric, pixel::PixelValue},
630
        system::SystemStyle,
631
    };
632
    use rust_fontconfig::FcFontCache;
633

            
634
    use super::*;
635
    #[cfg(feature = "icu")]
636
    use crate::icu::IcuLocalizerHandle;
637
    use crate::{
638
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
639
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
640
        window::{DomLayoutResult, LayoutWindow},
641
        window_state::FullWindowState,
642
    };
643

            
644
    // ------------------------------------------------------------------
645
    // Helpers
646
    // ------------------------------------------------------------------
647

            
648
    const ALL_KINDS: [ToastKind; 4] = [
649
        ToastKind::Info,
650
        ToastKind::Success,
651
        ToastKind::Warning,
652
        ToastKind::Danger,
653
    ];
654

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

            
671
    /// The inline (static) CSS properties actually attached to a DOM node.
672
    fn inline_props(node: &Dom) -> Vec<CssProperty> {
673
        node.root
674
            .style
675
            .iter_inline_properties()
676
            .map(|(p, _)| p.clone())
677
            .collect()
678
    }
679

            
680
    /// The `background-color` of a style vec (first background layer only).
681
    fn background_color(style: &CssPropertyWithConditionsVec) -> Option<ColorU> {
682
        style.as_ref().iter().find_map(|p| match &p.property {
683
            CssProperty::BackgroundContent(v) => match v.get_property()?.as_ref().first()? {
684
                StyleBackgroundContent::Color(c) => Some(*c),
685
                _ => None,
686
            },
687
            _ => None,
688
        })
689
    }
690

            
691
    /// Every `border-*-color` in a style vec, in declaration order.
692
    fn border_colors(style: &CssPropertyWithConditionsVec) -> Vec<ColorU> {
693
        style
694
            .as_ref()
695
            .iter()
696
            .filter_map(|p| match &p.property {
697
                CssProperty::BorderTopColor(v) => v.get_property().map(|c| c.inner),
698
                CssProperty::BorderBottomColor(v) => v.get_property().map(|c| c.inner),
699
                CssProperty::BorderLeftColor(v) => v.get_property().map(|c| c.inner),
700
                CssProperty::BorderRightColor(v) => v.get_property().map(|c| c.inner),
701
                _ => None,
702
            })
703
            .collect()
704
    }
705

            
706
    /// The `color` (text colour) of a style vec.
707
    fn text_color(style: &CssPropertyWithConditionsVec) -> Option<ColorU> {
708
        style.as_ref().iter().find_map(|p| match &p.property {
709
            CssProperty::TextColor(v) => v.get_property().map(|c| c.inner),
710
            _ => None,
711
        })
712
    }
713

            
714
    /// The declared `position` of a style vec.
715
    fn position_of(style: &CssPropertyWithConditionsVec) -> Option<LayoutPosition> {
716
        style.as_ref().iter().find_map(|p| match &p.property {
717
            CssProperty::Position(v) => v.get_property().copied(),
718
            _ => None,
719
        })
720
    }
721

            
722
    /// The `bottom` offset of a style vec, as a raw `PixelValue`.
723
    fn bottom_px(style: &CssPropertyWithConditionsVec) -> Option<PixelValue> {
724
        style.as_ref().iter().find_map(|p| match &p.property {
725
            CssProperty::Bottom(v) => v.get_property().map(|b| b.inner),
726
            _ => None,
727
        })
728
    }
729

            
730
    /// The `right` offset of a style vec, as a raw `PixelValue`.
731
    fn right_px(style: &CssPropertyWithConditionsVec) -> Option<PixelValue> {
732
        style.as_ref().iter().find_map(|p| match &p.property {
733
            CssProperty::Right(v) => v.get_property().map(|r| r.inner),
734
            _ => None,
735
        })
736
    }
737

            
738
    /// The `max-width` of a style vec, as a raw `PixelValue`.
739
    fn max_width_px(style: &CssPropertyWithConditionsVec) -> Option<PixelValue> {
740
        style.as_ref().iter().find_map(|p| match &p.property {
741
            CssProperty::MaxWidth(v) => v.get_property().map(|w| w.inner),
742
            _ => None,
743
        })
744
    }
745

            
746
    /// The *kind* of every declared property, in order (ignores the values).
747
    fn property_types(
748
        style: &CssPropertyWithConditionsVec,
749
    ) -> Vec<core::mem::Discriminant<CssProperty>> {
750
        style
751
            .as_ref()
752
            .iter()
753
            .map(|p| core::mem::discriminant(&p.property))
754
            .collect()
755
    }
756

            
757
    /// A `RefAny` payload recording every `ToastState` a user `on_dismiss` sees.
758
    struct DismissLog {
759
        calls: Vec<bool>,
760
    }
761

            
762
    extern "C" fn record_dismiss(mut data: RefAny, _: CallbackInfo, state: ToastState) -> Update {
763
        if let Some(mut log) = data.downcast_mut::<DismissLog>() {
764
            log.calls.push(state.visible);
765
        }
766
        Update::RefreshDom
767
    }
768

            
769
    extern "C" fn dismiss_do_nothing(_: RefAny, _: CallbackInfo, _: ToastState) -> Update {
770
        Update::DoNothing
771
    }
772

            
773
    fn dismiss_cb(f: ToastOnDismissCallbackType) -> ToastOnDismissCallback {
774
        f.into()
775
    }
776

            
777
    /// `visible` of a `ToastStateWrapper` payload.
778
    fn wrapper_visible(data: &mut RefAny) -> bool {
779
        data.downcast_ref::<ToastStateWrapper>()
780
            .expect("payload must still be a ToastStateWrapper")
781
            .inner
782
            .visible
783
    }
784

            
785
    /// The `visible` flags recorded by a `DismissLog` payload.
786
    fn log_calls(data: &mut RefAny) -> Vec<bool> {
787
        data.downcast_ref::<DismissLog>()
788
            .expect("payload must still be a DismissLog")
789
            .calls
790
            .clone()
791
    }
792

            
793
    /// A `DomLayoutResult` with an *empty* layout tree: the dismiss handler only
794
    /// walks `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
795
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
796
        DomLayoutResult {
797
            styled_dom,
798
            layout_tree: LayoutTree {
799
                nodes: Vec::new(),
800
                warm: Vec::new(),
801
                cold: Vec::new(),
802
                root: 0,
803
                dom_to_layout: BTreeMap::new(),
804
                children_arena: Vec::new(),
805
                children_offsets: Vec::new(),
806
                subtree_needs_intrinsic: Vec::new(),
807
            },
808
            calculated_positions: Vec::new(),
809
            viewport: LogicalRect::zero(),
810
            display_list: Arc::new(DisplayList::default()),
811
            scroll_ids: HashMap::new(),
812
            scroll_id_to_node_id: HashMap::new(),
813
        }
814
    }
815

            
816
    /// The flattened DOM of a default toast: `container(0)`, `message(1)`,
817
    /// `close(2)` — i.e. exactly the hierarchy `default_on_toast_dismiss` walks
818
    /// (hit node -> parent).
819
    fn dismissible_styled_dom() -> StyledDom {
820
        let toast = Toast::create(AzString::from("msg"));
821
        assert!(
822
            toast.dismissible,
823
            "a fresh toast must already carry a close button"
824
        );
825
        let styled = StyledDom::create_from_dom(toast.dom());
826
        assert_eq!(
827
            styled.node_hierarchy.as_ref().len(),
828
            5,
829
            "fixture must flatten to container / message <p> + text / close <p> + text"
830
        );
831
        styled
832
    }
833

            
834
    /// Invokes `default_on_toast_dismiss` against a `LayoutWindow` holding
835
    /// `styled` (or nothing at all, when `styled` is `None`), with `hit` as the
836
    /// hit node. Returns the `Update` plus every recorded `CallbackChange`.
837
    /// Flat indices in `dismissible_styled_dom`, depth-first pre-order:
838
    /// `0 container / 1 message <p> / 2 message text / 3 close <p> / 4 close text`.
839
    /// Both callbacks and styles sit on the `<p>`s, never on the text nodes.
840
    const MESSAGE_NODE: usize = 1;
841
    const CLOSE_NODE: usize = 3;
842

            
843
    fn run_dismiss(
844
        styled: Option<StyledDom>,
845
        hit: usize,
846
        data: RefAny,
847
    ) -> (Update, Vec<CallbackChange>) {
848
        let mut layout_window =
849
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
850
        if let Some(sd) = styled {
851
            layout_window
852
                .layout_results
853
                .insert(DomId::ROOT_ID, layout_result(sd));
854
        }
855

            
856
        let renderer_resources = RendererResources::default();
857
        let previous_window_state: Option<FullWindowState> = None;
858
        let current_window_state = FullWindowState::default();
859
        let gl_context = OptionGlContextPtr::None;
860
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
861
            BTreeMap::new();
862
        let window_handle = RawWindowHandle::Unsupported;
863
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
864

            
865
        let ref_data = CallbackInfoRefData {
866
            layout_window: &layout_window,
867
            renderer_resources: &renderer_resources,
868
            previous_window_state: &previous_window_state,
869
            current_window_state: &current_window_state,
870
            gl_context: &gl_context,
871
            current_scroll_manager: &scroll_states,
872
            current_window_handle: &window_handle,
873
            system_callbacks: &system_callbacks,
874
            system_style: Arc::new(SystemStyle::default()),
875
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
876
            #[cfg(feature = "icu")]
877
            icu_localizer: IcuLocalizerHandle::default(),
878
            ctx: OptionRefAny::None,
879
        };
880

            
881
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
882

            
883
        let info = CallbackInfo::new(
884
            &ref_data,
885
            &changes,
886
            DomNodeId {
887
                dom: DomId::ROOT_ID,
888
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
889
            },
890
            OptionLogicalPosition::None,
891
            OptionLogicalPosition::None,
892
        );
893

            
894
        let update = default_on_toast_dismiss(data, info);
895
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
896
        (update, recorded)
897
    }
898

            
899
    /// Every `display` write recorded in the change log, as `(node index, display)`.
900
    fn display_writes(changes: &[CallbackChange]) -> Vec<(usize, LayoutDisplay)> {
901
        let mut out = Vec::new();
902
        for change in changes {
903
            if let CallbackChange::ChangeNodeCssProperties {
904
                node_id,
905
                properties,
906
                ..
907
            } = change
908
            {
909
                for p in properties.as_ref() {
910
                    if let CssProperty::Display(v) = p {
911
                        if let Some(d) = v.get_property() {
912
                            out.push((node_id.index(), *d));
913
                        }
914
                    }
915
                }
916
            }
917
        }
918
        out
919
    }
920

            
921
    // ------------------------------------------------------------------
922
    // ToastKind::colors  (getter)
923
    // ------------------------------------------------------------------
924

            
925
    #[test]
926
    fn kind_colors_are_the_documented_bootstrap_palette() {
927
        let expect = |(r, g, b): (u8, u8, u8)| ColorU { r, g, b, a: 255 };
928

            
929
        assert_eq!(
930
            ToastKind::Info.colors(),
931
            (
932
                expect((207, 244, 252)), // #cff4fc
933
                expect((182, 239, 251)), // #b6effb
934
                expect((5, 81, 96)),     // #055160
935
            )
936
        );
937
        assert_eq!(
938
            ToastKind::Success.colors(),
939
            (
940
                expect((209, 231, 221)), // #d1e7dd
941
                expect((186, 219, 204)), // #badbcc
942
                expect((15, 81, 50)),    // #0f5132
943
            )
944
        );
945
        assert_eq!(
946
            ToastKind::Warning.colors(),
947
            (
948
                expect((255, 243, 205)), // #fff3cd
949
                expect((255, 236, 181)), // #ffecb5
950
                expect((102, 77, 3)),    // #664d03
951
            )
952
        );
953
        assert_eq!(
954
            ToastKind::Danger.colors(),
955
            (
956
                expect((248, 215, 218)), // #f8d7da
957
                expect((245, 194, 199)), // #f5c2c7
958
                expect((132, 32, 41)),   // #842029
959
            )
960
        );
961
    }
962

            
963
    #[test]
964
    fn kind_colors_are_fully_opaque_and_pairwise_distinct() {
965
        for kind in ALL_KINDS {
966
            let (bg, border, text) = kind.colors();
967
            for (name, c) in [("bg", bg), ("border", border), ("text", text)] {
968
                assert_eq!(c.a, 255, "{kind:?}.{name} must be fully opaque");
969
            }
970
            // a floating card is only legible if bg != text
971
            assert_ne!(bg, text, "{kind:?}: background must differ from text");
972
            // ... and only visible against the page if bg != border
973
            assert_ne!(
974
                bg, border,
975
                "{kind:?}: the border must be visible on the card"
976
            );
977
        }
978

            
979
        for (i, a) in ALL_KINDS.iter().enumerate() {
980
            for b in &ALL_KINDS[i + 1..] {
981
                assert_ne!(
982
                    a.colors(),
983
                    b.colors(),
984
                    "{a:?} and {b:?} must be visually distinguishable"
985
                );
986
            }
987
        }
988
    }
989

            
990
    #[test]
991
    fn kind_colors_default_is_info_and_the_call_is_pure() {
992
        assert_eq!(ToastKind::default(), ToastKind::Info);
993
        assert_eq!(ToastKind::default().colors(), ToastKind::Info.colors());
994

            
995
        // repeated calls on the same (Copy) receiver must be stable
996
        let k = ToastKind::Danger;
997
        assert_eq!(k.colors(), k.colors());
998
        assert_eq!(k.colors(), k.colors());
999
    }
    #[test]
    fn kind_colors_is_const_evaluable() {
        const INFO: (ColorU, ColorU, ColorU) = ToastKind::Info.colors();
        assert_eq!(
            INFO.0,
            ColorU {
                r: 207,
                g: 244,
                b: 252,
                a: 255
            }
        );
    }
    // ------------------------------------------------------------------
    // ToastKind::class_name  (getter)
    // ------------------------------------------------------------------
    #[test]
    fn class_name_exact_values_and_shape() {
        assert_eq!(ToastKind::Info.class_name(), "__azul-toast-info");
        assert_eq!(ToastKind::Success.class_name(), "__azul-toast-success");
        assert_eq!(ToastKind::Warning.class_name(), "__azul-toast-warning");
        assert_eq!(ToastKind::Danger.class_name(), "__azul-toast-danger");
        for kind in ALL_KINDS {
            let name = kind.class_name();
            assert!(
                name.starts_with("__azul-toast-"),
                "{kind:?} -> {name:?} must keep the widget prefix"
            );
            assert!(
                !name.contains(char::is_whitespace),
                "{name:?} must be a single CSS class token"
            );
            assert!(name.is_ascii(), "{name:?} must stay ASCII");
            // stable across calls, and equal for equal kinds
            assert_eq!(name, kind.class_name());
        }
    }
    #[test]
    fn class_name_is_unique_per_kind() {
        let mut names: Vec<&str> = ALL_KINDS.iter().map(|k| k.class_name()).collect();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), 4, "every kind needs its own class name");
    }
    #[test]
    fn class_name_never_collides_with_the_structural_classes() {
        // the kind classes live in a different namespace than the three
        // `__azul-native-toast*` structural classes emitted by `dom()`
        let structural = [
            "__azul-native-toast",
            "__azul-native-toast-message",
            "__azul-native-toast-close",
        ];
        for kind in ALL_KINDS {
            for s in structural {
                assert_ne!(kind.class_name(), s, "{kind:?} must not shadow {s:?}");
            }
        }
    }
    #[test]
    fn class_name_is_const_evaluable() {
        const DANGER: &str = ToastKind::Danger.class_name();
        assert_eq!(DANGER, "__azul-toast-danger");
    }
    // ------------------------------------------------------------------
    // build_toast_style
    // ------------------------------------------------------------------
    #[test]
    fn build_toast_style_declares_the_same_properties_for_every_kind() {
        let info = property_types(&build_toast_style(ToastKind::Info));
        assert_eq!(
            info.len(),
            32,
            "the container style declares 32 properties (pin: adding/removing one is a deliberate \
             change)"
        );
        for kind in ALL_KINDS {
            let style = build_toast_style(kind);
            assert_eq!(
                property_types(&style),
                info,
                "{kind:?} must declare the same properties, in the same order, as Info"
            );
            // the style is unconditional: nothing is gated behind :hover/@media/...
            for p in style.as_ref() {
                assert!(
                    p.apply_if.as_ref().is_empty(),
                    "{kind:?}: {:?} must be unconditional",
                    p.property
                );
            }
        }
    }
    #[test]
    fn build_toast_style_declares_no_property_twice() {
        // a duplicated property would silently shadow the earlier declaration
        for kind in ALL_KINDS {
            let types = property_types(&build_toast_style(kind));
            for (i, a) in types.iter().enumerate() {
                for b in &types[i + 1..] {
                    assert_ne!(
                        a, b,
                        "{kind:?}: the container style declares the same property twice"
                    );
                }
            }
        }
    }
    #[test]
    fn build_toast_style_colors_track_the_kind_palette() {
        for kind in ALL_KINDS {
            let style = build_toast_style(kind);
            let (bg, border, text) = kind.colors();
            assert_eq!(background_color(&style), Some(bg), "{kind:?}: background");
            assert_eq!(text_color(&style), Some(text), "{kind:?}: text colour");
            let borders = border_colors(&style);
            assert_eq!(
                borders.len(),
                4,
                "{kind:?}: all four edges must be coloured"
            );
            assert!(
                borders.iter().all(|c| *c == border),
                "{kind:?}: every edge must use the kind's border colour, got {borders:?}"
            );
        }
    }
    #[test]
    fn build_toast_style_pins_the_card_to_the_bottom_right_corner() {
        // This is what makes a toast a toast (rather than an inline alert):
        // position:absolute + bottom/right insets + a width cap.
        for kind in ALL_KINDS {
            let style = build_toast_style(kind);
            assert_eq!(
                position_of(&style),
                Some(LayoutPosition::Absolute),
                "{kind:?}: a toast must float out of flow"
            );
            assert_eq!(
                bottom_px(&style),
                Some(LayoutInsetBottom::const_px(TOAST_INSET).inner),
                "{kind:?}: bottom inset"
            );
            assert_eq!(
                right_px(&style),
                Some(LayoutRight::const_px(TOAST_INSET).inner),
                "{kind:?}: right inset"
            );
            assert_eq!(
                max_width_px(&style),
                Some(LayoutMaxWidth::const_px(TOAST_MAX_WIDTH).inner),
                "{kind:?}: width cap"
            );
            // an absolutely-positioned card must not also try to grow in a flex row
            assert!(
                style.as_ref().contains(&CssPropertyWithConditions::simple(
                    CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))
                )),
                "{kind:?}: the container must not flex-grow"
            );
        }
    }
    #[test]
    fn toast_inset_and_max_width_survive_the_fixed_point_encoding_exactly() {
        // The `isize`-backed `FloatValue` encoding must reproduce the constants
        // bit-exactly — a drifting inset silently mis-places every toast.
        assert_eq!(TOAST_INSET, 24);
        assert_eq!(TOAST_MAX_WIDTH, 360);
        assert!(
            TOAST_INSET > 0 && TOAST_MAX_WIDTH > TOAST_INSET,
            "an inset must push the card inward, and the cap must exceed the inset"
        );
        let style = build_toast_style(ToastKind::Info);
        for (name, got, want) in [
            ("bottom", bottom_px(&style), TOAST_INSET),
            ("right", right_px(&style), TOAST_INSET),
            ("max-width", max_width_px(&style), TOAST_MAX_WIDTH),
        ] {
            let pv = got.unwrap_or_else(|| panic!("{name} must be declared"));
            assert_eq!(
                pv.metric,
                SizeMetric::Px,
                "{name} must be an absolute px length, not a %/em"
            );
            assert!(
                (pv.number.get() - want as f32).abs() < f32::EPSILON,
                "{name}: {} px decoded back as {}",
                want,
                pv.number.get()
            );
            assert!(
                pv.number.get().is_finite(),
                "{name} must never decode to NaN/inf"
            );
        }
    }
    #[test]
    fn build_toast_style_geometry_is_kind_independent() {
        // Everything that is *not* a colour must be identical for all kinds.
        let expected = [
            CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
            CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
                LayoutFlexDirection::Row,
            )),
            CssPropertyWithConditions::simple(CssProperty::const_align_items(
                LayoutAlignItems::Start,
            )),
            CssPropertyWithConditions::simple(CssProperty::const_position(
                LayoutPosition::Absolute,
            )),
            CssPropertyWithConditions::simple(CssProperty::const_padding_top(
                LayoutPaddingTop::const_px(12),
            )),
            CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
                LayoutBorderTopWidth::const_px(1),
            )),
            CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
                StyleBorderTopLeftRadius::const_px(6),
            )),
            CssPropertyWithConditions::simple(CssProperty::const_font_size(
                StyleFontSize::const_px(14),
            )),
        ];
        for kind in ALL_KINDS {
            let style = build_toast_style(kind);
            for want in &expected {
                assert!(
                    style.as_ref().contains(want),
                    "{kind:?}: missing {:?}",
                    want.property
                );
            }
        }
    }
    #[test]
    fn build_toast_style_differs_only_in_the_colours() {
        let info = build_toast_style(ToastKind::Info);
        for kind in [ToastKind::Success, ToastKind::Warning, ToastKind::Danger] {
            let other = build_toast_style(kind);
            let differing: Vec<_> = info
                .as_ref()
                .iter()
                .zip(other.as_ref().iter())
                .filter(|(a, b)| a != b)
                .map(|(a, _)| core::mem::discriminant(&a.property))
                .collect();
            // background + 4 border colours + text colour = 6 kind-dependent props
            assert_eq!(
                differing.len(),
                6,
                "{kind:?}: only bg + 4 border colours + text colour may depend on the kind"
            );
        }
    }
    #[test]
    fn build_toast_style_is_pure_and_repeatable() {
        for kind in ALL_KINDS {
            assert_eq!(
                build_toast_style(kind),
                build_toast_style(kind),
                "{kind:?}: the builder must be deterministic"
            );
        }
    }
    // ------------------------------------------------------------------
    // Toast::create / with_kind / Default
    // ------------------------------------------------------------------
    #[test]
    fn create_is_an_info_toast_that_is_dismissible_by_default() {
        let toast = Toast::create(AzString::from("hello"));
        assert_eq!(toast.message.as_str(), "hello");
        assert_eq!(toast.kind, ToastKind::Info);
        assert!(
            toast.dismissible,
            "unlike Alert, a fresh Toast ships the close button (the only way to dismiss it)"
        );
        assert!(toast.toast_state.inner.visible, "a fresh toast is visible");
        assert!(toast.toast_state.on_dismiss.is_none());
        assert_eq!(
            toast.resolved_container_style(),
            build_toast_style(ToastKind::Info)
        );
    }
    #[test]
    fn toast_state_defaults_to_visible_not_to_the_bool_default() {
        // `bool::default()` is false — `ToastState` must *override* that, else
        // every default-constructed toast would start out already dismissed.
        assert!(ToastState::default().visible);
        assert!(ToastStateWrapper::default().inner.visible);
        assert!(ToastStateWrapper::default().on_dismiss.is_none());
        assert!(Toast::default().toast_state.inner.visible);
    }
    #[test]
    fn create_with_empty_message_equals_default_and_is_value_comparable() {
        assert_eq!(Toast::create(AzString::from("")), Toast::default());
        // equality is structural, not pointer-based
        assert_eq!(
            Toast::create(AzString::from("a")),
            Toast::create(AzString::from("a"))
        );
        assert_ne!(
            Toast::create(AzString::from("a")),
            Toast::create(AzString::from("b"))
        );
        assert_ne!(
            Toast::create(AzString::from("a")),
            Toast::with_kind(AzString::from("a"), ToastKind::Danger)
        );
    }
    #[test]
    fn create_survives_extreme_messages_and_round_trips_them_into_the_dom() {
        let long = "ab".repeat(50_000);
        let cases: Vec<AzString> = alloc::vec![
            AzString::from(""),
            AzString::from(" "),
            AzString::from("a\0b"),             // interior NUL
            AzString::from("line\nbreak\ttab"), // control chars
            AzString::from("👨‍👩‍👧‍👦 e\u{0301}\u{0327} مرحبا שלום 🇩🇪"), // ZWJ + combining + RTL
            AzString::from("\u{feff}\u{202e}rtl-override"), // BOM + bidi override
            AzString::from("×"),                // same glyph as the close button
            AzString::from("\u{00D7}\u{00D7}\u{00D7}"), // three close glyphs
            AzString::from(long.as_str()),      // 100k chars
        ];
        for message in cases {
            let toast = Toast::create(message.clone());
            assert_eq!(toast.message.as_str(), message.as_str());
            // the message must survive the trip through the DOM byte-for-byte
            let dom = toast.dom();
            let children = dom.children.as_ref();
            assert_eq!(
                children.len(),
                2,
                "message content must never change the child count"
            );
            assert_eq!(text_of(&children[0]), Some(message.as_str()));
            // a "×" in the *message* must not be mistaken for the close button
            assert!(
                children[0].root.has_class("__azul-native-toast-message"),
                "the first child is always the message"
            );
            assert!(
                children[1].root.has_class("__azul-native-toast-close"),
                "the close button is always last"
            );
        }
    }
    #[test]
    fn with_kind_stores_both_args_for_every_kind() {
        for kind in ALL_KINDS {
            let toast = Toast::with_kind(AzString::from("m"), kind);
            assert_eq!(toast.kind, kind);
            assert_eq!(toast.message.as_str(), "m");
            assert!(toast.dismissible);
            assert!(toast.toast_state.on_dismiss.is_none());
            assert!(toast.toast_state.inner.visible);
            assert_eq!(
                toast.resolved_container_style(),
                build_toast_style(kind),
                "{kind:?}: the container style must match the kind it was built with"
            );
        }
    }
    #[test]
    fn create_is_with_kind_info() {
        assert_eq!(
            Toast::create(AzString::from("m")),
            Toast::with_kind(AzString::from("m"), ToastKind::Info)
        );
        assert_eq!(
            Toast::create(AzString::from("m")),
            Toast::with_kind(AzString::from("m"), ToastKind::default())
        );
    }
    // ------------------------------------------------------------------
    // set_kind / with_toast_kind
    // ------------------------------------------------------------------
    #[test]
    fn set_kind_recomputes_the_style_and_is_idempotent() {
        let mut toast = Toast::create(AzString::from("m"));
        for kind in ALL_KINDS {
            toast.set_kind(kind);
            assert_eq!(toast.kind, kind);
            assert_eq!(toast.resolved_container_style(), build_toast_style(kind));
            // applying the same kind twice must not append/duplicate anything
            let before = toast.resolved_container_style();
            toast.set_kind(kind);
            assert_eq!(
                toast.resolved_container_style(),
                before,
                "{kind:?}: set_kind must be idempotent"
            );
            assert_eq!(
                toast.resolved_container_style().len(),
                32,
                "{kind:?}: restyling must not grow the property vec"
            );
        }
        // a full cycle back to the original kind restores the original toast
        let original = Toast::create(AzString::from("m"));
        let mut cycled = original.clone();
        for kind in ALL_KINDS {
            cycled.set_kind(kind);
        }
        cycled.set_kind(ToastKind::Info);
        assert_eq!(cycled, original, "kind cycling must not accumulate state");
    }
    #[test]
    fn set_kind_leaves_message_dismissible_and_callback_alone() {
        let log = RefAny::new(DismissLog { calls: Vec::new() });
        let mut toast = Toast::create(AzString::from("keep me"));
        toast.set_on_dismiss(log, dismiss_cb(dismiss_do_nothing));
        toast.toast_state.inner.visible = false;
        toast.set_kind(ToastKind::Warning);
        assert_eq!(toast.message.as_str(), "keep me");
        assert!(
            toast.dismissible,
            "set_kind must not clear the close button"
        );
        assert!(
            toast.toast_state.on_dismiss.is_some(),
            "set_kind must not drop the callback"
        );
        assert!(
            !toast.toast_state.inner.visible,
            "set_kind must not resurrect a dismissed toast"
        );
    }
    #[test]
    fn with_toast_kind_matches_set_kind_and_last_write_wins() {
        for kind in ALL_KINDS {
            let built = Toast::create(AzString::from("m")).with_toast_kind(kind);
            let mut mutated = Toast::create(AzString::from("m"));
            mutated.set_kind(kind);
            assert_eq!(built, mutated, "{kind:?}: builder and setter must agree");
        }
        let toast = Toast::create(AzString::from("m"))
            .with_toast_kind(ToastKind::Danger)
            .with_toast_kind(ToastKind::Success);
        assert_eq!(toast.kind, ToastKind::Success);
        assert_eq!(
            toast.resolved_container_style(),
            build_toast_style(ToastKind::Success)
        );
    }
    // ------------------------------------------------------------------
    // set_dismissible / with_dismissible
    // ------------------------------------------------------------------
    #[test]
    fn set_dismissible_last_write_wins_and_touches_nothing_else() {
        let mut toast = Toast::with_kind(AzString::from("m"), ToastKind::Warning);
        let style_before = toast.resolved_container_style();
        for flag in [true, true, false, true, false, false] {
            toast.set_dismissible(flag);
            assert_eq!(toast.dismissible, flag);
        }
        assert_eq!(toast.kind, ToastKind::Warning);
        assert_eq!(toast.message.as_str(), "m");
        assert_eq!(
            toast.resolved_container_style(),
            style_before,
            "toggling must not restyle"
        );
        assert!(
            toast.toast_state.on_dismiss.is_none(),
            "toggling must not invent a callback"
        );
        assert!(
            toast.toast_state.inner.visible,
            "toggling the close button must not hide the toast"
        );
    }
    #[test]
    fn with_dismissible_toggle_sequence_ends_on_the_last_value() {
        assert!(Toast::default().with_dismissible(true).dismissible);
        assert!(!Toast::default().with_dismissible(false).dismissible);
        assert!(
            !Toast::default()
                .with_dismissible(true)
                .with_dismissible(false)
                .dismissible
        );
        assert!(
            Toast::default()
                .with_dismissible(false)
                .with_dismissible(true)
                .dismissible
        );
        // builder == setter
        let mut mutated = Toast::default();
        mutated.set_dismissible(false);
        assert_eq!(Toast::default().with_dismissible(false), mutated);
        // and re-enabling restores the exact default value
        assert_eq!(
            Toast::default()
                .with_dismissible(false)
                .with_dismissible(true),
            Toast::default()
        );
    }
    // ------------------------------------------------------------------
    // set_on_dismiss / with_on_dismiss
    // ------------------------------------------------------------------
    #[test]
    fn set_on_dismiss_forces_dismissible_back_on() {
        let mut toast = Toast::create(AzString::from("m")).with_dismissible(false);
        assert!(!toast.dismissible);
        toast.set_on_dismiss(RefAny::new(1u8), dismiss_cb(dismiss_do_nothing));
        assert!(
            toast.dismissible,
            "a dismiss callback must re-render the close button"
        );
        assert!(toast.toast_state.on_dismiss.is_some());
        assert!(
            toast.toast_state.inner.visible,
            "wiring a callback must not hide the toast"
        );
    }
    #[test]
    fn set_on_dismiss_replaces_rather_than_appends() {
        let mut toast = Toast::create(AzString::from("m"));
        toast.set_on_dismiss(RefAny::new(1u8), dismiss_cb(dismiss_do_nothing));
        let first = toast
            .toast_state
            .on_dismiss
            .as_ref()
            .expect("first callback")
            .refany
            .get_type_id();
        assert_eq!(first, RefAny::new(1u8).get_type_id());
        // a second call must *replace* the payload + function, not stack another one
        toast.set_on_dismiss(RefAny::new(9i64), dismiss_cb(record_dismiss));
        let second = toast
            .toast_state
            .on_dismiss
            .as_ref()
            .expect("second callback");
        assert_eq!(second.refany.get_type_id(), RefAny::new(9i64).get_type_id());
        assert_eq!(second.callback, dismiss_cb(record_dismiss));
        assert_ne!(second.callback, dismiss_cb(dismiss_do_nothing));
    }
    #[test]
    fn with_on_dismiss_keeps_message_and_kind() {
        let toast = Toast::with_kind(AzString::from("boom"), ToastKind::Danger)
            .with_on_dismiss(RefAny::new(0u8), dismiss_cb(dismiss_do_nothing));
        assert_eq!(toast.message.as_str(), "boom");
        assert_eq!(toast.kind, ToastKind::Danger);
        assert_eq!(
            toast.resolved_container_style(),
            build_toast_style(ToastKind::Danger)
        );
        assert!(toast.dismissible);
        assert!(toast.toast_state.on_dismiss.is_some());
    }
    #[test]
    fn set_dismissible_false_after_set_on_dismiss_silently_drops_the_close_button() {
        // Footgun, pinned as the *current* behaviour: `set_on_dismiss` forces
        // `dismissible = true`, but a later `set_dismissible(false)` wins and the
        // wired-up callback becomes unreachable. For a toast this is worse than
        // for an alert: the "x" is the *only* dismissal path (no auto-timeout),
        // so the toast can never be dismissed at all.
        let mut toast = Toast::create(AzString::from("m"));
        toast.set_on_dismiss(RefAny::new(0u8), dismiss_cb(record_dismiss));
        toast.set_dismissible(false);
        assert!(
            toast.toast_state.on_dismiss.is_some(),
            "the callback is still stored"
        );
        let dom = toast.dom();
        assert_eq!(
            dom.children.as_ref().len(),
            1,
            "no close button is rendered, so the toast is undismissable"
        );
        assert!(
            dom.children.as_ref()[0]
                .root
                .get_callbacks()
                .as_ref()
                .is_empty(),
            "and no handler is attached anywhere else either"
        );
    }
    // ------------------------------------------------------------------
    // swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_returns_the_original_and_resets_self() {
        let mut toast =
            Toast::with_kind(AzString::from("payload"), ToastKind::Danger).with_dismissible(false);
        let snapshot = toast.clone();
        let returned = toast.swap_with_default();
        assert_eq!(returned, snapshot, "the original must come back untouched");
        assert_eq!(
            toast,
            Toast::default(),
            "self must be reset to a default toast"
        );
        assert_eq!(toast.message.as_str(), "");
        assert_eq!(toast.kind, ToastKind::Info);
        assert!(
            toast.dismissible,
            "the reset toast is a *default* toast, so it is dismissible again"
        );
        assert!(toast.toast_state.on_dismiss.is_none());
        assert!(toast.toast_state.inner.visible);
    }
    #[test]
    fn swap_with_default_is_stable_when_repeated() {
        let mut toast = Toast::default();
        for _ in 0..3 {
            let returned = toast.swap_with_default();
            assert_eq!(returned, Toast::default());
            assert_eq!(toast, Toast::default());
        }
    }
    #[test]
    fn swap_with_default_moves_the_callback_out_of_self() {
        let mut toast = Toast::create(AzString::from("m"))
            .with_on_dismiss(RefAny::new(7u32), dismiss_cb(record_dismiss));
        let returned = toast.swap_with_default();
        assert!(
            returned.toast_state.on_dismiss.is_some(),
            "the callback moves out"
        );
        assert!(
            toast.toast_state.on_dismiss.is_none(),
            "the reset toast must not keep a reference to the old callback"
        );
    }
    #[test]
    fn swap_with_default_round_trips_a_dismissed_toast() {
        // a toast that was already dismissed must hand its `visible == false`
        // state to the caller, not silently reset it in the returned value
        let mut toast = Toast::create(AzString::from("m"));
        toast.toast_state.inner.visible = false;
        let returned = toast.swap_with_default();
        assert!(!returned.toast_state.inner.visible);
        assert!(
            toast.toast_state.inner.visible,
            "the fresh toast is visible"
        );
    }
    // ------------------------------------------------------------------
    // Toast::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_of_a_default_toast_is_a_container_with_message_and_close() {
        let toast = Toast::create(AzString::from("hi"));
        let style = toast.resolved_container_style();
        let dom = toast.dom();
        assert!(dom.root.has_class("__azul-native-toast"));
        assert!(
            dom.root.get_callbacks().as_ref().is_empty(),
            "the container itself must carry no live callback"
        );
        assert_eq!(
            dom.root.style.iter_inline_properties().count(),
            style.len(),
            "every container property must reach the node's inline style"
        );
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 2, "[message, close]");
        assert!(children[0].root.has_class("__azul-native-toast-message"));
        assert_eq!(text_of(&children[0]), Some("hi"));
        assert!(children[0].root.get_callbacks().as_ref().is_empty());
        assert!(children[0].root.get_tab_index().is_none());
    }
    #[test]
    fn dom_children_carry_exactly_the_static_child_styles() {
        let dom = Toast::create(AzString::from("hi")).dom();
        let children = dom.children.as_ref();
        let want_message: Vec<CssProperty> = TOAST_MESSAGE_STYLE
            .iter()
            .map(|p| p.property.clone())
            .collect();
        let want_close: Vec<CssProperty> = TOAST_CLOSE_STYLE
            .iter()
            .map(|p| p.property.clone())
            .collect();
        assert_eq!(inline_props(&children[0]), want_message);
        assert_eq!(inline_props(&children[1]), want_close);
        // the message takes the free space, the close button never does
        assert!(want_message.contains(&CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))));
        assert!(want_close.contains(&CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))));
        // ... and the "x" must not be text-selectable / must show a pointer
        assert!(want_close.contains(&CssProperty::const_cursor(StyleCursor::Pointer)));
        assert!(want_close.contains(&CssProperty::user_select(StyleUserSelect::None)));
    }
    #[test]
    fn dom_close_button_is_focusable_and_wired_to_the_dismiss_handler() {
        let dom = Toast::create(AzString::from("hi")).dom();
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 2);
        let close = &children[1];
        assert!(close.root.has_class("__azul-native-toast-close"));
        assert_eq!(
            text_of(close),
            Some("\u{00D7}"),
            "the close glyph is U+00D7 MULTIPLICATION SIGN"
        );
        assert!(
            matches!(close.root.get_tab_index(), Some(TabIndex::Auto)),
            "the close button must be keyboard-reachable"
        );
        let callbacks = close.root.get_callbacks();
        assert_eq!(callbacks.as_ref().len(), 1, "exactly one dismiss handler");
        let cb = &callbacks.as_ref()[0];
        assert!(matches!(
            &cb.event,
            EventFilter::Hover(HoverEventFilter::Click)
        ));
        assert_eq!(cb.callback.cb, default_on_toast_dismiss as usize);
        assert!(matches!(&cb.callback.ctx, OptionRefAny::None));
    }
    #[test]
    fn dom_hands_the_toast_state_to_the_close_button() {
        let toast = Toast::create(AzString::from("hi"))
            .with_on_dismiss(RefAny::new(0u8), dismiss_cb(record_dismiss));
        let dom = toast.dom();
        let close = &dom.children.as_ref()[1];
        let mut payload = close.root.get_callbacks().as_ref()[0].refany.clone();
        assert!(
            wrapper_visible(&mut payload),
            "the close button must receive a live, visible ToastStateWrapper"
        );
        assert!(
            payload
                .downcast_ref::<ToastStateWrapper>()
                .expect("ToastStateWrapper")
                .on_dismiss
                .is_some(),
            "the user callback must travel with the state"
        );
    }
    #[test]
    fn dom_of_a_non_dismissible_toast_has_no_callbacks_at_all() {
        let dom = Toast::create(AzString::from("m"))
            .with_dismissible(false)
            .dom();
        assert!(dom.root.has_class("__azul-native-toast"));
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 1, "no close button without `dismissible`");
        assert!(children[0].root.has_class("__azul-native-toast-message"));
        assert!(children[0].root.get_callbacks().as_ref().is_empty());
        assert!(dom.root.get_callbacks().as_ref().is_empty());
    }
    #[test]
    fn dom_renders_even_when_the_state_says_hidden() {
        // Pinned current behaviour: `visible` is *only* consulted by the dismiss
        // handler (which restyles the live node); `dom()` ignores it, so a
        // pre-dismissed toast is still emitted at full size.  A host that
        // rebuilds its DOM must filter dismissed toasts out itself.
        let mut toast = Toast::create(AzString::from("gone"));
        toast.toast_state.inner.visible = false;
        let dom = toast.dom();
        assert_eq!(dom.children.as_ref().len(), 2);
        assert_eq!(text_of(&dom.children.as_ref()[0]), Some("gone"));
        let close = &dom.children.as_ref()[1];
        let mut payload = close.root.get_callbacks().as_ref()[0].refany.clone();
        assert!(
            !wrapper_visible(&mut payload),
            "the hidden state travels into the DOM verbatim"
        );
    }
    #[test]
    fn dom_is_stable_across_kinds_and_the_kind_class_is_not_emitted() {
        for kind in ALL_KINDS {
            let dom = Toast::with_kind(AzString::from("m"), kind).dom();
            assert!(dom.root.has_class("__azul-native-toast"));
            assert_eq!(dom.children.as_ref().len(), 2);
            // NOTE: `ToastKind::class_name()` is *not* applied to the DOM - the
            // container only ever carries the generic container class.
            assert!(
                !dom.root.has_class(kind.class_name()),
                "current behaviour: the kind class is not emitted"
            );
        }
    }
    #[test]
    fn from_toast_for_dom_is_exactly_dom() {
        // non-dismissible, so no RefAny identity is involved in the comparison
        let toast =
            Toast::with_kind(AzString::from("m"), ToastKind::Success).with_dismissible(false);
        let via_from = Dom::from(toast.clone());
        let via_method = toast.dom();
        assert!(
            via_from == via_method,
            "`impl From<Toast> for Dom` must delegate to `Toast::dom`"
        );
    }
    // ------------------------------------------------------------------
    // default_on_toast_dismiss
    // ------------------------------------------------------------------
    #[test]
    fn dismiss_hides_the_container_and_flips_visible() {
        let mut data = RefAny::new(ToastStateWrapper::default());
        // node 2 == the close button, its parent (node 0) is the container
        let (update, changes) =
            run_dismiss(Some(dismissible_styled_dom()), CLOSE_NODE, data.clone());
        assert_eq!(update, Update::DoNothing, "no user callback -> DoNothing");
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)],
            "the *container* (not the close button) must be hidden"
        );
        assert!(!wrapper_visible(&mut data), "state must flip to hidden");
    }
    #[test]
    fn dismiss_invokes_the_user_callback_with_the_already_flipped_state() {
        let mut log = RefAny::new(DismissLog { calls: Vec::new() });
        let mut data = RefAny::new(ToastStateWrapper {
            inner: ToastState { visible: true },
            on_dismiss: Some(ToastOnDismiss {
                callback: dismiss_cb(record_dismiss),
                refany: log.clone(),
            })
            .into(),
        });
        let (update, changes) =
            run_dismiss(Some(dismissible_styled_dom()), CLOSE_NODE, 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 `visible == false` (already dismissed)"
        );
        assert!(!wrapper_visible(&mut data));
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)],
            "the container is hidden even after a user callback ran"
        );
    }
    #[test]
    fn dismiss_twice_is_idempotent() {
        let mut log = RefAny::new(DismissLog { calls: Vec::new() });
        let mut data = RefAny::new(ToastStateWrapper {
            inner: ToastState { visible: true },
            on_dismiss: Some(ToastOnDismiss {
                callback: dismiss_cb(record_dismiss),
                refany: log.clone(),
            })
            .into(),
        });
        for _ in 0..2 {
            let (update, changes) =
                run_dismiss(Some(dismissible_styled_dom()), CLOSE_NODE, data.clone());
            assert_eq!(update, Update::RefreshDom);
            assert_eq!(
                display_writes(&changes),
                alloc::vec![(0usize, LayoutDisplay::None)]
            );
        }
        assert!(
            !wrapper_visible(&mut data),
            "a second dismiss must not un-hide"
        );
        assert_eq!(
            log_calls(&mut log),
            alloc::vec![false, false],
            "each click fires the callback exactly once, always with visible == false"
        );
    }
    #[test]
    fn dismiss_from_the_message_node_also_hides_the_container() {
        // Pinned: the handler hides `parent(hit)`, whatever the hit node is.
        // For the toast the message <p>'s parent is the container too, so a
        // mis-wired handler would still "work" - which is why the close button
        // must stay the only node carrying it (see the wiring test above).
        let mut data = RefAny::new(ToastStateWrapper::default());
        let (update, changes) =
            run_dismiss(Some(dismissible_styled_dom()), MESSAGE_NODE, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)]
        );
        assert!(!wrapper_visible(&mut data));
    }
    #[test]
    fn dismiss_on_a_root_hit_node_is_a_noop() {
        // node 0 has no parent -> there is no container to hide
        let mut data = RefAny::new(ToastStateWrapper::default());
        let (update, changes) = run_dismiss(Some(dismissible_styled_dom()), 0, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "nothing may be restyled without a parent"
        );
        assert!(wrapper_visible(&mut data), "state must not flip");
    }
    #[test]
    fn dismiss_with_a_stale_hit_node_is_a_noop() {
        // node 999 does not exist in the 3-node fixture
        let mut data = RefAny::new(ToastStateWrapper::default());
        let (update, changes) = run_dismiss(Some(dismissible_styled_dom()), 999, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(wrapper_visible(&mut data));
    }
    #[test]
    fn dismiss_with_an_absurd_hit_node_index_does_not_panic() {
        // usize::MAX / 2 is far past any allocated NodeId
        let mut data = RefAny::new(ToastStateWrapper::default());
        let (update, changes) =
            run_dismiss(Some(dismissible_styled_dom()), usize::MAX / 2, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(wrapper_visible(&mut data));
    }
    #[test]
    fn dismiss_without_any_layout_result_is_a_noop() {
        let mut data = RefAny::new(ToastStateWrapper::default());
        let (update, changes) = run_dismiss(None, CLOSE_NODE, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(wrapper_visible(&mut data), "state must not flip");
    }
    #[test]
    fn dismiss_with_a_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_dismiss(Some(dismissible_styled_dom()), CLOSE_NODE, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign payload must not hide the container"
        );
    }
    #[test]
    fn dismiss_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 toast = Toast::create(AzString::from("bye"));
        let dom = toast.dom();
        let close = &dom.children.as_ref()[1];
        let entry = &close.root.get_callbacks().as_ref()[0];
        assert_eq!(entry.callback.cb, default_on_toast_dismiss as usize);
        let mut payload = entry.refany.clone();
        let styled = StyledDom::create_from_dom(dom);
        let (update, changes) = run_dismiss(Some(styled), CLOSE_NODE, payload.clone());
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)]
        );
        assert!(
            !wrapper_visible(&mut payload),
            "the state living in the DOM must be flipped to hidden"
        );
    }
    #[test]
    fn dismiss_end_to_end_reaches_a_user_callback_wired_through_the_builder() {
        let mut log = RefAny::new(DismissLog { calls: Vec::new() });
        let dom = Toast::with_kind(AzString::from("bye"), ToastKind::Danger)
            .with_on_dismiss(log.clone(), dismiss_cb(record_dismiss))
            .dom();
        let payload = dom.children.as_ref()[1].root.get_callbacks().as_ref()[0]
            .refany
            .clone();
        let styled = StyledDom::create_from_dom(dom);
        let (update, changes) = run_dismiss(Some(styled), CLOSE_NODE, payload);
        assert_eq!(update, Update::RefreshDom);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(0usize, LayoutDisplay::None)]
        );
        assert_eq!(
            log_calls(&mut log),
            alloc::vec![false],
            "the builder-wired callback must fire exactly once, with visible == false"
        );
    }
}