1
//! Frame widget — a titled border container similar to an HTML `<fieldset>`
2
//! or a Windows group box.
3
//!
4
//! Renders a header with a centered title flanked by horizontal border lines,
5
//! and a bordered content area below.
6

            
7
use azul_core::dom::{Dom, DomVec, IdOrClass, IdOrClass::Class, IdOrClassVec};
8
#[allow(clippy::wildcard_imports)]
9
// widget/render module pulls in the css property/value types it builds with
10
use azul_css::{
11
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
12
    props::{
13
        basic::*,
14
        layout::*,
15
        property::{CssProperty, *},
16
        style::*,
17
    },
18
    *,
19
};
20

            
21
const BORDER_COLOR: ColorU = ColorU {
22
    r: 221,
23
    g: 221,
24
    b: 221,
25
    a: 255,
26
};
27

            
28
const STRING_16146701490593874959: AzString = AzString::from_const_str("system:ui");
29
const STYLE_FONT_FAMILY_8122988506401935406_ITEMS: &[StyleFontFamily] =
30
    &[StyleFontFamily::System(STRING_16146701490593874959)];
31

            
32
const CSS_MATCH_15775557796860201720_PROPERTIES: &[CssPropertyWithConditions] = &[
33
    // A flex container: `flex-direction` / `justify-content` / `align-items`
34
    // below do nothing without it (this rule had none, so the box laid out as
35
    // a block and its children stacked vertically).
36
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
37
        LayoutDisplay::Flex,
38
    ))),
39
    // .__azul-native-frame .__azul-native-frame-header .__azul-native-frame-header-before div
40
    CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
41
        LayoutHeight::Px(PixelValue::const_px(8)),
42
    ))),
43
    CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
44
        LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
45
            inner: PixelValue::const_px(1),
46
        }),
47
    )),
48
    CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
49
        StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
50
            inner: BorderStyle::Solid,
51
        }),
52
    )),
53
    CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
54
        StyleBorderTopColorValue::Exact(StyleBorderTopColor {
55
            inner: BORDER_COLOR,
56
        }),
57
    )),
58
    CssPropertyWithConditions::simple(CssProperty::BorderLeftWidth(
59
        LayoutBorderLeftWidthValue::Exact(LayoutBorderLeftWidth {
60
            inner: PixelValue::const_px(1),
61
        }),
62
    )),
63
    CssPropertyWithConditions::simple(CssProperty::BorderLeftStyle(
64
        StyleBorderLeftStyleValue::Exact(StyleBorderLeftStyle {
65
            inner: BorderStyle::Solid,
66
        }),
67
    )),
68
    CssPropertyWithConditions::simple(CssProperty::BorderLeftColor(
69
        StyleBorderLeftColorValue::Exact(StyleBorderLeftColor {
70
            inner: BORDER_COLOR,
71
        }),
72
    )),
73
    // .__azul-native-frame .__azul-native-frame-header .__azul-native-frame-header-before
74
    CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
75
        LayoutWidth::Px(PixelValue::const_px(5)),
76
    ))),
77
    CssPropertyWithConditions::simple(CssProperty::MarginTop(LayoutMarginTopValue::Exact(
78
        LayoutMarginTop {
79
            inner: PixelValue::const_px(6),
80
        },
81
    ))),
82
    CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
83
        LayoutFlexGrow {
84
            inner: FloatValue::const_new(1),
85
        },
86
    ))),
87
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
88
        LayoutFlexDirection::Column,
89
    ))),
90
];
91
const CSS_MATCH_15775557796860201720: CssPropertyWithConditionsVec =
92
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_15775557796860201720_PROPERTIES);
93

            
94
const CSS_MATCH_16739370686243728873_PROPERTIES: &[CssPropertyWithConditions] = &[
95
    // A flex container: `flex-direction` / `justify-content` / `align-items`
96
    // below do nothing without it (this rule had none, so the box laid out as
97
    // a block and its children stacked vertically).
98
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
99
        LayoutDisplay::Flex,
100
    ))),
101
    // .__azul-native-frame .__azul-native-frame-header
102
    CssPropertyWithConditions::simple(CssProperty::FontSize(StyleFontSizeValue::Exact(
103
        StyleFontSize {
104
            inner: PixelValue::const_px(11),
105
        },
106
    ))),
107
    CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
108
        StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_8122988506401935406_ITEMS),
109
    ))),
110
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
111
        LayoutFlexDirection::Row,
112
    ))),
113
    CssPropertyWithConditions::simple(CssProperty::AlignItems(LayoutAlignItemsValue::Exact(
114
        LayoutAlignItems::End,
115
    ))),
116
];
117
const CSS_MATCH_16739370686243728873: CssPropertyWithConditionsVec =
118
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_16739370686243728873_PROPERTIES);
119

            
120
const CSS_MATCH_4236783900531286611_PROPERTIES: &[CssPropertyWithConditions] = &[
121
    // .__azul-native-frame .__azul-native-frame-header p
122
    CssPropertyWithConditions::simple(CssProperty::TextAlign(StyleTextAlignValue::Exact(
123
        StyleTextAlign::Center,
124
    ))),
125
    CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
126
        LayoutPaddingLeft {
127
            inner: PixelValue::const_px(3),
128
        },
129
    ))),
130
    CssPropertyWithConditions::simple(CssProperty::PaddingRight(LayoutPaddingRightValue::Exact(
131
        LayoutPaddingRight {
132
            inner: PixelValue::const_px(1),
133
        },
134
    ))),
135
    CssPropertyWithConditions::simple(CssProperty::PaddingBottom(LayoutPaddingBottomValue::Exact(
136
        LayoutPaddingBottom {
137
            inner: PixelValue::const_px(0),
138
        },
139
    ))),
140
    CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
141
        LayoutPaddingTop {
142
            inner: PixelValue::const_px(0),
143
        },
144
    ))),
145
];
146
const CSS_MATCH_4236783900531286611: CssPropertyWithConditionsVec =
147
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_4236783900531286611_PROPERTIES);
148

            
149
const CSS_MATCH_8602559445190067154_PROPERTIES: &[CssPropertyWithConditions] = &[
150
    // .__azul-native-frame
151
    CssPropertyWithConditions::simple(CssProperty::PaddingRight(LayoutPaddingRightValue::Exact(
152
        LayoutPaddingRight {
153
            inner: PixelValue::const_px(5),
154
        },
155
    ))),
156
    CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
157
        LayoutPaddingLeft {
158
            inner: PixelValue::const_px(5),
159
        },
160
    ))),
161
    CssPropertyWithConditions::simple(CssProperty::PaddingBottom(LayoutPaddingBottomValue::Exact(
162
        LayoutPaddingBottom {
163
            inner: PixelValue::const_px(3),
164
        },
165
    ))),
166
    CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
167
        LayoutPaddingTop {
168
            inner: PixelValue::const_px(3),
169
        },
170
    ))),
171
];
172
const CSS_MATCH_8602559445190067154: CssPropertyWithConditionsVec =
173
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_8602559445190067154_PROPERTIES);
174

            
175
const CSS_MATCH_9156589477016488419_PROPERTIES: &[CssPropertyWithConditions] = &[
176
    // A flex container: `flex-direction` / `justify-content` / `align-items`
177
    // below do nothing without it (this rule had none, so the box laid out as
178
    // a block and its children stacked vertically).
179
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
180
        LayoutDisplay::Flex,
181
    ))),
