1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod audit_tests {
5
    use azul_css::props::basic::StyleFontFamily;
6

            
7
    use super::*;
8

            
9
6
    fn fam(name: &str) -> StyleFontFamily {
10
6
        StyleFontFamily::System(name.to_string().into())
11
6
    }
12

            
13
    #[test]
14
1
    fn style_font_families_hash_is_length_sensitive() {
15
        // The length prefix guarantees that lists of different lengths cannot
16
        // collide, and that hashing is deterministic.
17
1
        let a = StyleFontFamiliesHash::new(&[fam("Arial")]);
18
1
        let a2 = StyleFontFamiliesHash::new(&[fam("Arial")]);
19
1
        assert_eq!(a, a2, "hash must be deterministic");
20

            
21
1
        let two = StyleFontFamiliesHash::new(&[fam("Arial"), fam("Helvetica")]);
22
1
        assert_ne!(a, two, "different-length family lists must not collide");
23

            
24
1
        let empty = StyleFontFamiliesHash::new(&[]);
25
1
        assert_ne!(empty, a);
26
1
        assert_ne!(empty, two);
27

            
28
        // Order still matters.
29
1
        let rev = StyleFontFamiliesHash::new(&[fam("Helvetica"), fam("Arial")]);
30
1
        assert_ne!(two, rev);
31
1
    }
32
}
33

            
34
#[cfg(test)]
35
#[allow(clippy::too_many_lines)]
36
mod autotest_generated {
37
    use azul_css::{dynamic_selector::PseudoStateFlags, props::basic::StyleFontFamily};
38

            
39
    use super::*;
40

            
41
    // ---------------------------------------------------------------------
42
    // helpers
43
    // ---------------------------------------------------------------------
44

            
45
    /// Builds a `NodeHierarchyItem` directly from the RAW (1-based) encoding:
46
    /// `0` = none, `n` = `NodeId(n - 1)`.
47
    const fn raw_item(parent: usize, prev: usize, next: usize, last: usize) -> NodeHierarchyItem {
48
        NodeHierarchyItem {
49
            parent,
50
            previous_sibling: prev,
51
            next_sibling: next,
52
            last_child: last,
53
        }
54
    }
55

            
56
    /// `<body>` with `n` leaf `<div>` children, cascaded against an empty stylesheet.
57
    /// Node ids are `0 = body`, `1..=n` = the children.
58
    fn flat_body(n: usize) -> StyledDom {
59
        let children: Vec<Dom> = (0..n).map(|_| Dom::create_div()).collect();
60
        let mut dom = Dom::create_body().with_children(children.into());
61
        StyledDom::create(&mut dom, Css::empty())
62
    }
63

            
64
    /// `<body> > <div> > <div>` — the last direct child of the root is itself a parent.
65
    fn nested_body() -> StyledDom {
66
        let mut dom = Dom::create_body().with_children(
67
            vec![Dom::create_div().with_children(vec![Dom::create_div()].into())].into(),
68
        );
69
        StyledDom::create(&mut dom, Css::empty())
70
    }
71

            
72
    fn parse_css(s: &str) -> Css {
73
        azul_css::parser2::new_from_str(s).0
74
    }
75

            
76
    fn family(name: &str) -> StyleFontFamily {
77
        StyleFontFamily::System(name.to_string().into())
78
    }
79

            
80
    const fn pseudo_flags(all: bool) -> PseudoStateFlags {
81
        PseudoStateFlags {
82
            hover: all,
83
            active: all,
84
            focused: all,
85
            disabled: all,
86
            checked: all,
87
            focus_within: all,
88
            visited: all,
89
            backdrop: all,
90
            dragging: all,
91
            drag_over: all,
92
            placeholder: all,
93
            seat_focused: all,
94
        }
95
    }
96

            
97
    fn empty_menu() -> Menu {
98
        let items: Vec<crate::menu::MenuItem> = Vec::new();
99
        Menu::create(items.into())
100
    }
101

            
102
    // ---------------------------------------------------------------------
103
    // RestyleResult (predicate + merge)
104
    // ---------------------------------------------------------------------
105

            
106
    #[test]
107
    fn restyle_result_default_reports_no_changes() {
108
        let r = RestyleResult::default();
109
        assert!(!r.has_changes());
110
        assert!(!r.needs_layout);
111
        assert!(!r.needs_display_list);
112
        assert!(!r.gpu_only_changes);
113
        assert_eq!(r.max_relayout_scope, RelayoutScope::None);
114
    }
115

            
116
    #[test]
117
    fn restyle_result_has_changes_keys_off_node_map_not_property_count() {
118
        // A node entry with an EMPTY change list still counts as "changed":
119
        // has_changes() only looks at the node map, never at the inner Vec.
120
        let mut r = RestyleResult::default();
121
        r.changed_nodes.insert(NodeId::ZERO, Vec::new());
122
        assert!(r.has_changes());
123

            
124
        r.changed_nodes.clear();
125
        assert!(!r.has_changes());
126
    }
127

            
128
    #[test]
129
    fn restyle_result_merge_ors_layout_flags_and_ands_gpu_only() {
130
        let mut a = RestyleResult {
131
            needs_layout: false,
132
            needs_display_list: false,
133
            gpu_only_changes: true,
134
            ..RestyleResult::default()
135
        };
136
        let b = RestyleResult {
137
            needs_layout: true,
138
            needs_display_list: true,
139
            gpu_only_changes: true,
140
            ..RestyleResult::default()
141
        };
142
        a.merge(b);
143
        assert!(a.needs_layout, "needs_layout is OR-ed");
144
        assert!(a.needs_display_list, "needs_display_list is OR-ed");
145
        assert!(a.gpu_only_changes, "true && true stays true");
146

            
147
        // ...and a single non-GPU-only participant clears the flag.
148
        let mut c = RestyleResult {
149
            gpu_only_changes: true,
150
            ..RestyleResult::default()
151
        };
152
        c.merge(RestyleResult {
153
            gpu_only_changes: false,
154
            ..RestyleResult::default()
155
        });
156
        assert!(!c.gpu_only_changes, "gpu_only_changes is AND-ed");
157
    }
158

            
159
    #[test]
160
    fn restyle_result_merge_keeps_the_most_expensive_scope() {
161
        let mut low = RestyleResult {
162
            max_relayout_scope: RelayoutScope::None,
163
            ..RestyleResult::default()
164
        };
165
        low.merge(RestyleResult {
166
            max_relayout_scope: RelayoutScope::Full,
167
            ..RestyleResult::default()
168
        });
169
        assert_eq!(low.max_relayout_scope, RelayoutScope::Full);
170

            
171
        // ...and merging a cheaper scope must NOT downgrade it.
172
        let mut high = RestyleResult {
173
            max_relayout_scope: RelayoutScope::Full,
174
            ..RestyleResult::default()
175
        };
176
        high.merge(RestyleResult {
177
            max_relayout_scope: RelayoutScope::IfcOnly,
178
            ..RestyleResult::default()
179
        });
180
        assert_eq!(high.max_relayout_scope, RelayoutScope::Full);
181
    }
182

            
183
    #[test]
184
    fn restyle_result_merge_of_default_is_not_the_identity_for_gpu_only() {
185
        // `RestyleResult::default()` has gpu_only_changes == false, and merge()
186
        // AND-s that flag — so merging an EMPTY result still clears it. Pinned
187
        // here because it is a genuine footgun for callers that merge in a loop.
188
        let mut a = RestyleResult {
189
            gpu_only_changes: true,
190
            ..RestyleResult::default()
191
        };
192
        a.merge(RestyleResult::default());
193
        assert!(!a.gpu_only_changes);
194
        assert!(!a.has_changes());
195
    }
196

            
197
    #[test]
198
    fn restyle_result_merge_concatenates_changes_for_the_same_node() {
199
        let prop = |t| ChangedCssProperty {
200
            previous_state: StyledNodeState::new(),
201
            previous_prop: CssProperty::auto(t),
202
            current_state: StyledNodeState::new(),
203
            current_prop: CssProperty::initial(t),
204
        };
205

            
206
        let mut a = RestyleResult::default();
207
        a.changed_nodes
208
            .insert(NodeId::ZERO, vec![prop(CssPropertyType::Width)]);
209

            
210
        let mut b = RestyleResult::default();
211
        b.changed_nodes
212
            .insert(NodeId::ZERO, vec![prop(CssPropertyType::Height)]);
213
        b.changed_nodes
214
            .insert(NodeId::new(1), vec![prop(CssPropertyType::Opacity)]);
215

            
216
        a.merge(b);
217

            
218
        assert_eq!(a.changed_nodes.len(), 2);
219
        assert_eq!(
220
            a.changed_nodes[&NodeId::ZERO].len(),
221
            2,
222
            "changes for the same node are appended, not replaced"
223
        );
224
        assert_eq!(a.changed_nodes[&NodeId::new(1)].len(), 1);
225
        assert!(a.has_changes());
226
    }
227

            
228
    // ---------------------------------------------------------------------
229
    // StyledNodeState (constructor + predicates)
230
    // ---------------------------------------------------------------------
231

            
232
    #[test]
233
    fn styled_node_state_new_is_all_false_and_normal() {
234
        let s = StyledNodeState::new();
235
        assert!(s.is_normal());
236
        assert!(!s.hover);
237
        assert!(!s.active);
238
        assert!(!s.focused);
239
        assert!(!s.disabled);
240
        assert!(!s.checked);
241
        assert!(!s.focus_within);
242
        assert!(!s.visited);
243
        assert!(!s.backdrop);
244
        assert!(!s.dragging);
245
        assert!(!s.drag_over);
246
        assert_eq!(s, StyledNodeState::default());
247
    }
248

            
249
    #[test]
250
    fn styled_node_state_has_state_zero_is_always_true() {
251
        // 0 == "Normal", which is active regardless of the other flags.
252
        assert!(StyledNodeState::new().has_state(0));
253
        assert!(StyledNodeState::from_pseudo_state_flags(&pseudo_flags(true)).has_state(0));
254
    }
255

            
256
    #[test]
257
    fn styled_node_state_has_state_maps_every_index_exactly_once() {
258
        // Each setter must light up exactly one state index in 1..=10.
259
        let setters: [(u8, fn(&mut StyledNodeState)); 11] = [
260
            (1, |s| s.hover = true),
261
            (2, |s| s.active = true),
262
            (3, |s| s.focused = true),
263
            (4, |s| s.disabled = true),
264
            (5, |s| s.checked = true),
265
            (6, |s| s.focus_within = true),
266
            (7, |s| s.visited = true),
267
            (8, |s| s.backdrop = true),
268
            (9, |s| s.dragging = true),
269
            (10, |s| s.drag_over = true),
270
            (11, |s| s.seat_focused = true),
271
        ];
272

            
273
        for (expected_idx, set) in setters {
274
            let mut s = StyledNodeState::new();
275
            set(&mut s);
276
            assert!(!s.is_normal(), "state {expected_idx} must not be 'normal'");
277
            for idx in 1..=11u8 {
278
                assert_eq!(
279
                    s.has_state(idx),
280
                    idx == expected_idx,
281
                    "state index {idx} misreported for setter {expected_idx}"
282
                );
283
            }
284
        }
285
    }
286

            
287
    #[test]
288
    fn styled_node_state_has_state_is_false_for_every_out_of_range_u8() {
289
        let all_on = StyledNodeState::from_pseudo_state_flags(&pseudo_flags(true));
290
        for idx in 12..=u8::MAX {
291
            assert!(!StyledNodeState::new().has_state(idx));
292
            assert!(
293
                !all_on.has_state(idx),
294
                "unknown state index {idx} must be inactive even when every flag is set"
295
            );
296
        }
297
    }
298

            
299
    #[test]
300
    fn styled_node_state_from_pseudo_state_flags_roundtrips_every_field() {
301
        let all_on = StyledNodeState::from_pseudo_state_flags(&pseudo_flags(true));
302
        assert!(!all_on.is_normal());
303
        for idx in 0..=11u8 {
304
            assert!(all_on.has_state(idx), "state {idx} should be active");
305
        }
306

            
307
        let all_off = StyledNodeState::from_pseudo_state_flags(&pseudo_flags(false));
308
        assert!(all_off.is_normal());
309
        assert_eq!(all_off, StyledNodeState::new());
310
    }
311

            
312
    #[test]
313
    fn styled_node_state_debug_lists_active_states_and_normal_when_empty() {
314
        assert_eq!(format!("{:?}", StyledNodeState::new()), "[\"normal\"]");
315

            
316
        let mut s = StyledNodeState::new();
317
        s.hover = true;
318
        s.drag_over = true;
319
        let dbg = format!("{s:?}");
320
        assert!(dbg.contains("hover"), "{dbg}");
321
        assert!(dbg.contains("drag_over"), "{dbg}");
322
        assert!(!dbg.contains("normal"), "{dbg}");
323
    }
324

            
325
    // ---------------------------------------------------------------------
326
    // StyledNodeVec containers
327
    // ---------------------------------------------------------------------
328

            
329
    #[test]
330
    fn styled_node_vec_empty_container_is_empty_and_get_returns_none() {
331
        let v: StyledNodeVec = Vec::new().into();
332
        let c = v.as_container();
333
        assert_eq!(c.len(), 0);
334
        assert!(c.is_empty());
335
        assert!(c.get(NodeId::ZERO).is_none());
336
        assert!(c.get(NodeId::new(usize::MAX)).is_none());
337
    }
338

            
339
    #[test]
340
    fn styled_node_vec_container_mut_writes_are_visible_through_container() {
341
        let mut v: StyledNodeVec = vec![StyledNode::default(), StyledNode::default()].into();
342
        {
343
            let mut c = v.as_container_mut();
344
            c[NodeId::new(1)].styled_node_state.hover = true;
345
        }
346
        let c = v.as_container();
347
        assert_eq!(c.len(), 2);
348
        assert!(!c[NodeId::ZERO].styled_node_state.hover);
349
        assert!(c[NodeId::new(1)].styled_node_state.hover);
350
        assert!(c.get(NodeId::new(2)).is_none());
351
    }
352

            
353
    // ---------------------------------------------------------------------
354
    // Font family hashes
355
    // ---------------------------------------------------------------------
356

            
357
    #[test]
358
    fn style_font_family_hash_is_deterministic_and_input_sensitive() {
359
        assert_eq!(
360
            StyleFontFamilyHash::new(&family("Arial")),
361
            StyleFontFamilyHash::new(&family("Arial"))
362
        );
363
        assert_ne!(
364
            StyleFontFamilyHash::new(&family("Arial")),
365
            StyleFontFamilyHash::new(&family("Ariaĺ"))
366
        );
367
        // Same string, different variant → different cache key.
368
        assert_ne!(
369
            StyleFontFamilyHash::new(&StyleFontFamily::System("x".to_string().into())),
370
            StyleFontFamilyHash::new(&StyleFontFamily::File("x".to_string().into()))
371
        );
372
    }
373

            
374
    #[test]
375
    fn style_font_family_hash_handles_empty_unicode_and_huge_names() {
376
        let empty = family("");
377
        let unicode = family("🦀 ノート ﷽ عربى");
378
        let huge = family(&"A".repeat(100_000));
379

            
380
        // No panic, and each distinct input is stable across calls.
381
        assert_eq!(
382
            StyleFontFamilyHash::new(&empty),
383
            StyleFontFamilyHash::new(&empty)
384
        );
385
        assert_eq!(
386
            StyleFontFamilyHash::new(&unicode),
387
            StyleFontFamilyHash::new(&unicode)
388
        );
389
        assert_eq!(
390
            StyleFontFamilyHash::new(&huge),
391
            StyleFontFamilyHash::new(&huge)
392
        );
393
        assert_ne!(
394
            StyleFontFamilyHash::new(&empty),
395
            StyleFontFamilyHash::new(&unicode)
396
        );
397
        assert_ne!(
398
            StyleFontFamilyHash::new(&empty),
399
            StyleFontFamilyHash::new(&huge)
400
        );
401
    }
402

            
403
    #[test]
404
    fn style_font_families_hash_empty_slice_is_stable_and_distinct() {
405
        let empty = StyleFontFamiliesHash::new(&[]);
406
        assert_eq!(empty, StyleFontFamiliesHash::new(&[]));
407
        assert_ne!(empty, StyleFontFamiliesHash::new(&[family("")]));
408
    }
409

            
410
    #[test]
411
    fn style_font_families_hash_scales_to_large_lists_and_is_length_sensitive() {
412
        let big: Vec<StyleFontFamily> = (0..1000).map(|i| family(&format!("font-{i}"))).collect();
413
        let one_shorter = &big[..999];
414

            
415
        assert_eq!(
416
            StyleFontFamiliesHash::new(&big),
417
            StyleFontFamiliesHash::new(&big),
418
            "hashing 1000 families must be deterministic"
419
        );
420
        assert_ne!(
421
            StyleFontFamiliesHash::new(&big),
422
            StyleFontFamiliesHash::new(one_shorter),
423
            "the length prefix must separate [0..1000) from [0..999)"
424
        );
425
    }
426

            
427
    // ---------------------------------------------------------------------
428
    // NodeHierarchyItemId: 1-based encode/decode round-trip
429
    // ---------------------------------------------------------------------
430

            
431
    #[test]
432
    fn node_hierarchy_item_id_none_is_zero() {
433
        assert_eq!(NodeHierarchyItemId::NONE.into_raw(), 0);
434
        assert_eq!(NodeHierarchyItemId::NONE.into_crate_internal(), None);
435
        assert_eq!(NodeHierarchyItemId::from_crate_internal(None).into_raw(), 0);
436
        assert_eq!(NodeHierarchyItemId::from_raw(0).into_crate_internal(), None);
437
        assert_eq!(
438
            NodeHierarchyItemId::from_crate_internal(None),
439
            NodeHierarchyItemId::NONE
440
        );
441
    }
442

            
443
    #[test]
444
    fn node_hierarchy_item_id_encode_decode_roundtrip_at_boundaries() {
445
        // usize::MAX - 1 is the largest index that survives the +1 encoding.
446
        for idx in [0usize, 1, 2, 1023, usize::MAX / 2, usize::MAX - 1] {
447
            let id = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx)));
