1
//! Alert / banner widget — a coloured inline message box conveying an
2
//! informational, success, warning or danger status. A container (a near-clone
3
//! of [`crate::widgets::card::Card`] / [`crate::widgets::frame::Frame`]) holding
4
//! a message string, with an optional dismissible "x" close affordance.
5
//!
6
//! When made dismissible (`with_dismissible(true)` or `set_on_dismiss`), the
7
//! alert mirrors the stateful pattern of [`crate::widgets::check_box::CheckBox`]:
8
//! it carries an [`AlertStateWrapper`] (`{ visible } + on_dismiss`) in a
9
//! [`RefAny`] attached to the close button. Clicking the close button flips
10
//! `visible` to `false`, invokes the optional user `on_dismiss`, and hides the
11
//! whole alert by setting `display: none` on the container via
12
//! `set_css_property` (mirroring check_box's live restyle). A non-dismissible
13
//! alert renders no close button and carries no live callback — it is then just
14
//! a stateless styled container.
15
//!
16
//! Key types: [`Alert`], [`AlertKind`], [`AlertState`], [`AlertOnDismiss`].
17

            
18
use azul_core::{
19
    callbacks::{CoreCallbackData, Update},
20
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
21
    refany::RefAny,
22
};
23
use azul_css::{
24
    dynamic_selector::{
25
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
26
    },
27
    impl_option_inner,
28
    props::{
29
        basic::{
30
            color::ColorU,
31
            font::{StyleFontFamily, StyleFontFamilyVec},
32
            StyleFontSize,
33
        },
34
        layout::{
35
            LayoutAlignItems, LayoutAlignSelf, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow,
36
            LayoutMarginLeft, LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight,
37
            LayoutPaddingTop,
38
        },
39
        property::{CssProperty, *},
40
        style::{
41
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
42
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
43
            StyleBorderBottomColor, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius,
44
            StyleBorderBottomStyle, StyleBorderLeftColor, StyleBorderLeftStyle,
45
            StyleBorderRightColor, StyleBorderRightStyle, StyleBorderTopColor,
46
            StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderTopStyle, StyleCursor,
47
            StyleTextAlign, StyleTextColor, StyleUserSelect,
48
        },
49
    },
50
    AzString,
51
};
52

            
53
use crate::callbacks::{Callback, CallbackInfo};
54

            
55
static ALERT_CONTAINER_CLASS: &[IdOrClass] =
56
    &[Class(AzString::from_const_str("__azul-native-alert"))];
57
static ALERT_MESSAGE_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
58
    "__azul-native-alert-message",
59
))];
60
static ALERT_CLOSE_CLASS: &[IdOrClass] =
61
    &[Class(AzString::from_const_str("__azul-native-alert-close"))];
62

            
63
const SYSTEM_UI_STR: AzString = AzString::from_const_str("system:ui");
64
const SYSTEM_UI_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SYSTEM_UI_STR)];
65
const SYSTEM_UI_FAMILY: StyleFontFamilyVec =
66
    StyleFontFamilyVec::from_const_slice(SYSTEM_UI_FAMILIES);
67

            
68
/// Callback function type invoked when a dismissible alert's close button is clicked.
69
pub type AlertOnDismissCallbackType = extern "C" fn(RefAny, CallbackInfo, AlertState) -> Update;
70
impl_widget_callback!(
71
    AlertOnDismiss,
72
    OptionAlertOnDismiss,
73
    AlertOnDismissCallback,
74
    AlertOnDismissCallbackType
75
);
76

            
77
azul_core::impl_managed_callback! {
78
    wrapper:        AlertOnDismissCallback,
79
    info_ty:        CallbackInfo,
80
    return_ty:      Update,
81
    default_ret:    Update::DoNothing,
82
    invoker_static: ALERT_ON_DISMISS_INVOKER,
83
    invoker_ty:     AzAlertOnDismissCallbackInvoker,
84
    thunk_fn:       az_alert_on_dismiss_callback_thunk,
85
    setter_fn:      AzApp_setAlertOnDismissCallbackInvoker,
86
    from_handle_fn: AzAlertOnDismissCallback_createFromHostHandle,
87
    extra_args:     [ state: AlertState ],
88
}
89

            
90
/// The semantic colour variant of an [`Alert`] (Bootstrap alert palette).
91
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
92
#[repr(C)]
93
pub enum AlertKind {
94
    /// Blue informational alert — the default.
95
    #[default]
96
    Info,
97
    /// Green success alert.
98
    Success,
99
    /// Yellow warning alert.
100
    Warning,
101
    /// Red danger/error alert.
102
    Danger,
103
}
104

            
105
impl AlertKind {
106
    /// Returns the `(background, border, text)` colours for this alert kind.
107
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
108
                                                 // pixel/coord path or to avoid churning call sites
109
                                                 // for a perf-neutral change)
110
113
    const fn colors(&self) -> (ColorU, ColorU, ColorU) {
111
113
        match self {
112
49
            Self::Info => (
113
49
                ColorU {
114
49
                    r: 207,
115
49
                    g: 244,
116
49
                    b: 252,
117
49
                    a: 255,
118
49
                }, // #cff4fc
119
49
                ColorU {
120
49
                    r: 182,
121
49
                    g: 239,
122
49
                    b: 251,
123
49
                    a: 255,
124
49
                }, // #b6effb
125
49
                ColorU {
126
49
                    r: 5,
127
49
                    g: 81,
128
49
                    b: 96,
129
49
                    a: 255,
130
49
                }, // #055160
131
49
            ),
132
20
            Self::Success => (
133
20
                ColorU {
134
20
                    r: 209,
135
20
                    g: 231,
136
20
                    b: 221,
137
20
                    a: 255,
138
20
                }, // #d1e7dd
139
20
                ColorU {
140
20
                    r: 186,
141
20
                    g: 219,
142
20
                    b: 204,
143
20
                    a: 255,
144
20
                }, // #badbcc
145
20
                ColorU {
146
20
                    r: 15,
147
20
                    g: 81,
148
20
                    b: 50,
149
20
                    a: 255,
150
20
                }, // #0f5132
151
20
            ),
152
20
            Self::Warning => (
153
20
                ColorU {
154
20
                    r: 255,
155
20
                    g: 243,
156
20
                    b: 205,
157
20
                    a: 255,
158
20
                }, // #fff3cd
159
20
                ColorU {
160
20
                    r: 255,
161
20
                    g: 236,
162
20
                    b: 181,
163
20
                    a: 255,
164
20
                }, // #ffecb5
165
20
                ColorU {
166
20
                    r: 102,
167
20
                    g: 77,
168
20
                    b: 3,
169
20
                    a: 255,
170
20
                }, // #664d03
171
20
            ),
172
24
            Self::Danger => (
173
24
                ColorU {
174
24
                    r: 248,
175
24
                    g: 215,
176
24
                    b: 218,
177
24
                    a: 255,
178
24
                }, // #f8d7da
179
24
                ColorU {
180
24
                    r: 245,
181
24
                    g: 194,
182
24
                    b: 199,
183
24
                    a: 255,
184
24
                }, // #f5c2c7
185
24
                ColorU {
186
24
                    r: 132,
187
24
                    g: 32,
188
24
                    b: 41,
189
24
                    a: 255,
190
24
                }, // #842029
191
24
            ),
192
        }
193
113
    }
194

            
195
    /// CSS class name for this alert kind (mirrors `ButtonType::class_name`).
196
    #[must_use]
197
20
    pub const fn class_name(&self) -> &'static str {
198
20
        match self {
199
5
            Self::Info => "__azul-alert-info",
200
5
            Self::Success => "__azul-alert-success",
201
5
            Self::Warning => "__azul-alert-warning",
202
5
            Self::Danger => "__azul-alert-danger",
203
        }
204
20
    }
