1
//! CSS property cache for efficient style resolution and animation.
2
//!
3
//! This module implements a cache layer between the raw CSS stylesheet and the rendered DOM.
4
//! It resolves CSS properties for each node, handling:
5
//!
6
//! - **Cascade resolution**: Computes final values from CSS rules, inline styles, and inheritance
7
//! - **Pseudo-class states**: Caches styles for `:hover`, `:active`, `:focus`, etc.
8
//! - **Animation support**: Tracks animating properties for smooth interpolation
9
//! - **Performance**: Avoids re-parsing and re-resolving unchanged properties
10
//!
11
//! # Architecture
12
//!
13
//! The cache is organized per-node and per-property-type. Each property has a dedicated
14
//! getter method that:
15
//!
16
//! 1. Checks if the property is cached
17
//! 2. If not, resolves it from CSS rules + inline styles
18
//! 3. Caches the result for subsequent frames
19
//!
20
//! # Thread Safety
21
//!
22
//! Not thread-safe. Each window has its own cache instance.
23

            
24
extern crate alloc;
25

            
26
use alloc::{boxed::Box, string::String, vec::Vec};
27
use core::{fmt::Write, mem::ManuallyDrop};
28

            
29
use crate::dom::NodeType;
30

            
31
/// Tracks the origin of a CSS property value.
32
/// Used to correctly implement the CSS cascade and inheritance rules.
33
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34
pub enum CssPropertyOrigin {
35
    /// Property was inherited from parent node (only for inheritable properties)
36
    Inherited,
37
    /// Property is the node's own value (from UA CSS, CSS file, inline style, or user override)
38
    Own,
39
}
40

            
41
/// A CSS property with its origin tracking.
42
#[derive(Debug, Clone, PartialEq, Eq)]
43
pub struct CssPropertyWithOrigin {
44
    pub property: CssProperty,
45
    pub origin: CssPropertyOrigin,
46
}
47

            
48
use azul_css::{
49
    css::{Css, CssPath},
50
    dynamic_selector::{
51
        CssPropertyWithConditions, CssPropertyWithConditionsVec, DynamicSelectorContext,
52
    },
53
    props::{
54
        basic::{StyleFontFamily, StyleFontFamilyVec, StyleFontSize},
55
        layout::{LayoutDisplay, LayoutHeight, LayoutWidth},
56
        property::{
57
            BoxDecorationBreakValue, BreakInsideValue, CaretAnimationDurationValue,
58
            CaretColorValue, CaretWidthValue, ClipPathValue, ColumnCountValue, ColumnFillValue,
59
            ColumnRuleColorValue, ColumnRuleStyleValue, ColumnRuleWidthValue, ColumnSpanValue,
60
            ColumnWidthValue, ContentValue, CounterIncrementValue, CounterResetValue, CssProperty,
61
            CssPropertyType, FlowFromValue, FlowIntoValue, LayoutAlignContentValue,
62
            LayoutAlignItemsValue, LayoutAlignSelfValue, LayoutBorderBottomWidthValue,
63
            LayoutBorderLeftWidthValue, LayoutBorderRightWidthValue, LayoutBorderSpacingValue,
64
            LayoutBorderTopWidthValue, LayoutBoxSizingValue, LayoutClearValue,
65
            LayoutColumnGapValue, LayoutDisplayValue, LayoutFlexBasisValue,
66
            LayoutFlexDirectionValue, LayoutFlexGrowValue, LayoutFlexShrinkValue,
67
            LayoutFlexWrapValue, LayoutFloatValue, LayoutGapValue, LayoutGridAutoColumnsValue,
68
            LayoutGridAutoFlowValue, LayoutGridAutoRowsValue, LayoutGridColumnValue,
69
            LayoutGridRowValue, LayoutGridTemplateColumnsValue, LayoutGridTemplateRowsValue,
70
            LayoutHeightValue, LayoutInsetBottomValue, LayoutJustifyContentValue,
71
            LayoutJustifyItemsValue, LayoutJustifySelfValue, LayoutLeftValue,
72
            LayoutMarginBottomValue, LayoutMarginLeftValue, LayoutMarginRightValue,
73
            LayoutMarginTopValue, LayoutMaxHeightValue, LayoutMaxWidthValue, LayoutMinHeightValue,
74
            LayoutMinWidthValue, LayoutOverflowValue, LayoutPaddingBottomValue,
75
            LayoutPaddingLeftValue, LayoutPaddingRightValue, LayoutPaddingTopValue,
76
            LayoutPositionValue, LayoutRightValue, LayoutRowGapValue, LayoutScrollbarWidthValue,
77
            LayoutTableLayoutValue, LayoutTextJustifyValue, LayoutTopValue, LayoutWidthValue,
78
            LayoutWritingModeValue, LayoutZIndexValue, OrphansValue, OverscrollBehaviorValue,
79
            PageBreakValue, ScrollbarFadeDelayValue, ScrollbarFadeDurationValue,
80
            ScrollbarVisibilityModeValue, SelectionBackgroundColorValue, SelectionColorValue,
81
            SelectionRadiusValue, ShapeImageThresholdValue, ShapeInsideValue, ShapeMarginValue,
82
            ShapeOutsideValue, StringSetValue, StyleAlignmentBaselineValue, StyleAppRegionValue,
83
            StyleAspectRatioValue, StyleBackfaceVisibilityValue, StyleBackgroundContentValue,
84
            StyleBackgroundContentVecValue, StyleBackgroundPositionVecValue,
85
            StyleBackgroundRepeatVecValue, StyleBackgroundSizeVecValue, StyleBaselineSourceValue,
86
            StyleBorderBottomColorValue, StyleBorderBottomLeftRadiusValue,
87
            StyleBorderBottomRightRadiusValue, StyleBorderBottomStyleValue,
88
            StyleBorderCollapseValue, StyleBorderLeftColorValue, StyleBorderLeftStyleValue,
89
            StyleBorderRightColorValue, StyleBorderRightStyleValue, StyleBorderTopColorValue,
90
            StyleBorderTopLeftRadiusValue, StyleBorderTopRightRadiusValue,
91
            StyleBorderTopStyleValue, StyleBoxShadowValue, StyleCaptionSideValue,
92
            StyleClipRectValue, StyleCursorValue, StyleDirectionValue, StyleDominantBaselineValue,
93
            StyleEmptyCellsValue, StyleExclusionMarginValue, StyleFilterVecValue,
94
            StyleFontFamilyVecValue, StyleFontSizeValue, StyleFontStyleValue, StyleFontValue,
95
            StyleFontWeightValue, StyleHangingPunctuationValue, StyleHyphenationLanguageValue,
96
            StyleHyphensValue, StyleInitialLetterAlignValue, StyleInitialLetterValue,
97
            StyleInitialLetterWrapValue, StyleLetterSpacingValue, StyleLineBreakValue,
98
            StyleLineClampValue, StyleLineFitEdgeValue, StyleLineHeightValue,
99
            StyleListStylePositionValue, StyleListStyleTypeValue, StyleMixBlendModeValue,
100
            StyleObjectFitValue, StyleObjectPositionValue, StyleOpacityValue,
101
            StyleOverflowClipMarginValue, StyleOverflowWrapValue, StylePerspectiveOriginValue,
102
            StyleScrollbarColorValue, StyleScrollbarGutterValue, StyleSpatialNavigationActionValue,
103
            StyleSpatialNavigationContainValue, StyleTabSizeValue, StyleTextAlignLastValue,
104
            StyleTextAlignValue, StyleTextBoxEdgeValue, StyleTextBoxTrimValue, StyleTextColorValue,
105
            StyleTextCombineUprightValue, StyleTextDecorationValue, StyleTextIndentValue,
106
            StyleTextOrientationValue, StyleTextOverflowValue, StyleTextTransformValue,
107
            StyleTransformOriginValue, StyleTransformVecValue, StyleUnicodeBidiValue,
108
            StyleUserSelectValue, StyleVerticalAlignValue, StyleVisibilityValue,
109
            StyleWhiteSpaceValue, StyleWordBreakValue, StyleWordSpacingValue, WidowsValue,
110
        },
111
        style::{StyleCursor, StyleTextColor, StyleTransformOrigin},
112
    },
113
    AzString,
114
};
115

            
116
use crate::{
117
    dom::{NodeData, NodeId, TabIndex, TagId},
118
    id::{NodeDataContainer, NodeDataContainerRef},
119
    style::CascadeInfo,
120
    styled_dom::{
121
        NodeHierarchyItem, NodeHierarchyItemId, NodeHierarchyItemVec, ParentWithNodeDepth,
122
        ParentWithNodeDepthVec, StyledNodeState, TagIdToNodeIdMapping,
123
    },
124
};
125

            
126
#[cfg(feature = "std")]
127
std::thread_local! {
128
    static PROP_COUNTS: core::cell::RefCell<
129
        std::collections::HashMap<&'static str, usize>
130
    > = core::cell::RefCell::new(std::collections::HashMap::new());
131
}
132

            
133
/// Drain the per-thread CSS cascade-walk counter populated by
134
/// [`CssPropertyCache::get_property`] when `AZ_PROP_COUNT=1` is set
135
/// in the environment.
136
///
137
/// Returns `(property_label, count)` pairs
138
/// sorted by count descending. Layout-side instrumentation calls
139
/// this after each `layout_document` to print which properties
140
/// drove the most cascade walks.
141
#[cfg(feature = "std")]
142
#[must_use]
143
2
pub fn drain_css_prop_counts() -> Vec<(&'static str, usize)> {
144
    // try_with: no real TLS in the lifted-to-wasm web backend (see the
145
    // get_property recording site) — return empty rather than panic.
146
2
    PROP_COUNTS
147
2
        .try_with(|c| {
148
2
            let map = core::mem::take(&mut *c.borrow_mut());
149
2
            let mut v: Vec<_> = map.into_iter().collect();
150
2
            v.sort_by(|a, b| b.1.cmp(&a.1));
151
2
            v
152
2
        })
153
2
        .unwrap_or_default()
154
2
}
155

            
156
// Unit conversion constants (CSS absolute units → pixels)
157
const PT_TO_PX: f32 = 1.333_333;
158
const IN_TO_PX: f32 = 96.0;
159
const CM_TO_PX: f32 = 37.795_277;
160
const MM_TO_PX: f32 = 3.779_527_7;
161

            
162
/// Match on any `CssProperty` variant and access the inner `CssPropertyValue`<T>.
163
#[allow(unused_macros)]
164
macro_rules! match_property_value {
165
    ($property:expr, $value:ident, $expr:expr) => {
166
        match $property {
167
            CssProperty::CaretColor($value) => $expr,
168
            CssProperty::CaretAnimationDuration($value) => $expr,
169
            CssProperty::SelectionBackgroundColor($value) => $expr,
170
            CssProperty::SelectionColor($value) => $expr,
171
            CssProperty::SelectionRadius($value) => $expr,
172
            CssProperty::TextColor($value) => $expr,
173
            CssProperty::FontSize($value) => $expr,
174
            CssProperty::FontFamily($value) => $expr,
175
            CssProperty::FontWeight($value) => $expr,
176
            CssProperty::FontStyle($value) => $expr,
177
            CssProperty::TextAlign($value) => $expr,
178
            CssProperty::TextJustify($value) => $expr,
179
            CssProperty::VerticalAlign($value) => $expr,
180
            CssProperty::LetterSpacing($value) => $expr,
181
            CssProperty::TextIndent($value) => $expr,
182
            CssProperty::InitialLetter($value) => $expr,
183
            CssProperty::LineClamp($value) => $expr,
184
            CssProperty::HangingPunctuation($value) => $expr,
185
            CssProperty::TextCombineUpright($value) => $expr,
186
            CssProperty::UnicodeBidi($value) => $expr,
187
            CssProperty::TextBoxTrim($value) => $expr,
188
            CssProperty::TextBoxEdge($value) => $expr,
189
            CssProperty::DominantBaseline($value) => $expr,
190
            CssProperty::AlignmentBaseline($value) => $expr,
191
            CssProperty::BaselineSource($value) => $expr,
192
            CssProperty::LineFitEdge($value) => $expr,
193
            CssProperty::InitialLetterAlign($value) => $expr,
194
            CssProperty::InitialLetterWrap($value) => $expr,
195
            CssProperty::ScrollbarGutter($value) => $expr,
196
            CssProperty::OverflowClipMargin($value) => $expr,
197
            CssProperty::Clip($value) => $expr,
198
            CssProperty::ExclusionMargin($value) => $expr,
199
            CssProperty::HyphenationLanguage($value) => $expr,
200
            CssProperty::LineHeight($value) => $expr,
201
            CssProperty::WordSpacing($value) => $expr,
202
            CssProperty::TabSize($value) => $expr,
203
            CssProperty::WhiteSpace($value) => $expr,
204
            CssProperty::Hyphens($value) => $expr,
205
            CssProperty::Direction($value) => $expr,
206
            CssProperty::UserSelect($value) => $expr,
207
            CssProperty::TextDecoration($value) => $expr,
208
            CssProperty::Cursor($value) => $expr,
209
            CssProperty::Display($value) => $expr,
210
            CssProperty::Float($value) => $expr,
211
            CssProperty::BoxSizing($value) => $expr,
212
            CssProperty::Width($value) => $expr,
213
            CssProperty::Height($value) => $expr,
214
            CssProperty::MinWidth($value) => $expr,
215
            CssProperty::MinHeight($value) => $expr,
216
            CssProperty::MaxWidth($value) => $expr,
217
            CssProperty::MaxHeight($value) => $expr,
218
            CssProperty::Position($value) => $expr,
219
            CssProperty::Top($value) => $expr,
220
            CssProperty::Right($value) => $expr,
221
            CssProperty::Left($value) => $expr,
222
            CssProperty::Bottom($value) => $expr,
223
            CssProperty::ZIndex($value) => $expr,
224
            CssProperty::FlexWrap($value) => $expr,
225
            CssProperty::FlexDirection($value) => $expr,
226
            CssProperty::FlexGrow($value) => $expr,
227
            CssProperty::FlexShrink($value) => $expr,
228
            CssProperty::FlexBasis($value) => $expr,
229
            CssProperty::JustifyContent($value) => $expr,
230
            CssProperty::AlignItems($value) => $expr,
231
            CssProperty::AlignContent($value) => $expr,
232
            CssProperty::AlignSelf($value) => $expr,
233
            CssProperty::JustifyItems($value) => $expr,
234
            CssProperty::JustifySelf($value) => $expr,
235
            CssProperty::BackgroundContent($value) => $expr,
236
            CssProperty::BackgroundPosition($value) => $expr,
237
            CssProperty::BackgroundSize($value) => $expr,
238
            CssProperty::BackgroundRepeat($value) => $expr,
239
            CssProperty::OverflowX($value) => $expr,
240
            CssProperty::OverflowY($value) => $expr,
241
            CssProperty::OverflowBlock($value) => $expr,
242
            CssProperty::OverflowInline($value) => $expr,
243
            CssProperty::PaddingTop($value) => $expr,
244
            CssProperty::PaddingLeft($value) => $expr,
245
            CssProperty::PaddingRight($value) => $expr,
246
            CssProperty::PaddingBottom($value) => $expr,
247
            CssProperty::MarginTop($value) => $expr,
248
            CssProperty::MarginLeft($value) => $expr,
249
            CssProperty::MarginRight($value) => $expr,
250
            CssProperty::MarginBottom($value) => $expr,
251
            CssProperty::BorderTopLeftRadius($value) => $expr,
252
            CssProperty::BorderTopRightRadius($value) => $expr,
253
            CssProperty::BorderBottomLeftRadius($value) => $expr,
254
            CssProperty::BorderBottomRightRadius($value) => $expr,
255
            CssProperty::BorderTopColor($value) => $expr,
256
            CssProperty::BorderRightColor($value) => $expr,
257
            CssProperty::BorderLeftColor($value) => $expr,
258
            CssProperty::BorderBottomColor($value) => $expr,
259
            CssProperty::BorderTopStyle($value) => $expr,
260
            CssProperty::BorderRightStyle($value) => $expr,
261
            CssProperty::BorderLeftStyle($value) => $expr,
262
            CssProperty::BorderBottomStyle($value) => $expr,
263
            CssProperty::BorderTopWidth($value) => $expr,
264
            CssProperty::BorderRightWidth($value) => $expr,
265
            CssProperty::BorderLeftWidth($value) => $expr,
266
            CssProperty::BorderBottomWidth($value) => $expr,
267
            CssProperty::BoxShadow($value) => $expr,
268
            CssProperty::Opacity($value) => $expr,
269
            CssProperty::Transform($value) => $expr,
270
            CssProperty::TransformOrigin($value) => $expr,
271
            CssProperty::PerspectiveOrigin($value) => $expr,
272
            CssProperty::BackfaceVisibility($value) => $expr,
273
            CssProperty::MixBlendMode($value) => $expr,
274
            CssProperty::Filter($value) => $expr,
275
            CssProperty::Visibility($value) => $expr,
276
            CssProperty::WritingMode($value) => $expr,
277
            CssProperty::GridTemplateColumns($value) => $expr,
278
            CssProperty::GridTemplateRows($value) => $expr,
279
            CssProperty::GridAutoColumns($value) => $expr,
280
            CssProperty::GridAutoRows($value) => $expr,
281
            CssProperty::GridAutoFlow($value) => $expr,
282
            CssProperty::GridColumn($value) => $expr,
283
            CssProperty::GridRow($value) => $expr,
284
            CssProperty::GridTemplateAreas($value) => $expr,
285
            CssProperty::Gap($value) => $expr,
286
            CssProperty::ColumnGap($value) => $expr,
287
            CssProperty::RowGap($value) => $expr,
288
            CssProperty::Clear($value) => $expr,
289
            CssProperty::ScrollbarTrack($value) => $expr,
290
            CssProperty::ScrollbarThumb($value) => $expr,
291
            CssProperty::ScrollbarButton($value) => $expr,
292
            CssProperty::ScrollbarCorner($value) => $expr,
293
            CssProperty::ScrollbarResizer($value) => $expr,
294
            CssProperty::ScrollbarWidth($value) => $expr,
295
            CssProperty::ScrollbarColor($value) => $expr,
296
            CssProperty::ListStyleType($value) => $expr,
297
            CssProperty::ListStylePosition($value) => $expr,
298
            CssProperty::Font($value) => $expr,
299
            CssProperty::ColumnCount($value) => $expr,
300
            CssProperty::ColumnWidth($value) => $expr,
301
            CssProperty::ColumnSpan($value) => $expr,
302
            CssProperty::ColumnFill($value) => $expr,
303
            CssProperty::ColumnRuleStyle($value) => $expr,
304
            CssProperty::ColumnRuleWidth($value) => $expr,
305
            CssProperty::ColumnRuleColor($value) => $expr,
306
            CssProperty::FlowInto($value) => $expr,
307
            CssProperty::FlowFrom($value) => $expr,
308
            CssProperty::ShapeOutside($value) => $expr,
309
            CssProperty::ShapeInside($value) => $expr,
310
            CssProperty::ShapeImageThreshold($value) => $expr,
311
            CssProperty::ShapeMargin($value) => $expr,
312
            CssProperty::ClipPath($value) => $expr,
313
            CssProperty::Content($value) => $expr,
314
            CssProperty::CounterIncrement($value) => $expr,
315
            CssProperty::CounterReset($value) => $expr,
316
            CssProperty::StringSet($value) => $expr,
317
            CssProperty::Orphans($value) => $expr,
318
            CssProperty::Widows($value) => $expr,
319
            CssProperty::PageBreakBefore($value) => $expr,
320
            CssProperty::PageBreakAfter($value) => $expr,
321
            CssProperty::PageBreakInside($value) => $expr,
322
            CssProperty::BreakInside($value) => $expr,
323
            CssProperty::BoxDecorationBreak($value) => $expr,
324
            CssProperty::TableLayout($value) => $expr,
325
            CssProperty::BorderCollapse($value) => $expr,
326
            CssProperty::BorderSpacing($value) => $expr,
327
            CssProperty::CaptionSide($value) => $expr,
328
            CssProperty::EmptyCells($value) => $expr,
329
        }
330
    };
331
}
332

            
333
/// A CSS property tagged with its pseudo-state and property type.
334
///
335
/// Replaces the per-pseudo-state `BTreeMap` approach: instead of 6 `BTreeMaps`
336
/// per node (Normal/Hover/Active/Focus/Dragging/DragOver), we store one Vec
337
/// per node and tag each property with its state. Lookups use `.iter().find()`.
338
#[derive(Debug, Clone, PartialEq, Eq)]
339
pub struct StatefulCssProperty {
340
    pub state: azul_css::dynamic_selector::PseudoStateType,
341
    pub prop_type: CssPropertyType,
342
    pub property: CssProperty,
343
    /// `true` when this entry was pushed by [`CssPropertyCache::apply_ua_css`]
344
    /// (a user-agent default), `false` for everything the author cascade and
345
    /// the inheritance walk produced.
346
    ///
347
    /// The UA defaults are answered from the window's THEME (`<hr>` rule,
348
    /// native button borders, the root text colour), so a theme flip has to
349
    /// replace them. `apply_ua_css` guards duplicates with a per-node bitset
350
    /// built from the entries already present — which made a second
351
    /// application a no-op: the stale light entry marked the bit, the dark
352
    /// twin was skipped, and the flip never reached `cascaded_props`. The
353
    /// origin tag is what lets a re-application strip exactly its own
354
    /// previous entries first (and nothing else).
355
    pub ua_origin: bool,
356
}
357

            
358
/// One bit per `CssPropertyType` (fewer than 256 variants): "this node has
359
/// a Normal-state value of this type from a layer that beats the UA sheet".
360
type PropTypeBits = [u128; 2];
361

            
362
#[inline]
363
8326689
const fn prop_type_bit_set(bits: &mut PropTypeBits, prop_type: CssPropertyType) {
364
8326689
    let d = prop_type as u16 as usize;
365
8326689
    if d < 128 {
366
7932566
        bits[0] |= 1u128 << d;
367
7932994
    } else {
368
394123
        bits[1] |= 1u128 << (d - 128);
369
394123
    }
370
8326689
}
371

            
372
#[inline]
373
71758702
const fn prop_type_bit_test(bits: &PropTypeBits, prop_type: CssPropertyType) -> bool {
374
71758702
    let d = prop_type as u16 as usize;
375
71758702
    if d < 128 {
376
58149293
        (bits[0] & (1u128 << d)) != 0
377
    } else {
378
13609409
        (bits[1] & (1u128 << (d - 128))) != 0
379
    }
380
71758702
}
381

            
382
// =============================================================================
383
// FlatVecVec: Cache-friendly replacement for Vec<Vec<T>>
384
// =============================================================================
385

            
386
/// A flat, cache-friendly replacement for `Vec<Vec<T>>`.
387
///
388
/// During the **build phase**, items are pushed into per-node inner Vecs
389
/// (same as before). After building is complete, `flatten()` compacts all
390
/// inner Vecs into a single contiguous `Vec<T>` with a `(start, len)` offset
391
/// table per node. All subsequent reads use the flat layout, eliminating
392
/// N heap allocations and pointer chasing.
393
///
394
/// ## Lifecycle
395
///
396
/// ```text
397
/// new(n) → push_to(idx, item)* → sort_each_and_flatten(key_fn) → get_slice(idx)*
398
///          ── build phase ──       ── transition ──                ── read phase ──
399
/// ```
400
#[derive(Debug, Clone)]
401
pub struct FlatVecVec<T> {
402
    /// Per-node inner Vecs (used during build phase, empty after flatten).
403
    build: Vec<Vec<T>>,
404
    /// Flat contiguous storage (populated after flatten).
405
    data: Vec<T>,
406
    /// `(start, len)` offsets into `data` for each node (populated after flatten).
407
    offsets: Vec<(u32, u32)>,
408
}
409

            
410
impl<T: PartialEq> PartialEq for FlatVecVec<T> {
411
7
    fn eq(&self, other: &Self) -> bool {
412
7
        let self_in_build = !self.build.is_empty() && self.offsets.is_empty();
413
7
        let other_in_build = !other.build.is_empty() && other.offsets.is_empty();
414
7
        debug_assert!(
415
            self_in_build == other_in_build,
416
            "FlatVecVec::eq called across phases (one build, one flattened)"
417
        );
418
7
        if self_in_build || other_in_build {
419
4
            self.build == other.build
420
        } else {
421
3
            self.data == other.data && self.offsets == other.offsets
422
        }
423
7
    }
424
}
425

            
426
impl<T> Default for FlatVecVec<T> {
427
6
    fn default() -> Self {
428
6
        Self {
429
6
            build: Vec::new(),
430
6
            data: Vec::new(),
431
6
            offsets: Vec::new(),
432
6
        }
433
6
    }
434
}
435

            
436
impl<T> FlatVecVec<T> {
437
    /// Approximate heap bytes retained. Sums capacity of the
438
    /// flattened `data` + `offsets` tables and the per-node build
439
    /// Vecs (in case `sort_each_and_flatten` hasn't been called
440
    /// yet). `per_element_size` should be `size_of::<T>()`.
441
    #[must_use]
442
20
    pub fn heap_bytes(&self, per_element_size: usize) -> usize {
443
20
        let data_bytes = self.data.capacity() * per_element_size;
444
20
        let offsets_bytes = self.offsets.capacity() * size_of::<(u32, u32)>();
445
20
        let mut build_bytes = self.build.capacity() * size_of::<Vec<T>>();
446
144
        for v in &self.build {
447
124
            build_bytes += v.capacity() * per_element_size;
448
124
        }
449
20
        data_bytes + offsets_bytes + build_bytes
450
20
    }
451

            
452
    /// Create a new `FlatVecVec` with `node_count` empty slots (build phase).
453
    #[must_use]
454
173727
    pub fn new(node_count: usize) -> Self {
455
173727
        let mut build = Vec::with_capacity(node_count);
456
3520402
        for _ in 0..node_count {
457
3520402
            build.push(Vec::new());
458
3520402
        }
459
173727
        Self {
460
173727
            build,
461
173727
            data: Vec::new(),
462
173727
            offsets: Vec::new(),
463
173727
        }
464
173727
    }
465

            
466
    /// Push an item to the inner Vec at `node_index` (build phase).
467
    ///
468
    /// # Panics
469
    /// Panics if already flattened or if `node_index >= len()`.
470
    #[inline]
471
2316894
    pub fn push_to(&mut self, node_index: usize, item: T) {
472
2316894
        self.build[node_index].push(item);
473
2316894
    }
474

            
475
    /// Get a mutable reference to the inner Vec at `node_index` (build phase).
476
    #[inline]
477
629614
    pub fn build_mut(&mut self, node_index: usize) -> &mut Vec<T> {
478
629614
        &mut self.build[node_index]
479
629614
    }
480

            
481
    /// Iterate mutably over all inner Vecs (build phase, e.g. for clearing).
482
    #[inline]
483
1
    pub fn build_iter_mut(&mut self) -> core::slice::IterMut<'_, Vec<T>> {
484
1
        self.build.iter_mut()
485
1
    }