448
            assert_eq!(id.into_raw(), idx + 1, "1-based encoding for {idx}");
449
            assert_eq!(
450
                id.into_crate_internal(),
451
                Some(NodeId::new(idx)),
452
                "decode(encode(x)) == x for {idx}"
453
            );
454
        }
455
    }
456

            
457
    #[test]
458
    fn node_hierarchy_item_id_raw_roundtrip_is_identity_even_at_usize_max() {
459
        for raw in [0usize, 1, 2, 7, u32::MAX as usize, usize::MAX] {
460
            let decoded = NodeHierarchyItemId::from_raw(raw).into_crate_internal();
461
            let reencoded = NodeHierarchyItemId::from_crate_internal(decoded).into_raw();
462
            assert_eq!(
463
                reencoded, raw,
464
                "encode(decode(raw)) must be identity for {raw}"
465
            );
466
        }
467
    }
468

            
469
    #[test]
470
    fn node_hierarchy_item_id_from_raw_decodes_one_based() {
471
        assert_eq!(
472
            NodeHierarchyItemId::from_raw(1).into_crate_internal(),
473
            Some(NodeId::ZERO),
474
            "raw 1 is NodeId(0), NOT NodeId(1)"
475
        );
476
        assert_eq!(
477
            NodeHierarchyItemId::from_raw(usize::MAX).into_crate_internal(),
478
            Some(NodeId::new(usize::MAX - 1))
479
        );
480
    }
481

            
482
    #[test]
483
    fn node_hierarchy_item_id_debug_and_display_agree() {
484
        let none = NodeHierarchyItemId::NONE;
485
        assert_eq!(format!("{none:?}"), "None");
486
        assert_eq!(format!("{none}"), format!("{none:?}"));
487

            
488
        let some = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(5)));
489
        assert_eq!(format!("{some:?}"), "Some(NodeId(5))");
490
        assert_eq!(format!("{some}"), format!("{some:?}"));
491

            
492
        // Extreme value: must not panic and must stay non-empty.
493
        let max = NodeHierarchyItemId::from_raw(usize::MAX);
494
        assert!(!format!("{max:?}").is_empty());
495
    }
496

            
497
    #[test]
498
    fn node_hierarchy_item_id_ordering_follows_raw_value() {
499
        let a = NodeHierarchyItemId::from_raw(0);
500
        let b = NodeHierarchyItemId::from_raw(1);
501
        let c = NodeHierarchyItemId::from_raw(usize::MAX);
502
        assert!(a < b);
503
        assert!(b < c);
504
        assert_eq!(a, NodeHierarchyItemId::NONE);
505
    }
506

            
507
    #[test]
508
    fn node_hierarchy_item_id_from_impls_match_the_explicit_ones() {
509
        let opt = Some(NodeId::new(41));
510
        let via_from: NodeHierarchyItemId = opt.into();
511
        assert_eq!(via_from, NodeHierarchyItemId::from_crate_internal(opt));
512

            
513
        let back: Option<NodeId> = via_from.into();
514
        assert_eq!(back, opt);
515

            
516
        let none: NodeHierarchyItemId = None.into();
517
        assert_eq!(none.into_raw(), 0);
518
    }
519

            
520
    // ---------------------------------------------------------------------
521
    // NodeHierarchyItem getters
522
    // ---------------------------------------------------------------------
523

            
524
    #[test]
525
    fn node_hierarchy_item_zeroed_has_no_links() {
526
        let z = NodeHierarchyItem::zeroed();
527
        assert_eq!(z.parent_id(), None);
528
        assert_eq!(z.previous_sibling_id(), None);
529
        assert_eq!(z.next_sibling_id(), None);
530
        assert_eq!(z.last_child_id(), None);
531
        assert_eq!(z.first_child_id(NodeId::ZERO), None);
532
        assert_eq!(z.first_child_id(NodeId::new(usize::MAX)), None);
533
        assert_eq!(z, NodeHierarchyItem::from(Node::ROOT));
534
    }
535

            
536
    #[test]
537
    fn node_hierarchy_item_getters_decode_the_one_based_fields() {
538
        let item = raw_item(1, 2, 3, 4);
539
        assert_eq!(item.parent_id(), Some(NodeId::new(0)));
540
        assert_eq!(item.previous_sibling_id(), Some(NodeId::new(1)));
541
        assert_eq!(item.next_sibling_id(), Some(NodeId::new(2)));
542
        assert_eq!(item.last_child_id(), Some(NodeId::new(3)));
543

            
544
        // first_child is derived: parent + 1, but only if the node has children.
545
        assert_eq!(item.first_child_id(NodeId::new(7)), Some(NodeId::new(8)));
546
    }
547

            
548
    #[test]
549
    fn node_hierarchy_item_getters_at_usize_max_do_not_overflow() {
550
        let item = raw_item(usize::MAX, usize::MAX, usize::MAX, usize::MAX);
551
        assert_eq!(item.parent_id(), Some(NodeId::new(usize::MAX - 1)));
552
        assert_eq!(
553
            item.previous_sibling_id(),
554
            Some(NodeId::new(usize::MAX - 1))
555
        );
556
        assert_eq!(item.next_sibling_id(), Some(NodeId::new(usize::MAX - 1)));
557
        assert_eq!(item.last_child_id(), Some(NodeId::new(usize::MAX - 1)));
558

            
559
        // NodeId's Add is saturating, so `current + 1` clamps instead of wrapping
560
        // to 0 (which would alias the root node).
561
        assert_eq!(
562
            item.first_child_id(NodeId::new(usize::MAX)),
563
            Some(NodeId::new(usize::MAX)),
564
            "first_child_id must saturate, never wrap to NodeId(0)"
565
        );
566
    }
567

            
568
    #[test]
569
    fn node_hierarchy_item_from_node_preserves_every_link() {
570
        let node = Node {
571
            parent: Some(NodeId::new(3)),
572
            previous_sibling: None,
573
            next_sibling: Some(NodeId::new(9)),
574
            last_child: Some(NodeId::new(12)),
575
        };
576
        let item: NodeHierarchyItem = node.into();
577
        assert_eq!(item.parent_id(), node.parent);
578
        assert_eq!(item.previous_sibling_id(), node.previous_sibling);
579
        assert_eq!(item.next_sibling_id(), node.next_sibling);
580
        assert_eq!(item.last_child_id(), node.last_child);
581
    }
582

            
583
    // ---------------------------------------------------------------------
584
    // NodeHierarchyItemVec container + subtree_len
