1
//! Button widget with Bootstrap-inspired type-based styling (`ButtonType`).
2

            
3
use std::vec::Vec;
4

            
5
use azul_core::{
6
    callbacks::{CoreCallbackData, Update},
7
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, NodeType, OptionDom, TabIndex},
8
    refany::RefAny,
9
    resources::{ImageRef, OptionImageRef},
10
};
11
#[allow(clippy::wildcard_imports)]
12
// widget/render module pulls in the css property/value types it builds with
13
use azul_css::{
14
    dynamic_selector::{
15
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
16
    },
17
    props::{
18
        basic::{
19
            color::ColorU,
20
            font::{StyleFontFamily, StyleFontFamilyVec},
21
            *,
22
        },
23
        layout::*,
24
        property::{CssProperty, *},
25
        style::*,
26
    },
27
    system::SystemFontType,
28
    *,
29
};
30

            
31
use crate::callbacks::{Callback, CallbackInfo};
32

            
33
/// The semantic type/role of a button.
34
///
35
/// Each type has distinct styling to indicate its purpose to the user.
36
/// Colors are based on Bootstrap's button variants for familiarity.
37
#[repr(C)]
38
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
39
pub enum ButtonType {
40
    /// Default button style - neutral/gray appearance
41
    #[default]
42
    Default,
43
    /// Primary action button - blue, uses system accent color on macOS
44
    Primary,
45
    /// Secondary button - gray, less prominent than primary
46
    Secondary,
47
    /// Success/confirmation button - green with white text
48
    Success,
49
    /// Danger/destructive button - red with white text
50
    Danger,
51
    /// Warning button - yellow with BLACK text
52
    Warning,
53
    /// Informational button - teal/cyan with white text
54
    Info,
55
    /// Link-style button - appears as a hyperlink, no background
56
    Link,
57
}
58

            
59
/// What a button type's face IS, which decides what a theme may do to it
60
/// in dark mode. The migration's rule: a page-neutral surface takes the
61
/// theme's dark tokens; a surface that is its own colour keeps it in both
62
/// modes; a light value never moves.
63
#[repr(C)]
64
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
65
pub enum ButtonSurface {
66
    /// The standard command: light grey paper, dark text. Page-neutral —
67
    /// the theme paints it in its dark face and ink.
68
    Neutral,
69
    /// A coloured command (primary, success, danger, ...): the colour is the
70
    /// meaning. The theme leaves face, text and border alone.
71
    OwnColour,
72
    /// The link button: no face at all, only text.
73
    NoSurface,
74
}
75

            
76
impl ButtonType {
77
    /// See [`ButtonSurface`].
78
    #[must_use]
79
420
    pub const fn surface(self) -> ButtonSurface {
80
420
        match self {
81
273
            Self::Default => ButtonSurface::Neutral,
82
11
            Self::Link => ButtonSurface::NoSurface,
83
            Self::Primary
84
            | Self::Secondary
85
            | Self::Success
86
            | Self::Danger
87
            | Self::Warning
88
136
            | Self::Info => ButtonSurface::OwnColour,
89
        }
90
420
    }
91

            
92
    /// Get the CSS class name for this button type
93
    #[must_use]
94
16256
    pub const fn class_name(&self) -> &'static str {
95
16256
        match self {
96
16132
            Self::Default => "__azul-btn-default",
97
25
            Self::Primary => "__azul-btn-primary",
98
16
            Self::Secondary => "__azul-btn-secondary",
99
17
            Self::Success => "__azul-btn-success",
100
16
            Self::Danger => "__azul-btn-danger",
101
16
            Self::Warning => "__azul-btn-warning",
102
17
            Self::Info => "__azul-btn-info",
103
17
            Self::Link => "__azul-btn-link",
104
        }
105
16256
    }
106
}
107

            
108
#[repr(C)]
109
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
110
pub struct Button {
111
    /// Content (image or text) of this button, centered by default
112
    pub label: AzString,
113
    /// Optional image that is displayed next to the label
114
    pub image: OptionImageRef,
115
    /// Optional leading icon name, resolved through the registered icon
116
    /// provider (e.g. the builtin Material Icons pack: "`content_copy`").
117
    /// An empty string means "no icon".
118
    pub icon: AzString,
119
    /// A ready-made DOM to use AS the leading icon, instead of resolving
120
    /// [`icon`](Self::icon) into one.
121
    ///
122
    /// The escape hatch for an icon that is not a fixed picture: a control
123
    /// whose glyph depends on live state (the window control that draws
124
    /// "maximize" or "restore") wraps itself in a `VirtualView` so it can
125
    /// re-render in place, and hands the view here. `icon` is still read for
126
    /// the ACCESSIBLE NAME, so set both: the name is what a screen reader
127
    /// announces and a view cannot supply it.
128
    pub icon_dom: OptionDom,
129
    /// Optional trailing icon name (e.g. "`arrow_drop_down`" for menu/split
130
    /// buttons). An empty string means "no trailing icon".
131
    pub trailing_icon: AzString,
132
    /// The semantic type of this button (Primary, Success, Danger, etc.)
133
    pub button_type: ButtonType,
134
    /// Style for this button container, or `None` for "no opinion" — in which
135
    /// case the style is derived from `button_type` at render time.
136
    ///
137
    /// `None` and `Some(empty)` are different answers throughout this struct:
138
    /// the first means the widget picks, the second means the caller asked for
139
    /// no properties at all and gets none.
140
    pub container_style: OptionCssPropertyWithConditionsVec,
141
    /// Style of the label, or `None` for the widget's default.
142
    pub label_style: OptionCssPropertyWithConditionsVec,
143
    /// Style of the image, or `None` for the widget's default.
144
    pub image_style: OptionCssPropertyWithConditionsVec,
145
    /// Style of the leading icon, or `None` for the widget's default.
146
    pub icon_style: OptionCssPropertyWithConditionsVec,
147
    /// Style of the trailing icon, or `None` for the widget's default.
148
    pub trailing_icon_style: OptionCssPropertyWithConditionsVec,
149
    /// Optional: Function to call when the button is clicked
150
    pub on_click: OptionButtonOnClick,
151
    pub theme: crate::widgets::themes::OptionUiTheme,
152
}
153

            
154
pub type ButtonOnClickCallbackType = extern "C" fn(RefAny, CallbackInfo) -> Update;
155
impl_widget_callback!(
156
    ButtonOnClick,
157
    OptionButtonOnClick,
158
    ButtonOnClickCallback,
159
    ButtonOnClickCallbackType
160
);
161

            
162
// Host-invoker plumbing for managed-FFI bindings — see core/src/host_invoker.rs.
163
azul_core::impl_managed_callback! {
164
    wrapper:        ButtonOnClickCallback,
165
    info_ty:        CallbackInfo,
166
    return_ty:      Update,
167
    default_ret:    Update::DoNothing,
168
    invoker_static: BUTTON_ON_CLICK_INVOKER,
169
    invoker_ty:     AzButtonOnClickCallbackInvoker,
170
    thunk_fn:       az_button_on_click_callback_thunk,
171
    setter_fn:      AzApp_setButtonOnClickCallbackInvoker,
172
    from_handle_fn: AzButtonOnClickCallback_createFromHostHandle,
173
}
174

            
175
// ButtonType-specific styling
176
// ============================================================
177

            
178
/// Get the background color for a button type
179
825
pub(crate) const fn get_button_colors(button_type: ButtonType) -> (ColorU, ColorU, ColorU) {
180
    // Returns (normal, hover, active) colors
181
825
    match button_type {
182
330
        ButtonType::Default => (
183
330
            ColorU::rgb(248, 249, 250), // Light gray
184
330
            ColorU::rgb(233, 236, 239), // Darker gray on hover
185
330
            ColorU::rgb(218, 222, 226), // Even darker on active
186
330
        ),
187
92
        ButtonType::Primary => (
188
92
            ColorU::bootstrap_primary(),
189
92
            ColorU::bootstrap_primary_hover(),
190
92
            ColorU::bootstrap_primary_active(),
191
92
        ),
192
68
        ButtonType::Secondary => (
193
68
            ColorU::bootstrap_secondary(),
194
68
            ColorU::bootstrap_secondary_hover(),
195
68
            ColorU::bootstrap_secondary_active(),
196
68
        ),
197
70
        ButtonType::Success => (
198
70
            ColorU::bootstrap_success(),
199
70
            ColorU::bootstrap_success_hover(),
200
70
            ColorU::bootstrap_success_active(),
201
70
        ),
202
69
        ButtonType::Danger => (
203
69
            ColorU::bootstrap_danger(),
204
69
            ColorU::bootstrap_danger_hover(),
205
69
            ColorU::bootstrap_danger_active(),
206
69
        ),
207
68
        ButtonType::Warning => (
208
68
            ColorU::bootstrap_warning(),
209
68
            ColorU::bootstrap_warning_hover(),
210
68
            ColorU::bootstrap_warning_active(),
211
68
        ),
212
70
        ButtonType::Info => (
213
70
            ColorU::bootstrap_info(),
214
70
            ColorU::bootstrap_info_hover(),
215
70
            ColorU::bootstrap_info_active(),
216
70
        ),
217
58
        ButtonType::Link => (
218
58
            ColorU::TRANSPARENT,
219
58
            ColorU::TRANSPARENT,
220
58
            ColorU::TRANSPARENT,
221
58
        ),
222
    }
223
825
}
224

            
225
/// Get the text color for a button type
226
606
const fn get_button_text_color(button_type: ButtonType) -> ColorU {
227
606
    match button_type {
228
192
        ButtonType::Default => ColorU::rgb(33, 37, 41), // Dark text
229
57
        ButtonType::Warning => ColorU::BLACK,           // Black text on yellow
230
57
        ButtonType::Link => ColorU::bootstrap_link(),   // Blue link color
231
300
        _ => ColorU::WHITE,                             // White text on colored buttons
232
    }
233
606
}
234

            
235
/// Build container style properties for a button type
236
567
fn build_button_container_style(button_type: ButtonType) -> Vec<CssPropertyWithConditions> {
237
    // The 2026-06-02 BISECTION PROBE used to `return` a minimal 3-property style
238
    // HERE, unconditionally — which made every branch below dead code, so all 8
239
    // button types rendered identically (no background, no border, no hover /
240
    // active / focus). It was a web-lift experiment ("Remove this `return` to
241
    // restore the real button styling") that shipped to every target and was
242
    // never reverted; Default / Primary / Danger were visually indistinguishable.
243
    //
244
    // The probe's two findings still hold for the WEB LIFT only: the container's
245
    // complex props tripped a cascade OOB, and `display: inline-flex` hits the
246
    // (deferred) taffy flex-algorithm lift gap, so block layout is the
247
    // known-good shape there. Keep that minimal style — but behind the
248
    // `web_lift` feature that actually needs it, instead of on every platform.
249
567
    if cfg!(feature = "web_lift") {
250
        return alloc::vec![
251
            CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
252
            CssPropertyWithConditions::simple(CssProperty::const_padding_top(
253
                LayoutPaddingTop::const_px(6)
254
            )),
255
            CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
256
                LayoutPaddingBottom::const_px(6)
257
            )),
258
        ];
