1
//! Card widget — an elevated, bordered content container with rounded corners,
2
//! a soft drop shadow and padding, holding arbitrary child content. A near-clone
3
//! of [`crate::widgets::frame::Frame`] (a container) but without the fieldset
4
//! title/header — just a single styled box wrapping the body content.
5
//!
6
//! Key types: [`Card`], [`CardOnClick`].
7

            
8
use azul_core::{
9
    callbacks::Update,
10
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec},
11
    refany::RefAny,
12
};
13
use azul_css::{
14
    css::BoxOrStatic,
15
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
16
    impl_option_inner,
17
    props::{
18
        basic::{ColorU, FloatValue, PixelValue, PixelValueNoPercent},
19
        layout::{
20
            LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow, LayoutPaddingBottom,
21
            LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop,
22
        },
23
        property::{CssProperty, LayoutFlexGrowValue, StyleBoxShadowValue},
24
        style::{
25
            BorderStyle, BoxShadowClipMode, LayoutBorderBottomWidth, LayoutBorderLeftWidth,
26
            LayoutBorderRightWidth, LayoutBorderTopWidth, StyleBackgroundContent,
27
            StyleBackgroundContentVec, StyleBorderBottomColor, StyleBorderBottomLeftRadius,
28
            StyleBorderBottomRightRadius, StyleBorderBottomStyle, StyleBorderLeftColor,
29
            StyleBorderLeftStyle, StyleBorderRightColor, StyleBorderRightStyle,
30
            StyleBorderTopColor, StyleBorderTopLeftRadius, StyleBorderTopRightRadius,
31
            StyleBorderTopStyle, StyleBoxShadow,
32
        },
33
    },
34
    AzString,
35
};
36

            
37
use crate::callbacks::CallbackInfo;
38

            
39
/// Card border colour (#dee2e6).
40
const CARD_BORDER_COLOR: ColorU = ColorU {
41
    r: 222,
42
    g: 226,
43
    b: 230,
44
    a: 255,
45
};
46
/// Card background colour (white).
47
const CARD_BG_COLOR: ColorU = ColorU {
48
    r: 255,
49
    g: 255,
50
    b: 255,
51
    a: 255,
52
};
53
/// Soft drop-shadow colour (black @ ~15% alpha).
54
const CARD_SHADOW_COLOR: ColorU = ColorU {
55
    r: 0,
56
    g: 0,
57
    b: 0,
58
    a: 38,
59
};
60

            
61
const CARD_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(CARD_BG_COLOR)];
62
const CARD_BG: StyleBackgroundContentVec =
63
    StyleBackgroundContentVec::from_const_slice(CARD_BG_ITEMS);
64

            
65
/// Shared drop-shadow descriptor referenced by all four edge box-shadows.
66
static CARD_SHADOW: StyleBoxShadow = StyleBoxShadow {
67
    offset_x: PixelValueNoPercent {
68
        inner: PixelValue::const_px(0),
69
    },
70
    offset_y: PixelValueNoPercent {
71
        inner: PixelValue::const_px(2),
72
    },
73
    blur_radius: PixelValueNoPercent {
74
        inner: PixelValue::const_px(6),
75
    },
76
    spread_radius: PixelValueNoPercent {
77
        inner: PixelValue::const_px(0),
78
    },
79
    clip_mode: BoxShadowClipMode::Outset,
80
    color: CARD_SHADOW_COLOR,
81
};
82

            
83
const CARD_STYLE: &[CssPropertyWithConditions] = &[
84
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
85
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
86
        LayoutFlexDirection::Column,
87
    )),
88
    CssPropertyWithConditions::simple(CssProperty::const_background_content(CARD_BG)),
89
    // padding: 12px
90
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
91
        12,
92
    ))),
93
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
94
        LayoutPaddingBottom::const_px(12),
95
    )),
96
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
97
        LayoutPaddingLeft::const_px(12),
98
    )),
99
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
100
        LayoutPaddingRight::const_px(12),
101
    )),
102
    // border: 1px solid #dee2e6
103
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
104
        LayoutBorderTopWidth::const_px(1),
105
    )),
106
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
107
        LayoutBorderBottomWidth::const_px(1),
108
    )),
109
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
110
        LayoutBorderLeftWidth::const_px(1),
111
    )),
112
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
113
        LayoutBorderRightWidth::const_px(1),
114
    )),
115
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
116
        inner: BorderStyle::Solid,
117
    })),
118
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
119
        StyleBorderBottomStyle {
120
            inner: BorderStyle::Solid,
121
        },
122
    )),
123
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
124
        inner: BorderStyle::Solid,
125
    })),
126
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
127
        StyleBorderRightStyle {
128
            inner: BorderStyle::Solid,
129
        },
130
    )),
131
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
132
        inner: CARD_BORDER_COLOR,
133
    })),
134
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
135
        StyleBorderBottomColor {
136
            inner: CARD_BORDER_COLOR,
137
        },
138
    )),
139
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
140
        inner: CARD_BORDER_COLOR,
141
    })),
142
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
143
        StyleBorderRightColor {
144
            inner: CARD_BORDER_COLOR,
145
        },
146
    )),
147
    // border-radius: 8px
148
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
149
        StyleBorderTopLeftRadius::const_px(8),
150
    )),
151
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
152
        StyleBorderTopRightRadius::const_px(8),
153
    )),
154
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
155
        StyleBorderBottomLeftRadius::const_px(8),
156
    )),
157
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
158
        StyleBorderBottomRightRadius::const_px(8),
159
    )),
160
    // soft drop shadow on all four edges
161
    CssPropertyWithConditions::simple(CssProperty::BoxShadowTop(StyleBoxShadowValue::Exact(
162
        BoxOrStatic::Static(&raw const CARD_SHADOW),
163
    ))),
164
    CssPropertyWithConditions::simple(CssProperty::BoxShadowBottom(StyleBoxShadowValue::Exact(
165
        BoxOrStatic::Static(&raw const CARD_SHADOW),
166
    ))),