585
    // ---------------------------------------------------------------------
586

            
587
    #[test]
588
    fn node_hierarchy_item_vec_containers_read_and_write() {
589
        let mut v: NodeHierarchyItemVec = vec![NodeHierarchyItem::zeroed(); 2].into();
590
        {
591
            let mut c = v.as_container_mut();
592
            c[NodeId::new(1)].parent = 1; // raw 1 == NodeId(0)
593
        }
594
        let c = v.as_container();
595
        assert_eq!(c.len(), 2);
596
        assert_eq!(c[NodeId::new(1)].parent_id(), Some(NodeId::ZERO));
597
        assert!(c.get(NodeId::new(2)).is_none());
598

            
599
        let empty: NodeHierarchyItemVec = Vec::new().into();
600
        assert!(empty.as_container().is_empty());
601
    }
602

            
603
    #[test]
604
    fn subtree_len_counts_descendants_of_a_real_tree() {
605
        // body(0) > div(1) > div(2)
606
        let sd = nested_body();
607
        let h = sd.node_hierarchy.as_container();
608
        assert_eq!(h.len(), 3);
609
        assert_eq!(h.subtree_len(NodeId::ZERO), 2, "root has 2 descendants");
610
        assert_eq!(h.subtree_len(NodeId::new(1)), 1);
611
        assert_eq!(
612
            h.subtree_len(NodeId::new(2)),
613
            0,
614
            "a leaf has no descendants"
615
        );
616
    }
617

            
618
    #[test]
619
    fn subtree_len_saturates_on_a_malformed_backwards_next_sibling() {
620
        // Node 2 claims its next sibling is node 0 — a backwards link a malformed
621
        // FastDom can produce. The subtraction must saturate, not underflow-panic.
622
        let v: NodeHierarchyItemVec = vec![
623
            raw_item(0, 0, 0, 0),
624
            raw_item(0, 0, 0, 0),
625
            raw_item(0, 0, /* next = NodeId(0) */ 1, 0),
626
        ]
627
        .into();
628
        let c = v.as_container();
629
        assert_eq!(c.subtree_len(NodeId::new(2)), 0);
630

            
631
        // Self-referential next_sibling (node 1 -> node 1) must also saturate.
632
        let v2: NodeHierarchyItemVec = vec![raw_item(0, 0, 0, 0), raw_item(0, 0, 2, 0)].into();
633
        assert_eq!(v2.as_container().subtree_len(NodeId::new(1)), 0);
634
    }
635

            
636
    // ---------------------------------------------------------------------
637
    // StyledDomMemoryReport
638
    // ---------------------------------------------------------------------
639

            
640
    #[test]
641
    fn memory_report_default_total_is_zero() {
642
        assert_eq!(StyledDomMemoryReport::default().total_bytes(), 0);
643
    }
644

            
645
    #[test]
646
    fn memory_report_total_bytes_sums_every_field() {
647
        let r = StyledDomMemoryReport {
648
            node_count: 3,
649
            node_hierarchy_bytes: 1,
650
            node_data_bytes: 2,
651
            styled_nodes_bytes: 4,
652
            cascade_info_bytes: 8,
653
            tag_ids_bytes: 16,
654
            non_leaf_nodes_bytes: 32,
655
            callback_vecs_bytes: 64,
656
            ..StyledDomMemoryReport::default()
657
        };
658
        assert_eq!(
659
            r.total_bytes(),
660
            127,
661
            "node_count must NOT be part of the sum"
662
        );
663

            
664
        // A single saturated field must not overflow the running sum.
665
        let extreme = StyledDomMemoryReport {
666
            node_data_bytes: usize::MAX,
667
            ..StyledDomMemoryReport::default()
668
        };
669
        assert_eq!(extreme.total_bytes(), usize::MAX);
670
    }
671

            
672
    #[test]
673
    fn memory_report_tracks_node_count_and_is_monotonic_in_dom_size() {
674
        let small = flat_body(1).memory_report();
675
        let large = flat_body(50).memory_report();
676
        assert_eq!(small.node_count, 2);
677
        assert_eq!(large.node_count, 51);
678
        assert!(large.total_bytes() > small.total_bytes());
679
        assert!(small.total_bytes() >= small.node_hierarchy_bytes + small.node_data_bytes);
680

            
681
        // Also fine on the smallest possible DOM.
682
        let d = StyledDom::default().memory_report();
683
        assert_eq!(d.node_count, 1);
684
        assert!(d.total_bytes() > 0);
685
    }
686

            
687
    // ---------------------------------------------------------------------
688
    // StyledDom construction
689
    // ---------------------------------------------------------------------
690

            
691
    #[test]
692
    fn default_styled_dom_is_a_single_rooted_body() {
693
        let sd = StyledDom::default();
694
        assert_eq!(sd.node_count(), 1);
695
        assert_eq!(sd.root.into_crate_internal(), Some(NodeId::ZERO));
696
        assert_eq!(sd.node_hierarchy.as_ref().len(), 1);
697
        assert_eq!(sd.styled_nodes.as_ref().len(), 1);
698
        assert_eq!(sd.cascade_info.as_ref().len(), 1);
699
        assert_eq!(sd.non_leaf_nodes.as_ref().len(), 1);
700
        assert_eq!(sd.non_leaf_nodes.as_ref()[0].depth, 0);
701
        assert!(sd.tag_ids_to_node_ids.as_ref().is_empty());
702
        assert!(sd.get_styled_node_state(&NodeId::ZERO).is_normal());
703
    }
704

            
705
    /// miniword ENGINE-ISSUE 4:
706
    /// `Dom::create_text_do_not_use_without_block_level_wrapper(..).with_css(..)` silently
707
    /// dropped EVERY declaration — the bare-decl wrapper parses to
708
    /// `* { .. }`, and the `Global` matcher refused text nodes even for
709
    /// rules scoped to exactly that node. All four reported strings now
710
    /// cascade onto the text node.
711
    #[test]
712
    fn with_css_on_a_text_node_applies_its_declarations() {
713
        use azul_css::props::basic::color::ColorU;
714

            
715
        let cases: &[(&str, ColorU, isize)] = &[
716
            (
717
                "font-size: 38px; color: #565656;",
718
                ColorU {
719
                    r: 0x56,
720
                    g: 0x56,
721
                    b: 0x56,
722
                    a: 255,
723
                },
724
                38,
725
            ),
726
            (
727
                "font-size: 38px; color: #565656; flex-grow: 0;",
728
                ColorU {
729
                    r: 0x56,
730
                    g: 0x56,
731
                    b: 0x56,
732
                    a: 255,
733
                },
734
                38,
735
            ),
736
            (
737
                "font-size: 16px; color: #2b579a; margin-bottom: 12px;",
738
                ColorU {
739
                    r: 0x2b,
740
                    g: 0x57,
741
                    b: 0x9a,
742
                    a: 255,
743
                },
744
                16,
745
            ),
746
            (
747
                "font-size: 13px; color: white;",
748
                ColorU {
749
                    r: 255,
750
                    g: 255,
751
                    b: 255,
752
                    a: 255,
753
                },
754
                13,
755
            ),
756
        ];
757

            
758
        for (css_str, want_color, want_px) in cases {
759
            let dom = crate::dom::Dom::create_body().with_child(
760
                crate::dom::Dom::create_div()
761
                    .with_css("color: #444444; font-size: 10px;")
762
                    .with_child(
763
                        crate::dom::Dom::create_text_do_not_use_without_block_level_wrapper("X")
764
                            .with_css(css_str),
765
                    ),
766
            );
767
            // create_from_dom is the production path (scope_inline_css +
768
            // collect_css_from_dom); plain create() ignores dom.css.
769
            let styled = StyledDom::create_from_dom(dom);
770
            let cache = styled.get_css_property_cache();
771
            let n = styled.node_data.as_ref().len() - 1;
772
            let node_id = NodeId::new(n);
773
            let node_data = &styled.node_data.as_ref()[n];
774
            assert!(
775
                node_data.is_text_node(),
776
                "fixture: last node must be the text node"
777
            );
778
            let state = &styled.styled_nodes.as_ref()[n].styled_node_state;
779

            
780
            let color = cache
781
                .get_text_color(node_data, &node_id, state)
782
                .and_then(|p| p.get_property().copied())
783
                .map(|c| c.inner);
784
            assert_eq!(
785
                color,
786
                Some(*want_color),
787
                "inline color lost on text node for {css_str:?}"
788
            );
789
            let size = cache
790
                .get_font_size(node_data, &node_id, state)
791
                .and_then(|p| p.get_property().copied())
792
                .map(|s| s.inner.to_pixels_internal(16.0, 16.0, 16.0) as isize);
793
            assert_eq!(
794
                size,
795
                Some(*want_px),
796
                "inline font-size lost on text node for {css_str:?}"
797
            );
798
        }
799

            
800
        // Negative control: a text node WITHOUT inline css keeps taking its
801
        // color by INHERITANCE (the parent's #444444 arrives via
802
        // cascaded_props) — the matcher exception must not have rerouted or
803
        // broken the inheritance lane.
804
        let dom = crate::dom::Dom::create_body().with_child(
805
            crate::dom::Dom::create_div()
806
                .with_css("color: #444444;")
807
                .with_child(
808
                    crate::dom::Dom::create_text_do_not_use_without_block_level_wrapper("X"),
809
                ),
810
        );
811
        let styled = StyledDom::create_from_dom(dom);
812
        let cache = styled.get_css_property_cache();
813
        let n = styled.node_data.as_ref().len() - 1;
814
        let node_id = NodeId::new(n);
815
        let node_data = &styled.node_data.as_ref()[n];
816
        let state = &styled.styled_nodes.as_ref()[n].styled_node_state;
817
        assert!(node_data.is_text_node());
818
        assert!(
819
            cache.css_props.get_slice(n).is_empty(),
820
            "an unstyled text node must have no OWN css_props"
821
        );
822
        let inherited = cache
823
            .get_text_color(node_data, &node_id, state)
824
            .and_then(|p| p.get_property().copied())
825
            .map(|c| c.inner);
826
        assert_eq!(
827
            inherited,
828
            Some(ColorU {
829
                r: 0x44,
830
                g: 0x44,
831
                b: 0x44,
832
                a: 255
833
            }),
834
            "inheritance must still deliver the parent's color to the text node"
835
        );
836
    }
837

            
838
    #[test]
839
    fn create_empties_the_source_dom() {
840
        // Documented: "After calling this function, the DOM will be reset to an empty DOM."
841
        let mut dom = Dom::create_body().with_children(vec![Dom::create_div(); 3].into());
842
        let sd = StyledDom::create(&mut dom, Css::empty());
843
        assert_eq!(sd.node_count(), 4);
844
        assert!(
845
            dom.children.as_ref().is_empty(),
846
            "the source Dom must be left empty (it is swapped out, not cloned)"
847
        );
848
    }
849

            
850
    #[test]
851
    fn create_keeps_every_parallel_array_the_same_length() {
852
        for n in [0usize, 1, 3, 64] {
853
            let sd = flat_body(n);
854
            let count = sd.node_count();
855
            assert_eq!(count, n + 1);
856
            assert_eq!(sd.node_hierarchy.as_ref().len(), count);
857
            assert_eq!(sd.styled_nodes.as_ref().len(), count);
858
            assert_eq!(sd.cascade_info.as_ref().len(), count);
859
        }
860
    }
861

            
862
    #[test]
863
    fn create_survives_malformed_truncated_and_unicode_css() {
864
        let cases: Vec<String> = vec![
865
            String::new(),
866
            "}}}{{{".to_string(),
867
            "div {".to_string(),
868
            "div { color: }".to_string(),
869
            "div { : red; }".to_string(),
870
            "@media".to_string(),
871
            "/* unterminated comment".to_string(),
872
            "div { width: 99999999999999999999999px; }".to_string(),
873
            "div { width: -0px; opacity: 1e400; }".to_string(),
874
            "div { width: NaNpx; height: infpx; }".to_string(),
875
            "* { color: #ZZZZZZ; }".to_string(),
876
            "日本語 { content: \"🦀\"; }".to_string(),
877
            ".\u{202e}rtl { color: red; }".to_string(),
878
            "a".repeat(10_000),
879
            "div { color: red; }".repeat(500),
880
        ];
881

            
882
        for case in &cases {
883
            let css = parse_css(case);
884
            let mut dom = Dom::create_body().with_children(vec![Dom::create_div()].into());
885
            let sd = StyledDom::create(&mut dom, css);
886
            assert_eq!(
887
                sd.node_count(),
888
                2,
889
                "CSS must never change the node count; failing input: {case:?}"
890
            );
891
        }
892
    }