182
    // .__azul-native-frame .__azul-native-frame-header .__azul-native-frame-header-after div
183
    CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
184
        LayoutHeight::Px(PixelValue::const_px(8)),
185
    ))),
186
    CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
187
        LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
188
            inner: PixelValue::const_px(1),
189
        }),
190
    )),
191
    CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
192
        StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
193
            inner: BorderStyle::Solid,
194
        }),
195
    )),
196
    CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
197
        StyleBorderTopColorValue::Exact(StyleBorderTopColor {
198
            inner: BORDER_COLOR,
199
        }),
200
    )),
201
    CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
202
        LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
203
            inner: PixelValue::const_px(1),
204
        }),
205
    )),
206
    CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
207
        StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
208
            inner: BorderStyle::Solid,
209
        }),
210
    )),
211
    CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
212
        StyleBorderRightColorValue::Exact(StyleBorderRightColor {
213
            inner: BORDER_COLOR,
214
        }),
215
    )),
216
    // .__azul-native-frame .__azul-native-frame-header .__azul-native-frame-header-after
217
    CssPropertyWithConditions::simple(CssProperty::MarginTop(LayoutMarginTopValue::Exact(
218
        LayoutMarginTop {
219
            inner: PixelValue::const_px(6),
220
        },
221
    ))),
222
    CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
223
        LayoutFlexGrow {
224
            inner: FloatValue::const_new(1),
225
        },
226
    ))),
227
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
228
        LayoutFlexDirection::Column,
229
    ))),
230
];
231
const CSS_MATCH_9156589477016488419: CssPropertyWithConditionsVec =
232
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_9156589477016488419_PROPERTIES);
233

            
234
const CSS_MATCH_CONTENT_AREA_PROPERTIES: &[CssPropertyWithConditions] = &[
235
    // .__azul-native-frame .__azul-native-frame-content (static properties)
236
    CssPropertyWithConditions::simple(CssProperty::PaddingRight(LayoutPaddingRightValue::Exact(
237
        LayoutPaddingRight {
238
            inner: PixelValue::const_px(5),
239
        },
240
    ))),
241
    CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
242
        LayoutPaddingLeft {
243
            inner: PixelValue::const_px(5),
244
        },
245
    ))),
246
    CssPropertyWithConditions::simple(CssProperty::PaddingBottom(LayoutPaddingBottomValue::Exact(
247
        LayoutPaddingBottom {
248
            inner: PixelValue::const_px(5),
249
        },
250
    ))),
251
    CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
252
        LayoutPaddingTop {
253
            inner: PixelValue::const_px(5),
254
        },
255
    ))),
256
    CssPropertyWithConditions::simple(CssProperty::FontSize(StyleFontSizeValue::Exact(
257
        StyleFontSize {
258
            inner: PixelValue::const_px(11),
259
        },
260
    ))),
261
    CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
262
        StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_8122988506401935406_ITEMS),
263
    ))),
264
    CssPropertyWithConditions::simple(CssProperty::BorderBottomWidth(
265
        LayoutBorderBottomWidthValue::Exact(LayoutBorderBottomWidth {
266
            inner: PixelValue::const_px(1),
267
        }),
268
    )),
269
    CssPropertyWithConditions::simple(CssProperty::BorderLeftWidth(
270
        LayoutBorderLeftWidthValue::Exact(LayoutBorderLeftWidth {
271
            inner: PixelValue::const_px(1),
272
        }),
273
    )),
274
    CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
275
        LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
276
            inner: PixelValue::const_px(1),
277
        }),
278
    )),
279
    CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
280
        LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
281
            inner: PixelValue::const_px(1),
282
        }),
283
    )),
284
    CssPropertyWithConditions::simple(CssProperty::BorderBottomStyle(
285
        StyleBorderBottomStyleValue::Exact(StyleBorderBottomStyle {
286
            inner: BorderStyle::Solid,
287
        }),
288
    )),
289
    CssPropertyWithConditions::simple(CssProperty::BorderLeftStyle(
290
        StyleBorderLeftStyleValue::Exact(StyleBorderLeftStyle {
291
            inner: BorderStyle::Solid,
292
        }),
293
    )),
294
    CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
295
        StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
296
            inner: BorderStyle::Solid,
297
        }),
298
    )),
299
    CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
300
        StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
301
            inner: BorderStyle::Solid,
302
        }),
303
    )),
304
    CssPropertyWithConditions::simple(CssProperty::BorderBottomColor(
305
        StyleBorderBottomColorValue::Exact(StyleBorderBottomColor {
306
            inner: BORDER_COLOR,
307
        }),
308
    )),
309
    CssPropertyWithConditions::simple(CssProperty::BorderLeftColor(
310
        StyleBorderLeftColorValue::Exact(StyleBorderLeftColor {
311
            inner: BORDER_COLOR,
312
        }),
313
    )),
314
    CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
315
        StyleBorderRightColorValue::Exact(StyleBorderRightColor {
316
            inner: BORDER_COLOR,
317
        }),
318
    )),
319
    CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
320
        StyleBorderTopColorValue::Exact(StyleBorderTopColor {
321
            inner: BORDER_COLOR,
322
        }),
323
    )),