167
    CssPropertyWithConditions::simple(CssProperty::BoxShadowLeft(StyleBoxShadowValue::Exact(
168
        BoxOrStatic::Static(&raw const CARD_SHADOW),
169
    ))),
170
    CssPropertyWithConditions::simple(CssProperty::BoxShadowRight(StyleBoxShadowValue::Exact(
171
        BoxOrStatic::Static(&raw const CARD_SHADOW),
172
    ))),
173
];
174

            
175
/// An elevated, bordered content container with rounded corners, a soft drop
176
/// shadow and padding. Holds arbitrary child content (`content`).
177
#[derive(Debug, Clone, PartialEq)]
178
#[repr(C)]
179
pub struct Card {
180
    /// The body content rendered inside the card.
181
    pub content: Dom,
182
    /// `flex-grow` factor applied to the card container.
183
    pub flex_grow: f32,
184
    /// Optional: Function to call when the card is clicked
185
    pub on_click: OptionCardOnClick,
186
}
187

            
188
/// Callback function type invoked when the card container is clicked.
189
pub type CardOnClickCallbackType = extern "C" fn(RefAny, CallbackInfo) -> Update;
190
impl_widget_callback!(
191
    CardOnClick,
192
    OptionCardOnClick,
193
    CardOnClickCallback,
194
    CardOnClickCallbackType
195
);
196

            
197
// Host-invoker plumbing for managed-FFI bindings — see core/src/host_invoker.rs.
198
azul_core::impl_managed_callback! {
199
    wrapper:        CardOnClickCallback,
200
    info_ty:        CallbackInfo,
201
    return_ty:      Update,
202
    default_ret:    Update::DoNothing,
203
    invoker_static: CARD_ON_CLICK_INVOKER,
204
    invoker_ty:     AzCardOnClickCallbackInvoker,
205
    thunk_fn:       az_card_on_click_callback_thunk,
206
    setter_fn:      AzApp_setCardOnClickCallbackInvoker,
207
    from_handle_fn: AzCardOnClickCallback_createFromHostHandle,
208
}
209

            
210
impl Card {
211
    /// Creates a new `Card` wrapping the given content DOM.
212
    #[must_use]
213
260
    pub const fn create(content: Dom) -> Self {
214
260
        Self {
215
260
            content,
216
260
            flex_grow: 0.0,
217
260
            on_click: OptionCardOnClick::None,
218
260
        }
219
260
    }
220

            
221
    /// Replaces `self` with an empty default card and returns the original.
222
    #[must_use]
223
10
    pub const fn swap_with_default(&mut self) -> Self {
224
10
        let mut s = Self::create(Dom::create_div());
225
10
        core::mem::swap(&mut s, self);
226
10
        s
227
10
    }
228

            
229
    /// Sets the body content.
230
4
    pub fn set_content(&mut self, content: Dom) {
231
4
        self.content = content;
232
4
    }
233

            
234
    /// Builder-style setter for the body content.
235
    #[must_use]
236
2
    pub fn with_content(mut self, content: Dom) -> Self {
237
2
        self.set_content(content);
238
2
        self
239
2
    }
240

            
241
    /// Sets the flex-grow factor for the card container.
242
175
    pub const fn set_flex_grow(&mut self, flex_grow: f32) {
243
175
        self.flex_grow = flex_grow;
244
175
    }
245

            
246
    /// Builder-style setter for the flex-grow factor.
247
    #[must_use]
248
147
    pub const fn with_flex_grow(mut self, flex_grow: f32) -> Self {
249
147
        self.set_flex_grow(flex_grow);
250
147
        self
251
147
    }
252

            
253
    /// Sets the click callback, invoked when the card container is clicked.
254
8
    pub fn set_on_click<C: Into<CardOnClickCallback>>(&mut self, data: RefAny, on_click: C) {
255
8
        self.on_click = Some(CardOnClick {
256
8
            refany: data,
257
8
            callback: on_click.into(),
258
8
        })
259
8
        .into();
260
8
    }
261

            
262
    /// Builder-style setter for the click callback.
263
    #[must_use]
264
4
    pub fn with_on_click<C: Into<CardOnClickCallback>>(
265
4
        mut self,
266
4
        data: RefAny,
267
4
        on_click: C,
268
4
    ) -> Self {
269
4
        self.set_on_click(data, on_click);
270
4
        self
271
4
    }
272

            
273
    #[must_use]
274
172
    pub fn dom(self) -> Dom {
275
        use azul_core::{
276
            callbacks::{CoreCallback, CoreCallbackData},
277
            dom::{EventFilter, HoverEventFilter},
278
        };
279

            
280
        static CARD_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str("__azul-native-card"))];
281

            
282
        // Optional click callback on the card's root container (same wiring
283
        // as button's on_click).
284
172
        let callbacks = match self.on_click.into_option() {
285
            Some(CardOnClick {
286
5
                refany: data,
287
5
                callback,
288
5
            }) => vec![CoreCallbackData {
289
5
                event: EventFilter::Hover(HoverEventFilter::Click),
290
5
                callback: CoreCallback {
291
5
                    cb: callback.cb as *const () as usize,
292
5
                    ctx: callback.ctx,
293
5
                },
294
5
                refany: data,
295
5
            }],
296
167
            None => Vec::new(),
297
        };
298

            
299
        // Prepend the (param-dependent) flex-grow, then the static card style.
300
172
        let mut props = vec![CssPropertyWithConditions::simple(CssProperty::FlexGrow(
301
172
            LayoutFlexGrowValue::Exact(LayoutFlexGrow {
302
172
                inner: FloatValue::new(self.flex_grow),
303
172
            }),
304
172
        ))];
305
172
        props.extend_from_slice(CARD_STYLE);
306

            
307
172
        Dom::create_div()
308
172
            .with_ids_and_classes(IdOrClassVec::from_const_slice(CARD_CLASS))