893

            
894
    #[test]
895
    fn create_handles_deep_and_wide_doms() {
896
        // deep: 64 nested divs under a body
897
        let mut deep = Dom::create_div();
898
        for _ in 0..63 {
899
            deep = Dom::create_div().with_children(vec![deep].into());
900
        }
901
        let mut deep_body = Dom::create_body().with_children(vec![deep].into());
902
        let sd = StyledDom::create(&mut deep_body, Css::empty());
903
        assert_eq!(sd.node_count(), 65);
904
        assert_eq!(
905
            sd.non_leaf_nodes.as_ref().len(),
906
            64,
907
            "every node except the innermost leaf is a parent"
908
        );
909

            
910
        // wide: 1000 siblings
911
        let wide = flat_body(1000);
912
        assert_eq!(wide.node_count(), 1001);
913
        assert_eq!(
914
            wide.node_hierarchy.as_container().subtree_len(NodeId::ZERO),
915
            1000
916
        );
917
        assert_eq!(wide.non_leaf_nodes.as_ref().len(), 1);
918
    }
919

            
920
    #[test]
921
    fn create_from_dom_collects_scoped_css_without_changing_the_tree() {
922
        let dom = Dom::create_body().with_children(
923
            vec![
924
                Dom::create_div().with_css("color: red"),
925
                Dom::create_div()
926
                    .with_children(vec![Dom::create_div().with_css("width: 5px")].into()),
927
            ]
928
            .into(),
929
        );
930
        let sd = StyledDom::create_from_dom(dom);
931
        assert_eq!(sd.node_count(), 4);
932
        assert_eq!(sd.node_hierarchy.as_ref().len(), 4);
933
        assert!(sd.get_css_property_cache().compact_cache.is_some());
934
    }
935

            
936
    #[test]
937
    fn create_from_dom_on_a_bare_leaf_produces_one_node() {
938
        let sd = StyledDom::create_from_dom(Dom::create_div());
939
        assert_eq!(sd.node_count(), 1);
940
        assert_eq!(sd.root.into_crate_internal(), Some(NodeId::ZERO));
941
    }
942

            
943
    // ---------------------------------------------------------------------
944
    // append_child / append_child_with_index / finalize / with_child
945
    // ---------------------------------------------------------------------
946

            
947
    #[test]
948
    fn append_child_grows_the_node_count_by_the_child_dom_size() {
949
        let mut base = flat_body(2);
950
        base.append_child(flat_body(3));
951
        assert_eq!(base.node_count(), 3 + 4);
952
        assert_eq!(base.node_hierarchy.as_ref().len(), 7);
953
        assert_eq!(base.styled_nodes.as_ref().len(), 7);
954
        assert_eq!(base.cascade_info.as_ref().len(), 7);
955
    }
956

            
957
    #[test]
958
    fn append_child_links_the_new_root_as_the_last_sibling() {
959
        // Flat parent: body(0) > [div(1), div(2)], then append a 1-node StyledDom.
960
        let mut base = flat_body(2);
961
        base.append_child(StyledDom::default());
962

            
963
        let h = base.node_hierarchy.as_container();
964
        let children: Vec<NodeId> = NodeId::ZERO.az_children(&h).collect();
965
        assert_eq!(
966
            children,
967
            vec![NodeId::new(1), NodeId::new(2), NodeId::new(3)],
968
            "the appended root must become the last direct child"
969
        );
970
        assert_eq!(h[NodeId::new(3)].parent_id(), Some(NodeId::ZERO));
971
        assert_eq!(
972
            h[NodeId::new(3)].previous_sibling_id(),
973
            Some(NodeId::new(2))
974
        );
975
        assert_eq!(h[NodeId::new(3)].next_sibling_id(), None);
976
    }
977

            
978
    /// ADVERSARIAL: `append_child` reads `last_child_id()` to find the current
979
    /// last sibling. If `last_child` names a *descendant* rather than the last
980
    /// *direct child*, the appended root is spliced into the wrong sibling chain
981
    /// and disappears from the root's children.
982
    #[test]
983
    fn append_child_keeps_the_root_children_reachable_for_a_nested_dom() {
984
        let mut base = nested_body(); // body(0) > div(1) > div(2)
985
        base.append_child(StyledDom::default());
986
        assert_eq!(base.node_count(), 4);
987

            
988
        let h = base.node_hierarchy.as_container();
989
        let children: Vec<NodeId> = NodeId::ZERO.az_children(&h).collect();
990
        assert_eq!(
991
            children,
992
            vec![NodeId::new(1), NodeId::new(3)],
993
            "after append_child the root must have exactly its old child plus the appended root"
994
        );
995
    }
996

            
997
    #[test]