486

            
487
    /// Get a reference to the inner Vec at `node_index` during build phase.
488
    /// During read phase, returns None (use `get_slice` instead).
489
    #[inline]
490
    #[must_use]
491
6
    pub fn build_get(&self, node_index: usize) -> Option<&Vec<T>> {
492
6
        self.build.get(node_index)
493
6
    }
494

            
495
    /// Number of node slots.
496
    #[inline]
497
    #[must_use]
498
142431
    pub const fn len(&self) -> usize {
499
142431
        if self.offsets.is_empty() {
500
91977
            self.build.len()
501
        } else {
502
50454
            self.offsets.len()
503
        }
504
142431
    }
505

            
506
    /// Returns `true` if there are no node slots.
507
    #[inline]
508
    #[must_use]
509
5
    pub const fn is_empty(&self) -> bool {
510
5
        self.len() == 0
511
5
    }
512

            
513
    /// Returns true if this is in read (flattened) mode.
514
    #[inline]
515
    #[must_use]
516
50094
    pub const fn is_flattened(&self) -> bool {
517
50094
        !self.offsets.is_empty() || self.build.is_empty()
518
50094
    }
519

            
520
    /// Get a slice for the node at `node_index` (read phase).
521
    /// Returns empty slice if index is out of bounds or not yet flattened
522
    /// (falls back to build-phase data if not yet flattened).
523
    #[inline]
524
    #[must_use]
525
54124208
    pub fn get_slice(&self, node_index: usize) -> &[T] {
526
54124208
        if self.offsets.is_empty() {
527
            // Build phase fallback: use inner Vecs
528
8480334
            self.build
529
8480334
                .get(node_index)
530
8480334
                .map_or(&[], alloc::vec::Vec::as_slice)
531
        } else {
532
            // Read phase: use flat data
533
45643874
            if let Some(&(start, len)) = self.offsets.get(node_index) {
534
45643872
                let s = start as usize;
535
45643872
                let l = len as usize;
536
45643872
                &self.data[s..s + l]
537
            } else {
538
2
                &[]
539
            }
540
        }
541
54124208
    }
542

            
543
    /// Collapse IDENTICAL per-node runs so nodes with the same property set
544
    /// share ONE copy of it.
545
    ///
546
    /// A stylesheet's declarations repeat across every node they match, and the
547
    /// flat store held a private copy for each: on the 50k-node XHTML bench,
548
    /// `css_props` was 165 120 entries carrying EIGHT distinct values, at 144
549
    /// bytes per entry — 23.8 MB of the same handful of properties written out
550
    /// over and over.
551
    ///
552
    /// Nothing is dropped and no API changes: `get_slice` still returns a real
553
    /// contiguous slice, several nodes simply point at the same range. That is
554
    /// sound because no caller can obtain a `&mut` to a node's run — the store
555
    /// is rebuilt wholesale by `sort_each_and_flatten` / `retain`, never patched
556
    /// in place.
557
    ///
558
    /// The run table is scanned linearly and CAPPED: distinct runs are few in
559
    /// practice (a stylesheet has far fewer rule combinations than nodes), and
560
    /// the cap turns the pathological case into "stops deduplicating" rather
561
    /// than into quadratic time.
562
142227
    fn dedup_runs(&mut self)
563
142227
    where
564
142227
        T: Clone + PartialEq,
565
    {
566
        /// Beyond this many distinct runs, stop recording new ones. Existing
567
        /// runs are still reused, so the result is partial sharing, never wrong.
568
        const MAX_RUNS: usize = 1024;
569

            
570
142227
        if self.offsets.is_empty() {
571
73
            return;
572
142154
        }
573
142154
        let mut new_data: Vec<T> = Vec::new();
574
142154
        let mut runs: Vec<(u32, u32)> = Vec::new();
575
142154
        let mut new_offsets = Vec::with_capacity(self.offsets.len());
576

            
577
3471448
        for &(start, len) in &self.offsets {
578
3329294
            if len == 0 {
579
1291458
                new_offsets.push((0, 0));
580
1291458
                continue;
581
2037836
            }
582
2037836
            let s = start as usize;
583
2037836
            let run = &self.data[s..s + len as usize];
584
2037836
            let existing = runs
585
2037836
                .iter()
586
2037836
                .copied()
587
8483281
                .find(|&(rs, rl)| rl == len && new_data[rs as usize..(rs + rl) as usize] == *run);
588
2037836
            if let Some((rs, rl)) = existing {
589
1710068
                new_offsets.push((rs, rl));
590
1710068
                continue;
591
327768
            }
592
327768
            let ns = u32::try_from(new_data.len()).unwrap_or(u32::MAX);
593
327768
            new_data.extend_from_slice(run);
594
327768
            if runs.len() < MAX_RUNS {
595
327768
                runs.push((ns, len));
596
327768
            }
597
327768
            new_offsets.push((ns, len));
598
        }
599

            
600
142154
        self.data = new_data;
601
142154
        self.offsets = new_offsets;
602
142227
    }
603

            
604
    /// Flatten: sort each inner Vec by key, deduplicate by keeping the last
605
    /// occurrence of each key (CSS cascade: later source order wins among
606
    /// equal specificity), then compact into flat storage.
607
    ///
608
    /// Drains all build-phase Vecs. After this call, only `get_slice()` works.
609
92213
    pub fn sort_each_and_flatten<K: Ord + Eq>(&mut self, key_fn: impl Fn(&T) -> K)
610
92213
    where
611
92213
        T: Clone + PartialEq,
612
    {
613
92213
        let node_count = self.build.len();
614
92213
        let total: usize = self.build.iter().map(alloc::vec::Vec::len).sum();
615

            
616
92213
        let mut flat_data = Vec::with_capacity(total);
617
92213
        let mut offsets = Vec::with_capacity(node_count);
618

            
619
2231996
        for inner in &mut self.build {
620
8832582
            inner.sort_by_key(|a| key_fn(a));
621

            
622
            // Deduplicate: keep last of each consecutive-key group (CSS cascade).
623
2139783
            let n = inner.len();
624
2139783
            let mut keep = vec![false; n];
625
4062982
            for i in 0..n {
626
4062341
                if i + 1 >= n || key_fn(&inner[i]) != key_fn(&inner[i + 1]) {
627
4035989
                    keep[i] = true;
628
4035989
                }
629
            }
630

            
631
2139783
            let start = u32::try_from(flat_data.len()).unwrap_or(u32::MAX);
632
            // Drain inner and push only kept items
633
4062982
            for (i, item) in inner.drain(..).enumerate() {
634
4062341
                if keep[i] {
635
4035989
                    flat_data.push(item);
636
4035989
                }
637
            }
638

            
639
2139783
            let len = u32::try_from(flat_data.len()).unwrap_or(u32::MAX) - start;
640
2139783
            offsets.push((start, len));
641
        }
642

            
643
92213
        flat_data.shrink_to_fit();
644
92213
        self.data = flat_data;
645
92213
        self.offsets = offsets;
646
92213
        self.build = Vec::new();
647
92213
        self.dedup_runs();
648
92213
    }
649

            
650
    /// Flatten without sorting (for data that's already sorted).
651
14
    pub fn flatten(&mut self) {
652
14
        let node_count = self.build.len();
653
14
        let total: usize = self.build.iter().map(alloc::vec::Vec::len).sum();
654

            
655
14
        let mut flat_data = Vec::with_capacity(total);
656
14
        let mut offsets = Vec::with_capacity(node_count);
657

            
658
41
        for inner in &mut self.build {
659
27
            let start = u32::try_from(flat_data.len()).unwrap_or(u32::MAX);
660
27
            let len = u32::try_from(inner.len()).unwrap_or(u32::MAX);
661
27
            offsets.push((start, len));
662
27
            flat_data.append(inner);
663
27
        }
664

            
665
14
        self.data = flat_data;
666
14
        self.offsets = offsets;
667
14
        self.build = Vec::new();
668
14
    }
669

            
670
    /// Rebuild flat storage, keeping only items matching `predicate`.
671
    /// Must be called after flatten. Preserves per-node ordering.
672
50088
    pub fn retain(&mut self, predicate: impl Fn(&T) -> bool)
673
50088
    where
674
50088
        T: Clone + PartialEq,
675
    {
676
50088
        if self.offsets.is_empty() {
677
74
            return;
678
50014
        }
679
50014
        let node_count = self.offsets.len();
680
50014
        let mut new_data = Vec::new();
681
50014
        let mut new_offsets = Vec::with_capacity(node_count);
682
1239525
        for &(start, len) in &self.offsets {
683
1189511
            let s = start as usize;
684
1189511
            let l = len as usize;
685
1189511
            let new_start = u32::try_from(new_data.len()).unwrap_or(u32::MAX);
686
1189511
            let slice = &self.data[s..s + l];
687
1189511
            let mut kept = 0u32;
688
3993086
            for item in slice {
689
2803575
                if predicate(item) {
690
1059472
                    new_data.push((*item).clone());
691
1059472
                    kept += 1;
692
1744103
                }
693
            }
694
1189511
            new_offsets.push((new_start, kept));
695
        }
696
50014
        new_data.shrink_to_fit();
697
50014
        self.data = new_data;
698
50014
        self.offsets = new_offsets;
699
50014
        self.dedup_runs();
700
50088
    }
701

            
702
    /// Return to build phase from read (flattened) phase, preserving all data, so
703
    /// `push_to` / `build_mut` work again. No-op if already in build phase.
704
    ///
705
    /// The build → flatten → read progression is otherwise one-way, but `restyle()`
706
    /// legitimately runs more than once on the same cache (`StyledDom::create` does one
707
    /// internal pass, then the public API may do more), and building the compact cache
708
    /// flattens these vecs in between. Without re-entering build phase, the next
709
    /// restyle's `push_to` / `build_mut` would index an emptied `build` and panic.
710
50221
    pub fn ensure_build_phase(&mut self)
711
50221
    where
712
50221
        T: Clone,
713
    {
714
50221
        if self.offsets.is_empty() {
715
41891
            return; // already in build phase (or wholly empty)
716
8330
        }
717
8330
        let mut build = Vec::with_capacity(self.offsets.len());
718
343201
        for &(start, len) in &self.offsets {
719
334871
            let s = start as usize;
720
334871
            let l = len as usize;
721
334871
            build.push(self.data[s..s + l].to_vec());
722
334871
        }
723
8330
        self.build = build;
724
8330
        self.data = Vec::new();
725
8330
        self.offsets = Vec::new();
726
50221
    }
727

            
728
    /// Like `retain`, but passes each item's owning node index to the predicate.
729
    /// Must be called after flatten. Preserves per-node ordering.
730
2
    pub fn retain_with_node_index(&mut self, predicate: impl Fn(usize, &T) -> bool)
731
2
    where
732
2
        T: Clone,
733
    {
734
2
        if self.offsets.is_empty() {
735
1
            return;
736
1
        }
737
1
        let node_count = self.offsets.len();
738
1
        let mut new_data = Vec::new();
739
1
        let mut new_offsets = Vec::with_capacity(node_count);
740
3
        for (node_idx, &(start, len)) in self.offsets.iter().enumerate() {
741
3
            let s = start as usize;
742
3
            let l = len as usize;
743
3
            let new_start = u32::try_from(new_data.len()).unwrap_or(u32::MAX);
744
3
            let slice = &self.data[s..s + l];
745
3
            let mut kept = 0u32;
746
6
            for item in slice {
747
3
                if predicate(node_idx, item) {
748
1
                    new_data.push((*item).clone());
749
1
                    kept += 1;
750
2
                }
751
            }
752
3
            new_offsets.push((new_start, kept));
753
        }
754
1
        new_data.shrink_to_fit();
755
1
        self.data = new_data;
756
1
        self.offsets = new_offsets;
757
2
    }
758

            
759
    /// Iterate over all nodes, yielding (`node_index`, &[T]) for each.
760
    /// Works in both build and flattened phases.
761
100445
    pub(crate) const fn iter_node_slices(&self) -> FlatVecVecIter<'_, T> {
762
100445
        FlatVecVecIter {
763
100445
            fvv: self,
764
100445
            idx: 0,
765
100445
            count: self.len(),
766
100445
        }
767
100445
    }
768

            
769
    /// Extend this `FlatVecVec` with all nodes from `other` (append for DOM merge).
770
    /// Both must be in build phase, or both must be flattened.
771
491
    pub fn extend_from(&mut self, other: &mut Self) {
772
491
        if !self.offsets.is_empty() && !other.offsets.is_empty() {
773
            // Both flattened: extend flat data with offset adjustment
774
471
            let base = u32::try_from(self.data.len()).unwrap_or(u32::MAX);
775
471
            self.data.append(&mut other.data);
776
471
            self.offsets
777
756
                .extend(other.offsets.drain(..).map(|(s, l)| (s + base, l)));
778
20
        } else {
779
20
            // At least one in build phase: extend build vecs
780
20
            self.build.append(&mut other.build);
781
20
            // Invalidate flat data if it existed
782
20
            self.data.clear();
783
20
            self.offsets.clear();
784
20
        }
785
491
    }
786
}
787

            
788
/// Iterator over (`node_index`, &[T]) pairs from a `FlatVecVec`.
789
pub(crate) struct FlatVecVecIter<'a, T> {
790
    fvv: &'a FlatVecVec<T>,
791
    idx: usize,
792
    count: usize,