324
];
325

            
326
/// A titled border container widget, similar to an HTML `<fieldset>` or
327
/// a Windows group box. Displays a header with a centered title and a
328
/// bordered content area below.
329
#[derive(Debug, Clone)]
330
#[repr(C)]
331
pub struct Frame {
332
    pub title: AzString,
333
    pub flex_grow: f32,
334
    pub content: Dom,
335
}
336

            
337
impl Frame {
338
    /// Creates a new `Frame` with the given title and content DOM.
339
    #[must_use]
340
328
    pub const fn create(title: AzString, content: Dom) -> Self {
341
328
        Self {
342
328
            title,
343
328
            content,
344
328
            flex_grow: 0.0,
345
328
        }
346
328
    }
347

            
348
    /// Replaces `self` with a default frame and returns the original.
349
    #[must_use]
350
12
    pub const fn swap_with_default(&mut self) -> Self {
351
12
        let mut s = Self::create(AzString::from_const_str(""), Dom::create_div());
352
12
        core::mem::swap(&mut s, self);
353
12
        s
354
12
    }
355

            
356
    /// Sets the flex-grow factor for the content area.
357
295
    pub const fn set_flex_grow(&mut self, flex_grow: f32) {
358
295
        self.flex_grow = flex_grow;
359
295
    }
360

            
361
    /// Builder-style setter for the flex-grow factor.
362
    #[must_use]
363
252
    pub const fn with_flex_grow(mut self, flex_grow: f32) -> Self {
364
252
        self.set_flex_grow(flex_grow);
365
252
        self
366
252
    }
367

            
368
    #[must_use]
369
271
    pub fn dom(self) -> Dom {
370
271
        Dom::create_div()
371
271
            .with_css_props(CSS_MATCH_8602559445190067154)
372
271
            .with_ids_and_classes({
373
                const IDS_AND_CLASSES_14615537625743340639: &[IdOrClass] =
374
                    &[Class(AzString::from_const_str("__azul-native-frame"))];
375
271
                IdOrClassVec::from_const_slice(IDS_AND_CLASSES_14615537625743340639)
376
            })
377
271
            .with_children(DomVec::from_vec(vec![
378
271
                Dom::create_div()
379
271
                    .with_css_props(CSS_MATCH_16739370686243728873)
380
271
                    .with_ids_and_classes({
381
                        const IDS_AND_CLASSES_17776797146874875377: &[IdOrClass] = &[Class(
382
                            AzString::from_const_str("__azul-native-frame-header"),
383
                        )];
384
271
                        IdOrClassVec::from_const_slice(IDS_AND_CLASSES_17776797146874875377)
385
                    })
386
271
                    .with_children(DomVec::from_vec(vec![
387
271
                        Dom::create_div()
388
271
                            .with_css_props(CSS_MATCH_15775557796860201720)
389
271
                            .with_ids_and_classes({
390
                                const IDS_AND_CLASSES_15264202958442287530: &[IdOrClass] =
391
                                    &[Class(AzString::from_const_str(
392
                                        "__azul-native-frame-header-before",
393
                                    ))];
394
271
                                IdOrClassVec::from_const_slice(IDS_AND_CLASSES_15264202958442287530)
395
                            })
396
271
                            .with_children(DomVec::from_vec(vec![Dom::create_div()])),
397
271
                        crate::widgets::widget_p_with_text(self.title)
398
271
                            .with_css_props(CSS_MATCH_4236783900531286611),
399
271
                        Dom::create_div()
400
271
                            .with_css_props(CSS_MATCH_9156589477016488419)
401
271
                            .with_ids_and_classes({
402
                                const IDS_AND_CLASSES_5689091102265932280: &[IdOrClass] = &[Class(
403
                                    AzString::from_const_str("__azul-native-frame-header-after"),
404
                                )];
405
271
                                IdOrClassVec::from_const_slice(IDS_AND_CLASSES_5689091102265932280)
406
                            })
407
271
                            .with_children(DomVec::from_vec(vec![Dom::create_div()])),
408
                    ])),
409
271
                Dom::create_div()
410
271
                    .with_css_props({
411
271
                        let mut props = vec![CssPropertyWithConditions::simple(
412
271
                            CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(LayoutFlexGrow {
413
271
                                inner: FloatValue::new(self.flex_grow),
414
271
                            })),
415
                        )];
416
271
                        props.extend_from_slice(CSS_MATCH_CONTENT_AREA_PROPERTIES);
417
271
                        CssPropertyWithConditionsVec::from_vec(props)
418
                    })
419
271
                    .with_ids_and_classes({
420
                        const IDS_AND_CLASSES_9898887665724137124: &[IdOrClass] = &[Class(
421
                            AzString::from_const_str("__azul-native-frame-content"),
422
                        )];
423
271
                        IdOrClassVec::from_const_slice(IDS_AND_CLASSES_9898887665724137124)
424
                    })
425
271
                    .with_children(vec![self.content].into()),
426
            ]))
427
271
    }
428
}
429

            
430
#[cfg(test)]
431
#[allow(
432
    clippy::float_cmp,
433
    clippy::cast_precision_loss,
434
    clippy::unreadable_literal,
435
    clippy::too_many_lines