998
    fn append_child_with_index_saturates_the_u32_cascade_index() {
999
        for (child_index, expected) in [
            (0usize, 0u32),
            (7, 7),
            (u32::MAX as usize, u32::MAX),
            (u32::MAX as usize + 1, u32::MAX),
            (usize::MAX, u32::MAX),
        ] {
            let mut base = flat_body(0); // single body node
            base.append_child_with_index(StyledDom::default(), child_index);
            // The appended root lands at index self_len == 1 in the merged arrays.
            assert_eq!(
                base.cascade_info.as_ref()[1].index_in_parent,
                expected,
                "child_index {child_index} must saturate to {expected}, never wrap"
            );
            assert!(base.cascade_info.as_ref()[1].is_last_child);
            assert_eq!(base.node_count(), 2);
        }
    }
    #[test]
    fn finalize_non_leaf_nodes_sorts_by_depth_and_is_idempotent() {
        let mut base = flat_body(1);
        base.append_child_with_index(flat_body(2), 1);
        base.append_child_with_index(flat_body(2), 2);
        base.finalize_non_leaf_nodes();
        let depths: Vec<usize> = base
            .non_leaf_nodes
            .as_ref()
            .iter()
            .map(|p| p.depth)
            .collect();
        let mut sorted = depths.clone();
        sorted.sort_unstable();
        assert_eq!(depths, sorted, "non_leaf_nodes must be depth-ordered");
        base.finalize_non_leaf_nodes();
        let again: Vec<usize> = base
            .non_leaf_nodes
            .as_ref()
            .iter()
            .map(|p| p.depth)
            .collect();
        assert_eq!(depths, again, "finalize must be idempotent");
    }
    #[test]
    fn with_child_matches_append_child() {
        let mut appended = flat_body(2);
        appended.append_child(flat_body(1));
        let built = flat_body(2).with_child(flat_body(1));
        assert_eq!(built.node_count(), appended.node_count());
        assert_eq!(
            built.node_hierarchy.as_ref(),
            appended.node_hierarchy.as_ref()
        );
    }
    #[test]
    fn swap_with_default_returns_the_old_dom_and_resets_self() {
        let mut sd = flat_body(3);
        let old = sd.swap_with_default();
        assert_eq!(old.node_count(), 4);
        assert_eq!(
            sd.node_count(),
            1,
            "self must be left as the default StyledDom"
        );
        assert_eq!(sd.root.into_crate_internal(), Some(NodeId::ZERO));
    }
    // ---------------------------------------------------------------------
    // Menus
    // ---------------------------------------------------------------------
    #[test]
    fn context_menu_and_menu_bar_are_stored_on_the_root_node() {
        let mut sd = flat_body(1);
        assert!(sd.node_data.as_container()[NodeId::ZERO]
            .get_context_menu()
            .is_none());
        sd.set_context_menu(empty_menu());
        sd.set_menu_bar(empty_menu());
        let data = sd.node_data.as_container();
        assert!(data[NodeId::ZERO].get_context_menu().is_some());
        assert!(data[NodeId::ZERO].get_menu_bar().is_some());
        // ...and the child must not have inherited either of them.
        assert!(data[NodeId::new(1)].get_context_menu().is_none());
        assert!(data[NodeId::new(1)].get_menu_bar().is_none());
    }
    #[test]
    fn menu_builders_are_equivalent_to_the_setters_and_dont_touch_the_tree() {
        let sd = StyledDom::default()
            .with_context_menu(empty_menu())
            .with_menu_bar(empty_menu());
        assert_eq!(sd.node_count(), 1);
        let data = sd.node_data.as_container();
        assert!(data[NodeId::ZERO].get_context_menu().is_some());
        assert!(data[NodeId::ZERO].get_menu_bar().is_some());
    }
    // ---------------------------------------------------------------------
    // restyle_nodes_* / restyle_on_state_change / restyle_user_property
    // ---------------------------------------------------------------------
    #[test]
    fn restyle_nodes_hover_sets_and_clears_the_state_flag() {
        let mut sd = flat_body(2);
        let _ = sd.restyle_nodes_hover(&[NodeId::new(1)], true);
        assert!(sd.get_styled_node_state(&NodeId::new(1)).hover);
        assert!(!sd.get_styled_node_state(&NodeId::new(2)).hover);
        let _ = sd.restyle_nodes_hover(&[NodeId::new(1)], false);
        assert!(!sd.get_styled_node_state(&NodeId::new(1)).hover);
        assert!(sd.get_styled_node_state(&NodeId::new(1)).is_normal());
    }
    #[test]
    fn restyle_nodes_active_and_focus_set_independent_flags() {
        let mut sd = flat_body(1);
        let _ = sd.restyle_nodes_active(&[NodeId::ZERO], true);
        let _ = sd.restyle_nodes_focus(&[NodeId::ZERO], true);
        let state = sd.get_styled_node_state(&NodeId::ZERO);
        assert!(state.active);
        assert!(state.focused);
        assert!(!state.hover, "hover must be untouched");
        assert!(!state.is_normal());
    }
    #[test]
    fn restyle_nodes_ignores_out_of_range_node_ids_instead_of_panicking() {
        let mut sd = flat_body(1); // valid ids: 0, 1
        let changed = sd.restyle_nodes_hover(&[NodeId::new(2), NodeId::new(usize::MAX)], true);
        assert!(changed.is_empty());
        assert!(!sd.get_styled_node_state(&NodeId::ZERO).hover);
        assert!(!sd.get_styled_node_state(&NodeId::new(1)).hover);
        // A mix of valid and stale ids must still apply the valid ones.
        let _ = sd.restyle_nodes_hover(&[NodeId::new(1), NodeId::new(999)], true);
        assert!(sd.get_styled_node_state(&NodeId::new(1)).hover);
    }
    #[test]
    fn restyle_nodes_handles_empty_and_duplicated_input() {
        let mut sd = flat_body(1);
        assert!(sd.restyle_nodes_focus(&[], true).is_empty());
        // Duplicates must be idempotent, not double-applied or panicking.
        let _ = sd.restyle_nodes_focus(&[NodeId::ZERO, NodeId::ZERO, NodeId::ZERO], true);
        assert!(sd.get_styled_node_state(&NodeId::ZERO).focused);
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn get_styled_node_state_panics_on_an_out_of_range_node_id() {
        // Documents the contract: unlike restyle_nodes_*, this getter does NOT
        // bounds-check — callers must pass an id that indexes into this DOM.
        let sd = flat_body(1);
        let _ = sd.get_styled_node_state(&NodeId::new(99));
    }
    #[test]
    fn restyle_on_state_change_with_no_changes_reports_nothing_to_do() {
        let mut sd = flat_body(2);
        let r = sd.restyle_on_state_change(None, None, None);
        assert!(!r.has_changes());
        assert!(!r.needs_layout);
        assert!(!r.needs_display_list);
        assert!(!r.gpu_only_changes);
        assert_eq!(r.max_relayout_scope, RelayoutScope::None);
    }
    #[test]
    fn restyle_on_state_change_tolerates_stale_node_ids() {
        let mut sd = flat_body(1);
        let r = sd.restyle_on_state_change(
            Some(FocusChange {
                lost_focus: Some(NodeId::new(500)),
                gained_focus: Some(NodeId::new(usize::MAX)),
            }),
            Some(HoverChange {
                left_nodes: vec![NodeId::new(700)],
                entered_nodes: vec![NodeId::new(800)],
            }),
            Some(ActiveChange {
                deactivated: vec![NodeId::new(900)],
                activated: vec![NodeId::new(1000)],
            }),
        );
        assert!(!r.has_changes(), "stale ids must be filtered, not applied");
        assert_eq!(sd.node_count(), 2);
    }
    #[test]
    fn restyle_on_state_change_applies_state_to_valid_nodes() {
        let mut sd = flat_body(1);
        let r = sd.restyle_on_state_change(
            None,
            Some(HoverChange {
                left_nodes: Vec::new(),
                entered_nodes: vec![NodeId::new(1)],
            }),
            None,
        );
        assert!(sd.get_styled_node_state(&NodeId::new(1)).hover);
        assert!(
            r.changed_nodes.keys().all(|n| *n == NodeId::new(1)),
            "only the node whose state actually changed may be reported"
        );
    }
    /// A geometry patch must leave the compact cache PRESENT and already
    /// reflecting the override. The old behaviour (drop the cache, "the next
    /// full cascade rebuilds it") broke every consumer that derives state
    /// from the cache during the very relayout that applies the patch: the
    /// font phase resolved an EMPTY font world (no stack signature, no
    /// chains, empty GC keep-set), so the patched-in subtree's text laid out
    /// at zero size and, pre-guard, the font GC evicted every loaded font
    /// mid-frame.
    #[test]
    fn restyle_user_property_rebuilds_the_compact_cache_with_the_patch() {
        use azul_css::props::{layout::display::LayoutDisplay, property::CssProperty};
        let mut sd = flat_body(2);
        let node = NodeId::new(1);
        // Sanity: the fixture starts with a compact cache.
        assert!(
            sd.get_css_property_cache().compact_cache.is_some(),
            "fixture should carry a compact cache"
        );
        let changes =
            sd.restyle_user_property(&node, &[CssProperty::const_display(LayoutDisplay::None)]);
        assert!(
            !changes.is_empty(),
            "display default -> none must report a change"
        );
        let cc = sd
            .get_css_property_cache()
            .compact_cache
            .as_ref()
            .expect("compact cache must be REBUILT by a geometry patch, not dropped");
        assert_eq!(
            cc.get_display(node.index()),
            LayoutDisplay::None,
            "the rebuilt compact cache must already reflect the patched value"
        );
        // And back again - repeated patches keep rebuilding, not accumulating.
        let _ = sd.restyle_user_property(&node, &[CssProperty::const_display(LayoutDisplay::Flex)]);
        let cc = sd
            .get_css_property_cache()
            .compact_cache
            .as_ref()
            .expect("second patch keeps the cache present");
        assert_eq!(cc.get_display(node.index()), LayoutDisplay::Flex);
    }
    #[test]
    fn restyle_user_property_rejects_empty_lists_and_stale_nodes() {
        let mut sd = flat_body(1);
        assert!(sd.restyle_user_property(&NodeId::ZERO, &[]).is_empty());
        assert!(
            sd.restyle_user_property(
                &NodeId::new(50),
                &[CssProperty::auto(CssPropertyType::Width)]
            )
            .is_empty(),
            "an out-of-range node id must be a no-op, not a panic"
        );
        assert!(
            sd.get_css_property_cache()
                .user_overridden_properties
                .iter()
                .all(Vec::is_empty),
            "a rejected call must not record an override"
        );
    }
    #[test]
    fn restyle_user_property_stores_the_override_and_initial_removes_it() {
        let mut sd = flat_body(1);
        let node = NodeId::ZERO;
        let _ = sd.restyle_user_property(&node, &[CssProperty::auto(CssPropertyType::Width)]);
        {
            let overrides = &sd.get_css_property_cache().user_overridden_properties;
            assert_eq!(
                overrides.len(),
                sd.node_count(),
                "table grows to cover the DOM"
            );
            assert_eq!(overrides[0].len(), 1);
            assert_eq!(overrides[0][0].0, CssPropertyType::Width);
        }
        // Re-setting the same type replaces rather than duplicating.
        let _ = sd.restyle_user_property(&node, &[CssProperty::none(CssPropertyType::Width)]);
        assert_eq!(
            sd.get_css_property_cache().user_overridden_properties[0].len(),
            1
        );
        // CssProperty::Initial removes the override again.
        let _ = sd.restyle_user_property(&node, &[CssProperty::initial(CssPropertyType::Width)]);
        assert!(sd.get_css_property_cache().user_overridden_properties[0].is_empty());
        // Removing a property that was never set must not panic.
        let _ = sd.restyle_user_property(&node, &[CssProperty::initial(CssPropertyType::Height)]);
        assert!(sd.get_css_property_cache().user_overridden_properties[0].is_empty());
    }
    #[test]
    fn restyle_and_recompute_preserve_the_tree_and_rebuild_the_compact_cache() {
        let mut sd = flat_body(3);
        let before = sd.node_count();
        sd.restyle(parse_css(
            "div { color: red; } body > div:hover { color: blue; }",
        ));
        assert_eq!(sd.node_count(), before);
        assert!(sd.get_css_property_cache().compact_cache.is_some());
        // A second restyle with garbage CSS must not corrupt the structure.
        sd.restyle(parse_css("}}} div { : ; }"));
        assert_eq!(sd.node_count(), before);
        sd.recompute_inheritance_and_compact_cache();
        assert_eq!(sd.node_count(), before);
        assert!(sd.get_css_property_cache().compact_cache.is_some());
    }
    #[test]
    fn get_css_property_cache_mut_sees_the_same_cache_as_the_shared_getter() {
        let mut sd = flat_body(1);
        let node_count = sd.node_count();
        sd.get_css_property_cache_mut()
            .user_overridden_properties
            .resize(node_count, Vec::new());
        assert_eq!(
            sd.get_css_property_cache().user_overridden_properties.len(),
            node_count
        );
    }
    // ---------------------------------------------------------------------
    // get_html_string
    // ---------------------------------------------------------------------
    #[test]
    fn get_html_string_test_mode_omits_the_html_wrapper() {
        let sd = flat_body(2);
        let out = sd.get_html_string("HEAD_MARK", "BODY_MARK", true);
        assert!(!out.is_empty());
        assert!(
            !out.contains("HEAD_MARK"),
            "test_mode must not emit the custom head"
        );
        assert!(
            !out.contains("BODY_MARK"),
            "test_mode must not emit the custom body"
        );
        assert!(!out.contains("<html>"));
    }
    #[test]
    fn get_html_string_embeds_custom_head_and_body_verbatim() {
        let sd = flat_body(1);
        let head = "🦀 <meta charset=\"utf-8\"> & ünïcödé";
        let body = "x".repeat(10_000);
        let out = sd.get_html_string(head, &body, false);
        assert!(out.contains("<html>"));
        assert!(out.contains(head));
        assert!(out.contains(&body));
    }
    #[test]
    fn get_html_string_does_not_panic_on_extreme_doms() {
        // A single-node DOM has no non_leaf parent entry for its root — the depth
        // lookup must fall back to 0 rather than panic-indexing the map.
        assert!(!StyledDom::default()
            .get_html_string("", "", true)
            .is_empty());
        assert!(!flat_body(0).get_html_string("", "", true).is_empty());
        assert!(!nested_body().get_html_string("", "", true).is_empty());
        assert!(!flat_body(200).get_html_string("", "", true).is_empty());
    }
    // ---------------------------------------------------------------------
    // rendering order
    // ---------------------------------------------------------------------
    #[test]
    fn get_rects_in_rendering_order_is_a_permutation_of_the_children() {
        let sd = flat_body(3);
        let group = sd.get_rects_in_rendering_order();
        assert_eq!(group.root.into_crate_internal(), Some(NodeId::ZERO));
        let mut ids: Vec<usize> = group
            .children
            .as_ref()
            .iter()
            .filter_map(|c| c.root.into_crate_internal())
            .map(|n| n.index())
            .collect();
        ids.sort_unstable();
        assert_eq!(ids, vec![1, 2, 3], "every child appears exactly once");
    }
    #[test]
    fn get_rects_in_rendering_order_nests_grandchildren() {
        let sd = nested_body(); // body(0) > div(1) > div(2)
        let group = sd.get_rects_in_rendering_order();
        assert_eq!(group.children.as_ref().len(), 1);
        let child = &group.children.as_ref()[0];
        assert_eq!(child.root.into_crate_internal(), Some(NodeId::new(1)));
        assert_eq!(child.children.as_ref().len(), 1);
        assert_eq!(
            child.children.as_ref()[0].root.into_crate_internal(),
            Some(NodeId::new(2))
        );
    }
    #[test]
    fn determine_rendering_order_with_no_parents_yields_a_childless_root() {
        let sd = StyledDom::default();
        let hierarchy = sd.node_hierarchy.as_container();
        let styled = sd.styled_nodes.as_container();
        let data = sd.node_data.as_container();
        let group = StyledDom::determine_rendering_order(
            &[],
            &hierarchy,
            &styled,
            &data,
            sd.get_css_property_cache(),
        );
        assert_eq!(group.root.into_crate_internal(), Some(NodeId::ZERO));
        assert!(group.children.as_ref().is_empty());
    }
    #[test]
    fn sort_children_by_position_returns_every_child_of_a_leaf_free_parent() {
        let sd = flat_body(3);
        let hierarchy = sd.node_hierarchy.as_container();
        let styled = sd.styled_nodes.as_container();
        let data = sd.node_data.as_container();
        let sorted = sort_children_by_position(
            NodeId::ZERO,
            &hierarchy,
            &styled,
            &data,
            sd.get_css_property_cache(),
        );
        assert_eq!(sorted.len(), 3);
        // A leaf parent has no children at all.
        let leaf = sort_children_by_position(
            NodeId::new(3),
            &hierarchy,
            &styled,
            &data,
            sd.get_css_property_cache(),
        );
        assert!(leaf.is_empty());
    }
    #[test]
    fn fill_content_group_children_builds_the_nested_group_tree() {
        let id = |i: usize| NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(i)));
        let mut sorted: BTreeMap<NodeHierarchyItemId, Vec<NodeHierarchyItemId>> = BTreeMap::new();
        sorted.insert(id(0), vec![id(1), id(2)]);
        sorted.insert(id(1), vec![id(3)]);
        let mut group = ContentGroup {
            root: id(0),
            children: Vec::new().into(),
        };
        fill_content_group_children(&mut group, &sorted);
        assert_eq!(group.children.as_ref().len(), 2);
        assert_eq!(group.children.as_ref()[0].root, id(1));
        assert_eq!(group.children.as_ref()[0].children.as_ref().len(), 1);
        assert_eq!(group.children.as_ref()[0].children.as_ref()[0].root, id(3));
        assert!(
            group.children.as_ref()[1].children.as_ref().is_empty(),
            "a node with no entry in the map is a leaf"
        );
    }
    #[test]
    fn fill_content_group_children_leaves_an_unknown_root_untouched() {
        let sorted: BTreeMap<NodeHierarchyItemId, Vec<NodeHierarchyItemId>> = BTreeMap::new();
        let mut group = ContentGroup {
            root: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(9))),
            children: Vec::new().into(),
        };
        fill_content_group_children(&mut group, &sorted);
        assert!(group.children.as_ref().is_empty());
    }
    // ---------------------------------------------------------------------
    // recursive_get_last_child / get_path_to_root
    // ---------------------------------------------------------------------
    #[test]
    fn recursive_get_last_child_descends_to_the_deepest_last_child() {
        // 0 -> 1 -> 2 (2 is a leaf)
        let items = vec![
            raw_item(0, 0, 0, 2), // node 0, last_child = NodeId(1)
            raw_item(1, 0, 0, 3), // node 1, last_child = NodeId(2)
            raw_item(2, 0, 0, 0), // node 2, leaf
        ];
        let mut target = None;
        recursive_get_last_child(NodeId::ZERO, &items, &mut target);
        assert_eq!(target, Some(NodeId::new(2)));
    }
    #[test]
    fn recursive_get_last_child_leaves_the_target_untouched_for_a_leaf() {
        let items = vec![raw_item(0, 0, 0, 0)];
        let mut target = None;
        recursive_get_last_child(NodeId::ZERO, &items, &mut target);
        assert_eq!(target, None);
        // A pre-set target is also left alone.
        let mut preset = Some(NodeId::new(7));
        recursive_get_last_child(NodeId::ZERO, &items, &mut preset);
        assert_eq!(preset, Some(NodeId::new(7)));
    }
    #[test]
    fn get_path_to_root_is_root_first_and_tolerates_unknown_nodes() {
        let sd = nested_body(); // body(0) > div(1) > div(2)
        let h = sd.node_hierarchy.as_container();
        assert_eq!(get_path_to_root(&h, NodeId::ZERO), vec![NodeId::ZERO]);
        assert_eq!(
            get_path_to_root(&h, NodeId::new(2)),
            vec![NodeId::ZERO, NodeId::new(1), NodeId::new(2)]
        );
        // An id outside the arena yields a one-element path instead of panicking.
        assert_eq!(
            get_path_to_root(&h, NodeId::new(9999)),
            vec![NodeId::new(9999)]
        );
    }
    // ---------------------------------------------------------------------
    // document order
    // ---------------------------------------------------------------------
    #[test]
    fn is_before_in_document_order_is_false_for_identical_nodes() {
        let sd = flat_body(2);
        assert!(!is_before_in_document_order(
            &sd.node_hierarchy,
            NodeId::new(1),
            NodeId::new(1)
        ));
    }
    #[test]
    fn is_before_in_document_order_orders_ancestors_and_siblings() {
        let sd = flat_body(3); // body(0) > [1, 2, 3]
        let h = &sd.node_hierarchy;
        assert!(is_before_in_document_order(h, NodeId::ZERO, NodeId::new(1)));
        assert!(!is_before_in_document_order(
            h,
            NodeId::new(1),
            NodeId::ZERO
        ));
        assert!(is_before_in_document_order(
            h,
            NodeId::new(1),
            NodeId::new(3)
        ));
        assert!(!is_before_in_document_order(
            h,
            NodeId::new(3),
            NodeId::new(1)
        ));
    }
    #[test]
    fn is_before_in_document_order_is_antisymmetric_across_a_nested_tree() {
        let sd = nested_body();
        let h = &sd.node_hierarchy;
        for a in 0..3 {
            for b in 0..3 {
                let ab = is_before_in_document_order(h, NodeId::new(a), NodeId::new(b));
                let ba = is_before_in_document_order(h, NodeId::new(b), NodeId::new(a));
                if a == b {
                    assert!(!ab && !ba, "a node is never before itself");
                } else {
                    assert_ne!(ab, ba, "exactly one of ({a},{b}) / ({b},{a}) must hold");
                }
            }
        }
    }
    #[test]
    fn is_before_in_document_order_is_deterministic_for_unknown_nodes() {
        let sd = flat_body(1);
        let h = &sd.node_hierarchy;
        // Out-of-range ids fall back to a single-element path; the comparison must
        // still terminate and return a stable answer instead of panicking.
        assert!(is_before_in_document_order(
            h,
            NodeId::ZERO,
            NodeId::new(usize::MAX)
        ));
        assert!(!is_before_in_document_order(
            h,
            NodeId::new(usize::MAX),
            NodeId::ZERO
        ));
    }
    #[test]
    fn collect_nodes_in_document_order_start_equals_end() {
        let sd = flat_body(2);
        assert_eq!(
            collect_nodes_in_document_order(&sd.node_hierarchy, NodeId::new(2), NodeId::new(2)),
            vec![NodeId::new(2)]
        );
        // Even a bogus id short-circuits to itself (documented start == end path).
        assert_eq!(
            collect_nodes_in_document_order(
                &sd.node_hierarchy,
                NodeId::new(usize::MAX),
                NodeId::new(usize::MAX)
            ),
            vec![NodeId::new(usize::MAX)]
        );
    }
    #[test]
    fn collect_nodes_in_document_order_walks_the_tree_in_pre_order() {
        let sd = flat_body(3); // body(0) > [1, 2, 3]
        assert_eq!(
            collect_nodes_in_document_order(&sd.node_hierarchy, NodeId::ZERO, NodeId::new(3)),
            vec![NodeId::ZERO, NodeId::new(1), NodeId::new(2), NodeId::new(3)]
        );
        assert_eq!(
            collect_nodes_in_document_order(&sd.node_hierarchy, NodeId::new(1), NodeId::new(2)),
            vec![NodeId::new(1), NodeId::new(2)]
        );
        // Nested: body(0) > div(1) > div(2) — pre-order is 0, 1, 2.
        let nested = nested_body();
        assert_eq!(
            collect_nodes_in_document_order(&nested.node_hierarchy, NodeId::ZERO, NodeId::new(2)),
            vec![NodeId::ZERO, NodeId::new(1), NodeId::new(2)]
        );
    }
    #[test]
    fn collect_nodes_in_document_order_terminates_when_end_precedes_start() {
        // The traversal hits `end` before it ever enters the range, so it bails
        // out with an empty result rather than looping forever.
        let sd = flat_body(3);
        let out =
            collect_nodes_in_document_order(&sd.node_hierarchy, NodeId::new(2), NodeId::new(1));
        assert!(out.is_empty());
    }
    #[test]
    fn collect_nodes_in_document_order_with_an_unreachable_end_stops_at_the_tree_end() {
        let sd = flat_body(3);
        let out = collect_nodes_in_document_order(
            &sd.node_hierarchy,
            NodeId::new(1),
            NodeId::new(usize::MAX),
        );
        assert_eq!(
            out,
            vec![NodeId::new(1), NodeId::new(2), NodeId::new(3)],
            "an end node that is never reached must terminate at the end of the traversal"
        );
    }
    // ---------------------------------------------------------------------
    // is_layout_equivalent
    // ---------------------------------------------------------------------
    #[test]
    fn is_layout_equivalent_holds_for_independently_built_identical_doms() {
        assert!(is_layout_equivalent(&flat_body(3), &flat_body(3)));
        assert!(is_layout_equivalent(
            &StyledDom::default(),
            &StyledDom::default()
        ));
        assert!(is_layout_equivalent(&nested_body(), &nested_body()));
    }
    #[test]
    fn is_layout_equivalent_rejects_a_different_node_count() {
        assert!(!is_layout_equivalent(&flat_body(3), &flat_body(4)));
        assert!(!is_layout_equivalent(&flat_body(0), &flat_body(1)));
    }
    #[test]
    fn is_layout_equivalent_rejects_a_different_structure() {
        // Same node count (3), different shape: [body > div > div] vs [body > div, div]
        assert!(!is_layout_equivalent(&nested_body(), &flat_body(2)));
    }
    #[test]
    fn is_layout_equivalent_rejects_a_changed_class() {
        let build = |class: &str| {
            let mut dom = Dom::create_body()
                .with_children(vec![Dom::create_div().with_class(class.to_string().into())].into());
            StyledDom::create(&mut dom, Css::empty())
        };
        assert!(is_layout_equivalent(&build("a"), &build("a")));
        assert!(!is_layout_equivalent(&build("a"), &build("b")));
    }
    #[test]
    fn is_layout_equivalent_rejects_a_changed_pseudo_state() {
        let base = flat_body(2);
        let mut hovered = flat_body(2);
        let _ = hovered.restyle_nodes_hover(&[NodeId::new(1)], true);
        assert!(
            !is_layout_equivalent(&base, &hovered),
            ":hover changes CSS resolution, so the DOMs are not layout-equivalent"
        );
    }
    // ---------------------------------------------------------------------
    // CompactDom + convert_dom_into_compact_dom
    // ---------------------------------------------------------------------
    #[test]
    fn compact_dom_len_and_is_empty() {
        let single = convert_dom_into_compact_dom(Dom::create_div());
        assert_eq!(single.len(), 1);
        assert!(!single.is_empty());
        let tree = convert_dom_into_compact_dom(
            Dom::create_body().with_children(vec![Dom::create_div(); 4].into()),
        );
        assert_eq!(tree.len(), 5);
        assert!(!tree.is_empty());
        // A hand-built zero-node arena is the only way to observe is_empty() == true.
        let empty = CompactDom {
            node_hierarchy: NodeHierarchy {
                internal: Vec::new(),
            },
            node_data: NodeDataContainer {
                internal: Vec::new(),
            },
            root: NodeId::ZERO,
        };
        assert_eq!(empty.len(), 0);
        assert!(empty.is_empty());
    }
    #[test]
    fn convert_dom_into_compact_dom_links_flat_siblings() {
        let compact = convert_dom_into_compact_dom(
            Dom::create_body().with_children(vec![Dom::create_div(); 3].into()),
        );
        assert_eq!(compact.len(), 4);
        assert_eq!(compact.root, NodeId::ZERO);
        let h = compact.node_hierarchy.as_ref();
        assert_eq!(h[NodeId::ZERO].parent, None);
        assert_eq!(h[NodeId::ZERO].last_child, Some(NodeId::new(3)));
        for i in 1..=3usize {
            assert_eq!(h[NodeId::new(i)].parent, Some(NodeId::ZERO));
            let expected_next = if i == 3 {
                None
            } else {
                Some(NodeId::new(i + 1))
            };
            assert_eq!(h[NodeId::new(i)].next_sibling, expected_next);
            let expected_prev = if i == 1 {
                None
            } else {
                Some(NodeId::new(i - 1))
            };
            assert_eq!(h[NodeId::new(i)].previous_sibling, expected_prev);
            assert_eq!(
                h[NodeId::new(i)].last_child,
                None,
                "the children are leaves"
            );
        }
    }
    /// ADVERSARIAL: `last_child` must name the last DIRECT child — that is the
    /// contract `NodeHierarchyItem::last_child_id()` documents, the one
    /// `az_reverse_children` walks backwards from, and the one `append_child`
    /// splices new siblings onto. The flat encoding computes it as
    /// `node_id + estimated_total_children`, which is the last node of the whole
    /// SUBTREE — those coincide only when the last direct child is a leaf.
    #[test]
    fn convert_dom_into_compact_dom_last_child_is_the_last_direct_child() {
        // body(0) > div(1) > div(2): the body's only direct child is node 1.
        let sd = nested_body();
        let h = sd.node_hierarchy.as_container();
        let last_direct_child = NodeId::ZERO.az_children(&h).last();
        assert_eq!(last_direct_child, Some(NodeId::new(1)));
        assert_eq!(
            h[NodeId::ZERO].last_child_id(),
            last_direct_child,
            "last_child_id() must agree with the forward child iteration"
        );
    }
    #[test]
    fn convert_dom_into_compact_dom_handles_an_empty_and_a_deep_tree() {
        assert_eq!(convert_dom_into_compact_dom(Dom::create_body()).len(), 1);
        let mut deep = Dom::create_div();
        for _ in 0..64 {
            deep = Dom::create_div().with_children(vec![deep].into());
        }
        let compact = convert_dom_into_compact_dom(deep);
        assert_eq!(compact.len(), 65);
        // Pre-order ids: every node's parent is the node right before it.
        let h = compact.node_hierarchy.as_ref();
        for i in 1..65usize {
            assert_eq!(h[NodeId::new(i)].parent, Some(NodeId::new(i - 1)));
        }
    }
    // ---------------------------------------------------------------------
    // scope_inline_css / collect_css_from_dom / strip_css_from_dom
    // ---------------------------------------------------------------------
    #[test]
    fn scope_inline_css_advances_next_id_once_per_node() {
        let mut dom = Dom::create_body().with_children(
            vec![
                Dom::create_div().with_children(vec![Dom::create_div()].into()),
                Dom::create_div(),
            ]
            .into(),
        );
        let _ = dom.fixup_children_estimated();
        let mut next = 0usize;
        scope_inline_css(&mut dom, &mut next);
        assert_eq!(
            next, 4,
            "4 nodes → the counter must land on 4 (pre-order ids 0..3)"
        );
    }
    #[test]
    fn scope_inline_css_from_zero_and_from_a_large_offset() {
        let mut leaf = Dom::create_div();
        let _ = leaf.fixup_children_estimated();
        let mut next = 0usize;
        scope_inline_css(&mut leaf, &mut next);
        assert_eq!(next, 1, "a single leaf consumes exactly one id");
        // A large (but non-saturating) starting id must not panic or wrap.
        let mut dom = Dom::create_body().with_children(vec![Dom::create_div(); 2].into());
        let _ = dom.fixup_children_estimated();
        let mut big = 1_000_000usize;
        scope_inline_css(&mut dom, &mut big);
        assert_eq!(big, 1_000_003);
    }
    #[test]
    fn scope_inline_css_preserves_the_rule_count_of_every_node() {
        let mut dom = Dom::create_body()
            .with_css("color: red")
            .with_children(vec![Dom::create_div().with_css("width: 5px")].into());
        let _ = dom.fixup_children_estimated();
        let rules_before: usize = dom
            .css
            .as_ref()
            .iter()
            .map(|c| c.rules.as_ref().len())
            .sum::<usize>()
            + dom.children.as_ref()[0]
                .css
                .as_ref()
                .iter()
                .map(|c| c.rules.as_ref().len())
                .sum::<usize>();
        assert!(rules_before > 0, "with_css must produce at least one rule");
        let mut next = 0usize;
        scope_inline_css(&mut dom, &mut next);
        let rules_after: usize = dom
            .css
            .as_ref()
            .iter()
            .map(|c| c.rules.as_ref().len())
            .sum::<usize>()
            + dom.children.as_ref()[0]
                .css
                .as_ref()
                .iter()
                .map(|c| c.rules.as_ref().len())
                .sum::<usize>();
        assert_eq!(
            rules_before, rules_after,
            "scoping rewrites paths in place; it must not add or drop rules"
        );
        assert_eq!(next, 2);
    }
    #[test]
    fn collect_css_from_dom_yields_inner_css_before_outer_css() {
        let outer = parse_css("div { color: red; } span { color: blue; }");
        let inner = parse_css("p { color: green; }");
        let outer_rules = outer.rules.as_ref().len();
        let inner_rules = inner.rules.as_ref().len();
        assert_ne!(
            outer_rules, inner_rules,
            "the two stylesheets must be distinguishable by rule count"
        );
        let mut child = Dom::create_div();
        child.add_component_css(inner);
        let mut dom = Dom::create_body().with_children(vec![child].into());
        dom.add_component_css(outer);
        let mut out = Vec::new();
        collect_css_from_dom(&dom, &mut out);
        assert_eq!(out.len(), 2);
        assert_eq!(
            out[0].rules.as_ref().len(),
            inner_rules,
            "deeper CSS is collected first (lower cascade priority)"
        );
        assert_eq!(out[1].rules.as_ref().len(), outer_rules);
    }
    #[test]
    fn collect_css_from_dom_on_a_css_free_tree_appends_nothing() {
        let dom = Dom::create_body().with_children(vec![Dom::create_div(); 3].into());
        let mut out = Vec::new();
        collect_css_from_dom(&dom, &mut out);
        assert!(out.is_empty());
        // ...and an already-populated `out` is appended to, not replaced.
        let mut prefilled = vec![Css::empty()];
        collect_css_from_dom(&dom, &mut prefilled);
        assert_eq!(prefilled.len(), 1);
    }
    #[test]
    fn strip_css_from_dom_clears_every_node_recursively() {
        let mut dom = Dom::create_body().with_css("color: red").with_children(
            vec![Dom::create_div()
                .with_css("width: 5px")
                .with_children(vec![Dom::create_div().with_css("height: 5px")].into())]
            .into(),
        );
        assert!(!dom.css.as_ref().is_empty());
        strip_css_from_dom(&mut dom);
        assert!(dom.css.as_ref().is_empty());
        let child = &dom.children.as_ref()[0];
        assert!(child.css.as_ref().is_empty());
        assert!(child.children.as_ref()[0].css.as_ref().is_empty());
        // Idempotent.
        strip_css_from_dom(&mut dom);
        assert!(dom.css.as_ref().is_empty());
    }
    // ---------------------------------------------------------------------
    // hierarchy_ancestors — THE DOM ancestor walk, explicit inclusivity
    // ---------------------------------------------------------------------
    /// 0 <- 1 <- 2 (the `parent` field is 1-based encoded: 0 = none).
    fn linear_hierarchy() -> [NodeHierarchyItem; 3] {
        [
            NodeHierarchyItem {
                parent: 0,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 2,
            },
            NodeHierarchyItem {
                parent: 1,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 3,
            },
            NodeHierarchyItem {
                parent: 2,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
        ]
    }
    fn walk(h: &[NodeHierarchyItem], n: usize, incl: crate::spaces::Inclusivity) -> Vec<usize> {
        hierarchy_ancestors(h, NodeId::new(n), incl)
            .map(|n| n.index())
            .collect()
    }
    #[test]
    fn hierarchy_ancestors_inclusivity_decides_only_the_first_element() {
        use crate::spaces::Inclusivity;
        let h = linear_hierarchy();
        assert_eq!(walk(&h, 2, Inclusivity::SelfAndAncestors), vec![2, 1, 0]);
        assert_eq!(walk(&h, 2, Inclusivity::AncestorsOnly), vec![1, 0]);
        assert_eq!(walk(&h, 0, Inclusivity::SelfAndAncestors), vec![0]);
        assert!(walk(&h, 0, Inclusivity::AncestorsOnly).is_empty());
    }
    #[test]
    fn hierarchy_ancestors_survives_empty_and_out_of_range_input() {
        use crate::spaces::Inclusivity;
        for incl in [Inclusivity::AncestorsOnly, Inclusivity::SelfAndAncestors] {
            // An empty hierarchy has a zero budget, so nothing is yielded even
            // self-inclusively — and, crucially, nothing is indexed.
            assert!(walk(&[], 0, incl).is_empty());
            assert!(walk(&[], 9_999, incl).is_empty());
        }
        let h = linear_hierarchy();
        assert!(walk(&h, 9_999, Inclusivity::AncestorsOnly).is_empty());
        assert_eq!(walk(&h, 9_999, Inclusivity::SelfAndAncestors), vec![9_999]);
    }
    #[test]
    fn hierarchy_ancestors_terminates_on_a_cycle() {
        use crate::spaces::Inclusivity;
        // 0 -> 1 -> 0
        let h = [
            NodeHierarchyItem {
                parent: 2,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
            NodeHierarchyItem {
                parent: 1,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
        ];
        let walked = walk(&h, 0, Inclusivity::SelfAndAncestors);
        assert!(
            walked.len() <= h.len(),
            "the budget must stop a cyclic chain"
        );
    }
}
/// Theme-chain analysis 2026-09-12, item 1: a theme flip is a RESTYLE.
///
/// `set_dynamic_selector_context` used to rebuild the compact cache only, so
/// `cascaded_props` / `computed_values` — what the slow path and the display
/// list read — kept the answers of the context the DOM was created under.
/// These pin the re-cascade and its idempotence (a UA entry is replaced, never
/// duplicated, on every flip).
#[cfg(test)]
mod theme_flip_is_a_restyle {
    use azul_css::{
        dynamic_selector::{DynamicSelectorContext, PseudoStateType, ThemeCondition},
        props::property::CssPropertyType,
    };
    use super::*;
    use crate::dom::NodeType;
22
    fn ctx(theme: ThemeCondition) -> DynamicSelectorContext {
22
        DynamicSelectorContext {
22
            theme,
22
            ..Default::default()
22
        }
22
    }
    /// `body > button`, no author css, no inline style: the button's border
    /// colour is a themed UA default (light `#c8c8c8`, dark `#5a5a5a`).
6
    fn body_with_button() -> Dom {
6
        Dom::create_body().with_child(Dom::create_node(NodeType::Button))
6
    }
    const BUTTON: NodeId = NodeId::new(1);
7
    fn border_top_color(sd: &StyledDom) -> Option<CssProperty> {
7
        let node_data = sd.node_data.as_container();
7
        sd.get_css_property_cache()
7
            .get_property_slow(
7
                &node_data[BUTTON],
7
                &BUTTON,
7
                &StyledNodeState::default(),
7
                &CssPropertyType::BorderTopColor,
            )
7
            .cloned()
7
    }
9
    fn ua_border_top_color(theme: ThemeCondition) -> CssProperty {
9
        crate::ua_css::get_ua_property_themed(
9
            &NodeType::Button,
9
            CssPropertyType::BorderTopColor,
9
            Some(&ctx(theme)),
        )
9
        .cloned()
9
        .expect("the UA sheet defines the button border")
9
    }
    /// The Normal-state `BorderTopColor` entries in the button's cascaded
    /// slice, with their origin tag.
3
    fn cascaded_border_entries(sd: &StyledDom) -> Vec<(CssProperty, bool)> {
3
        sd.get_css_property_cache()
3
            .cascaded_props
3
            .get_slice(BUTTON.index())
3
            .iter()
57
            .filter(|p| {
57
                p.state == PseudoStateType::Normal && p.prop_type == CssPropertyType::BorderTopColor
57
            })
3
            .map(|p| (p.property.clone(), p.ua_origin))
3
            .collect()
3
    }
    #[test]
1
    fn a_theme_flip_replaces_the_ua_defaults_in_cascaded_props() {
1
        let mut dom = body_with_button();
1
        let mut sd = StyledDom::create(&mut dom, Css::empty());
1
        assert_eq!(
1
            border_top_color(&sd),
1
            Some(ua_border_top_color(ThemeCondition::Light)),
            "no context yet: the light table"
        );
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Dark));
1
        assert_eq!(
1
            border_top_color(&sd),
1
            Some(ua_border_top_color(ThemeCondition::Dark)),
            "the dark window's border must be the dark twin, in the resolved style"
        );
1
        assert_eq!(
1
            cascaded_border_entries(&sd),
1
            vec![(ua_border_top_color(ThemeCondition::Dark), true)],
            "exactly ONE UA-origin entry: the light one was stripped, not shadowed"
        );
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Light));
1
        assert_eq!(
1
            border_top_color(&sd),
1
            Some(ua_border_top_color(ThemeCondition::Light)),
            "and back"
        );