793
}
794

            
795
impl<'a, T> Iterator for FlatVecVecIter<'a, T> {
796
    type Item = (usize, &'a [T]);
797

            
798
    #[inline]
799
2574889
    fn next(&mut self) -> Option<Self::Item> {
800
2574889
        if self.idx >= self.count {
801
100445
            return None;
802
2474444
        }
803
2474444
        let i = self.idx;
804
2474444
        self.idx += 1;
805
2474444
        Some((i, self.fvv.get_slice(i)))
806
2574889
    }
807

            
808
2
    fn size_hint(&self) -> (usize, Option<usize>) {
809
2
        let rem = self.count - self.idx;
810
2
        (rem, Some(rem))
811
2
    }
812
}
813

            
814
impl<T> ExactSizeIterator for FlatVecVecIter<'_, T> {}
815

            
816
/// The slow path's inherited-value store, TRANSPOSED: one copy of each distinct
817
/// value plus the nodes that resolve to it.
818
///
819
/// The per-node shape (`Vec<Vec<(CssPropertyType, CssPropertyWithOrigin)>>`)
820
/// paid for the VALUE once per node, and `CssProperty` is a 136-byte enum held
821
/// inline. Inherited values are shared down a subtree by definition, so that is
822
/// the worst possible layout for them: on the 50k-node XHTML bench the store
823
/// held 53 476 entries carrying just EIGHT distinct values — `cursor` alone was
824
/// 29 391 entries of one value, re-paid in every descendant of the node that
825
/// set it.
826
///
827
/// Transposed, the same content is 215 KB instead of 8.1 MB (38x). The lookup
828
/// stays cheap because the bucket count is tiny: a linear scan over ~6 property
829
/// types beats hashing, and the node list is sorted (nodes are cascaded in
830
/// increasing index order, so it is built by `push`) for a binary search.
831
///
832
/// INVARIANT: every bucket's `prop_type.is_inheritable()` is true — this store
833
/// is only ever written through [`CssPropertyCache::store_if_changed`], which
834
/// filters. Non-inherited properties live in `cascaded_props` / `css_props` /
835
/// the compact cache.
836
#[derive(Debug, Clone, Default, PartialEq)]
837
pub struct InheritedValues {
838
    buckets: Vec<InheritedBucket>,
839
    /// Node count this store was sized for; `Vec<Vec<_>>::len()` used to answer
840
    /// this and several callers (and tests) still ask.
841
    node_count: usize,
842
}
843

            
844
#[derive(Debug, Clone, PartialEq)]
845
struct InheritedBucket {
846
    prop_type: CssPropertyType,
847
    value: CssPropertyWithOrigin,
848
    /// Node indices with this value, ascending.
849
    nodes: Vec<u32>,
850
}
851

            
852
impl InheritedValues {
853
    #[must_use]
854
95923
    pub const fn new() -> Self {
855
95923
        Self {
856
95923
            buckets: Vec::new(),
857
95923
            node_count: 0,
858
95923
        }
859
95923
    }
860

            
861
    #[must_use]
862
2
    pub const fn len(&self) -> usize {
863
2
        self.node_count
864
2
    }
865

            
866
    #[must_use]
867
2
    pub const fn is_empty(&self) -> bool {
868
2
        self.node_count == 0
869
2
    }
870

            
871
    /// Number of distinct (type, value) buckets — the figure the scan cost is
872
    /// linear in. Exposed for the memory/coverage tests.
873
    #[must_use]
874
    pub const fn bucket_count(&self) -> usize {
875
        self.buckets.len()
876
    }
877

            
878
    /// Total (node, property) pairs — what the old per-node vecs would have
879
    /// stored one entry each for.
880
    #[must_use]
881
    pub fn entry_count(&self) -> usize {
882
        self.buckets.iter().map(|b| b.nodes.len()).sum()
883
    }
884

            
885
102074
    pub fn grow_to(&mut self, node_count: usize) {
886
102074
        self.node_count = self.node_count.max(node_count);
887
102074
    }
888

            
889
    /// Drop every value, keeping the sizing. Called at the head of a cascade.
890
19
    pub fn clear_values(&mut self) {
891
19
        self.buckets.clear();
892
19
    }
893

            
894
    /// The resolved value of `prop_type` for `node`, if any.
895
    ///
896
    /// Linear over buckets (a handful) then binary over the node list.
897
    #[must_use]
898
31705125
    pub fn get(&self, node: usize, prop_type: CssPropertyType) -> Option<&CssPropertyWithOrigin> {
899
31705125
        let n = u32::try_from(node).ok()?;
900
31705111
        self.buckets
901
31705111
            .iter()
902
441525008
            .find(|b| b.prop_type == prop_type && b.nodes.binary_search(&n).is_ok())
903
31705111
            .map(|b| &b.value)
904
31705125
    }
905

            
906
    /// Every (type, value) this node resolved to, ascending by type — the shape
907
    /// the per-node `Vec` used to hand out.
908
    #[must_use]
909
2429051
    pub fn values_for(&self, node: usize) -> Vec<(CssPropertyType, CssPropertyWithOrigin)> {
910
2429051
        let Ok(n) = u32::try_from(node) else {
911
            return Vec::new();
912
        };
913
2429051
        let mut out: Vec<_> = self
914
2429051
            .buckets
915
2429051
            .iter()
916
23504827
            .filter(|b| b.nodes.binary_search(&n).is_ok())
917
5468951
            .map(|b| (b.prop_type, b.value.clone()))
918
2429051
            .collect();
919
2429051
        out.sort_by_key(|(t, _)| *t);
920
2429051
        out
921
2429051
    }
922

            
923
    /// `values_for`, as an `Option` that is `None` when the node resolved to
924
    /// nothing — the shape `Vec<Vec<_>>::get` had, so `if let Some(..)` call
925
    /// sites keep their structure.
926
    ///
927
    /// `None` iff `node` is outside the store; a node that exists but resolved
928
    /// no inherited properties yields `Some(vec![])`.
929
    ///
930
    /// This used to key off emptiness (`(!v.is_empty()).then_some(v)`), which
931
    /// made "this node has nothing" and "there is no such node"
932
    /// indistinguishable. That was harmless while every node held a value, but
933
    /// the store now keeps only properties a reader can actually reach, so a
934
    /// plain `<div>` with no inherited CSS legitimately has none - and the
935
    /// caller could no longer tell that from an out-of-range index.
936
    #[must_use]
937
703
    pub fn values_for_opt(
938
703
        &self,
939
703
        node: usize,
940
703
    ) -> Option<Vec<(CssPropertyType, CssPropertyWithOrigin)>> {
941
703
        (node < self.node_count).then(|| self.values_for(node))
942
703
    }
943

            
944
    /// Record `entries` as `node`'s resolved set.
945
    ///
946
    /// Nodes are cascaded in ascending index order, so each `nodes` list is
947
    /// built by `push` and stays sorted without an insert.
948
1239676
    pub fn set_node(&mut self, node: usize, entries: &[(CssPropertyType, CssPropertyWithOrigin)]) {
949
1239676
        let Ok(n) = u32::try_from(node) else { return };
950
5988170
        for (prop_type, value) in entries {
951
4748494
            match self
952
4748494
                .buckets
953
4748494
                .iter_mut()
954
36069054
                .find(|b| b.prop_type == *prop_type && b.value == *value)
955
            {
956
4403106
                Some(b) => {
957
4403106
                    if b.nodes.last() != Some(&n) {
958
4403106
                        b.nodes.push(n);
959
4403106
                    }
960
                }
961
345388
                None => self.buckets.push(InheritedBucket {
962
345388
                    prop_type: *prop_type,
963
345388
                    value: value.clone(),
964
345388
                    nodes: vec![n],
965
345388
                }),
966
            }
967
        }
968
1239676
    }
969

            
970
    /// Absorb another store whose nodes sit after this one's (subtree
971
    /// composition), shifting its node indices by this store's node count.
972
244
    pub fn append(&mut self, other: &mut Self) {
973
244
        let shift = u32::try_from(self.node_count).unwrap_or(u32::MAX);
974
587
        for mut ob in core::mem::take(&mut other.buckets) {
975
1189
            for n in &mut ob.nodes {
976
606
                *n = n.saturating_add(shift);
977
606
            }
978
583
            match self
979
583
                .buckets
980
583
                .iter_mut()
981
972
                .find(|b| b.prop_type == ob.prop_type && b.value == ob.value)
982
            {
983
469
                Some(b) => b.nodes.extend_from_slice(&ob.nodes),
984
114
                None => self.buckets.push(ob),
985
            }
986
        }
987
244
        self.node_count += other.node_count;
988
244
        other.node_count = 0;
989
244
    }
990

            
991
    /// Approximate retained heap bytes: one value per bucket plus the node ids.
992
    #[must_use]
993
5
    pub fn heap_bytes(&self) -> usize {
994
5
        let entry = size_of::<(CssPropertyType, CssPropertyWithOrigin)>();
995
5
        self.buckets.capacity() * size_of::<InheritedBucket>()
996
5
            + self.buckets.len() * entry
997
5
            + self
998
5
                .buckets
999
5
                .iter()
5
                .map(|b| b.nodes.capacity() * size_of::<u32>())
5
                .sum::<usize>()
5
    }
}
// NOTE: To avoid large memory allocations, this is a "cache" that stores all the CSS properties
// found in the DOM. This cache exists on a per-DOM basis, so it scales independent of how many
// nodes are in the DOM.
//
// If each node would carry its own CSS properties, that would unnecessarily consume memory
// because most nodes use the default properties or override only one or two properties.
//
// The cache can compute the property of any node at any given time, given the current node
// state (hover, active, focused, normal). This way we don't have to duplicate the CSS properties
// onto every single node and exchange them when the style changes. Two caches can be appended
// to each other by simply merging their NodeIds.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct CssPropertyCache {
    // number of nodes in the current DOM
    pub node_count: usize,
    // The author stylesheet this cache was last cascaded with. Retained so nodes
    // inserted at runtime can be re-styled (`StyledDom::restyle_retained`) — the
    // cascade runs once at creation, and without the rules an inserted node could
    // only ever receive UA defaults + inheritance, never its author CSS.
    // (This struct lives behind `CssPropertyCachePtr`, so the field is invisible
    // to the C ABI.)
    pub retained_author_css: Css,
    // properties that were overridden in callbacks (not specific to any node state)
    pub user_overridden_properties: Vec<Vec<(CssPropertyType, CssProperty)>>,
    /// The window's dynamic-selector context (viewport size, theme, OS,
    /// media type...), provided by the layout funnel before the first
    /// layout. `None` = context UNKNOWN (a freshly created `StyledDom` that no
    /// window has adopted yet): non-pseudo-state conditions then evaluate to
    /// "does not apply", which is the same behaviour they always had before
    /// contexts were wired through. Pseudo-state conditions never depend on
    /// this field.
    pub dynamic_context: Option<Box<DynamicSelectorContext>>,
    /// Whether [`Self::apply_ua_css`] has run on this cache at least once.
    ///
    /// Read by the re-application path: the UA defaults it pushed last time
    /// were answered under the context of THAT time (the theme, above all),
    /// so a second application first strips every `ua_origin` entry and
    /// re-answers them. Also what the paint-time fallbacks assert against: a
    /// cache the UA pass has run on carries the inherited text colour in its
    /// resolved style, so a reader falling back to a constant is a bug there
    /// and merely "no cascade yet" here.
    pub ua_applied: bool,
    /// The CASCADE GENERATION: bumped by everything that changes what a node's
    /// resolved style answers — a restyle, a UA/inheritance re-cascade, a
    /// compact-cache rebuild, a context change (`set_dynamic_selector_context`),
    /// a user override written through `restyle_user_property`, a DOM merge.
    ///
    /// Caches that serve PAINTED output key on it (the display-list cache via
    /// `dl_input_fingerprint`, the per-pass `StyleCache`, the DL patch gate):
    /// colour is deliberately excluded from the relayout hash, so without this
    /// two cascades of one DOM under two themes (or before/after a `color`
    /// override) hashed identically and the cache served the other one's
    /// list. One monotonic counter replaces the three compensations that grew
    /// for that (`paint_defaults_fingerprint`, the `last_dynamic_context`
    /// equality gate, `reset_incremental` on a style change) — theme-chain
    /// analysis 2026-09-12, R4/I5.
    ///
    /// NOT bumped by `set_user_property_override_fast`: that is the per-tick
    /// animation channel, whose caller patches the display list with the
    /// interpolated pixels itself; bumping there would miss the DL cache on
    /// every tick of every transition. Only equality is ever compared, so
    /// wrapping is fine.
    pub cascade_epoch: u64,
    // non-default CSS properties that were cascaded from the parent,
    // unified across all pseudo-states (Normal, Hover, Active, Focus, Dragging, DragOver).
    // Stored in a flat cache-friendly layout after sort_and_flatten().
    pub cascaded_props: FlatVecVec<StatefulCssProperty>,
    // non-default CSS properties that were set via a CSS file,
    // unified across all pseudo-states.
    pub css_props: FlatVecVec<StatefulCssProperty>,
    /// Pre-resolved INHERITABLE properties, sorted per node and keyed by
    /// `CssPropertyType`.
    ///
    /// INVARIANT: every entry's `prop_type.is_inheritable()` is true — enforced
    /// at the single write site, `store_if_changed`. Non-inherited properties
    /// live in `cascaded_props` / `css_props` / the compact cache; storing them
    /// here too made this 80% unreachable duplicate (see `store_if_changed`).
    pub computed_values: InheritedValues,
    // Compact layout cache: three-tier numeric encoding for O(1) layout lookups.
    // Built once after restyle + apply_ua_css + compute_inherited_values.
    // Non-compact properties (background, shadow, transform) use get_property_slow().
    pub compact_cache: Option<azul_css::compact_cache::CompactLayoutCache>,
    // Global CSS properties from `*` rules — shared across all nodes.
    // Applied during build_compact_cache_with_inheritance instead of being
    // cloned into each node's css_props (saves 50K×N clones).
    pub global_css_props: Vec<CssProperty>,
    /// Per-node resolved font-size, in pixels, for the `Normal`
    /// pseudo-state. Populated lazily on first call to
    /// [`crate::styled_dom::StyledDom::resolved_font_size_px`] via a
    /// single bottom-up DOM walk; subsequent reads are O(1) Vec
    /// index by `NodeId::index()`.
    ///
    /// Motivation: `get_font_size` is called ~730× per node per
    /// layout pass (see `AZ_PROP_COUNT=1` report — 329 629
    /// cascade walks on excel.html alone). Each resolution
    /// recursively reads the parent's font-size (for `em`) plus
    /// the root's font-size (for `rem`), multiplying the walk
    /// count. Caching the pre-resolved pixel value collapses that
    /// to a single `Vec<f32>` indexed lookup.
    pub resolved_font_sizes_px: crate::sync::OnceLock<Vec<f32>>,
}
/// Heap-size breakdown of a `CssPropertyCache`, produced by
/// [`CssPropertyCache::memory_breakdown`]. All values in bytes.
///
/// Primarily a diagnostic — the numbers are capacity-based and
/// don't chase into property-variant payloads (e.g. the `Vec`
/// inside a `FontFamily(...)`). Intended for "which subfield is
/// eating RSS" triage, not for precise accounting.
#[derive(Debug, Clone, Copy, Default)]
pub struct CssPropertyCacheBreakdown {
    pub node_count: usize,
    pub cascaded_props_bytes: usize,
    pub css_props_bytes: usize,
    pub computed_values_bytes: usize,
    pub user_overridden_bytes: usize,
    pub global_css_props_bytes: usize,
    pub compact_cache_bytes: usize,
    pub resolved_font_sizes_bytes: usize,
}
impl CssPropertyCacheBreakdown {
    /// Sum of all subfields.
    #[must_use]
12
    pub const fn total_bytes(&self) -> usize {
12
        self.cascaded_props_bytes
12
            + self.css_props_bytes
12
            + self.computed_values_bytes
12
            + self.user_overridden_bytes
12
            + self.global_css_props_bytes
12
            + self.compact_cache_bytes
12
            + self.resolved_font_sizes_bytes
12
    }
}
impl CssPropertyCache {
    /// Approximate heap bytes retained by this cache, broken out by
    /// subfield. Used by `StyledDom::memory_breakdown` + the
    /// `AZ_PROFILE=memory` reporter. Sums capacity × element size
    /// for each Vec and adds a coarse allowance for the inner Vec
    /// headers inside `computed_values`.
    ///
    /// This is a measurement helper, not a tight bound — it doesn't
    /// chase into the `CssProperty` enum variants that carry their
    /// own `Vec`/`String` allocations (notably `FontFamily` →
    /// `StyleFontFamilyVec` → `Vec<StyleFontFamily>`), so the real
    /// heap footprint for a property-rich DOM can be 2-3× these
    /// numbers. Still useful for spotting gross duplication between
    /// the pre-compact and compact caches.
5
    pub fn memory_breakdown(&self) -> CssPropertyCacheBreakdown {
5
        let stateful_sz = size_of::<StatefulCssProperty>();
5
        let computed_entry_sz = size_of::<(CssPropertyType, CssPropertyWithOrigin)>();
5
        let outer_vec_sz = size_of::<Vec<(CssPropertyType, CssPropertyWithOrigin)>>();
5
        let cascaded_bytes = self.cascaded_props.heap_bytes(stateful_sz);
5
        let css_bytes = self.css_props.heap_bytes(stateful_sz);
5
        let computed_bytes = self.computed_values.heap_bytes();
5
        let user_overridden_bytes = {
5
            let mut b = self.user_overridden_properties.capacity() * outer_vec_sz;
5
            for v in &self.user_overridden_properties {
                b += v.capacity() * size_of::<(CssPropertyType, CssProperty)>();
            }
5
            b
        };
5
        let global_bytes = self.global_css_props.capacity() * size_of::<CssProperty>();
5
        let compact_bytes = self.compact_cache.as_ref().map_or(0, |c| {
2
            c.tier1_enums.capacity() * 8
2
                + c.tier2_dims.capacity() * 68
2
                + c.tier2_cold.capacity() * 28
2
                + c.tier2b_text.capacity() * 24
2
                + c.prev_font_hashes.capacity() * 8
2
                + c.font_dirty_nodes.capacity() * 8
2
        });
5
        let resolved_font_sizes_bytes = self
5
            .resolved_font_sizes_px
5
            .get()
5
            .map_or(0, |v| v.capacity() * size_of::<f32>());
5
        CssPropertyCacheBreakdown {
5
            node_count: self.node_count,
5
            cascaded_props_bytes: cascaded_bytes,
5
            css_props_bytes: css_bytes,
5
            computed_values_bytes: computed_bytes,
5
            user_overridden_bytes,
5
            global_css_props_bytes: global_bytes,
5
            compact_cache_bytes: compact_bytes,
5
            resolved_font_sizes_bytes,
5
        }
5
    }
    /// Drop Normal-state properties that have compact encodings from
    /// `css_props` and `cascaded_props`. After `build_compact_cache_with_inheritance`,
    /// these are redundant — the compact cache is the source of truth for layout.
    /// Non-Normal entries (hover/active/focus) and non-compact properties
    /// (background, box-shadow, transform, etc.) are kept for `get_property_slow`.
41754
    pub fn prune_compact_normal_props(&mut self) {
        use azul_css::dynamic_selector::PseudoStateType;
        #[cfg(feature = "std")]
        {
            static PRUNE_DBG: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
41754
            let dbg = *PRUNE_DBG.get_or_init(crate::profile::memory_enabled);
41754
            if dbg {
                let mut normal_compact = 0usize;
                let mut normal_noncompact = 0usize;
                let mut nonnormal = 0usize;
                for i in 0..self.css_props.len() {
                    for p in self.css_props.get_slice(i) {
                        if p.state != PseudoStateType::Normal {
                            nonnormal += 1;
                        } else if p.prop_type.has_compact_encoding() {
                            normal_compact += 1;
                        } else {
                            normal_noncompact += 1;
                        }
                    }
                }
                let ssp_sz = size_of::<StatefulCssProperty>();
                let mut casc_normal_compact = 0usize;
                let mut casc_total = 0usize;
                for i in 0..self.cascaded_props.len() {
                    for p in self.cascaded_props.get_slice(i) {
                        casc_total += 1;
                        if p.state == PseudoStateType::Normal && p.prop_type.has_compact_encoding()
                        {
                            casc_normal_compact += 1;
                        }
                    }
                }
                eprintln!(
                    "[PRUNE] css_props: norm+compact={normal_compact} \
                     norm+other={normal_noncompact} nonnorm={nonnormal} SSP={ssp_sz}B | cascaded: \
                     total={casc_total} norm+compact={casc_normal_compact}"
                );
41754
            }
        }
        // The compact cache stores SENTINEL for pixel-valued properties whose inner
        // value is Exact with a non-px metric (vh, vw, %, em, rem, calc(), ...).
        // Those need the slow `css_props` walk at layout time because the compact
        // cache has nothing usable. We must keep them here or the slow path falls
        // back to UA CSS and silently clobbers the author's rule.
2455613
        let keep = |p: &StatefulCssProperty| -> bool {
2455613
            if p.state != PseudoStateType::Normal {
23989
                return true;
2431624
            }
2431624
            if !p.prop_type.has_compact_encoding() {
737645
                return true;
1693979
            }
            // Compact-encoded AND Normal: drop only if the compact cache fully
            // captured the value (px metric, or Auto/Initial/Inherit/None).
1693979
            if property_needs_slow_path_after_compact(&p.property) {
28032
                return true;
1665947
            }
1665947
            false
2455613
        };
        // css_props is STILL NOT PRUNED, but not for the reason recorded here
        // before. That reason — "regenerate_layout rebuilds the compact cache
        // from css_props every frame" (#8: white-space:pre-wrap collapsing) —
        // is FALSE, and the measurement is in the module docs of
        // `StyledDom::cascade_trace`: a 252-pass scenario produced ONE rebuild
        // and 251 context offers that early-returned unchanged. The rebuild
        // fires once per distinct dynamic context, not per frame, and
        // `css_props` is exactly re-derivable from `retained_author_css`, so
        // re-deriving it around a rebuild is affordable.
        //
        // The REAL blocker is the reader set. `css_props` is also read directly
        // by `transient::extract_subtree_as_dom`, which copies a node's matched
        // author rules — ALL pseudo-states — into the extracted DOM's inline
        // style; pruning drops the Normal compact-encoded ones and a scoped
        // `with_css` width vanishes from the extracted subtree
        // (`resolved_style_travels_with_the_extracted_subtree` catches it).
        // `get_property_slow` cannot stand in: it answers one (node, type) at a
        // time and cannot enumerate a node's pseudo-state rules.
        //
        // And the compact cache cannot back-fill what would be dropped:
        // `FontFamily` has a compact encoding but is stored as a u64 HASH, so a
        // pruned family is unrecoverable for any reader not going through
        // `computed_values`.
        //
        // So the prerequisite is not incremental recompute — it is giving
        // extraction a source that survives the prune (its own retained view,
        // or a lossless `CssPropertyType -> CssProperty` bridge over the compact
        // cache, which does not exist today).
        //
        // MEASURED (`AZ_CASCADE_TRACE=1`, e2e scenario of a click plus 250
        // keystrokes, 252 layout passes):
        //
        //     253 cascade decisions | 1 compact rebuild | 251 context offers
        //     that early-returned unchanged
        //
        // The rebuild is gated behind `set_dynamic_selector_context`, which
        // returns immediately when the context is equal — so it fires ONCE per
        // distinct dynamic context (viewport size, theme, focus), i.e. once at
        // startup, and again per size during a resize. Not per frame.
        //
        // What makes the prune SOUND is not the rarity, though — it is that
        // `css_props` is written only by `restyle()`, wholly from
        // `retained_author_css`, so it is exactly re-derivable. Every rebuild
        // site now runs `restyle_retained()` first (see
        // `StyledDom::set_dynamic_selector_context` and its siblings), which
        // repopulates `css_props` before the rebuild reads it. #8 cannot recur:
        // the rebuild never sees a pruned store.
41754
        if !self.cascaded_props.is_flattened() {
21
            self.cascaded_props
31
                .sort_each_and_flatten(|p| (p.state, p.prop_type));
41733
        }
41754
        self.cascaded_props.retain(keep);
41754
    }
    /// Look up a CSS property for a specific pseudo-state in a stateful property vec.
    /// Requires the vec to be sorted by (state, `prop_type`).
    #[inline]
    // prop_cache threads &NodeId/&CssPropertyType uniformly through its hot cascade
    // lookup API (40+ such params); flipping only clippy's few flags to by-value
    // would force ref/deref juggling at every boundary with the by-ref majority,
    // for no measurable hot-path gain — keep the uniform by-ref convention.
    #[allow(clippy::trivially_copy_pass_by_ref)]
23227616
    fn find_in_stateful<'a>(
23227616
        props: &'a [StatefulCssProperty],
23227616
        state: azul_css::dynamic_selector::PseudoStateType,
23227616
        prop_type: &CssPropertyType,
23227616
    ) -> Option<&'a CssProperty> {
23227616
        let key = (state, *prop_type);
23227616
        props
37127764
            .binary_search_by_key(&key, |p| (p.state, p.prop_type))
23227616
            .ok()
23227616
            .map(|idx| &props[idx].property)
23227616
    }
    /// Check if any properties exist for a specific pseudo-state in a stateful property vec.
    /// Requires the vec to be sorted by (state, `prop_type`).
    #[inline]
11017173
    fn has_state_props(
11017173
        props: &[StatefulCssProperty],
11017173
        state: azul_css::dynamic_selector::PseudoStateType,
11017173
    ) -> bool {
        // All entries with the same state are contiguous. Use partition_point
        // to find the first entry >= state, then check if it matches.
11029098
        let i = props.partition_point(|p| p.state < state);
11017173
        i < props.len() && props[i].state == state
11017173
    }
    /// Collect all property types for a specific pseudo-state.
1170
    pub(crate) fn prop_types_for_state(
1170
        props: &[StatefulCssProperty],
1170
        state: azul_css::dynamic_selector::PseudoStateType,
1170
    ) -> impl Iterator<Item = &CssPropertyType> + '_ {
1170
        props
1170
            .iter()
1632
            .filter(move |p| p.state == state)
1170
            .map(|p| &p.prop_type)