436
)]
437
mod autotest_generated {
438
    use std::collections::HashSet;
439

            
440
    use azul_core::dom::{NodeData, NodeType};
441

            
442
    use super::*;
443

            
444
    // ------------------------------------------------------------------
445
    // Helpers
446
    // ------------------------------------------------------------------
447

            
448
    /// Titles a caller can realistically hand to a frame: empty, an interior NUL,
449
    /// stacked combining marks, a ZWJ emoji sequence, an RTL override run and a
450
    /// replacement-char/BOM/control mix. The frame never parses or normalises its
451
    /// title — every one of these has to reach the DOM byte-for-byte.
452
    const ADVERSARIAL_TEXT: [&str; 6] = [
453
        "",
454
        "a\0b",
455
        "e\u{0301}\u{0301}\u{0301}",
456
        "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}",
457
        "\u{202E}gnirts desrever\u{202C}",
458
        "\u{FFFD}\u{FEFF}\t\n",
459
    ];
460

            
461
    /// Every f32 the numeric surface of `set_flex_grow` has to survive.
462
    /// `FloatValue::new` multiplies by 1000 and casts to `isize` — NaN, the
463
    /// infinities and `f32::MAX` all hit the saturating-cast path, and anything
464
    /// below 0.001 truncates away.
465
    const ADVERSARIAL_FLOATS: [f32; 14] = [
466
        0.0,
467
        -0.0,
468
        1.0,
469
        -1.0,
470
        0.001,
471
        -0.001,
472
        f32::EPSILON,
473
        f32::MIN_POSITIVE,
474
        -f32::MIN_POSITIVE,
475
        f32::MAX,
476
        f32::MIN,
477
        f32::INFINITY,
478
        f32::NEG_INFINITY,
479
        f32::NAN,
480
    ];
481

            
482
    /// A frame with the given title over the given content.
483
    fn frame(title: &str, content: Dom) -> Frame {
484
        Frame::create(AzString::from(title), content)
485
    }
486

            
487
    /// The frame `swap_with_default` leaves behind: empty title, empty div, no growth.
488
    fn default_frame() -> Frame {
489
        Frame::create(AzString::from_const_str(""), Dom::create_div())
490
    }
491

            
492
    fn kids(dom: &Dom) -> &[Dom] {
493
        dom.children.as_ref()
494
    }
495

            
496
    /// The header row (`.__azul-native-frame-header`).
497
    fn header(dom: &Dom) -> &Dom {
498
        &kids(dom)[0]
499
    }
500

            
501
    /// The bordered content area (`.__azul-native-frame-content`).
502
    fn content_area(dom: &Dom) -> &Dom {
503
        &kids(dom)[1]
504
    }
505

            
506
    /// The left rule of the header (`.__azul-native-frame-header-before`).
507
    fn rule_before(dom: &Dom) -> &Dom {
508
        &kids(header(dom))[0]
509
    }
510

            
511
    /// The title `<p>` box, wedged between the two header rules.
512
    fn title_node(dom: &Dom) -> &Dom {
513
        &kids(header(dom))[1]
514
    }
515

            
516
    /// The right rule of the header (`.__azul-native-frame-header-after`).
517
    fn rule_after(dom: &Dom) -> &Dom {
518
        &kids(header(dom))[2]
519
    }
520

            
521
    /// The declared properties of a node's inline style, in declaration order.
522
    fn props_of(node: &NodeData) -> Vec<CssProperty> {
523
        node.style
524
            .iter_inline_properties()
525
            .map(|(p, _)| p.clone())
526
            .collect()
527
    }
528

            
529
    fn inline_props(dom: &Dom) -> Vec<CssProperty> {
530
        props_of(&dom.root)
531
    }
532

            
533
    /// The properties of a build-time constant, in declaration order.
534
    fn declared(v: &[CssPropertyWithConditions]) -> Vec<CssProperty> {
535
        v.iter().map(|p| p.property.clone()).collect()
536
    }
537

            
538
    /// The CSS classes of a node, in declaration order.
539
    fn classes(dom: &Dom) -> Vec<String> {
540
        dom.root
541
            .get_ids_and_classes()
542
            .as_ref()
543
            .iter()
544
            .filter_map(|c| match c {
545
                Class(s) => Some(s.as_str().to_string()),
546
                IdOrClass::Id(_) => None,
547
            })
548
            .collect()
549
    }
550

            
551
    /// The text of a text node, looking through the `<p>` block wrapper the
552
    /// label convention mandates (`p > text`).
553
    fn text_of(dom: &Dom) -> Option<&str> {
554
        match dom.root.get_node_type() {
555
            NodeType::Text(s) => Some(s.as_ref().as_str()),
556
            NodeType::P => match dom.children.as_ref() {
557
                [only] => match only.root.get_node_type() {
558
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
559
                    _ => None,
560
                },
561
                _ => None,
562
            },
563
            _ => None,
564
        }
565
    }
566

            
567
    /// The `flex-grow` factor as it actually lands in a node's style — i.e. *after*
568
    /// the lossy `f32 -> isize` encoding inside `FloatValue::new`.
569
    fn flex_grow_of(dom: &Dom) -> Option<f32> {
570
        dom.root
571
            .style
572
            .iter_inline_properties()
573
            .find_map(|(p, _)| match p {
574
                CssProperty::FlexGrow(v) => v.get_property().map(|f| f.inner.get()),
575
                _ => None,
576
            })
577
    }
578

            
579
    /// The `flex-grow` of the content area — the only place the caller's factor
580
    /// is allowed to surface.
581
    fn content_flex_grow(dom: &Dom) -> Option<f32> {
582
        flex_grow_of(content_area(dom))
583
    }
584

            
585
    fn count_flex_grow(dom: &Dom) -> usize {
586
        inline_props(dom)
587
            .iter()
588
            .filter(|p| matches!(p, CssProperty::FlexGrow(_)))
589
            .count()
590
    }
591

            
592
    /// The `f32` of a `PixelValue`, asserting the length is an absolute `px`. An
593
    /// `em`/`%` slipping into the frame chrome would resolve against the parent
594
    /// font/box instead of staying a fixed border, padding or rule size.
595
    fn px(pv: &PixelValue) -> f32 {
596
        assert_eq!(
597
            pv.metric,
598
            SizeMetric::Px,
599
            "frame geometry must be absolute px, got {:?}",
600
            pv.metric
601
        );
602
        pv.number.get()
603
    }
604

            
605
    /// The length a property declares, if it declares one at all.
606
    fn length_of(p: &CssProperty) -> Option<PixelValue> {
607
        match p {
608
            CssProperty::Height(v) => match v.get_property() {
609
                Some(LayoutHeight::Px(pv)) => Some(*pv),
610
                _ => None,
611
            },
612
            CssProperty::Width(v) => match v.get_property() {
613
                Some(LayoutWidth::Px(pv)) => Some(*pv),
614
                _ => None,
615
            },
616
            CssProperty::FontSize(v) => v.get_property().map(|x| x.inner),
617
            CssProperty::MarginTop(v) => v.get_property().map(|x| x.inner),
618
            CssProperty::PaddingTop(v) => v.get_property().map(|x| x.inner),
619
            CssProperty::PaddingBottom(v) => v.get_property().map(|x| x.inner),
620
            CssProperty::PaddingLeft(v) => v.get_property().map(|x| x.inner),
621
            CssProperty::PaddingRight(v) => v.get_property().map(|x| x.inner),
622
            CssProperty::BorderTopWidth(v) => v.get_property().map(|x| x.inner),
623
            CssProperty::BorderBottomWidth(v) => v.get_property().map(|x| x.inner),
624
            CssProperty::BorderLeftWidth(v) => v.get_property().map(|x| x.inner),
625
            CssProperty::BorderRightWidth(v) => v.get_property().map(|x| x.inner),
626
            _ => None,
627
        }
628
    }
629

            
630
    /// The border colour a property declares, if it declares one at all.
631
    fn border_color_of(p: &CssProperty) -> Option<ColorU> {
632
        match p {
633
            CssProperty::BorderTopColor(v) => v.get_property().map(|x| x.inner),
634
            CssProperty::BorderBottomColor(v) => v.get_property().map(|x| x.inner),
635
            CssProperty::BorderLeftColor(v) => v.get_property().map(|x| x.inner),
636
            CssProperty::BorderRightColor(v) => v.get_property().map(|x| x.inner),
637
            _ => None,
638
        }
639
    }
640

            
641
    fn walk<'a>(dom: &'a Dom, out: &mut Vec<&'a Dom>) {
642
        out.push(dom);
643
        for c in dom.children.as_ref() {
644
            walk(c, out);
645
        }
646
    }
647

            
648
    /// Every node of the tree, root first.
649
    fn all_nodes(dom: &Dom) -> Vec<&Dom> {
650
        let mut v = Vec::new();
651
        walk(dom, &mut v);
652
        v
653
    }
654

            
655
    /// The recursive descendant count. `Dom::estimated_total_children` is a
656
    /// *cached* value that, if too small, makes `convert_dom_into_compact_dom`
657
    /// under-allocate its arenas and panic on out-of-bounds writes — so it has to
658
    /// match this exactly.
659
    fn count_descendants(dom: &Dom) -> usize {
660
        dom.children
661
            .as_ref()
662
            .iter()
663
            .map(|c| 1 + count_descendants(c))
664
            .sum()
665
    }
666

            
667
    /// A chain of `depth` nested divs (depth kept modest: `Dom`'s `Drop`/`PartialEq`
668
    /// recurse).
669
    fn nested_divs(depth: usize) -> Dom {
670
        let mut d = Dom::create_div();
671
        for _ in 0..depth {
672
            d = Dom::create_div().with_child(d);
673
        }
674
        d
675
    }
676

            
677
    // ------------------------------------------------------------------
678
    // Frame::create
679
    // ------------------------------------------------------------------
680

            
681
    #[test]
682
    fn create_zeroes_flex_grow_and_stores_both_arguments_verbatim() {
683
        let f = frame(
684
            "Settings",
685
            Dom::create_text_do_not_use_without_block_level_wrapper("body"),
686
        );
687

            
688
        // Positive zero, not -0.0: a negative zero would flip the sign of the encoded
689
        // isize on some paths and is not what "no growth" means.
690
        assert_eq!(f.flex_grow.to_bits(), 0_u32, "flex_grow must start at +0.0");
691
        assert_eq!(
692
            f.title.as_str(),
693
            "Settings",
694
            "the title was not stored verbatim"
695
        );
696
        assert_eq!(
697
            text_of(&f.content),
698
            Some("body"),
699
            "the content was not stored verbatim",
700
        );
701
    }
702

            
703
    #[test]
704
    fn create_stores_pathological_titles_byte_for_byte() {
705
        for t in ADVERSARIAL_TEXT {
706
            let f = frame(t, Dom::create_div());
707
            assert_eq!(
708
                f.title.as_str(),
709
                t,
710
                "the frame mangled or normalised its title"
711
            );
712
            assert_eq!(
713
                f.title.as_str().len(),
714
                t.len(),
715
                "the byte length of the title changed (NUL truncation or re-encoding?)",
716
            );
717

            
718
            // ... and it survives the trip into the rendered DOM.
719
            let dom = f.dom();
720
            assert_eq!(
721
                text_of(title_node(&dom)),
722
                Some(t),
723
                "the title was corrupted on the way into the DOM",
724
            );
725
        }
726
    }
727

            
728
    #[test]