205
}
206

            
207
/// A coloured inline message box with an optional dismissible close button.
208
#[derive(Debug, Clone, PartialEq, Eq)]
209
#[repr(C)]
210
pub struct Alert {
211
    /// Runtime state (`visible`) plus the optional dismiss callback.
212
    pub alert_state: AlertStateWrapper,
213
    /// The message text shown inside the alert.
214
    pub message: AzString,
215
    /// The colour variant.
216
    pub kind: AlertKind,
217
    /// Whether to render the "x" close button (hides the alert on click).
218
    pub dismissible: bool,
219
    /// The computed inline style for the container.
220
    /// The container's CSS, or `None` for "no opinion" — in which case the
221
    /// style is derived from `kind` at render time.
222
    ///
223
    /// `None` and `Some(empty)` are different answers: the first means the
224
    /// widget picks, the second means the caller asked for no properties at
225
    /// all and gets none.
226
    pub container_style: OptionCssPropertyWithConditionsVec,
227
}
228

            
229
#[derive(Debug, Default, Clone, PartialEq, Eq)]
230
#[repr(C)]
231
pub struct AlertStateWrapper {
232
    /// Whether the alert is currently visible.
233
    pub inner: AlertState,
234
    /// Optional: function to call when the alert is dismissed.
235
    pub on_dismiss: OptionAlertOnDismiss,
236
}
237

            
238
/// The visible/hidden state of an [`Alert`].
239
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
240
#[repr(C)]
241
pub struct AlertState {
242
    /// `true` (default) = shown, `false` = dismissed/hidden.
243
    pub visible: bool,
244
}
245

            
246
impl Default for AlertState {
247
83
    fn default() -> Self {
248
83
        Self { visible: true }
249
83
    }
250
}
251

            
252
/// Builds the container style for a given [`AlertKind`]. The colours are the
253
/// only kind-dependent properties, so the style is built at runtime per the
254
/// recipe's "runtime vec when param-dependent" path (see `badge::build_badge_style`).
255
83
fn build_alert_style(kind: AlertKind) -> CssPropertyWithConditionsVec {
256
83
    let (bg, border, text) = kind.colors();
257
83
    let bg_vec =
258
83
        StyleBackgroundContentVec::from_vec(alloc::vec![StyleBackgroundContent::Color(bg)]);
259
83
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
260
83
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
261
83
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
262
83
            LayoutFlexDirection::Row,
263
        )),
264
83
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Start)),
265
        // Span the full width of a flex-column parent.
266
83
        CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Stretch)),
267
83
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
268
            0,
269
        ))),
270
        // padding: 12px
271
83
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(
272
83
            LayoutPaddingTop::const_px(12,)
273
        )),
274
83
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
275
83
            LayoutPaddingBottom::const_px(12),
276
        )),
277
83
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
278
83
            LayoutPaddingLeft::const_px(12),
279
        )),
280
83
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
281
83
            LayoutPaddingRight::const_px(12),
282
        )),
283
        // border: 1px solid <border>
284
83
        CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
285
83
            LayoutBorderTopWidth::const_px(1),
286
        )),
287
83
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
288
83
            LayoutBorderBottomWidth::const_px(1),
289
        )),
290
83
        CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
291
83
            LayoutBorderLeftWidth::const_px(1),
292
        )),
293
83
        CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
294
83
            LayoutBorderRightWidth::const_px(1),
295
        )),
296
83
        CssPropertyWithConditions::simple(CssProperty::const_border_top_style(
297
83
            StyleBorderTopStyle {
298
83
                inner: BorderStyle::Solid,
299
83
            }
300
        )),
301
83
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
302
83
            StyleBorderBottomStyle {
303
83
                inner: BorderStyle::Solid,
304
83
            },
305
        )),
306
83
        CssPropertyWithConditions::simple(CssProperty::const_border_left_style(
307
83
            StyleBorderLeftStyle {
308
83
                inner: BorderStyle::Solid,
309
83
            },
310
        )),
311
83
        CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
312
83
            StyleBorderRightStyle {
313
83
                inner: BorderStyle::Solid,
314
83
            },
315
        )),
316
83
        CssPropertyWithConditions::simple(CssProperty::const_border_top_color(
317
83
            StyleBorderTopColor { inner: border }
318
        )),
319
83
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
320
83
            StyleBorderBottomColor { inner: border },
321
        )),
322
83
        CssPropertyWithConditions::simple(CssProperty::const_border_left_color(
323
83
            StyleBorderLeftColor { inner: border },
324
        )),
325
83
        CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
326
83
            StyleBorderRightColor { inner: border },
327
        )),
328
        // border-radius: 6px
329
83
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
330
83
            StyleBorderTopLeftRadius::const_px(6),
331
        )),
332
83
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
333
83
            StyleBorderTopRightRadius::const_px(6),
334
        )),
335
83
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
336
83
            StyleBorderBottomLeftRadius::const_px(6),
337
        )),
338
83
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
339
83
            StyleBorderBottomRightRadius::const_px(6),
340
        )),
341
83
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
342
            14
343
        ))),
344
83
        CssPropertyWithConditions::simple(CssProperty::const_font_family(SYSTEM_UI_FAMILY)),