1170
    }
}
/// Returns true if `prop`'s value cannot be fully represented in the compact
/// cache and therefore needs to survive `prune_compact_normal_props` so the
/// slow `css_props` walk can still find it at layout time.
///
/// Pixel-valued properties (margin, padding, width, height, ...) are the only
/// case: `Exact(pv)` with `pv.metric != Px` (vh, vw, %, em, rem, ...) encodes
/// to the compact cache's SENTINEL slot, which loses the value. All other
/// compact-encoded types (tier1 enums, colors, hashes, etc.) always round-trip
/// through the compact encoding.
1693992
fn property_needs_slow_path_after_compact(prop: &CssProperty) -> bool {
    use azul_css::{
        css::CssPropertyValue,
        props::{
            basic::length::SizeMetric,
            layout::{
                dimensions::{LayoutHeight, LayoutWidth},
                flex::LayoutFlexBasis,
            },
        },
    };
    // `inner: PixelValue` wrapper types — check metric directly.
    macro_rules! check_plain {
        ($v:expr) => {{
            if let CssPropertyValue::Exact(ref inner) = $v {
                return inner.inner.metric != SizeMetric::Px;
            }
            false
        }};
    }
1693992
    match prop {
        // LayoutWidth / LayoutHeight: enum with `Px(PixelValue)` variant.
        // Non-pixel variants (Auto / MinContent / MaxContent / FitContent / Calc)
        // are already handled by the tier1 fast path or don't exist as i16 dims.
4
        CssProperty::Width(v) => {
3
            if let CssPropertyValue::Exact(LayoutWidth::Px(pv)) = v {
3
                return pv.metric != SizeMetric::Px;
1
            }
1
            false
        }
2
        CssProperty::Height(v) => {
2
            if let CssPropertyValue::Exact(LayoutHeight::Px(pv)) = v {
2
                return pv.metric != SizeMetric::Px;
            }
            false
        }
        // LayoutFlexBasis: enum with `Exact(PixelValue)` variant.
2
        CssProperty::FlexBasis(v) => {
2
            if let CssPropertyValue::Exact(LayoutFlexBasis::Exact(pv)) = v {
1
                return pv.metric != SizeMetric::Px;
1
            }
1
            false
        }
        // `inner: PixelValue` wrappers
1
        CssProperty::MinWidth(v) => check_plain!(v),
        CssProperty::MaxWidth(v) => check_plain!(v),
        CssProperty::MinHeight(v) => check_plain!(v),
        CssProperty::MaxHeight(v) => check_plain!(v),
20755
        CssProperty::FontSize(v) => check_plain!(v),
2382
        CssProperty::PaddingTop(v) => check_plain!(v),
2382
        CssProperty::PaddingRight(v) => check_plain!(v),
2382
        CssProperty::PaddingBottom(v) => check_plain!(v),
3127
        CssProperty::PaddingLeft(v) => check_plain!(v),
42295
        CssProperty::MarginTop(v) => check_plain!(v),
17743
        CssProperty::MarginRight(v) => check_plain!(v),
21091
        CssProperty::MarginBottom(v) => check_plain!(v),
17743
        CssProperty::MarginLeft(v) => check_plain!(v),
1350
        CssProperty::BorderTopWidth(v) => check_plain!(v),
1350
        CssProperty::BorderRightWidth(v) => check_plain!(v),
1350
        CssProperty::BorderBottomWidth(v) => check_plain!(v),
1350
        CssProperty::BorderLeftWidth(v) => check_plain!(v),
        CssProperty::Top(v) => check_plain!(v),
        CssProperty::Right(v) => check_plain!(v),
        CssProperty::Bottom(v) => check_plain!(v),
        CssProperty::Left(v) => check_plain!(v),
        CssProperty::ColumnGap(v) => check_plain!(v),
        CssProperty::RowGap(v) => check_plain!(v),
36
        CssProperty::LetterSpacing(v) => check_plain!(v),
12
        CssProperty::WordSpacing(v) => check_plain!(v),
12
        CssProperty::TextIndent(v) => check_plain!(v),
        CssProperty::TabSize(v) => check_plain!(v),
        // All other compact-encoded types round-trip through the compact cache.
1558623
        _ => false,
    }
1693992
}
/// Clone a `CssProperty` WITHOUT going through its derived `Clone`. The derived clone
/// is a ~179-arm `match self { V(x) => V(x.clone()) }` that LLVM lowers to an indirect
/// HALFWORD jump table (`ldrh`-indexed). The web (remill→wasm) backend mis-lifts that
/// table, so for HEAP/Vec-bearing variants (gradients, font-family, shadows, filters,
/// transforms) the mis-dispatched clone reads wrong-sized data and the cascade traps
/// with "memory access out of bounds" (restyle → inherit → clone). Here every
/// heap-bearing variant is dispatched via single-variant `if let` — a direct
/// discriminant compare, NO jump table — and each inner `v.clone()` is the value
/// type's own clone, which lifts correctly. POD variants fall through to the derived
/// clone: correct on native, and harmless on web (a mis-dispatched discriminant 0 is
/// `CaretColor`, a `Copy` value with no heap pointer to deref). On native this function
/// is byte-for-byte equivalent to `p.clone()`.
/// Inheritable properties whose value must be inherited as the parent's already
/// *resolved* value, NOT propagated as a raw declaration through `cascaded_props`.
///
/// `font-size` is the case: a relative parent value (`1.5em`) propagated raw
/// would be re-resolved against the already-resolved parent at every descendant
/// (multiplicative error: 30px -> 45px -> 67.5px down a chain), and a parent
/// whose own `cascaded` font-size is the *grandparent's* absolute value would
/// skip the parent's own size entirely. Both consuming paths already inherit
/// font-size correctly from the parent's resolved value — `inherit_from_parent`
/// for `computed_values`, and the parent's resolved compact slot in
/// `build_compact_cache_with_inheritance` — so font-size must not ride the raw
/// propagation at all.
1325123
fn is_resolved_parent_inherited(prop_type: CssPropertyType) -> bool {
1325123
    prop_type == CssPropertyType::FontSize
1325123
}
1121811
fn clone_inheritable_property(p: &CssProperty) -> CssProperty {
    use azul_css::props::property::CssProperty;
1121811
    if let CssProperty::FontFamily(v) = p {
209309
        return CssProperty::FontFamily(v.clone());
912502
    }
912502
    if let CssProperty::BackgroundContent(v) = p {
2
        return CssProperty::BackgroundContent(v.clone());
912500
    }
912500
    if let CssProperty::BackgroundPosition(v) = p {
        return CssProperty::BackgroundPosition(v.clone());
912500
    }
912500
    if let CssProperty::BackgroundSize(v) = p {
        return CssProperty::BackgroundSize(v.clone());
912500
    }
912500
    if let CssProperty::BackgroundRepeat(v) = p {
        return CssProperty::BackgroundRepeat(v.clone());
912500
    }
912500
    if let CssProperty::BoxShadowLeft(v) = p {
        return CssProperty::BoxShadowLeft(v.clone());
912500
    }
912500
    if let CssProperty::BoxShadowRight(v) = p {
        return CssProperty::BoxShadowRight(v.clone());
912500
    }
912500
    if let CssProperty::BoxShadowTop(v) = p {
        return CssProperty::BoxShadowTop(v.clone());
912500
    }
912500
    if let CssProperty::BoxShadowBottom(v) = p {
        return CssProperty::BoxShadowBottom(v.clone());
912500
    }
912500
    if let CssProperty::TextShadow(v) = p {
        return CssProperty::TextShadow(v.clone());
912500
    }
912500
    if let CssProperty::ScrollbarTrack(v) = p {
        return CssProperty::ScrollbarTrack(v.clone());
912500
    }
912500
    if let CssProperty::ScrollbarThumb(v) = p {
        return CssProperty::ScrollbarThumb(v.clone());
912500
    }
912500
    if let CssProperty::ScrollbarButton(v) = p {
        return CssProperty::ScrollbarButton(v.clone());
912500
    }
912500
    if let CssProperty::ScrollbarCorner(v) = p {
        return CssProperty::ScrollbarCorner(v.clone());
912500
    }
912500
    if let CssProperty::ScrollbarResizer(v) = p {
        return CssProperty::ScrollbarResizer(v.clone());
912500
    }
912500
    if let CssProperty::Transform(v) = p {
2
        return CssProperty::Transform(v.clone());
912498
    }
912498
    if let CssProperty::Filter(v) = p {
        return CssProperty::Filter(v.clone());
912498
    }
912498
    if let CssProperty::BackdropFilter(v) = p {
        return CssProperty::BackdropFilter(v.clone());
912498
    }
912498
    if let CssProperty::Content(v) = p {
2
        return CssProperty::Content(v.clone());
912496
    }
912496
    if let CssProperty::HyphenationLanguage(v) = p {
        return CssProperty::HyphenationLanguage(v.clone());
912496
    }
912496
    if let CssProperty::Cursor(v) = p {
301106
        return CssProperty::Cursor(*v);
611390
    }
611390
    p.clone()
1121811
}
impl CssPropertyCache {
    /// Match CSS selectors to nodes and populate `css_props`.
    /// Returns tag IDs for hit-testing. If `compact_cache` is available,
    /// uses it for fast display/overflow checks; otherwise falls back to slow path.
    #[must_use]
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive:
                                                                   // single-purpose
                                                                   // parser/builder/dispatch (one
                                                                   // branch per input variant)
41962
    pub fn restyle(
41962
        &mut self,
41962
        css: &mut Css,
41962
        node_data: &NodeDataContainerRef<'_, NodeData>,
41962
        node_hierarchy: &NodeHierarchyItemVec,
41962
        non_leaf_nodes: &ParentWithNodeDepthVec,
41962
        html_tree: &NodeDataContainerRef<'_, CascadeInfo>,
41962
    ) -> Vec<TagIdToNodeIdMapping> {
        use azul_css::{
            css::{
                CssPathPseudoSelector::{
                    Active, DragOver, Dragging, Focus, Hover, Placeholder, SeatFocus,
                },
                CssPathSelector, CssRuleBlock,
            },
            dynamic_selector::{DynamicSelector, PseudoStateType},
            props::layout::LayoutDisplay,
        };
41962
        let css_is_empty = css.is_empty();
        // @-rule conditions (@media width/height, theme, OS...) gate whole
        // rule BLOCKS. Evaluated here against the window's dynamic context —
        // rules whose conditions do not hold are dropped from this cascade
        // exactly as if absent, and `StyledDom::set_dynamic_selector_context`
        // re-runs the cascade when the context changes and the author css
        // has conditional rules. With NO context yet (a StyledDom no window
        // has adopted), conditional rules do not apply — the same behaviour
        // inline conditional properties have always had. (Until 2026-08-10
        // these conditions were silently IGNORED: an author
        // `@media (max-width: 720px)` block applied at every viewport.)
41962
        let dyn_ctx = self.dynamic_context.clone();
83027381
        let rule_applies = |conds: &azul_css::dynamic_selector::DynamicSelectorVec| -> bool {
83027381
            let cs = conds.as_slice();
83027381
            cs.is_empty()
213391
                || dyn_ctx
213391
                    .as_deref()
213391
                    .is_some_and(|c| cs.iter().all(|sel| sel.matches(c)))
83027381
        };
        // Re-enter build phase before repopulating. restyle() is not
        // single-shot: StyledDom::create runs one restyle internally, and building
        // the compact cache flattens these vecs — so on a later restyle both are in
        // read phase, where the old reset `build_iter_mut().clear()` silently
        // iterated ZERO entries (flatten empties `build`). The push_to / build_mut
        // below then indexed an emptied Vec and panicked.
        //
        // css_props is rebuilt from scratch each restyle (repopulated below,
        // flattened at the end), so replace it with a fresh build-phase vec.
        //
        // cascaded_props is rebuilt from scratch TOO (2026-08-12): the old
        // preserve-and-or_insert approach LEAKED properties of rules whose
        // @-condition turned OFF — a color inherited under a min-width
        // block survived in every descendant after crossing below it, so
        // wide and narrow styling applied SIMULTANEOUSLY (the
        // media_restyle_cost law pin caught it). Preservation is
        // unnecessary: the inheritance walk is top-down (parents' fresh
        // slices are written before children read them — the same
        // ordering css_props relies on), so a fresh build-phase vec
        // repopulates completely. The historical reason for preserving
        // was a phase-bug in the old clear, not a data dependency.
        //
        // UNCONDITIONALLY, not only for a non-empty stylesheet: the
        // inheritance walk below runs for every restyle and pushes into
        // `cascaded_props` via `build_mut`, so a restyle with an EMPTY sheet
        // on an already-built cache (a theme flip on an inline-styled DOM
        // is exactly that) indexed the emptied build vec and panicked. The
        // UA entries a previous `apply_ua_css` pushed go with the rest; the
        // caller re-applies them.
41962
        let node_count = self.css_props.len();
41962
        self.css_props = FlatVecVec::new(node_count);
41962
        self.cascaded_props = FlatVecVec::new(node_count);
41962
        self.ua_applied = false;
        // Collect global-only rule declarations ONCE (not per-node).
        // These are stored in self.global_css_props and applied during
        // build_compact_cache_with_inheritance for each node, avoiding
        // 50K × N clones into per-node css_props Vecs.
41962
        self.global_css_props.clear();
41962
        if !css_is_empty {
28044
            css.sort_by_specificity();
            // Separate CSS rules into "global only" (just `*`) vs "has specific selector".
            // Global-only rules apply to ALL nodes — push directly into css_props
            // without per-node selector matching (avoids m×n for these rules).
            // Specific rules still go through matches_html_element per-node.
28044
            let mut global_only_rules: Vec<&CssRuleBlock> = Vec::new();
28044
            let mut specific_rules: Vec<&CssRuleBlock> = Vec::new();
211363
            for rule in css.rules() {
211363
                let selectors = rule.path.selectors.as_ref();
211363
                let is_global_only = selectors.len() == 1
29943
                    && matches!(selectors.first(), Some(CssPathSelector::Global));
211363
                if is_global_only {
3094
                    global_only_rules.push(rule);
208269
                } else {
208269
                    specific_rules.push(rule);
208269
                }
            }
31138
            for rule in &global_only_rules {
3094
                if !rule_applies(&rule.conditions) {
                    continue;
3094
                }
3094
                if crate::style::rule_ends_with(&rule.path, None) {
27362
                    for d in &rule.declarations {
                        // `Static` as-is; an `env()` declaration resolved
                        // against the same context that gates the rule.
24268
                        if let Some(s) = d.resolve_in_cascade(dyn_ctx.as_deref()) {
24268
                            self.global_css_props.push(s);
24268
                        }
                    }
                }
            }
            // Phase 2: Match specific rules per-node (only non-global rules)
28044
            if !specific_rules.is_empty() {
                // Per-node "which declarations match" lists are built as
                // `(rule_idx, decl_idx)` pairs — 4 bytes per entry instead of
                // cloning a 140-byte `CssProperty`. The clone only happens at
                // the final push_to step, so the transient peak is ~35× smaller.
                //
                // rule_idx indexes into `specific_rules` (Vec<&CssRuleBlock>),
                // decl_idx indexes into `rule.declarations.as_slice()`. Both
                // fit in u16 since real stylesheets have far fewer than 65k
                // rules and declarations per rule.
                macro_rules! filter_rules {
                    ($expected_pseudo_selector:expr, $node_id:expr) => {{
                        let mut out: Vec<(u16, u16)> = Vec::new();
                        for (rule_idx, rule_block) in specific_rules.iter().enumerate() {
                            if !rule_applies(&rule_block.conditions) {
                                continue;
                            }
                            if !crate::style::rule_ends_with(
                                &rule_block.path,
                                $expected_pseudo_selector,
                            ) {
                                continue;
                            }
                            if !crate::style::matches_html_element(
                                &rule_block.path,
                                $node_id,
                                &node_hierarchy.as_container(),
                                &node_data,
                                &html_tree,
                                $expected_pseudo_selector,
                            ) {
                                continue;
                            }
                            for (decl_idx, decl) in
                                rule_block.declarations.as_slice().iter().enumerate()
                            {
                                if decl.is_cascade_resolvable() {
                                    out.push((
                                        u16::try_from(rule_idx).unwrap_or(u16::MAX),
                                        u16::try_from(decl_idx).unwrap_or(u16::MAX),
                                    ));
                                }
                            }
                        }
                        out
                    }};
                }
                // Pre-check which pseudo-states have any matching rules at all.
                // This avoids iterating 50K nodes for pseudo-states with zero rules
                // (common: most stylesheets have no :hover/:focus/:active rules).
27993
                let has_normal = specific_rules
27993
                    .iter()
27993
                    .any(|r| crate::style::rule_ends_with(&r.path, None));
27993
                let has_hover = specific_rules
27993
                    .iter()
208005
                    .any(|r| crate::style::rule_ends_with(&r.path, Some(Hover)));
27993
                let has_active = specific_rules
27993
                    .iter()
208269
                    .any(|r| crate::style::rule_ends_with(&r.path, Some(Active)));
27993
                let has_focus = specific_rules
27993
                    .iter()
208269
                    .any(|r| crate::style::rule_ends_with(&r.path, Some(Focus)));
27993
                let has_seat_focus = specific_rules
27993
                    .iter()
208267
                    .any(|r| crate::style::rule_ends_with(&r.path, Some(SeatFocus)));
27993
                let has_dragging = specific_rules
27993
                    .iter()
208269
                    .any(|r| crate::style::rule_ends_with(&r.path, Some(Dragging)));
27993
                let has_drag_over = specific_rules
27993
                    .iter()
208269
                    .any(|r| crate::style::rule_ends_with(&r.path, Some(DragOver)));
27993
                let has_placeholder = specific_rules
27993
                    .iter()
208269
                    .any(|r| crate::style::rule_ends_with(&r.path, Some(Placeholder)));
                macro_rules! collect_and_assign {
                    ($pseudo:expr, $state:expr, $has_any:expr) => {
                        if $has_any {
                            let indices: NodeDataContainer<(NodeId, Vec<(u16, u16)>)> = node_data
849113
                                .transform_nodeid_optional(|node_id| {
82853132
                                    let r = filter_rules!($pseudo, node_id);
849113
                                    if r.is_empty() {
572568
                                        None
                                    } else {
276545
                                        Some((node_id, r))
                                    }
849113
                                });
                            for (n, pairs) in indices.internal.into_iter() {
                                for (rule_idx, decl_idx) in pairs {
                                    let decl = &specific_rules[rule_idx as usize]
                                        .declarations
                                        .as_slice()[decl_idx as usize];
                                    if let Some(prop) = decl.resolve_in_cascade(dyn_ctx.as_deref())
                                    {
                                        self.css_props.push_to(
                                            n.index(),
                                            StatefulCssProperty {
                                                state: $state,
                                                prop_type: prop.get_type(),
                                                property: prop,
                                                ua_origin: false,
                                            },
                                        );
                                    }
                                }
                            }
                        }
                    };
                }
866972
                collect_and_assign!(None, PseudoStateType::Normal, has_normal);
27993
                collect_and_assign!(Some(Hover), PseudoStateType::Hover, has_hover);
27993
                collect_and_assign!(Some(Active), PseudoStateType::Active, has_active);
27993
                collect_and_assign!(Some(Focus), PseudoStateType::Focus, has_focus);
27993
                collect_and_assign!(Some(SeatFocus), PseudoStateType::SeatFocus, has_seat_focus);
27993
                collect_and_assign!(Some(Dragging), PseudoStateType::Dragging, has_dragging);
27993
                collect_and_assign!(Some(DragOver), PseudoStateType::DragOver, has_drag_over);
                collect_and_assign!(
                    Some(Placeholder),
                    PseudoStateType::Placeholder,
27993
                    has_placeholder
                );
51
            } // end if !specific_rules.is_empty()
13918
        }
        // Inheritance: Inherit all values of the parent to the children, but
        // only if the property is inheritable and isn't yet set
509279
        for ParentWithNodeDepth { depth: _, node_id } in non_leaf_nodes {
467317
            let Some(parent_id) = node_id.into_crate_internal() else {
                continue;
            };
467317
            let all_states = [
467317
                PseudoStateType::Normal,
467317
                PseudoStateType::Hover,
467317
                PseudoStateType::Active,
467317
                PseudoStateType::Focus,
467317
                PseudoStateType::SeatFocus,
467317
                PseudoStateType::Dragging,
467317
                PseudoStateType::DragOver,
467317
                PseudoStateType::Placeholder,
467317
            ];
4205853
            for &state in &all_states {
                // 1. Inherit inline CSS properties from parent for this pseudo-state.
                //
                // A declaration belongs to the pseudo-state named in its
                // conditions (none = Normal), and its OTHER conditions — the
                // theme, the viewport, the OS — must hold under the dynamic
                // context, exactly as `apply_cascade_properties` decides for
                // the node itself. Last match wins per property, the way inline
                // declarations resolve everywhere else. This used to keep only
                // declarations whose every condition was a pseudo-state, so a
                // `dark_theme(color)` twin never qualified and the child got
                // the light value as a cascaded declaration of ITS OWN — which
                // `compute_inherited_values` then preferred over the twin it
                // had just inherited from the parent. Every widget label under
                // a dark window (the button's, the tree view's, the ribbon's)
                // was dark-on-dark on a DOM cascaded under the window's
                // context from the start; a DOM that had the context set
                // afterwards was recascaded after the prune and came out
                // right by accident.
3738536
                let parent_inheritable_inline: Vec<(CssPropertyType, CssProperty)> = {
3738536
                    let mut picked: Vec<(CssPropertyType, CssProperty)> = Vec::new();
32836424
                    for (prop, conds) in node_data[parent_id].style.iter_inline_properties() {
32801664
                        let conditions = conds.as_slice();
32801664
                        let decl_state = conditions
32801664
                            .iter()
32801664
                            .find_map(|c| match c {
3528288
                                DynamicSelector::PseudoState(s) => Some(*s),
3156224
                                _ => None,
6684512
                            })
32801664
                            .unwrap_or(PseudoStateType::Normal);
32801664
                        let applies = decl_state == state
4100208
                            && conditions.iter().all(|c| match c {
222792
                                DynamicSelector::PseudoState(s) => *s == state,
394528
                                other => dyn_ctx.as_deref().is_some_and(|ctx| other.matches(ctx)),
617320
                            });
32801664
                        let prop_type = prop.get_type();
32801664
                        if !applies
3705873
                            || !prop_type.is_inheritable()
746328
                            || is_resolved_parent_inherited(prop_type)
                        {
32203188
                            continue;
598476
                        }
598476
                        let value = clone_inheritable_property(prop);
624012
                        match picked.iter_mut().find(|(t, _)| *t == prop_type) {
1597
                            Some(slot) => slot.1 = value,
596879
                            None => picked.push((prop_type, value)),
                        }
                    }
3738536
                    picked
                };
                // 2. Inherit CSS stylesheet properties from parent for this pseudo-state
3738536
                let parent_inheritable_css: Vec<(CssPropertyType, CssProperty)> = if css_is_empty {
243104
                    Vec::new()
                } else {
3495432
                    self.css_props
3495432
                        .get_slice(parent_id.index())
3495432
                        .iter()
6119272
                        .filter(|p| {
6110984
                            p.state == state
763873
                                && p.prop_type.is_inheritable()
79854
                                && !is_resolved_parent_inherited(p.prop_type)
6110984
                        })
3495432
                        .map(|p| (p.prop_type, clone_inheritable_property(&p.property)))
3495432
                        .collect()
                };
                // 3. Inherit cascaded properties from parent for this pseudo-state
3738536
                let parent_inheritable_cascaded: Vec<(CssPropertyType, CssProperty)> = self
3738536
                    .cascaded_props
3738536
                    .get_slice(parent_id.index())
3738536
                    .iter()
4028552
                    .filter(|p| {
3991528
                        p.state == state
498941
                            && p.prop_type.is_inheritable()
498941
                            && !is_resolved_parent_inherited(p.prop_type)
3991528
                    })
3738536
                    .map(|p| (p.prop_type, clone_inheritable_property(&p.property)))
3738536
                    .collect();
                // Combine all inheritable props (inline first = strongest, cascaded last)
                // Only insert if child doesn't already have that (state, prop_type) combo
3738536
                if parent_inheritable_inline.is_empty()
3503733
                    && parent_inheritable_css.is_empty()
3482442
                    && parent_inheritable_cascaded.is_empty()
                {
3356580
                    continue;
381956
                }
629613
                for child_id in parent_id.az_children(&node_hierarchy.as_container()) {
629613
                    let child_vec = self.cascaded_props.build_mut(child_id.index());
1552476
                    for (prop_type, prop_value) in parent_inheritable_inline
629613
                        .iter()
629613
                        .chain(parent_inheritable_css.iter())
629613
                        .chain(parent_inheritable_cascaded.iter())
                    {
                        // or_insert: only insert if child doesn't already have this (state,
                        // prop_type)
1552476
                        if !child_vec
1552476
                            .iter()
1806672
                            .any(|p| p.state == state && p.prop_type == *prop_type)
1476091
                        {
1476091
                            child_vec.push(StatefulCssProperty {
1476091
                                state,
1476091
                                prop_type: *prop_type,
1476091
                                property: prop_value.clone(),
1476091
                                ua_origin: false,
1476091
                            });
1476091
                        }
                    }
                }
            }
        }
        // Sort css_props by (state, prop_type) for binary search lookups,
        // then flatten into contiguous memory for cache-friendly reads.
41962
        self.css_props
3886392
            .sort_each_and_flatten(|p| (p.state, p.prop_type));
        // Restyling can change font-size properties; the memoized resolved font
        // sizes are now stale and must be recomputed on next access.
41962
        self.invalidate_resolved_font_sizes();
41962
        self.generate_tag_ids(node_data, node_hierarchy)
41962
    }
    /// Generate hit-test tag IDs for nodes that need event handling.
    /// Uses compact cache (if available) for fast display/overflow reads.
    /// Can be called separately after `build_compact_cache_with_inheritance`.
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose tag-id walk
92257
    pub fn generate_tag_ids(
92257
        &self,
92257
        node_data: &NodeDataContainerRef<'_, NodeData>,
92257
        node_hierarchy: &NodeHierarchyItemVec,
92257
    ) -> Vec<TagIdToNodeIdMapping> {
        // Tag ID generation: determine which nodes need hit-test tags for
        // hover/click/scroll events. Uses compact cache for display/overflow
        // checks instead of get_property_slow (which searches 6 data structures).
        use azul_css::compact_cache::{
            DISPLAY_MASK, DISPLAY_SHIFT, OVERFLOW_MASK, OVERFLOW_X_SHIFT, OVERFLOW_Y_SHIFT,
        };
92257
        let compact_cache = self.compact_cache.as_ref();
92257
        let node_data_container = &node_data.internal;
92257
        let tag_ids = node_data
92257
            .internal
92257
            .iter()
92257
            .enumerate()
2139567
            .filter_map(|(node_idx, node_data)| {
2139567
                let node_id = NodeId::new(node_idx);
2139567
                let should_auto_insert_tabindex = node_data
2139567
                    .get_callbacks()
2139567
                    .iter()
2139567
                    .any(|cb| cb.event.is_focus_callback());
2139567
                let tab_index = node_data.get_tab_index().map_or(
2139567
                    if should_auto_insert_tabindex {
18732
                        Some(TabIndex::Auto)
                    } else {
2120835
                        None
                    },
                    Some,
                );
2139567
                let mut need_tag = false;
                // Single-pass guard block: each check `break`s out early once it
                // decides `need_tag`. Labeled block (not `loop`) makes the
                // never-iterating control flow explicit (clippy::never_loop).
                'compute_need_tag: {
                    // display:none check — read directly from compact tier1 (fast u64 read)
2139567
                    if let Some(cc) = compact_cache.as_ref() {
1285013
                        let t1 = cc.tier1_enums[node_idx];
1285013
                        let display_val = ((t1 >> DISPLAY_SHIFT) & DISPLAY_MASK) as u8;
1285013
                        if display_val == 4 {
4524
                            break 'compute_need_tag;
1280489
                        } // 4 = LayoutDisplay::None (new encoding)
854554
                    }
2135043
                    if node_data.has_context_menu() || node_data.get_context_menu().is_some() {
96
                        need_tag = true;
96
                        break 'compute_need_tag;
2134947
                    }
2134947
                    if tab_index.is_some() {
216555
                        need_tag = true;
216555
                        break 'compute_need_tag;
1918392
                    }
                    // Pseudo-state property checks (hover/active/focus/dragging/drag-over)
                    {
                        use azul_css::dynamic_selector::{DynamicSelector, PseudoStateType};
11097544
                        let has_pseudo = |state: PseudoStateType| -> bool {
28071340
                            node_data.style.iter_inline_properties().any(|(_p, conds)| {
27952009
                                conds.as_slice().iter().any(
135361
                                    |c| matches!(c, DynamicSelector::PseudoState(s) if *s == state),
                                )
28069781
                            }) || Self::has_state_props(self.css_props.get_slice(node_idx), state)
11097544
                        };
1918392
                        if has_pseudo(PseudoStateType::Hover)
1835879
                            || has_pseudo(PseudoStateType::Active)
1835879
                            || has_pseudo(PseudoStateType::Focus)
1835798
                            || has_pseudo(PseudoStateType::SeatFocus)
1835798
                            || has_pseudo(PseudoStateType::Dragging)
1835798
                            || has_pseudo(PseudoStateType::DragOver)
                        {
82594
                            need_tag = true;
82594
                            break 'compute_need_tag;
1835798
                        }
                    }
                    // Non-window callbacks
1835798
                    let has_non_window_cb = !node_data.get_callbacks().is_empty()
15348
                        && !node_data
15348
                            .get_callbacks()
15348
                            .iter()
15348
                            .all(|cb| cb.event.is_window_callback());
1835798
                    if has_non_window_cb {
15348
                        need_tag = true;
15348
                        break 'compute_need_tag;
1820450
                    }
                    // Cursor check — read from cached css_props or inline style.
1826065
                    if self.css_props.get_slice(node_idx).iter().any(|p| {
1588087
                        p.state == azul_css::dynamic_selector::PseudoStateType::Normal
1588087
                            && p.prop_type == CssPropertyType::Cursor
1821061
                    }) || node_data
1815446
                        .style
1815446
                        .iter_inline_properties()
4060754
                        .any(|(p, _)| p.get_type() == CssPropertyType::Cursor)
                    {
51109
                        need_tag = true;
51109
                        break 'compute_need_tag;
1769341
                    }
                    // Overflow scroll check — read from compact tier1
1769341
                    if let Some(cc) = compact_cache.as_ref() {
1072788
                        let t1 = cc.tier1_enums[node_idx];
1072788
                        let ox = ((t1 >> OVERFLOW_X_SHIFT) & OVERFLOW_MASK) as u8;
1072788
                        let oy = ((t1 >> OVERFLOW_Y_SHIFT) & OVERFLOW_MASK) as u8;
                        // 2 = Scroll, 3 = Auto in layout_overflow_to_u8 (new encoding)
1072788
                        if ox == 2 || ox == 3 || oy == 2 || oy == 3 {
6192
                            need_tag = true;
6192
                            break 'compute_need_tag;
1066596
                        }
696553
                    }
                    // Selectable text check
                    {
                        use crate::dom::NodeType;
1763149
                        let hier = node_hierarchy.as_container()[node_id];
1763149
                        let mut has_text = false;
1763149
                        if let Some(first_child) = hier.first_child_id(node_id) {
767065
                            let mut child_id = Some(first_child);
1690811
                            while let Some(cid) = child_id {
923746
                                if matches!(
1380761
                                    node_data_container[cid.index()].get_node_type(),
                                    NodeType::Text(_)
                                ) {
457015
                                    has_text = true;
457015
                                    break;
923746
                                }
923746
                                child_id = node_hierarchy.as_container()[cid].next_sibling_id();
                            }
996084
                        }
1763149
                        if has_text {
457015
                            need_tag = true;
457015
                            break 'compute_need_tag;
1306134
                        }
                    }
1306134
                    break 'compute_need_tag;
                }
2139567
                if need_tag {
                    // DETERMINISTIC tag: a pure function of node identity
                    // (node index + 1; 0 stays "no tag"), NOT a global
                    // counter. Tag values are namespaced by tag TYPE
                    // (`TAG_TYPE_DOM_NODE` vs cursor/scrollbar/... — every
                    // consumer matches `tag.1`) and resolved per-DOM, so
                    // per-node determinism is all that is required.
                    //
                    // The old `TagId::unique()` counter made tag numbers an
                    // ALLOCATION ORDER artifact: rebuilding the SAME UI (any
                    // callback returning RefreshDom) produced a fresh tag
                    // map, while the structural-identity display-list cache
                    // (solver3 Step 1.1 — root subtree hash + viewport)
                    // correctly reused the old display list. Map and display
                    // list then disagreed about every tag, and each lookup
                    // that crosses the two — `get_node_hit_test_bounds`, the
                    // WebRender hit-test translation — silently resolved to
                    // nothing: after a hash-identical rebuild, clicks aimed
                    // by node stopped landing (the E2E `double_click` on the
                    // ribbon tab was the visible case). With tags derived
                    // from node identity, a structurally identical tree gets
                    // identical tags, which is exactly the invariant the
                    // display-list cache assumes.
828909
                    Some(TagIdToNodeIdMapping {
828909
                        tag_id: TagId::from_crate_internal(TagId {
828909
                            inner: (node_idx as u64) + 1,
828909
                        }),
828909
                        node_id: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
828909
                        tab_index: tab_index.into(),
828909
                    })
                } else {
1310658
                    None
                }
2139567
            })
92257
            .collect::<Vec<_>>();
92257
        tag_ids
92257
    }
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive:
                                                                   // single-purpose
                                                                   // parser/builder/dispatch (one
                                                                   // branch per input variant)