259
567
    }
260

            
261
    // Only the RESTING colour is needed here now: the hover and pressed values
262
    // from this triple, and the focus accent, are read by the theme modules.
263
567
    let (bg_normal, _, _) = get_button_colors(button_type);
264
567
    let text_color = get_button_text_color(button_type);
265

            
266
567
    let mut props = Vec::with_capacity(40);
267

            
268
    // Basic layout - use InlineFlex so flex properties (justify-content, align-items) work
269
567
    props.push(CssPropertyWithConditions::simple(
270
567
        CssProperty::const_display(LayoutDisplay::InlineFlex),
271
    ));
272
567
    props.push(CssPropertyWithConditions::simple(
273
567
        CssProperty::const_flex_direction(LayoutFlexDirection::Row),
274
    ));
275
567
    props.push(CssPropertyWithConditions::simple(
276
567
        CssProperty::const_justify_content(LayoutJustifyContent::Center),
277
    ));
278
567
    props.push(CssPropertyWithConditions::simple(
279
567
        CssProperty::const_align_items(LayoutAlignItems::Center),
280
    ));
281
    // Prevent stretching when inside a flex column container
282
567
    props.push(CssPropertyWithConditions::simple(CssProperty::align_self(
283
567
        LayoutAlignSelf::Start,
284
    )));
285
567
    props.push(CssPropertyWithConditions::simple(
286
567
        CssProperty::const_cursor(StyleCursor::Pointer),
287
    ));
288
567
    props.push(CssPropertyWithConditions::simple(
289
567
        CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0)),
290
    ));
291

            
292
    // Text color
293
567
    props.push(CssPropertyWithConditions::simple(
294
567
        CssProperty::const_text_color(StyleTextColor { inner: text_color }),
295
    ));
296

            
297
    // Padding (Bootstrap-like)
298
567
    props.push(CssPropertyWithConditions::simple(
299
567
        CssProperty::const_padding_top(LayoutPaddingTop::const_px(6)),
300
    ));
301
567
    props.push(CssPropertyWithConditions::simple(
302
567
        CssProperty::const_padding_bottom(LayoutPaddingBottom::const_px(6)),
303
    ));
304
567
    props.push(CssPropertyWithConditions::simple(
305
567
        CssProperty::const_padding_left(LayoutPaddingLeft::const_px(12)),
306
    ));
307
567
    props.push(CssPropertyWithConditions::simple(
308
567
        CssProperty::const_padding_right(LayoutPaddingRight::const_px(12)),
309
    ));
310

            
311
    // Border radius
312
567
    props.push(CssPropertyWithConditions::simple(
313
567
        CssProperty::const_border_top_left_radius(StyleBorderTopLeftRadius::const_px(4)),
314
    ));
315
567
    props.push(CssPropertyWithConditions::simple(
316
567
        CssProperty::const_border_top_right_radius(StyleBorderTopRightRadius::const_px(4)),
317
    ));
318
567
    props.push(CssPropertyWithConditions::simple(
319
567
        CssProperty::const_border_bottom_left_radius(StyleBorderBottomLeftRadius::const_px(4)),
320
    ));
321
567
    props.push(CssPropertyWithConditions::simple(
322
567
        CssProperty::const_border_bottom_right_radius(StyleBorderBottomRightRadius::const_px(4)),
323
    ));
324

            
325
567
    if button_type == ButtonType::Link {
326
53
        // Link buttons have no background or border
327
53
        props.push(CssPropertyWithConditions::simple(
328
53
            CssProperty::const_background_content(StyleBackgroundContentVec::from_const_slice(&[
329
53
                StyleBackgroundContent::Color(ColorU::TRANSPARENT),
330
53
            ])),
331
53
        ));
332
53

            
333
53
        // The underline-on-hover lives in the theme modules with the rest of
334
53
        // this button's states — see `flat::button_states`.
335
53
    } else {
336
        // Normal background
337
514
        props.push(CssPropertyWithConditions::simple(
338
514
            CssProperty::const_background_content(StyleBackgroundContentVec::from_vec(vec![
339
514
                StyleBackgroundContent::Color(bg_normal),
340
            ])),
341
        ));
342

            
343
        // Border (subtle for Default, transparent for others to maintain size)
344
514
        let border_color = if button_type == ButtonType::Default {
345
187
            ColorU::rgb(206, 212, 218)
346
        } else {
347
327
            bg_normal
348
        };
349
514
        props.push(CssPropertyWithConditions::simple(
350
514
            CssProperty::const_border_top_width(LayoutBorderTopWidth::const_px(1)),
351
        ));
352
514
        props.push(CssPropertyWithConditions::simple(
353
514
            CssProperty::const_border_bottom_width(LayoutBorderBottomWidth::const_px(1)),
354
        ));
355
514
        props.push(CssPropertyWithConditions::simple(
356
514
            CssProperty::const_border_left_width(LayoutBorderLeftWidth::const_px(1)),
357
        ));
358
514
        props.push(CssPropertyWithConditions::simple(
359
514
            CssProperty::const_border_right_width(LayoutBorderRightWidth::const_px(1)),
360
        ));
361
514
        props.push(CssPropertyWithConditions::simple(
362
514
            CssProperty::const_border_top_style(StyleBorderTopStyle {
363
514
                inner: BorderStyle::Solid,
364
514
            }),
365
        ));
366
514
        props.push(CssPropertyWithConditions::simple(
367
514
            CssProperty::const_border_bottom_style(StyleBorderBottomStyle {
368
514
                inner: BorderStyle::Solid,
369
514
            }),
370
        ));
371
514
        props.push(CssPropertyWithConditions::simple(
372
514
            CssProperty::const_border_left_style(StyleBorderLeftStyle {
373
514
                inner: BorderStyle::Solid,
374
514
            }),
375
        ));
376
514
        props.push(CssPropertyWithConditions::simple(
377
514
            CssProperty::const_border_right_style(StyleBorderRightStyle {
378
514
                inner: BorderStyle::Solid,
379
514
            }),
380
        ));
381
514
        props.push(CssPropertyWithConditions::simple(
382
514
            CssProperty::const_border_top_color(StyleBorderTopColor {
383
514
                inner: border_color,
384
514
            }),
385
        ));
386
514
        props.push(CssPropertyWithConditions::simple(
387
514
            CssProperty::const_border_bottom_color(StyleBorderBottomColor {
388
514
                inner: border_color,
389
514
            }),
390
        ));
391
514
        props.push(CssPropertyWithConditions::simple(
392
514
            CssProperty::const_border_left_color(StyleBorderLeftColor {
393
514
                inner: border_color,
394
514
            }),
395
        ));
396
514
        props.push(CssPropertyWithConditions::simple(
397
514
            CssProperty::const_border_right_color(StyleBorderRightColor {
398
514
                inner: border_color,
399
514
            }),
400
        ));
401

            
402
        // Hover, pressed and focus are NOT here. They live in the theme
403
        // modules (`flat::button_states`, `flora::button_states`) and are
404
        // appended by `flat::button` / `flora::button`, because the dark half of
405
        // each pair needs a palette this file cannot see. Declared here they
406
        // could only ever name the light-mode colour, which is how a hovered
407
        // button came to keep its light fill on a dark surface.
408
    }