729
    fn create_accepts_a_very_long_title_without_truncating_it() {
730
        // 100k astral-plane chars: 400 KB of UTF-8 through the AzString/BoxOrStatic path.
731
        let huge: String = "\u{1F600}".repeat(100_000);
732
        let f = frame(&huge, Dom::create_div());
733
        assert_eq!(
734
            f.title.as_str().len(),
735
            400_000,
736
            "the long title was truncated on store"
737
        );
738

            
739
        let dom = f.dom();
740
        assert_eq!(
741
            text_of(title_node(&dom)).map(str::len),
742
            Some(400_000),
743
            "the long title was truncated on the way into the DOM",
744
        );
745
    }
746

            
747
    #[test]
748
    fn create_accepts_deeply_nested_and_very_wide_content() {
749
        let deep = frame("deep", nested_divs(64)).dom();
750
        assert_eq!(
751
            deep.estimated_total_children,
752
            count_descendants(&deep),
753
            "the cached child count desynced for deeply nested content",
754
        );
755
        assert_eq!(
756
            deep.estimated_total_children,
757
            9 + 64,
758
            "frame chrome is 8 nodes + the content"
759
        );
760

            
761
        let wide = frame(
762
            "wide",
763
            Dom::create_div().with_children(
764
                (0..2000)
765
                    .map(|_| Dom::create_div())
766
                    .collect::<Vec<_>>()
767
                    .into(),
768
            ),
769
        )
770
        .dom();
771
        assert_eq!(
772
            wide.estimated_total_children,
773
            count_descendants(&wide),
774
            "the cached child count desynced for very wide content",
775
        );
776
        assert_eq!(wide.estimated_total_children, 9 + 2000);
777
    }
778

            
779
    #[test]
780
    fn frames_nest_without_desyncing_the_child_count_cache() {
781
        let inner = frame("inner", Dom::create_div()).dom();
782
        assert_eq!(
783
            inner.estimated_total_children, 9,
784
            "a bare frame is 9 nodes below the root"
785
        );
786

            
787
        let outer = frame("outer", inner).dom();
788
        assert_eq!(
789
            outer.estimated_total_children,
790
            count_descendants(&outer),
791
            "nesting a frame inside a frame desynced the cached child count",
792
        );
793
        assert_eq!(outer.estimated_total_children, 18);
794
    }
795

            
796
    // ------------------------------------------------------------------
797
    // Frame::swap_with_default
798
    // ------------------------------------------------------------------
799

            
800
    #[test]
801
    fn swap_with_default_moves_every_field_out_and_leaves_a_default() {
802
        let mut f = frame(
803
            "payload",
804
            Dom::create_text_do_not_use_without_block_level_wrapper("body"),
805
        )
806
        .with_flex_grow(2.5);
807

            
808
        let taken = f.swap_with_default();
809

            
810
        assert_eq!(
811
            taken.title.as_str(),
812
            "payload",
813
            "the title did not travel out"
814
        );
815
        assert_eq!(
816
            text_of(&taken.content),
817
            Some("body"),
818
            "the content did not travel out"
819
        );
820
        assert_eq!(taken.flex_grow, 2.5, "flex_grow did not travel out");
821

            
822
        assert_eq!(f.title.as_str(), "", "the swapped-in default kept a title");
823
        assert_eq!(
824
            f.content,
825
            Dom::create_div(),
826
            "the swapped-in default is not an empty div"
827
        );
828
        assert_eq!(
829
            f.flex_grow.to_bits(),
830
            0_u32,
831
            "the swapped-in default has a non-zero flex_grow",
832
        );
833
    }
834

            
835
    #[test]
836
    fn repeated_swap_with_default_never_accumulates_state() {
837
        let mut f = frame(
838
            "x",
839
            Dom::create_text_do_not_use_without_block_level_wrapper("y"),
840
        )
841
        .with_flex_grow(1.0);
842
        let first = f.swap_with_default();
843
        assert_eq!(first.title.as_str(), "x");
844

            
845
        for i in 0..8 {
846
            let taken = f.swap_with_default();
847
            assert_eq!(
848
                taken.title.as_str(),
849
                "",
850
                "swap #{i} handed back a non-default title"
851
            );
852
            assert_eq!(
853
                taken.content,
854
                Dom::create_div(),
855
                "swap #{i} handed back non-default content"
856
            );
857
            assert_eq!(
858
                taken.flex_grow.to_bits(),
859
                0_u32,
860
                "swap #{i} handed back a non-zero factor"
861
            );
862
            assert_eq!(
863
                f.title.as_str(),
864
                "",
865
                "swap #{i} left a non-default title behind"
866
            );
867
        }
868

            
869
        // The DOM of the drained frame is still a well-formed, empty-titled frame.
870
        let dom = f.dom();
871
        assert_eq!(kids(&dom).len(), 2);
872
        assert_eq!(text_of(title_node(&dom)), Some(""));
873
        assert_eq!(content_flex_grow(&dom), Some(0.0));
874
    }
875

            
876
    #[test]
877
    fn swap_with_default_preserves_a_nan_factor_in_the_value_it_hands_back() {
878
        // The setter never sanitises, so a NaN has to survive the swap unchanged —
879
        // only the *encoding* into the DOM is allowed to collapse it (see below).
880
        let mut f = default_frame().with_flex_grow(f32::NAN);
881
        let taken = f.swap_with_default();
882
        assert!(
883
            taken.flex_grow.is_nan(),
884
            "the NaN factor was rewritten by the swap"
885
        );
886
        assert_eq!(
887
            f.flex_grow.to_bits(),
888
            0_u32,
889
            "the NaN leaked into the swapped-in default"
890
        );
891
    }
892

            
893
    #[test]
894
    fn swap_with_default_leaves_a_frame_that_still_renders() {
895
        // Guards against the swapped-in default sharing/aliasing the moved-out DOM:
896
        // both halves have to render independently, in either order.
897
        let mut f = frame("original", nested_divs(8));
898
        let taken = f.swap_with_default();
899

            
900
        let left_behind = f.dom();
901
        let moved_out = taken.dom();
902

            
903
        assert_eq!(text_of(title_node(&left_behind)), Some(""));
904
        assert_eq!(text_of(title_node(&moved_out)), Some("original"));
905
        assert_eq!(left_behind.estimated_total_children, 9);
906
        assert_eq!(moved_out.estimated_total_children, 9 + 8);
907
    }
908

            
909
    // ------------------------------------------------------------------
910
    // Frame::set_flex_grow / Frame::with_flex_grow  (numeric)
911
    // ------------------------------------------------------------------
912

            
913
    #[test]
914
    fn set_flex_grow_stores_the_bit_pattern_verbatim_without_sanitising() {
915
        // The setter is a plain assignment — it must not clamp, round or NaN-scrub.
916
        // (Sanitisation happens later, at encode time; see the tests below.)
917
        for v in ADVERSARIAL_FLOATS {
918
            let mut f = default_frame();
919
            f.set_flex_grow(v);
920
            if v.is_nan() {
921
                assert!(
922
                    f.flex_grow.is_nan(),
923
                    "a NaN flex_grow was silently rewritten"
924
                );
925
            } else {
926
                assert_eq!(
927
                    f.flex_grow.to_bits(),
928
                    v.to_bits(),
929
                    "flex_grow {v} was not stored verbatim",
930
                );
931
            }
932
        }
933
    }
934

            
935
    #[test]