345
        // Text colour is inherited by the message + close children.
346
83
        CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
347
83
            inner: text,
348
83
        })),
349
83
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg_vec)),
350
    ])
351
83
}
352

            
353
/// Message-text style: takes the remaining horizontal space, left-aligned.
354
static ALERT_MESSAGE_STYLE: &[CssPropertyWithConditions] = &[
355
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
356
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
357
];
358

            
359
/// Close-button ("x") style: a small pointer-cursor box on the right.
360
static ALERT_CLOSE_STYLE: &[CssPropertyWithConditions] = &[
361
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
362
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(18))),
363
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
364
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
365
    CssPropertyWithConditions::simple(CssProperty::const_margin_left(LayoutMarginLeft::const_px(
366
        12,
367
    ))),
368
];
369

            
370
impl Alert {
371
    /// Creates a new informational (blue) alert with the given message.
372
    #[inline]
373
    #[must_use]
374
67
    pub fn create(message: AzString) -> Self {
375
67
        Self::with_kind(message, AlertKind::Info)
376
67
    }
377

            
378
    /// Creates a new alert with the given message and colour variant.
379
    #[inline]
380
    #[must_use]
381
79
    pub fn with_kind(message: AzString, kind: AlertKind) -> Self {
382
79
        Self {
383
79
            alert_state: AlertStateWrapper::default(),
384
79
            message,
385
79
            kind,
386
79
            dismissible: false,
387
79
            container_style: OptionCssPropertyWithConditionsVec::None,
388
79
        }
389
79
    }
390

            
391
    /// Sets the colour variant.
392
    ///
393
    /// Does not touch `container_style`: the derived style is resolved from
394
    /// `kind` when the DOM is built, so changing the kind is enough. Writing it
395
    /// here would also overwrite a caller's explicit style.
396
    #[inline]
397
24
    pub const fn set_kind(&mut self, kind: AlertKind) {
398
24
        self.kind = kind;
399
24
    }
400

            
401
    /// Replace the container's CSS.
402
    ///
403
    /// Passing an empty vec is meaningful: it says "no properties", as opposed
404
    /// to leaving this unset, which says "derive them from `kind`".
405
    #[inline]
406
    pub fn set_container_style(&mut self, css: CssPropertyWithConditionsVec) {
407
        self.container_style = OptionCssPropertyWithConditionsVec::Some(css);
408
    }
409

            
410
    /// Builder-style [`Self::set_container_style`].
411
    #[inline]
412
    #[must_use]
413
    pub fn with_container_style(mut self, css: CssPropertyWithConditionsVec) -> Self {
414
        self.set_container_style(css);
415
        self
416
    }
417

            
418
    /// Builder-style setter for the colour variant.
419
    #[inline]
420
    #[must_use]
421
6
    pub const fn with_alert_kind(mut self, kind: AlertKind) -> Self {
422
6
        self.set_kind(kind);
423
6
        self
424
6
    }
425

            
426
    /// Sets whether the alert shows a "x" close button.
427
    #[inline]
428
34
    pub const fn set_dismissible(&mut self, dismissible: bool) {
429
34
        self.dismissible = dismissible;
430
34
    }
431

            
432
    /// Builder-style setter for the dismissible flag.
433
    #[inline]
434
    #[must_use]
435
26
    pub const fn with_dismissible(mut self, dismissible: bool) -> Self {
436
26
        self.set_dismissible(dismissible);
437
26
        self
438
26
    }
439

            
440
    /// Sets the dismiss callback. Implies `dismissible = true` so the close
441
    /// button is rendered.
442
    #[inline]
443
8
    pub fn set_on_dismiss<C: Into<AlertOnDismissCallback>>(&mut self, data: RefAny, on_dismiss: C) {
444
8
        self.dismissible = true;
445
8
        self.alert_state.on_dismiss = Some(AlertOnDismiss {
446
8
            callback: on_dismiss.into(),
447
8
            refany: data,
448
8
        })
449
8
        .into();
450
8
    }
451

            
452
    /// Builder-style setter for the dismiss callback (implies dismissible).
453
    #[inline]
454
    #[must_use]
455
3
    pub fn with_on_dismiss<C: Into<AlertOnDismissCallback>>(
456
3
        mut self,
457
3
        data: RefAny,
458
3
        on_dismiss: C,
459
3
    ) -> Self {
460
3
        self.set_on_dismiss(data, on_dismiss);
461
3
        self
462
3
    }
463

            
464
    /// Replaces `self` with a default (empty info) alert and returns the original.
465
    #[inline]
466
    #[must_use]
467
5
    pub fn swap_with_default(&mut self) -> Self {
468
5
        let mut s = Self::create(AzString::from_const_str(""));
469
5
        core::mem::swap(&mut s, self);
470
5
        s
471
5
    }
472

            
473
    /// Converts this alert into a DOM subtree with the `__azul-native-alert` class.
474
    #[inline]
475
    #[must_use]
476
29
    pub fn dom(self) -> Dom {
477
        use azul_core::{
478
            callbacks::CoreCallback,
479
            dom::{EventFilter, HoverEventFilter},
480
            refany::OptionRefAny,
481
        };
482

            
483
29
        let message = crate::widgets::widget_p_with_text(self.message)
484
29
            .with_ids_and_classes(IdOrClassVec::from_const_slice(ALERT_MESSAGE_CLASS))
485
29
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
486
29
                ALERT_MESSAGE_STYLE,
487
            ));
488

            
489
29
        let mut children = alloc::vec![message];
490

            
491
29
        if self.dismissible {
492
19
            let close = crate::widgets::widget_p_with_text(AzString::from_const_str("\u{00D7}"))
493
19
                .with_ids_and_classes(IdOrClassVec::from_const_slice(ALERT_CLOSE_CLASS))
494
19
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(ALERT_CLOSE_STYLE))
495
19
                .with_tab_index(TabIndex::Auto)
496
19
                // This is the CLOSE BUTTON, not the alert — the tab stop is on
497
19
                // the dismiss affordance. Its visible label is "\u{00D7}", a
498
19
                // multiplication sign, which is a picture of an X and not a
499
19
                // name: a screen reader reads it as "times" or skips it. So the
500
19
                // name is explicit, and the role is PushButton rather than the
501
19
                // Alert role that belongs to the container.
502
19
                .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
503
19
                    role: azul_core::a11y::AccessibilityRole::PushButton,
504
19
                    accessibility_name: Some(AzString::from_const_str("Close")).into(),