409

            
410
567
    props
411
567
}
412

            
413
/// Default style for the optional leading/trailing icon nodes: a fixed-size,
414
/// non-selectable glyph that does not flex.
415
static BUTTON_ICON_DEFAULT_STYLE: &[CssPropertyWithConditions] = &[
416
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(16))),
417
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
418
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
419
];
420

            
421
/// Build label style properties
422
16948
fn build_button_label_style() -> Vec<CssPropertyWithConditions> {
423
    // Use system UI font
424
16948
    let font_family =
425
16948
        StyleFontFamilyVec::from_vec(vec![StyleFontFamily::SystemType(SystemFontType::Ui)]);
426

            
427
16948
    vec![
428
16948
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
429
            14,
430
        ))),
431
16948
        CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Center)),
432
16948
        CssPropertyWithConditions::simple(CssProperty::const_font_family(font_family)),
433
16948
        CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
434
    ]
435
16948
}
436

            
437
impl Button {
438
    /// Create a button with `ButtonType::Default` styling.
439
    #[inline]
440
    #[must_use]
441
19270
    pub fn create(label: AzString) -> Self {
442
19270
        Self::with_type(label, ButtonType::Default)
443
19270
    }
444

            
445
    /// Create a button with a specific type (Primary, Success, Danger, etc.)
446
    #[inline]
447
    #[must_use]
448
19519
    pub fn with_type(label: AzString, button_type: ButtonType) -> Self {
449
19519
        Self {
450
19519
            label,
451
19519
            image: None.into(),
452
19519
            icon: AzString::from_const_str(""),
453
19519
            icon_dom: None.into(),
454
19519
            trailing_icon: AzString::from_const_str(""),
455
19519
            button_type,
456
19519
            on_click: None.into(),
457
19519
            container_style: OptionCssPropertyWithConditionsVec::None,
458
19519
            label_style: OptionCssPropertyWithConditionsVec::None,
459
19519
            image_style: OptionCssPropertyWithConditionsVec::None,
460
19519
            theme: crate::widgets::themes::OptionUiTheme::Some(
461
19519
                crate::widgets::themes::UiTheme::Flat,
462
19519
            ),
463
19519
            icon_style: OptionCssPropertyWithConditionsVec::None,
464
19519
            trailing_icon_style: OptionCssPropertyWithConditionsVec::None,
465
19519
        }
466
19519
    }
467

            
468
    /// The container CSS this button renders with.
469
    ///
470
    /// `None` means no opinion, so `button_type` decides — the same answer both
471
    /// themes give, asked in one place so they cannot drift. It is also why
472
    /// `set_button_type` is a plain field write: the type and the colours derived
473
    /// from it were two facts stored apart, and a caller writing the public
474
    /// `button_type` field left a Primary button painted like a Default one.
475
    #[must_use]
476
16415
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
477
16415
        self.container_style
478
16415
            .clone()
479
16415
            .into_option()
480
16415
            .unwrap_or_else(|| {
481
428
                CssPropertyWithConditionsVec::from_vec(build_button_container_style(
482
428
                    self.button_type,
483
                ))
484
428
            })
485
16415
    }
486

            
487
    /// The label CSS this button renders with.
488
    #[must_use]
489
16404
    pub fn resolved_label_style(&self) -> CssPropertyWithConditionsVec {
490
16404
        self.label_style
491
16404
            .clone()
492
16404
            .into_option()
493
16404
            .unwrap_or_else(|| CssPropertyWithConditionsVec::from_vec(build_button_label_style()))
494
16404
    }
495

            
496
    /// The image CSS this button renders with.
497
    ///
498
    /// Defaults to the label's style: an image sits where the label would and
499
    /// inherits the same box.
500
    #[must_use]
501
16301
    pub fn resolved_image_style(&self) -> CssPropertyWithConditionsVec {
502
16301
        self.image_style
503
16301
            .clone()
504
16301
            .into_option()
505
16301
            .unwrap_or_else(|| CssPropertyWithConditionsVec::from_vec(build_button_label_style()))
506
16301
    }
507

            
508
    /// The leading-icon CSS this button renders with.
509
    #[must_use]
510
16198
    pub fn resolved_icon_style(&self) -> CssPropertyWithConditionsVec {
511
16198
        self.icon_style.clone().into_option().unwrap_or_else(|| {
512
211
            CssPropertyWithConditionsVec::from_const_slice(BUTTON_ICON_DEFAULT_STYLE)
513
211
        })
514
16198
    }
515

            
516
    /// The trailing-icon CSS this button renders with.
517
    #[must_use]
518
16198
    pub fn resolved_trailing_icon_style(&self) -> CssPropertyWithConditionsVec {
519
16198
        self.trailing_icon_style
520
16198
            .clone()
521
16198
            .into_option()
522
16198
            .unwrap_or_else(|| {
523
342
                CssPropertyWithConditionsVec::from_const_slice(BUTTON_ICON_DEFAULT_STYLE)
524
342
            })
525
16198
    }
526

            
527
    /// Set the button type.
528
    ///
529
    /// Does not touch `container_style`: the type-specific colours are resolved
530
    /// from `button_type` when the DOM is built.
531
    #[inline]
532
145
    pub const fn set_button_type(&mut self, button_type: ButtonType) {
533
145
        self.button_type = button_type;
534
145
    }
535

            
536
    /// Builder method to set the button type
537
    #[inline]
538
    #[must_use]
539
35
    pub const fn with_button_type(mut self, button_type: ButtonType) -> Self {
540
35
        self.set_button_type(button_type);
541
35
        self
542
35
    }
543

            
544
    #[inline]
545
    #[must_use]
546
1002
    pub fn swap_with_default(&mut self) -> Self {
547
1002
        let mut m = Self::create(AzString::from_const_str(""));
548
1002
        core::mem::swap(&mut m, self);
549
1002
        m
550
1002
    }
551

            
552
    /// Pick the widget theme. Unset (`None`), the widget renders in the
553
    /// default theme (`crate::widgets::themes::UiTheme::default()`).
554
    pub const fn set_theme(&mut self, theme: crate::widgets::themes::UiTheme) {
555
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
556
    }
557

            
558
    /// [`Self::set_theme`] for the builder chain.
559
    #[must_use]
560
    pub const fn with_theme(mut self, theme: crate::widgets::themes::UiTheme) -> Self {
561
        self.set_theme(theme);
562
        self
563
    }
564

            
565
    #[inline]
566
9
    pub fn set_image(&mut self, image: ImageRef) {
567
9
        self.image = Some(image).into();
568
9
    }
569

            
570
    /// Sets the leading icon name (empty string clears it).
571
    #[inline]
572
    pub fn set_icon(&mut self, icon: AzString) {
573
        self.icon = icon;
574
    }
575

            
576
    /// Builder method to set the leading icon name.
577
    #[inline]
578
    #[must_use]
579
    pub fn with_icon(mut self, icon: AzString) -> Self {
580
        self.set_icon(icon);
581
        self
582
    }
583

            
584
    /// Sets the trailing icon name (empty string clears it).
585
    #[inline]
586
    pub fn set_trailing_icon(&mut self, icon: AzString) {
587
        self.trailing_icon = icon;
588
    }
589

            
590
    /// Builder method to set the trailing icon name.
591
    #[inline]
592
    #[must_use]
593
    pub fn with_trailing_icon(mut self, icon: AzString) -> Self {
594
        self.set_trailing_icon(icon);
595
        self
596
    }
597

            
598
    #[inline]
599
5
    pub fn set_on_click<C: Into<ButtonOnClickCallback>>(&mut self, data: RefAny, on_click: C) {
600
5
        self.on_click = Some(ButtonOnClick {
601
5
            refany: data,
602
5
            callback: on_click.into(),
603
5
        })
604
5
        .into();
605
5
    }
606

            
607
    #[inline]
608
    #[must_use]
609
2
    pub fn with_on_click<C: Into<ButtonOnClickCallback>>(
610
2
        mut self,
611
2
        data: RefAny,
612
2
        on_click: C,
613
2
    ) -> Self {
614
2
        self.set_on_click(data, on_click);
615
2
        self
616
2
    }
617

            
618
    #[inline]
619
    #[must_use]
620
16195
    pub fn dom(self) -> Dom {
621
        // Rendering lives in the theme modules, where the palette is in scope:
622
        // the dark-mode colours, the interactive states and (for flora) the
623
        // raised face are all appended there. This used to build its own copy of
624
        // the tree and never reach `flat::button` / `flora::button`, which left
625
        // both functions dead and the product's buttons without any of that.
626
        //
627
        // `UiTheme::default()` is Flat, and so is every other widget's fallback.
628
16195
        match self.theme.into_option() {
629
            Some(crate::widgets::themes::UiTheme::Flora) => {
630
3
                crate::widgets::themes::flora::button(self)
631
            }
632
            Some(crate::widgets::themes::UiTheme::Flat) | None => {
633
16192
                crate::widgets::themes::flat::button(self)
634
            }
635
        }
636
16195
    }
