1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(clippy::float_cmp, clippy::too_many_lines)]
5
mod autotest_generated {
6
    use azul_css::{
7
        css::CssPropertyValue,
8
        dynamic_selector::{
9
            CssPropertyWithConditions, DynamicSelector, DynamicSelectorContext, PseudoStateType,
10
        },
11
        props::{
12
            basic::{length::SizeMetric, pixel::PixelValue},
13
            layout::{
14
                LayoutFlexBasis, LayoutInsetBottom, LayoutLeft, LayoutMarginTop, LayoutMaxWidth,
15
                LayoutMinWidth, LayoutOverflow, LayoutPaddingLeft, LayoutRight, LayoutTop,
16
            },
17
            style::LayoutBorderLeftWidth,
18
        },
19
    };
20

            
21
    use super::*;
22

            
23
    // ---------------------------------------------------------------------
24
    // helpers
25
    // ---------------------------------------------------------------------
26

            
27
    /// Approximate float compare — every value here round-trips through
28
    /// `FloatValue`'s fixed-point (1/1000) encoding.
29
    fn close(a: f32, b: f32) -> bool {
30
        (a - b).abs() < 0.01
31
    }
32

            
33
    fn n0() -> NodeId {
34
        NodeId::new(0)
35
    }
36

            
37
    fn normal() -> StyledNodeState {
38
        StyledNodeState::default()
39
    }
40

            
41
    /// A `<div>` carrying `props` as unconditional (Normal-state) inline CSS.
42
    fn div_with(props: Vec<CssProperty>) -> NodeData {
43
        let mut nd = NodeData::create_div();
44
        for property in props {
45
            nd.add_css_property(CssPropertyWithConditions {
46
                property,
47
                apply_if: Vec::new().into(),
48
            });
49
        }
50
        nd
51
    }
52

            
53
    /// A `<div>` carrying `props` gated on a single pseudo-state.
54
    fn div_with_pseudo(props: Vec<CssProperty>, state: PseudoStateType) -> NodeData {
55
        let mut nd = NodeData::create_div();
56
        for property in props {
57
            nd.add_css_property(CssPropertyWithConditions {
58
                property,
59
                apply_if: vec![DynamicSelector::PseudoState(state)].into(),
60
            });
61
        }
62
        nd
63
    }
64

            
65
    fn width_px(v: f32) -> CssProperty {
66
        CssProperty::Width(CssPropertyValue::Exact(LayoutWidth::Px(PixelValue::px(v))))
67
    }
68

            
69
    fn width_pct(v: f32) -> CssProperty {
70
        CssProperty::Width(CssPropertyValue::Exact(LayoutWidth::Px(
71
            PixelValue::percent(v),
72
        )))
73
    }
74

            
75
    fn font_size(pv: PixelValue) -> CssProperty {
76
        CssProperty::FontSize(CssPropertyValue::Exact(StyleFontSize { inner: pv }))
77
    }
78

            
79
    /// Pull `(metric, number)` back out of a `CssProperty::FontSize`.
80
    fn font_size_parts(p: &CssProperty) -> Option<(SizeMetric, f32)> {
81
        match p {
82
            CssProperty::FontSize(v) => v
83
                .get_property()
84
                .map(|fs| (fs.inner.metric, fs.inner.number.get())),
85
            _ => None,
86
        }
87
    }
88

            
89
    fn stateful(state: PseudoStateType, property: CssProperty) -> StatefulCssProperty {
90
        StatefulCssProperty {
91
            state,
92
            prop_type: property.get_type(),
93
            property,
94
            ua_origin: false,
95
        }
96
    }
97

            
98
    // =====================================================================
99
    // FlatVecVec — construction / getters / predicates
100
    // =====================================================================
101

            
102
    #[test]
103
    fn flatvecvec_new_zero_is_empty() {
104
        let f = FlatVecVec::<i32>::new(0);
105
        assert_eq!(f.len(), 0);
106
        assert!(f.is_empty());
107
        // Quirk worth pinning: with no build slots at all, `is_flattened()` is
108
        // vacuously true (`build.is_empty()`), even though `flatten()` never ran.
109
        assert!(f.is_flattened());
110
        assert!(f.get_slice(0).is_empty());
111
    }
112

            
113
    #[test]
114
    fn flatvecvec_new_invariants_hold() {
115
        let f = FlatVecVec::<i32>::new(3);
116
        assert_eq!(f.len(), 3);
117
        assert!(!f.is_empty());
118
        assert!(!f.is_flattened(), "fresh multi-slot vec is in build phase");
119
        assert_eq!(f.build_get(0), Some(&Vec::new()));
120
        assert_eq!(f.build_get(2), Some(&Vec::new()));
121
        assert_eq!(f.build_get(3), None, "one past the end");
122
        assert_eq!(f.build_get(usize::MAX), None);
123
        assert!(f.get_slice(0).is_empty());
124
    }
125

            
126
    #[test]
127
    fn flatvecvec_default_is_neutral() {
128
        let f = FlatVecVec::<i32>::default();
129
        assert_eq!(f.len(), 0);
130
        assert!(f.is_empty());
131
        assert_eq!(f.build_get(0), None);
132
        assert!(f.get_slice(0).is_empty());
133
    }
134

            
135
    #[test]
136
    fn flatvecvec_get_slice_out_of_bounds_is_empty_in_both_phases() {
137
        let mut f = FlatVecVec::<i32>::new(2);
138
        f.push_to(0, 7);
139
        // build phase
140
        assert_eq!(f.get_slice(0), &[7]);
141
        assert!(f.get_slice(2).is_empty());
142
        assert!(f.get_slice(usize::MAX).is_empty());
143

            
144
        f.flatten();
145
        // read phase — same out-of-bounds contract, still no panic
146
        assert_eq!(f.get_slice(0), &[7]);
147
        assert!(f.get_slice(2).is_empty());
148
        assert!(f.get_slice(usize::MAX).is_empty());
149
    }
150

            
151
    #[test]
152
    #[should_panic(expected = "index out of bounds")]
153
    fn flatvecvec_push_to_out_of_bounds_panics() {
154
        // Documented in `push_to`: "Panics if ... node_index >= len()".
155
        let mut f = FlatVecVec::<i32>::new(1);
156
        f.push_to(1, 0);
157
    }
158

            
159
    #[test]
160
    #[should_panic(expected = "index out of bounds")]
161
    fn flatvecvec_push_to_after_flatten_panics() {
162
        // Documented in `push_to`: "Panics if already flattened".
163
        let mut f = FlatVecVec::<i32>::new(1);
164
        f.flatten();
165
        f.push_to(0, 0);
166
    }
167

            
168
    #[test]
169
    #[should_panic(expected = "index out of bounds")]
170
    fn flatvecvec_build_mut_out_of_bounds_panics() {
171
        let mut f = FlatVecVec::<i32>::new(1);
172
        let _ = f.build_mut(usize::MAX);
173
    }
174

            
175
    #[test]
176
    fn flatvecvec_build_iter_mut_visits_every_slot() {
177
        let mut f = FlatVecVec::<i32>::new(3);
178
        f.push_to(0, 1);
179
        f.push_to(2, 2);
180
        let mut visited = 0;
181
        for v in f.build_iter_mut() {
182
            visited += 1;
183
            v.clear();
184
        }
185
        assert_eq!(visited, 3);
186
        assert!(f.get_slice(0).is_empty());
187
        assert!(f.get_slice(2).is_empty());
188
    }
189

            
190
    #[test]
191
    fn flatvecvec_build_get_returns_none_once_flattened() {
192
        let mut f = FlatVecVec::<i32>::new(1);
193
        f.push_to(0, 5);
194
        f.flatten();
195
        // Doc: "During read phase, returns None (use `get_slice` instead)."
196
        assert_eq!(f.build_get(0), None);
197
        assert_eq!(f.get_slice(0), &[5]);
198
    }
199

            
200
    // =====================================================================
201
    // FlatVecVec — heap_bytes (numeric)
202
    // =====================================================================
203

            
204
    #[test]
205
    fn flatvecvec_heap_bytes_zero_and_empty() {
206
        let f = FlatVecVec::<i32>::default();
207
        assert_eq!(f.heap_bytes(0), 0, "empty vec, zero element size");
208
        // All three capacities are 0, so even a nonsensical MAX element size
209
        // multiplies out to 0 rather than overflowing.
210
        assert_eq!(f.heap_bytes(usize::MAX), 0);
211
        assert_eq!(f.heap_bytes(size_of::<i32>()), 0);
212
    }
213

            
214
    #[test]
215
    fn flatvecvec_heap_bytes_counts_build_and_flat_storage() {
216
        let mut f = FlatVecVec::<i32>::new(4);
217
        // Build-phase slots cost at least the outer Vec headers, even at a
218
        // per-element size of 0.
219
        assert!(f.heap_bytes(0) >= 4 * size_of::<Vec<i32>>());
220

            
221
        f.push_to(0, 1);
222
        f.push_to(0, 2);
223
        let build_bytes = f.heap_bytes(size_of::<i32>());
224
        assert!(build_bytes > 0);
225

            
226
        f.flatten();
227
        // Flat storage accounts for the 2 elements + the 4-entry offset table.
228
        let flat_bytes = f.heap_bytes(size_of::<i32>());
229
        assert!(flat_bytes >= 2 * size_of::<i32>() + 4 * size_of::<(u32, u32)>());
230
    }
231

            
232
    // =====================================================================
233
    // FlatVecVec — flatten / sort_each_and_flatten
234
    // =====================================================================
235

            
236
    #[test]
237
    fn flatvecvec_sort_each_and_flatten_keeps_last_of_equal_keys() {
238
        // CSS cascade rule: among equal keys, later source order wins.
239
        let mut f = FlatVecVec::<(i32, i32)>::new(1);
240
        f.push_to(0, (1, 10));
241
        f.push_to(0, (1, 20)); // same key, pushed later => must win
242
        f.push_to(0, (0, 30));
243
        f.sort_each_and_flatten(|p| p.0);
244

            
245
        assert!(f.is_flattened());
246
        assert_eq!(f.get_slice(0), &[(0, 30), (1, 20)]);
247
    }
248

            
249
    #[test]
250
    fn flatvecvec_sort_each_and_flatten_on_empty_slots() {
251
        let mut f = FlatVecVec::<i32>::new(3);
252
        f.push_to(1, 42);
253
        f.sort_each_and_flatten(|v| *v);
254
        assert_eq!(f.len(), 3);
255
        assert!(f.get_slice(0).is_empty());
256
        assert_eq!(f.get_slice(1), &[42]);
257
        assert!(f.get_slice(2).is_empty());
258
    }
259

            
260
    #[test]
261
    fn flatvecvec_sort_each_and_flatten_on_zero_nodes_does_not_panic() {
262
        let mut f = FlatVecVec::<i32>::new(0);
263
        f.sort_each_and_flatten(|v| *v);
264
        assert_eq!(f.len(), 0);
265
        assert!(f.get_slice(0).is_empty());
266
    }
267

            
268
    #[test]
269
    fn flatvecvec_flatten_does_not_deduplicate() {
270
        let mut f = FlatVecVec::<i32>::new(2);
271
        f.push_to(0, 5);
272
        f.push_to(0, 5);
273
        f.push_to(1, 9);
274
        f.flatten();
275
        assert!(f.is_flattened());
276
        assert_eq!(f.get_slice(0), &[5, 5], "flatten() must not dedup");
277
        assert_eq!(f.get_slice(1), &[9]);
278
    }
279

            
280
    // =====================================================================
281
    // FlatVecVec — retain
282
    // =====================================================================
283

            
284
    #[test]
285
    fn flatvecvec_retain_before_flatten_is_a_noop() {
286
        // Doc: "Must be called after flatten." Before that it must not silently
287
        // corrupt the build-phase data — it early-returns.
288
        let mut f = FlatVecVec::<i32>::new(1);
289
        f.push_to(0, 1);
290
        f.push_to(0, 2);
291
        f.retain(|_| false);
292
        assert_eq!(f.get_slice(0), &[1, 2], "build-phase data left untouched");
293
    }
294

            
295
    #[test]
296
    fn flatvecvec_retain_preserves_per_node_order() {
297
        let mut f = FlatVecVec::<i32>::new(2);
298
        for v in [1, 2, 3, 4] {
299
            f.push_to(0, v);
300
        }
301
        f.push_to(1, 5);
302
        f.flatten();
303

            
304
        f.retain(|v| v % 2 == 0);
305
        assert_eq!(f.get_slice(0), &[2, 4]);
306
        assert!(f.get_slice(1).is_empty());
307
        assert_eq!(f.len(), 2, "node slots survive an empty retain");
308
    }
309

            
310
    #[test]
311
    fn flatvecvec_retain_dropping_everything_leaves_empty_slices() {
312
        let mut f = FlatVecVec::<i32>::new(2);
313
        f.push_to(0, 1);
314
        f.push_to(1, 2);
315
        f.flatten();
316
        f.retain(|_| false);
317
        assert_eq!(f.len(), 2);
318
        assert!(f.get_slice(0).is_empty());
319
        assert!(f.get_slice(1).is_empty());
320
    }
321

            
322
    #[test]
323
    fn flatvecvec_retain_with_node_index_sees_owning_node() {
324
        let mut f = FlatVecVec::<i32>::new(3);
325
        f.push_to(0, 10);
326
        f.push_to(1, 11);
327
        f.push_to(2, 12);
328
        f.flatten();
329

            
330
        f.retain_with_node_index(|idx, _| idx == 1);
331
        assert!(f.get_slice(0).is_empty());
332
        assert_eq!(f.get_slice(1), &[11]);
333
        assert!(f.get_slice(2).is_empty());
334
    }
335

            
336
    #[test]
337
    fn flatvecvec_retain_with_node_index_before_flatten_is_a_noop() {
338
        let mut f = FlatVecVec::<i32>::new(1);
339
        f.push_to(0, 1);
340
        f.retain_with_node_index(|_, _| false);
341
        assert_eq!(f.get_slice(0), &[1]);
342
    }
343

            
344
    // =====================================================================
345
    // FlatVecVec — iteration / extend_from
346
    // =====================================================================
347

            
348
    #[test]
349
    fn flatvecvec_iter_node_slices_covers_all_nodes_in_both_phases() {
350
        let mut f = FlatVecVec::<i32>::new(3);
351
        f.push_to(1, 7);
352

            
353
        let build: Vec<(usize, Vec<i32>)> =
354
            f.iter_node_slices().map(|(i, s)| (i, s.to_vec())).collect();
355
        assert_eq!(build, vec![(0, vec![]), (1, vec![7]), (2, vec![])]);
356

            
357
        f.flatten();
358
        let flat: Vec<(usize, Vec<i32>)> =
359
            f.iter_node_slices().map(|(i, s)| (i, s.to_vec())).collect();
360
        assert_eq!(flat, build, "iteration is phase-independent");
361
    }
362

            
363
    #[test]
364
    fn flatvecvec_iter_node_slices_on_empty_yields_nothing() {
365
        let f = FlatVecVec::<i32>::new(0);
366
        assert_eq!(f.iter_node_slices().count(), 0);
367
    }
368

            
369
    #[test]
370
    fn flatvecvec_extend_from_both_in_build_phase() {
371
        let mut a = FlatVecVec::<i32>::new(1);
372
        a.push_to(0, 1);
373
        let mut b = FlatVecVec::<i32>::new(2);
374
        b.push_to(0, 2);
375
        b.push_to(1, 3);
376

            
377
        a.extend_from(&mut b);
378
        assert_eq!(a.len(), 3);
379
        assert_eq!(a.get_slice(0), &[1]);
380
        assert_eq!(a.get_slice(1), &[2]);
381
        assert_eq!(a.get_slice(2), &[3]);
382
        assert_eq!(b.len(), 0, "other is drained");
383
    }
384

            
385
    #[test]
386
    fn flatvecvec_extend_from_both_flattened_rebases_offsets() {
387
        let mut a = FlatVecVec::<i32>::new(2);
388
        a.push_to(0, 1);
389
        a.push_to(1, 2);
390
        a.flatten();
391

            
392
        let mut b = FlatVecVec::<i32>::new(2);
393
        b.push_to(0, 3);
394
        b.push_to(1, 4);
395
        b.flatten();
396

            
397
        a.extend_from(&mut b);
398
        assert_eq!(a.len(), 4);
399
        assert_eq!(a.get_slice(0), &[1]);
400
        assert_eq!(a.get_slice(1), &[2]);
401
        assert_eq!(a.get_slice(2), &[3], "offsets rebased onto a's flat data");
402
        assert_eq!(a.get_slice(3), &[4]);
403
    }
404

            
405
    #[test]
406
    fn flatvecvec_extend_from_across_phases_discards_self_flat_data() {
407
        // Doc precondition: "Both must be in build phase, or both must be
408
        // flattened." This pins what a violation actually does today — the
409
        // flattened side's items are dropped on the floor rather than merged.
410
        let mut a = FlatVecVec::<i32>::new(1);
411
        a.push_to(0, 1);
412
        a.flatten();
413

            
414
        let mut b = FlatVecVec::<i32>::new(1);
415
        b.push_to(0, 2);
416

            
417
        a.extend_from(&mut b); // no panic...
418
        assert_eq!(a.len(), 1);
419
        assert_eq!(
420
            a.get_slice(0),
421
            &[2],
422
            "a's own flattened item (1) is silently lost"
423
        );
424
    }
425

            
426
    #[test]
427
    fn flatvecvec_eq_within_the_same_phase() {
428
        let mut a = FlatVecVec::<i32>::new(1);
429
        a.push_to(0, 1);
430
        let mut b = FlatVecVec::<i32>::new(1);
431
        b.push_to(0, 1);
432
        assert_eq!(a, b);
433

            
434
        b.push_to(0, 2);
435
        assert_ne!(a, b);
436

            
437
        a.flatten();
438
        // (a and c are both flattened below — equality is only meaningful
439
        // between two caches in the same phase)
440
        let mut c = FlatVecVec::<i32>::new(1);
441
        c.push_to(0, 1);
442
        c.flatten();
443
        assert_eq!(a, c);
444
    }
445

            
446
    // =====================================================================
447
    // CssPropertyCacheBreakdown
448
    // =====================================================================
449

            
450
    #[test]
451
    fn breakdown_total_bytes_sums_subfields_and_excludes_node_count() {
452
        let b = CssPropertyCacheBreakdown {
453
            node_count: 999_999,
454
            cascaded_props_bytes: 1,
455
            css_props_bytes: 2,
456
            computed_values_bytes: 4,
457
            user_overridden_bytes: 8,
458
            global_css_props_bytes: 16,
459
            compact_cache_bytes: 32,
460
            resolved_font_sizes_bytes: 64,
461
        };
462
        assert_eq!(b.total_bytes(), 127, "node_count is not a byte count");
463
    }
464

            
465
    #[test]
466
    fn breakdown_total_bytes_default_is_zero_and_max_single_field_does_not_overflow() {
467
        assert_eq!(CssPropertyCacheBreakdown::default().total_bytes(), 0);
468

            
469
        let b = CssPropertyCacheBreakdown {
470
            cascaded_props_bytes: usize::MAX,
471
            ..Default::default()
472
        };
473
        assert_eq!(b.total_bytes(), usize::MAX);
474
    }
475

            
476
    // =====================================================================
477
    // CssPropertyCache — construction / memory / append
478
    // =====================================================================
479

            
480
    #[test]
481
    fn cache_empty_zero_is_neutral() {
482
        let c = CssPropertyCache::empty(0);
483
        assert_eq!(c.node_count, 0);
484
        assert!(c.css_props.is_empty());
485
        assert!(c.cascaded_props.is_empty());
486
        assert!(c.computed_values.is_empty());
487
        assert!(c.user_overridden_properties.is_empty());
488
        assert!(c.global_css_props.is_empty());
489
        assert!(c.compact_cache.is_none());
490

            
491
        let b = c.memory_breakdown();
492
        assert_eq!(b.node_count, 0);
493
        assert_eq!(b.total_bytes(), 0, "a zero-node cache retains no heap");
494
    }
495

            
496
    #[test]
497
    fn cache_empty_invariants_hold() {
498
        let c = CssPropertyCache::empty(7);
499
        assert_eq!(c.node_count, 7);
500
        assert_eq!(c.css_props.len(), 7);
501
        assert_eq!(c.cascaded_props.len(), 7);
502
        assert!(!c.css_props.is_flattened(), "starts in build phase");
503
        assert!(c.compact_cache.is_none());
504

            
505
        let b = c.memory_breakdown();
506
        assert_eq!(b.node_count, 7);
507
        assert!(b.total_bytes() > 0);
508
        assert_eq!(b.compact_cache_bytes, 0);
509
        assert_eq!(b.resolved_font_sizes_bytes, 0);
510
    }
511

            
512
    #[test]
513
    fn cache_invalidate_resolved_font_sizes_clears_the_once_lock() {
514
        let mut c = CssPropertyCache::empty(1);
515
        assert!(c.resolved_font_sizes_px.set(vec![16.0]).is_ok());
516
        assert!(c.resolved_font_sizes_px.get().is_some());
517

            
518
        c.invalidate_resolved_font_sizes();
519
        assert!(
520
            c.resolved_font_sizes_px.get().is_none(),
521
            "next read must recompute"
522
        );
523
        // and it can be re-populated afterwards
524
        assert!(c.resolved_font_sizes_px.set(vec![12.0]).is_ok());
525
    }
526

            
527
    #[test]
528
    fn cache_append_sums_nodes_and_invalidates_derived_caches() {
529
        let mut a = CssPropertyCache::empty(2);
530
        let mut b = CssPropertyCache::empty(3);
531
        assert!(a.resolved_font_sizes_px.set(vec![16.0, 16.0]).is_ok());
532

            
533
        a.append(&mut b);
534

            
535
        assert_eq!(a.node_count, 5);
536
        assert_eq!(a.css_props.len(), 5);
537
        assert_eq!(a.cascaded_props.len(), 5);
538
        assert!(
539
            a.resolved_font_sizes_px.get().is_none(),
540
            "node indices shifted"
541
        );
542
        assert!(a.compact_cache.is_none());
543
    }
544

            
545
    #[test]
546
    fn cache_append_of_empty_cache_is_a_noop_on_node_count() {
547
        let mut a = CssPropertyCache::empty(2);
548
        let mut b = CssPropertyCache::empty(0);
549
        a.append(&mut b);
550
        assert_eq!(a.node_count, 2);
551
        assert_eq!(a.css_props.len(), 2);
552
    }
553

            
554
    #[test]
555
    fn cache_invalidate_resolved_cache_drops_compact_cache() {
556
        let mut c = CssPropertyCache::empty(1);
557
        c.invalidate_resolved_cache();
558
        assert!(c.compact_cache.is_none());
559
    }
560

            
561
    #[test]
562
    fn cache_ptr_new_and_downcast_roundtrip() {
563
        let mut p = CssPropertyCachePtr::new(CssPropertyCache::empty(4));
564
        assert!(p.run_destructor);
565
        assert_eq!(p.downcast_mut().node_count, 4);
566

            
567
        p.downcast_mut().node_count = 9;
568
        assert_eq!(
569
            p.downcast_mut().node_count,
570
            9,
571
            "downcast_mut aliases the box"
572
        );
573
    }
574

            
575
    // =====================================================================
576
    // Predicates (overflow / border / box-shadow)
577
    // =====================================================================
578

            
579
    #[test]
580
    fn overflow_predicates_default_to_visible_for_a_bare_div() {
581
        let c = CssPropertyCache::empty(1);
582
        let nd = NodeData::create_div();
583
        assert!(c.is_horizontal_overflow_visible(&nd, &n0(), &normal()));
584
        assert!(c.is_vertical_overflow_visible(&nd, &n0(), &normal()));
585
        assert!(!c.is_horizontal_overflow_hidden(&nd, &n0(), &normal()));
586
        assert!(!c.is_vertical_overflow_hidden(&nd, &n0(), &normal()));
587
    }
588

            
589
    #[test]
590
    fn overflow_predicates_are_per_axis() {
591
        let c = CssPropertyCache::empty(1);
592
        let nd = div_with(vec![CssProperty::OverflowX(CssPropertyValue::Exact(
593
            LayoutOverflow::Hidden,
594
        ))]);
595
        assert!(c.is_horizontal_overflow_hidden(&nd, &n0(), &normal()));
596
        assert!(!c.is_horizontal_overflow_visible(&nd, &n0(), &normal()));
597
        // the Y axis must be untouched
598
        assert!(!c.is_vertical_overflow_hidden(&nd, &n0(), &normal()));
599
        assert!(c.is_vertical_overflow_visible(&nd, &n0(), &normal()));
600
    }
601

            
602
    #[test]
603
    fn overflow_predicates_do_not_panic_on_an_out_of_range_node_id() {
604
        let c = CssPropertyCache::empty(0);
605
        let nd = NodeData::create_div();
606
        let far = NodeId::new(999_999);
607
        assert!(c.is_horizontal_overflow_visible(&nd, &far, &normal()));
608
        assert!(!c.is_vertical_overflow_hidden(&nd, &far, &normal()));
609
    }
610

            
611
    #[test]
612
    fn has_border_false_without_and_true_with_a_border_width() {
613
        let c = CssPropertyCache::empty(1);
614
        assert!(!c.has_border(&NodeData::create_div(), &n0(), &normal()));
615

            
616
        let bordered = div_with(vec![CssProperty::BorderLeftWidth(CssPropertyValue::Exact(
617
            LayoutBorderLeftWidth {
618
                inner: PixelValue::px(2.0),
619
            },
620
        ))]);
621
        assert!(c.has_border(&bordered, &n0(), &normal()));
622
    }
623

            
624
    #[test]
625
    fn has_box_shadow_false_for_a_bare_div() {
626
        let c = CssPropertyCache::empty(1);
627
        assert!(!c.has_box_shadow(&NodeData::create_div(), &n0(), &normal()));
628
        // out-of-range node id must not panic either
629
        assert!(!c.has_box_shadow(&NodeData::create_div(), &NodeId::new(500), &normal()));
630
    }
631

            
632
    // =====================================================================
633
    // `*_or_default` getters
634
    // =====================================================================
635

            
636
    #[test]
637
    fn or_default_getters_fall_back_to_the_css_defaults() {
638
        let c = CssPropertyCache::empty(1);
639
        let nd = NodeData::create_div();
640

            
641
        assert_eq!(
642
            c.get_font_size_or_default(&nd, &n0(), &normal()),
643
            azul_css::defaults::DEFAULT_FONT_SIZE
644
        );
645
        assert_eq!(
646
            c.get_text_color_or_default(&nd, &n0(), &normal()),
647
            azul_css::defaults::DEFAULT_TEXT_COLOR
648
        );
649

            
650
        let fams = c.get_font_id_or_default(&nd, &n0(), &normal());
651
        assert_eq!(fams.as_ref().len(), 1);
652
        match &fams.as_ref()[0] {
653
            StyleFontFamily::System(s) => {
654
                assert_eq!(s.as_str(), azul_css::defaults::DEFAULT_FONT_ID);
655
            }
656
            other => panic!("expected the default System font family, got {other:?}"),
657
        }
658
    }
659

            
660
    #[test]
661
    fn get_font_size_or_default_prefers_the_inline_value() {
662
        let c = CssPropertyCache::empty(1);
663
        let nd = div_with(vec![font_size(PixelValue::px(42.0))]);
664
        let fs = c.get_font_size_or_default(&nd, &n0(), &normal());
665
        assert!(close(fs.inner.number.get(), 42.0));
666
        assert_eq!(fs.inner.metric, SizeMetric::Px);
667
    }
668

            
669
    #[test]
670
    fn or_default_getters_survive_an_out_of_range_node_id() {
671
        let c = CssPropertyCache::empty(0);
672
        let nd = NodeData::create_div();
673
        let far = NodeId::new(usize::MAX / 2);
674
        assert_eq!(
675
            c.get_font_size_or_default(&nd, &far, &normal()),
676
            azul_css::defaults::DEFAULT_FONT_SIZE
677
        );
678
        assert_eq!(
679
            c.get_font_id_or_default(&nd, &far, &normal())
680
                .as_ref()
681
                .len(),
682
            1
683
        );
684
    }
685

            
686
    // =====================================================================
687
    // calc_* (numeric: zero / negative / NaN / inf / saturation)
688
    // =====================================================================
689

            
690
    #[test]
691
    fn calc_width_is_zero_when_unset() {
692
        let c = CssPropertyCache::empty(1);
693
        let nd = NodeData::create_div();
694
        assert_eq!(c.calc_width(&nd, &n0(), &normal(), 800.0), 0.0);
695
        assert_eq!(c.calc_width(&nd, &n0(), &normal(), 0.0), 0.0);
696
        assert_eq!(c.calc_height(&nd, &n0(), &normal(), f32::NAN), 0.0);
697
    }
698

            
699
    #[test]
700
    fn calc_width_resolves_px_and_percent() {
701
        let c = CssPropertyCache::empty(1);
702

            
703
        let px = div_with(vec![width_px(100.0)]);
704
        assert!(close(c.calc_width(&px, &n0(), &normal(), 800.0), 100.0));
705
        // px must ignore the reference entirely
706
        assert!(close(c.calc_width(&px, &n0(), &normal(), 0.0), 100.0));
707

            
708
        let pct = div_with(vec![width_pct(50.0)]);
709
        assert!(close(c.calc_width(&pct, &n0(), &normal(), 800.0), 400.0));
710
        assert!(close(c.calc_width(&pct, &n0(), &normal(), 0.0), 0.0));
711
    }
712

            
713
    #[test]
714
    fn calc_width_with_a_negative_reference_is_negative_not_clamped() {
715
        let c = CssPropertyCache::empty(1);
716
        let pct = div_with(vec![width_pct(50.0)]);
717
        assert!(close(c.calc_width(&pct, &n0(), &normal(), -800.0), -400.0));
718
    }
719

            
720
    #[test]
721
    fn calc_width_with_nan_and_infinite_references_is_defined() {
722
        let c = CssPropertyCache::empty(1);
723
        let pct = div_with(vec![width_pct(50.0)]);
724

            
725
        assert!(c.calc_width(&pct, &n0(), &normal(), f32::NAN).is_nan());
726
        assert_eq!(
727
            c.calc_width(&pct, &n0(), &normal(), f32::INFINITY),
728
            f32::INFINITY
729
        );
730
        assert_eq!(
731
            c.calc_width(&pct, &n0(), &normal(), f32::NEG_INFINITY),
732
            f32::NEG_INFINITY
733
        );
734
    }
735

            
736
    #[test]
737
    fn calc_width_saturates_non_finite_pixel_values_at_construction() {
738
        let c = CssPropertyCache::empty(1);
739

            
740
        // PixelValue stores a fixed-point isize, so `as isize` saturates:
741
        // NaN => 0, +inf => isize::MAX, -inf => isize::MIN. Nothing panics and
742
        // nothing leaks a NaN into layout.
743
        let nan = div_with(vec![width_px(f32::NAN)]);
744
        assert_eq!(c.calc_width(&nan, &n0(), &normal(), 800.0), 0.0);
745

            
746
        let inf = div_with(vec![width_px(f32::INFINITY)]);
747
        let got = c.calc_width(&inf, &n0(), &normal(), 800.0);
748
        assert!(got.is_finite() && got > 0.0, "saturated, got {got}");
749

            
750
        let neg_inf = div_with(vec![width_px(f32::NEG_INFINITY)]);
751
        let got = c.calc_width(&neg_inf, &n0(), &normal(), 800.0);
752
        assert!(got.is_finite() && got < 0.0, "saturated, got {got}");
753

            
754
        let huge = div_with(vec![width_px(f32::MAX)]);
755
        assert!(c.calc_width(&huge, &n0(), &normal(), 800.0).is_finite());
756
    }
757

            
758
    #[test]
759
    fn calc_width_of_auto_and_intrinsic_keywords_is_zero() {
760
        let c = CssPropertyCache::empty(1);
761

            
762
        let auto = div_with(vec![CssProperty::Width(CssPropertyValue::Auto)]);
763
        assert_eq!(c.calc_width(&auto, &n0(), &normal(), 800.0), 0.0);
764

            
765
        // min-content/max-content are not resolvable here; documented as 0.0.
766
        let min_content = div_with(vec![CssProperty::Width(CssPropertyValue::Exact(
767
            LayoutWidth::MinContent,
768
        ))]);
769
        assert_eq!(c.calc_width(&min_content, &n0(), &normal(), 800.0), 0.0);
770
    }
771

            
772
    #[test]
773
    fn calc_height_mirrors_calc_width() {
774
        let c = CssPropertyCache::empty(1);
775
        let nd = div_with(vec![CssProperty::Height(CssPropertyValue::Exact(
776
            LayoutHeight::Px(PixelValue::percent(25.0)),
777
        ))]);
778
        assert!(close(c.calc_height(&nd, &n0(), &normal(), 400.0), 100.0));
779
        assert!(c.calc_height(&nd, &n0(), &normal(), f32::NAN).is_nan());
780
    }
781

            
782
    #[test]
783
    fn calc_min_width_defaults_to_zero_and_max_width_defaults_to_none() {
784
        let c = CssPropertyCache::empty(1);
785
        let nd = NodeData::create_div();
786

            
787
        assert_eq!(c.calc_min_width(&nd, &n0(), &normal(), 800.0), 0.0);
788
        assert_eq!(c.calc_min_height(&nd, &n0(), &normal(), 600.0), 0.0);
789
        assert_eq!(c.calc_max_width(&nd, &n0(), &normal(), 800.0), None);
790
        assert_eq!(c.calc_max_height(&nd, &n0(), &normal(), 600.0), None);
791
    }
792

            
793
    #[test]
794
    fn calc_min_max_width_resolve_percentages_and_propagate_nan() {
795
        let c = CssPropertyCache::empty(1);
796
        let nd = div_with(vec![
797
            CssProperty::MinWidth(CssPropertyValue::Exact(LayoutMinWidth {
798
                inner: PixelValue::percent(10.0),
799
            })),
800
            CssProperty::MaxWidth(CssPropertyValue::Exact(LayoutMaxWidth {
801
                inner: PixelValue::percent(90.0),
802
            })),
803
        ]);
804

            
805
        assert!(close(
806
            c.calc_min_width(&nd, &n0(), &normal(), 1000.0),
807
            100.0
808
        ));
809
        assert!(close(
810
            c.calc_max_width(&nd, &n0(), &normal(), 1000.0).unwrap(),
811
            900.0
812
        ));
813
        assert!(c.calc_min_width(&nd, &n0(), &normal(), f32::NAN).is_nan());
814
        assert!(c
815
            .calc_max_width(&nd, &n0(), &normal(), f32::NAN)
816
            .unwrap()
817
            .is_nan());
818
    }
819

            
820
    #[test]
821
    fn calc_inset_getters_are_none_when_unset_and_some_when_set() {
822
        let c = CssPropertyCache::empty(1);
823
        let bare = NodeData::create_div();
824
        assert_eq!(c.calc_left(&bare, &n0(), &normal(), 800.0), None);
825
        assert_eq!(c.calc_right(&bare, &n0(), &normal(), 800.0), None);
826
        assert_eq!(c.calc_top(&bare, &n0(), &normal(), 600.0), None);
827
        assert_eq!(c.calc_bottom(&bare, &n0(), &normal(), 600.0), None);
828

            
829
        let inset = div_with(vec![
830
            CssProperty::Left(CssPropertyValue::Exact(LayoutLeft {
831
                inner: PixelValue::px(5.0),
832
            })),
833
            CssProperty::Right(CssPropertyValue::Exact(LayoutRight {
834
                inner: PixelValue::percent(10.0),
835
            })),
836
            CssProperty::Top(CssPropertyValue::Exact(LayoutTop {
837
                inner: PixelValue::px(-7.0),
838
            })),
839
            CssProperty::Bottom(CssPropertyValue::Exact(LayoutInsetBottom {
840
                inner: PixelValue::px(0.0),
841
            })),
842
        ]);
843
        assert!(close(
844
            c.calc_left(&inset, &n0(), &normal(), 800.0).unwrap(),
845
            5.0
846
        ));
847
        assert!(close(
848
            c.calc_right(&inset, &n0(), &normal(), 800.0).unwrap(),
849
            80.0
850
        ));
851
        assert!(close(
852
            c.calc_top(&inset, &n0(), &normal(), 600.0).unwrap(),
853
            -7.0
854
        ));
855
        assert_eq!(c.calc_bottom(&inset, &n0(), &normal(), 600.0), Some(0.0));
856
    }
857

            
858
    #[test]
859
    fn calc_padding_margin_border_default_to_zero() {
860
        let c = CssPropertyCache::empty(1);
861
        let nd = NodeData::create_div();
862
        assert_eq!(c.calc_padding_left(&nd, &n0(), &normal(), 800.0), 0.0);
863
        assert_eq!(c.calc_padding_right(&nd, &n0(), &normal(), 800.0), 0.0);
864
        assert_eq!(c.calc_padding_top(&nd, &n0(), &normal(), 600.0), 0.0);
865
        assert_eq!(c.calc_padding_bottom(&nd, &n0(), &normal(), 600.0), 0.0);
866
        assert_eq!(c.calc_margin_left(&nd, &n0(), &normal(), 800.0), 0.0);
867
        assert_eq!(c.calc_margin_right(&nd, &n0(), &normal(), 800.0), 0.0);
868
        assert_eq!(c.calc_margin_top(&nd, &n0(), &normal(), 600.0), 0.0);
869
        assert_eq!(c.calc_margin_bottom(&nd, &n0(), &normal(), 600.0), 0.0);
870
        assert_eq!(c.calc_border_left_width(&nd, &n0(), &normal(), 800.0), 0.0);
871
        assert_eq!(c.calc_border_right_width(&nd, &n0(), &normal(), 800.0), 0.0);
872
        assert_eq!(c.calc_border_top_width(&nd, &n0(), &normal(), 600.0), 0.0);
873
        assert_eq!(
874
            c.calc_border_bottom_width(&nd, &n0(), &normal(), 600.0),
875
            0.0
876
        );
877
    }
878

            
879
    #[test]
880
    fn calc_padding_em_uses_the_default_font_size_not_the_reference() {
881
        // `calc_*` passes DEFAULT_FONT_SIZE (16px) as both em and rem resolvers,
882
        // so an em padding must be invariant under the reference width.
883
        let c = CssPropertyCache::empty(1);
884
        let nd = div_with(vec![CssProperty::PaddingLeft(CssPropertyValue::Exact(
885
            LayoutPaddingLeft {
886
                inner: PixelValue::em(2.0),
887
            },
888
        ))]);
889
        assert!(close(
890
            c.calc_padding_left(&nd, &n0(), &normal(), 800.0),
891
            32.0
892
        ));
893
        assert!(close(c.calc_padding_left(&nd, &n0(), &normal(), 0.0), 32.0));
894
        assert!(close(
895
            c.calc_padding_left(&nd, &n0(), &normal(), f32::NAN),
896
            32.0
897
        ));
898
    }
899

            
900
    #[test]
901
    fn calc_margin_and_border_resolve_px_and_percent() {
902
        let c = CssPropertyCache::empty(1);
903
        let nd = div_with(vec![
904
            CssProperty::MarginTop(CssPropertyValue::Exact(LayoutMarginTop {
905
                inner: PixelValue::percent(50.0),
906
            })),
907
            CssProperty::BorderLeftWidth(CssPropertyValue::Exact(LayoutBorderLeftWidth {
908
                inner: PixelValue::px(3.0),
909
            })),
910
        ]);
911
        assert!(close(
912
            c.calc_margin_top(&nd, &n0(), &normal(), 200.0),
913
            100.0
914
        ));
915
        assert!(close(
916
            c.calc_border_left_width(&nd, &n0(), &normal(), 800.0),
917
            3.0
918
        ));
919
        assert!(c.calc_margin_top(&nd, &n0(), &normal(), f32::NAN).is_nan());
920
    }
921

            
922
    #[test]
923
    fn calc_getters_do_not_panic_on_an_out_of_range_node_id() {
924
        let c = CssPropertyCache::empty(0);
925
        let nd = NodeData::create_div();
926
        let far = NodeId::new(usize::MAX / 2);
927
        assert_eq!(c.calc_width(&nd, &far, &normal(), 800.0), 0.0);
928
        assert_eq!(c.calc_max_height(&nd, &far, &normal(), 600.0), None);
929
        assert_eq!(c.calc_padding_top(&nd, &far, &normal(), f32::INFINITY), 0.0);
930
    }
931

            
932
    // =====================================================================
933
    // property_needs_slow_path_after_compact
934
    // =====================================================================
935

            
936
    #[test]
937
    fn slow_path_only_needed_for_non_px_pixel_values() {
938
        // px round-trips through the compact cache => no slow path
939
        assert!(!property_needs_slow_path_after_compact(&width_px(10.0)));
940
        // % encodes to SENTINEL => must survive the prune
941
        assert!(property_needs_slow_path_after_compact(&width_pct(50.0)));
942

            
943
        assert!(!property_needs_slow_path_after_compact(
944
            &CssProperty::Height(CssPropertyValue::Exact(LayoutHeight::Px(PixelValue::px(
945
                1.0
946
            ))))
947
        ));
948
        assert!(property_needs_slow_path_after_compact(
949
            &CssProperty::Height(CssPropertyValue::Exact(LayoutHeight::Px(PixelValue::em(
950
                1.0
951
            ))))
952
        ));
953
    }
954

            
955
    #[test]
956
    fn slow_path_covers_the_plain_pixelvalue_wrappers() {
957
        assert!(property_needs_slow_path_after_compact(&font_size(
958
            PixelValue::rem(2.0)
959
        )));
960
        assert!(!property_needs_slow_path_after_compact(&font_size(
961
            PixelValue::px(16.0)
962
        )));
963

            
964
        assert!(property_needs_slow_path_after_compact(
965
            &CssProperty::MinWidth(CssPropertyValue::Exact(LayoutMinWidth {
966
                inner: PixelValue::percent(10.0),
967
            }))
968
        ));
969
        assert!(!property_needs_slow_path_after_compact(
970
            &CssProperty::PaddingLeft(CssPropertyValue::Exact(LayoutPaddingLeft {
971
                inner: PixelValue::px(4.0),
972
            }))
973
        ));
974
    }
975

            
976
    #[test]
977
    fn slow_path_handles_flex_basis_and_non_pixel_properties() {
978
        assert!(property_needs_slow_path_after_compact(
979
            &CssProperty::FlexBasis(CssPropertyValue::Exact(LayoutFlexBasis::Exact(
980
                PixelValue::percent(50.0)
981
            )))
982
        ));
983
        assert!(!property_needs_slow_path_after_compact(
984
            &CssProperty::FlexBasis(CssPropertyValue::Exact(LayoutFlexBasis::Auto))
985
        ));
986

            
987
        // Non-Exact keywords and non-pixel properties never need the slow path.
988
        assert!(!property_needs_slow_path_after_compact(
989
            &CssProperty::Width(CssPropertyValue::Auto)
990
        ));
991
        assert!(!property_needs_slow_path_after_compact(
992
            &CssProperty::const_none(CssPropertyType::Display)
993
        ));
994
        assert!(!property_needs_slow_path_after_compact(
995
            &CssProperty::const_none(CssPropertyType::BackgroundContent)
996
        ));
997
    }
998

            
999
    // =====================================================================
    // clone_inheritable_property (round-trip)
    // =====================================================================
    #[test]
    fn clone_inheritable_property_round_trips_heap_and_pod_variants() {
        // The whole point of this hand-rolled clone is that it must be
        // byte-equivalent to the derived Clone on native.
        let font_family = CssProperty::FontFamily(CssPropertyValue::Exact(
            vec![StyleFontFamily::System(AzString::from_const_str("serif"))].into(),
        ));
        assert_eq!(clone_inheritable_property(&font_family), font_family);
        for p in [
            CssProperty::const_none(CssPropertyType::Cursor),
            CssProperty::const_none(CssPropertyType::TextColor),
            CssProperty::const_none(CssPropertyType::BackgroundContent),
            CssProperty::const_none(CssPropertyType::Transform),
            CssProperty::const_none(CssPropertyType::Content),
            width_px(3.0),
            font_size(PixelValue::em(1.5)),
        ] {
            assert_eq!(clone_inheritable_property(&p), p, "clone must be identity");
            assert_eq!(clone_inheritable_property(&p).get_type(), p.get_type());
        }
    }
    // =====================================================================
    // find_in_stateful / has_state_props / prop_types_for_state
    // =====================================================================
    fn sorted_stateful_fixture() -> Vec<StatefulCssProperty> {
        let mut v = vec![
            stateful(PseudoStateType::Normal, width_px(1.0)),
            stateful(
                PseudoStateType::Normal,
                CssProperty::const_none(CssPropertyType::Display),
            ),
            stateful(PseudoStateType::Hover, width_px(2.0)),
        ];
        // The lookup helpers require (state, prop_type) sort order.
        v.sort_by_key(|p| (p.state, p.prop_type));
        v
    }
    #[test]
    fn find_in_stateful_on_an_empty_slice_is_none() {
        assert!(CssPropertyCache::find_in_stateful(
            &[],
            PseudoStateType::Normal,
            &CssPropertyType::Width
        )
        .is_none());
    }
    #[test]
    fn find_in_stateful_is_keyed_on_both_state_and_prop_type() {
        let v = sorted_stateful_fixture();
        let normal_width = CssPropertyCache::find_in_stateful(
            &v,
            PseudoStateType::Normal,
            &CssPropertyType::Width,
        )
        .expect("normal width present");
        assert_eq!(normal_width.get_type(), CssPropertyType::Width);
        let hover_width =
            CssPropertyCache::find_in_stateful(&v, PseudoStateType::Hover, &CssPropertyType::Width)
                .expect("hover width present");
        // same prop type, different state => a different entry
        assert_ne!(normal_width, hover_width);
        // present prop type, absent state
        assert!(CssPropertyCache::find_in_stateful(
            &v,
            PseudoStateType::Focus,
            &CssPropertyType::Width
        )
        .is_none());
        // present state, absent prop type
        assert!(CssPropertyCache::find_in_stateful(
            &v,
            PseudoStateType::Hover,
            &CssPropertyType::Display
        )
        .is_none());
    }
    #[test]
    fn has_state_props_true_false_and_edges() {
        let v = sorted_stateful_fixture();
        assert!(CssPropertyCache::has_state_props(
            &v,
            PseudoStateType::Normal
        ));
        assert!(CssPropertyCache::has_state_props(
            &v,
            PseudoStateType::Hover
        ));
        assert!(!CssPropertyCache::has_state_props(
            &v,
            PseudoStateType::Focus
        ));
        // empty slice: deterministic false, no partition_point OOB read
        assert!(!CssPropertyCache::has_state_props(
            &[],
            PseudoStateType::Normal
        ));
    }
    #[test]
    fn prop_types_for_state_filters_by_state() {
        let v = sorted_stateful_fixture();
        let mut normal: Vec<CssPropertyType> =
            CssPropertyCache::prop_types_for_state(&v, PseudoStateType::Normal)
                .copied()
                .collect();
        normal.sort_unstable();
        assert_eq!(normal.len(), 2);
        assert!(normal.contains(&CssPropertyType::Width));
        assert!(normal.contains(&CssPropertyType::Display));
        let hover: Vec<CssPropertyType> =
            CssPropertyCache::prop_types_for_state(&v, PseudoStateType::Hover)
                .copied()
                .collect();
        assert_eq!(hover, vec![CssPropertyType::Width]);
        assert_eq!(
            CssPropertyCache::prop_types_for_state(&v, PseudoStateType::Active).count(),
            0
        );
        assert_eq!(
            CssPropertyCache::prop_types_for_state(&[], PseudoStateType::Normal).count(),
            0
        );
    }
    // =====================================================================
    // font-size resolution (numeric)
    // =====================================================================
    #[test]
    fn resolve_font_size_to_pixels_converts_absolute_units() {
        let px =
            CssPropertyCache::resolve_font_size_to_pixels(&font_size(PixelValue::px(20.0)), 10.0);
        let (metric, n) = font_size_parts(&px).unwrap();
        assert_eq!(metric, SizeMetric::Px);
        assert!(close(n, 20.0));
        let pt =
            CssPropertyCache::resolve_font_size_to_pixels(&font_size(PixelValue::pt(12.0)), 10.0);
        assert!(close(font_size_parts(&pt).unwrap().1, 12.0 * PT_TO_PX));
    }
    #[test]
    fn resolve_font_size_to_pixels_em_scales_by_reference_but_rem_does_not() {
        let em =
            CssPropertyCache::resolve_font_size_to_pixels(&font_size(PixelValue::em(2.0)), 10.0);
        assert!(close(font_size_parts(&em).unwrap().1, 20.0));
        // rem deliberately ignores the reference and uses DEFAULT_FONT_SIZE (16).
        let rem =
            CssPropertyCache::resolve_font_size_to_pixels(&font_size(PixelValue::rem(2.0)), 10.0);
        assert!(close(font_size_parts(&rem).unwrap().1, 32.0));
        let pct = CssPropertyCache::resolve_font_size_to_pixels(
            &font_size(PixelValue::percent(50.0)),
            10.0,
        );
        assert!(close(font_size_parts(&pct).unwrap().1, 5.0));
    }
    #[test]
    fn resolve_font_size_to_pixels_with_nan_and_infinite_references() {
        // NaN * anything => NaN => saturates to 0 in the fixed-point encoding.
        let nan = CssPropertyCache::resolve_font_size_to_pixels(
            &font_size(PixelValue::em(2.0)),
            f32::NAN,
        );
        let (metric, n) = font_size_parts(&nan).unwrap();
        assert_eq!(metric, SizeMetric::Px);
        assert_eq!(n, 0.0, "NaN must not escape into the cascade");
        let inf = CssPropertyCache::resolve_font_size_to_pixels(
            &font_size(PixelValue::em(2.0)),
            f32::INFINITY,
        );
        let n = font_size_parts(&inf).unwrap().1;
        assert!(n.is_finite() && n > 0.0, "saturated, got {n}");
        let zero =
            CssPropertyCache::resolve_font_size_to_pixels(&font_size(PixelValue::em(2.0)), 0.0);
        assert_eq!(font_size_parts(&zero).unwrap().1, 0.0);
        let neg =
            CssPropertyCache::resolve_font_size_to_pixels(&font_size(PixelValue::em(2.0)), -10.0);
        assert!(close(font_size_parts(&neg).unwrap().1, -20.0));
    }
    #[test]
    fn resolve_font_size_to_pixels_passes_through_unresolvable_inputs() {
        // viewport units need a viewport => returned unchanged
        let vw = font_size(PixelValue::from_metric(SizeMetric::Vw, 10.0));
        assert_eq!(CssPropertyCache::resolve_font_size_to_pixels(&vw, 16.0), vw);
        // a non-font-size property is returned verbatim
        let w = width_px(10.0);
        assert_eq!(CssPropertyCache::resolve_font_size_to_pixels(&w, 16.0), w);
        // a keyword (non-Exact) font-size has no PixelValue to convert
        let inherit = CssProperty::FontSize(CssPropertyValue::Inherit);
        assert_eq!(
            CssPropertyCache::resolve_font_size_to_pixels(&inherit, 16.0),
            inherit
        );
    }
    #[test]
    fn has_relative_font_size_unit_true_false_and_edges() {
        assert!(CssPropertyCache::has_relative_font_size_unit(&font_size(
            PixelValue::em(1.0)
        )));
        assert!(CssPropertyCache::has_relative_font_size_unit(&font_size(
            PixelValue::rem(1.0)
        )));
        assert!(CssPropertyCache::has_relative_font_size_unit(&font_size(
            PixelValue::percent(100.0)
        )));
        assert!(!CssPropertyCache::has_relative_font_size_unit(&font_size(
            PixelValue::px(16.0)
        )));
        assert!(!CssPropertyCache::has_relative_font_size_unit(&font_size(
            PixelValue::pt(12.0)
        )));
        // keyword font-size and non-font-size properties are not "relative"
        assert!(!CssPropertyCache::has_relative_font_size_unit(
            &CssProperty::FontSize(CssPropertyValue::Auto)
        ));
        assert!(!CssPropertyCache::has_relative_font_size_unit(&width_px(
            1.0
        )));
    }
    // =====================================================================
    // resolve_property_dependency
    // =====================================================================
    #[test]
    fn resolve_property_dependency_scales_relative_targets_by_an_absolute_reference() {
        let reference = font_size(PixelValue::px(10.0));
        let em = CssPropertyCache::resolve_property_dependency(
            &font_size(PixelValue::em(2.0)),
            &reference,
        )
        .expect("em resolves against an absolute reference");
        assert!(close(font_size_parts(&em).unwrap().1, 20.0));
        let pct = CssPropertyCache::resolve_property_dependency(
            &font_size(PixelValue::percent(50.0)),
            &reference,
        )
        .expect("percent resolves");
        assert!(close(font_size_parts(&pct).unwrap().1, 5.0));
        // The reference itself may be in any absolute unit.
        let pt_ref = font_size(PixelValue::pt(10.0));
        let em2 =
            CssPropertyCache::resolve_property_dependency(&font_size(PixelValue::em(2.0)), &pt_ref)
                .expect("pt reference is absolute");
        assert!(close(
            font_size_parts(&em2).unwrap().1,
            2.0 * 10.0 * PT_TO_PX
        ));
    }
    #[test]
    fn resolve_property_dependency_rewrites_the_target_variant_in_place() {
        let reference = font_size(PixelValue::px(10.0));
        let padding = CssProperty::PaddingLeft(CssPropertyValue::Exact(LayoutPaddingLeft {
            inner: PixelValue::em(3.0),
        }));
        let out = CssPropertyCache::resolve_property_dependency(&padding, &reference)
            .expect("padding is a supported target");
        match out {
            CssProperty::PaddingLeft(v) => {
                let inner = v.get_property().unwrap().inner;
                assert_eq!(inner.metric, SizeMetric::Px);
                assert!(close(inner.number.get(), 30.0));
            }
            other => panic!("variant must be preserved, got {other:?}"),
        }
    }
    #[test]
    fn resolve_property_dependency_returns_none_for_unresolvable_inputs() {
        let abs = font_size(PixelValue::px(10.0));
        // a relative reference cannot anchor anything
        assert!(CssPropertyCache::resolve_property_dependency(
            &font_size(PixelValue::em(2.0)),
            &font_size(PixelValue::em(2.0))
        )
        .is_none());
        // viewport-unit target needs a viewport
        assert!(CssPropertyCache::resolve_property_dependency(
            &font_size(PixelValue::from_metric(SizeMetric::Vh, 5.0)),
            &abs
        )
        .is_none());
        // unsupported target type (no PixelValue to extract)
        assert!(CssPropertyCache::resolve_property_dependency(&width_px(5.0), &abs).is_none());
        // unsupported reference type
        assert!(CssPropertyCache::resolve_property_dependency(
            &font_size(PixelValue::em(2.0)),
            &width_px(5.0)
        )
        .is_none());
        // keyword (non-Exact) target
        assert!(CssPropertyCache::resolve_property_dependency(
            &CssProperty::FontSize(CssPropertyValue::Inherit),
            &abs
        )
        .is_none());
    }
    // =====================================================================
    // should_apply_cascaded
    // =====================================================================
    #[test]
    fn should_apply_cascaded_respects_origin_and_relative_font_sizes() {
        let own = |p: CssProperty| {
            vec![(
                p.get_type(),
                CssPropertyWithOrigin {
                    property: p,
                    origin: CssPropertyOrigin::Own,
                },
            )]
        };
        let inherited = |p: CssProperty| {
            vec![(
                p.get_type(),
                CssPropertyWithOrigin {
                    property: p,
                    origin: CssPropertyOrigin::Inherited,
                },
            )]
        };
        // nothing computed yet => apply
        assert!(CssPropertyCache::should_apply_cascaded(
            &[],
            CssPropertyType::Width,
            &width_px(1.0)
        ));
        // the node already set it itself => the UA/cascaded value must not win
        assert!(!CssPropertyCache::should_apply_cascaded(
            &own(width_px(2.0)),
            CssPropertyType::Width,
            &width_px(1.0)
        ));
        // an inherited value is weaker than a cascaded one => apply
        assert!(CssPropertyCache::should_apply_cascaded(
            &inherited(width_px(2.0)),
            CssPropertyType::Width,
            &width_px(1.0)
        ));
        // A cascaded (UA/author) font-size — relative OR absolute — overrides an
        // inherited value: it is the node's own declared size (e.g. <h1>'s UA
        // `font-size: 2em`), and `resolve_font_size_property` resolves the `em`
        // against the parent's size, so there is no double-scaling.
        let inherited_fs = inherited(font_size(PixelValue::px(20.0)));
        assert!(CssPropertyCache::should_apply_cascaded(
            &inherited_fs,
            CssPropertyType::FontSize,
            &font_size(PixelValue::em(2.0))
        ));
        assert!(CssPropertyCache::should_apply_cascaded(
            &inherited_fs,
            CssPropertyType::FontSize,
            &font_size(PixelValue::px(12.0))
        ));
    }
    // =====================================================================
    // get_property / get_property_slow (cascade layering)
    // =====================================================================
    #[test]
    fn get_property_finds_an_inline_normal_property() {
        let c = CssPropertyCache::empty(1);
        let nd = div_with(vec![width_px(100.0)]);
        let got = c
            .get_property(&nd, &n0(), &normal(), &CssPropertyType::Width)
            .expect("inline width");
        assert_eq!(*got, width_px(100.0));
    }
    #[test]
    fn get_property_ignores_pseudo_state_props_unless_the_state_is_active() {
        let c = CssPropertyCache::empty(1);
        let nd = div_with_pseudo(vec![width_px(100.0)], PseudoStateType::Hover);
        assert!(
            c.get_property(&nd, &n0(), &normal(), &CssPropertyType::Width)
                .is_none(),
            ":hover width must not leak into the Normal state"
        );
        let hovered = StyledNodeState {
            hover: true,
            ..StyledNodeState::default()
        };
        assert_eq!(
            c.get_property(&nd, &n0(), &hovered, &CssPropertyType::Width),
            Some(&width_px(100.0))
        );
    }
    #[test]
    fn get_property_user_override_beats_inline_and_stylesheet() {
        let mut c = CssPropertyCache::empty(1);
        c.user_overridden_properties
            .push(vec![(CssPropertyType::Width, width_px(1.0))]);
        c.css_props
            .push_to(0, stateful(PseudoStateType::Normal, width_px(2.0)));
        c.css_props
            .sort_each_and_flatten(|p| (p.state, p.prop_type));
        let nd = div_with(vec![width_px(3.0)]);
        assert_eq!(
            c.get_property(&nd, &n0(), &normal(), &CssPropertyType::Width),
            Some(&width_px(1.0)),
            "user override is the top cascade layer"
        );
    }
    #[test]
    fn get_property_falls_back_through_stylesheet_global_cascaded_then_ua() {
        let nd = NodeData::create_div();
        // stylesheet layer
        let mut c = CssPropertyCache::empty(1);
        c.css_props
            .push_to(0, stateful(PseudoStateType::Normal, width_px(2.0)));
        c.css_props
            .sort_each_and_flatten(|p| (p.state, p.prop_type));
        assert_eq!(
            c.get_property(&nd, &n0(), &normal(), &CssPropertyType::Width),
            Some(&width_px(2.0))
        );
        // `*` global layer (below per-node rules)
        let mut c = CssPropertyCache::empty(1);
        c.global_css_props.push(width_px(4.0));
        assert_eq!(
            c.get_property(&nd, &n0(), &normal(), &CssPropertyType::Width),
            Some(&width_px(4.0))
        );
        // cascaded (inherited/UA) layer
        let mut c = CssPropertyCache::empty(1);
        c.cascaded_props
            .push_to(0, stateful(PseudoStateType::Normal, width_px(5.0)));
        c.cascaded_props
            .sort_each_and_flatten(|p| (p.state, p.prop_type));
        assert_eq!(
            c.get_property(&nd, &n0(), &normal(), &CssPropertyType::Width),
            Some(&width_px(5.0))
        );
        // UA fallback: a <div> has no UA width, but it does have `display: block`
        let c = CssPropertyCache::empty(1);
        assert!(c
            .get_property(&nd, &n0(), &normal(), &CssPropertyType::Width)
            .is_none());
        assert!(c
            .get_property(&nd, &n0(), &normal(), &CssPropertyType::Display)
            .is_some());
    }
    #[test]
    fn get_property_on_an_out_of_range_node_id_falls_through_to_ua_css() {
        let c = CssPropertyCache::empty(0);
        let nd = NodeData::create_div();
        let far = NodeId::new(usize::MAX / 2);
        assert!(c
            .get_property(&nd, &far, &normal(), &CssPropertyType::Width)
            .is_none());
        assert!(
            c.get_property(&nd, &far, &normal(), &CssPropertyType::Display)
                .is_some(),
            "UA CSS is node-type-keyed, not index-keyed"
        );
    }
    #[test]
    fn get_property_with_context_matches_pseudo_state_conditions() {
        let c = CssPropertyCache::empty(1);
        let nd = div_with_pseudo(vec![width_px(100.0)], PseudoStateType::Hover);
        let plain = DynamicSelectorContext::default();
        assert!(c
            .get_property_with_context(&nd, &n0(), &plain, &CssPropertyType::Width)
            .is_none());
        let mut hovered = DynamicSelectorContext::default();
        hovered.pseudo_state.hover = true;
        assert_eq!(
            c.get_property_with_context(&nd, &n0(), &hovered, &CssPropertyType::Width),
            Some(&width_px(100.0))
        );
    }
    /// The same twin on a DOM CREATED under the dark context — the app's
    /// path (`style_user_dom_for` → `create_with_context`), not one that
    /// had the context set after the fact. The restyle's inheritance walk
    /// materializes the parent's inline declarations into the children's
    /// cascaded props; it used to admit only pseudo-state conditions, so the
    /// light value went down as the child's OWN declaration and beat the
    /// inherited twin. The other path only came out right because the prune
    /// had emptied the cascaded props before the recascade.
    #[test]
    fn a_dom_created_under_the_dark_context_inherits_the_twin() {
        use azul_css::{
            dynamic_selector::{
                CssPropertyWithConditions, CssPropertyWithConditionsVec, ThemeCondition,
            },
            props::{basic::color::ColorU, style::StyleTextColor},
        };
        use crate::{dom::Dom, styled_dom::StyledDom};
        let light = ColorU::rgb(33, 37, 41);
        let dark = ColorU::rgb(232, 232, 232);
        let build = |ctx: Option<DynamicSelectorContext>| {
            let mut dom = Dom::create_body().with_child(
                Dom::create_div()
                    .with_css_props(CssPropertyWithConditionsVec::from_vec(vec![
                        CssPropertyWithConditions::simple(CssProperty::const_text_color(
                            StyleTextColor { inner: light },
                        )),
                        CssPropertyWithConditions::dark_theme(CssProperty::const_text_color(
                            StyleTextColor { inner: dark },
                        )),
                    ]))
                    .with_child(Dom::create_p().with_child(
                        Dom::create_text_do_not_use_without_block_level_wrapper("label"),
                    )),
            );
            StyledDom::create_with_context(&mut dom, azul_css::css::Css::empty(), ctx)
        };
        // body(0) > div(1) > p(2) > text(3)
        let colour_of = |sd: &StyledDom, i: usize| {
            let node_data = sd.node_data.as_container();
            let n = NodeId::new(i);
            sd.get_css_property_cache()
                .get_text_color(node_data.get(n).expect("node"), &n, &normal())
                .and_then(|v| v.get_property().copied())
                .map(|c| c.inner)
        };
        let ctx = DynamicSelectorContext {
            theme: ThemeCondition::Dark,
            ..Default::default()
        };
        let sd = build(Some(ctx));
        assert_eq!(colour_of(&sd, 1), Some(dark), "the container's own twin");
        assert_eq!(
            colour_of(&sd, 2),
            Some(dark),
            "the p inherits the twin, not the light value the restyle walk used to hand it"
        );
        assert_eq!(colour_of(&sd, 3), Some(dark), "…and so does the text");
        let light_ctx = DynamicSelectorContext {
            theme: ThemeCondition::Light,
            ..Default::default()
        };
        let sd = build(Some(light_ctx));
        assert_eq!(
            colour_of(&sd, 3),
            Some(light),
            "under a light window the twin stays out"
        );
    }
    /// A container's conditional declaration is inherited by its children
    /// when the condition holds — `dark_theme(color: ..)` on a button reaches
    /// the label's text under a dark window, and stays out of the way under a
    /// light one.
    #[test]
    fn conditional_inline_declarations_take_part_in_inheritance() {
        use azul_css::{
            dynamic_selector::{
                CssPropertyWithConditions, CssPropertyWithConditionsVec, ThemeCondition,
            },
            props::{basic::color::ColorU, style::StyleTextColor},
        };
        use crate::{dom::Dom, styled_dom::StyledDom};
        let light = ColorU::rgb(33, 37, 41);
        let dark = ColorU::rgb(232, 232, 232);
        let build = || {
            let mut dom = Dom::create_body().with_child(
                Dom::create_div()
                    .with_css_props(CssPropertyWithConditionsVec::from_vec(vec![
                        CssPropertyWithConditions::simple(CssProperty::const_text_color(
                            StyleTextColor { inner: light },
                        )),
                        CssPropertyWithConditions::dark_theme(CssProperty::const_text_color(
                            StyleTextColor { inner: dark },
                        )),
                    ]))
                    .with_child(Dom::create_p().with_child(
                        Dom::create_text_do_not_use_without_block_level_wrapper("label"),
                    )),
            );
            StyledDom::create(&mut dom, azul_css::css::Css::empty())
        };
        // body(0) > div(1) > p(2) > text(3)
        let text_colour = |sd: &StyledDom| {
            let node_data = sd.node_data.as_container();
            let n = NodeId::new(3);
            sd.get_css_property_cache()
                .get_text_color(node_data.get(n).expect("text node"), &n, &normal())
                .and_then(|v| v.get_property().copied())
                .map(|c| c.inner)
        };
        let mut sd = build();
        let ctx = DynamicSelectorContext {
            theme: ThemeCondition::Light,
            ..Default::default()
        };
        sd.set_dynamic_selector_context(ctx);
        assert_eq!(
            text_colour(&sd),
            Some(light),
            "light window: the unconditional value"
        );
        let mut sd = build();
        let ctx = DynamicSelectorContext {
            theme: ThemeCondition::Dark,
            ..Default::default()
        };
        sd.set_dynamic_selector_context(ctx);
        assert_eq!(
            text_colour(&sd),
            Some(dark),
            "dark window: the twin, inherited"
        );
    }
    #[test]
    fn check_properties_changed_only_fires_when_a_condition_flips() {
        let plain = DynamicSelectorContext::default();
        let mut hovered = DynamicSelectorContext::default();
        hovered.pseudo_state.hover = true;
        // unconditional props never "change" between contexts
        let unconditional = div_with(vec![width_px(1.0)]);
        assert!(!CssPropertyCache::check_properties_changed(
            &unconditional,
            &plain,
            &hovered
        ));
        let conditional = div_with_pseudo(vec![width_px(1.0)], PseudoStateType::Hover);
        assert!(CssPropertyCache::check_properties_changed(
            &conditional,
            &plain,
            &hovered
        ));
        assert!(
            !CssPropertyCache::check_properties_changed(&conditional, &plain, &plain),
            "identical contexts can never differ"
        );
        // a node with no inline style at all
        assert!(!CssPropertyCache::check_properties_changed(
            &NodeData::create_div(),
            &plain,
            &hovered
        ));
    }
    #[test]
    fn check_layout_properties_changed_ignores_non_layout_properties() {
        let plain = DynamicSelectorContext::default();
        let mut hovered = DynamicSelectorContext::default();
        hovered.pseudo_state.hover = true;
        let layout = div_with_pseudo(vec![width_px(1.0)], PseudoStateType::Hover);
        assert!(CssPropertyCache::check_layout_properties_changed(
            &layout, &plain, &hovered
        ));
        assert!(CssPropertyType::Width.can_trigger_relayout());
        // A paint-only property flipping must not force a relayout.
        let paint = div_with_pseudo(
            vec![CssProperty::const_none(CssPropertyType::BackgroundContent)],
            PseudoStateType::Hover,
        );
        assert!(!CssPropertyType::BackgroundContent.can_trigger_relayout());
        assert!(!CssPropertyCache::check_layout_properties_changed(
            &paint, &plain, &hovered
        ));
        // ...though the generic check still sees it
        assert!(CssPropertyCache::check_properties_changed(
            &paint, &plain, &hovered
        ));
    }
    // =====================================================================
    // grid-gap / scrollbar getters
    // =====================================================================
    #[test]
    fn grid_gap_and_scrollbar_getters_are_none_on_a_bare_div() {
        let c = CssPropertyCache::empty(1);
        let nd = NodeData::create_div();
        assert!(c.get_grid_gap(&nd, &n0(), &normal()).is_none());
        assert!(c.get_scrollbar_track(&nd, &n0(), &normal()).is_none());
        assert!(c.get_scrollbar_thumb(&nd, &n0(), &normal()).is_none());
        assert!(c.get_scrollbar_button(&nd, &n0(), &normal()).is_none());
        assert!(c.get_scrollbar_corner(&nd, &n0(), &normal()).is_none());
        assert!(c.get_scrollbar_resizer(&nd, &n0(), &normal()).is_none());
        // and on an out-of-range node id
        let far = NodeId::new(4_242);
        assert!(c.get_grid_gap(&nd, &far, &normal()).is_none());
        assert!(c.get_scrollbar_thumb(&nd, &far, &normal()).is_none());
    }
    // =====================================================================
    // get_computed_css_style_string
    // =====================================================================
    #[test]
    fn computed_css_style_string_serializes_set_properties() {
        let c = CssPropertyCache::empty(1);
        // A bare <div> still gets `display: block` from the UA sheet.
        let s = c.get_computed_css_style_string(&NodeData::create_div(), &n0(), &normal());
        assert!(s.contains("display:"), "got {s:?}");
        let styled = div_with(vec![width_px(100.0), font_size(PixelValue::px(12.0))]);
        let s = c.get_computed_css_style_string(&styled, &n0(), &normal());
        assert!(s.contains("width:"), "got {s:?}");
        assert!(s.contains("font-size:"), "got {s:?}");
        assert!(s.ends_with(';'), "each declaration is terminated: {s:?}");
    }
    #[test]
    fn computed_css_style_string_does_not_panic_on_an_out_of_range_node_id() {
        let c = CssPropertyCache::empty(0);
        let s = c.get_computed_css_style_string(
            &NodeData::create_div(),
            &NodeId::new(usize::MAX / 2),
            &normal(),
        );
        assert!(s.contains("display:"));
    }
    // =====================================================================
    // apply_ua_css / sort_cascaded_props / prune_compact_normal_props
    // =====================================================================
    #[test]
    fn apply_ua_css_inserts_ua_properties_into_cascaded_props() {
        let nodes = vec![NodeData::create_div()];
        let mut c = CssPropertyCache::empty(1);
        c.apply_ua_css(&nodes);
        // The pass leaves the store sorted + flattened (read phase).
        assert!(c.cascaded_props.is_flattened());
        let props = c.cascaded_props.get_slice(0);
        assert!(
            props.iter().any(|p| p.prop_type == CssPropertyType::Display
                && p.state == PseudoStateType::Normal
                && p.ua_origin),
            "UA `div {{ display: block }}` must land in the cascade, tagged as UA-origin"
        );
        assert!(c.ua_applied);
    }
    #[test]
    fn apply_ua_css_does_not_override_an_existing_inline_property() {
        let nodes = vec![div_with(vec![CssProperty::const_none(
            CssPropertyType::Display,
        )])];
        let mut c = CssPropertyCache::empty(1);
        c.apply_ua_css(&nodes);
        let props = c.cascaded_props.get_slice(0);
        assert!(
            !props
                .iter()
                .any(|p| p.prop_type == CssPropertyType::Display),
            "UA CSS is the weakest layer and must not clobber inline"
        );
    }
    #[test]
    fn apply_ua_css_on_zero_nodes_returns_early() {
        let mut c = CssPropertyCache::empty(0);
        c.apply_ua_css(&[]);
        assert_eq!(c.cascaded_props.len(), 0);
    }
    #[test]
    fn sort_cascaded_props_flattens_and_orders_by_state_then_type() {
        let mut c = CssPropertyCache::empty(1);
        c.cascaded_props
            .push_to(0, stateful(PseudoStateType::Hover, width_px(1.0)));
        c.cascaded_props.push_to(
            0,
            stateful(
                PseudoStateType::Normal,
                CssProperty::const_none(CssPropertyType::Display),
            ),
        );
        c.cascaded_props
            .push_to(0, stateful(PseudoStateType::Normal, width_px(2.0)));
        c.sort_cascaded_props();
        assert!(c.cascaded_props.is_flattened());
        let slice = c.cascaded_props.get_slice(0);
        assert_eq!(slice.len(), 3);
        let keys: Vec<_> = slice.iter().map(|p| (p.state, p.prop_type)).collect();
        let mut sorted = keys.clone();
        sorted.sort_unstable();
        assert_eq!(keys, sorted, "binary_search lookups require sort order");
    }
    #[test]
    fn prune_compact_normal_props_keeps_what_the_slow_path_still_needs() {
        let mut c = CssPropertyCache::empty(1);
        // Normal + compact-encoded + fully representable => droppable
        c.cascaded_props.push_to(
            0,
            stateful(
                PseudoStateType::Normal,
                CssProperty::const_none(CssPropertyType::Display),
            ),
        );
        // Normal + compact-encoded but SENTINEL-encoded (%) => must survive
        c.cascaded_props
            .push_to(0, stateful(PseudoStateType::Normal, width_pct(50.0)));
        // Normal + no compact encoding at all => must survive
        c.cascaded_props.push_to(
            0,
            stateful(
                PseudoStateType::Normal,
                CssProperty::const_none(CssPropertyType::BackgroundContent),
            ),
        );
        // non-Normal => always survives
        c.cascaded_props.push_to(
            0,
            stateful(
                PseudoStateType::Hover,
                CssProperty::const_none(CssPropertyType::Display),
            ),
        );
        c.prune_compact_normal_props();
        let kept: Vec<(PseudoStateType, CssPropertyType)> = c
            .cascaded_props
            .get_slice(0)
            .iter()
            .map(|p| (p.state, p.prop_type))
            .collect();
        assert!(
            !kept.contains(&(PseudoStateType::Normal, CssPropertyType::Display)),
            "the compact cache is authoritative for this one"
        );
        assert!(kept.contains(&(PseudoStateType::Normal, CssPropertyType::Width)));
        assert!(kept.contains(&(PseudoStateType::Normal, CssPropertyType::BackgroundContent)));
        assert!(kept.contains(&(PseudoStateType::Hover, CssPropertyType::Display)));
        assert_eq!(kept.len(), 3);
    }
    #[test]
    fn prune_compact_normal_props_on_an_empty_cache_does_not_panic() {
        let mut c = CssPropertyCache::empty(0);
        c.prune_compact_normal_props();
        assert_eq!(c.cascaded_props.len(), 0);
        let mut c = CssPropertyCache::empty(3);
        c.prune_compact_normal_props();
        assert_eq!(c.cascaded_props.len(), 3);
        assert!(c.cascaded_props.get_slice(0).is_empty());
    }
    // =====================================================================
    // compute_inherited_values
    // =====================================================================
    /// `[root, child]`, child's parent = root (the hierarchy uses 1-based ids).
    fn two_node_hierarchy() -> Vec<NodeHierarchyItem> {
        vec![
            NodeHierarchyItem {
                parent: 0,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 2,
            },
            NodeHierarchyItem {
                parent: 1,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
        ]
    }
    #[test]
    fn compute_inherited_values_propagates_font_size_to_children() {
        let hierarchy = two_node_hierarchy();
        assert_eq!(hierarchy[1].parent_id(), Some(NodeId::new(0)));
        let nodes = vec![
            div_with(vec![font_size(PixelValue::px(20.0))]),
            NodeData::create_div(),
        ];
        let mut c = CssPropertyCache::empty(2);
        let changed = c.compute_inherited_values(&hierarchy, &nodes);
        assert_eq!(c.computed_values.len(), 2);
        assert_eq!(changed.len(), 2, "both nodes gained a computed value");
        let entries = c.computed_values.values_for(1);
        let (t, v) = &entries[0];
        assert_eq!(*t, CssPropertyType::FontSize);
        assert_eq!(v.origin, CssPropertyOrigin::Inherited);
        assert!(close(font_size_parts(&v.property).unwrap().1, 20.0));
        // the parent's own value keeps the Own origin
        assert_eq!(
            c.computed_values.values_for(0)[0].1.origin,
            CssPropertyOrigin::Own
        );
    }
    #[test]
    fn compute_inherited_values_resolves_a_child_em_against_the_parent_px() {
        let hierarchy = two_node_hierarchy();
        let nodes = vec![
            div_with(vec![font_size(PixelValue::px(20.0))]),
            div_with(vec![font_size(PixelValue::em(2.0))]),
        ];
        let mut c = CssPropertyCache::empty(2);
        c.compute_inherited_values(&hierarchy, &nodes);
        let entries = c.computed_values.values_for(1);
        let (t, v) = &entries[0];
        assert_eq!(*t, CssPropertyType::FontSize);
        assert_eq!(v.origin, CssPropertyOrigin::Own);
        let (metric, n) = font_size_parts(&v.property).unwrap();
        assert_eq!(metric, SizeMetric::Px, "resolved to absolute px");
        assert!(close(n, 40.0), "2em of the parent's 20px, got {n}");
    }
    #[test]
    fn compute_inherited_values_is_idempotent_on_a_second_run() {
        let hierarchy = two_node_hierarchy();
        let nodes = vec![
            div_with(vec![font_size(PixelValue::px(20.0))]),
            NodeData::create_div(),
        ];
        let mut c = CssPropertyCache::empty(2);
        assert_eq!(c.compute_inherited_values(&hierarchy, &nodes).len(), 2);
        assert!(
            c.compute_inherited_values(&hierarchy, &nodes).is_empty(),
            "nothing changed the second time around"
        );
    }
    #[test]
    fn compute_inherited_values_on_an_empty_tree_does_not_panic() {
        let mut c = CssPropertyCache::empty(0);
        assert!(c.compute_inherited_values(&[], &[]).is_empty());
        assert!(c.computed_values.is_empty());
    }
    // =====================================================================
    // restyle / generate_tag_ids
    // =====================================================================
    fn one_node_scaffold() -> (NodeHierarchyItemVec, NodeDataContainer<CascadeInfo>) {
        (
            vec![NodeHierarchyItem::zeroed()].into(),
            NodeDataContainer::new(vec![CascadeInfo {
                index_in_parent: 0,
                is_last_child: true,
            }]),
        )
    }
    #[test]
    fn restyle_with_an_empty_stylesheet_flattens_and_yields_no_tags() {
        let (hierarchy, cascade) = one_node_scaffold();
        let nodes = NodeDataContainer::new(vec![NodeData::create_div()]);
        let non_leaf: ParentWithNodeDepthVec = Vec::new().into();
        let mut css = Css::empty();
        let mut c = CssPropertyCache::empty(1);
        let tags = c.restyle(
            &mut css,
            &nodes.as_ref(),
            &hierarchy,
            &non_leaf,
            &cascade.as_ref(),
        );
        assert!(tags.is_empty(), "a plain div needs no hit-test tag");
        assert!(
            c.css_props.is_flattened(),
            "restyle must leave css_props in read phase"
        );
        assert!(c.resolved_font_sizes_px.get().is_none());
    }
    #[test]
    fn generate_tag_ids_skips_inert_nodes_and_tags_interactive_ones() {
        let (hierarchy, _) = one_node_scaffold();
        let inert = NodeDataContainer::new(vec![NodeData::create_div()]);
        let c = CssPropertyCache::empty(1);
        assert!(c.generate_tag_ids(&inert.as_ref(), &hierarchy).is_empty());
        // an inline :hover rule makes the node hit-testable
        let hoverable = NodeDataContainer::new(vec![div_with_pseudo(
            vec![width_px(1.0)],
            PseudoStateType::Hover,
        )]);
        let tags = c.generate_tag_ids(&hoverable.as_ref(), &hierarchy);
        assert_eq!(tags.len(), 1);
        assert_eq!(tags[0].node_id.into_crate_internal(), Some(NodeId::new(0)));
    }
    #[test]
    fn generate_tag_ids_tags_a_node_with_a_cursor_declaration() {
        let (hierarchy, _) = one_node_scaffold();
        let nodes = NodeDataContainer::new(vec![div_with(vec![CssProperty::const_none(
            CssPropertyType::Cursor,
        )])]);
        let c = CssPropertyCache::empty(1);
        assert_eq!(c.generate_tag_ids(&nodes.as_ref(), &hierarchy).len(), 1);
    }
    #[test]
    fn generate_tag_ids_on_an_empty_dom_yields_nothing() {
        let nodes: NodeDataContainer<NodeData> = NodeDataContainer::new(Vec::new());
        let hierarchy: NodeHierarchyItemVec = Vec::new().into();
        let c = CssPropertyCache::empty(0);
        assert!(c.generate_tag_ids(&nodes.as_ref(), &hierarchy).is_empty());
    }
    // =====================================================================
    // std-gated profiling helpers
    // =====================================================================
    #[cfg(feature = "std")]
    #[test]
    fn css_prop_type_label_is_interned_and_distinct_per_variant() {
        let a = CssPropertyCache::css_prop_type_label(&CssPropertyType::Width);
        let b = CssPropertyCache::css_prop_type_label(&CssPropertyType::Width);
        assert!(!a.is_empty());
        assert_eq!(
            a.as_ptr(),
            b.as_ptr(),
            "the label table must leak at most one &'static str per variant"
        );
        let other = CssPropertyCache::css_prop_type_label(&CssPropertyType::Height);
        assert_ne!(a, other);
    }
    #[cfg(feature = "std")]
    #[test]
    fn drain_css_prop_counts_is_sorted_descending_and_drains() {
        // The counter is thread-local and only records when AZ_PROP_COUNT=1, so
        // the contract to pin here is "never panics, and drains".
        let first = drain_css_prop_counts();
        for w in first.windows(2) {
            assert!(w[0].1 >= w[1].1, "counts must be sorted descending");
        }
        assert!(
            drain_css_prop_counts().is_empty(),
            "a drained counter comes back empty"
        );
    }
}