505
19
                    ..Default::default()
506
19
                })
507
19
                .with_callbacks(
508
19
                    alloc::vec![CoreCallbackData {
509
19
                        event: EventFilter::Hover(HoverEventFilter::Click),
510
19
                        callback: CoreCallback {
511
19
                            cb: default_on_alert_dismiss as usize,
512
19
                            ctx: OptionRefAny::None,
513
19
                        },
514
19
                        refany: RefAny::new(self.alert_state),
515
19
                    }]
516
19
                    .into(),
517
19
                );
518
19
            children.push(close);
519
19
        }
520

            
521
29
        Dom::create_div()
522
29
            .with_ids_and_classes(IdOrClassVec::from_const_slice(ALERT_CONTAINER_CLASS))
523
29
            .with_css_props(
524
29
                self.container_style
525
29
                    .clone()
526
29
                    .into_option()
527
29
                    .unwrap_or_else(|| build_alert_style(self.kind)),
528
            )
529
29
            .with_children(children.into())
530
29
    }
531
}
532

            
533
impl Default for Alert {
534
15
    fn default() -> Self {
535
15
        Self::create(AzString::from_const_str(""))
536
15
    }
537
}
538

            
539
/// Close-button click handler. The hit node is the close button (the
540
/// callback-bearing node, per `currentTarget` semantics — see `radio_group`);
541
/// its parent is the alert container. Flips `visible` to `false`, invokes the
542
/// optional user callback, then hides the whole alert via `display: none`.
543
9
extern "C" fn default_on_alert_dismiss(mut data: RefAny, mut info: CallbackInfo) -> Update {
544
9
    let close_node = info.get_hit_node();
545
9
    let Some(container) = info.get_parent(close_node) else {
546
3
        return Update::DoNothing;
547
    };
548

            
549
5
    let result = {
550
6
        let Some(mut alert) = data.downcast_mut::<AlertStateWrapper>() else {
551
1
            return Update::DoNothing;
552
        };
553
5
        alert.inner.visible = false;
554
5
        let inner = alert.inner;
555
5
        let alert = &mut *alert;
556
5
        match alert.on_dismiss.as_mut() {
557
3
            Some(AlertOnDismiss { callback, refany }) => (callback.cb)(refany.clone(), info, inner),
558
2
            None => Update::DoNothing,
559
        }
560
    };
561

            
562
    // TODO2: hides the alert by toggling `display: none` via set_css_property.
563
    // This follows the proven live-restyle pattern of switch/check_box/radio_group
564
    // (which toggle opacity/margin/background); the display:none relayout itself is
565
    // not GUI-verified in this build.
566
5
    info.set_css_property(container, CssProperty::const_display(LayoutDisplay::None));
567

            
568
5
    result
569
9
}
570

            
571
impl From<Alert> for Dom {
572
    fn from(a: Alert) -> Self {
573
        a.dom()
574
    }
575
}
576

            
577
#[cfg(test)]
578
mod autotest_generated {
579
    use std::{
580
        collections::{BTreeMap, HashMap},
581
        sync::{Arc, Mutex},
582
    };
583

            
584
    use azul_core::{
585
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
586
        geom::{LogicalRect, OptionLogicalPosition},
587
        gl::OptionGlContextPtr,
588
        hit_test::ScrollPosition,
589
        refany::OptionRefAny,
590
        resources::RendererResources,
591
        styled_dom::{NodeHierarchyItemId, StyledDom},
592
        window::{MonitorVec, RawWindowHandle},
593
    };
594
    use azul_css::system::SystemStyle;
595

            
596
    /// The container CSS the widget actually renders with, resolving the
597
    /// "no opinion" case the way `dom()` does.
598
    ///
599
    /// The tests used to read `alert.container_style` directly, back when the
600
    /// constructor pre-filled it. It is `None` until somebody sets one, so the
601
    /// question "does this alert carry its kind's style" is now asked of the
602
    /// resolved value rather than of the field.
603
    fn resolved_style(alert: &Alert) -> CssPropertyWithConditionsVec {
604
        alert
605
            .container_style
606
            .clone()
607
            .into_option()
608
            .unwrap_or_else(|| build_alert_style(alert.kind))
609
    }
610

            
611
    use rust_fontconfig::FcFontCache;
612

            
613
    use super::*;
614
    #[cfg(feature = "icu")]
615
    use crate::icu::IcuLocalizerHandle;
616
    use crate::{
617
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
618
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
619
        window::{DomLayoutResult, LayoutWindow},
620
        window_state::FullWindowState,
621
    };
622

            
623
    // ------------------------------------------------------------------
624
    // Helpers
625
    // ------------------------------------------------------------------
626

            
627
    const ALL_KINDS: [AlertKind; 4] = [
628
        AlertKind::Info,
629
        AlertKind::Success,
630
        AlertKind::Warning,
631
        AlertKind::Danger,
632
    ];
633

            
634
    /// The text of a text node, looking through the `<p>` block wrapper the
635
    /// label convention mandates (`p > text`).
636
    fn text_of(node: &Dom) -> Option<&str> {
637
        match node.root.get_node_type() {
638
            NodeType::Text(s) => Some(s.as_ref().as_str()),
639
            NodeType::P => match node.children.as_ref() {
640
                [only] => match only.root.get_node_type() {
641
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
642
                    _ => None,
643
                },
644
                _ => None,
645
            },
646
            _ => None,
647
        }
648
    }
649

            
650
    /// The `background-color` of a style vec (first background layer only).
651
    fn background_color(style: &CssPropertyWithConditionsVec) -> Option<ColorU> {
652
        style.as_ref().iter().find_map(|p| match &p.property {
653
            CssProperty::BackgroundContent(v) => match v.get_property()?.as_ref().first()? {
654
                StyleBackgroundContent::Color(c) => Some(*c),
655
                _ => None,
656
            },
657
            _ => None,
658
        })
659
    }
660

            
661
    /// Every `border-*-color` in a style vec, in declaration order.
662
    fn border_colors(style: &CssPropertyWithConditionsVec) -> Vec<ColorU> {
663
        style
664
            .as_ref()
665
            .iter()
666
            .filter_map(|p| match &p.property {
667
                CssProperty::BorderTopColor(v) => v.get_property().map(|c| c.inner),
668
                CssProperty::BorderBottomColor(v) => v.get_property().map(|c| c.inner),
669
                CssProperty::BorderLeftColor(v) => v.get_property().map(|c| c.inner),
670
                CssProperty::BorderRightColor(v) => v.get_property().map(|c| c.inner),
671
                _ => None,
672
            })
673
            .collect()
674
    }
675

            
676
    /// The `color` (text colour) of a style vec.
677
    fn text_color(style: &CssPropertyWithConditionsVec) -> Option<ColorU> {
678
        style.as_ref().iter().find_map(|p| match &p.property {
679
            CssProperty::TextColor(v) => v.get_property().map(|c| c.inner),
680
            _ => None,
681
        })
682
    }
683

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

            
695
    /// A `RefAny` payload recording every `AlertState` a user `on_dismiss` sees.
696
    struct DismissLog {
697
        calls: Vec<bool>,
698
    }
699

            
700
    extern "C" fn record_dismiss(mut data: RefAny, _: CallbackInfo, state: AlertState) -> Update {
701
        if let Some(mut log) = data.downcast_mut::<DismissLog>() {
702
            log.calls.push(state.visible);
703
        }
704
        Update::RefreshDom
705
    }
706

            
707
    extern "C" fn dismiss_do_nothing(_: RefAny, _: CallbackInfo, _: AlertState) -> Update {
708
        Update::DoNothing
709
    }
710

            
711
    fn dismiss_cb(f: AlertOnDismissCallbackType) -> AlertOnDismissCallback {
712
        f.into()
713
    }
714

            
715
    /// `visible` of an `AlertStateWrapper` payload.
716
    fn wrapper_visible(data: &mut RefAny) -> bool {
717
        data.downcast_ref::<AlertStateWrapper>()
718
            .expect("payload must still be an AlertStateWrapper")
719
            .inner
720
            .visible
721
    }
722

            
723
    /// The `visible` flags recorded by a `DismissLog` payload.
724
    fn log_calls(data: &mut RefAny) -> Vec<bool> {
725
        data.downcast_ref::<DismissLog>()
726
            .expect("payload must still be a DismissLog")
727
            .calls
728
            .clone()
729
    }
730

            
731
    /// A `DomLayoutResult` with an *empty* layout tree: the dismiss handler only
732
    /// walks `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
733
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
734
        DomLayoutResult {
735
            styled_dom,
736
            layout_tree: LayoutTree {
737
                nodes: Vec::new(),
738
                warm: Vec::new(),
739
                cold: Vec::new(),
740
                root: 0,
741
                dom_to_layout: BTreeMap::new(),
742
                children_arena: Vec::new(),
743
                children_offsets: Vec::new(),
744
                subtree_needs_intrinsic: Vec::new(),
745
            },
746
            calculated_positions: Vec::new(),
747
            viewport: LogicalRect::zero(),
748
            display_list: Arc::new(DisplayList::default()),
749
            scroll_ids: HashMap::new(),
750
            scroll_id_to_node_id: HashMap::new(),
751
        }
752
    }