637
}
638

            
639
#[cfg(test)]
640
mod autotest_generated {
641
    use std::collections::HashSet;
642

            
643
    use azul_core::{
644
        dom::{EventFilter, HoverEventFilter},
645
        resources::RawImageFormat,
646
    };
647
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
648

            
649
    use super::*;
650
    use crate::widgets::theme_probe;
651

            
652
    // ------------------------------------------------------------------
653
    // Helpers
654
    // ------------------------------------------------------------------
655

            
656
    /// Every variant of `ButtonType` - the complete input domain of `class_name`,
657
    /// `get_button_colors`, `get_button_text_color` and `build_button_container_style`.
658
    const ALL_TYPES: [ButtonType; 8] = [
659
        ButtonType::Default,
660
        ButtonType::Primary,
661
        ButtonType::Secondary,
662
        ButtonType::Success,
663
        ButtonType::Danger,
664
        ButtonType::Warning,
665
        ButtonType::Info,
666
        ButtonType::Link,
667
    ];
668

            
669
    const WHITE: ColorU = ColorU {
670
        r: 255,
671
        g: 255,
672
        b: 255,
673
        a: 255,
674
    };
675
    const BLACK: ColorU = ColorU {
676
        r: 0,
677
        g: 0,
678
        b: 0,
679
        a: 255,
680
    };
681
    const TRANSPARENT: ColorU = ColorU {
682
        r: 0,
683
        g: 0,
684
        b: 0,
685
        a: 0,
686
    };
687
    /// The "dark text" of the Default button (Bootstrap `$gray-900`).
688
    const DARK: ColorU = ColorU {
689
        r: 33,
690
        g: 37,
691
        b: 41,
692
        a: 255,
693
    };
694

            
695
    extern "C" fn test_click(_data: RefAny, _info: CallbackInfo) -> Update {
696
        Update::DoNothing
697
    }
698

            
699
    extern "C" fn other_click(_data: RefAny, _info: CallbackInfo) -> Update {
700
        Update::RefreshDom
701
    }
702

            
703
    fn btn(label: &str, button_type: ButtonType) -> Button {
704
        Button::with_type(AzString::from(label), button_type)
705
    }
706

            
707
    /// The declared properties of a style vec, in declaration order.
708
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
709
        v.as_ref().iter().map(|p| p.property.clone()).collect()
710
    }
711

            
712
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length - an
713
    /// `em`/`%` slipping into the button geometry would resolve against the parent
714
    /// font/box instead of the intended fixed padding or font size.
715
    fn px(pv: &PixelValue) -> f32 {
716
        assert_eq!(
717
            pv.metric,
718
            SizeMetric::Px,
719
            "button geometry must be absolute px, got {:?}",
720
            pv.metric
721
        );
722
        pv.number.get()
723
    }
724

            
725
    fn padding_top_bottom_px(v: &CssPropertyWithConditionsVec) -> (Option<f32>, Option<f32>) {
726
        let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| {
727
            v.as_ref().iter().find_map(|p| f(&p.property))
728
        };
729
        (
730
            find(&|p| match p {
731
                CssProperty::PaddingTop(x) => x.get_property().map(|x| px(&x.inner)),
732
                _ => None,
733
            }),
734
            find(&|p| match p {
735
                CssProperty::PaddingBottom(x) => x.get_property().map(|x| px(&x.inner)),
736
                _ => None,
737
            }),
738
        )
739
    }
740

            
741
    fn font_size_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
742
        v.as_ref().iter().find_map(|p| match &p.property {
743
            CssProperty::FontSize(f) => f.get_property().map(|f| px(&f.inner)),
744
            _ => None,
745
        })
746
    }
747

            
748
    /// The CSS classes of a rendered node, in declaration order.
749
    fn classes(dom: &Dom) -> Vec<String> {
750
        dom.root
751
            .get_ids_and_classes()
752
            .as_ref()
753
            .iter()
754
            .filter_map(|c| match c {
755
                Class(s) => Some(s.as_str().to_string()),
756
                IdOrClass::Id(_) => None,
757
            })
758
            .collect()
759
    }
760

            
761
    /// The properties of a rendered node's *inline* style, in declaration order.
762
    fn inline_properties(dom: &Dom) -> Vec<CssProperty> {
763
        dom.root
764
            .style
765
            .iter_inline_properties()
766
            .map(|(p, _)| p.clone())
767
            .collect()
768
    }
769

            
770
    /// The label text behind the block wrapper: `<p>` wrapping one text node.
771
    fn p_label_of(dom: &Dom) -> Option<&str> {
772
        if !matches!(dom.root.get_node_type(), NodeType::P) {
773
            return None;
774
        }
775
        let inner = dom.children.as_ref();
776
        if inner.len() != 1 {
777
            return None;
778
        }
779
        text_of(&inner[0])
780
    }
781

            
782
    fn text_of(dom: &Dom) -> Option<&str> {
783
        match dom.root.get_node_type() {
784
            NodeType::Text(s) => Some(s.as_ref().as_str()),
785
            _ => None,
786
        }
787
    }
788

            
789
    /// The recursive descendant count - `Dom::estimated_total_children` is a *cached*
790
    /// value that, if too small, makes `convert_dom_into_compact_dom` under-allocate
791
    /// its arenas and panic on out-of-bounds writes.
792
    fn count_descendants(dom: &Dom) -> usize {
793
        dom.children
794
            .as_ref()
795
            .iter()
796
            .map(|c| 1 + count_descendants(c))
797
            .sum()
798
    }
799

            
800
    /// Perceived brightness (0..=255) of an sRGB colour, Rec.709 weights. Kept to
801
    /// plain `+`/`*` (no gamma expansion) so the readability assertions stay exact
802
    /// and toolchain-independent.
803
    fn luma(c: ColorU) -> f32 {
804
        0.2126 * f32::from(c.r) + 0.7152 * f32::from(c.g) + 0.0722 * f32::from(c.b)
805
    }
806

            
807
    /// Adversarial button labels: empty, whitespace, combining marks, ZWJ emoji, RTL,
808
    /// embedded NULs (`AzString` is length-based, so a NUL must not truncate), bidi
809
    /// overrides and a string far longer than any plausible button label.
810
    fn adversarial_labels() -> Vec<String> {
811
        let mut v: Vec<String> = [
812
            "",
813
            " ",
814
            "OK",
815
            "e\u{0301}",                                   // e + combining acute
816
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}", // ZWJ family emoji
817
            "\u{5E9}\u{5DC}\u{5D5}\u{5DD}",                // RTL Hebrew
818
            "\0",                                          // a single NUL
819
            "a\0b",                                        // embedded NUL
820
            "\u{FFFD}\u{202E}\u{200B}",                    // replacement char, RTL override, ZWSP
821
            "…\t\r\n",                                     // control chars in a label
822
            "__azul-btn-primary",                          // a label that looks like a class name
823
        ]
824
        .iter()
825
        .map(|s| (*s).to_string())
826
        .collect();
827
        v.push("x".repeat(100_000));
828
        v
829
    }
830

            
831
    // ------------------------------------------------------------------
832
    // ButtonType::class_name  (getter)
833
    // ------------------------------------------------------------------
834

            
835
    #[test]
836
    fn class_name_returns_the_documented_class_for_every_type() {
837
        let expected = [
838
            (ButtonType::Default, "__azul-btn-default"),
839
            (ButtonType::Primary, "__azul-btn-primary"),
840
            (ButtonType::Secondary, "__azul-btn-secondary"),
841
            (ButtonType::Success, "__azul-btn-success"),
842
            (ButtonType::Danger, "__azul-btn-danger"),
843
            (ButtonType::Warning, "__azul-btn-warning"),
844
            (ButtonType::Info, "__azul-btn-info"),
845
            (ButtonType::Link, "__azul-btn-link"),
846
        ];
847
        for (ty, class) in expected {
848
            assert_eq!(ty.class_name(), class, "{ty:?}: wrong CSS class");
849
        }
850
        assert_eq!(
851
            expected.len(),
852
            ALL_TYPES.len(),
853
            "a ButtonType variant is missing from this table"
854
        );
855
    }
856

            
857
    #[test]
858
    fn class_name_is_unique_per_type() {
859
        // Two types sharing a class make the semantic variant unstylable: the
860
        // stylesheet could not tell a Danger button from a Success one.
861
        let mut seen = HashSet::new();
862
        for ty in ALL_TYPES {
863
            assert!(
864
                seen.insert(ty.class_name()),
865
                "{ty:?}: duplicate class name {}",
866
                ty.class_name()
867
            );
868
        }
869
        assert_eq!(seen.len(), ALL_TYPES.len());
870
    }
871

            
872
    #[test]