1
        assert_eq!(
1
            cascaded_border_entries(&sd),
1
            vec![(ua_border_top_color(ThemeCondition::Light), true)],
            "still one entry after the second flip"
        );
1
    }
    #[test]
1
    fn a_dom_created_under_a_context_is_cascaded_for_it_at_once() {
1
        let mut dom = body_with_button();
1
        let mut sd =
1
            StyledDom::create_with_context(&mut dom, Css::empty(), Some(ctx(ThemeCondition::Dark)));
1
        assert_eq!(
1
            border_top_color(&sd),
1
            Some(ua_border_top_color(ThemeCondition::Dark)),
            "born dark: the first cascade already answered the dark table"
        );
        // (Creation prunes the compact-encoded Normal entries out of
        // `cascaded_props` — the compact cache and `computed_values` carry
        // them — so the border is asserted through the readers, not the
        // store: the slow path above, the compact tier here.)
1
        let dark_raw = sd
1
            .get_css_property_cache()
1
            .compact_cache
1
            .as_ref()
1
            .map(|cc| cc.get_border_top_color_raw(BUTTON.index()))
1
            .expect("compact cache built at creation");
1
        assert_ne!(dark_raw, 0, "the border is in the compact tier");
1
        let epoch_before = sd.get_css_property_cache().cascade_epoch;
1
        let cascaded_before = sd.get_css_property_cache().cascaded_props.clone();
        // The funnel's offer of the SAME context is a no-op: no new
        // generation, no second cascade, nothing pushed twice.
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Dark));
1
        assert_eq!(
1
            sd.get_css_property_cache().cascade_epoch,
            epoch_before,
            "same context: not a new generation"
        );