753

            
754
    /// The flattened DOM of a dismissible alert: `container(0)`, `message(1)`,
755
    /// `close(2)` — i.e. exactly the hierarchy `default_on_alert_dismiss` walks
756
    /// (hit node -> parent).
757
    fn dismissible_styled_dom() -> StyledDom {
758
        let alert = Alert::create(AzString::from("msg")).with_dismissible(true);
759
        let styled = StyledDom::create_from_dom(alert.dom());
760
        assert_eq!(
761
            styled.node_hierarchy.as_ref().len(),
762
            5,
763
            "fixture must flatten to container / message <p> + text / close <p> + text"
764
        );
765
        styled
766
    }
767

            
768
    /// Invokes `default_on_alert_dismiss` against a `LayoutWindow` holding
769
    /// `styled` (or nothing at all, when `styled` is `None`), with `hit` as the
770
    /// hit node. Returns the `Update` plus every recorded `CallbackChange`.
771
    fn run_dismiss(
772
        styled: Option<StyledDom>,
773
        hit: usize,
774
        data: RefAny,
775
    ) -> (Update, Vec<CallbackChange>) {
776
        let mut layout_window =
777
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
778
        if let Some(sd) = styled {
779
            layout_window
780
                .layout_results
781
                .insert(DomId::ROOT_ID, layout_result(sd));
782
        }
783

            
784
        let renderer_resources = RendererResources::default();
785
        let previous_window_state: Option<FullWindowState> = None;
786
        let current_window_state = FullWindowState::default();
787
        let gl_context = OptionGlContextPtr::None;
788
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
789
            BTreeMap::new();
790
        let window_handle = RawWindowHandle::Unsupported;
791
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
792

            
793
        let ref_data = CallbackInfoRefData {
794
            layout_window: &layout_window,
795
            renderer_resources: &renderer_resources,
796
            previous_window_state: &previous_window_state,
797
            current_window_state: &current_window_state,
798
            gl_context: &gl_context,
799
            current_scroll_manager: &scroll_states,
800
            current_window_handle: &window_handle,
801
            system_callbacks: &system_callbacks,
802
            system_style: Arc::new(SystemStyle::default()),
803
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
804
            #[cfg(feature = "icu")]
805
            icu_localizer: IcuLocalizerHandle::default(),
806
            ctx: OptionRefAny::None,
807
        };
808

            
809
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
810

            
811
        let info = CallbackInfo::new(
812
            &ref_data,
813
            &changes,
814
            DomNodeId {
815
                dom: DomId::ROOT_ID,
816
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
817
            },
818
            OptionLogicalPosition::None,
819
            OptionLogicalPosition::None,
820
        );
821

            
822
        let update = default_on_alert_dismiss(data, info);
823
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
824
        (update, recorded)
825
    }
826

            
827
    /// Every `display` write recorded in the change log, as `(node index, display)`.
828
    fn display_writes(changes: &[CallbackChange]) -> Vec<(usize, LayoutDisplay)> {
829
        let mut out = Vec::new();
830
        for change in changes {
831
            if let CallbackChange::ChangeNodeCssProperties {
832
                node_id,
833
                properties,
834
                ..
835
            } = change
836
            {
837
                for p in properties.as_ref() {
838
                    if let CssProperty::Display(v) = p {
839
                        if let Some(d) = v.get_property() {
840
                            out.push((node_id.index(), *d));
841
                        }
842
                    }
843
                }
844
            }
845
        }
846
        out
847
    }
848

            
849
    // ------------------------------------------------------------------
850
    // AlertKind::colors  (getter)
851
    // ------------------------------------------------------------------
852

            
853
    #[test]