334
    pub fn get_computed_css_style_string(
334
        &self,
334
        node_data: &NodeData,
334
        node_id: &NodeId,
334
        node_state: &StyledNodeState,
334
    ) -> String {
334
        let mut s = String::new();
334
        if let Some(p) = self.get_background_content(node_data, node_id, node_state) {
15
            let _ = write!(s, "background: {};", p.get_css_value_fmt());
319
        }
334
        if let Some(p) = self.get_background_position(node_data, node_id, node_state) {
            let _ = write!(s, "background-position: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_background_size(node_data, node_id, node_state) {
            let _ = write!(s, "background-size: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_background_repeat(node_data, node_id, node_state) {
            let _ = write!(s, "background-repeat: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_font_size(node_data, node_id, node_state) {
111
            let _ = write!(s, "font-size: {};", p.get_css_value_fmt());
323
        }
334
        if let Some(p) = self.get_font_family(node_data, node_id, node_state) {
            let _ = write!(s, "font-family: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_text_color(node_data, node_id, node_state) {
333
            let _ = write!(s, "color: {};", p.get_css_value_fmt());
333
        }
334
        if let Some(p) = self.get_text_align(node_data, node_id, node_state) {
            let _ = write!(s, "text-align: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_line_height(node_data, node_id, node_state) {
            let _ = write!(s, "line-height: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_letter_spacing(node_data, node_id, node_state) {
            let _ = write!(s, "letter-spacing: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_word_spacing(node_data, node_id, node_state) {
            let _ = write!(s, "word-spacing: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_tab_size(node_data, node_id, node_state) {
            let _ = write!(s, "tab-size: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_cursor(node_data, node_id, node_state) {
65
            let _ = write!(s, "cursor: {};", p.get_css_value_fmt());
279
        }
334
        if let Some(p) = self.get_box_shadow_left(node_data, node_id, node_state) {
            let _ = write!(s, "-azul-box-shadow-left: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_box_shadow_right(node_data, node_id, node_state) {
            let _ = write!(s, "-azul-box-shadow-right: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_box_shadow_top(node_data, node_id, node_state) {
            let _ = write!(s, "-azul-box-shadow-top: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_box_shadow_bottom(node_data, node_id, node_state) {
            let _ = write!(s, "-azul-box-shadow-bottom: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_top_color(node_data, node_id, node_state) {
            let _ = write!(s, "border-top-color: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_left_color(node_data, node_id, node_state) {
            let _ = write!(s, "border-left-color: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_right_color(node_data, node_id, node_state) {
            let _ = write!(s, "border-right-color: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_bottom_color(node_data, node_id, node_state) {
            let _ = write!(s, "border-bottom-color: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_top_style(node_data, node_id, node_state) {
            let _ = write!(s, "border-top-style: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_left_style(node_data, node_id, node_state) {
            let _ = write!(s, "border-left-style: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_right_style(node_data, node_id, node_state) {
            let _ = write!(s, "border-right-style: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_bottom_style(node_data, node_id, node_state) {
            let _ = write!(s, "border-bottom-style: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_top_left_radius(node_data, node_id, node_state) {
            let _ = write!(s, "border-top-left-radius: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_top_right_radius(node_data, node_id, node_state) {
            let _ = write!(s, "border-top-right-radius: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_bottom_left_radius(node_data, node_id, node_state) {
            let _ = write!(s, "border-bottom-left-radius: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_bottom_right_radius(node_data, node_id, node_state) {
            let _ = write!(s, "border-bottom-right-radius: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_opacity(node_data, node_id, node_state) {
            let _ = write!(s, "opacity: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_transform(node_data, node_id, node_state) {
            let _ = write!(s, "transform: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_transform_origin(node_data, node_id, node_state) {
            let _ = write!(s, "transform-origin: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_perspective_origin(node_data, node_id, node_state) {
            let _ = write!(s, "perspective-origin: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_backface_visibility(node_data, node_id, node_state) {
            let _ = write!(s, "backface-visibility: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_hyphens(node_data, node_id, node_state) {
            let _ = write!(s, "hyphens: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_direction(node_data, node_id, node_state) {
            let _ = write!(s, "direction: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_unicode_bidi(node_data, node_id, node_state) {
            let _ = write!(s, "unicode-bidi: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_text_box_trim(node_data, node_id, node_state) {
            let _ = write!(s, "text-box-trim: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_text_box_edge(node_data, node_id, node_state) {
            let _ = write!(s, "text-box-edge: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_dominant_baseline(node_data, node_id, node_state) {
            let _ = write!(s, "dominant-baseline: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_alignment_baseline(node_data, node_id, node_state) {
            let _ = write!(s, "alignment-baseline: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_baseline_source(node_data, node_id, node_state) {
            let _ = write!(s, "baseline-source: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_line_fit_edge(node_data, node_id, node_state) {
            let _ = write!(s, "line-fit-edge: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_initial_letter_align(node_data, node_id, node_state) {
            let _ = write!(s, "initial-letter-align: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_initial_letter_wrap(node_data, node_id, node_state) {
            let _ = write!(s, "initial-letter-wrap: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_scrollbar_gutter(node_data, node_id, node_state) {
            let _ = write!(s, "scrollbar-gutter: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_overflow_clip_margin(node_data, node_id, node_state) {
            let _ = write!(s, "overflow-clip-margin: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_clip(node_data, node_id, node_state) {
            let _ = write!(s, "clip: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_white_space(node_data, node_id, node_state) {
            let _ = write!(s, "white-space: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_display(node_data, node_id, node_state) {
334
            let _ = write!(s, "display: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_float(node_data, node_id, node_state) {
            let _ = write!(s, "float: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_box_sizing(node_data, node_id, node_state) {
            let _ = write!(s, "box-sizing: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_width(node_data, node_id, node_state) {
16
            let _ = write!(s, "width: {};", p.get_css_value_fmt());
318
        }
334
        if let Some(p) = self.get_height(node_data, node_id, node_state) {
15
            let _ = write!(s, "height: {};", p.get_css_value_fmt());
319
        }
334
        if let Some(p) = self.get_min_width(node_data, node_id, node_state) {
            let _ = write!(s, "min-width: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_min_height(node_data, node_id, node_state) {
            let _ = write!(s, "min-height: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_max_width(node_data, node_id, node_state) {
            let _ = write!(s, "max-width: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_max_height(node_data, node_id, node_state) {
            let _ = write!(s, "max-height: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_position(node_data, node_id, node_state) {
            let _ = write!(s, "position: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_top(node_data, node_id, node_state) {
            let _ = write!(s, "top: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_bottom(node_data, node_id, node_state) {
            let _ = write!(s, "bottom: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_right(node_data, node_id, node_state) {
            let _ = write!(s, "right: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_left(node_data, node_id, node_state) {
            let _ = write!(s, "left: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_padding_top(node_data, node_id, node_state) {
            let _ = write!(s, "padding-top: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_padding_bottom(node_data, node_id, node_state) {
            let _ = write!(s, "padding-bottom: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_padding_left(node_data, node_id, node_state) {
            let _ = write!(s, "padding-left: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_padding_right(node_data, node_id, node_state) {
            let _ = write!(s, "padding-right: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_margin_top(node_data, node_id, node_state) {
26
            let _ = write!(s, "margin-top: {};", p.get_css_value_fmt());
308
        }
334
        if let Some(p) = self.get_margin_bottom(node_data, node_id, node_state) {
26
            let _ = write!(s, "margin-bottom: {};", p.get_css_value_fmt());
308
        }
334
        if let Some(p) = self.get_margin_left(node_data, node_id, node_state) {
16
            let _ = write!(s, "margin-left: {};", p.get_css_value_fmt());
318
        }
334
        if let Some(p) = self.get_margin_right(node_data, node_id, node_state) {
16
            let _ = write!(s, "margin-right: {};", p.get_css_value_fmt());
318
        }
334
        if let Some(p) = self.get_border_top_width(node_data, node_id, node_state) {
            let _ = write!(s, "border-top-width: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_left_width(node_data, node_id, node_state) {
            let _ = write!(s, "border-left-width: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_right_width(node_data, node_id, node_state) {
            let _ = write!(s, "border-right-width: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_border_bottom_width(node_data, node_id, node_state) {
            let _ = write!(s, "border-bottom-width: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_overflow_x(node_data, node_id, node_state) {
            let _ = write!(s, "overflow-x: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_overflow_y(node_data, node_id, node_state) {
            let _ = write!(s, "overflow-y: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_flex_direction(node_data, node_id, node_state) {
10
            let _ = write!(s, "flex-direction: {};", p.get_css_value_fmt());
324
        }
334
        if let Some(p) = self.get_flex_wrap(node_data, node_id, node_state) {
            let _ = write!(s, "flex-wrap: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_flex_grow(node_data, node_id, node_state) {
            let _ = write!(s, "flex-grow: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_flex_shrink(node_data, node_id, node_state) {
            let _ = write!(s, "flex-shrink: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_justify_content(node_data, node_id, node_state) {
            let _ = write!(s, "justify-content: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_align_items(node_data, node_id, node_state) {
            let _ = write!(s, "align-items: {};", p.get_css_value_fmt());
334
        }
334
        if let Some(p) = self.get_align_content(node_data, node_id, node_state) {
            let _ = write!(s, "align-content: {};", p.get_css_value_fmt());
334
        }
334
        s
334
    }
}
#[repr(C)]
#[derive(Debug, PartialEq, Clone)]
pub struct CssPropertyCachePtr {
    // `ManuallyDrop` so the owned `Box` is freed ONLY by our `Drop` (gated on
    // `run_destructor`), never by drop-glue. The codegen Az wrapper (AzStyledDom)
    // nests an AzCssPropertyCachePtr field whose own `Drop` re-runs
    // `_delete` -> `drop_in_place::<CssPropertyCachePtr>` on the SAME bytes; with a
    // bare `Box` the glue freed it a second time -> double free. Layout is
    // unchanged (one pointer), so the AzCssPropertyCachePtr<->CssPropertyCachePtr
    // FFI transmute stays valid. Matches the GlContextPtr / InstantPtr convention.
    pub ptr: ManuallyDrop<Box<CssPropertyCache>>,
    pub run_destructor: bool,
}
impl CssPropertyCachePtr {
44762
    pub fn new(cache: CssPropertyCache) -> Self {
44762
        Self {
44762
            ptr: ManuallyDrop::new(Box::new(cache)),
44762
            run_destructor: true,
44762
        }
44762
    }
75704
    pub fn downcast_mut(&mut self) -> &mut CssPropertyCache {
75704
        &mut self.ptr
75704
    }
}
impl Drop for CssPropertyCachePtr {
46706
    fn drop(&mut self) {
        // First drop (run_destructor still true) frees the Box and clears the flag in
        // the shared bytes; the codegen's redundant second drop sees false -> no-op.
46706
        if self.run_destructor {
46706
            self.run_destructor = false;
46706
            unsafe {
46706
                ManuallyDrop::drop(&mut self.ptr);
46706
            }
        }
46706
    }
}
/// Generates a mechanical `get_<name>` CSS-property accessor: resolve the property
/// for `(node_data, node_id, node_state)` via `get_property`, then downcast it with
/// the given `as_*` method. Covers the long run of one-line accessors below.
macro_rules! impl_get_prop {
    ($name:ident, $value_ty:ty, $variant:ident, $as_method:ident) => {
11806914
        pub fn $name<'a>(
11806914
            &'a self,
11806914
            node_data: &'a NodeData,
11806914
            node_id: &NodeId,
11806914
            node_state: &StyledNodeState,
11806914
        ) -> Option<&'a $value_ty> {
11806914
            self.get_property(node_data, node_id, node_state, &CssPropertyType::$variant)
11806914
                .and_then(|p| p.$as_method())
11806914
        }
    };
}
impl CssPropertyCache {
    #[must_use]
44886
    pub fn empty(node_count: usize) -> Self {
44886
        Self {
44886
            node_count,
44886
            retained_author_css: Css::default(),
44886
            user_overridden_properties: Vec::new(),
44886
            dynamic_context: None,
44886
            ua_applied: false,
44886
            cascade_epoch: 0,
44886

            
44886
            cascaded_props: FlatVecVec::new(node_count),
44886
            css_props: FlatVecVec::new(node_count),
44886

            
44886
            computed_values: InheritedValues::new(),
44886
            compact_cache: None,
44886
            global_css_props: Vec::new(),
44886
            resolved_font_sizes_px: crate::sync::OnceLock::new(),
44886
        }
44886
    }
    /// Clear the lazily-populated font-size cache. Call after any
    /// mutation that could change resolved font-sizes (restyle,
    /// DOM mutation, `append`, etc.). The next
    /// [`crate::styled_dom::StyledDom::resolved_font_size_px`] call
    /// repopulates via a single bottom-up tree walk.
52015
    pub fn invalidate_resolved_font_sizes(&mut self) {
52015
        self.resolved_font_sizes_px = crate::sync::OnceLock::new();
52015
    }
244
    pub fn append(&mut self, other: &mut Self) {
244
        self.user_overridden_properties
244
            .append(&mut other.user_overridden_properties);
        // The parent's dynamic context wins; a child subtree styled before
        // composition has no window context of its own worth keeping.
244
        if self.dynamic_context.is_none() {
242
            self.dynamic_context = other.dynamic_context.take();
244
        }
        // The merged store carries UA entries as soon as either half did.
244
        self.ua_applied |= other.ua_applied;
244
        self.cascade_epoch = self.cascade_epoch.wrapping_add(1);
244
        self.cascaded_props.extend_from(&mut other.cascaded_props);
244
        self.css_props.extend_from(&mut other.css_props);
244
        self.computed_values.append(&mut other.computed_values);
244
        self.node_count += other.node_count;
        // Indices shifted — invalidate the font-size cache too.
244
        self.resolved_font_sizes_px = crate::sync::OnceLock::new();
        // Invalidate compact cache since node IDs shifted
244
        self.compact_cache = None;
244
    }
3
    pub fn is_horizontal_overflow_visible(
3
        &self,
3
        node_data: &NodeData,
3
        node_id: &NodeId,
3
        node_state: &StyledNodeState,
3
    ) -> bool {
3
        self.get_overflow_x(node_data, node_id, node_state)
3
            .and_then(|p| p.get_property_or_default())
3
            .unwrap_or_default()
3
            .is_overflow_visible()
3
    }
2
    pub fn is_vertical_overflow_visible(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        node_state: &StyledNodeState,
2
    ) -> bool {
2
        self.get_overflow_y(node_data, node_id, node_state)
2
            .and_then(|p| p.get_property_or_default())
2
            .unwrap_or_default()
2
            .is_overflow_visible()
2
    }
2
    pub fn is_horizontal_overflow_hidden(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        node_state: &StyledNodeState,
2
    ) -> bool {
2
        self.get_overflow_x(node_data, node_id, node_state)
2
            .and_then(|p| p.get_property_or_default())
2
            .unwrap_or_default()
2
            .is_overflow_hidden()
2
    }
3
    pub fn is_vertical_overflow_hidden(
3
        &self,
3
        node_data: &NodeData,
3
        node_id: &NodeId,
3
        node_state: &StyledNodeState,
3
    ) -> bool {
3
        self.get_overflow_y(node_data, node_id, node_state)
3
            .and_then(|p| p.get_property_or_default())
3
            .unwrap_or_default()
3
            .is_overflow_hidden()
3
    }
    /// The node's USER OVERRIDE for a property, if any — the runtime layer a
    /// transition writes. Public so the display-list builder's inheritance
    /// walk can consult ancestors (the precomputed inherited tables cannot
    /// see a runtime override on an ancestor).
    #[must_use]
2184217
    pub fn get_user_override(
2184217
        &self,
2184217
        node_id: &NodeId,
2184217
        css_property_type: &CssPropertyType,
2184217
    ) -> Option<&CssProperty> {
2184217
        let v = self.user_overridden_properties.get(node_id.index())?;
140
        v.binary_search_by_key(css_property_type, |(k, _)| *k)
140
            .ok()
140
            .map(|idx| &v[idx].1)
2184217
    }
    /// Does this node DECLARE the property itself (inline style or a matched
    /// stylesheet rule, any pseudo-state)? Inherited values do NOT count —
    /// this is the "inheritance re-roots here" test for the ancestor-override
    /// walk: below a node with its own `color`, an animated ancestor colour
    /// must not leak through.
    #[must_use]
2184267
    pub fn has_own_declaration(
2184267
        &self,
2184267
        node_data: &NodeData,
2184267
        node_id: &NodeId,
2184267
        css_property_type: &CssPropertyType,
2184267
    ) -> bool {
2184267
        if node_data
2184267
            .style
2184267
            .iter_inline_properties()
2184267
            .any(|(p, _)| p.get_type() == *css_property_type)
        {
49488
            return true;
2134779
        }
2134779
        self.css_props
2134779
            .get_slice(node_id.index())
2134779
            .iter()
3537173
            .any(|p| p.prop_type == *css_property_type)
2184267
    }
8821
    pub fn get_text_color_or_default(
8821
        &self,
8821
        node_data: &NodeData,
8821
        node_id: &NodeId,
8821
        node_state: &StyledNodeState,
8821
    ) -> StyleTextColor {
        use azul_css::defaults::DEFAULT_TEXT_COLOR;
8821
        self.get_text_color(node_data, node_id, node_state)
8821
            .and_then(|fs| fs.get_property().copied())
8821
            .unwrap_or_else(|| {
                // On a cascaded DOM the UA root text colour is in every
                // node's resolved style (root: `cascaded_props`; below it:
                // `computed_values`), so reaching this constant means a
                // reader lost the cascade's answer — the theme-blind seed
                // the theme-chain analysis (2026-09-12, R1) traced the
                // black-on-dark family to. Legitimate only for a cache no UA
                // pass has run on.
                debug_assert!(
                    !self.ua_applied,
                    "get_text_color_or_default: node {} has no `color` in its resolved style \
                     although the UA pass ran — the themed root default did not reach it",
                    node_id.index()
                );
                DEFAULT_TEXT_COLOR
            })
8821
    }
    /// Returns the font family of the node, or the default font family if none is set.
38
    pub fn get_font_id_or_default(
38
        &self,
38
        node_data: &NodeData,
38
        node_id: &NodeId,
38
        node_state: &StyledNodeState,
38
    ) -> StyleFontFamilyVec {
        use azul_css::defaults::DEFAULT_FONT_ID;
38
        let default_font_id = vec![StyleFontFamily::System(AzString::from_const_str(
38
            DEFAULT_FONT_ID,
38
        ))]
38
        .into();
38
        let font_family_opt = self.get_font_family(node_data, node_id, node_state);
38
        font_family_opt
38
            .as_ref()
38
            .and_then(|family| Some(family.get_property()?.clone()))
38
            .unwrap_or(default_font_id)
38
    }
3
    pub fn get_font_size_or_default(
3
        &self,
3
        node_data: &NodeData,
3
        node_id: &NodeId,
3
        node_state: &StyledNodeState,
3
    ) -> StyleFontSize {
        use azul_css::defaults::DEFAULT_FONT_SIZE;
3
        self.get_font_size(node_data, node_id, node_state)
3
            .and_then(|fs| fs.get_property().copied())
3
            .unwrap_or(DEFAULT_FONT_SIZE)
3
    }
2
    pub fn has_border(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        node_state: &StyledNodeState,
2
    ) -> bool {
2
        self.get_border_left_width(node_data, node_id, node_state)
2
            .is_some()
1
            || self
1
                .get_border_right_width(node_data, node_id, node_state)
1
                .is_some()
1
            || self
1
                .get_border_top_width(node_data, node_id, node_state)
1
                .is_some()
1
            || self
1
                .get_border_bottom_width(node_data, node_id, node_state)
1
                .is_some()
2
    }
2
    pub fn has_box_shadow(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        node_state: &StyledNodeState,
2
    ) -> bool {
2
        self.get_box_shadow_left(node_data, node_id, node_state)
2
            .is_some()
2
            || self
2
                .get_box_shadow_right(node_data, node_id, node_state)
2
                .is_some()
2
            || self
2
                .get_box_shadow_top(node_data, node_id, node_state)
2
                .is_some()
2
            || self
2
                .get_box_shadow_bottom(node_data, node_id, node_state)
2
                .is_some()
2
    }
11894221
    pub fn get_property<'a>(
11894221
        &'a self,
11894221
        node_data: &'a NodeData,
11894221
        node_id: &NodeId,
11894221
        node_state: &StyledNodeState,
11894221
        css_property_type: &CssPropertyType,
11894221
    ) -> Option<&'a CssProperty> {
        // Thread-local counter of cascade walks, broken down by
        // property type. Drain with `drain_css_prop_counts` (free
        // fn below) when `AZ_PROP_COUNT=1` is set to see which
        // properties dominate the cold layout path.
        //
        // Env check is read ONCE at process start and cached in a
        // `OnceLock<bool>`. Before this, the env check ran per
        // `get_property` call — and the function fires 710k+ times
        // per cold layout on excel.html. `std::env::var_os` takes
        // ~100 ns per call on macOS (env lock + hashmap lookup), so
        // the naive check added ~70 ms of pure noise to every
        // single layout, regardless of whether the env var was set.
        // Using a one-time cached bool removes that overhead.
        //
        // `no_std` builds have no thread-locals / env, so the profiling
        // counter is compiled out entirely.
        #[cfg(feature = "std")]
        {
            static PROP_COUNT_ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
11894221
            let enabled = *PROP_COUNT_ENABLED.get_or_init(crate::profile::cascade_enabled);
11894221
            if enabled {
                // `try_with` (not `with`): the lifted-to-wasm web backend has no
                // real TLS, so `with` would hit `panic_access_error` (the layout
                // path reads CSS props via these getters → would trap). `try_with`
                // returns Err and we skip the profiling-only increment (and its
                // inner Mutex-guarded label table). Desktop behaviour unchanged —
                // when the env var is unset the whole block is gated off anyway.
                let _ = PROP_COUNTS.try_with(|c| {
                    *c.borrow_mut()
                        .entry(Self::css_prop_type_label(css_property_type))
                        .or_insert(0) += 1;
                });
11894221
            }
        }
        // Always use full cascade resolution.
        // Tier 1/2/2b handle layout-hot properties via direct typed getters.
        // This path is only used for paint-time reads (background, shadow, etc.)
11894221
        self.get_property_slow(node_data, node_id, node_state, css_property_type)
11894221
    }
    #[cfg(feature = "std")]
    #[allow(clippy::trivially_copy_pass_by_ref)] // uniform by-ref cascade-API convention (see
                                                 // find_in_stateful)
3
    fn css_prop_type_label(t: &CssPropertyType) -> &'static str {
        // Intern Debug-format labels under a mutex-guarded map so
        // we leak at most one `&'static str` per distinct
        // `CssPropertyType` variant (bounded at ≤ 178 total). Only
        // triggered when `AZ_PROP_COUNT=1`, so zero cost normally.
        use std::sync::{Mutex, OnceLock};
        static TABLE: OnceLock<Mutex<std::collections::HashMap<CssPropertyType, &'static str>>> =
            OnceLock::new();
3
        let m = TABLE.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
3
        let mut g = m.lock().expect("AZ_PROP_COUNT label table poisoned");
3
        if let Some(s) = g.get(t) {
1
            return s;
2
        }
2
        let s: String = std::format!("{t:?}");
2
        let leaked: &'static str = std::boxed::Box::leak(s.into_boxed_str());
2
        g.insert(*t, leaked);
2
        leaked
3
    }
    /// Full cascade resolution for any CSS property type.
    /// Walks all cascade layers: user overrides → inline → stylesheet → cascaded → computed → UA.
    /// Also used by restyle functions that need state-aware lookups.
    #[allow(clippy::trivially_copy_pass_by_ref)] // uniform by-ref cascade-API convention (see find_in_stateful)
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch
                                     // (one branch per input variant)
11896809
    pub(crate) fn get_property_slow<'a>(
11896809
        &'a self,
11896809
        node_data: &'a NodeData,
11896809
        node_id: &NodeId,
11896809
        node_state: &StyledNodeState,
11896809
        css_property_type: &CssPropertyType,
11896809
    ) -> Option<&'a CssProperty> {
        use azul_css::dynamic_selector::{DynamicSelector, PseudoStateType};
        // Helper: do these conditions identify a rule that applies in `state`
        // under the window's dynamic context? Empty conditions = Normal-only.
        // Otherwise EVERY condition must hold: a pseudo-state condition must
        // equal `state`, and every other condition (viewport/@media, theme,
        // OS, container...) is evaluated against the window-provided
        // `dynamic_context`. With no context yet (a StyledDom no window has
        // adopted), non-pseudo conditions do not apply - the exact behaviour
        // they had before contexts were wired through, so creation-time
        // styling is unchanged.
11896809
        let ctx = self.dynamic_context.as_deref();
11896809
        let matches_pseudo_state = |conds: &azul_css::dynamic_selector::DynamicSelectorVec,
                                    state: PseudoStateType|
7733746
         -> bool {
7733746
            let conditions = conds.as_slice();
7733746
            if conditions.is_empty() {
6001100
                state == PseudoStateType::Normal
            } else {
1734254
                conditions.iter().all(|c| match c {
567577
                    DynamicSelector::PseudoState(s) => *s == state,
1166677
                    non_pseudo => ctx.is_some_and(|ctx| non_pseudo.matches(ctx)),
1734254
                })
            }
7733746
        };
        // First test if there is some user-defined override for the property
11896809
        if let Some(v) = self.user_overridden_properties.get(node_id.index()) {
44383
            if let Ok(idx) = v.binary_search_by_key(css_property_type, |(k, _)| *k) {
1488
                return Some(&v[idx].1);
42895
            }
11852426
        }
        // If that fails, see if there is an inline CSS property that matches
        // ::placeholder FIRST. It is a pseudo-ELEMENT: the flag is only ever
        // set for the ONE resolve the engine does to style the prompt it
        // paints inside an empty editable, and for that resolve the
        // pseudo-element's own declarations must outrank every state of the
        // host. Anything `::placeholder` does not declare keeps falling
        // through to the host's normal value below, which is what makes an
        // unstyled prompt inherit the field's font.
11895321
        if node_state.placeholder {
            // PRIORITY 1: inline declarations (`on_placeholder(...)`)
96
            if let Some(p) =
1008
                node_data
1008
                    .style
1008
                    .iter_inline_properties()
6912
                    .fold(None, |acc, (prop, conds)| {
6912
                        if matches_pseudo_state(conds, PseudoStateType::Placeholder)
576
                            && prop.get_type() == *css_property_type
                        {
96
                            Some(prop)
                        } else {
6816
                            acc
                        }
6912
                    })
            {
96
                return Some(p);
912
            }
            // PRIORITY 2: stylesheet rules (`.field::placeholder { ... }`)
912
            if let Some(p) = Self::find_in_stateful(
912
                self.css_props.get_slice(node_id.index()),
912
                PseudoStateType::Placeholder,
912
                css_property_type,
912
            ) {
                return Some(p);
912
            }
            // PRIORITY 3: cascaded / inherited
912
            if let Some(p) = Self::find_in_stateful(
912
                self.cascaded_props.get_slice(node_id.index()),
912
                PseudoStateType::Placeholder,
912
                css_property_type,
912
            ) {
                return Some(p);
912
            }
11894313
        }
        // :focus > :active > :hover > normal (fallback)
11895225
        if node_state.focused {
            // PRIORITY 1: Inline CSS properties (highest priority per CSS spec)
342
            if let Some(p) =
3660
                node_data
3660
                    .style
3660
                    .iter_inline_properties()
4658
                    .fold(None, |acc, (prop, conds)| {
1352
                        if matches_pseudo_state(conds, PseudoStateType::Focus)
342
                            && prop.get_type() == *css_property_type
                        {
                            // LAST matching inline declaration wins (CSS source order),
                            // same as the compact builder's later-overwrites-earlier and
                            // get_property_with_context - a widget's merged_style()
                            // appends overrides and relies on exactly this.
342
                            Some(prop)
                        } else {
1010
                            acc
                        }
1352
                    })
            {
342
                return Some(p);
3318
            }
            // PRIORITY 2: CSS stylesheet properties
3318
            if let Some(p) = Self::find_in_stateful(
3318
                self.css_props.get_slice(node_id.index()),
3318
                PseudoStateType::Focus,
3318
                css_property_type,
3318
            ) {
12
                return Some(p);
3306
            }
            // PRIORITY 3: Cascaded/inherited properties
3306
            if let Some(p) = Self::find_in_stateful(
3306
                self.cascaded_props.get_slice(node_id.index()),
3306
                PseudoStateType::Focus,
3306
                css_property_type,
3306
            ) {
                return Some(p);
3306
            }
11891565
        }
        // `:seat-focus` (9b-ii-a-i-d-iii-a): a non-primary seat's focus, the
        // same three-tier lookup as `:focus`.
11894871
        if node_state.seat_focused {
            // PRIORITY 1: Inline CSS properties (highest priority per CSS spec)
            if let Some(p) =
577
                node_data
577
                    .style
577
                    .iter_inline_properties()
577
                    .fold(None, |acc, (prop, conds)| {
                        if matches_pseudo_state(conds, PseudoStateType::SeatFocus)
                            && prop.get_type() == *css_property_type
                        {
                            // LAST matching inline declaration wins (CSS source order),
                            // same as the compact builder's later-overwrites-earlier and
                            // get_property_with_context - a widget's merged_style()
                            // appends overrides and relies on exactly this.
                            Some(prop)
                        } else {
                            acc
                        }
                    })
            {
                return Some(p);
577
            }
            // PRIORITY 2: CSS stylesheet properties
577
            if let Some(p) = Self::find_in_stateful(
577
                self.css_props.get_slice(node_id.index()),
577
                PseudoStateType::SeatFocus,
577
                css_property_type,
577
            ) {
4
                return Some(p);
573
            }
            // PRIORITY 3: Cascaded/inherited properties
573
            if let Some(p) = Self::find_in_stateful(
573
                self.cascaded_props.get_slice(node_id.index()),
573
                PseudoStateType::SeatFocus,
573
                css_property_type,
573
            ) {
                return Some(p);
573
            }
11894294
        }
11894867
        if node_state.active {
            // PRIORITY 1: Inline CSS properties (highest priority per CSS spec)
95
            if let Some(p) =
95
                node_data
95
                    .style
95
                    .iter_inline_properties()
380
                    .fold(None, |acc, (prop, conds)| {
380
                        if matches_pseudo_state(conds, PseudoStateType::Active)
95
                            && prop.get_type() == *css_property_type
                        {
                            // LAST matching inline declaration wins (CSS source order),
                            // same as the compact builder's later-overwrites-earlier and
                            // get_property_with_context - a widget's merged_style()
                            // appends overrides and relies on exactly this.
95
                            Some(prop)
                        } else {
285
                            acc
                        }
380
                    })
            {
95
                return Some(p);
            }
            // PRIORITY 2: CSS stylesheet properties
            if let Some(p) = Self::find_in_stateful(
                self.css_props.get_slice(node_id.index()),
                PseudoStateType::Active,
                css_property_type,
            ) {
                return Some(p);
            }
            // PRIORITY 3: Cascaded/inherited properties
            if let Some(p) = Self::find_in_stateful(
                self.cascaded_props.get_slice(node_id.index()),
                PseudoStateType::Active,
                css_property_type,
            ) {
                return Some(p);
            }
11894772
        }
        // :dragging pseudo-state (higher priority than :hover)
11894772
        if node_state.dragging {
            if let Some(p) =
                node_data
                    .style
                    .iter_inline_properties()
                    .fold(None, |acc, (prop, conds)| {
                        if matches_pseudo_state(conds, PseudoStateType::Dragging)
                            && prop.get_type() == *css_property_type
                        {
                            // LAST matching inline declaration wins (CSS source order),
                            // same as the compact builder's later-overwrites-earlier and
                            // get_property_with_context - a widget's merged_style()
                            // appends overrides and relies on exactly this.
                            Some(prop)
                        } else {
                            acc
                        }
                    })
            {
                return Some(p);
            }
            if let Some(p) = Self::find_in_stateful(
                self.css_props.get_slice(node_id.index()),
                PseudoStateType::Dragging,
                css_property_type,
            ) {
                return Some(p);
            }
            if let Some(p) = Self::find_in_stateful(
                self.cascaded_props.get_slice(node_id.index()),
                PseudoStateType::Dragging,
                css_property_type,
            ) {
                return Some(p);
            }
11894772
        }
        // :drag-over pseudo-state (higher priority than :hover)
11894772
        if node_state.drag_over {
            if let Some(p) =
                node_data
                    .style
                    .iter_inline_properties()
                    .fold(None, |acc, (prop, conds)| {
                        if matches_pseudo_state(conds, PseudoStateType::DragOver)
                            && prop.get_type() == *css_property_type
                        {
                            // LAST matching inline declaration wins (CSS source order),
                            // same as the compact builder's later-overwrites-earlier and
                            // get_property_with_context - a widget's merged_style()
                            // appends overrides and relies on exactly this.
                            Some(prop)
                        } else {
                            acc
                        }
                    })
            {
                return Some(p);
            }
            if let Some(p) = Self::find_in_stateful(
                self.css_props.get_slice(node_id.index()),
                PseudoStateType::DragOver,
                css_property_type,
            ) {
                return Some(p);
            }
            if let Some(p) = Self::find_in_stateful(
                self.cascaded_props.get_slice(node_id.index()),
                PseudoStateType::DragOver,
                css_property_type,
            ) {
                return Some(p);
            }
11894772
        }
11894772
        if node_state.hover {
            // PRIORITY 1: Inline CSS properties (highest priority per CSS spec)
134
            if let Some(p) =
17968
                node_data
17968
                    .style
17968
                    .iter_inline_properties()
18367
                    .fold(None, |acc, (prop, conds)| {
593
                        if matches_pseudo_state(conds, PseudoStateType::Hover)
134
                            && prop.get_type() == *css_property_type
                        {
                            // LAST matching inline declaration wins (CSS source order),
                            // same as the compact builder's later-overwrites-earlier and
                            // get_property_with_context - a widget's merged_style()
                            // appends overrides and relies on exactly this.
134
                            Some(prop)
                        } else {
459
                            acc
                        }
593
                    })
            {
134
                return Some(p);
17834
            }
            // PRIORITY 2: CSS stylesheet properties
17834
            if let Some(p) = Self::find_in_stateful(
17834
                self.css_props.get_slice(node_id.index()),
17834
                PseudoStateType::Hover,
17834
                css_property_type,
17834
            ) {
12
                return Some(p);
17822
            }
            // PRIORITY 3: Cascaded/inherited properties
17822
            if let Some(p) = Self::find_in_stateful(
17822
                self.cascaded_props.get_slice(node_id.index()),
17822
                PseudoStateType::Hover,
17822
                css_property_type,
17822
            ) {
                return Some(p);
17822
            }
11876804
        }
        // Normal/fallback properties - always apply as base layer
        // PRIORITY 1: Inline CSS properties (highest priority per CSS spec)
140526
        if let Some(p) =
11894626
            node_data
11894626
                .style
11894626
                .iter_inline_properties()
11895348
                .fold(None, |acc, (prop, conds)| {
7724509
                    if matches_pseudo_state(conds, PseudoStateType::Normal)
5997219
                        && prop.get_type() == *css_property_type
                    {
                        // LAST matching inline declaration wins (CSS source order),
                        // same as the compact builder's later-overwrites-earlier and
                        // get_property_with_context - the widget pattern
                        // "display:none + display:flex @media(max-width)" relies on
                        // exactly this ordering.
140575
                        Some(prop)
                    } else {
7583934
                        acc
                    }
7724509
                })
        {
140526
            return Some(p);
11754100
        }
        // PRIORITY 2: CSS stylesheet properties
11754100
        if let Some(p) = Self::find_in_stateful(
11754100
            self.css_props.get_slice(node_id.index()),
11754100
            PseudoStateType::Normal,
11754100
            css_property_type,
11754100
        ) {
325842
            return Some(p);
11428258
        }
        // PRIORITY 2b: Global `*` selector properties (specificity 0,0,0)
        // These are collected once during restyle and apply to all nodes.
        // Lower priority than per-node rules but higher than inheritance/UA.
11428258
        if let Some(p) = self
11428258
            .global_css_props
11428258
            .iter()
18250942
            .find(|p| p.get_type() == *css_property_type)
        {
1
            return Some(p);
11428257
        }
        // PRIORITY 3: Cascaded/inherited properties
11428257
        if let Some(p) = Self::find_in_stateful(
11428257
            self.cascaded_props.get_slice(node_id.index()),
11428257
            PseudoStateType::Normal,
11428257
            css_property_type,
11428257
        ) {
743221
            return Some(p);
10685036
        }
        // Check computed values cache for inherited properties
        // Sorted Vec with binary search
10685036
        if css_property_type.is_inheritable() {
9515029
            if let Some(v) = self
9515029
                .computed_values
9515029
                .get(node_id.index(), *css_property_type)
            {
748476
                return Some(&v.property);
8766553
            }
1170007
        }
        // User-agent stylesheet fallback (lowest precedence): the SAME themed
        // table `apply_ua_css` and the compact builder consume. On a cascaded
        // DOM every answer here is already in `cascaded_props` /
        // `computed_values` above (the root's document-wide defaults
        // included), so this is reached for caches no UA pass has run on and
        // for the properties the cascade prunes back out
        // (`prune_compact_normal_props`).
9936560
        crate::ua_css::get_ua_default(
9936560
            node_data,
9936560
            node_id.index() == 0,
9936560
            *css_property_type,
9936560
            self.dynamic_context.as_deref(),
        )
11896809
    }
    /// Get a CSS property using `DynamicSelectorContext` for evaluation.
    ///
    /// This is the new API that supports @media queries, @container queries,
    /// OS-specific styles, and all pseudo-states via `CssPropertyWithConditions`.
    ///
    /// The evaluation follows "last wins" semantics - properties are evaluated
    /// in reverse order and the first matching property wins.
    #[allow(clippy::trivially_copy_pass_by_ref)] // uniform by-ref cascade-API convention (see
                                                 // find_in_stateful)
2
    pub(crate) fn get_property_with_context<'a>(
2
        &'a self,
2
        node_data: &'a NodeData,
2
        node_id: &NodeId,
2
        context: &DynamicSelectorContext,
2
        css_property_type: &CssPropertyType,
2
    ) -> Option<&'a CssProperty> {
        // First test if there is some user-defined override for the property
2
        if let Some(v) = self.user_overridden_properties.get(node_id.index()) {
            if let Ok(idx) = v.binary_search_by_key(css_property_type, |(k, _)| *k) {
                return Some(&v[idx].1);
            }
2
        }
        // Check inline CSS properties with DynamicSelectorContext evaluation.
        // Iterate in REVERSE order across the flat (prop, conds) view —
        // "last found wins" semantics, replacing the old Focus > Active >
        // Hover > Normal priority chain.
        // "last found wins": scan the flat (prop, conds) view forward and keep the
        // last match (iter_inline_properties is not DoubleEndedIterator, so this
        // replaces an earlier collect-then-rev-find_map).
2
        let mut last_inline = None;
2
        for (prop, conds) in node_data.style.iter_inline_properties() {
2
            let conditions_match = conds.as_slice().iter().all(|c| c.matches(context));
2
            if prop.get_type() == *css_property_type && conditions_match {
1
                last_inline = Some(prop);
1
            }
        }
2
        if let Some(prop) = last_inline {
1
            return Some(prop);
1
        }
        // Fall back to CSS file and cascaded properties
1
        let legacy_state = StyledNodeState::from_pseudo_state_flags(&context.pseudo_state);
1
        if let Some(p) = self.get_property(node_data, node_id, &legacy_state, css_property_type) {
            return Some(p);
1
        }
1
        None
2
    }
    /// Check if any properties with conditions would change between two contexts.
    /// This is used for re-layout detection on viewport/container resize.
5
    pub(crate) fn check_properties_changed(
5
        node_data: &NodeData,
5
        old_context: &DynamicSelectorContext,
5
        new_context: &DynamicSelectorContext,
5
    ) -> bool {
5
        for (_prop, conds) in node_data.style.iter_inline_properties() {
4
            let was_active = conds.as_slice().iter().all(|c| c.matches(old_context));
4
            let is_active = conds.as_slice().iter().all(|c| c.matches(new_context));
4
            if was_active != is_active {
2
                return true;
2
            }
        }
3
        false
5
    }
    /// Check if any layout-affecting properties would change between two contexts.
    /// This is a more targeted check for re-layout detection.
2
    pub(crate) fn check_layout_properties_changed(
2
        node_data: &NodeData,
2
        old_context: &DynamicSelectorContext,
2
        new_context: &DynamicSelectorContext,
2
    ) -> bool {
2
        for (prop, conds) in node_data.style.iter_inline_properties() {
            // Skip non-layout-affecting properties
2
            if !prop.get_type().can_trigger_relayout() {
1
                continue;
1
            }
1
            let was_active = conds.as_slice().iter().all(|c| c.matches(old_context));
1
            let is_active = conds.as_slice().iter().all(|c| c.matches(new_context));
1
            if was_active != is_active {
1
                return true;
            }
        }
1
        false
2
    }
    impl_get_prop!(
        get_background_content,
        StyleBackgroundContentVecValue,
        BackgroundContent,
        as_background_content
    );
    impl_get_prop!(get_hyphens, StyleHyphensValue, Hyphens, as_hyphens);
    impl_get_prop!(
        get_word_break,
        StyleWordBreakValue,
        WordBreak,
        as_word_break
    );
    impl_get_prop!(
        get_overflow_wrap,
        StyleOverflowWrapValue,
        OverflowWrap,
        as_overflow_wrap
    );
    impl_get_prop!(
        get_line_break,
        StyleLineBreakValue,
        LineBreak,
        as_line_break
    );
    impl_get_prop!(
        get_text_align_last,
        StyleTextAlignLastValue,
        TextAlignLast,
        as_text_align_last
    );
    impl_get_prop!(
        get_text_transform,
        StyleTextTransformValue,
        TextTransform,
        as_text_transform
    );
    impl_get_prop!(
        get_object_fit,
        StyleObjectFitValue,
        ObjectFit,
        as_object_fit
    );
    impl_get_prop!(
        get_text_overflow,
        StyleTextOverflowValue,
        TextOverflow,
        as_text_overflow
    );
    impl_get_prop!(
        get_text_orientation,
        StyleTextOrientationValue,
        TextOrientation,
        as_text_orientation
    );
    impl_get_prop!(
        get_object_position,
        StyleObjectPositionValue,
        ObjectPosition,
        as_object_position
    );
    impl_get_prop!(
        get_aspect_ratio,
        StyleAspectRatioValue,
        AspectRatio,
        as_aspect_ratio
    );
    impl_get_prop!(get_direction, StyleDirectionValue, Direction, as_direction);
    impl_get_prop!(
        get_unicode_bidi,
        StyleUnicodeBidiValue,
        UnicodeBidi,
        as_unicode_bidi
    );
    impl_get_prop!(
        get_text_box_trim,
        StyleTextBoxTrimValue,
        TextBoxTrim,
        as_text_box_trim
    );
    impl_get_prop!(
        get_text_box_edge,
        StyleTextBoxEdgeValue,
        TextBoxEdge,
        as_text_box_edge
    );
    impl_get_prop!(
        get_dominant_baseline,
        StyleDominantBaselineValue,
        DominantBaseline,
        as_dominant_baseline
    );
    impl_get_prop!(
        get_alignment_baseline,
        StyleAlignmentBaselineValue,
        AlignmentBaseline,
        as_alignment_baseline
    );
    impl_get_prop!(
        get_baseline_source,
        StyleBaselineSourceValue,
        BaselineSource,
        as_baseline_source
    );
    impl_get_prop!(
        get_line_fit_edge,
        StyleLineFitEdgeValue,
        LineFitEdge,
        as_line_fit_edge
    );
    impl_get_prop!(
        get_initial_letter_align,
        StyleInitialLetterAlignValue,
        InitialLetterAlign,
        as_initial_letter_align
    );
    impl_get_prop!(
        get_initial_letter_wrap,
        StyleInitialLetterWrapValue,
        InitialLetterWrap,
        as_initial_letter_wrap
    );
    impl_get_prop!(
        get_scrollbar_gutter,
        StyleScrollbarGutterValue,
        ScrollbarGutter,
        as_scrollbar_gutter
    );
    impl_get_prop!(
        get_overflow_clip_margin,
        StyleOverflowClipMarginValue,
        OverflowClipMargin,
        as_overflow_clip_margin
    );
    impl_get_prop!(get_clip, StyleClipRectValue, Clip, as_clip);
    impl_get_prop!(
        get_white_space,
        StyleWhiteSpaceValue,
        WhiteSpace,
        as_white_space
    );
    impl_get_prop!(
        get_background_position,
        StyleBackgroundPositionVecValue,
        BackgroundPosition,
        as_background_position
    );
    impl_get_prop!(
        get_background_size,
        StyleBackgroundSizeVecValue,
        BackgroundSize,
        as_background_size
    );
    impl_get_prop!(
        get_background_repeat,
        StyleBackgroundRepeatVecValue,
        BackgroundRepeat,
        as_background_repeat
    );
    impl_get_prop!(get_font_size, StyleFontSizeValue, FontSize, as_font_size);
    impl_get_prop!(
        get_font_family,
        StyleFontFamilyVecValue,
        FontFamily,
        as_font_family
    );
    impl_get_prop!(
        get_font_weight,
        StyleFontWeightValue,
        FontWeight,
        as_font_weight
    );
    impl_get_prop!(
        get_font_style,
        StyleFontStyleValue,
        FontStyle,
        as_font_style
    );
    impl_get_prop!(
        get_text_color,
        StyleTextColorValue,
        TextColor,
        as_text_color
    );
    impl_get_prop!(
        get_text_indent,
        StyleTextIndentValue,
        TextIndent,
        as_text_indent
    );
    impl_get_prop!(
        get_initial_letter,
        StyleInitialLetterValue,
        InitialLetter,
        as_initial_letter
    );
    impl_get_prop!(
        get_line_clamp,
        StyleLineClampValue,
        LineClamp,
        as_line_clamp
    );
    impl_get_prop!(
        get_hanging_punctuation,
        StyleHangingPunctuationValue,
        HangingPunctuation,
        as_hanging_punctuation
    );
    impl_get_prop!(
        get_text_combine_upright,
        StyleTextCombineUprightValue,
        TextCombineUpright,
        as_text_combine_upright
    );
    impl_get_prop!(
        get_exclusion_margin,
        StyleExclusionMarginValue,
        ExclusionMargin,
        as_exclusion_margin
    );
    impl_get_prop!(
        get_hyphenation_language,
        StyleHyphenationLanguageValue,
        HyphenationLanguage,
        as_hyphenation_language
    );
    impl_get_prop!(get_caret_color, CaretColorValue, CaretColor, as_caret_color);
    impl_get_prop!(get_caret_width, CaretWidthValue, CaretWidth, as_caret_width);
    impl_get_prop!(
        get_caret_animation_duration,
        CaretAnimationDurationValue,
        CaretAnimationDuration,
        as_caret_animation_duration
    );
    impl_get_prop!(
        get_selection_background_color,
        SelectionBackgroundColorValue,
        SelectionBackgroundColor,
        as_selection_background_color
    );
    impl_get_prop!(
        get_selection_color,
        SelectionColorValue,
        SelectionColor,
        as_selection_color
    );
    impl_get_prop!(
        get_selection_radius,
        SelectionRadiusValue,
        SelectionRadius,
        as_selection_radius
    );
    impl_get_prop!(
        get_text_justify,
        LayoutTextJustifyValue,
        TextJustify,
        as_text_justify
    );
    impl_get_prop!(get_z_index, LayoutZIndexValue, ZIndex, as_z_index);
    impl_get_prop!(
        get_flex_basis,
        LayoutFlexBasisValue,
        FlexBasis,
        as_flex_basis
    );
    impl_get_prop!(
        get_column_gap,
        LayoutColumnGapValue,
        ColumnGap,
        as_column_gap
    );
    impl_get_prop!(get_row_gap, LayoutRowGapValue, RowGap, as_row_gap);
    impl_get_prop!(
        get_grid_template_columns,
        LayoutGridTemplateColumnsValue,
        GridTemplateColumns,
        as_grid_template_columns
    );
    impl_get_prop!(
        get_grid_template_rows,
        LayoutGridTemplateRowsValue,
        GridTemplateRows,
        as_grid_template_rows
    );
    impl_get_prop!(
        get_grid_auto_columns,
        LayoutGridAutoColumnsValue,
        GridAutoColumns,
        as_grid_auto_columns
    );
    impl_get_prop!(
        get_grid_auto_rows,
        LayoutGridAutoRowsValue,
        GridAutoRows,
        as_grid_auto_rows
    );
    impl_get_prop!(
        get_grid_column,
        LayoutGridColumnValue,
        GridColumn,
        as_grid_column
    );
    impl_get_prop!(get_grid_row, LayoutGridRowValue, GridRow, as_grid_row);
    impl_get_prop!(
        get_grid_auto_flow,
        LayoutGridAutoFlowValue,
        GridAutoFlow,
        as_grid_auto_flow
    );
    impl_get_prop!(
        get_justify_self,
        LayoutJustifySelfValue,
        JustifySelf,
        as_justify_self
    );
    impl_get_prop!(
        get_justify_items,
        LayoutJustifyItemsValue,
        JustifyItems,
        as_justify_items
    );
    impl_get_prop!(get_gap, LayoutGapValue, Gap, as_gap);
    /// Method for getting grid-gap property
    #[allow(clippy::trivially_copy_pass_by_ref)] // uniform by-ref cascade-API convention (see
                                                 // find_in_stateful)
2
    pub(crate) fn get_grid_gap<'a>(
2
        &'a self,
2
        node_data: &'a NodeData,
2
        node_id: &NodeId,
2
        node_state: &StyledNodeState,
2
    ) -> Option<&'a LayoutGapValue> {
2
        self.get_property(node_data, node_id, node_state, &CssPropertyType::GridGap)
2
            .and_then(|p| p.as_grid_gap())
2
    }
    impl_get_prop!(
        get_align_self,
        LayoutAlignSelfValue,
        AlignSelf,
        as_align_self
    );
    impl_get_prop!(get_font, StyleFontValue, Font, as_font);
    impl_get_prop!(
        get_writing_mode,
        LayoutWritingModeValue,
        WritingMode,
        as_writing_mode
    );
    impl_get_prop!(get_clear, LayoutClearValue, Clear, as_clear);
    impl_get_prop!(
        get_shape_outside,
        ShapeOutsideValue,
        ShapeOutside,
        as_shape_outside
    );
    impl_get_prop!(
        get_shape_inside,
        ShapeInsideValue,
        ShapeInside,
        as_shape_inside
    );
    impl_get_prop!(get_clip_path, ClipPathValue, ClipPath, as_clip_path);
    /// Method for getting scrollbar track background
774
    pub fn get_scrollbar_track<'a>(
774
        &'a self,
774
        node_data: &'a NodeData,
774
        node_id: &NodeId,
774
        node_state: &StyledNodeState,
774
    ) -> Option<&'a StyleBackgroundContentValue> {
774
        self.get_property(
774
            node_data,
774
            node_id,
774
            node_state,
774
            &CssPropertyType::ScrollbarTrack,
        )
774
        .and_then(|p| p.as_scrollbar_track())
774
    }
    /// Method for getting scrollbar thumb background
775
    pub fn get_scrollbar_thumb<'a>(
775
        &'a self,
775
        node_data: &'a NodeData,
775
        node_id: &NodeId,
775
        node_state: &StyledNodeState,
775
    ) -> Option<&'a StyleBackgroundContentValue> {
775
        self.get_property(
775
            node_data,
775
            node_id,
775
            node_state,
775
            &CssPropertyType::ScrollbarThumb,
        )
775
        .and_then(|p| p.as_scrollbar_thumb())
775
    }
    /// Method for getting scrollbar button background
774
    pub fn get_scrollbar_button<'a>(
774
        &'a self,
774
        node_data: &'a NodeData,
774
        node_id: &NodeId,
774
        node_state: &StyledNodeState,
774
    ) -> Option<&'a StyleBackgroundContentValue> {
774
        self.get_property(
774
            node_data,
774
            node_id,
774
            node_state,
774
            &CssPropertyType::ScrollbarButton,
        )
774
        .and_then(|p| p.as_scrollbar_button())
774
    }
    /// Method for getting scrollbar corner background
774
    pub fn get_scrollbar_corner<'a>(
774
        &'a self,
774
        node_data: &'a NodeData,
774
        node_id: &NodeId,
774
        node_state: &StyledNodeState,
774
    ) -> Option<&'a StyleBackgroundContentValue> {
774
        self.get_property(
774
            node_data,
774
            node_id,
774
            node_state,
774
            &CssPropertyType::ScrollbarCorner,
        )
774
        .and_then(|p| p.as_scrollbar_corner())
774
    }
    /// Method for getting scrollbar resizer background
1
    pub fn get_scrollbar_resizer<'a>(
1
        &'a self,
1
        node_data: &'a NodeData,
1
        node_id: &NodeId,
1
        node_state: &StyledNodeState,
1
    ) -> Option<&'a StyleBackgroundContentValue> {
1
        self.get_property(
1
            node_data,
1
            node_id,
1
            node_state,
1
            &CssPropertyType::ScrollbarResizer,
        )
1
        .and_then(|p| p.as_scrollbar_resizer())
1
    }
    impl_get_prop!(
        get_scrollbar_width,
        LayoutScrollbarWidthValue,
        ScrollbarWidth,
        as_scrollbar_width
    );
    impl_get_prop!(
        get_overscroll_behavior_x,
        OverscrollBehaviorValue,
        OverscrollBehaviorX,
        as_overscroll_behavior_x
    );
    impl_get_prop!(
        get_overscroll_behavior_y,
        OverscrollBehaviorValue,
        OverscrollBehaviorY,
        as_overscroll_behavior_y
    );
    impl_get_prop!(
        get_scrollbar_color,
        StyleScrollbarColorValue,
        ScrollbarColor,
        as_scrollbar_color
    );
    impl_get_prop!(
        get_scrollbar_visibility,
        ScrollbarVisibilityModeValue,
        ScrollbarVisibility,
        as_scrollbar_visibility
    );
    impl_get_prop!(
        get_scrollbar_fade_delay,
        ScrollbarFadeDelayValue,
        ScrollbarFadeDelay,
        as_scrollbar_fade_delay
    );
    impl_get_prop!(
        get_scrollbar_fade_duration,
        ScrollbarFadeDurationValue,
        ScrollbarFadeDuration,
        as_scrollbar_fade_duration
    );
    impl_get_prop!(
        get_visibility,
        StyleVisibilityValue,
        Visibility,
        as_visibility
    );
    impl_get_prop!(
        get_break_before,
        PageBreakValue,
        BreakBefore,
        as_break_before
    );
    impl_get_prop!(get_break_after, PageBreakValue, BreakAfter, as_break_after);
    impl_get_prop!(
        get_break_inside,
        BreakInsideValue,
        BreakInside,
        as_break_inside
    );
    impl_get_prop!(get_orphans, OrphansValue, Orphans, as_orphans);
    impl_get_prop!(get_widows, WidowsValue, Widows, as_widows);
    impl_get_prop!(
        get_box_decoration_break,
        BoxDecorationBreakValue,
        BoxDecorationBreak,
        as_box_decoration_break
    );
    impl_get_prop!(
        get_column_count,
        ColumnCountValue,
        ColumnCount,
        as_column_count
    );
    impl_get_prop!(
        get_column_width,
        ColumnWidthValue,
        ColumnWidth,
        as_column_width
    );
    impl_get_prop!(get_column_span, ColumnSpanValue, ColumnSpan, as_column_span);
    impl_get_prop!(get_column_fill, ColumnFillValue, ColumnFill, as_column_fill);
    impl_get_prop!(
        get_column_rule_width,
        ColumnRuleWidthValue,
        ColumnRuleWidth,
        as_column_rule_width
    );
    impl_get_prop!(
        get_column_rule_style,
        ColumnRuleStyleValue,
        ColumnRuleStyle,
        as_column_rule_style
    );
    impl_get_prop!(
        get_column_rule_color,
        ColumnRuleColorValue,
        ColumnRuleColor,
        as_column_rule_color
    );
    impl_get_prop!(get_flow_into, FlowIntoValue, FlowInto, as_flow_into);
    impl_get_prop!(get_flow_from, FlowFromValue, FlowFrom, as_flow_from);
    impl_get_prop!(
        get_shape_margin,
        ShapeMarginValue,
        ShapeMargin,
        as_shape_margin
    );
    impl_get_prop!(
        get_shape_image_threshold,
        ShapeImageThresholdValue,
        ShapeImageThreshold,
        as_shape_image_threshold
    );
    impl_get_prop!(get_content, ContentValue, Content, as_content);
    impl_get_prop!(
        get_counter_reset,
        CounterResetValue,
        CounterReset,
        as_counter_reset
    );
    impl_get_prop!(
        get_counter_increment,
        CounterIncrementValue,
        CounterIncrement,
        as_counter_increment
    );
    impl_get_prop!(get_string_set, StringSetValue, StringSet, as_string_set);
    impl_get_prop!(
        get_text_align,
        StyleTextAlignValue,
        TextAlign,
        as_text_align
    );
    impl_get_prop!(
        get_user_select,
        StyleUserSelectValue,
        UserSelect,
        as_user_select
    );
    impl_get_prop!(
        get_text_decoration,
        StyleTextDecorationValue,
        TextDecoration,
        as_text_decoration
    );
    impl_get_prop!(
        get_vertical_align,
        StyleVerticalAlignValue,
        VerticalAlign,
        as_vertical_align
    );
    impl_get_prop!(
        get_line_height,
        StyleLineHeightValue,
        LineHeight,
        as_line_height
    );
    impl_get_prop!(
        get_letter_spacing,
        StyleLetterSpacingValue,
        LetterSpacing,
        as_letter_spacing
    );
    impl_get_prop!(
        get_word_spacing,
        StyleWordSpacingValue,
        WordSpacing,
        as_word_spacing
    );
    impl_get_prop!(get_tab_size, StyleTabSizeValue, TabSize, as_tab_size);
    impl_get_prop!(get_cursor, StyleCursorValue, Cursor, as_cursor);
    impl_get_prop!(
        get_box_shadow_left,
        StyleBoxShadowValue,
        BoxShadowLeft,
        as_box_shadow_left
    );
    impl_get_prop!(
        get_box_shadow_right,
        StyleBoxShadowValue,
        BoxShadowRight,
        as_box_shadow_right
    );
    impl_get_prop!(
        get_box_shadow_top,
        StyleBoxShadowValue,
        BoxShadowTop,
        as_box_shadow_top
    );
    impl_get_prop!(
        get_box_shadow_bottom,
        StyleBoxShadowValue,
        BoxShadowBottom,
        as_box_shadow_bottom
    );
    impl_get_prop!(
        get_border_top_color,
        StyleBorderTopColorValue,
        BorderTopColor,
        as_border_top_color
    );
    impl_get_prop!(
        get_border_left_color,
        StyleBorderLeftColorValue,
        BorderLeftColor,
        as_border_left_color
    );
    impl_get_prop!(
        get_border_right_color,
        StyleBorderRightColorValue,
        BorderRightColor,
        as_border_right_color
    );
    impl_get_prop!(
        get_border_bottom_color,
        StyleBorderBottomColorValue,
        BorderBottomColor,
        as_border_bottom_color
    );
    impl_get_prop!(
        get_border_top_style,
        StyleBorderTopStyleValue,
        BorderTopStyle,
        as_border_top_style
    );
    impl_get_prop!(
        get_border_left_style,
        StyleBorderLeftStyleValue,
        BorderLeftStyle,
        as_border_left_style
    );
    impl_get_prop!(
        get_border_right_style,
        StyleBorderRightStyleValue,
        BorderRightStyle,
        as_border_right_style
    );
    impl_get_prop!(
        get_border_bottom_style,
        StyleBorderBottomStyleValue,
        BorderBottomStyle,
        as_border_bottom_style
    );
    impl_get_prop!(
        get_border_top_left_radius,
        StyleBorderTopLeftRadiusValue,
        BorderTopLeftRadius,
        as_border_top_left_radius
    );
    impl_get_prop!(
        get_border_top_right_radius,
        StyleBorderTopRightRadiusValue,
        BorderTopRightRadius,
        as_border_top_right_radius
    );
    impl_get_prop!(
        get_border_bottom_left_radius,
        StyleBorderBottomLeftRadiusValue,
        BorderBottomLeftRadius,
        as_border_bottom_left_radius
    );
    impl_get_prop!(
        get_border_bottom_right_radius,
        StyleBorderBottomRightRadiusValue,
        BorderBottomRightRadius,
        as_border_bottom_right_radius
    );
    impl_get_prop!(get_opacity, StyleOpacityValue, Opacity, as_opacity);
    impl_get_prop!(
        get_transform,
        StyleTransformVecValue,
        Transform,
        as_transform
    );
    impl_get_prop!(
        get_transform_origin,
        StyleTransformOriginValue,
        TransformOrigin,
        as_transform_origin
    );
    impl_get_prop!(
        get_perspective_origin,
        StylePerspectiveOriginValue,
        PerspectiveOrigin,
        as_perspective_origin
    );
    impl_get_prop!(
        get_backface_visibility,
        StyleBackfaceVisibilityValue,
        BackfaceVisibility,
        as_backface_visibility
    );
    impl_get_prop!(
        get_app_region,
        StyleAppRegionValue,
        AppRegion,
        as_app_region
    );
    impl_get_prop!(
        get_spatial_navigation_action,
        StyleSpatialNavigationActionValue,
        SpatialNavigationAction,
        as_spatial_navigation_action
    );
    impl_get_prop!(
        get_spatial_navigation_contain,
        StyleSpatialNavigationContainValue,
        SpatialNavigationContain,
        as_spatial_navigation_contain
    );
    impl_get_prop!(get_display, LayoutDisplayValue, Display, as_display);
    impl_get_prop!(get_float, LayoutFloatValue, Float, as_float);
    impl_get_prop!(
        get_box_sizing,
        LayoutBoxSizingValue,
        BoxSizing,
        as_box_sizing
    );
    impl_get_prop!(get_width, LayoutWidthValue, Width, as_width);
    impl_get_prop!(get_height, LayoutHeightValue, Height, as_height);
    impl_get_prop!(get_min_width, LayoutMinWidthValue, MinWidth, as_min_width);
    impl_get_prop!(
        get_min_height,
        LayoutMinHeightValue,
        MinHeight,
        as_min_height
    );
    impl_get_prop!(get_max_width, LayoutMaxWidthValue, MaxWidth, as_max_width);
    impl_get_prop!(
        get_max_height,
        LayoutMaxHeightValue,
        MaxHeight,
        as_max_height
    );
    impl_get_prop!(get_position, LayoutPositionValue, Position, as_position);
    impl_get_prop!(get_top, LayoutTopValue, Top, as_top);
    impl_get_prop!(get_bottom, LayoutInsetBottomValue, Bottom, as_bottom);
    impl_get_prop!(get_right, LayoutRightValue, Right, as_right);
    impl_get_prop!(get_left, LayoutLeftValue, Left, as_left);
    impl_get_prop!(
        get_padding_top,
        LayoutPaddingTopValue,
        PaddingTop,
        as_padding_top
    );
    impl_get_prop!(
        get_padding_bottom,
        LayoutPaddingBottomValue,
        PaddingBottom,
        as_padding_bottom
    );
    impl_get_prop!(
        get_padding_left,
        LayoutPaddingLeftValue,
        PaddingLeft,
        as_padding_left
    );
    impl_get_prop!(
        get_padding_right,
        LayoutPaddingRightValue,
        PaddingRight,
        as_padding_right
    );
    impl_get_prop!(
        get_margin_top,
        LayoutMarginTopValue,
        MarginTop,
        as_margin_top
    );
    impl_get_prop!(
        get_margin_bottom,
        LayoutMarginBottomValue,
        MarginBottom,
        as_margin_bottom
    );
    impl_get_prop!(
        get_margin_left,
        LayoutMarginLeftValue,
        MarginLeft,
        as_margin_left
    );
    impl_get_prop!(
        get_margin_right,
        LayoutMarginRightValue,
        MarginRight,
        as_margin_right
    );
    impl_get_prop!(
        get_border_top_width,
        LayoutBorderTopWidthValue,
        BorderTopWidth,
        as_border_top_width
    );
    impl_get_prop!(
        get_border_left_width,
        LayoutBorderLeftWidthValue,
        BorderLeftWidth,
        as_border_left_width
    );
    impl_get_prop!(
        get_border_right_width,
        LayoutBorderRightWidthValue,
        BorderRightWidth,
        as_border_right_width
    );
    impl_get_prop!(
        get_border_bottom_width,
        LayoutBorderBottomWidthValue,
        BorderBottomWidth,
        as_border_bottom_width
    );
    impl_get_prop!(
        get_overflow_x,
        LayoutOverflowValue,
        OverflowX,
        as_overflow_x
    );
    impl_get_prop!(
        get_overflow_y,
        LayoutOverflowValue,
        OverflowY,
        as_overflow_y
    );
    impl_get_prop!(
        get_overflow_block,
        LayoutOverflowValue,
        OverflowBlock,
        as_overflow_block
    );
    impl_get_prop!(
        get_overflow_inline,
        LayoutOverflowValue,
        OverflowInline,
        as_overflow_inline
    );
    impl_get_prop!(
        get_flex_direction,
        LayoutFlexDirectionValue,
        FlexDirection,
        as_flex_direction
    );
    impl_get_prop!(get_flex_wrap, LayoutFlexWrapValue, FlexWrap, as_flex_wrap);
    impl_get_prop!(get_flex_grow, LayoutFlexGrowValue, FlexGrow, as_flex_grow);
    impl_get_prop!(
        get_flex_shrink,
        LayoutFlexShrinkValue,
        FlexShrink,
        as_flex_shrink
    );
    impl_get_prop!(
        get_justify_content,
        LayoutJustifyContentValue,
        JustifyContent,
        as_justify_content
    );
    impl_get_prop!(
        get_align_items,
        LayoutAlignItemsValue,
        AlignItems,
        as_align_items
    );
    impl_get_prop!(
        get_align_content,
        LayoutAlignContentValue,
        AlignContent,
        as_align_content
    );
    impl_get_prop!(
        get_mix_blend_mode,
        StyleMixBlendModeValue,
        MixBlendMode,
        as_mix_blend_mode
    );
    impl_get_prop!(get_filter, StyleFilterVecValue, Filter, as_filter);
    impl_get_prop!(
        get_backdrop_filter,
        StyleFilterVecValue,
        BackdropFilter,
        as_backdrop_filter
    );
    impl_get_prop!(
        get_text_shadow,
        StyleBoxShadowValue,
        TextShadow,
        as_text_shadow
    );
    impl_get_prop!(
        get_list_style_type,
        StyleListStyleTypeValue,
        ListStyleType,
        as_list_style_type
    );
    impl_get_prop!(
        get_list_style_position,
        StyleListStylePositionValue,
        ListStylePosition,
        as_list_style_position
    );
    impl_get_prop!(
        get_table_layout,
        LayoutTableLayoutValue,
        TableLayout,
        as_table_layout
    );
    impl_get_prop!(
        get_border_collapse,
        StyleBorderCollapseValue,
        BorderCollapse,
        as_border_collapse
    );
    impl_get_prop!(
        get_border_spacing,
        LayoutBorderSpacingValue,
        BorderSpacing,
        as_border_spacing
    );
    impl_get_prop!(
        get_caption_side,
        StyleCaptionSideValue,
        CaptionSide,
        as_caption_side
    );
    impl_get_prop!(
        get_empty_cells,
        StyleEmptyCellsValue,
        EmptyCells,
        as_empty_cells
    );
    // Width calculation methods
17
    pub fn calc_width(
17
        &self,
17
        node_data: &NodeData,
17
        node_id: &NodeId,
17
        styled_node_state: &StyledNodeState,
17
        reference_width: f32,
17
    ) -> f32 {
17
        self.get_width(node_data, node_id, styled_node_state)
17
            .and_then(|w| match w.get_property()? {
12
                LayoutWidth::Px(px) => Some(px.to_pixels_internal(
12
                    reference_width,
12
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
12
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
12
                )),
1
                _ => Some(0.0), // min-content/max-content not resolved here
14
            })
17
            .unwrap_or(0.0)
17
    }
3
    pub fn calc_min_width(
3
        &self,
3
        node_data: &NodeData,
3
        node_id: &NodeId,
3
        styled_node_state: &StyledNodeState,
3
        reference_width: f32,
3
    ) -> f32 {
3
        self.get_min_width(node_data, node_id, styled_node_state)
3
            .and_then(|w| {
2
                Some(w.get_property()?.inner.to_pixels_internal(
2
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
2
            })
3
            .unwrap_or(0.0)
3
    }
3
    pub fn calc_max_width(
3
        &self,
3
        node_data: &NodeData,
3
        node_id: &NodeId,
3
        styled_node_state: &StyledNodeState,
3
        reference_width: f32,
3
    ) -> Option<f32> {
3
        self.get_max_width(node_data, node_id, styled_node_state)
3
            .and_then(|w| {
2
                Some(w.get_property()?.inner.to_pixels_internal(
2
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
2
            })
3
    }
    // Height calculation methods
3
    pub fn calc_height(
3
        &self,
3
        node_data: &NodeData,
3
        node_id: &NodeId,
3
        styled_node_state: &StyledNodeState,
3
        reference_height: f32,
3
    ) -> f32 {
3
        self.get_height(node_data, node_id, styled_node_state)
3
            .and_then(|h| match h.get_property()? {
2
                LayoutHeight::Px(px) => Some(px.to_pixels_internal(
2
                    reference_height,
2
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
2
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
2
                )),
                _ => Some(0.0), // min-content/max-content not resolved here
2
            })
3
            .unwrap_or(0.0)
3
    }
1
    pub fn calc_min_height(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_height: f32,
1
    ) -> f32 {
1
        self.get_min_height(node_data, node_id, styled_node_state)
1
            .and_then(|h| {
                Some(h.get_property()?.inner.to_pixels_internal(
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
2
    pub fn calc_max_height(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        styled_node_state: &StyledNodeState,
2
        reference_height: f32,
2
    ) -> Option<f32> {
2
        self.get_max_height(node_data, node_id, styled_node_state)
2
            .and_then(|h| {
                Some(h.get_property()?.inner.to_pixels_internal(
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
2
    }
    // Position calculation methods
2
    pub fn calc_left(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        styled_node_state: &StyledNodeState,
2
        reference_width: f32,
2
    ) -> Option<f32> {
2
        self.get_left(node_data, node_id, styled_node_state)
2
            .and_then(|l| {
1
                Some(l.get_property()?.inner.to_pixels_internal(
1
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
1
            })
2
    }
2
    pub fn calc_right(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        styled_node_state: &StyledNodeState,
2
        reference_width: f32,
2
    ) -> Option<f32> {
2
        self.get_right(node_data, node_id, styled_node_state)
2
            .and_then(|r| {
1
                Some(r.get_property()?.inner.to_pixels_internal(
1
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
1
            })
2
    }
2
    pub fn calc_top(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        styled_node_state: &StyledNodeState,
2
        reference_height: f32,
2
    ) -> Option<f32> {
2
        self.get_top(node_data, node_id, styled_node_state)
2
            .and_then(|t| {
1
                Some(t.get_property()?.inner.to_pixels_internal(
1
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
1
            })
2
    }
2
    pub fn calc_bottom(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        styled_node_state: &StyledNodeState,
2
        reference_height: f32,
2
    ) -> Option<f32> {
2
        self.get_bottom(node_data, node_id, styled_node_state)
2
            .and_then(|b| {
1
                Some(b.get_property()?.inner.to_pixels_internal(
1
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
1
            })
2
    }
    // Border calculation methods
2
    pub fn calc_border_left_width(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        styled_node_state: &StyledNodeState,
2
        reference_width: f32,
2
    ) -> f32 {
2
        self.get_border_left_width(node_data, node_id, styled_node_state)
2
            .and_then(|b| {
1
                Some(b.get_property()?.inner.to_pixels_internal(
1
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
1
            })
2
            .unwrap_or(0.0)
2
    }
1
    pub fn calc_border_right_width(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_width: f32,
1
    ) -> f32 {
1
        self.get_border_right_width(node_data, node_id, styled_node_state)
1
            .and_then(|b| {
                Some(b.get_property()?.inner.to_pixels_internal(
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
1
    pub fn calc_border_top_width(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_height: f32,
1
    ) -> f32 {
1
        self.get_border_top_width(node_data, node_id, styled_node_state)
1
            .and_then(|b| {
                Some(b.get_property()?.inner.to_pixels_internal(
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
1
    pub fn calc_border_bottom_width(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_height: f32,
1
    ) -> f32 {
1
        self.get_border_bottom_width(node_data, node_id, styled_node_state)
1
            .and_then(|b| {
                Some(b.get_property()?.inner.to_pixels_internal(
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
    // Padding calculation methods
4
    pub fn calc_padding_left(
4
        &self,
4
        node_data: &NodeData,
4
        node_id: &NodeId,
4
        styled_node_state: &StyledNodeState,
4
        reference_width: f32,
4
    ) -> f32 {
4
        self.get_padding_left(node_data, node_id, styled_node_state)
4
            .and_then(|p| {
3
                Some(p.get_property()?.inner.to_pixels_internal(
3
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
3
            })
4
            .unwrap_or(0.0)
4
    }
1
    pub fn calc_padding_right(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_width: f32,
1
    ) -> f32 {
1
        self.get_padding_right(node_data, node_id, styled_node_state)
1
            .and_then(|p| {
                Some(p.get_property()?.inner.to_pixels_internal(
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
2
    pub fn calc_padding_top(
2
        &self,
2
        node_data: &NodeData,
2
        node_id: &NodeId,
2
        styled_node_state: &StyledNodeState,
2
        reference_height: f32,
2
    ) -> f32 {
2
        self.get_padding_top(node_data, node_id, styled_node_state)
2
            .and_then(|p| {
                Some(p.get_property()?.inner.to_pixels_internal(
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
2
            .unwrap_or(0.0)
2
    }
1
    pub fn calc_padding_bottom(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_height: f32,
1
    ) -> f32 {
1
        self.get_padding_bottom(node_data, node_id, styled_node_state)
1
            .and_then(|p| {
                Some(p.get_property()?.inner.to_pixels_internal(
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
    // Margin calculation methods
1
    pub fn calc_margin_left(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_width: f32,
1
    ) -> f32 {
1
        self.get_margin_left(node_data, node_id, styled_node_state)
1
            .and_then(|m| {
                Some(m.get_property()?.inner.to_pixels_internal(
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
1
    pub fn calc_margin_right(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_width: f32,
1
    ) -> f32 {
1
        self.get_margin_right(node_data, node_id, styled_node_state)
1
            .and_then(|m| {
                Some(m.get_property()?.inner.to_pixels_internal(
                    reference_width,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
3
    pub fn calc_margin_top(
3
        &self,
3
        node_data: &NodeData,
3
        node_id: &NodeId,
3
        styled_node_state: &StyledNodeState,
3
        reference_height: f32,
3
    ) -> f32 {
3
        self.get_margin_top(node_data, node_id, styled_node_state)
3
            .and_then(|m| {
2
                Some(m.get_property()?.inner.to_pixels_internal(
2
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
2
            })
3
            .unwrap_or(0.0)
3
    }
1
    pub fn calc_margin_bottom(
1
        &self,
1
        node_data: &NodeData,
1
        node_id: &NodeId,
1
        styled_node_state: &StyledNodeState,
1
        reference_height: f32,
1
    ) -> f32 {
1
        self.get_margin_bottom(node_data, node_id, styled_node_state)
1
            .and_then(|m| {
                Some(m.get_property()?.inner.to_pixels_internal(
                    reference_height,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                ))
            })
1
            .unwrap_or(0.0)
1
    }
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch
                                     // (one branch per input variant)
7314425
    fn resolve_property_dependency(
7314425
        target_property: &CssProperty,
7314425
        reference_property: &CssProperty,
7314425
    ) -> Option<CssProperty> {
        // wildcard import: this big property-dispatch match references the full set
        // of layout property types; enumerating them all is unmaintainable.
        #[allow(clippy::wildcard_imports)]
        use azul_css::{
            css::CssPropertyValue,
            props::{
                basic::{font::StyleFontSize, length::SizeMetric, pixel::PixelValue},
                layout::*,
                style::{SelectionRadius, StyleLetterSpacing, StyleWordSpacing},
            },
        };
        // Extract PixelValue from various property types (returns owned value)
8461825
        let get_pixel_value = |prop: &CssProperty| -> Option<PixelValue> {
8461825
            match prop {
1317077
                CssProperty::FontSize(val) => val.get_property().map(|v| v.inner),
72
                CssProperty::LetterSpacing(val) => val.get_property().map(|v| v.inner),
24
                CssProperty::WordSpacing(val) => val.get_property().map(|v| v.inner),
126307
                CssProperty::PaddingLeft(val) => val.get_property().map(|v| v.inner),
124348
                CssProperty::PaddingRight(val) => val.get_property().map(|v| v.inner),
156052
                CssProperty::PaddingTop(val) => val.get_property().map(|v| v.inner),
118804
                CssProperty::PaddingBottom(val) => val.get_property().map(|v| v.inner),
42780
                CssProperty::MarginLeft(val) => val.get_property().map(|v| v.inner),
8544
                CssProperty::MarginRight(val) => val.get_property().map(|v| v.inner),
190245
                CssProperty::MarginTop(val) => val.get_property().map(|v| v.inner),
193543
                CssProperty::MarginBottom(val) => val.get_property().map(|v| v.inner),
13572
                CssProperty::MinWidth(val) => val.get_property().map(|v| v.inner),
3432
                CssProperty::MinHeight(val) => val.get_property().map(|v| v.inner),
                CssProperty::MaxWidth(val) => val.get_property().map(|v| v.inner),
                CssProperty::MaxHeight(val) => val.get_property().map(|v| v.inner),
                CssProperty::SelectionRadius(val) => val.get_property().map(|v| v.inner),
6167025
                _ => None,
            }
8461825
        };
7314425
        let target_pixel_value = get_pixel_value(target_property)?;
1147400
        let reference_pixel_value = get_pixel_value(reference_property)?;
        // Convert reference to absolute pixels first
1147399
        let reference_px = match reference_pixel_value.metric {
1147397
            SizeMetric::Px => reference_pixel_value.number.get(),
1
            SizeMetric::Pt => reference_pixel_value.number.get() * PT_TO_PX,
            SizeMetric::In => reference_pixel_value.number.get() * IN_TO_PX,
            SizeMetric::Cm => reference_pixel_value.number.get() * CM_TO_PX,
            SizeMetric::Mm => reference_pixel_value.number.get() * MM_TO_PX,
            // Reference can't be relative (em/rem/%) or viewport-relative.
            SizeMetric::Em
            | SizeMetric::Rem
            | SizeMetric::Percent
            | SizeMetric::Vw
            | SizeMetric::Vh
            | SizeMetric::Vmin
1
            | SizeMetric::Vmax => return None,
        };
        // Resolve target based on reference
1147398
        let resolved_px = match target_pixel_value.metric {
1106625
            SizeMetric::Px => target_pixel_value.number.get(),
            SizeMetric::Pt => target_pixel_value.number.get() * PT_TO_PX,
            SizeMetric::In => target_pixel_value.number.get() * IN_TO_PX,
            SizeMetric::Cm => target_pixel_value.number.get() * CM_TO_PX,
            SizeMetric::Mm => target_pixel_value.number.get() * MM_TO_PX,
            // em/rem both scale by reference (rem uses reference as root font-size).
40657
            SizeMetric::Em | SizeMetric::Rem => target_pixel_value.number.get() * reference_px,
115
            SizeMetric::Percent => target_pixel_value.number.get() / 100.0 * reference_px,
            // Need viewport context
1
            SizeMetric::Vw | SizeMetric::Vh | SizeMetric::Vmin | SizeMetric::Vmax => return None,
        };
        // Create a new property with the resolved value
1147397
        let resolved_pixel_value = PixelValue::px(resolved_px);
1147397
        match target_property {
169674
            CssProperty::FontSize(_) => Some(CssProperty::FontSize(CssPropertyValue::Exact(
169674
                StyleFontSize {
169674
                    inner: resolved_pixel_value,
169674
                },
169674
            ))),
72
            CssProperty::LetterSpacing(_) => Some(CssProperty::LetterSpacing(
72
                CssPropertyValue::Exact(StyleLetterSpacing {
72
                    inner: resolved_pixel_value,
72
                }),
72
            )),
24
            CssProperty::WordSpacing(_) => Some(CssProperty::WordSpacing(CssPropertyValue::Exact(
24
                StyleWordSpacing {
24
                    inner: resolved_pixel_value,
24
                },
24
            ))),
126307
            CssProperty::PaddingLeft(_) => Some(CssProperty::PaddingLeft(CssPropertyValue::Exact(
126307
                LayoutPaddingLeft {
126307
                    inner: resolved_pixel_value,
126307
                },
126307
            ))),
124348
            CssProperty::PaddingRight(_) => Some(CssProperty::PaddingRight(
124348
                CssPropertyValue::Exact(LayoutPaddingRight {
124348
                    inner: resolved_pixel_value,
124348
                }),
124348
            )),
156052
            CssProperty::PaddingTop(_) => Some(CssProperty::PaddingTop(CssPropertyValue::Exact(
156052
                LayoutPaddingTop {
156052
                    inner: resolved_pixel_value,
156052
                },
156052
            ))),
118804
            CssProperty::PaddingBottom(_) => Some(CssProperty::PaddingBottom(
118804
                CssPropertyValue::Exact(LayoutPaddingBottom {
118804
                    inner: resolved_pixel_value,
118804
                }),
118804
            )),
42780
            CssProperty::MarginLeft(_) => Some(CssProperty::MarginLeft(CssPropertyValue::Exact(
42780
                LayoutMarginLeft {
42780
                    inner: resolved_pixel_value,
42780
                },
42780
            ))),
8544
            CssProperty::MarginRight(_) => Some(CssProperty::MarginRight(CssPropertyValue::Exact(
8544
                LayoutMarginRight {
8544
                    inner: resolved_pixel_value,
8544
                },
8544
            ))),
190245
            CssProperty::MarginTop(_) => Some(CssProperty::MarginTop(CssPropertyValue::Exact(
190245
                LayoutMarginTop {
190245
                    inner: resolved_pixel_value,
190245
                },
190245
            ))),
193543
            CssProperty::MarginBottom(_) => Some(CssProperty::MarginBottom(
193543
                CssPropertyValue::Exact(LayoutMarginBottom {
193543
                    inner: resolved_pixel_value,
193543
                }),
193543
            )),
13572
            CssProperty::MinWidth(_) => Some(CssProperty::MinWidth(CssPropertyValue::Exact(
13572
                LayoutMinWidth {
13572
                    inner: resolved_pixel_value,
13572
                },
13572
            ))),
3432
            CssProperty::MinHeight(_) => Some(CssProperty::MinHeight(CssPropertyValue::Exact(
3432
                LayoutMinHeight {
3432
                    inner: resolved_pixel_value,
3432
                },
3432
            ))),
            CssProperty::MaxWidth(_) => Some(CssProperty::MaxWidth(CssPropertyValue::Exact(
                LayoutMaxWidth {
                    inner: resolved_pixel_value,
                },
            ))),
            CssProperty::MaxHeight(_) => Some(CssProperty::MaxHeight(CssPropertyValue::Exact(
                LayoutMaxHeight {
                    inner: resolved_pixel_value,
                },
            ))),
            CssProperty::SelectionRadius(_) => Some(CssProperty::SelectionRadius(
                CssPropertyValue::Exact(SelectionRadius {
                    inner: resolved_pixel_value,
                }),
            )),
            _ => None,
        }
7314425
    }
    /// Applies user-agent (UA) CSS properties to the cascade before inheritance.
    ///
    /// UA CSS has the lowest priority in the cascade, so it should only be applied
    /// if the node doesn't already have the property from inline styles or author CSS.
    ///
    /// This is critical for text nodes: UA CSS properties (like font-weight: bold for H1)
    /// must be in the cascade maps so they can be inherited by child text nodes.
    ///
    /// Uses a bitset per node to avoid O(n²) scanning of property vecs.
    ///
    /// Idempotent under a context change: the defaults are answered from
    /// [`Self::dynamic_context`] (the theme picks the `<hr>` rule, the native
    /// button border, the root text colour), and a second call — a theme
    /// flip on a retained DOM — first removes the entries the previous call
    /// pushed (`StatefulCssProperty::ua_origin`) and answers them again.
    /// Leaves `cascaded_props` sorted and flattened.
50294
    pub fn apply_ua_css(&mut self, node_data: &[NodeData]) {
        use azul_css::dynamic_selector::PseudoStateType;
50294
        let node_count = node_data.len();
50294
        if node_count == 0 {
73
            return;
50221
        }
50221
        self.strip_ua_entries();
        // `push_to` needs the build phase; a cache that has been through the
        // compact build (or a prune) is flattened.
50221
        self.cascaded_props.ensure_build_phase();
50221
        let prop_set = self.normal_props_present(node_data);
50221
        let ctx = self.dynamic_context.as_deref();
        // Apply UA CSS: only insert for property types not yet set (bitset
        // check = O(1)). The ONE list both cascade passes walk (the compact
        // builder reads the same const): a UA property present in one pass
        // but not the other made the two readers disagree about a node's
        // computed value. The document root additionally carries the
        // document-wide defaults (the inherited text colour) — themed, and
        // IN the cascade from here on, so `computed_values` inherits it down
        // to every text node and no paint-time reader has to guess it.
1237219
        for (node_index, node) in node_data.iter().enumerate() {
1237219
            let is_root = node_index == 0;
1237219
            let present = &prop_set[node_index];
72995921
            for prop_type in crate::ua_css::UA_PROPERTY_TYPES {
71758702
                if prop_type_bit_test(present, *prop_type) {
6569576
                    continue;
65189126
                }
1447478
                let Some(ua_prop) =
65189126
                    crate::ua_css::get_ua_default(node, is_root, *prop_type, ctx)
                else {
63741648
                    continue;
                };
                // No bitset write needed: `UA_PROPERTY_TYPES` has no
                // duplicates (pinned by `one_themed_ua_table` tests), so one
                // node sees each type once.
1447478
                self.cascaded_props.push_to(
1447478
                    node_index,
1447478
                    StatefulCssProperty {
1447478
                        state: PseudoStateType::Normal,
1447478
                        prop_type: *prop_type,
1447478
                        property: ua_prop.clone(),
1447478
                        ua_origin: true,
1447478
                    },
                );
            }
        }
        // Back to the read phase the rest of the pipeline expects
        // (`append` merges two flattened stores; a build-phase half would
        // drop the other's data). Sorted, so the slow path's binary search
        // over `cascaded_props` stays valid after a re-application too.
50221
        self.sort_cascaded_props();
50221
        self.ua_applied = true;
50221
        self.cascade_epoch = self.cascade_epoch.wrapping_add(1);
50294
    }
    /// RE-APPLICATION of the UA pass: strip what the previous pass pushed
    /// before answering again.
    ///
    /// The UA defaults depend on the context's theme, and the presence
    /// bitset treats an existing entry of a type as "already set" — so
    /// without this a theme flip found the stale light entry, skipped the
    /// dark twin, and `cascaded_props` never moved (the non-idempotence the
    /// theme-chain analysis of 2026-09-12 traces the whole black-text-on-dark
    /// family back to). Only `ua_origin` entries go; everything the author
    /// cascade and the inheritance walk produced stays, exactly as it was
    /// when the first pass ran after them. A no-op before the first pass.
50221
    fn strip_ua_entries(&mut self) {
50221
        if !self.ua_applied {
41891
            return;
8330
        }
8330
        if self.cascaded_props.is_flattened() {
346955
            self.cascaded_props.retain(|p| !p.ua_origin);
        } else {
            for v in self.cascaded_props.build_iter_mut() {
                v.retain(|p| !p.ua_origin);
            }
        }
50221
    }
    /// Per node, which property types already have a Normal-state value from
    /// a layer that beats the UA sheet: author css (`css_props`), the cascade
    /// (`cascaded_props`, i.e. inherited values), unconditional inline
    /// declarations, and the global `*` bucket.
    ///
    /// A `* { margin: 0 }` reset is author CSS and must beat UA defaults on
    /// every ELEMENT (origin beats specificity), but it is stored once
    /// globally rather than per node, so a per-node scan alone never saw it -
    /// the UA body margin (8px) survived the classic reset and every page
    /// using it rendered shifted against the browser reference. Text nodes
    /// are exempt: `*` matches elements only (the compact builder makes the
    /// same distinction), and UA defaults for text nodes must stay.
50221
    fn normal_props_present(&self, node_data: &[NodeData]) -> Vec<PropTypeBits> {
        use azul_css::dynamic_selector::PseudoStateType;
50221
        let mut prop_set: Vec<PropTypeBits> = vec![[0u128; 2]; node_data.len()];
1237219
        for (node_idx, props) in self.css_props.iter_node_slices() {
1240974
            for p in props.iter().filter(|p| p.state == PseudoStateType::Normal) {
1036612
                prop_type_bit_set(&mut prop_set[node_idx], p.prop_type);
1036612
            }
        }
1237219
        for (node_idx, props) in self.cascaded_props.iter_node_slices() {
1756675
            for p in props.iter().filter(|p| p.state == PseudoStateType::Normal) {
1701403
                prop_type_bit_set(&mut prop_set[node_idx], p.prop_type);
1701403
            }
        }
1237219
        for (node_idx, node) in node_data.iter().enumerate() {
6732115
            for (prop, conds) in node.style.iter_inline_properties() {
6723497
                if conds.as_slice().is_empty() {
5540274
                    prop_type_bit_set(&mut prop_set[node_idx], prop.get_type());
5541110
                }
            }
        }
50221
        if !self.global_css_props.is_empty() {
6129
            let mut global_bits: PropTypeBits = [0u128; 2];
54529
            for p in &self.global_css_props {
48400
                prop_type_bit_set(&mut global_bits, p.get_type());
48400
            }
46532
            for (node_idx, node) in node_data.iter().enumerate() {
46532
                if !node.is_text_node() {
28201
                    prop_set[node_idx][0] |= global_bits[0];
28201
                    prop_set[node_idx][1] |= global_bits[1];
28201
                }
            }
44092
        }
50221
        prop_set
50221
    }
    /// Sort `cascaded_props` by (state, `prop_type`) and flatten into contiguous memory.
    /// Must be called after `apply_ua_css()` which adds entries to `cascaded_props`.
50222
    pub fn sort_cascaded_props(&mut self) {
50222
        self.cascaded_props
10368812
            .sort_each_and_flatten(|p| (p.state, p.prop_type));
50222
    }
    /// Compute inherited values for all nodes in the DOM tree.
    ///
    /// Implements CSS inheritance: walk tree depth-first, apply cascade priority
    /// (inherited → cascaded → css → inline → user), create dependency chains for
    /// relative values. Call `apply_ua_css()` before this function.
51037
    pub fn compute_inherited_values(
51037
        &mut self,
51037
        node_hierarchy: &[NodeHierarchyItem],
51037
        node_data: &[NodeData],
51037
    ) -> Vec<NodeId> {
51037
        self.computed_values.grow_to(node_hierarchy.len());
        // The cascade rewrites every node, and the transposed store appends to
        // per-value node lists — so it starts empty or the previous pass's
        // nodes would still be listed. Change detection compares against the
        // snapshot taken below, not against the live store.
51037
        let previous = core::mem::replace(&mut self.computed_values, InheritedValues::new());
51037
        self.computed_values.grow_to(node_hierarchy.len());
51037
        node_hierarchy
51037
            .iter()
51037
            .enumerate()
1239676
            .filter_map(|(node_index, hierarchy_item)| {
1239676
                let node_id = NodeId::new(node_index);
1239676
                let parent_id = hierarchy_item.parent_id();
                // Materialised from the transposed store (a handful of bucket
                // probes) instead of DEEP-CLONING the parent's vec of 136-byte
                // enums once per node, which is what the per-node shape forced.
1239676
                let parent_computed: Option<Vec<(CssPropertyType, CssPropertyWithOrigin)>> =
1239676
                    parent_id.map(|pid| self.computed_values.values_for(pid.index()));
1239676
                let mut ctx = InheritanceContext {
1239676
                    node_id,
1239676
                    parent_id,
1239676
                    computed_values: Vec::new(),
1239676
                };
                // Step 1: Inherit from parent
1239676
                if let Some(ref parent_values) = parent_computed {
1188712
                    Self::inherit_from_parent(&mut ctx, parent_values);
1188712
                }
                // Steps 2-5: Apply cascade in priority order
1239676
                self.apply_cascade_properties(
1239676
                    &mut ctx,
1239676
                    node_id,
1239676
                    parent_computed.as_ref(),
1239676
                    node_data,
1239676
                    node_index,
                );
                // Check for changes and store
1239676
                let changed = self.store_if_changed(&ctx, &previous);
1239676
                changed.then_some(node_id)
1239676
            })
51037
            .collect()
51037
    }
    /// Inherit inheritable properties from parent node
1188712
    fn inherit_from_parent(
1188712
        ctx: &mut InheritanceContext,
1188712
        parent_values: &[(CssPropertyType, CssPropertyWithOrigin)],
1188712
    ) {
3843755
        for (prop_type, prop_with_origin) in
3843755
            parent_values.iter().filter(|(pt, _)| pt.is_inheritable())
        {
3843755
            let entry = (
3843755
                *prop_type,
3843755
                CssPropertyWithOrigin {
3843755
                    property: prop_with_origin.property.clone(),
3843755
                    origin: CssPropertyOrigin::Inherited,
3843755
                },
3843755
            );
            // Insert into sorted vec
3843755
            match ctx
3843755
                .computed_values
3843755
                .binary_search_by_key(prop_type, |(k, _)| *k)
            {
                Ok(idx) => ctx.computed_values[idx] = entry,
3843755
                Err(idx) => ctx.computed_values.insert(idx, entry),
            }
        }
1188712
    }
    /// Apply all cascade properties in priority order
1239676
    fn apply_cascade_properties(
1239676
        &self,
1239676
        ctx: &mut InheritanceContext,
1239676
        node_id: NodeId,
1239676
        parent_computed: Option<&Vec<(CssPropertyType, CssPropertyWithOrigin)>>,
1239676
        node_data: &[NodeData],
1239676
        node_index: usize,
1239676
    ) {
        // Step 2: Cascaded properties (UA CSS)
        {
1239676
            let cascaded_slice = self.cascaded_props.get_slice(node_id.index());
4434750
            for p in cascaded_slice {
3195074
                if p.state == azul_css::dynamic_selector::PseudoStateType::Normal
3151082
                    && Self::should_apply_cascaded(&ctx.computed_values, p.prop_type, &p.property)
3151082
                {
3151082
                    Self::process_property(ctx, &p.property, parent_computed);
3151082
                }
            }
        }
        // Step 3: CSS properties (stylesheets)
        {
1239676
            let css_slice = self.css_props.get_slice(node_id.index());
2277544
            for p in css_slice {
1037868
                if p.state == azul_css::dynamic_selector::PseudoStateType::Normal {
1036707
                    Self::process_property(ctx, &p.property, parent_computed);
1036707
                }
            }
        }
        // Step 4: Inline CSS properties.
        //
        // Conditional declarations take part in inheritance exactly when they
        // apply to the node's RESTING style under the window's context — the
        // same test `get_property` makes for the node's own value, minus every
        // pseudo-state (hover/focus/active are runtime overlays, never an
        // inherited default). Skipping every conditional declaration, as this
        // did, made a container's `dark_theme(color: ..)` twin invisible to
        // its children: the label under a dark-mode button inherited the light
        // value and painted dark-on-dark. Source order, last match wins, like
        // the node's own resolution.
1239676
        let dyn_ctx = self.dynamic_context.as_deref();
6734572
        for (prop, conds) in node_data[node_index].style.iter_inline_properties() {
6724470
            let applies = conds.as_slice().iter().all(|c| match c {
403181
                azul_css::dynamic_selector::DynamicSelector::PseudoState(s) => {
403181
                    *s == azul_css::dynamic_selector::PseudoStateType::Normal
                }
780318
                other => dyn_ctx.is_some_and(|ctx| other.matches(ctx)),
1183499
            });
6724470
            if applies {
5541813
                Self::process_property(ctx, prop, parent_computed);
5541813
            }
        }
        // Step 5: User-overridden properties
1239676
        if let Some(user_props) = self.user_overridden_properties.get(node_id.index()) {
55
            for (_, prop) in user_props {
5
                Self::process_property(ctx, prop, parent_computed);
5
            }
1239626
        }
1239676
    }
    /// Check if a cascaded property should be applied.
    ///
    /// A cascaded (UA / author-selector) value applies unless the node has
    /// already set its OWN value (`origin == Own`), which wins per the cascade.
    /// An `Inherited` placeholder must NOT block it — including a relative
    /// `font-size`: an earlier version skipped a cascaded relative font-size when
    /// an inherited value existed, which silently dropped `<h1>`'s UA
    /// `font-size: 2em` (and every heading), leaving headings at their parent's
    /// size. That was wrong: `resolve_font_size_property` resolves the `em`
    /// against the *parent's* font-size, not the inherited value, so there is no
    /// double-scaling — the cascaded relative size must apply and overwrite the
    /// inherited entry.
3151087
    fn should_apply_cascaded(
3151087
        computed: &[(CssPropertyType, CssPropertyWithOrigin)],
3151087
        prop_type: CssPropertyType,
3151087
        _prop: &CssProperty,
3151087
    ) -> bool {
3151087
        computed
3151087
            .binary_search_by_key(&prop_type, |(k, _)| *k)
3151087
            .map_or(true, |idx| {
1740131
                computed[idx].1.origin == CssPropertyOrigin::Inherited
1740131
            })
3151087
    }
    /// Process a single property: resolve and store
9729607
    fn process_property(
9729607
        ctx: &mut InheritanceContext,
9729607
        prop: &CssProperty,
9729607
        parent_computed: Option<&Vec<(CssPropertyType, CssPropertyWithOrigin)>>,
9729607
    ) {
9729607
        let prop_type = prop.get_type();
9729607
        let resolved = if prop_type == CssPropertyType::FontSize {
302356
            Self::resolve_font_size_property(prop, parent_computed)
        } else {
9427251
            Self::resolve_other_property(prop, &ctx.computed_values)
        };
9729607
        let entry = (
9729607
            prop_type,
9729607
            CssPropertyWithOrigin {
9729607
                property: resolved,
9729607
                origin: CssPropertyOrigin::Own,
9729607
            },
9729607
        );
9729607
        match ctx
9729607
            .computed_values
9729607
            .binary_search_by_key(&prop_type, |(k, _)| *k)
        {
2293534
            Ok(idx) => ctx.computed_values[idx] = entry,
7436073
            Err(idx) => ctx.computed_values.insert(idx, entry),
        }
9729607
    }
    /// Resolve font-size property (uses parent's font-size as reference)
302356
    fn resolve_font_size_property(
302356
        prop: &CssProperty,
302356
        parent_computed: Option<&Vec<(CssPropertyType, CssPropertyWithOrigin)>>,
302356
    ) -> CssProperty {
302356
        let parent_font_size = parent_computed.and_then(|p| {
292938
            p.binary_search_by_key(&CssPropertyType::FontSize, |(k, _)| *k)
292938
                .ok()
292938
                .map(|idx| &p[idx].1)
292938
        });
302356
        parent_font_size.map_or_else(
132685
            || {
132685
                Self::resolve_font_size_to_pixels(
132685
                    prop,
                    azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                )
132685
            },
169671
            |pfs| {
169671
                Self::resolve_property_dependency(prop, &pfs.property).unwrap_or_else(|| {
                    Self::resolve_font_size_to_pixels(
                        prop,
                        azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                    )
                })
169671
            },
        )
302356
    }
    /// Resolve other properties (uses current node's font-size as reference)
9427251
    fn resolve_other_property(
9427251
        prop: &CssProperty,
9427251
        computed: &[(CssPropertyType, CssPropertyWithOrigin)],
9427251
    ) -> CssProperty {
9427251
        computed
9427251
            .binary_search_by_key(&CssPropertyType::FontSize, |(k, _)| *k)
9427251
            .ok()
9427251
            .and_then(|idx| Self::resolve_property_dependency(prop, &computed[idx].1.property))
9427251
            .unwrap_or_else(|| prop.clone())
9427251
    }
    /// Convert font-size to absolute pixels
132697
    fn resolve_font_size_to_pixels(prop: &CssProperty, reference_px: f32) -> CssProperty {
        use azul_css::{
            css::CssPropertyValue,
            props::basic::{font::StyleFontSize, length::SizeMetric, pixel::PixelValue},
        };
132697
        let CssProperty::FontSize(css_val) = prop else {
1
            return prop.clone();
        };
132696
        let Some(font_size) = css_val.get_property() else {
1
            return prop.clone();
        };
132695
        let resolved_px = match font_size.inner.metric {
132450
            SizeMetric::Px => font_size.inner.number.get(),
1
            SizeMetric::Pt => font_size.inner.number.get() * PT_TO_PX,
            SizeMetric::In => font_size.inner.number.get() * IN_TO_PX,
            SizeMetric::Cm => font_size.inner.number.get() * CM_TO_PX,
            SizeMetric::Mm => font_size.inner.number.get() * MM_TO_PX,
229
            SizeMetric::Em => font_size.inner.number.get() * reference_px,
            SizeMetric::Rem => {
1
                font_size.inner.number.get() * azul_css::props::basic::pixel::DEFAULT_FONT_SIZE
            }
1
            SizeMetric::Percent => font_size.inner.number.get() / 100.0 * reference_px,
            SizeMetric::Vw | SizeMetric::Vh | SizeMetric::Vmin | SizeMetric::Vmax => {
13
                return prop.clone();
            }
        };
132682
        CssProperty::FontSize(CssPropertyValue::Exact(StyleFontSize {
132682
            inner: PixelValue::px(resolved_px),
132682
        }))
132697
    }
    /// Check if font-size has relative unit (em, rem, %)
7
    fn has_relative_font_size_unit(prop: &CssProperty) -> bool {
        use azul_css::props::basic::length::SizeMetric;
7
        let CssProperty::FontSize(css_val) = prop else {
1
            return false;
        };
6
        css_val.get_property().is_some_and(|fs| {
2
            matches!(
5
                fs.inner.metric,
                SizeMetric::Em | SizeMetric::Rem | SizeMetric::Percent
            )
5
        })
7
    }
    /// Store computed values if changed, returns true if values were updated
    /// Store the node's resolved values — INHERITABLE ONLY.
    ///
    /// `computed_values` is documented as "pre-resolved INHERITED properties",
    /// and every consumer treats it that way: `get_property_slow` consults it
    /// only when `css_property_type.is_inheritable()`, `inherit_from_parent`
    /// filters to inheritable before handing values down, and
    /// `transient::extract_subtree_as_dom` filters again on the way out
    /// ("non-inheritable entries must not travel"). But the cascade built the
    /// FULL set here and stored it, so 80% of the store was entries no reader
    /// could reach: on the 50k-node XHTML bench, 226 610 of 284 438 entries
    /// were `display` (one per node), `margin-*`, `padding-*` and
    /// `vertical-align` — none of them inheritable, none of them readable
    /// through the `is_inheritable()` gate.
    ///
    /// Filtering here is safe for the cascade because the only parent value the
    /// cascade reads back is `FontSize` (`process_property` →
    /// `resolve_font_size_property`), which is itself inheritable. Non-inherited
    /// properties are still answered by `cascaded_props` / `css_props` / the
    /// compact cache, which is where the layout path reads them from anyway.
1239676
    fn store_if_changed(&mut self, ctx: &InheritanceContext, previous: &InheritedValues) -> bool {
1239676
        let inheritable: Vec<(CssPropertyType, CssPropertyWithOrigin)> = ctx
1239676
            .computed_values
1239676
            .iter()
11279828
            .filter(|(pt, _)| pt.is_inheritable())
1239676
            .cloned()
1239676
            .collect();
1239676
        let changed = previous.values_for(ctx.node_id.index()) != inheritable;
1239676
        self.computed_values
1239676
            .set_node(ctx.node_id.index(), &inheritable);
1239676
        changed
1239676
    }
}
/// Context for computing inherited values for a single node
struct InheritanceContext {
    node_id: NodeId,
    parent_id: Option<NodeId>,
    computed_values: Vec<(CssPropertyType, CssPropertyWithOrigin)>,
}
impl CssPropertyCache {
    /// Clear the entire compact cache. Call after major DOM changes.
1
    pub(crate) fn invalidate_resolved_cache(&mut self) {
1
        self.compact_cache = None;
1
    }
}
#[cfg(test)]
#[path = "prop_cache_test.rs"]
mod prop_cache_test;