309
172
            .with_css_props(CssPropertyWithConditionsVec::from_vec(props))
310
172
            .with_callbacks(callbacks.into())
311
172
            .with_children(vec![self.content].into())
312
172
    }
313
}
314

            
315
impl Default for Card {
316
159
    fn default() -> Self {
317
159
        Self::create(Dom::create_div())
318
159
    }
319
}
320

            
321
impl From<Card> for Dom {
322
1
    fn from(c: Card) -> Self {
323
1
        c.dom()
324
1
    }
325
}
326

            
327
#[cfg(test)]
328
#[allow(
329
    clippy::float_cmp,
330
    clippy::cast_precision_loss,
331
    clippy::unreadable_literal,
332
    clippy::too_many_lines
333
)]
334
mod autotest_generated {
335
    use azul_core::dom::{EventFilter, HoverEventFilter, NodeType};
336
    use azul_css::props::basic::length::SizeMetric;
337

            
338
    use super::*;
339
    use crate::callbacks::Callback;
340

            
341
    // ------------------------------------------------------------------
342
    // Helpers
343
    // ------------------------------------------------------------------
344

            
345
    extern "C" fn click_a(_data: RefAny, _info: CallbackInfo) -> Update {
346
        Update::DoNothing
347
    }
348

            
349
    extern "C" fn click_b(_data: RefAny, _info: CallbackInfo) -> Update {
350
        Update::RefreshDom
351
    }
352

            
353
    /// Content DOMs a caller can realistically hand to a card: empty text, a NUL byte,
354
    /// combining marks, a ZWJ emoji sequence, RTL text and a lone surrogate-ish escape.
355
    /// The card must carry all of them through to the DOM byte-for-byte — it never parses
356
    /// or normalises its content.
357
    const ADVERSARIAL_TEXT: [&str; 6] = [
358
        "",
359
        "a\0b",
360
        "e\u{0301}\u{0301}\u{0301}",
361
        "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}",
362
        "\u{202E}gnirts desrever\u{202C}",
363
        "\u{FFFD}\u{FEFF}\t\n",
364
    ];
365

            
366
    /// Every f32 the numeric surface of `set_flex_grow` has to survive. `FloatValue::new`
367
    /// multiplies by 1000 and casts to `isize` — NaN, the infinities and `f32::MAX` all
368
    /// hit the saturating-cast path, and anything under 0.001 truncates away.
369
    const ADVERSARIAL_FLOATS: [f32; 14] = [
370
        0.0,
371
        -0.0,
372
        1.0,
373
        -1.0,
374
        0.001,
375
        -0.001,
376
        f32::EPSILON,
377
        f32::MIN_POSITIVE,
378
        -f32::MIN_POSITIVE,
379
        f32::MAX,
380
        f32::MIN,
381
        f32::INFINITY,
382
        f32::NEG_INFINITY,
383
        f32::NAN,
384
    ];
385

            
386
    /// The declared properties of a rendered node's inline style, in declaration order.
387
    fn inline_props(dom: &Dom) -> Vec<CssProperty> {
388
        dom.root
389
            .style
390
            .iter_inline_properties()
391
            .map(|(p, _)| p.clone())
392
            .collect()
393
    }
394

            
395
    /// The CSS classes of a rendered node, in declaration order.
396
    fn classes(dom: &Dom) -> Vec<String> {
397
        dom.root
398
            .get_ids_and_classes()
399
            .as_ref()
400
            .iter()
401
            .filter_map(|c| match c {
402
                Class(s) => Some(s.as_str().to_string()),
403
                IdOrClass::Id(_) => None,
404
            })
405
            .collect()
406
    }
407

            
408
    /// The `flex-grow` factor as it actually lands in the style tree — i.e. *after* the
409
    /// lossy `f32 -> isize` encoding inside `FloatValue::new`.
410
    fn dom_flex_grow(dom: &Dom) -> Option<f32> {
411
        dom.root
412
            .style
413
            .iter_inline_properties()
414
            .find_map(|(p, _)| match p {
415
                CssProperty::FlexGrow(v) => v.get_property().map(|f| f.inner.get()),
416
                _ => None,
417
            })
418
    }
419

            
420
    /// The `f32` of a `PixelValue`, asserting the length is an absolute `px`. An `em`/`%`
421
    /// slipping into the card geometry would resolve against the parent font/box instead
422
    /// of the intended fixed padding, border or radius.
423
    fn px(pv: &PixelValue) -> f32 {
424
        assert_eq!(
425
            pv.metric,
426
            SizeMetric::Px,
427
            "card geometry must be absolute px, got {:?}",
428
            pv.metric
429
        );
430
        pv.number.get()
431
    }
432

            
433
    /// The recursive descendant count. `Dom::estimated_total_children` is a *cached* value
434
    /// that, if too small, makes `convert_dom_into_compact_dom` under-allocate its arenas
435
    /// and panic on out-of-bounds writes — so it has to match this exactly.
436
    fn count_descendants(dom: &Dom) -> usize {
437
        dom.children
438
            .as_ref()
439
            .iter()
440
            .map(|c| 1 + count_descendants(c))
441
            .sum()
442
    }
443

            
444
    /// A chain of `depth` nested divs (depth kept modest: `Dom`'s `Drop`/`PartialEq` recurse).
445
    fn nested_divs(depth: usize) -> Dom {
446
        let mut d = Dom::create_div();
447
        for _ in 0..depth {
448
            d = Dom::create_div().with_child(d);
449
        }
450
        d
451
    }
452

            
453
    fn text_of(dom: &Dom) -> Option<&str> {
454
        match dom.root.get_node_type() {
455
            NodeType::Text(s) => Some(s.as_ref().as_str()),
456
            _ => None,
457
        }
458
    }
459

            
460
    // ------------------------------------------------------------------
461
    // Card::create
462
    // ------------------------------------------------------------------
463

            
464
    #[test]
465
    fn create_zeroes_the_numeric_field_and_leaves_the_callback_unset() {
466
        let c = Card::create(Dom::create_div());
467

            
468
        // Positive zero, not -0.0: a negative zero would flip the sign of the encoded
469
        // isize on some paths and is not what "no growth" means.
470
        assert_eq!(c.flex_grow.to_bits(), 0_u32, "flex_grow must start at +0.0");
471
        assert!(c.on_click.is_none(), "a fresh card must have no callback");
472
        assert_eq!(
473
            c.content,
474
            Dom::create_div(),
475
            "the content was not stored verbatim"
476
        );
477
    }
478

            
479
    #[test]
480
    fn create_with_a_div_is_exactly_the_default_card() {
481
        assert_eq!(
482
            Card::create(Dom::create_div()),
483
            Card::default(),
484
            "Default and create(div) drifted apart",
485
        );
486
    }
487

            
488
    #[test]
489
    fn create_stores_pathological_content_verbatim() {
490
        for t in ADVERSARIAL_TEXT {
491
            let c = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(t));
492
            assert_eq!(
493
                text_of(&c.content),
494
                Some(t),
495
                "the card mangled or normalised its text content",
496
            );
497

            
498
            // ... and it survives the trip into the rendered DOM.
499
            let dom = c.dom();
500
            let child = &dom.children.as_ref()[0];
501
            assert_eq!(
502
                text_of(child),
503
                Some(t),
504
                "the text was corrupted on the way into the DOM"
505
            );
506
        }
507
    }