854
    fn kind_colors_are_the_documented_bootstrap_palette() {
855
        let expect = |(r, g, b): (u8, u8, u8)| ColorU { r, g, b, a: 255 };
856

            
857
        assert_eq!(
858
            AlertKind::Info.colors(),
859
            (
860
                expect((207, 244, 252)), // #cff4fc
861
                expect((182, 239, 251)), // #b6effb
862
                expect((5, 81, 96)),     // #055160
863
            )
864
        );
865
        assert_eq!(
866
            AlertKind::Success.colors(),
867
            (
868
                expect((209, 231, 221)), // #d1e7dd
869
                expect((186, 219, 204)), // #badbcc
870
                expect((15, 81, 50)),    // #0f5132
871
            )
872
        );
873
        assert_eq!(
874
            AlertKind::Warning.colors(),
875
            (
876
                expect((255, 243, 205)), // #fff3cd
877
                expect((255, 236, 181)), // #ffecb5
878
                expect((102, 77, 3)),    // #664d03
879
            )
880
        );
881
        assert_eq!(
882
            AlertKind::Danger.colors(),
883
            (
884
                expect((248, 215, 218)), // #f8d7da
885
                expect((245, 194, 199)), // #f5c2c7
886
                expect((132, 32, 41)),   // #842029
887
            )
888
        );
889
    }
890

            
891
    #[test]
892
    fn kind_colors_are_fully_opaque_and_pairwise_distinct() {
893
        for kind in ALL_KINDS {
894
            let (bg, border, text) = kind.colors();
895
            for (name, c) in [("bg", bg), ("border", border), ("text", text)] {
896
                assert_eq!(c.a, 255, "{kind:?}.{name} must be fully opaque");
897
            }
898
            // a coloured banner is only legible if bg != text
899
            assert_ne!(bg, text, "{kind:?}: background must differ from text");
900
        }
901

            
902
        for (i, a) in ALL_KINDS.iter().enumerate() {
903
            for b in &ALL_KINDS[i + 1..] {
904
                assert_ne!(
905
                    a.colors(),
906
                    b.colors(),
907
                    "{a:?} and {b:?} must be visually distinguishable"
908
                );
909
            }
910
        }
911
    }
912

            
913
    #[test]
914
    fn kind_colors_default_is_info_and_call_is_pure() {
915
        assert_eq!(AlertKind::default(), AlertKind::Info);
916
        assert_eq!(AlertKind::default().colors(), AlertKind::Info.colors());
917

            
918
        // repeated calls on the same (Copy) receiver must be stable
919
        let k = AlertKind::Danger;
920
        assert_eq!(k.colors(), k.colors());
921
        assert_eq!(k.colors(), k.colors());
922
    }
923

            
924
    #[test]
925
    fn kind_colors_is_const_evaluable() {
926
        const INFO: (ColorU, ColorU, ColorU) = AlertKind::Info.colors();
927
        assert_eq!(
928
            INFO.0,
929
            ColorU {
930
                r: 207,
931
                g: 244,
932
                b: 252,
933
                a: 255
934
            }
935
        );
936
    }
937

            
938
    // ------------------------------------------------------------------
939
    // AlertKind::class_name  (getter)
940
    // ------------------------------------------------------------------
941

            
942
    #[test]
943
    fn class_name_exact_values_and_shape() {
944
        assert_eq!(AlertKind::Info.class_name(), "__azul-alert-info");
945
        assert_eq!(AlertKind::Success.class_name(), "__azul-alert-success");
946
        assert_eq!(AlertKind::Warning.class_name(), "__azul-alert-warning");
947
        assert_eq!(AlertKind::Danger.class_name(), "__azul-alert-danger");
948

            
949
        for kind in ALL_KINDS {
950
            let name = kind.class_name();
951
            assert!(
952
                name.starts_with("__azul-alert-"),
953
                "{kind:?} -> {name:?} must keep the widget prefix"
954
            );
955
            assert!(
956
                !name.contains(char::is_whitespace),
957
                "{name:?} must be a single CSS class token"
958
            );
959
            assert!(name.is_ascii(), "{name:?} must stay ASCII");
960
            // stable across calls, and equal for equal kinds
961
            assert_eq!(name, kind.class_name());
962
        }
963
    }
964

            
965
    #[test]
966
    fn class_name_is_unique_per_kind() {
967
        let mut names: Vec<&str> = ALL_KINDS.iter().map(|k| k.class_name()).collect();
968
        names.sort_unstable();
969
        names.dedup();
970
        assert_eq!(names.len(), 4, "every kind needs its own class name");
971
    }
972

            
973
    #[test]
974
    fn class_name_is_const_evaluable() {
975
        const DANGER: &str = AlertKind::Danger.class_name();
976
        assert_eq!(DANGER, "__azul-alert-danger");
977
    }
978

            
979
    // ------------------------------------------------------------------
980
    // build_alert_style
981
    // ------------------------------------------------------------------
982

            
983
    #[test]