1
        assert_eq!(sd.get_css_property_cache().cascaded_props, cascaded_before);
1
        assert_eq!(
1
            border_top_color(&sd),
1
            Some(ua_border_top_color(ThemeCondition::Dark))
        );
1
    }
    #[test]
1
    fn create_from_dom_with_context_threads_the_context_through() {
1
        let sd = StyledDom::create_from_dom_with_context(
1
            body_with_button(),
1
            Some(ctx(ThemeCondition::Dark)),
        );
1
        assert_eq!(
1
            sd.get_css_property_cache()
1
                .dynamic_context
1
                .as_deref()
1
                .map(|c| c.theme.clone()),
            Some(ThemeCondition::Dark)
        );
1
        assert_eq!(
1
            border_top_color(&sd),
1
            Some(ua_border_top_color(ThemeCondition::Dark))
        );
1
    }
    /// `restyle` with an empty sheet used to push into a flattened (emptied)
    /// build vec and panic; a theme flip on an inline-styled widget DOM is
    /// exactly that call.
    #[test]
1
    fn restyle_with_an_empty_stylesheet_recascades_instead_of_panicking() {
1
        let mut dom = body_with_button();
1
        let mut sd = StyledDom::create(&mut dom, Css::empty());
1
        sd.restyle(Css::empty());
1
        assert_eq!(
1
            border_top_color(&sd),
1
            Some(ua_border_top_color(ThemeCondition::Light))
        );
1
        assert_eq!(
1
            cascaded_border_entries(&sd).len(),
            1,
            "a second full cascade must not duplicate the UA entry"
        );
1
        assert!(sd.get_css_property_cache().ua_applied);
1
    }
    #[test]