873
    fn class_name_is_a_well_formed_css_identifier() {
874
        // A space, quote or `.` would silently split/escape into a *different*
875
        // selector once written into a stylesheet.
876
        for ty in ALL_TYPES {
877
            let c = ty.class_name();
878
            assert!(!c.is_empty(), "{ty:?}: empty class name");
879
            assert!(
880
                c.starts_with("__azul-btn-"),
881
                "{ty:?}: class {c} lost the widget prefix"
882
            );
883
            assert!(c.is_ascii(), "{ty:?}: non-ASCII class name {c}");
884
            assert!(
885
                c.chars()
886
                    .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_'),
887
                "{ty:?}: class {c} contains a character that needs CSS escaping",
888
            );
889
        }
890
    }
891

            
892
    #[test]
893
    fn class_name_is_pure_and_const_evaluable() {
894
        // Declared `const fn` returning `&'static str`: the same variant must yield
895
        // the *same* static, call after call (no per-call allocation).
896
        const DEFAULT_CLASS: &str = ButtonType::Default.class_name();
897
        const LINK_CLASS: &str = ButtonType::Link.class_name();
898
        assert_eq!(DEFAULT_CLASS, "__azul-btn-default");
899
        assert_eq!(LINK_CLASS, "__azul-btn-link");
900

            
901
        for ty in ALL_TYPES {
902
            let a = ty.class_name();
903
            let b = ty.class_name();
904
            assert_eq!(
905
                a.as_ptr(),
906
                b.as_ptr(),
907
                "{ty:?}: class_name is not returning a stable static"
908
            );
909
        }
910
    }
911

            
912
    #[test]
913
    fn class_name_of_the_default_type_matches_derived_default() {
914
        // `#[default] Default` — a reordering of the enum that moves `#[default]`
915
        // would silently restyle every `Button::create`.
916
        assert_eq!(ButtonType::default(), ButtonType::Default);
917
        assert_eq!(ButtonType::default().class_name(), "__azul-btn-default");
918
    }
919

            
920
    // ------------------------------------------------------------------
921
    // get_button_colors  (private)
922
    // ------------------------------------------------------------------
923

            
924
    #[test]
925
    fn get_button_colors_returns_the_documented_bootstrap_triples() {
926
        let expected = [
927
            (
928
                ButtonType::Default,
929
                ColorU::rgb(248, 249, 250),
930
                ColorU::rgb(233, 236, 239),
931
                ColorU::rgb(218, 222, 226),
932
            ),
933
            (
934
                ButtonType::Primary,
935
                ColorU::rgb(13, 110, 253),
936
                ColorU::rgb(11, 94, 215),
937
                ColorU::rgb(10, 88, 202),
938
            ),
939
            (
940
                ButtonType::Secondary,
941
                ColorU::rgb(108, 117, 125),
942
                ColorU::rgb(92, 99, 106),
943
                ColorU::rgb(86, 94, 100),
944
            ),
945
            (
946
                ButtonType::Success,
947
                ColorU::rgb(25, 135, 84),
948
                ColorU::rgb(21, 115, 71),
949
                ColorU::rgb(20, 108, 67),
950
            ),
951
            (
952
                ButtonType::Danger,
953
                ColorU::rgb(220, 53, 69),
954
                ColorU::rgb(187, 45, 59),
955
                ColorU::rgb(176, 42, 55),
956
            ),
957
            (
958
                ButtonType::Warning,
959
                ColorU::rgb(255, 193, 7),
960
                ColorU::rgb(255, 202, 44),
961
                ColorU::rgb(255, 205, 57),
962
            ),
963
            (
964
                ButtonType::Info,
965
                ColorU::rgb(13, 202, 240),
966
                ColorU::rgb(49, 210, 242),
967
                ColorU::rgb(61, 213, 243),
968
            ),
969
            (ButtonType::Link, TRANSPARENT, TRANSPARENT, TRANSPARENT),
970
        ];
971
        for (ty, normal, hover, active) in expected {
972
            assert_eq!(
973
                get_button_colors(ty),
974
                (normal, hover, active),
975
                "{ty:?}: wrong colour triple"
976
            );
977
        }
978
    }
979

            
980
    #[test]
981
    fn get_button_colors_is_pure() {
982
        for ty in ALL_TYPES {
983
            assert_eq!(
984
                get_button_colors(ty),
985
                get_button_colors(ty),
986
                "{ty:?}: colours are not deterministic"
987
            );
988
        }
989
    }
990

            
991
    #[test]