984
    fn build_alert_style_declares_the_same_properties_for_every_kind() {
985
        let info = property_types(&build_alert_style(AlertKind::Info));
986
        assert!(!info.is_empty(), "the container style must not be empty");
987

            
988
        for kind in ALL_KINDS {
989
            let style = build_alert_style(kind);
990
            assert_eq!(
991
                property_types(&style),
992
                info,
993
                "{kind:?} must declare the same properties, in the same order, as Info"
994
            );
995
            // the style is unconditional: nothing is gated behind :hover/@media/...
996
            for p in style.as_ref() {
997
                assert!(
998
                    p.apply_if.as_ref().is_empty(),
999
                    "{kind:?}: {:?} must be unconditional",
                    p.property
                );
            }
        }
    }
    #[test]
    fn build_alert_style_declares_no_property_twice() {
        // a duplicated property would silently shadow the earlier declaration
        for kind in ALL_KINDS {
            let types = property_types(&build_alert_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_alert_style_colors_track_the_kind_palette() {
        for kind in ALL_KINDS {
            let style = build_alert_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_alert_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_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_alert_style(kind);
            for want in &expected {
                assert!(
                    style.as_ref().contains(want),
                    "{kind:?}: missing {:?}",
                    want.property
                );
            }
        }
    }
    #[test]
    fn build_alert_style_differs_only_in_the_colours() {
        let info = build_alert_style(AlertKind::Info);
        for kind in [AlertKind::Success, AlertKind::Warning, AlertKind::Danger] {
            let other = build_alert_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"
            );
        }
    }
    // ------------------------------------------------------------------
    // Alert::create / with_kind / Default
    // ------------------------------------------------------------------
    #[test]
    fn create_is_an_info_alert_with_no_close_button() {
        let alert = Alert::create(AzString::from("hello"));
        assert_eq!(alert.message.as_str(), "hello");
        assert_eq!(alert.kind, AlertKind::Info);
        assert!(!alert.dismissible, "a fresh alert has no close button");
        assert!(alert.alert_state.inner.visible, "a fresh alert is visible");
        assert!(alert.alert_state.on_dismiss.is_none());
        assert_eq!(resolved_style(&alert), build_alert_style(AlertKind::Info));
    }
    #[test]
    fn create_with_empty_message_equals_default_and_is_value_comparable() {
        assert_eq!(Alert::create(AzString::from("")), Alert::default());
        // equality is structural, not pointer-based
        assert_eq!(
            Alert::create(AzString::from("a")),
            Alert::create(AzString::from("a"))
        );
        assert_ne!(
            Alert::create(AzString::from("a")),
            Alert::create(AzString::from("b"))
        );
        assert_ne!(
            Alert::create(AzString::from("a")),
            Alert::with_kind(AzString::from("a"), AlertKind::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(long.as_str()),      // 100k chars
        ];
        for message in cases {
            let alert = Alert::create(message.clone());
            assert_eq!(alert.message.as_str(), message.as_str());
            // the message must survive the trip through the DOM byte-for-byte
            let dom = alert.dom();
            let msg_node = &dom.children.as_ref()[0];
            assert_eq!(text_of(msg_node), Some(message.as_str()));
        }
    }
    #[test]
    fn with_kind_stores_both_args_for_every_kind() {
        for kind in ALL_KINDS {
            let alert = Alert::with_kind(AzString::from("m"), kind);
            assert_eq!(alert.kind, kind);
            assert_eq!(alert.message.as_str(), "m");
            assert!(!alert.dismissible);
            assert!(alert.alert_state.on_dismiss.is_none());
            assert!(alert.alert_state.inner.visible);
            assert_eq!(
                resolved_style(&alert),
                build_alert_style(kind),
                "{kind:?}: the container style must match the kind it was built with"
            );
        }
    }
    // ------------------------------------------------------------------
    // set_kind / with_alert_kind
    // ------------------------------------------------------------------
    #[test]
    fn set_kind_recomputes_the_style_and_is_idempotent() {
        let mut alert = Alert::create(AzString::from("m"));
        for kind in ALL_KINDS {
            alert.set_kind(kind);
            assert_eq!(alert.kind, kind);
            assert_eq!(resolved_style(&alert), build_alert_style(kind));
            // applying the same kind twice must not append/duplicate anything
            let before = resolved_style(&alert);
            alert.set_kind(kind);
            assert_eq!(
                resolved_style(&alert),
                before,
                "{kind:?}: set_kind must be idempotent"
            );
        }
        // a full cycle back to the original kind restores the original alert
        let original = Alert::create(AzString::from("m"));
        let mut cycled = original.clone();
        for kind in ALL_KINDS {
            cycled.set_kind(kind);
        }
        cycled.set_kind(AlertKind::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 alert = Alert::create(AzString::from("keep me"));
        alert.set_on_dismiss(log, dismiss_cb(dismiss_do_nothing));
        alert.alert_state.inner.visible = false;
        alert.set_kind(AlertKind::Warning);
        assert_eq!(alert.message.as_str(), "keep me");
        assert!(
            alert.dismissible,
            "set_kind must not clear the close button"
        );
        assert!(
            alert.alert_state.on_dismiss.is_some(),
            "set_kind must not drop the callback"
        );
        assert!(
            !alert.alert_state.inner.visible,
            "set_kind must not resurrect a dismissed alert"
        );
    }
    #[test]
    fn with_alert_kind_matches_set_kind_and_last_write_wins() {
        for kind in ALL_KINDS {
            let built = Alert::create(AzString::from("m")).with_alert_kind(kind);
            let mut mutated = Alert::create(AzString::from("m"));
            mutated.set_kind(kind);
            assert_eq!(built, mutated, "{kind:?}: builder and setter must agree");
        }
        let alert = Alert::create(AzString::from("m"))
            .with_alert_kind(AlertKind::Danger)
            .with_alert_kind(AlertKind::Success);
        assert_eq!(alert.kind, AlertKind::Success);
        assert_eq!(
            resolved_style(&alert),
            build_alert_style(AlertKind::Success)
        );
    }
    // ------------------------------------------------------------------
    // set_dismissible / with_dismissible
    // ------------------------------------------------------------------
    #[test]
    fn set_dismissible_last_write_wins_and_touches_nothing_else() {
        let mut alert = Alert::with_kind(AzString::from("m"), AlertKind::Warning);
        let style_before = resolved_style(&alert);
        for flag in [true, true, false, true, false, false] {
            alert.set_dismissible(flag);
            assert_eq!(alert.dismissible, flag);
        }
        assert_eq!(alert.kind, AlertKind::Warning);
        assert_eq!(alert.message.as_str(), "m");
        assert_eq!(
            resolved_style(&alert),
            style_before,
            "toggling must not restyle"
        );
        assert!(
            alert.alert_state.on_dismiss.is_none(),
            "toggling must not invent a callback"
        );
    }
    #[test]
    fn with_dismissible_toggle_sequence_ends_on_the_last_value() {
        assert!(Alert::default().with_dismissible(true).dismissible);
        assert!(!Alert::default().with_dismissible(false).dismissible);
        assert!(
            !Alert::default()
                .with_dismissible(true)
                .with_dismissible(false)
                .dismissible
        );
        assert!(
            Alert::default()
                .with_dismissible(false)
                .with_dismissible(true)
                .dismissible
        );
        // builder == setter
        let mut mutated = Alert::default();
        mutated.set_dismissible(true);
        assert_eq!(Alert::default().with_dismissible(true), mutated);
    }
    // ------------------------------------------------------------------
    // set_on_dismiss / with_on_dismiss
    // ------------------------------------------------------------------
    #[test]
    fn set_on_dismiss_implies_dismissible() {
        let mut alert = Alert::create(AzString::from("m"));
        assert!(!alert.dismissible);
        alert.set_on_dismiss(RefAny::new(1u8), dismiss_cb(dismiss_do_nothing));
        assert!(
            alert.dismissible,
            "a dismiss callback must render a close button"
        );
        assert!(alert.alert_state.on_dismiss.is_some());
        assert!(
            alert.alert_state.inner.visible,
            "wiring a callback must not hide the alert"
        );
    }
    #[test]
    fn set_on_dismiss_replaces_rather_than_appends() {
        let mut alert = Alert::create(AzString::from("m"));
        alert.set_on_dismiss(RefAny::new(1u8), dismiss_cb(dismiss_do_nothing));
        let first = alert
            .alert_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
        alert.set_on_dismiss(RefAny::new(9i64), dismiss_cb(record_dismiss));
        let second = alert
            .alert_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 alert = Alert::with_kind(AzString::from("boom"), AlertKind::Danger)
            .with_on_dismiss(RefAny::new(0u8), dismiss_cb(dismiss_do_nothing));
        assert_eq!(alert.message.as_str(), "boom");
        assert_eq!(alert.kind, AlertKind::Danger);
        assert_eq!(resolved_style(&alert), build_alert_style(AlertKind::Danger));
        assert!(alert.dismissible);
        assert!(alert.alert_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` implies
        // `dismissible = true`, but a later `set_dismissible(false)` wins and the
        // wired-up callback becomes unreachable (no close button is rendered).
        let mut alert = Alert::create(AzString::from("m"));
        alert.set_on_dismiss(RefAny::new(0u8), dismiss_cb(record_dismiss));
        alert.set_dismissible(false);
        assert!(
            alert.alert_state.on_dismiss.is_some(),
            "the callback is still stored"
        );
        let dom = alert.dom();
        assert_eq!(
            dom.children.as_ref().len(),
            1,
            "no close button is rendered, so the callback can never fire"
        );
    }
    // ------------------------------------------------------------------
    // swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_returns_the_original_and_resets_self() {
        let mut alert =
            Alert::with_kind(AzString::from("payload"), AlertKind::Danger).with_dismissible(true);
        let snapshot = alert.clone();
        let returned = alert.swap_with_default();
        assert_eq!(returned, snapshot, "the original must come back untouched");
        assert_eq!(
            alert,
            Alert::default(),
            "self must be reset to a default alert"
        );
        assert_eq!(alert.message.as_str(), "");
        assert_eq!(alert.kind, AlertKind::Info);
        assert!(!alert.dismissible);
        assert!(alert.alert_state.on_dismiss.is_none());
        assert!(alert.alert_state.inner.visible);
    }
    #[test]
    fn swap_with_default_is_stable_when_repeated() {
        let mut alert = Alert::default();
        for _ in 0..3 {
            let returned = alert.swap_with_default();
            assert_eq!(returned, Alert::default());
            assert_eq!(alert, Alert::default());
        }
    }
    #[test]
    fn swap_with_default_moves_the_callback_out_of_self() {
        let mut alert = Alert::create(AzString::from("m"))
            .with_on_dismiss(RefAny::new(7u32), dismiss_cb(record_dismiss));
        let returned = alert.swap_with_default();
        assert!(
            returned.alert_state.on_dismiss.is_some(),
            "the callback moves out"
        );
        assert!(
            alert.alert_state.on_dismiss.is_none(),
            "the reset alert must not keep a reference to the old callback"
        );
        assert!(!alert.dismissible);
    }
    // ------------------------------------------------------------------
    // Alert::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_of_a_plain_alert_is_a_container_with_one_message_child() {
        let alert = Alert::create(AzString::from("hi"));
        let style = resolved_style(&alert);
        let dom = alert.dom();
        assert!(dom.root.has_class("__azul-native-alert"));
        assert!(
            dom.root.get_callbacks().as_ref().is_empty(),
            "a non-dismissible alert 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(), 1, "no close button without `dismissible`");
        assert!(children[0].root.has_class("__azul-native-alert-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_of_a_dismissible_alert_appends_a_focusable_close_button() {
        let dom = Alert::create(AzString::from("hi"))
            .with_dismissible(true)
            .dom();
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 2, "[message, close]");
        let close = &children[1];
        assert!(close.root.has_class("__azul-native-alert-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_alert_dismiss as usize);
        assert!(matches!(&cb.callback.ctx, OptionRefAny::None));
    }
    #[test]
    fn dom_hands_the_alert_state_to_the_close_button() {
        let alert = Alert::create(AzString::from("hi"))
            .with_on_dismiss(RefAny::new(0u8), dismiss_cb(record_dismiss));
        let dom = alert.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 AlertStateWrapper"
        );
        assert!(
            payload
                .downcast_ref::<AlertStateWrapper>()
                .expect("AlertStateWrapper")
                .on_dismiss
                .is_some(),
            "the user callback must travel with the state"
        );
    }
    /// Flat index of the close button in `dismissible_styled_dom`: the tree is
    /// `0 container / 1 message <p> / 2 message text / 3 close <p> / 4 close text`
    /// in depth-first pre-order, and the callback sits on the `<p>`.
    const CLOSE_NODE: usize = 3;
    #[test]
    fn dom_is_stable_across_kinds_and_only_the_container_style_changes() {
        for kind in ALL_KINDS {
            let dom = Alert::with_kind(AzString::from("m"), kind)
                .with_dismissible(true)
                .dom();
            assert!(dom.root.has_class("__azul-native-alert"));
            assert_eq!(dom.children.as_ref().len(), 2);
            // NOTE: `AlertKind::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"
            );
        }
    }
    // ------------------------------------------------------------------
    // default_on_alert_dismiss
    // ------------------------------------------------------------------
    #[test]
    fn dismiss_hides_the_container_and_flips_visible() {
        let mut data = RefAny::new(AlertStateWrapper::default());
        // CLOSE_NODE == the close button <p>, 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(AlertStateWrapper {
            inner: AlertState { visible: true },
            on_dismiss: Some(AlertOnDismiss {
                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(AlertStateWrapper {
            inner: AlertState { visible: true },
            on_dismiss: Some(AlertOnDismiss {
                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_on_a_root_hit_node_is_a_noop() {
        // node 0 has no parent -> there is no container to hide
        let mut data = RefAny::new(AlertStateWrapper::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(AlertStateWrapper::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_without_any_layout_result_is_a_noop() {
        let mut data = RefAny::new(AlertStateWrapper::default());
        let (update, changes) = run_dismiss(None, 2, 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 alert = Alert::create(AzString::from("bye")).with_dismissible(true);
        let dom = alert.dom();
        let close = &dom.children.as_ref()[1];
        let entry = &close.root.get_callbacks().as_ref()[0];
        assert_eq!(entry.callback.cb, default_on_alert_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"
        );
    }
}