508

            
509
    #[test]
510
    fn create_accepts_deeply_nested_and_very_wide_content() {
511
        let deep = Card::create(nested_divs(64)).dom();
512
        assert_eq!(
513
            deep.estimated_total_children,
514
            count_descendants(&deep),
515
            "the cached child count desynced for deeply nested content",
516
        );
517

            
518
        let wide = Card::create(
519
            Dom::create_div().with_children(
520
                (0..2000)
521
                    .map(|_| Dom::create_div())
522
                    .collect::<Vec<_>>()
523
                    .into(),
524
            ),
525
        )
526
        .dom();
527
        assert_eq!(
528
            wide.estimated_total_children,
529
            count_descendants(&wide),
530
            "the cached child count desynced for very wide content",
531
        );
532
        assert_eq!(
533
            wide.estimated_total_children, 2001,
534
            "card div + 2000 grandchildren expected"
535
        );
536
    }
537

            
538
    // ------------------------------------------------------------------
539
    // Card::swap_with_default
540
    // ------------------------------------------------------------------
541

            
542
    #[test]
543
    fn swap_with_default_moves_every_field_out_and_leaves_a_default() {
544
        let mut c = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
545
            "payload",
546
        ))
547
        .with_flex_grow(2.5);
548
        c.set_on_click(RefAny::new(7u32), click_a as CardOnClickCallbackType);
549

            
550
        let taken = c.swap_with_default();
551

            
552
        assert_eq!(
553
            text_of(&taken.content),
554
            Some("payload"),
555
            "the content did not travel out"
556
        );
557
        assert_eq!(taken.flex_grow, 2.5, "flex_grow did not travel out");
558
        assert!(taken.on_click.is_some(), "the callback did not travel out");
559

            
560
        assert_eq!(
561
            c,
562
            Card::default(),
563
            "what was left behind is not a default card"
564
        );
565
        assert!(
566
            c.on_click.is_none(),
567
            "the swapped-in default still carries a callback"
568
        );
569
        assert_eq!(
570
            c.flex_grow.to_bits(),
571
            0_u32,
572
            "the swapped-in default has a non-zero flex_grow"
573
        );
574
    }
575

            
576
    #[test]
577
    fn repeated_swap_with_default_never_accumulates_state() {
578
        let mut c = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper("x"))
579
            .with_flex_grow(1.0);
580
        let _first = c.swap_with_default();
581

            
582
        for i in 0..8 {
583
            let taken = c.swap_with_default();
584
            assert_eq!(
585
                taken,
586
                Card::default(),
587
                "swap #{i} handed back something other than a default"
588
            );
589
            assert_eq!(
590
                c,
591
                Card::default(),
592
                "swap #{i} left something other than a default behind"
593
            );
594
        }
595

            
596
        // The DOM of the drained card is still a well-formed one-child card.
597
        let dom = c.dom();
598
        assert_eq!(dom.children.as_ref().len(), 1);
599
        assert_eq!(dom_flex_grow(&dom), Some(0.0));
600
    }
601

            
602
    // ------------------------------------------------------------------
603
    // Card::set_content / Card::with_content
604
    // ------------------------------------------------------------------
605

            
606
    #[test]
607
    fn set_content_replaces_rather_than_appends() {
608
        let mut c = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
609
            "first",
610
        ));
611
        c.set_content(Dom::create_text_do_not_use_without_block_level_wrapper(
612
            "second",
613
        ));
614
        c.set_content(Dom::create_text_do_not_use_without_block_level_wrapper(
615
            "third",
616
        ));
617

            
618
        assert_eq!(
619
            text_of(&c.content),
620
            Some("third"),
621
            "the last content did not win"
622
        );
623

            
624
        let dom = c.dom();
625
        assert_eq!(
626
            dom.children.as_ref().len(),
627
            1,
628
            "re-setting the content appended a child instead of replacing it",
629
        );
630
        assert_eq!(text_of(&dom.children.as_ref()[0]), Some("third"));
631
    }
632

            
633
    #[test]
634
    fn with_content_touches_only_the_content_field() {
635
        let base = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
636
            "old",
637
        ))
638
        .with_flex_grow(3.0);
639
        let c = base.with_content(Dom::create_text_do_not_use_without_block_level_wrapper(
640
            "new",
641
        ));
642

            
643
        assert_eq!(text_of(&c.content), Some("new"));
644
        assert_eq!(c.flex_grow, 3.0, "with_content clobbered flex_grow");
645
        assert!(c.on_click.is_none(), "with_content invented a callback");
646
    }
647

            
648
    #[test]