992
    fn get_button_colors_keeps_link_fully_transparent_and_every_other_type_opaque() {
993
        // A Link button that paints *any* background stops looking like a hyperlink;
994
        // a translucent solid button lets the page bleed through and destroys the
995
        // contrast the type was chosen for.
996
        for ty in ALL_TYPES {
997
            let (normal, hover, active) = get_button_colors(ty);
998
            if ty == ButtonType::Link {
999
                assert_eq!(
                    (normal, hover, active),
                    (TRANSPARENT, TRANSPARENT, TRANSPARENT),
                    "Link must paint nothing"
                );
            } else {
                for (state, c) in [("normal", normal), ("hover", hover), ("active", active)] {
                    assert_eq!(c.a, 255, "{ty:?}: {state} background {c:?} is not opaque");
                }
            }
        }
    }
    #[test]
    fn get_button_colors_gives_every_state_a_visible_delta() {
        // hover == normal means the button gives no feedback on mouse-over;
        // active == hover means the press is invisible.
        for ty in ALL_TYPES {
            if ty == ButtonType::Link {
                continue; // deliberately identical: a link has no background at all
            }
            let (normal, hover, active) = get_button_colors(ty);
            assert_ne!(
                normal, hover,
                "{ty:?}: hover state is indistinguishable from normal"
            );
            assert_ne!(
                hover, active,
                "{ty:?}: active state is indistinguishable from hover"
            );
            assert_ne!(
                normal, active,
                "{ty:?}: active state is indistinguishable from normal"
            );
        }
    }
    #[test]
    fn get_button_colors_gives_every_type_a_distinguishable_background() {
        // Two types that render identically make the semantic variant useless.
        let mut seen = HashSet::new();
        for ty in ALL_TYPES {
            let (normal, _, _) = get_button_colors(ty);
            assert!(
                seen.insert((normal.r, normal.g, normal.b, normal.a)),
                "{ty:?}: duplicate background {normal:?}"
            );
        }
        assert_eq!(seen.len(), ALL_TYPES.len());
    }
    // ------------------------------------------------------------------
    // get_button_text_color  (private)
    // ------------------------------------------------------------------
    #[test]
    fn get_button_text_color_returns_the_documented_colour_for_every_type() {
        let expected = [
            (ButtonType::Default, DARK),
            (ButtonType::Primary, WHITE),
            (ButtonType::Secondary, WHITE),
            (ButtonType::Success, WHITE),
            (ButtonType::Danger, WHITE),
            (ButtonType::Warning, BLACK), // doc: "Warning button - yellow with BLACK text"
            (ButtonType::Info, WHITE),
            (ButtonType::Link, ColorU::rgb(13, 110, 253)),
        ];
        for (ty, text) in expected {
            assert_eq!(get_button_text_color(ty), text, "{ty:?}: wrong text colour");
        }
        // The `_ => WHITE` catch-all is easy to widen by accident: only these three
        // variants may deviate from white.
        for ty in ALL_TYPES {
            let is_special = matches!(
                ty,
                ButtonType::Default | ButtonType::Warning | ButtonType::Link
            );
            assert_eq!(
                get_button_text_color(ty) != WHITE,
                is_special,
                "{ty:?}: text colour contradicts the documented variant"
            );
        }
    }
    #[test]
    fn get_button_text_color_is_pure_and_opaque() {
        for ty in ALL_TYPES {
            let c = get_button_text_color(ty);
            assert_eq!(
                c,
                get_button_text_color(ty),
                "{ty:?}: text colour is not deterministic"
            );
            assert_eq!(
                c.a, 255,
                "{ty:?}: invisible (translucent) text colour {c:?}"
            );
        }
    }
    #[test]
    fn get_button_text_color_stays_readable_on_its_own_background() {
        // The one real invariant of the pair: label must be legible on the fill.
        // NOTE: `Info` (white on #0dcaf0) is by far the weakest pairing at ~90 luma
        // of separation — Bootstrap and azul's own `Badge` widget both put *dark*
        // text on Info. The bound below is the current floor, not an endorsement;
        // moving Info to dark text raises its separation to ~128 and still passes.
        for ty in ALL_TYPES {
            if ty == ButtonType::Link {
                continue; // no fill: a link is drawn on the page background
            }
            let (bg, _, _) = get_button_colors(ty);
            let text = get_button_text_color(ty);
            let separation = (luma(bg) - luma(text)).abs();
            assert!(
                separation >= 85.0,
                "{ty:?}: text {text:?} on {bg:?} is unreadable (luma separation {separation:.1})"
            );
            // ... and the *more* readable of the two candidates was chosen.
            let alt = if text == WHITE { DARK } else { WHITE };
            let alt_separation = (luma(bg) - luma(alt)).abs();
            if ty != ButtonType::Info {
                assert!(
                    separation >= alt_separation,
                    "{ty:?}: {alt:?} would be more readable than {text:?} on {bg:?}"
                );
            }
        }
    }
    // ------------------------------------------------------------------
    // build_button_container_style  (private)
    // ------------------------------------------------------------------
    #[test]
    fn build_button_container_style_never_panics_and_is_pure() {
        for ty in ALL_TYPES {
            let a = build_button_container_style(ty);
            let b = build_button_container_style(ty);
            assert!(
                !a.is_empty(),
                "{ty:?}: a button with no container style is invisible"
            );
            assert_eq!(a, b, "{ty:?}: container style is not deterministic");
        }
    }
    #[test]
    fn build_button_container_style_always_declares_display_and_symmetric_vertical_padding() {
        // Without a `display` the button falls back to the UA default; asymmetric
        // vertical padding makes the label sit off-centre.
        for ty in ALL_TYPES {
            let v = CssPropertyWithConditionsVec::from_vec(build_button_container_style(ty));
            assert!(
                v.as_ref()
                    .iter()
                    .any(|p| matches!(p.property, CssProperty::Display(_))),
                "{ty:?}: container declares no `display`",
            );
            let (top, bottom) = padding_top_bottom_px(&v);
            assert_eq!(top, Some(6.0), "{ty:?}: wrong padding-top");
            assert_eq!(bottom, Some(6.0), "{ty:?}: wrong padding-bottom");
            assert_eq!(
                top, bottom,
                "{ty:?}: vertical padding is asymmetric — the label will not be centred"
            );
        }
    }
    /// Every button type must be VISUALLY DISTINGUISHABLE.
    ///
    /// Replaces the 2026-06-02 characterisation test that pinned the opposite:
    /// a bisection probe `return`ed a 3-property minimal style before any of the
    /// type-dependent styling ran, so Default / Primary / Danger rendered
    /// identically on every platform for months. The probe now applies only
    /// under the `web_lift` feature that needed it (see
    /// `build_button_container_style`), and this test is the guard that it never
    /// escapes again.
    #[test]
    fn build_button_container_style_gives_each_type_its_own_look() {
        // The probe shape is what web_lift deliberately keeps; there the
        // distinction genuinely does not exist, so assert the native contract.
        if cfg!(feature = "web_lift") {
            return;
        }
        fn background_of(v: &CssPropertyWithConditionsVec) -> Option<StyleBackgroundContentVec> {
            v.as_ref().iter().find_map(|p| match &p.property {
                CssProperty::BackgroundContent(b) if p.apply_if.as_ref().is_empty() => {
                    b.get_property().cloned()
                }
                _ => None,
            })
        }
        // A background and a text colour exist at all — the probe emitted neither.
        for ty in ALL_TYPES {
            let v = CssPropertyWithConditionsVec::from_vec(build_button_container_style(ty));
            assert!(
                v.as_ref()
                    .iter()
                    .any(|p| matches!(p.property, CssProperty::TextColor(_))),
                "{ty:?}: no text colour — is the bisection probe back?",
            );
            // The conditionals are no longer HERE: hover, pressed and focus moved
            // to the theme modules, which is where the dark half of each pair can
            // be written. What this half of the guard still checks is that the
            // base style did not quietly acquire some other conditional rule.
            assert!(
                v.as_ref().iter().all(|p| p.apply_if.as_ref().is_empty()),
                "{ty:?}: the base style declares a conditional property; states belong in the \
                 theme modules",
            );
            // ...and the guard's real subject — that SOMETHING reacts to the
            // pointer — is asked of the rendered button, where the theme has
            // appended its states.
            let rendered = Button::with_type(AzString::from_const_str("x"), ty).dom();
            assert!(
                rendered
                    .root
                    .style
                    .iter_inline_properties()
                    .any(|(_, conds)| !conds.as_ref().is_empty()),
                "{ty:?}: the rendered button has no conditional properties at all, so it gives no \
                 feedback on hover, press or focus",
            );
        }
        // The three the user sees side by side must not collide.
        let default_bg = background_of(&CssPropertyWithConditionsVec::from_vec(
            build_button_container_style(ButtonType::Default),
        ));
        let primary_bg = background_of(&CssPropertyWithConditionsVec::from_vec(
            build_button_container_style(ButtonType::Primary),
        ));
        let danger_bg = background_of(&CssPropertyWithConditionsVec::from_vec(
            build_button_container_style(ButtonType::Danger),
        ));
        assert!(default_bg.is_some(), "Default has no background");
        assert_ne!(default_bg, primary_bg, "Default and Primary look identical");
        assert_ne!(default_bg, danger_bg, "Default and Danger look identical");
        assert_ne!(primary_bg, danger_bg, "Primary and Danger look identical");
    }
    // ------------------------------------------------------------------
    // build_button_label_style  (private)
    // ------------------------------------------------------------------
    #[test]
    fn build_button_label_style_declares_the_four_documented_properties_unconditionally() {
        let v = CssPropertyWithConditionsVec::from_vec(build_button_label_style());
        assert_eq!(
            v.len(),
            4,
            "label style gained/lost a property: {:?}",
            properties(&v)
        );
        assert_eq!(font_size_px(&v), Some(14.0), "wrong label font size");
        let align = v.as_ref().iter().find_map(|p| match &p.property {
            CssProperty::TextAlign(t) => t.get_property().copied(),
            _ => None,
        });
        assert_eq!(
            align,
            Some(StyleTextAlign::Center),
            "a button label must be centred"
        );
        let family = v.as_ref().iter().find_map(|p| match &p.property {
            CssProperty::FontFamily(f) => f.get_property().cloned(),
            _ => None,
        });
        let family = family.expect("label style declares no font-family");
        assert_eq!(
            family.as_ref(),
            [StyleFontFamily::SystemType(SystemFontType::Ui)].as_slice(),
            "the label must use the system UI font",
        );
        let user_select = v.as_ref().iter().find_map(|p| match &p.property {
            CssProperty::UserSelect(u) => u.get_property().copied(),
            _ => None,
        });
        assert_eq!(
            user_select,
            Some(StyleUserSelect::None),
            "a button label must not be text-selectable"
        );
        // Every declaration is unconditional — a stray `:hover` here would make the
        // label font/size flicker on mouse-over.
        assert!(
            v.as_ref().iter().all(|p| p.apply_if.as_ref().is_empty()),
            "label style must be unconditional"
        );
    }
    #[test]
    fn build_button_label_style_is_pure() {
        assert_eq!(
            build_button_label_style(),
            build_button_label_style(),
            "label style is not deterministic"
        );
    }
    // ------------------------------------------------------------------
    // Button::create / Button::with_type  (constructors)
    // ------------------------------------------------------------------
    #[test]
    fn create_is_exactly_with_type_default() {
        for label in adversarial_labels() {
            let a = Button::create(AzString::from(label.as_str()));
            let b = Button::with_type(AzString::from(label.as_str()), ButtonType::Default);
            assert_eq!(
                a,
                b,
                "create() diverged from with_type(_, Default) for a {}-byte label",
                label.len()
            );
            assert_eq!(a.button_type, ButtonType::Default);
        }
    }
    #[test]
    fn with_type_holds_its_post_construction_invariants_for_every_type() {
        for ty in ALL_TYPES {
            for label in adversarial_labels() {
                let b = btn(&label, ty);
                // Fields match the arguments, byte for byte (a NUL must not truncate).
                assert_eq!(
                    b.label.as_str(),
                    label.as_str(),
                    "{ty:?}: label was mangled"
                );
                assert_eq!(
                    b.label.as_str().len(),
                    label.len(),
                    "{ty:?}: label length changed"
                );
                assert_eq!(
                    b.button_type, ty,
                    "{ty:?}: button_type field does not match the argument"
                );
                // Optionals start empty.
                assert!(
                    b.image.is_none(),
                    "{ty:?}: a freshly built button must have no image"
                );
                assert!(
                    b.on_click.is_none(),
                    "{ty:?}: a freshly built button must have no callback"
                );
                // Styles are the ones the builders produce, and the vec lengths are
                // consistent with what was handed to `from_vec`.
                let container = build_button_container_style(ty);
                let label_style = build_button_label_style();
                assert_eq!(
                    b.resolved_container_style().len(),
                    container.len(),
                    "{ty:?}: container_style length is inconsistent"
                );
                assert_eq!(
                    b.resolved_container_style().as_ref(),
                    container.as_slice(),
                    "{ty:?}: container_style does not match the builder"
                );
                assert_eq!(
                    b.resolved_label_style().as_ref(),
                    label_style.as_slice(),
                    "{ty:?}: label_style does not match the builder"
                );
                // `with_type` deliberately reuses the label style for the image.
                assert_eq!(
                    b.resolved_image_style().as_ref(),
                    b.resolved_label_style().as_ref(),
                    "{ty:?}: image_style diverged from label_style"
                );
            }
        }
    }
    #[test]
    fn with_type_survives_a_multi_megabyte_label() {
        // 4 MiB of label: no quadratic copy, no truncation, no panic.
        let huge = "\u{1F600}".repeat(1_000_000); // 4 bytes/char
        let b = btn(&huge, ButtonType::Danger);
        assert_eq!(b.label.as_str().len(), 4_000_000);
        assert_eq!(b.label.as_str(), huge.as_str());
    }
    #[test]
    fn buttons_are_cloneable_and_clones_compare_equal() {
        for ty in ALL_TYPES {
            let b = btn("Clone me", ty);
            let c = b.clone();
            assert_eq!(b, c, "{ty:?}: clone() produced a different button");
            assert_eq!(
                format!("{b:?}"),
                format!("{c:?}"),
                "{ty:?}: Debug output diverged between clones"
            );
        }
    }
    // ------------------------------------------------------------------
    // Button::set_button_type / with_button_type
    // ------------------------------------------------------------------
    #[test]
    fn set_button_type_updates_both_the_field_and_the_container_style() {
        let mut b = btn("Save", ButtonType::Default);
        for ty in ALL_TYPES {
            b.set_button_type(ty);
            assert_eq!(b.button_type, ty, "{ty:?}: field not updated");
            assert_eq!(
                b.resolved_container_style().as_ref(),
                build_button_container_style(ty).as_slice(),
                "{ty:?}: container_style was not rebuilt for the new type",
            );
        }
    }
    #[test]
    fn set_button_type_is_idempotent_and_never_accumulates_style() {
        // Re-setting the same type must *replace*, never append: an appending
        // implementation would grow the style vec without bound.
        let mut b = btn("Save", ButtonType::Primary);
        let len = b.resolved_container_style().len();
        for _ in 0..100 {
            b.set_button_type(ButtonType::Primary);
        }
        assert_eq!(
            b.resolved_container_style().len(),
            len,
            "container_style grew across repeated set_button_type calls"
        );
        assert_eq!(
            b,
            btn("Save", ButtonType::Primary),
            "set_button_type(same) is not idempotent"
        );
    }
    #[test]
    fn set_button_type_leaves_the_label_and_the_other_styles_untouched() {
        let mut b = btn("Delete", ButtonType::Default);
        let label_style = b.resolved_label_style().clone();
        let image_style = b.resolved_image_style().clone();
        b.set_button_type(ButtonType::Danger);
        assert_eq!(
            b.label.as_str(),
            "Delete",
            "set_button_type clobbered the label"
        );
        assert_eq!(
            b.resolved_label_style(),
            label_style,
            "set_button_type clobbered label_style"
        );
        assert_eq!(
            b.resolved_image_style(),
            image_style,
            "set_button_type clobbered image_style"
        );
    }
    #[test]
    fn with_button_type_round_trips_to_with_type() {
        // create(l).with_button_type(t) must be indistinguishable from with_type(l, t).
        for ty in ALL_TYPES {
            for label in ["", "OK", "\u{1F600}\0"] {
                let built = Button::create(AzString::from(label)).with_button_type(ty);
                let direct = Button::with_type(AzString::from(label), ty);
                assert_eq!(
                    built, direct,
                    "{ty:?}: builder path diverged from with_type for {label:?}"
                );
            }
        }
    }
    #[test]
    fn with_button_type_chains_take_the_last_type() {
        let b = btn("x", ButtonType::Default)
            .with_button_type(ButtonType::Primary)
            .with_button_type(ButtonType::Link)
            .with_button_type(ButtonType::Warning);
        assert_eq!(b.button_type, ButtonType::Warning);
        assert_eq!(b, btn("x", ButtonType::Warning));
    }
    // ------------------------------------------------------------------
    // Button::swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_returns_the_original_and_leaves_a_default_button_behind() {
        let mut b = btn("Delete", ButtonType::Danger);
        b.set_image(ImageRef::null_image(
            1,
            1,
            RawImageFormat::RGBA8,
            Vec::new(),
        ));
        b.set_on_click(RefAny::new(7u32), test_click as ButtonOnClickCallbackType);
        let taken = b.swap_with_default();
        // The returned value is the old button, whole.
        assert_eq!(taken.label.as_str(), "Delete");
        assert_eq!(taken.button_type, ButtonType::Danger);
        assert!(
            taken.image.is_some(),
            "the image did not travel with the swapped-out button"
        );
        assert!(
            taken.on_click.is_some(),
            "the callback did not travel with the swapped-out button"
        );
        // ... and what is left behind is a pristine empty Default button.
        assert_eq!(b.label.as_str(), "");
        assert_eq!(b.button_type, ButtonType::Default);
        assert!(
            b.image.is_none(),
            "the swapped-in default still carries an image"
        );
        assert!(
            b.on_click.is_none(),
            "the swapped-in default still carries a callback"
        );
        assert_eq!(
            b,
            Button::create(AzString::from("")),
            "swap_with_default left a non-default button"
        );
    }
    #[test]
    fn swap_with_default_is_stable_under_repetition() {
        // Repeated swapping must not double-free or drift: after the first call the
        // button is already default, so every further call is a no-op swap.
        let mut b = btn("x", ButtonType::Info);
        let first = b.swap_with_default();
        assert_eq!(first.label.as_str(), "x");
        for _ in 0..1000 {
            let taken = b.swap_with_default();
            assert_eq!(taken, Button::create(AzString::from("")));
            assert_eq!(b, Button::create(AzString::from("")));
        }
    }
    // ------------------------------------------------------------------
    // Button::set_image
    // ------------------------------------------------------------------
    #[test]
    fn set_image_stores_the_image_and_replaces_a_previous_one() {
        let mut b = btn("With icon", ButtonType::Primary);
        assert!(b.image.is_none());
        b.set_image(ImageRef::null_image(
            16,
            16,
            RawImageFormat::RGBA8,
            Vec::new(),
        ));
        assert!(b.image.is_some(), "set_image did not store the image");
        let first_id = b
            .image
            .as_ref()
            .map(|i| i.id)
            .expect("image must be present");
        b.set_image(ImageRef::null_image(
            32,
            32,
            RawImageFormat::RGB8,
            Vec::new(),
        ));
        let second_id = b
            .image
            .as_ref()
            .map(|i| i.id)
            .expect("image must be present");
        assert_ne!(
            first_id, second_id,
            "set_image did not replace the previous image"
        );
    }
    #[test]
    fn set_image_accepts_degenerate_and_extreme_dimensions() {
        // A null image carries only its metadata, so these must not allocate,
        // overflow (`w * h * bpp`) or panic.
        let extremes = [
            (0usize, 0usize),
            (0, 4096),
            (4096, 0),
            (1, usize::MAX),
            (usize::MAX, usize::MAX),
        ];
        for (w, h) in extremes {
            let mut b = btn("x", ButtonType::Default);
            b.set_image(ImageRef::null_image(
                w,
                h,
                RawImageFormat::RGBA8,
                Vec::new(),
            ));
            assert!(b.image.is_some(), "{w}x{h}: image was dropped");
            let dom = b.dom();
            assert_eq!(
                dom.children.as_ref().len(),
                2,
                "{w}x{h}: expected an image child and a label child"
            );
        }
    }
    // ------------------------------------------------------------------
    // Button::set_on_click / with_on_click
    // ------------------------------------------------------------------
    #[test]
    fn set_on_click_stores_the_callback_and_replaces_a_previous_one() {
        let mut b = btn("Click", ButtonType::Primary);
        assert!(b.on_click.is_none());
        b.set_on_click(RefAny::new(1u32), test_click as ButtonOnClickCallbackType);
        assert!(
            b.on_click.is_some(),
            "set_on_click did not store the callback"
        );
        b.set_on_click(RefAny::new(2u32), other_click as ButtonOnClickCallbackType);
        let stored = b.on_click.as_ref().expect("callback must be present");
        assert_eq!(
            stored.callback.cb as *const () as usize,
            other_click as ButtonOnClickCallbackType as *const () as usize,
            "the second set_on_click did not replace the first",
        );
        // ... and it replaced rather than accumulated: the DOM still fires once.
        let dom = b.dom();
        assert_eq!(
            dom.root.callbacks.as_ref().len(),
            1,
            "a re-set callback was appended instead of replaced"
        );
    }
    #[test]
    fn with_on_click_round_trips_the_function_pointer_and_the_payload_into_the_dom() {
        let cb: ButtonOnClickCallbackType = test_click;
        let expected_ptr = cb as *const () as usize;
        let dom = btn("Click", ButtonType::Success)
            .with_on_click(RefAny::new(0xDEAD_BEEF_u32), cb)
            .dom();
        let callbacks = dom.root.callbacks.as_ref();
        assert_eq!(callbacks.len(), 1, "exactly one click callback is expected");
        assert_eq!(
            callbacks[0].event,
            EventFilter::Hover(HoverEventFilter::Click),
            "the button must fire on mouse-up, not on any other filter",
        );
        assert_eq!(
            callbacks[0].callback.cb, expected_ptr,
            "the fn pointer was corrupted on the way into the DOM"
        );
        // The RefAny payload survives the move into the DOM (shared, not copied).
        let mut data = callbacks[0].refany.clone();
        assert_eq!(
            *data.downcast_ref::<u32>().expect("payload changed type"),
            0xDEAD_BEEF,
            "payload was corrupted"
        );
        assert!(
            data.downcast_ref::<u64>().is_none(),
            "downcast to the wrong type must fail, not reinterpret"
        );
    }
    #[test]
    fn with_on_click_accepts_a_generic_callback_without_mangling_the_pointer() {
        // The `From<Callback>` arm transmutes the fn pointer — this is the FFI path
        // (Python/C) into the same slot, so the pointer must come out untouched.
        let generic = Callback {
            cb: test_click,
            ctx: azul_core::refany::OptionRefAny::None,
        };
        let raw: ButtonOnClickCallbackType = test_click;
        let expected_ptr = raw as *const () as usize;
        let dom = btn("Click", ButtonType::Info)
            .with_on_click(RefAny::new(1u8), generic)
            .dom();
        let callbacks = dom.root.callbacks.as_ref();
        assert_eq!(callbacks.len(), 1);
        assert_eq!(
            callbacks[0].callback.cb, expected_ptr,
            "the Callback -> ButtonOnClickCallback transmute mangled the pointer"
        );
    }
    #[test]
    fn a_button_without_a_callback_registers_no_callbacks() {
        for ty in ALL_TYPES {
            let dom = btn("Inert", ty).dom();
            assert!(
                dom.root.callbacks.as_ref().is_empty(),
                "{ty:?}: a callback appeared out of nowhere"
            );
        }
    }
    // ------------------------------------------------------------------
    // Button::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_builds_a_focusable_button_node_with_the_base_and_type_class() {
        for ty in ALL_TYPES {
            let dom = btn("OK", ty).dom();
            assert!(
                matches!(dom.root.get_node_type(), NodeType::Button),
                "{ty:?}: root is not a Button node"
            );
            assert_eq!(
                dom.root.flags.get_tab_index(),
                Some(TabIndex::Auto),
                "{ty:?}: the button is not keyboard-focusable",
            );
            assert_eq!(
                classes(&dom),
                vec![
                    "__azul-native-button".to_string(),
                    ty.class_name().to_string(),
                    // The theme marker the render path adds — `Button::dom` renders through
                    // `flat::button` / `flora::button`, which tag the node with their theme.
                    "__azul-theme-flat".to_string(),
                ],
                "{ty:?}: wrong classes (base class first, then the type class)",
            );
            assert!(
                !dom.root.style.is_empty(),
                "{ty:?}: the container style did not reach the node"
            );
        }
    }
    /// `ButtonType::surface` decides what the theme may do in dark mode: the
    /// neutral (Default) face takes the theme's dark face; a coloured command
    /// keeps its own colour — no dark background twin at all — and the link
    /// has no face. A blue primary button on a dark window stays blue.
    #[test]
    fn only_the_neutral_surface_takes_a_dark_face() {
        use azul_css::props::property::CssPropertyType;
        // RESTING dark twins only — `[Theme(Dark)]` and nothing else. The
        // hover/pressed twins from `button_states` carry a pseudo-state too,
        // and a coloured command legitimately has those (in its own colour).
        let dark_backgrounds = |ty: ButtonType| {
            use azul_css::dynamic_selector::{DynamicSelector, ThemeCondition};
            btn("OK", ty)
                .dom()
                .root
                .style
                .iter_inline_properties()
                .filter(|(p, c)| {
                    p.get_type() == CssPropertyType::BackgroundContent
                        && !c.as_ref().is_empty()
                        && c.as_ref()
                            .iter()
                            .all(|s| matches!(s, DynamicSelector::Theme(ThemeCondition::Dark)))
                })
                .count()
        };
        assert!(
            dark_backgrounds(ButtonType::Default) >= 1,
            "the neutral face takes the theme's dark face"
        );
        for ty in [
            ButtonType::Primary,
            ButtonType::Secondary,
            ButtonType::Success,
            ButtonType::Danger,
            ButtonType::Warning,
            ButtonType::Info,
        ] {
            assert_eq!(ty.surface(), ButtonSurface::OwnColour);
            assert_eq!(
                dark_backgrounds(ty),
                0,
                "{ty:?}: a coloured command keeps its colour in dark mode"
            );
        }
        assert_eq!(ButtonType::Link.surface(), ButtonSurface::NoSurface);
        assert_eq!(ButtonType::Default.surface(), ButtonSurface::Neutral);
    }
    #[test]
    fn dom_carries_the_container_style_on_the_root_and_the_label_style_on_the_child() {
        for ty in ALL_TYPES {
            let b = btn("OK", ty);
            let container = properties(&b.resolved_container_style());
            let label_style = properties(&b.resolved_label_style());
            let dom = b.dom();
            // Only the RESTING declarations: the theme appends hover, pressed
            // and focus rules on top of the container style, and those are not
            // part of what the widget declared.
            assert_eq!(
                theme_probe::unconditional(&dom),
                container,
                "{ty:?}: the root inline style is not the container style"
            );
            let children = dom.children.as_ref();
            assert_eq!(
                children.len(),
                1,
                "{ty:?}: an image-less button is a Button node with exactly one <p> label child"
            );
            assert_eq!(
                p_label_of(&children[0]),
                Some("OK"),
                "{ty:?}: the label was mangled"
            );
            assert_eq!(
                inline_properties(&children[0]),
                label_style,
                "{ty:?}: the label style is not on the label node"
            );
        }
    }
    #[test]
    fn dom_puts_the_image_before_the_label_and_keeps_the_child_count_cache_honest() {
        let mut b = btn("Save", ButtonType::Primary);
        b.set_image(ImageRef::null_image(
            16,
            16,
            RawImageFormat::RGBA8,
            Vec::new(),
        ));
        let image_style = properties(&b.resolved_image_style());
        let dom = b.dom();
        let children = dom.children.as_ref();
        assert_eq!(
            children.len(),
            2,
            "an image button renders the image and the label"
        );
        assert!(
            matches!(children[0].root.get_node_type(), NodeType::Image(_)),
            "the image must come first (left of the label)"
        );
        assert_eq!(
            p_label_of(&children[1]),
            Some("Save"),
            "the label must be the second child"
        );
        assert_eq!(
            inline_properties(&children[0]),
            image_style,
            "the image style is not on the image node"
        );
        // `estimated_total_children` is a cache that, if wrong, makes the compact-DOM
        // conversion under-allocate its arenas and write out of bounds.
        assert_eq!(
            dom.estimated_total_children,
            count_descendants(&dom),
            "estimated_total_children is out of sync with the real subtree",
        );
    }
    #[test]
    fn dom_child_count_cache_is_honest_without_an_image_too() {
        for ty in ALL_TYPES {
            let dom = btn("x", ty).dom();
            assert_eq!(
                dom.estimated_total_children,
                count_descendants(&dom),
                "{ty:?}: stale estimated_total_children"
            );
            assert_eq!(
                dom.estimated_total_children, 2,
                "{ty:?}: an image-less button has the <p> label and its text node"
            );
        }
    }
    #[test]
    fn dom_preserves_adversarial_labels_verbatim() {
        for label in adversarial_labels() {
            let dom = btn(&label, ButtonType::Default).dom();
            let children = dom.children.as_ref();
            assert_eq!(children.len(), 1);
            let text =
                p_label_of(&children[0]).expect("the label child is not a <p>-wrapped text node");
            assert_eq!(
                text,
                label.as_str(),
                "a {}-byte label was mangled",
                label.len()
            );
            assert_eq!(
                text.len(),
                label.len(),
                "a NUL or a wide char truncated the label"
            );
        }
    }
    #[test]
    fn dom_of_a_button_whose_label_looks_like_a_class_name_does_not_leak_into_the_classes() {
        // The label is user data — it must never be able to add a CSS class.
        let dom = btn("__azul-btn-danger", ButtonType::Primary).dom();
        assert_eq!(
            classes(&dom),
            vec![
                "__azul-native-button".to_string(),
                "__azul-btn-primary".to_string(),
                // The theme marker the render path adds — `Button::dom` renders through
                // `flat::button` / `flora::button`, which tag the node with their theme.
                "__azul-theme-flat".to_string(),
            ],
            "the label leaked into the class list",
        );
    }
    #[test]
    fn dom_renders_the_type_the_button_was_last_set_to() {
        for ty in ALL_TYPES {
            let dom = btn("x", ButtonType::Default).with_button_type(ty).dom();
            assert!(
                classes(&dom).contains(&ty.class_name().to_string()),
                "{ty:?}: the DOM still carries the old type class",
            );
        }
    }
    #[test]
    fn dom_is_deterministic_across_identical_buttons() {
        // Same inputs, same tree: the node type, classes and inline styles must all
        // be reproducible (only the ImageRef/RefAny identities may differ).
        for ty in ALL_TYPES {
            let a = btn("Same", ty).dom();
            let b = btn("Same", ty).dom();
            assert_eq!(
                a.root.get_node_type(),
                b.root.get_node_type(),
                "{ty:?}: node type differs"
            );
            assert_eq!(classes(&a), classes(&b), "{ty:?}: classes differ");
            assert_eq!(
                inline_properties(&a),
                inline_properties(&b),
                "{ty:?}: inline style differs"
            );
            assert_eq!(
                a.children.as_ref().len(),
                b.children.as_ref().len(),
                "{ty:?}: child count differs"
            );
        }
    }
}