1
    fn a_context_change_that_keeps_the_theme_costs_nothing_on_a_plain_dom() {
1
        let mut dom = body_with_button();
1
        let mut sd = StyledDom::create_with_context(
1
            &mut dom,
1
            Css::empty(),
1
            Some(ctx(ThemeCondition::Light)),
        );
1
        let before = sd.get_css_property_cache().cascaded_props.clone();
        // A resize: same theme, different viewport.
1
        let resized = ctx(ThemeCondition::Light).with_viewport(320.0, 240.0);
1
        sd.set_dynamic_selector_context(resized);
1
        assert_eq!(
1
            sd.get_css_property_cache().cascaded_props,
            before,
            "no conditional declaration anywhere, same theme: the cascade must be untouched"
        );
1
    }
    // ------------------------------------------------------------------
    // Item 3: one themed UA table, the text colour IN the resolved style
    // ------------------------------------------------------------------
    #[test]
1
    fn a_theme_flip_rebuilds_the_compact_cache_from_the_new_defaults() {
1
        let mut dom = body_with_button();
1
        let mut sd = StyledDom::create(&mut dom, Css::empty());
1
        let light_raw = sd
1
            .get_css_property_cache()
1
            .compact_cache
1
            .as_ref()
1
            .map(|cc| cc.get_border_top_color_raw(BUTTON.index()))
1
            .expect("compact cache built at creation");
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Dark));
1
        let dark_raw = sd
1
            .get_css_property_cache()
1
            .compact_cache
1
            .as_ref()
1
            .map(|cc| cc.get_border_top_color_raw(BUTTON.index()))
1
            .expect("compact cache rebuilt on the flip");
1
        assert_ne!(light_raw, 0, "the light border is in the compact tier");
1
        assert_ne!(dark_raw, 0, "the dark border is in the compact tier");
1
        assert_ne!(
            light_raw, dark_raw,
            "the compact (normal-state fast path) tier must follow the theme too"
        );
1
    }
    /// `body > p > "text"`, nothing styled: the text colour is the UA's
    /// document default, and it must be IN the resolved style of every node
    /// on every reader — root `cascaded_props`, descendant `computed_values`
    /// (the slow path), the compact text tier (the fast path).
4
    fn body_p_text() -> Dom {
4
        Dom::create_body().with_child(
4
            Dom::create_p()
4
                .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("5")),
        )
4
    }
    const ROOT: NodeId = NodeId::new(0);
    const TEXT: NodeId = NodeId::new(2);
6
    fn slow_text_color(sd: &StyledDom, node: NodeId) -> Option<(u8, u8, u8)> {
6
        let node_data = sd.node_data.as_container();
6
        match sd.get_css_property_cache().get_property_slow(
6
            &node_data[node],
6
            &node,
6
            &StyledNodeState::default(),
6
            &CssPropertyType::TextColor,
        ) {
6
            Some(CssProperty::TextColor(v)) => {
6
                v.get_property().map(|c| (c.inner.r, c.inner.g, c.inner.b))
            }
            _ => None,
        }
6
    }
5
    fn compact_text_color(sd: &StyledDom, node: NodeId) -> Option<(u8, u8, u8)> {
5
        let raw = sd
5
            .get_css_property_cache()
5
            .compact_cache
5
            .as_ref()
5
            .map(|cc| cc.get_text_color_raw(node.index()))
5
            .unwrap_or(0);
5
        (raw != 0).then_some(((raw >> 24) as u8, (raw >> 16) as u8, (raw >> 8) as u8))
5
    }
    const BLACK: (u8, u8, u8) = (0, 0, 0);
    const DARK_INK: (u8, u8, u8) = (0xe8, 0xe8, 0xe8);
    #[test]
1
    fn the_ua_text_colour_is_cascaded_onto_the_root_and_inherited_below() {
1
        let mut dom = body_p_text();
1
        let sd =
1
            StyledDom::create_with_context(&mut dom, Css::empty(), Some(ctx(ThemeCondition::Dark)));
        // `computed_values` is the record of the cascade (creation prunes
        // the compact-encoded Normal entries out of `cascaded_props` once
        // the compact cache holds them): the root OWNS the colour — it came
        // from the UA table, not from a parent — and every descendant
        // INHERITS it rather than declaring one of its own (a UA `color` on
        // a child would block inheritance of an author colour above it).
        use crate::prop_cache::CssPropertyOrigin;
1
        let cv = &sd.get_css_property_cache().computed_values;
1
        let root = cv
1
            .get(ROOT.index(), CssPropertyType::TextColor)
1
            .expect("the root's resolved style carries `color`");
1
        assert_eq!(
            root.origin,
            CssPropertyOrigin::Own,
            "cascaded ONTO the root"
        );
2
        for node in [NodeId::new(1), TEXT] {
2
            let v = cv
2
                .get(node.index(), CssPropertyType::TextColor)
2
                .unwrap_or_else(|| panic!("node {} has no resolved `color`", node.index()));
2
            assert_eq!(
                v.origin,
                CssPropertyOrigin::Inherited,
                "node {} must inherit the root's colour, not own a UA one",
                node.index()
            );
        }
1
        assert_eq!(slow_text_color(&sd, ROOT), Some(DARK_INK));
1
        assert_eq!(
1
            slow_text_color(&sd, TEXT),
            Some(DARK_INK),
            "computed_values"
        );
1
        assert_eq!(
1
            compact_text_color(&sd, TEXT),
            Some(DARK_INK),
            "compact text tier"
        );
1
    }
    #[test]
1
    fn the_two_readers_agree_on_the_text_colour_under_both_themes_and_across_a_flip() {
1
        let mut dom = body_p_text();
1
        let mut sd = StyledDom::create(&mut dom, Css::empty());
1
        assert_eq!(slow_text_color(&sd, TEXT), Some(BLACK), "no context: light");
1
        assert_eq!(compact_text_color(&sd, TEXT), Some(BLACK));
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Dark));
1
        assert_eq!(
1
            slow_text_color(&sd, TEXT),
            Some(DARK_INK),
            "dark: slow path"
        );
1
        assert_eq!(
1
            compact_text_color(&sd, TEXT),
            Some(DARK_INK),
            "dark: fast path"
        );
        // The re-cascade does not prune, so here the store shows the entry
        // itself: exactly one, UA-origin, on the root and nowhere else.
3
        let ua_color_entries = |node: NodeId| -> Vec<bool> {
3
            sd.get_css_property_cache()
3
                .cascaded_props
3
                .get_slice(node.index())
3
                .iter()
11
                .filter(|p| p.prop_type == CssPropertyType::TextColor)
3
                .map(|p| p.ua_origin)
3
                .collect()
3
        };
1
        assert_eq!(
1
            ua_color_entries(ROOT),
1
            vec![true],
            "one UA `color` on the root"
        );
1
        assert_eq!(ua_color_entries(NodeId::new(1)), Vec::<bool>::new());
1
        assert_eq!(ua_color_entries(TEXT), Vec::<bool>::new());
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Light));
1
        assert_eq!(slow_text_color(&sd, TEXT), Some(BLACK), "back: slow path");
1
        assert_eq!(
1
            compact_text_color(&sd, TEXT),
            Some(BLACK),
            "back: fast path"
        );
1
    }
    #[test]
1
    fn get_text_color_or_default_never_needs_its_default_on_a_cascaded_dom() {
1
        let mut dom = body_p_text();
1
        let sd =
1
            StyledDom::create_with_context(&mut dom, Css::empty(), Some(ctx(ThemeCondition::Dark)));
1
        let node_data = sd.node_data.as_container();
3
        for i in 0..sd.node_count() {
3
            let n = NodeId::new(i);
3
            let c = sd.get_css_property_cache().get_text_color_or_default(
3
                &node_data[n],
3
                &n,
3
                &StyledNodeState::default(),
            );
3
            assert_eq!((c.inner.r, c.inner.g, c.inner.b), DARK_INK, "node {i}");
        }
1
    }
    #[test]
1
    fn an_author_colour_on_the_root_beats_the_ua_default() {
1
        let mut dom = body_p_text();
1
        dom.set_css("color: rgb(10, 20, 30);");
1
        let sd =
1
            StyledDom::create_with_context(&mut dom, Css::empty(), Some(ctx(ThemeCondition::Dark)));
1
        assert_eq!(slow_text_color(&sd, TEXT), Some((10, 20, 30)));
1
        assert_eq!(compact_text_color(&sd, TEXT), Some((10, 20, 30)));
1
        assert!(
1
            sd.get_css_property_cache()
1
                .cascaded_props
1
                .get_slice(ROOT.index())
1
                .iter()
1
                .all(|p| !(p.prop_type == CssPropertyType::TextColor && p.ua_origin)),
            "an inline `color` on the root suppresses the UA entry"
        );
1
    }
}
/// Theme-chain analysis 2026-09-12, item 4: `CssPropertyCache::cascade_epoch`
/// is the ONE key that tells two cascades of one DOM apart for every cache
/// that serves painted output.
#[cfg(test)]
mod cascade_epoch {
    use azul_css::{
        dynamic_selector::{DynamicSelectorContext, ThemeCondition},
        props::{basic::color::ColorU, style::StyleTextColor},
    };
    use super::*;
8
    fn ctx(theme: ThemeCondition) -> DynamicSelectorContext {
8
        DynamicSelectorContext {
8
            theme,
8
            ..Default::default()
8
        }
8
    }
5
    fn fixture() -> StyledDom {
5
        let mut dom = Dom::create_body().with_child(
5
            Dom::create_p()
5
                .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("5")),
        );
5
        StyledDom::create_with_context(&mut dom, Css::empty(), Some(ctx(ThemeCondition::Light)))
5
    }
12
    fn epoch(sd: &StyledDom) -> u64 {
12
        sd.get_css_property_cache().cascade_epoch
12
    }
2
    fn red() -> CssProperty {
2
        CssProperty::const_text_color(StyleTextColor {
2
            inner: ColorU::rgb(255, 0, 0),
2
        })
2
    }
    #[test]
1
    fn a_theme_flip_bumps_the_epoch_and_an_equal_offer_does_not() {
1
        let mut sd = fixture();
1
        let e0 = epoch(&sd);
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Light));
1
        assert_eq!(epoch(&sd), e0, "the same context again is free");
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Dark));
1
        assert_ne!(epoch(&sd), e0, "a flip is a new generation");
1
    }
    #[test]
1
    fn a_context_change_without_a_recascade_still_bumps() {
        // Plain DOM, same theme, different viewport: nothing re-cascades,
        // but the context is a cascade input and the DL key must move.
1
        let mut sd = fixture();
1
        let e0 = epoch(&sd);
1
        sd.set_dynamic_selector_context(ctx(ThemeCondition::Light).with_viewport(1.0, 1.0));
1
        assert_ne!(epoch(&sd), e0);
1
    }
    #[test]
1
    fn a_restyle_bumps() {
1
        let mut sd = fixture();
1
        let e0 = epoch(&sd);
1
        sd.restyle(Css::empty());
1
        assert_ne!(epoch(&sd), e0);
1
    }
    #[test]
1
    fn a_user_override_bumps_but_the_per_tick_channel_does_not() {
1
        let mut sd = fixture();
1
        let e0 = epoch(&sd);
1
        let _ = sd.restyle_user_property(&NodeId::new(1), &[red()]);
1
        let e1 = epoch(&sd);
1
        assert_ne!(e1, e0, "restyle_user_property changes the resolved style");
1
        sd.set_user_property_override_fast(&NodeId::new(1), &[red()]);
1
        assert_eq!(
1
            epoch(&sd),
            e1,
            "the animation channel patches the display list itself and must not invalidate the DL \
             cache every tick"
        );
1
    }
    #[test]
1
    fn a_recompute_of_the_compact_cache_bumps() {
1
        let mut sd = fixture();
1
        let e0 = epoch(&sd);
1
        sd.recompute_inheritance_and_compact_cache();
1
        assert_ne!(epoch(&sd), e0);
1
    }
}