649
    fn with_content_preserves_an_already_installed_callback() {
650
        let c = Card::default()
651
            .with_on_click(RefAny::new(1u8), click_a as CardOnClickCallbackType)
652
            .with_content(Dom::create_text_do_not_use_without_block_level_wrapper(
653
                "late content",
654
            ));
655

            
656
        assert!(c.on_click.is_some(), "with_content dropped the callback");
657
        let dom = c.dom();
658
        assert_eq!(
659
            dom.root.callbacks.as_ref().len(),
660
            1,
661
            "the callback was lost on the way into the DOM"
662
        );
663
        assert_eq!(text_of(&dom.children.as_ref()[0]), Some("late content"));
664
    }
665

            
666
    // ------------------------------------------------------------------
667
    // Card::set_flex_grow / Card::with_flex_grow  (numeric)
668
    // ------------------------------------------------------------------
669

            
670
    #[test]
671
    fn set_flex_grow_stores_the_bit_pattern_verbatim_without_sanitising() {
672
        // The setter is a plain assignment — it must not clamp, round or NaN-scrub.
673
        // (Sanitisation happens later, at encode time; see the tests below.)
674
        for v in ADVERSARIAL_FLOATS {
675
            let mut c = Card::default();
676
            c.set_flex_grow(v);
677
            if v.is_nan() {
678
                assert!(
679
                    c.flex_grow.is_nan(),
680
                    "a NaN flex_grow was silently rewritten"
681
                );
682
            } else {
683
                assert_eq!(
684
                    c.flex_grow.to_bits(),
685
                    v.to_bits(),
686
                    "flex_grow {v} was not stored verbatim"
687
                );
688
            }
689
        }
690
    }
691

            
692
    #[test]
693
    fn with_flex_grow_is_exactly_set_flex_grow() {
694
        for v in ADVERSARIAL_FLOATS {
695
            let mut by_setter = Card::default();
696
            by_setter.set_flex_grow(v);
697
            let by_builder = Card::default().with_flex_grow(v);
698

            
699
            assert_eq!(
700
                by_setter.flex_grow.to_bits(),
701
                by_builder.flex_grow.to_bits(),
702
                "the builder and the setter disagree for {v}",
703
            );
704
        }
705
    }
706

            
707
    #[test]
708
    fn with_flex_grow_touches_only_the_numeric_field() {
709
        let c = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
710
            "body",
711
        ))
712
        .with_on_click(RefAny::new(1u8), click_a as CardOnClickCallbackType)
713
        .with_flex_grow(f32::NAN);
714

            
715
        assert_eq!(
716
            text_of(&c.content),
717
            Some("body"),
718
            "with_flex_grow clobbered the content"
719
        );
720
        assert!(c.on_click.is_some(), "with_flex_grow dropped the callback");
721
    }
722

            
723
    #[test]
724
    fn a_nan_flex_grow_breaks_the_derived_equality_of_the_card() {
725
        // `Card` derives `PartialEq` over a raw `f32`, so a NaN factor makes a card
726
        // unequal to its own clone. Callers cannot use `==` as a "was it modified?"
727
        // probe once a NaN is in there — pinned so nobody relies on the opposite.
728
        let c = Card::default().with_flex_grow(f32::NAN);
729
        assert_ne!(c, c.clone(), "NaN equality semantics changed");
730

            
731
        // Every non-NaN factor keeps equality reflexive.
732
        for v in ADVERSARIAL_FLOATS.iter().copied().filter(|v| !v.is_nan()) {
733
            let c = Card::default().with_flex_grow(v);
734
            assert_eq!(
735
                c,
736
                c.clone(),
737
                "a card with flex_grow {v} is not equal to its own clone"
738
            );
739
        }
740
    }
741

            
742
    #[test]
743
    fn flex_grow_zero_encodes_to_positive_zero_even_from_negative_zero() {
744
        for v in [0.0_f32, -0.0_f32] {
745
            let dom = Card::default().with_flex_grow(v).dom();
746
            let got = dom_flex_grow(&dom).expect("flex-grow must always be declared");
747
            assert_eq!(
748
                got.to_bits(),
749
                0_u32,
750
                "flex_grow {v} did not encode to +0.0 (got {got})"
751
            );
752
        }
753
    }
754

            
755
    #[test]
756
    fn flex_grow_round_trips_through_the_dom_at_milli_precision() {
757
        // FloatValue keeps 3 decimal places (x1000, truncating cast), so any factor that is
758
        // a whole multiple of 0.001 must come back out of the DOM unchanged.
759
        for v in [0.0_f32, 0.001, 0.5, 1.0, 2.5, 3.0, -1.5, 1000.0, 65536.0] {
760
            let got = dom_flex_grow(&Card::default().with_flex_grow(v).dom())
761
                .expect("flex-grow must always be declared");
762
            assert!(
763
                (got - v).abs() <= 0.001,
764
                "flex_grow {v} did not survive the FloatValue encoding (got {got})",
765
            );
766
        }
767
    }
768

            
769
    #[test]
770
    fn flex_grow_below_the_encoding_precision_truncates_to_zero() {
771
        // Everything under one milli-unit is quantised away — including the sign, because
772
        // the truncating cast of -0.0001 * 1000 = -0.1 lands on integer 0.
773
        for v in [
774
            f32::EPSILON,
775
            f32::MIN_POSITIVE,
776
            -f32::MIN_POSITIVE,
777
            1e-4,
778
            -1e-4,
779
            0.0005,
780
            -0.0009,
781
        ] {
782
            let got = dom_flex_grow(&Card::default().with_flex_grow(v).dom())
783
                .expect("flex-grow must always be declared");
784
            assert_eq!(
785
                got.to_bits(),
786
                0_u32,
787
                "sub-milli flex_grow {v} did not truncate to +0.0 (got {got})"
788
            );
789
        }
790

            
791
        // ... and 0.001 is genuinely the smallest factor that still registers.
792
        let smallest = dom_flex_grow(&Card::default().with_flex_grow(0.001).dom()).unwrap();
793
        assert!(
794
            smallest > 0.0,
795
            "0.001 is supposed to be the smallest representable factor"
796
        );
797
    }