936
    fn set_flex_grow_is_last_write_wins() {
937
        let mut f = default_frame();
938
        for v in ADVERSARIAL_FLOATS {
939
            f.set_flex_grow(v);
940
        }
941
        assert!(f.flex_grow.is_nan(), "the final write (NaN) did not win");
942

            
943
        f.set_flex_grow(1.5);
944
        assert_eq!(f.flex_grow, 1.5, "a later write did not overwrite the NaN");
945
        assert_eq!(
946
            count_flex_grow(content_area(&f.dom())),
947
            1,
948
            "flex-grow was declared twice"
949
        );
950
    }
951

            
952
    #[test]
953
    fn with_flex_grow_is_exactly_set_flex_grow() {
954
        for v in ADVERSARIAL_FLOATS {
955
            let mut by_setter = default_frame();
956
            by_setter.set_flex_grow(v);
957
            let by_builder = default_frame().with_flex_grow(v);
958

            
959
            assert_eq!(
960
                by_setter.flex_grow.to_bits(),
961
                by_builder.flex_grow.to_bits(),
962
                "the builder and the setter disagree for {v}",
963
            );
964
        }
965
    }
966

            
967
    #[test]
968
    fn with_flex_grow_touches_only_the_numeric_field() {
969
        let f = frame(
970
            "title",
971
            Dom::create_text_do_not_use_without_block_level_wrapper("body"),
972
        )
973
        .with_flex_grow(f32::NAN);
974

            
975
        assert_eq!(
976
            f.title.as_str(),
977
            "title",
978
            "with_flex_grow clobbered the title"
979
        );
980
        assert_eq!(
981
            text_of(&f.content),
982
            Some("body"),
983
            "with_flex_grow clobbered the content"
984
        );
985
    }
986

            
987
    #[test]
988
    fn flex_grow_zero_encodes_to_positive_zero_even_from_negative_zero() {
989
        for v in [0.0_f32, -0.0_f32] {
990
            let dom = default_frame().with_flex_grow(v).dom();
991
            let got = content_flex_grow(&dom).expect("flex-grow must always be declared");
992
            assert_eq!(
993
                got.to_bits(),
994
                0_u32,
995
                "flex_grow {v} did not encode to +0.0 (got {got})"
996
            );
997
        }
998
    }