798

            
799
    #[test]
800
    fn a_nan_flex_grow_does_not_panic_and_lands_on_zero() {
801
        let dom = Card::default().with_flex_grow(f32::NAN).dom();
802
        let got = dom_flex_grow(&dom).expect("flex-grow must always be declared");
803
        assert!(!got.is_nan(), "a NaN flex-grow reached the style tree");
804
        assert_eq!(
805
            got.to_bits(),
806
            0_u32,
807
            "NaN must encode to +0.0 (saturating cast), got {got}"
808
        );
809
    }
810

            
811
    #[test]
812
    fn infinite_and_maximal_flex_grow_saturates_instead_of_overflowing() {
813
        // `FloatValue::new` does `(v * 1000.0) as isize`; f32::MAX * 1000 already overflows to
814
        // +inf, so MAX and INFINITY have to land on the same saturated bound. The point is that
815
        // nothing wraps around into a *negative* factor.
816
        let max_encoded = (isize::MAX as f32) / 1000.0;
817
        let min_encoded = (isize::MIN as f32) / 1000.0;
818

            
819
        for v in [f32::INFINITY, f32::MAX] {
820
            let got = dom_flex_grow(&Card::default().with_flex_grow(v).dom()).unwrap();
821
            assert!(
822
                got.is_finite(),
823
                "an infinite flex-grow reached the style tree for {v}"
824
            );
825
            assert_eq!(
826
                got, max_encoded,
827
                "{v} did not saturate at the isize upper bound"
828
            );
829
            assert!(got > 0.0, "{v} wrapped around into a non-positive factor");
830
        }
831

            
832
        for v in [f32::NEG_INFINITY, f32::MIN] {
833
            let got = dom_flex_grow(&Card::default().with_flex_grow(v).dom()).unwrap();
834
            assert!(
835
                got.is_finite(),
836
                "an infinite flex-grow reached the style tree for {v}"
837
            );
838
            assert_eq!(
839
                got, min_encoded,
840
                "{v} did not saturate at the isize lower bound"
841
            );
842
            assert!(got < 0.0, "{v} wrapped around into a non-negative factor");
843
        }
844
    }
845

            
846
    #[test]
847
    fn no_flex_grow_input_can_put_a_nan_or_an_infinity_into_the_style_tree() {
848
        for v in ADVERSARIAL_FLOATS {
849
            let dom = Card::default().with_flex_grow(v).dom();
850
            let got = dom_flex_grow(&dom)
851
                .unwrap_or_else(|| panic!("flex-grow disappeared for input {v}"));
852
            assert!(
853
                got.is_finite(),
854
                "input {v} produced a non-finite flex-grow ({got}) — the layout solver would NaN \
855
                 out",
856
            );
857
        }
858
    }
859

            
860
    #[test]
861
    fn flex_grow_encoding_is_monotonic() {
862
        // A sign- or rounding-bug in the x1000 cast would show up as an inversion here.
863
        let ascending = [-1000.0_f32, -1.5, -0.001, 0.0, 0.001, 1.5, 1000.0];
864
        let mut prev = f32::NEG_INFINITY;
865
        for v in ascending {
866
            let got = dom_flex_grow(&Card::default().with_flex_grow(v).dom()).unwrap();
867
            assert!(
868
                got >= prev,
869
                "encoding is not monotonic: {v} encoded to {got}, below the previous {prev}"
870
            );
871
            prev = got;
872
        }
873
    }
874

            
875
    // ------------------------------------------------------------------
876
    // Card::set_on_click / Card::with_on_click
877
    // ------------------------------------------------------------------
878

            
879
    #[test]
880
    fn set_on_click_replaces_the_previous_callback_instead_of_appending() {
881
        let mut c = Card::default();
882
        assert!(c.on_click.is_none());
883

            
884
        c.set_on_click(RefAny::new(1u32), click_a as CardOnClickCallbackType);
885
        assert!(
886
            c.on_click.is_some(),
887
            "set_on_click did not store the callback"
888
        );
889

            
890
        c.set_on_click(RefAny::new(2u32), click_b as CardOnClickCallbackType);
891
        let stored = c.on_click.as_ref().expect("callback must still be present");
892
        assert_eq!(
893
            stored.callback.cb as *const () as usize,
894
            click_b as CardOnClickCallbackType as *const () as usize,
895
            "the second set_on_click did not replace the first",
896
        );
897

            
898
        let dom = c.dom();
899
        assert_eq!(
900
            dom.root.callbacks.as_ref().len(),
901
            1,
902
            "a re-set callback was appended instead of replaced — the card would fire twice",
903
        );
904
    }
905

            
906
    #[test]
907
    fn with_on_click_round_trips_the_function_pointer_and_the_payload_into_the_dom() {
908
        let cb: CardOnClickCallbackType = click_a;
909
        let expected_ptr = cb as *const () as usize;
910

            
911
        let dom = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
912
            "clickable",
913
        ))
914
        .with_on_click(RefAny::new(0xDEAD_BEEF_u32), cb)
915
        .dom();
916

            
917
        let callbacks = dom.root.callbacks.as_ref();
918
        assert_eq!(callbacks.len(), 1, "exactly one click callback is expected");
919
        assert_eq!(
920
            callbacks[0].event,
921
            EventFilter::Hover(HoverEventFilter::Click),
922
            "the card must fire on mouse-up, not on any other filter",
923
        );
924
        assert_eq!(
925
            callbacks[0].callback.cb, expected_ptr,
926
            "the fn pointer was corrupted on the way into the DOM",
927
        );
928

            
929
        // The RefAny payload survives the move into the DOM, and a wrong-type downcast
930
        // must fail rather than reinterpret the bytes.
931
        let mut data = callbacks[0].refany.clone();
932
        assert_eq!(
933
            *data.downcast_ref::<u32>().expect("payload changed type"),
934
            0xDEAD_BEEF,
935
            "payload was corrupted",
936
        );
937
        assert!(
938
            data.downcast_ref::<u64>().is_none(),
939
            "a wrong-type downcast reinterpreted the payload"
940
        );
941
    }
942

            
943
    #[test]
944
    fn with_on_click_accepts_a_generic_callback_without_mangling_the_pointer() {
945
        // The `From<Callback>` arm transmutes the fn pointer — this is the FFI path
946
        // (Python/C) into the same slot, so the pointer must come out untouched.
947
        let generic = Callback {
948
            cb: click_a,
949
            ctx: azul_core::refany::OptionRefAny::None,
950
        };
951
        let raw: CardOnClickCallbackType = click_a;
952
        let expected_ptr = raw as *const () as usize;
953

            
954
        let dom = Card::default()
955
            .with_on_click(RefAny::new(1u8), generic)
956
            .dom();
957
        let callbacks = dom.root.callbacks.as_ref();
958
        assert_eq!(callbacks.len(), 1);
959
        assert_eq!(
960
            callbacks[0].callback.cb, expected_ptr,
961
            "the Callback -> CardOnClickCallback transmute mangled the pointer",
962
        );
963
        assert!(
964
            callbacks[0].callback.ctx.is_none(),
965
            "a native callback must carry no FFI context"
966
        );
967
    }
968

            
969
    #[test]
970
    fn a_card_without_a_callback_registers_no_callbacks() {
971
        let dom = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
972
            "inert",
973
        ))
974
        .with_flex_grow(1.0)
975
        .dom();
976
        assert!(
977
            dom.root.callbacks.as_ref().is_empty(),
978
            "a callback appeared on a card that was never given one",
979
        );
980
    }
981

            
982
    #[test]
983
    fn set_on_click_does_not_disturb_the_other_fields() {
984
        let mut c = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
985
            "body",
986
        ))
987
        .with_flex_grow(2.0);
988
        c.set_on_click(
989
            RefAny::new("payload".to_string()),
990
            click_a as CardOnClickCallbackType,
991
        );
992

            
993
        assert_eq!(
994
            text_of(&c.content),
995
            Some("body"),
996
            "set_on_click clobbered the content"
997
        );
998
        assert_eq!(c.flex_grow, 2.0, "set_on_click clobbered flex_grow");