999

            
    #[test]
    fn flex_grow_round_trips_through_the_dom_at_milli_precision() {
        // FloatValue keeps 3 decimal places (x1000, truncating cast), so any factor that
        // is a whole multiple of 0.001 must come back out of the DOM unchanged.
        for v in [0.0_f32, 0.001, 0.5, 1.0, 2.5, 3.0, -1.5, 1000.0, 65536.0] {
            let got = content_flex_grow(&default_frame().with_flex_grow(v).dom())
                .expect("flex-grow must always be declared");
            assert!(
                (got - v).abs() <= 0.001,
                "flex_grow {v} did not survive the FloatValue encoding (got {got})",
            );
        }
    }
    #[test]
    fn flex_grow_below_the_encoding_precision_truncates_to_zero() {
        // Everything under one milli-unit is quantised away — including the sign, because
        // the truncating cast of -0.0001 * 1000 = -0.1 lands on integer 0.
        for v in [
            f32::EPSILON,
            f32::MIN_POSITIVE,
            -f32::MIN_POSITIVE,
            1e-4,
            -1e-4,
            0.0005,
            -0.0009,
        ] {
            let got = content_flex_grow(&default_frame().with_flex_grow(v).dom())
                .expect("flex-grow must always be declared");
            assert_eq!(
                got.to_bits(),
                0_u32,
                "sub-milli flex_grow {v} did not truncate to +0.0 (got {got})",
            );
        }
        // ... and 0.001 is genuinely the smallest factor that still registers.
        let smallest = content_flex_grow(&default_frame().with_flex_grow(0.001).dom()).unwrap();
        assert!(
            smallest > 0.0,
            "0.001 is supposed to be the smallest representable factor"
        );
    }
    #[test]
    fn a_nan_flex_grow_does_not_panic_and_lands_on_zero() {
        let dom = default_frame().with_flex_grow(f32::NAN).dom();
        let got = content_flex_grow(&dom).expect("flex-grow must always be declared");
        assert!(!got.is_nan(), "a NaN flex-grow reached the style tree");
        assert_eq!(
            got.to_bits(),
            0_u32,
            "NaN must encode to +0.0 (saturating cast), got {got}"
        );
    }
    #[test]
    fn infinite_and_maximal_flex_grow_saturates_instead_of_overflowing() {
        // `FloatValue::new` does `(v * 1000.0) as isize`; f32::MAX * 1000 already overflows
        // to +inf, so MAX and INFINITY have to land on the same saturated bound. The point
        // is that nothing wraps around into a factor of the opposite sign.
        let max_encoded = (isize::MAX as f32) / 1000.0;
        let min_encoded = (isize::MIN as f32) / 1000.0;
        for v in [f32::INFINITY, f32::MAX] {
            let got = content_flex_grow(&default_frame().with_flex_grow(v).dom()).unwrap();
            assert!(
                got.is_finite(),
                "an infinite flex-grow reached the style tree for {v}"
            );
            assert_eq!(
                got, max_encoded,
                "{v} did not saturate at the isize upper bound"
            );
            assert!(got > 0.0, "{v} wrapped around into a non-positive factor");
        }
        for v in [f32::NEG_INFINITY, f32::MIN] {
            let got = content_flex_grow(&default_frame().with_flex_grow(v).dom()).unwrap();
            assert!(
                got.is_finite(),
                "an infinite flex-grow reached the style tree for {v}"
            );
            assert_eq!(
                got, min_encoded,
                "{v} did not saturate at the isize lower bound"
            );
            assert!(got < 0.0, "{v} wrapped around into a non-negative factor");
        }
    }
    #[test]
    fn no_flex_grow_input_can_put_a_nan_or_an_infinity_into_the_style_tree() {
        for v in ADVERSARIAL_FLOATS {
            let dom = default_frame().with_flex_grow(v).dom();
            let got = content_flex_grow(&dom)
                .unwrap_or_else(|| panic!("flex-grow disappeared for input {v}"));
            assert!(
                got.is_finite(),
                "input {v} produced a non-finite flex-grow ({got}) — the layout solver would NaN \
                 out",
            );
        }
    }
    #[test]
    fn flex_grow_encoding_is_monotonic() {
        // A sign- or rounding-bug in the x1000 cast would show up as an inversion here.
        let ascending = [-1000.0_f32, -1.5, -0.001, 0.0, 0.001, 1.5, 1000.0];
        let mut prev = f32::NEG_INFINITY;
        for v in ascending {
            let got = content_flex_grow(&default_frame().with_flex_grow(v).dom()).unwrap();
            assert!(
                got >= prev,
                "encoding is not monotonic: {v} encoded to {got}, below the previous {prev}",
            );
            prev = got;
        }
    }
    #[test]
    fn the_callers_factor_only_ever_reaches_the_content_area() {
        // The two header rules carry a *fixed* flex-grow of 1 so they split the leftover
        // header width evenly; a caller's factor bleeding into them would collapse or
        // stretch the rules on either side of the title.
        for v in ADVERSARIAL_FLOATS {
            let dom = default_frame().with_flex_grow(v).dom();
            assert_eq!(
                count_flex_grow(&dom),
                0,
                "the frame root declared a flex-grow"
            );
            assert_eq!(
                count_flex_grow(header(&dom)),
                0,
                "the header declared a flex-grow"
            );
            assert_eq!(
                count_flex_grow(title_node(&dom)),
                0,
                "the title declared a flex-grow"
            );
            assert_eq!(
                flex_grow_of(rule_before(&dom)),
                Some(1.0),
                "left rule factor changed"
            );
            assert_eq!(
                flex_grow_of(rule_after(&dom)),
                Some(1.0),
                "right rule factor changed"
            );
            assert_eq!(
                count_flex_grow(content_area(&dom)),
                1,
                "the content area must declare flex-grow exactly once",
            );
        }
    }
    // ------------------------------------------------------------------
    // Frame::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_has_the_documented_shape() {
        let dom = frame(
            "Title",
            Dom::create_text_do_not_use_without_block_level_wrapper("content"),
        )
        .dom();
        assert_eq!(
            kids(&dom).len(),
            2,
            "a frame is a header plus a content area"
        );
        assert_eq!(
            kids(header(&dom)).len(),
            3,
            "the header is rule / title / rule"
        );
        assert_eq!(
            kids(rule_before(&dom)).len(),
            1,
            "the left rule wraps exactly one div"
        );
        assert_eq!(
            kids(rule_after(&dom)).len(),
            1,
            "the right rule wraps exactly one div"
        );
        assert_eq!(
            kids(title_node(&dom)).len(),
            1,
            "the title is a <p> wrapping exactly one bare text node"
        );
        assert!(
            kids(&kids(title_node(&dom))[0]).is_empty(),
            "the text node itself must be a leaf"
        );
        assert_eq!(
            kids(content_area(&dom)).len(),
            1,
            "the content area holds exactly one child"
        );
        assert_eq!(text_of(title_node(&dom)), Some("Title"));
        assert_eq!(text_of(&kids(content_area(&dom))[0]), Some("content"));
        assert_eq!(dom.estimated_total_children, count_descendants(&dom));
    }
    #[test]
    fn an_empty_title_still_produces_a_text_node_between_the_two_rules() {
        // Dropping the node for an empty title would change the header's flex layout
        // (two rules instead of three items) and silently re-centre the rules.
        let dom = default_frame().dom();
        assert_eq!(
            kids(header(&dom)).len(),
            3,
            "an empty title collapsed the header"
        );
        assert_eq!(
            text_of(title_node(&dom)),
            Some(""),
            "the empty title node vanished"
        );
    }
    #[test]
    fn dom_carries_every_class_the_stylesheet_selects_on() {
        let dom = frame("t", Dom::create_div()).dom();
        assert_eq!(classes(&dom), vec!["__azul-native-frame".to_string()]);
        assert_eq!(
            classes(header(&dom)),
            vec!["__azul-native-frame-header".to_string()]
        );
        assert_eq!(
            classes(rule_before(&dom)),
            vec!["__azul-native-frame-header-before".to_string()],
        );
        assert_eq!(
            classes(rule_after(&dom)),
            vec!["__azul-native-frame-header-after".to_string()],
        );
        assert_eq!(
            classes(content_area(&dom)),
            vec!["__azul-native-frame-content".to_string()]
        );
        // The title node and the two inner rule divs are addressed by element/descendant
        // selectors only — they carry no class of their own.
        assert!(
            classes(title_node(&dom)).is_empty(),
            "the title node grew a class"
        );
        assert!(classes(&kids(rule_before(&dom))[0]).is_empty());
        assert!(classes(&kids(rule_after(&dom))[0]).is_empty());
    }
    #[test]
    fn dom_declares_exactly_the_build_time_constants_on_the_chrome_nodes() {
        let dom = frame("t", Dom::create_div()).dom();
        assert_eq!(
            inline_props(&dom),
            declared(CSS_MATCH_8602559445190067154.as_ref())
        );
        assert_eq!(
            inline_props(header(&dom)),
            declared(CSS_MATCH_16739370686243728873.as_ref())
        );
        assert_eq!(
            inline_props(rule_before(&dom)),
            declared(CSS_MATCH_15775557796860201720.as_ref()),
        );
        assert_eq!(
            inline_props(rule_after(&dom)),
            declared(CSS_MATCH_9156589477016488419.as_ref()),
        );
        assert_eq!(
            inline_props(title_node(&dom)),
            declared(CSS_MATCH_4236783900531286611.as_ref())
        );
    }
    #[test]
    fn the_content_area_declares_flex_grow_first_then_the_static_block_verbatim() {
        let dom = default_frame().with_flex_grow(2.5).dom();
        let mut expected = vec![CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
            LayoutFlexGrow {
                inner: FloatValue::new(2.5),
            },
        ))];
        expected.extend(declared(CSS_MATCH_CONTENT_AREA_PROPERTIES));
        assert_eq!(
            inline_props(content_area(&dom)),
            expected,
            "the content-area style block drifted from FlexGrow + the static constant",
        );
    }
    #[test]
    fn no_node_declares_the_same_property_twice() {
        // A duplicate declaration means one of the two is silently dead — and which one
        // wins depends on cascade order, so the widget would style differently per node.
        let dom = frame("t", Dom::create_div()).with_flex_grow(1.0).dom();
        for (i, node) in all_nodes(&dom).into_iter().enumerate() {
            let props = inline_props(node);
            let mut seen = HashSet::new();
            for p in &props {
                assert!(
                    seen.insert(p.get_type()),
                    "node {i} declares {:?} twice",
                    p.get_type(),
                );
            }
        }
    }
    #[test]
    fn every_declaration_is_unconditional() {
        // The frame chrome has no :hover/@media/@os variants — a stray condition would
        // make part of the border render only in one state.
        let dom = frame("t", Dom::create_div()).dom();
        for (i, node) in all_nodes(&dom).into_iter().enumerate() {
            for (p, conditions) in node.root.style.iter_inline_properties() {
                assert!(
                    conditions.as_ref().is_empty(),
                    "node {i} gates {:?} behind a dynamic selector",
                    p.get_type(),
                );
            }
        }
    }
    #[test]
    fn all_frame_lengths_are_absolute_px() {
        let dom = frame("t", Dom::create_div()).dom();
        for node in all_nodes(&dom) {
            for p in inline_props(node) {
                if let Some(pv) = length_of(&p) {
                    let v = px(&pv); // asserts SizeMetric::Px
                    assert!(
                        v.is_finite() && (0.0..=64.0).contains(&v),
                        "{:?} = {v}px is outside the plausible frame-chrome range",
                        p.get_type(),
                    );
                }
            }
        }
    }
    #[test]
    fn every_border_in_the_frame_uses_the_one_border_colour() {
        let dom = frame("t", Dom::create_div()).dom();
        let mut seen = 0_usize;
        for node in all_nodes(&dom) {
            for p in inline_props(node) {
                if let Some(c) = border_color_of(&p) {
                    assert_eq!(
                        c,
                        BORDER_COLOR,
                        "{:?} uses an off-palette colour",
                        p.get_type()
                    );
                    seen += 1;
                }
            }
        }
        // top+left on the left rule, top+right on the right rule, all four on the content
        // area.
        assert_eq!(
            seen, 8,
            "the number of coloured borders in the frame changed"
        );
    }
    #[test]
    fn the_content_area_is_fully_boxed_in_on_all_four_sides() {
        // A missing side would leave the group box visibly open.
        let props = inline_props(content_area(&frame("t", Dom::create_div()).dom()));
        let widths = [
            CssPropertyType::BorderTopWidth,
            CssPropertyType::BorderBottomWidth,
            CssPropertyType::BorderLeftWidth,
            CssPropertyType::BorderRightWidth,
        ];
        for want in widths {
            let found = props
                .iter()
                .find(|p| p.get_type() == want)
                .unwrap_or_else(|| panic!("the content area is missing {want:?}"));
            assert_eq!(
                length_of(found).map(|pv| px(&pv)),
                Some(1.0),
                "{want:?} is not a 1px hairline",
            );
        }
    }
    #[test]
    fn the_two_header_rules_are_symmetric_apart_from_the_left_rule_carrying_a_width() {
        // Pinned as-is: `.__azul-native-frame-header-before` declares `width: 5px` while
        // `-after` declares no width at all, so the stub of rule left of the title is
        // capped at 5px while the right-hand rule is only bounded by flex-grow. This is
        // an asymmetry in the widget's style constants, not in the code under test —
        // recorded here so a deliberate change to either side shows up as a failure.
        let dom = frame("t", Dom::create_div()).dom();
        let before: Vec<CssPropertyType> = inline_props(rule_before(&dom))
            .iter()
            .map(CssProperty::get_type)
            .collect();
        let after: Vec<CssPropertyType> = inline_props(rule_after(&dom))
            .iter()
            .map(CssProperty::get_type)
            .collect();
        assert!(
            before.contains(&CssPropertyType::Width),
            "the left rule lost its width cap"
        );
        assert!(
            !after.contains(&CssPropertyType::Width),
            "the right rule gained a width — the known before/after asymmetry was fixed, update \
             this test",
        );
        // Mirrored side: left draws a left border, right draws a right border.
        assert!(before.contains(&CssPropertyType::BorderLeftWidth));
        assert!(after.contains(&CssPropertyType::BorderRightWidth));
        // Everything else is shared, in the same order.
        for shared in [
            CssPropertyType::Height,
            CssPropertyType::BorderTopWidth,
            CssPropertyType::BorderTopStyle,
            CssPropertyType::BorderTopColor,
            CssPropertyType::MarginTop,
            CssPropertyType::FlexGrow,
            CssPropertyType::FlexDirection,
        ] {
            assert!(
                before.contains(&shared),
                "the left rule is missing {shared:?}"
            );
            assert!(
                after.contains(&shared),
                "the right rule is missing {shared:?}"
            );
        }
    }
    #[test]
    fn the_inner_rule_divs_carry_no_style_of_their_own() {
        // Pinned as-is: the constants comment their `... -header-before div` properties
        // (height + borders) separately from the container's, but both blocks are applied
        // to the *container* — the inner div is an unstyled, empty leaf. Recorded so that
        // re-splitting the two selectors shows up here instead of silently changing the
        // rendered header.
        let dom = frame("t", Dom::create_div()).dom();
        for inner in [&kids(rule_before(&dom))[0], &kids(rule_after(&dom))[0]] {
            assert!(
                inline_props(inner).is_empty(),
                "the inner rule div grew inline properties",
            );
            assert!(kids(inner).is_empty(), "the inner rule div grew children");
            assert_eq!(inner.root.get_node_type(), &NodeType::Div);
        }
        // ... and the height/border pair really does sit on the containers.
        for outer in [rule_before(&dom), rule_after(&dom)] {
            let types: Vec<CssPropertyType> = inline_props(outer)
                .iter()
                .map(CssProperty::get_type)
                .collect();
            assert!(types.contains(&CssPropertyType::Height));
            assert!(types.contains(&CssPropertyType::BorderTopWidth));
        }
    }
    #[test]
    fn the_frame_is_inert_and_attaches_no_callbacks_or_stylesheets() {
        let dom = frame("t", Dom::create_div()).with_flex_grow(1.0).dom();
        for (i, node) in all_nodes(&dom).into_iter().enumerate() {
            assert!(
                node.root.callbacks.as_ref().is_empty(),
                "node {i} of a stateless frame carries a callback",
            );
            // A <p> carries the UA-margin reset sheet (`widget_p_margin_reset`);
            // nothing else in a frame attaches a stylesheet.
            let is_p = matches!(node.root.get_node_type(), azul_core::dom::NodeType::P);
            assert!(
                node.css.as_ref().is_empty() || (is_p && node.css.as_ref().len() == 1),
                "node {i} attached a whole stylesheet instead of inline props",
            );
        }
    }
    #[test]
    fn dom_moves_the_content_in_verbatim_including_its_own_classes_and_children() {
        let content = Dom::create_div()
            .with_ids_and_classes(IdOrClassVec::from_vec(vec![Class(AzString::from(
                "user-content",
            ))]))
            .with_children(DomVec::from_vec(vec![
                Dom::create_text_do_not_use_without_block_level_wrapper("a"),
                Dom::create_text_do_not_use_without_block_level_wrapper("b"),
            ]));
        let expected = content.clone();
        let dom = frame("t", content).dom();
        let placed = &kids(content_area(&dom))[0];
        assert_eq!(
            *placed, expected,
            "the content DOM was rewritten on the way in"
        );
        assert_eq!(classes(placed), vec!["user-content".to_string()]);
        assert_eq!(kids(placed).len(), 2);
    }
    #[test]
    fn dom_is_deterministic_for_equal_inputs() {
        for t in ADVERSARIAL_TEXT {
            for v in ADVERSARIAL_FLOATS {
                let a = frame(
                    t,
                    Dom::create_text_do_not_use_without_block_level_wrapper(t),
                )
                .with_flex_grow(v)
                .dom();
                let b = frame(
                    t,
                    Dom::create_text_do_not_use_without_block_level_wrapper(t),
                )
                .with_flex_grow(v)
                .dom();
                assert_eq!(
                    a, b,
                    "two identical frames rendered differently for {t:?} / {v}"
                );
            }
        }
    }
    #[test]
    fn distinct_factors_that_encode_differently_produce_distinct_doms() {
        // The counterpart to the determinism test: the flex factor must actually reach
        // the tree, so a change in it has to be observable in the rendered DOM.
        let a = default_frame().with_flex_grow(1.0).dom();
        let b = default_frame().with_flex_grow(2.0).dom();
        assert_ne!(a, b, "the flex factor never reached the rendered DOM");
        // ... while two factors that collapse to the same encoding are indistinguishable.
        let nan = default_frame().with_flex_grow(f32::NAN).dom();
        let zero = default_frame().with_flex_grow(0.0).dom();
        assert_eq!(
            nan, zero,
            "NaN and 0.0 stopped encoding to the same style tree"
        );
    }
    #[test]
    fn the_title_is_styled_the_same_no_matter_what_it_contains() {
        let baseline = declared(CSS_MATCH_4236783900531286611.as_ref());
        for t in ADVERSARIAL_TEXT {
            let dom = frame(t, Dom::create_div()).dom();
            assert_eq!(
                inline_props(title_node(&dom)),
                baseline,
                "the title style changed for input {t:?}",
            );
            assert_eq!(
                kids(header(&dom)).len(),
                3,
                "the header shape changed for input {t:?}"
            );
            assert_eq!(
                dom.estimated_total_children, 9,
                "the node count changed for {t:?}"
            );
        }
    }
}