999

            
        let dom = c.dom();
        assert_eq!(dom_flex_grow(&dom), Some(2.0));
        let mut data = dom.root.callbacks.as_ref()[0].refany.clone();
        let payload = data.downcast_ref::<String>().expect("payload changed type");
        assert_eq!(
            payload.as_str(),
            "payload",
            "the RefAny payload was corrupted"
        );
    }
    // ------------------------------------------------------------------
    // Card::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_builds_a_single_card_div_holding_the_content_as_its_only_child() {
        let dom = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
            "body",
        ))
        .dom();
        assert_eq!(
            *dom.root.get_node_type(),
            NodeType::Div,
            "the card container must be a div"
        );
        assert_eq!(
            classes(&dom),
            vec!["__azul-native-card".to_string()],
            "the card class is what the UA stylesheet and tests key off",
        );
        assert_eq!(
            dom.children.as_ref().len(),
            1,
            "the card must wrap exactly one child"
        );
        assert_eq!(text_of(&dom.children.as_ref()[0]), Some("body"));
        assert_eq!(
            dom.estimated_total_children,
            count_descendants(&dom),
            "the cached child count is inconsistent — compact-DOM conversion would \
             over/under-allocate",
        );
    }
    #[test]
    fn dom_prepends_the_flex_grow_declaration_to_the_static_card_style() {
        let dom = Card::default().with_flex_grow(4.0).dom();
        let props = inline_props(&dom);
        assert_eq!(
            props.len(),
            1 + CARD_STYLE.len(),
            "the card's inline style must be exactly flex-grow + the static card style",
        );
        assert!(
            matches!(props[0], CssProperty::FlexGrow(_)),
            "flex-grow must come first, so nothing in the static style can shadow it",
        );
        assert_eq!(
            props
                .iter()
                .filter(|p| matches!(p, CssProperty::FlexGrow(_)))
                .count(),
            1,
            "flex-grow was declared more than once",
        );
    }
    #[test]
    fn dom_carries_the_static_card_geometry() {
        let props = inline_props(&Card::default().dom());
        let mut paddings = Vec::new();
        let mut border_widths = Vec::new();
        let mut radii = Vec::new();
        let mut border_colors = Vec::new();
        let mut border_styles = Vec::new();
        let mut display = None;
        let mut direction = None;
        let mut background = None;
        for p in &props {
            match p {
                CssProperty::PaddingTop(v) => paddings.push(v.get_property().map(|x| px(&x.inner))),
                CssProperty::PaddingBottom(v) => {
                    paddings.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::PaddingLeft(v) => {
                    paddings.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::PaddingRight(v) => {
                    paddings.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderTopWidth(v) => {
                    border_widths.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderBottomWidth(v) => {
                    border_widths.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderLeftWidth(v) => {
                    border_widths.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderRightWidth(v) => {
                    border_widths.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderTopLeftRadius(v) => {
                    radii.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderTopRightRadius(v) => {
                    radii.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderBottomLeftRadius(v) => {
                    radii.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderBottomRightRadius(v) => {
                    radii.push(v.get_property().map(|x| px(&x.inner)))
                }
                CssProperty::BorderTopColor(v) => {
                    border_colors.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::BorderBottomColor(v) => {
                    border_colors.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::BorderLeftColor(v) => {
                    border_colors.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::BorderRightColor(v) => {
                    border_colors.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::BorderTopStyle(v) => {
                    border_styles.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::BorderBottomStyle(v) => {
                    border_styles.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::BorderLeftStyle(v) => {
                    border_styles.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::BorderRightStyle(v) => {
                    border_styles.push(v.get_property().map(|x| x.inner))
                }
                CssProperty::Display(v) => display = v.get_property().copied(),
                CssProperty::FlexDirection(v) => direction = v.get_property().copied(),
                CssProperty::BackgroundContent(v) => {
                    background = v.get_property().map(|bg| bg.as_ref().to_vec());
                }
                _ => {}
            }
        }
        assert_eq!(
            paddings,
            vec![Some(12.0); 4],
            "all four paddings must be 12px"
        );
        assert_eq!(
            border_widths,
            vec![Some(1.0); 4],
            "all four borders must be 1px"
        );
        assert_eq!(radii, vec![Some(8.0); 4], "all four corners must be 8px");
        assert_eq!(
            border_colors,
            vec![Some(CARD_BORDER_COLOR); 4],
            "all four border colours must match"
        );
        assert_eq!(
            border_styles,
            vec![Some(BorderStyle::Solid); 4],
            "all four border styles must be solid"
        );
        assert_eq!(
            display,
            Some(LayoutDisplay::Flex),
            "the card container must be a flex box"
        );
        assert_eq!(
            direction,
            Some(LayoutFlexDirection::Column),
            "the card must stack its content in a column"
        );
        let bg = background.expect("the card must declare a background");
        assert_eq!(bg.len(), 1, "exactly one background layer expected");
        match &bg[0] {
            StyleBackgroundContent::Color(c) => {
                assert_eq!(*c, CARD_BG_COLOR, "the card background is not white")
            }
            other => panic!("the card background must be a flat colour, got {other:?}"),
        }
    }
    #[test]
    fn dom_box_shadows_dereference_the_shared_static_descriptor() {
        let dom = Card::default().dom();
        let mut shadows = 0_usize;
        for (p, _) in dom.root.style.iter_inline_properties() {
            let value = match p {
                CssProperty::BoxShadowTop(v)
                | CssProperty::BoxShadowBottom(v)
                | CssProperty::BoxShadowLeft(v)
                | CssProperty::BoxShadowRight(v) => v.get_property(),
                _ => None,
            };
            let Some(boxed) = value else { continue };
            // This is the interesting bit: the property holds a raw `*const StyleBoxShadow`
            // taken with `&raw const CARD_SHADOW`. Dereferencing it must yield the static.
            let s: &StyleBoxShadow = boxed.as_ref();
            assert_eq!(px(&s.offset_x.inner), 0.0);
            assert_eq!(px(&s.offset_y.inner), 2.0);
            assert_eq!(px(&s.blur_radius.inner), 6.0);
            assert_eq!(px(&s.spread_radius.inner), 0.0);
            assert_eq!(s.clip_mode, BoxShadowClipMode::Outset);
            assert_eq!(s.color, CARD_SHADOW_COLOR);
            shadows += 1;
        }
        assert_eq!(
            shadows, 4,
            "the card must declare a shadow on all four edges"
        );
    }
    #[test]
    fn dropping_card_doms_never_frees_the_static_shadow() {
        // Every card's four box-shadows are `BoxOrStatic::Static` pointers into the *same*
        // `CARD_SHADOW`. If a `Drop` ever treated one as `Boxed`, the second card's shadow
        // would be a use-after-free (and the third a double-free). Build, drop, re-read.
        let survivor = Card::default().dom();
        for _ in 0..64 {
            drop(
                Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
                    "throwaway",
                ))
                .with_flex_grow(1.0)
                .dom(),
            );
        }
        assert_eq!(
            CARD_SHADOW.offset_y.inner.number.get(),
            2.0,
            "the static shadow was mutated or freed"
        );
        assert_eq!(CARD_SHADOW.color, CARD_SHADOW_COLOR);
        let shadows = survivor
            .root
            .style
            .iter_inline_properties()
            .filter_map(|(p, _)| match p {
                CssProperty::BoxShadowTop(v)
                | CssProperty::BoxShadowBottom(v)
                | CssProperty::BoxShadowLeft(v)
                | CssProperty::BoxShadowRight(v) => v.get_property(),
                _ => None,
            })
            .map(|b| px(&b.as_ref().blur_radius.inner))
            .collect::<Vec<_>>();
        assert_eq!(
            shadows,
            vec![6.0; 4],
            "a surviving card's shadows were corrupted by other cards' drops"
        );
    }
    #[test]
    fn dom_is_deterministic_and_never_mutates_the_shared_static_style() {
        let baseline = inline_props(&Card::default().dom());
        for i in 0..32 {
            let props = inline_props(&Card::default().dom());
            assert_eq!(
                props.len(),
                baseline.len(),
                "build #{i} produced a different number of properties"
            );
            assert_eq!(
                props, baseline,
                "build #{i} diverged — the static CARD_STYLE was mutated"
            );
        }
    }
    #[test]
    fn from_card_for_dom_is_exactly_dom() {
        let c = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
            "body",
        ))
        .with_flex_grow(1.5);
        assert_eq!(
            Dom::from(c.clone()),
            c.dom(),
            "the From impl diverged from Card::dom"
        );
    }
    #[test]
    fn cards_nest_without_desyncing_the_child_counts() {
        let inner = Card::create(Dom::create_text_do_not_use_without_block_level_wrapper(
            "inner",
        ))
        .with_flex_grow(1.0)
        .dom();
        let outer = Card::create(inner).with_flex_grow(2.0).dom();
        assert_eq!(
            outer.estimated_total_children,
            count_descendants(&outer),
            "nesting cards desynced the cached child count",
        );
        assert_eq!(
            dom_flex_grow(&outer),
            Some(2.0),
            "the outer card's flex-grow was overwritten"
        );
        assert_eq!(
            dom_flex_grow(&outer.children.as_ref()[0]),
            Some(1.0),
            "the inner card's flex-grow was overwritten",
        );
        assert_eq!(
            classes(&outer.children.as_ref()[0]),
            vec!["__azul-native-card".to_string()]
        );
    }
}