1
//! `StyledDom` - the result of applying CSS styles to a DOM tree.
2
//!
3
//! This module contains [`StyledDom`], which is produced by combining a [`Dom`]
4
//! with a [`Css`] stylesheet via [`StyledDom::create`]. It stores the flattened
5
//! node hierarchy, per-node styled states, cascade information, and the CSS
6
//! property cache. Restyle operations (`restyle_nodes_hover`, etc.) allow
7
//! incremental updates when pseudo-class states change at runtime.
8
//!
9
//! `StyledDom` is the primary input to the layout engine.
10

            
11
use alloc::{
12
    boxed::Box,
13
    collections::btree_map::BTreeMap,
14
    string::{String, ToString},
15
    vec::Vec,
16
};
17
use core::{
18
    fmt,
19
    hash::{Hash, Hasher},
20
};
21

            
22
use azul_css::{
23
    css::Css,
24
    props::{
25
        basic::{StyleFontFamily, StyleFontFamilyVec, StyleFontSize},
26
        property::{
27
            BoxDecorationBreakValue, BreakInsideValue, CaretAnimationDurationValue,
28
            CaretColorValue, ColumnCountValue, ColumnFillValue, ColumnRuleColorValue,
29
            ColumnRuleStyleValue, ColumnRuleWidthValue, ColumnSpanValue, ColumnWidthValue,
30
            ContentValue, CounterIncrementValue, CounterResetValue, CssProperty, CssPropertyType,
31
            FlowFromValue, FlowIntoValue, LayoutAlignContentValue, LayoutAlignItemsValue,
32
            LayoutAlignSelfValue, LayoutBorderBottomWidthValue, LayoutBorderLeftWidthValue,
33
            LayoutBorderRightWidthValue, LayoutBorderTopWidthValue, LayoutBoxSizingValue,
34
            LayoutClearValue, LayoutColumnGapValue, LayoutDisplayValue, LayoutFlexBasisValue,
35
            LayoutFlexDirectionValue, LayoutFlexGrowValue, LayoutFlexShrinkValue,
36
            LayoutFlexWrapValue, LayoutFloatValue, LayoutGapValue, LayoutGridAutoColumnsValue,
37
            LayoutGridAutoFlowValue, LayoutGridAutoRowsValue, LayoutGridColumnValue,
38
            LayoutGridRowValue, LayoutGridTemplateColumnsValue, LayoutGridTemplateRowsValue,
39
            LayoutHeightValue, LayoutInsetBottomValue, LayoutJustifyContentValue,
40
            LayoutJustifyItemsValue, LayoutJustifySelfValue, LayoutLeftValue,
41
            LayoutMarginBottomValue, LayoutMarginLeftValue, LayoutMarginRightValue,
42
            LayoutMarginTopValue, LayoutMaxHeightValue, LayoutMaxWidthValue, LayoutMinHeightValue,
43
            LayoutMinWidthValue, LayoutOverflowValue, LayoutPaddingBottomValue,
44
            LayoutPaddingLeftValue, LayoutPaddingRightValue, LayoutPaddingTopValue,
45
            LayoutPositionValue, LayoutRightValue, LayoutRowGapValue, LayoutScrollbarWidthValue,
46
            LayoutTextJustifyValue, LayoutTopValue, LayoutWidthValue, LayoutWritingModeValue,
47
            LayoutZIndexValue, OrphansValue, PageBreakValue, RelayoutScope,
48
            SelectionBackgroundColorValue, SelectionColorValue, ShapeImageThresholdValue,
49
            ShapeMarginValue, ShapeOutsideValue, StringSetValue, StyleBackfaceVisibilityValue,
50
            StyleBackgroundContentVecValue, StyleBackgroundPositionVecValue,
51
            StyleBackgroundRepeatVecValue, StyleBackgroundSizeVecValue,
52
            StyleBorderBottomColorValue, StyleBorderBottomLeftRadiusValue,
53
            StyleBorderBottomRightRadiusValue, StyleBorderBottomStyleValue,
54
            StyleBorderLeftColorValue, StyleBorderLeftStyleValue, StyleBorderRightColorValue,
55
            StyleBorderRightStyleValue, StyleBorderTopColorValue, StyleBorderTopLeftRadiusValue,
56
            StyleBorderTopRightRadiusValue, StyleBorderTopStyleValue, StyleBoxShadowValue,
57
            StyleCursorValue, StyleDirectionValue, StyleFilterVecValue, StyleFontFamilyVecValue,
58
            StyleFontSizeValue, StyleFontValue, StyleHyphensValue, StyleLetterSpacingValue,
59
            StyleLineHeightValue, StyleMixBlendModeValue, StyleOpacityValue,
60
            StylePerspectiveOriginValue, StyleScrollbarColorValue, StyleTabSizeValue,
61
            StyleTextAlignValue, StyleTextColorValue, StyleTransformOriginValue,
62
            StyleTransformVecValue, StyleVisibilityValue, StyleWhiteSpaceValue,
63
            StyleWordSpacingValue, WidowsValue,
64
        },
65
        style::StyleTextColor,
66
    },
67
    AzString,
68
};
69

            
70
use crate::{
71
    callbacks::Update,
72
    dom::{Dom, DomId, NodeData, NodeDataVec, OptionTabIndex, TabIndex, TagId},
73
    events::{RelayoutNodes, RestyleNodes},
74
    id::{
75
        Node, NodeDataContainer, NodeDataContainerRef, NodeDataContainerRefMut, NodeHierarchy,
76
        NodeId,
77
    },
78
    menu::Menu,
79
    prop_cache::{CssPropertyCache, CssPropertyCachePtr},
80
    refany::RefAny,
81
    resources::{Au, ImageCache, ImageRef, ImmediateFontId, RendererResources},
82
    style::{
83
        construct_html_cascade_tree, matches_html_element, rule_ends_with, CascadeInfo,
84
        CascadeInfoVec,
85
    },
86
    FastBTreeSet, OrderedMap,
87
};
88

            
89
#[repr(C)]
90
#[derive(Debug, Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
91
pub struct ChangedCssProperty {
92
    pub previous_state: StyledNodeState,
93
    pub previous_prop: CssProperty,
94
    pub current_state: StyledNodeState,
95
    pub current_prop: CssProperty,
96
}
97

            
98
impl_option!(
99
    ChangedCssProperty,
100
    OptionChangedCssProperty,
101
    copy = false,
102
    [Debug, Clone, PartialEq, Hash, PartialOrd, Eq, Ord]
103
);
104

            
105
impl_vec!(
106
    ChangedCssProperty,
107
    ChangedCssPropertyVec,
108
    ChangedCssPropertyVecDestructor,
109
    ChangedCssPropertyVecDestructorType,
110
    ChangedCssPropertyVecSlice,
111
    OptionChangedCssProperty
112
);
113
impl_vec_debug!(ChangedCssProperty, ChangedCssPropertyVec);
114
impl_vec_partialord!(ChangedCssProperty, ChangedCssPropertyVec);
115
impl_vec_clone!(
116
    ChangedCssProperty,
117
    ChangedCssPropertyVec,
118
    ChangedCssPropertyVecDestructor
119
);
120
impl_vec_partialeq!(ChangedCssProperty, ChangedCssPropertyVec);
121

            
122
/// Focus state change for restyle operations
123
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124
pub struct FocusChange {
125
    /// Node that lost focus (if any)
126
    pub lost_focus: Option<NodeId>,
127
    /// Node that gained focus (if any)
128
    pub gained_focus: Option<NodeId>,
129
}
130

            
131
/// Hover state change for restyle operations
132
#[derive(Debug, Clone, PartialEq, Eq)]
133
pub struct HoverChange {
134
    /// Nodes that the mouse left
135
    pub left_nodes: Vec<NodeId>,
136
    /// Nodes that the mouse entered
137
    pub entered_nodes: Vec<NodeId>,
138
}
139

            
140
/// Active (mouse down) state change for restyle operations
141
#[derive(Debug, Clone, PartialEq, Eq)]
142
pub struct ActiveChange {
143
    /// Nodes that were deactivated (mouse up)
144
    pub deactivated: Vec<NodeId>,
145
    /// Nodes that were activated (mouse down)
146
    pub activated: Vec<NodeId>,
147
}
148

            
149
/// Result of a restyle operation, indicating what needs to be updated
150
#[derive(Debug, Clone, Default)]
151
pub struct RestyleResult {
152
    /// Nodes whose CSS properties changed, with details of the changes
153
    pub changed_nodes: RestyleNodes,
154
    /// Whether layout needs to be recalculated (layout properties changed)
155
    pub needs_layout: bool,
156
    /// Whether display list needs regeneration (visual properties changed)
157
    pub needs_display_list: bool,
158
    /// Whether only GPU-level properties changed (opacity, transform)
159
    /// If true and `needs_display_list` is false, we can update via GPU without display list
160
    /// rebuild
161
    pub gpu_only_changes: bool,
162
    /// The highest `RelayoutScope` seen across all property changes.
163
    ///
164
    /// This enables the IFC incremental layout optimization (Phase 2):
165
    /// - `None`      -> repaint only, zero layout work
166
    /// - `IfcOnly`   -> only the affected IFC needs re-shaping/repositioning
167
    /// - `SizingOnly`-> this node's size changed, parent repositions siblings
168
    /// - `Full`      -> full subtree relayout
169
    ///
170
    /// When `max_relayout_scope <= IfcOnly`, the layout engine can skip
171
    /// full `calculate_layout_for_subtree` and use the IFC fast path instead.
172
    pub max_relayout_scope: RelayoutScope,
173
}
174

            
175
impl RestyleResult {
176
    /// Returns true if any changes occurred
177
    #[must_use]
178
19
    pub fn has_changes(&self) -> bool {
179
19
        !self.changed_nodes.is_empty()
180
19
    }
181

            
182
    /// Merge another `RestyleResult` into this one
183
25
    pub fn merge(&mut self, other: Self) {
184
46
        for (node_id, changes) in other.changed_nodes {
185
21
            self.changed_nodes
186
21
                .entry(node_id)
187
21
                .or_default()
188
21
                .extend(changes);
189
21
        }
190
25
        self.needs_layout = self.needs_layout || other.needs_layout;
191
25
        self.needs_display_list = self.needs_display_list || other.needs_display_list;
192
25
        self.gpu_only_changes = self.gpu_only_changes && other.gpu_only_changes;
193
        // Keep the highest (most expensive) scope
194
25
        if other.max_relayout_scope > self.max_relayout_scope {
195
1
            self.max_relayout_scope = other.max_relayout_scope;
196
24
        }
197
25
    }
198
}
199

            
200
/// NOTE: multiple states can be active at the same time
201
///
202
/// Tracks all CSS pseudo-class states for a node.
203
/// Each flag is independent - a node can be both :hover and :focus simultaneously.
204
#[repr(C)]
205
#[derive(Clone, Copy, PartialEq, Hash, PartialOrd, Eq, Ord, Default)]
206
pub struct StyledNodeState {
207
    /// Element is being hovered (:hover)
208
    pub hover: bool,
209
    /// Element is active/being clicked (:active)
210
    pub active: bool,
211
    /// Element has focus (:focus)
212
    pub focused: bool,
213
    /// Element is disabled (:disabled)
214
    pub disabled: bool,
215
    /// Element is checked/selected (:checked)
216
    pub checked: bool,
217
    /// Element or descendant has focus (:focus-within)
218
    pub focus_within: bool,
219
    /// Link has been visited (:visited)
220
    pub visited: bool,
221
    /// Window is not focused (:backdrop) - GTK compatibility
222
    pub backdrop: bool,
223
    /// Element is currently being dragged (:dragging)
224
    pub dragging: bool,
225
    /// A dragged element is over this drop target (:drag-over)
226
    pub drag_over: bool,
227
    /// The PROMPT of an empty editable is being styled (`::placeholder`).
228
    ///
229
    /// A pseudo-ELEMENT rather than a state of the node: it is never set on
230
    /// a real node during the cascade. The engine turns it on for the single
231
    /// resolve that produces the prompt's own style, so `::placeholder`
232
    /// rules travel the same bucketing/inheritance/lookup path as `:hover`
233
    /// and `:focus` instead of needing storage of their own.
234
    pub placeholder: bool,
235
    /// A NON-primary pointer seat focuses this node (`:seat-focus`,
236
    /// 9b-ii-a-i-d-iii-a). Independent of `focused`, which is the primary's.
237
    pub seat_focused: bool,
238
}
239

            
240
impl fmt::Debug for StyledNodeState {
241
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242
2
        let mut v = Vec::new();
243
2
        if self.hover {
244
1
            v.push("hover");
245
1
        }
246
2
        if self.active {
247
            v.push("active");
248
2
        }
249
2
        if self.focused {
250
            v.push("focused");
251
2
        }
252
2
        if self.disabled {
253
            v.push("disabled");
254
2
        }
255
2
        if self.checked {
256
            v.push("checked");
257
2
        }
258
2
        if self.seat_focused {
259
            v.push("seat_focused");
260
2
        }
261
2
        if self.focus_within {
262
            v.push("focus_within");
263
2
        }
264
2
        if self.visited {
265
            v.push("visited");
266
2
        }
267
2
        if self.backdrop {
268
            v.push("backdrop");
269
2
        }
270
2
        if self.dragging {
271
            v.push("dragging");
272
2
        }
273
2
        if self.drag_over {
274
1
            v.push("drag_over");
275
1
        }
276
2
        if v.is_empty() {
277
1
            v.push("normal");
278
1
        }
279
2
        write!(f, "{v:?}")
280
2
    }
281
}
282

            
283
impl StyledNodeState {
284
    /// Creates a new state with all states set to false (normal state).
285
    #[must_use]
286
41998
    pub const fn new() -> Self {
287
41998
        Self {
288
41998
            hover: false,
289
41998
            active: false,
290
41998
            focused: false,
291
41998
            disabled: false,
292
41998
            checked: false,
293
41998
            focus_within: false,
294
41998
            visited: false,
295
41998
            backdrop: false,
296
41998
            dragging: false,
297
41998
            drag_over: false,
298
41998
            placeholder: false,
299
41998
            seat_focused: false,
300
41998
        }
301
41998
    }
302

            
303
    /// Check if a specific pseudo-state is active
304
    #[must_use]
305
623
    pub const fn has_state(&self, state_type: u8) -> bool {
306
623
        match state_type {
307
3
            0 => true, // Normal is always active
308
12
            1 => self.hover,
309
12
            2 => self.active,
310
12
            3 => self.focused,
311
12
            4 => self.disabled,
312
12
            5 => self.checked,
313
12
            6 => self.focus_within,
314
12
            7 => self.visited,
315
12
            8 => self.backdrop,
316
12
            9 => self.dragging,
317
12
            10 => self.drag_over,
318
12
            11 => self.seat_focused,
319
488
            _ => false,
320
        }
321
623
    }
322

            
323
    /// Returns true if no special state is active (just normal)
324
    #[must_use]
325
64603029
    pub const fn is_normal(&self) -> bool {
326
64603029
        !self.hover
327
64594582
            && !self.active
328
64594580
            && !self.focused
329
64594002
            && !self.disabled
330
64594001
            && !self.checked
331
64594000
            && !self.focus_within
332
64593999
            && !self.visited
333
64593998
            && !self.backdrop
334
64593997
            && !self.dragging
335
64593996
            && !self.drag_over
336
            // The `::placeholder` pseudo-ELEMENT is NOT the normal state:
337
            // leaving it out here sent the prompt's resolve down the
338
            // compact-cache fast path, which is keyed for the normal state,
339
            // so a `::placeholder` rule silently never applied.
340
64593995
            && !self.placeholder
341
64593155
            && !self.seat_focused
342
64603029
    }
343

            
344
    /// Create from `PseudoStateFlags`
345
    #[must_use]
346
5
    pub const fn from_pseudo_state_flags(
347
5
        flags: &azul_css::dynamic_selector::PseudoStateFlags,
348
5
    ) -> Self {
349
5
        Self {
350
5
            hover: flags.hover,
351
5
            active: flags.active,
352
5
            focused: flags.focused,
353
5
            disabled: flags.disabled,
354
5
            checked: flags.checked,
355
5
            focus_within: flags.focus_within,
356
5
            visited: flags.visited,
357
5
            backdrop: flags.backdrop,
358
5
            dragging: flags.dragging,
359
5
            drag_over: flags.drag_over,
360
5
            placeholder: flags.placeholder,
361
5
            seat_focused: flags.seat_focused,
362
5
        }
363
5
    }
364
}
365

            
366
/// A styled Dom node
367
// Per-DOM-node hot type passed by reference throughout the layout/style
368
// pipeline; kept non-Copy on purpose so it isn't silently bulk-copied and to
369
// avoid trivially_copy_pass_by_ref churn across the many &StyledNode callers.
370
#[allow(missing_copy_implementations)]
371
#[repr(C)]
372
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd)]
373
pub struct StyledNode {
374
    /// Current state of this styled node (used later for caching the style / layout)
375
    pub styled_node_state: StyledNodeState,
376
}
377

            
378
impl_option!(
379
    StyledNode,
380
    OptionStyledNode,
381
    copy = false,
382
    [Debug, Clone, PartialEq, Eq, PartialOrd]
383
);
384

            
385
impl_vec!(
386
    StyledNode,
387
    StyledNodeVec,
388
    StyledNodeVecDestructor,
389
    StyledNodeVecDestructorType,
390
    StyledNodeVecSlice,
391
    OptionStyledNode
392
);
393
impl_vec_mut!(StyledNode, StyledNodeVec);
394
impl_vec_debug!(StyledNode, StyledNodeVec);
395
impl_vec_partialord!(StyledNode, StyledNodeVec);
396
impl_vec_clone!(StyledNode, StyledNodeVec, StyledNodeVecDestructor);
397
impl_vec_partialeq!(StyledNode, StyledNodeVec);
398

            
399
impl StyledNodeVec {
400
    /// Returns an immutable container reference for indexed access.
401
    #[must_use]
402
47522212
    pub fn as_container(&self) -> NodeDataContainerRef<'_, StyledNode> {
403
47522212
        NodeDataContainerRef {
404
47522212
            internal: self.as_ref(),
405
47522212
        }
406
47522212
    }
407
    /// Returns a mutable container reference for indexed access.
408
584
    pub fn as_container_mut(&mut self) -> NodeDataContainerRefMut<'_, StyledNode> {
409
584
        NodeDataContainerRefMut {
410
584
            internal: self.as_mut(),
411
584
        }
412
584
    }
413
}
414

            
415
#[test]
416
#[allow(clippy::used_underscore_binding)] // intentional `_`-prefix (FFI/api.json pub field, or
417
                                          // cfg-gated binding); access is deliberate
418
1
fn test_css_styling_with_nested_divs() {
419
1
    let s = "
420
1
        html, body, p {
421
1
            margin: 0;
422
1
            padding: 0;
423
1
        }
424
1
        #div1 {
425
1
            border: solid black;
426
1
            height: 2in;
427
1
            position: absolute;
428
1
            top: 1in;
429
1
            width: 3in;
430
1
        }
431
1
        div div {
432
1
            background: blue;
433
1
            height: 1in;
434
1
            position: fixed;
435
1
            width: 1in;
436
1
        }
437
1
    ";
438

            
439
1
    let css = azul_css::parser2::new_from_str(s);
440
1
    let mut _styled_dom = Dom::create_body().with_children(
441
1
        vec![Dom::create_div()
442
1
            .with_ids_and_classes(vec![crate::dom::IdOrClass::Id("div1".to_string().into())].into())
443
1
            .with_children(vec![Dom::create_div()].into())]
444
1
        .into(),
445
    );
446
1
    _styled_dom.add_component_css(css.0);
447
1
}
448

            
449
/// Regression test for the calc.c "frame ≥2 loses all backgrounds" bug:
450
/// `recompute_inheritance_and_compact_cache()` must reproduce the
451
/// `hot_flags` that `create_from_compact_dom` produced on frame 1. If the
452
/// recompute path silently drops to the getters-only `build_compact_cache`
453
/// variant, `HOT_FLAG_HAS_BACKGROUND` is never written, the renderer's
454
/// `has_any_background()` negative fast-path returns false for every node,
455
/// and every painted background vanishes on the next layout pass.
456
#[test]
457
1
fn test_recompute_preserves_hot_flag_has_background() {
458
    use azul_css::compact_cache::HOT_FLAG_HAS_BACKGROUND;
459

            
460
1
    let css_str = "
461
1
        body { margin: 0; padding: 0; }
462
1
        .painted { background: red; width: 100px; height: 100px; }
463
1
    ";
464
1
    let css = azul_css::parser2::new_from_str(css_str).0;
465

            
466
1
    let mut dom = Dom::create_body()
467
1
        .with_children(vec![Dom::create_div().with_class("painted".to_string().into())].into());
468
1
    let mut styled = StyledDom::create(&mut dom, css);
469

            
470
    // Frame 1: find the painted node by walking its hot_flags.
471
1
    let any_bg_frame1 = {
472
1
        let cache = styled
473
1
            .css_property_cache
474
1
            .ptr
475
1
            .compact_cache
476
1
            .as_ref()
477
1
            .expect("compact_cache populated by create_from_compact_dom");
478
1
        (0..styled.node_hierarchy.as_ref().len())
479
2
            .any(|i| cache.tier2_cold[i].hot_flags & HOT_FLAG_HAS_BACKGROUND != 0)
480
    };
481
1
    assert!(
482
1
        any_bg_frame1,
483
        "frame 1: expected HOT_FLAG_HAS_BACKGROUND on the .painted node",
484
    );
485

            
486
    // Frame 2+: simulate regenerate_layout rebuilding the compact cache.
487
    // This is the path the calculator hit on every resize tick, and the
488
    // one that had silently regressed to the getter-only builder.
489
1
    styled.recompute_inheritance_and_compact_cache();
490

            
491
1
    let any_bg_frame2 = {
492
1
        let cache = styled
493
1
            .css_property_cache
494
1
            .ptr
495
1
            .compact_cache
496
1
            .as_ref()
497
1
            .expect("compact_cache rebuilt by recompute_inheritance_and_compact_cache");
498
1
        (0..styled.node_hierarchy.as_ref().len())
499
2
            .any(|i| cache.tier2_cold[i].hot_flags & HOT_FLAG_HAS_BACKGROUND != 0)
500
    };
501
1
    assert!(
502
1
        any_bg_frame2,
503
        "frame ≥2 after recompute_inheritance_and_compact_cache: HOT_FLAG_HAS_BACKGROUND \
504
         disappeared. The recompute path must use build_compact_cache_with_inheritance (not plain \
505
         build_compact_cache) so apply_css_property_to_compact runs and populates hot_flags for \
506
         the renderer's negative fast-paths.",
507
    );
508
1
}
509

            
510
/// Calculated hash of a font-family
511
#[derive(Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
512
pub struct StyleFontFamilyHash(pub u64);
513

            
514
impl ::core::fmt::Debug for StyleFontFamilyHash {
515
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516
        write!(f, "StyleFontFamilyHash({})", self.0)
517
    }
518
}
519

            
520
impl StyleFontFamilyHash {
521
    /// Computes a 64-bit hash of a font family for cache lookups.
522
    #[must_use]
523
22
    pub fn new(family: &StyleFontFamily) -> Self {
524
        use core::hash::Hasher;
525
22
        let mut hasher = crate::hash::DefaultHasher::new();
526
22
        family.hash(&mut hasher);
527
22
        Self(hasher.finish())
528
22
    }
529
}
530

            
531
/// Calculated hash of a font-family
532
#[derive(Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
533
pub struct StyleFontFamiliesHash(pub u64);
534

            
535
impl ::core::fmt::Debug for StyleFontFamiliesHash {
536
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537
        write!(f, "StyleFontFamiliesHash({})", self.0)
538
    }
539
}
540

            
541
impl StyleFontFamiliesHash {
542
    /// Computes a 64-bit hash of multiple font families for cache lookups.
543
    #[must_use]
544
54
    pub fn new(families: &[StyleFontFamily]) -> Self {
545
        use core::hash::Hasher;
546
54
        let mut hasher = crate::hash::DefaultHasher::new();
547
        // Prefix with the length so that e.g. `[A, B]` and `[AB]` (or any two
548
        // family lists whose concatenated element hashes coincide) cannot
549
        // collide into the same cache key.
550
54
        families.len().hash(&mut hasher);
551
4101
        for f in families {
552
4047
            f.hash(&mut hasher);
553
4047
        }
554
54
        Self(hasher.finish())
555
54
    }
556
}
557

            
558
/// FFI-safe representation of `Option<NodeId>` as a single `usize`.
559
///
560
/// # Encoding (1-based)
561
///
562
/// - `inner = 0` -> `None` (no node)
563
/// - `inner = n > 0` -> `Some(NodeId(n - 1))`
564
///
565
/// This type exists because C/C++ cannot use Rust's `Option` type.
566
/// Use [`NodeHierarchyItemId::into_crate_internal`] to decode and
567
/// [`NodeHierarchyItemId::from_crate_internal`] to encode.
568
///
569
/// # Difference from `NodeId`
570
///
571
/// - **`NodeId`**: A 0-based array index. `NodeId::new(0)` refers to the first node. Use directly
572
///   for array indexing: `nodes[node_id.index()]`.
573
///
574
/// - **`NodeHierarchyItemId`**: A 1-based encoded `Option<NodeId>`. `inner = 0` means `None`,
575
///   `inner = 1` means `Some(NodeId(0))`. **Never use `inner` as an array index!** Always decode
576
///   first.
577
///
578
/// # Warning
579
///
580
/// The `inner` field uses **1-based encoding**, not a direct index!
581
/// Never use `inner` directly as an array index - always decode first.
582
///
583
/// # Example
584
///
585
/// ```ignore
586
/// // Encoding: Option<NodeId> -> NodeHierarchyItemId
587
/// let opt = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(5)));
588
/// assert_eq!(opt.into_raw(), 6);  // 5 + 1 = 6
589
///
590
/// // Decoding: NodeHierarchyItemId -> Option<NodeId>
591
/// let decoded = opt.into_crate_internal();
592
/// assert_eq!(decoded, Some(NodeId::new(5)));
593
///
594
/// // None case
595
/// let none = NodeHierarchyItemId::NONE;
596
/// assert_eq!(none.into_raw(), 0);
597
/// assert_eq!(none.into_crate_internal(), None);
598
/// ```
599
#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
600
#[repr(C)]
601
pub struct NodeHierarchyItemId {
602
    // Uses 1-based encoding: 0 = None, n > 0 = Some(NodeId(n-1))
603
    // Do NOT use directly as an array index!
604
    inner: usize,
605
}
606

            
607
impl fmt::Debug for NodeHierarchyItemId {
608
315
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609
315
        match self.into_crate_internal() {
610
299
            Some(n) => write!(f, "Some(NodeId({n}))"),
611
16
            None => write!(f, "None"),
612
        }
613
315
    }
614
}
615

            
616
impl fmt::Display for NodeHierarchyItemId {
617
4
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618
4
        write!(f, "{self:?}")
619
4
    }
620
}
621

            
622
impl NodeHierarchyItemId {
623
    /// Represents `None` (no node). Encoded as `inner = 0`.
624
    pub const NONE: Self = Self { inner: 0 };
625

            
626
    /// Creates an `NodeHierarchyItemId` from a raw 1-based encoded value.
627
    ///
628
    /// # Warning
629
    ///
630
    /// The value must use 1-based encoding (0 = None, n = NodeId(n-1)).
631
    /// Prefer using [`NodeHierarchyItemId::from_crate_internal`] instead.
632
    #[inline]
633
    #[must_use]
634
2379
    pub const fn from_raw(value: usize) -> Self {
635
2379
        Self { inner: value }
636
2379
    }
637

            
638
    /// Returns the raw 1-based encoded value.
639
    ///
640
    /// # Warning
641
    ///
642
    /// The returned value uses 1-based encoding. Do NOT use as an array index!
643
    #[inline]
644
    #[must_use]
645
19
    pub const fn into_raw(&self) -> usize {
646
19
        self.inner
647
19
    }
648
}
649

            
650
impl_option!(
651
    NodeHierarchyItemId,
652
    OptionNodeHierarchyItemId,
653
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
654
);
655

            
656
impl_vec!(
657
    NodeHierarchyItemId,
658
    NodeHierarchyItemIdVec,
659
    NodeHierarchyItemIdVecDestructor,
660
    NodeHierarchyItemIdVecDestructorType,
661
    NodeHierarchyItemIdVecSlice,
662
    OptionNodeHierarchyItemId
663
);
664
impl_vec_mut!(NodeHierarchyItemId, NodeHierarchyItemIdVec);
665
impl_vec_debug!(NodeHierarchyItemId, NodeHierarchyItemIdVec);
666
impl_vec_ord!(NodeHierarchyItemId, NodeHierarchyItemIdVec);
667
impl_vec_eq!(NodeHierarchyItemId, NodeHierarchyItemIdVec);
668
impl_vec_hash!(NodeHierarchyItemId, NodeHierarchyItemIdVec);
669
impl_vec_partialord!(NodeHierarchyItemId, NodeHierarchyItemIdVec);
670
impl_vec_clone!(
671
    NodeHierarchyItemId,
672
    NodeHierarchyItemIdVec,
673
    NodeHierarchyItemIdVecDestructor
674
);
675
impl_vec_partialeq!(NodeHierarchyItemId, NodeHierarchyItemIdVec);
676

            
677
impl NodeHierarchyItemId {
678
    /// Decodes to `Option<NodeId>` (0 = None, n > 0 = Some(NodeId(n-1))).
679
    #[inline]
680
    #[must_use]
681
102801429
    pub const fn into_crate_internal(&self) -> Option<NodeId> {
682
102801429
        NodeId::from_usize(self.inner)
683
102801429
    }
684

            
685
    /// Encodes from `Option<NodeId>` (None -> 0, Some(NodeId(n)) -> n+1).
686
    #[inline]
687
    #[must_use]
688
1817495
    pub const fn from_crate_internal(t: Option<NodeId>) -> Self {
689
1817495
        Self {
690
1817495
            inner: NodeId::into_raw(&t),
691
1817495
        }
692
1817495
    }
693
}
694

            
695
impl From<Option<NodeId>> for NodeHierarchyItemId {
696
    #[inline]
697
30588
    fn from(opt: Option<NodeId>) -> Self {
698
30588
        Self::from_crate_internal(opt)
699
30588
    }
700
}
701

            
702
impl From<NodeHierarchyItemId> for Option<NodeId> {
703
    #[inline]
704
1
    fn from(id: NodeHierarchyItemId) -> Self {
705
1
        id.into_crate_internal()
706
1
    }
707
}
708

            
709
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
710
#[repr(C)]
711
pub struct NodeHierarchyItem {
712
    pub parent: usize,
713
    pub previous_sibling: usize,
714
    pub next_sibling: usize,
715
    pub last_child: usize,
716
}
717

            
718
impl_option!(
719
    NodeHierarchyItem,
720
    OptionNodeHierarchyItem,
721
    [Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash]
722
);
723

            
724
/// Iterator over a DOM node's ancestor chain - see [`hierarchy_ancestors`].
725
#[derive(Debug)]
726
pub struct HierarchyAncestors<'a> {
727
    hierarchy: &'a [NodeHierarchyItem],
728
    cursor: Option<NodeId>,
729
    budget: usize,
730
}
731

            
732
impl Iterator for HierarchyAncestors<'_> {
733
    type Item = NodeId;
734

            
735
284
    fn next(&mut self) -> Option<Self::Item> {
736
284
        if self.budget == 0 {
737
83
            return None;
738
201
        }
739
201
        let nid = self.cursor?;
740
163
        self.budget -= 1;
741
163
        self.cursor = self
742
163
            .hierarchy
743
163
            .get(nid.index())
744
163
            .and_then(NodeHierarchyItem::parent_id);
745
163
        Some(nid)
746
284
    }
747
}
748

            
749
/// THE ancestor walk over a `NodeHierarchy` - the DOM-tree twin of
750
/// `LayoutTree::ancestor_chain`.
751
///
752
/// Yields `node` (only when `inclusivity` says so) followed by every parent up
753
/// to the root, nearest first. `inclusivity` is an argument rather than a
754
/// property of the function's name because that is exactly the distinction
755
/// `ScrollManager::find_scroll_parent` used to bury in a `nid != node_id`
756
/// guard, where no caller could see it.
757
///
758
/// The walk is bounded by `hierarchy.len()`: no acyclic path can be longer, so
759
/// a corrupt parent chain terminates instead of spinning.
760
#[inline]
761
154
pub fn hierarchy_ancestors(
762
154
    hierarchy: &[NodeHierarchyItem],
763
154
    node: NodeId,
764
154
    inclusivity: crate::spaces::Inclusivity,
765
154
) -> HierarchyAncestors<'_> {
766
154
    let cursor = if inclusivity.includes_self() {
767
72
        Some(node)
768
    } else {
769
82
        hierarchy
770
82
            .get(node.index())
771
82
            .and_then(NodeHierarchyItem::parent_id)
772
    };
773
154
    HierarchyAncestors {
774
154
        hierarchy,
775
154
        cursor,
776
154
        budget: hierarchy.len(),
777
154
    }
778
154
}
779

            
780
impl NodeHierarchyItem {
781
    /// Creates a zeroed hierarchy item (no parent, siblings, or children).
782
    #[must_use]
783
7
    pub const fn zeroed() -> Self {
784
7
        Self {
785
7
            parent: 0,
786
7
            previous_sibling: 0,
787
7
            next_sibling: 0,
788
7
            last_child: 0,
789
7
        }
790
7
    }
791
}
792

            
793
impl From<Node> for NodeHierarchyItem {
794
761074
    fn from(node: Node) -> Self {
795
761074
        Self {
796
761074
            parent: NodeId::into_raw(&node.parent),
797
761074
            previous_sibling: NodeId::into_raw(&node.previous_sibling),
798
761074
            next_sibling: NodeId::into_raw(&node.next_sibling),
799
761074
            last_child: NodeId::into_raw(&node.last_child),
800
761074
        }
801
761074
    }
802
}
803

            
804
impl NodeHierarchyItem {
805
    /// Returns the parent node ID, if any.
806
    #[must_use]
807
34841148
    pub const fn parent_id(&self) -> Option<NodeId> {
808
34841148
        NodeId::from_usize(self.parent)
809
34841148
    }
810
    /// Returns the previous sibling node ID, if any.
811
    #[must_use]
812
3981
    pub const fn previous_sibling_id(&self) -> Option<NodeId> {
813
3981
        NodeId::from_usize(self.previous_sibling)
814
3981
    }
815
    /// Returns the next sibling node ID, if any.
816
    #[must_use]
817
3404678
    pub const fn next_sibling_id(&self) -> Option<NodeId> {
818
3404678
        NodeId::from_usize(self.next_sibling)
819
3404678
    }
820
    /// Returns the first child node ID (`current_node_id` + 1 if has children).
821
    #[must_use]
822
6479183
    pub fn first_child_id(&self, current_node_id: NodeId) -> Option<NodeId> {
823
6479183
        self.last_child_id().map(|_| current_node_id + 1)
824
6479183
    }
825
    /// Returns the last child node ID, if any.
826
    #[must_use]
827
6564516
    pub const fn last_child_id(&self) -> Option<NodeId> {
828
6564516
        NodeId::from_usize(self.last_child)
829
6564516
    }
830
}
831

            
832
impl_vec!(
833
    NodeHierarchyItem,
834
    NodeHierarchyItemVec,
835
    NodeHierarchyItemVecDestructor,
836
    NodeHierarchyItemVecDestructorType,
837
    NodeHierarchyItemVecSlice,
838
    OptionNodeHierarchyItem
839
);
840
impl_vec_mut!(NodeHierarchyItem, NodeHierarchyItemVec);
841
impl_vec_debug!(AzNode, NodeHierarchyItemVec);
842
impl_vec_partialord!(AzNode, NodeHierarchyItemVec);
843
impl_vec_clone!(
844
    NodeHierarchyItem,
845
    NodeHierarchyItemVec,
846
    NodeHierarchyItemVecDestructor
847
);
848
impl_vec_partialeq!(AzNode, NodeHierarchyItemVec);
849

            
850
impl NodeHierarchyItemVec {
851
    /// Returns an immutable container reference for indexed access.
852
    #[must_use]
853
94685131
    pub fn as_container(&self) -> NodeDataContainerRef<'_, NodeHierarchyItem> {
854
94685131
        NodeDataContainerRef {
855
94685131
            internal: self.as_ref(),
856
94685131
        }
857
94685131
    }
858
    /// Returns a mutable container reference for indexed access.
859
1069
    pub fn as_container_mut(&mut self) -> NodeDataContainerRefMut<'_, NodeHierarchyItem> {
860
1069
        NodeDataContainerRefMut {
861
1069
            internal: self.as_mut(),
862
1069
        }
863
1069
    }
864
}
865

            
866
impl NodeDataContainerRef<'_, NodeHierarchyItem> {
867
    /// Returns the number of descendant nodes under the given parent.
868
    #[inline]
869
    #[must_use]
870
3872
    pub fn subtree_len(&self, parent_id: NodeId) -> usize {
871
3872
        let self_item_index = parent_id.index();
872
3872
        let next_item_index = self[parent_id]
873
3872
            .next_sibling_id()
874
3872
            .map_or_else(|| self.len(), |s| s.index());
875
        // saturating: a malformed FastDom can leave next_sibling <= parent,
876
        // which would underflow-panic the subtraction.
877
3872
        next_item_index
878
3872
            .saturating_sub(self_item_index)
879
3872
            .saturating_sub(1)
880
3872
    }
881
}
882

            
883
#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
884
#[repr(C)]
885
pub struct ParentWithNodeDepth {
886
    pub depth: usize,
887
    pub node_id: NodeHierarchyItemId,
888
}
889

            
890
impl_option!(
891
    ParentWithNodeDepth,
892
    OptionParentWithNodeDepth,
893
    [Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash]
894
);
895

            
896
impl fmt::Debug for ParentWithNodeDepth {
897
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
898
        write!(
899
            f,
900
            "{{ depth: {}, node: {:?} }}",
901
            self.depth,
902
            self.node_id.into_crate_internal()
903
        )
904
    }
905
}
906

            
907
impl_vec!(
908
    ParentWithNodeDepth,
909
    ParentWithNodeDepthVec,
910
    ParentWithNodeDepthVecDestructor,
911
    ParentWithNodeDepthVecDestructorType,
912
    ParentWithNodeDepthVecSlice,
913
    OptionParentWithNodeDepth
914
);
915
impl_vec_mut!(ParentWithNodeDepth, ParentWithNodeDepthVec);
916
impl_vec_debug!(ParentWithNodeDepth, ParentWithNodeDepthVec);
917
impl_vec_partialord!(ParentWithNodeDepth, ParentWithNodeDepthVec);
918
impl_vec_clone!(
919
    ParentWithNodeDepth,
920
    ParentWithNodeDepthVec,
921
    ParentWithNodeDepthVecDestructor
922
);
923
impl_vec_partialeq!(ParentWithNodeDepth, ParentWithNodeDepthVec);
924

            
925
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
926
#[repr(C)]
927
pub struct TagIdToNodeIdMapping {
928
    // Hit-testing tag ID (not all nodes have a tag, only nodes that are hit-testable)
929
    pub tag_id: TagId,
930
    /// Node ID of the node that has a tag
931
    pub node_id: NodeHierarchyItemId,
932
    /// Whether this node has a tab-index field
933
    pub tab_index: OptionTabIndex,
934
}
935

            
936
impl_option!(
937
    TagIdToNodeIdMapping,
938
    OptionTagIdToNodeIdMapping,
939
    copy = false,
940
    [Debug, Clone, PartialEq, Eq, Ord, PartialOrd]
941
);
942

            
943
impl_vec!(
944
    TagIdToNodeIdMapping,
945
    TagIdToNodeIdMappingVec,
946
    TagIdToNodeIdMappingVecDestructor,
947
    TagIdToNodeIdMappingVecDestructorType,
948
    TagIdToNodeIdMappingVecSlice,
949
    OptionTagIdToNodeIdMapping
950
);
951
impl_vec_mut!(TagIdToNodeIdMapping, TagIdToNodeIdMappingVec);
952
impl_vec_debug!(TagIdToNodeIdMapping, TagIdToNodeIdMappingVec);
953
impl_vec_partialord!(TagIdToNodeIdMapping, TagIdToNodeIdMappingVec);
954
impl_vec_clone!(
955
    TagIdToNodeIdMapping,
956
    TagIdToNodeIdMappingVec,
957
    TagIdToNodeIdMappingVecDestructor
958
);
959
impl_vec_partialeq!(TagIdToNodeIdMapping, TagIdToNodeIdMappingVec);
960

            
961
#[derive(Debug, Clone, PartialEq, PartialOrd)]
962
#[repr(C)]
963
pub struct ContentGroup {
964
    /// The parent of the current node group, i.e. either the root node (0)
965
    /// or the last positioned node ()
966
    pub root: NodeHierarchyItemId,
967
    /// Node ids in order of drawing
968
    pub children: ContentGroupVec,
969
}
970

            
971
impl_option!(
972
    ContentGroup,
973
    OptionContentGroup,
974
    copy = false,
975
    [Debug, Clone, PartialEq, PartialOrd]
976
);
977

            
978
impl_vec!(
979
    ContentGroup,
980
    ContentGroupVec,
981
    ContentGroupVecDestructor,
982
    ContentGroupVecDestructorType,
983
    ContentGroupVecSlice,
984
    OptionContentGroup
985
);
986
impl_vec_mut!(ContentGroup, ContentGroupVec);
987
impl_vec_debug!(ContentGroup, ContentGroupVec);
988
impl_vec_partialord!(ContentGroup, ContentGroupVec);
989
impl_vec_clone!(ContentGroup, ContentGroupVec, ContentGroupVecDestructor);
990
impl_vec_partialeq!(ContentGroup, ContentGroupVec);
991

            
992
#[derive(Debug, PartialEq, Clone)]
993
#[repr(C)]
994
pub struct StyledDom {
995
    pub root: NodeHierarchyItemId,
996
    pub node_hierarchy: NodeHierarchyItemVec,
997
    pub node_data: NodeDataVec,
998
    pub styled_nodes: StyledNodeVec,
999
    pub cascade_info: CascadeInfoVec,
    pub nodes_with_window_callbacks: NodeHierarchyItemIdVec,
    pub nodes_with_datasets: NodeHierarchyItemIdVec,
    pub tag_ids_to_node_ids: TagIdToNodeIdMappingVec,
    pub non_leaf_nodes: ParentWithNodeDepthVec,
    pub css_property_cache: CssPropertyCachePtr,
    /// The ID of this DOM in the layout tree (for multi-DOM support with `VirtualViews`)
    pub dom_id: DomId,
}
impl_option!(
    StyledDom,
    OptionStyledDom,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl Default for StyledDom {
3029
    fn default() -> Self {
3029
        let root_node: NodeHierarchyItem = Node::ROOT.into();
3029
        let root_node_id: NodeHierarchyItemId =
3029
            NodeHierarchyItemId::from_crate_internal(Some(NodeId::ZERO));
3029
        Self {
3029
            root: root_node_id,
3029
            node_hierarchy: vec![root_node].into(),
3029
            node_data: vec![NodeData::create_body()].into(),
3029
            styled_nodes: vec![StyledNode::default()].into(),
3029
            cascade_info: vec![CascadeInfo {
3029
                index_in_parent: 0,
3029
                is_last_child: true,
3029
            }]
3029
            .into(),
3029
            tag_ids_to_node_ids: Vec::new().into(),
3029
            non_leaf_nodes: vec![ParentWithNodeDepth {
3029
                depth: 0,
3029
                node_id: root_node_id,
3029
            }]
3029
            .into(),
3029
            nodes_with_window_callbacks: Vec::new().into(),
3029
            nodes_with_datasets: Vec::new().into(),
3029
            css_property_cache: CssPropertyCachePtr::new(CssPropertyCache::empty(1)),
3029
            dom_id: DomId::ROOT_ID,
3029
        }
3029
    }
}
/// Per-field heap-byte breakdown of a `StyledDom`.
#[derive(Debug, Clone, Copy, Default)]
pub struct StyledDomMemoryReport {
    pub node_count: usize,
    pub node_hierarchy_bytes: usize,
    pub node_data_bytes: usize,
    pub styled_nodes_bytes: usize,
    pub cascade_info_bytes: usize,
    pub tag_ids_bytes: usize,
    pub non_leaf_nodes_bytes: usize,
    pub callback_vecs_bytes: usize,
    pub css_property_cache: crate::prop_cache::CssPropertyCacheBreakdown,
}
impl StyledDomMemoryReport {
    #[must_use]
7
    pub const fn total_bytes(&self) -> usize {
7
        self.node_hierarchy_bytes
7
            + self.node_data_bytes
7
            + self.styled_nodes_bytes
7
            + self.cascade_info_bytes
7
            + self.tag_ids_bytes
7
            + self.non_leaf_nodes_bytes
7
            + self.callback_vecs_bytes
7
            + self.css_property_cache.total_bytes()
7
    }
}
/// `AZ_CASCADE_TRACE=1`: one line per cascade-invalidating decision.
///
/// The two questions this exists to answer are the ones that gate any further
/// work on `CssPropertyCache::css_props` (24.2 MB, the largest remaining line
/// item): how often is the compact cache REBUILT, and how often does the
/// dynamic selector context actually change?
///
/// `css_props` is written only by `restyle()` and is therefore fully
/// reproducible from `retained_author_css`, so it could be pruned of
/// compact-encoded Normal properties and re-derived on demand — but only if
/// rebuilds are RARE. `prune_compact_normal_props` currently refuses to prune
/// it, citing a per-frame rebuild; that claim is untested, and the e2e runner
/// does not exercise `set_dynamic_selector_context` at all, so it cannot be
/// tested there. Run a real app with this dial to settle it.
#[cfg(feature = "std")]
21051
pub(crate) fn cascade_trace(msg: impl FnOnce() -> String) {
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        OnceLock,
    };
    static ON: OnceLock<bool> = OnceLock::new();
    static N: AtomicUsize = AtomicUsize::new(0);
21051
    if *ON.get_or_init(|| std::env::var("AZ_CASCADE_TRACE").is_ok()) {
        eprintln!(
            "[cascade #{}] {}",
            N.fetch_add(1, Ordering::Relaxed) + 1,
            msg()
        );
21051
    }
21051
}
#[cfg(not(feature = "std"))]
pub(crate) fn cascade_trace(_: impl FnOnce() -> alloc::string::String) {}
impl StyledDom {
    /// Approximate heap bytes retained by this `StyledDom`, broken out by field.
    #[must_use]
3
    pub fn memory_report(&self) -> StyledDomMemoryReport {
3
        let n = self.node_data.len();
        StyledDomMemoryReport {
3
            node_count: n,
3
            node_hierarchy_bytes: size_of_val(self.node_hierarchy.as_ref()),
            node_data_bytes: {
3
                let base = n * size_of::<NodeData>();
                // NodeData contains inline Vecs (callbacks, css_props, datasets)
                // that have their own heap allocations. Approximate:
3
                let mut inner = 0usize;
54
                for nd in self.node_data.as_ref() {
54
                    inner += nd.get_callbacks().len() * 64; // rough per-callback
54
                                                            // Each rule = path + decls Vec +
54
                                                            // conditions Vec + priority byte.
54
                                                            // Approximate at 64 bytes per rule +
54
                                                            // the heap for declarations.
54
                    inner += nd.style.rules.as_ref().len() * 64;
54
                }
3
                base + inner
            },
3
            styled_nodes_bytes: n * size_of::<StyledNode>(),
3
            cascade_info_bytes: n * size_of::<CascadeInfo>(),
3
            tag_ids_bytes: size_of_val(self.tag_ids_to_node_ids.as_ref()),
3
            non_leaf_nodes_bytes: size_of_val(self.non_leaf_nodes.as_ref()),
3
            callback_vecs_bytes: self.nodes_with_window_callbacks.as_ref().len() * 8
3
                + self.nodes_with_datasets.as_ref().len() * 8,
3
            css_property_cache: self.css_property_cache.ptr.memory_breakdown(),
        }
3
    }
    /// Creates a new `StyledDom` by applying CSS styles to a DOM tree.
    ///
    /// NOTE: After calling this function, the DOM will be reset to an empty DOM.
    // This is for memory optimization, so that the DOM does not need to be cloned.
    //
    // The CSS will be left in-place, but will be re-ordered
18852
    pub fn create(dom: &mut Dom, css: Css) -> Self {
18852
        Self::create_with_context(dom, css, None)
18852
    }
    /// [`Self::create`], cascading under a known window context from the
    /// start.
    ///
    /// The creation cascade evaluates `@theme` / `@media` / `@os` rules, the
    /// themed UA defaults and every conditional inline declaration against
    /// [`CssPropertyCache::dynamic_context`]. With `None` there is no context
    /// yet — conditional rules do not apply and the UA answers its light
    /// table — and the first [`Self::set_dynamic_selector_context`] the
    /// layout funnel makes re-cascades what depends on it. Passing the
    /// window's context here (what `LayoutWindow::style_user_dom_for` does)
    /// makes that first offer a no-op instead of a second pass, and means a
    /// DOM born in a dark window is dark from its first cascade rather than
    /// light-then-fixed.
38116
    pub fn create_with_context(
38116
        dom: &mut Dom,
38116
        css: Css,
38116
        context: Option<azul_css::dynamic_selector::DynamicSelectorContext>,
38116
    ) -> Self {
        use core::mem;
38116
        let mut swap_dom = Dom::create_body();
38116
        mem::swap(dom, &mut swap_dom);
        // Silent-loss fix: this entry point used to DISCARD every
        // node-attached stylesheet (`Dom::with_css` / `add_component_css`) —
        // the string parsed, rode the Dom to here, and vanished in the
        // CompactDom conversion, while `create_from_dom` applied it. The
        // classic split-brain constructor: half the callers styled nothing
        // and nobody was told (a `width:260px; height:100px` box silently
        // laid out auto-sized). Collect + subtree-scope exactly like
        // `create_from_dom` (#47), APPENDED after the caller's stylesheet —
        // inline rules already carry `rule_priority::INLINE`, so the cascade
        // ranks them correctly regardless of order.
38116
        swap_dom.fixup_children_estimated();
38116
        let mut next_scope_id = 0usize;
38116
        scope_inline_css(&mut swap_dom, &mut next_scope_id);
38116
        let mut node_css: Vec<Css> = Vec::new();
38116
        collect_css_from_dom(&swap_dom, &mut node_css);
38116
        let css = if node_css.is_empty() {
35079
            css
        } else {
3037
            let mut combined_rules = css.rules.into_library_owned_vec();
3037
            let mut combined_keyframes = css.keyframes.into_library_owned_vec();
56234
            for c in node_css {
53197
                combined_rules.extend(c.rules.into_library_owned_vec());
53197
                combined_keyframes.extend(c.keyframes.into_library_owned_vec());
53197
            }
3037
            let mut merged = Css::new(combined_rules);
3037
            merged.keyframes = combined_keyframes.into();
3037
            merged
        };
38116
        strip_css_from_dom(&mut swap_dom);
38116
        let compact_dom: CompactDom = swap_dom.into();
38116
        let node_hierarchy: NodeHierarchyItemVec = compact_dom
38116
            .node_hierarchy
38116
            .as_ref()
38116
            .internal
38116
            .iter()
756809
            .map(|i| (*i).into())
38116
            .collect::<Vec<NodeHierarchyItem>>()
38116
            .into();
38116
        Self::create_from_compact_dom(compact_dom, css, node_hierarchy, context)
38116
    }
    /// Creates a `StyledDom` from a `FastDom` (arena-based DOM).
    ///
    /// This skips the `convert_dom_into_compact_dom` tree->arena conversion
    /// entirely since `FastDom` already has flat `NodeHierarchyItemVec` and
    /// `NodeDataVec`. CSS is collected from `CssWithNodeIdVec`.
    #[must_use]
3616
    pub fn create_from_fast_dom(fast_dom: crate::dom::FastDom) -> Self {
        use azul_css::css::Css;
        // 1. Merge CSS from CssWithNodeIdVec into a single Css, scoping each node-attached
        //    stylesheet to its owner's subtree (#47): push_front a Root([owner, owner+subtree_len])
        //    selector so inline/XML css can't leak globally — the same scoping the recursive
        //    create_from_dom path applies via scope_inline_css. `node_id` is the owner's flat id (0
        //    = root).
3616
        let mut combined_rules: Vec<azul_css::css::CssRuleBlock> = Vec::new();
3616
        let mut combined_keyframes: Vec<azul_css::css::Keyframes> = Vec::new();
3616
        let css_entries = fast_dom.css.into_library_owned_vec();
        {
3616
            let hierarchy = fast_dom.node_hierarchy.as_container();
7064
            for mut css_with_id in css_entries {
                // Keyframes are name-global (no scoping): collect before the
                // rules are consumed. Later definitions win at resolve time.
3448
                combined_keyframes.extend(
3448
                    core::mem::take(&mut css_with_id.css.keyframes).into_library_owned_vec(),
                );
3448
                let owner = css_with_id.node_id;
3448
                let end = if owner < hierarchy.len() {
3448
                    owner + hierarchy.subtree_len(NodeId::new(owner))
                } else {
                    owner
                };
8466
                for mut rule in css_with_id.css.rules.into_library_owned_vec() {
8463
                    // Bare-declaration wrappers (INLINE priority) stay
8463
                    // node-only; a stylesheet's `* { ... }` (AUTHOR/UA
8463
                    // priority) scopes to the whole subtree. See
8463
                    // push_front_scope_for.
8463
                    let node_only = rule.priority >= azul_css::css::rule_priority::INLINE;
8463
                    rule.path.push_front_scope_for(owner, end, node_only);
8463
                    combined_rules.push(rule);
8463
                }
            }
        }
3616
        let combined_css = if combined_rules.is_empty() && combined_keyframes.is_empty() {
723
            Css::empty()
        } else {
2893
            let mut css = Css::new(combined_rules);
2893
            css.keyframes = combined_keyframes.into();
2893
            css
        };
        // 2. Convert NodeHierarchyItemVec → NodeHierarchy (Vec<Node>) for cascade tree computation
3616
        let node_hierarchy_items = fast_dom.node_hierarchy;
3616
        let nodes: Vec<Node> = node_hierarchy_items
3616
            .as_ref()
3616
            .iter()
3616
            .map(|item| Node {
97718
                parent: NodeId::from_usize(item.parent),
97718
                previous_sibling: NodeId::from_usize(item.previous_sibling),
97718
                next_sibling: NodeId::from_usize(item.next_sibling),
97718
                last_child: NodeId::from_usize(item.last_child),
97718
            })
3616
            .collect();
3616
        let node_hierarchy_internal = NodeHierarchy { internal: nodes };
        // 3. Build CompactDom from the flat arenas (no conversion needed)
3616
        let node_data_vec = fast_dom.node_data.into_library_owned_vec();
3616
        let compact_dom = CompactDom {
3616
            node_hierarchy: node_hierarchy_internal,
3616
            node_data: NodeDataContainer {
3616
                internal: node_data_vec,
3616
            },
3616
            root: NodeId::ZERO,
3616
        };
        // 4. Delegate to create() which handles cascade, UA CSS, etc. We need a mutable Dom to pass
        //    to create(), but we already have CompactDom. Instead, inline the cascade logic from
        //    create() with our CompactDom.
3616
        Self::create_from_compact_dom(compact_dom, combined_css, node_hierarchy_items, None)
3616
    }
    /// Internal: creates `StyledDom` from a `CompactDom` + CSS + pre-built hierarchy items.
    /// Shared by both the Slow path (create -> `convert_dom_into_compact_dom` -> this)
    /// and the Fast path (`create_from_fast_dom` -> this).
    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch
                                     // (one branch per input variant)
41732
    fn create_from_compact_dom(
41732
        compact_dom: CompactDom,
41732
        mut css: Css,
41732
        node_hierarchy: NodeHierarchyItemVec,
41732
        context: Option<azul_css::dynamic_selector::DynamicSelectorContext>,
41732
    ) -> Self {
        use crate::dom::EventFilter;
        static CASCADE_BREAKDOWN: crate::sync::OnceLock<bool> = crate::sync::OnceLock::new();
41732
        let cascade_dbg = *CASCADE_BREAKDOWN.get_or_init(crate::profile::memory_enabled);
41732
        let node_count = compact_dom.len();
41732
        let non_leaf_nodes = compact_dom
41732
            .node_hierarchy
41732
            .as_ref()
41732
            .get_parents_sorted_by_depth();
41732
        let mut styled_nodes = vec![
41732
            StyledNode {
41732
                styled_node_state: StyledNodeState::new()
41732
            };
41732
            node_count
        ];
41732
        let mut css_property_cache = CssPropertyCache::empty(compact_dom.node_data.len());
        // Installed BEFORE the cascade below so that every stage of it — the
        // author @-rule gating in `restyle`, the themed UA table in
        // `apply_ua_css`, the conditional inline declarations the compact
        // builder (and `compute_inherited_values`) evaluate — answers for the
        // window this DOM is about to be shown in. See `create_with_context`.
41732
        css_property_cache.dynamic_context = context.map(Box::new);
41732
        let html_tree = construct_html_cascade_tree(
41732
            &compact_dom.node_hierarchy.as_ref(),
41732
            &non_leaf_nodes[..],
41732
            &compact_dom.node_data.as_ref(),
        );
41732
        let non_leaf_nodes = non_leaf_nodes
41732
            .iter()
41732
            .map(|(depth, node_id)| ParentWithNodeDepth {
442743
                depth: *depth,
442743
                node_id: NodeHierarchyItemId::from_crate_internal(Some(*node_id)),
442743
            })
41732
            .collect::<Vec<_>>();
41732
        let non_leaf_nodes: ParentWithNodeDepthVec = non_leaf_nodes.into();
41732
        let _restyle_tag_ids = css_property_cache.restyle(
41732
            &mut css,
41732
            &compact_dom.node_data.as_ref(),
41732
            &node_hierarchy,
41732
            &non_leaf_nodes,
41732
            &html_tree.as_ref(),
        );
        // Retain the author stylesheet on the cache (this used to `drop(css)` to
        // save ~500 KiB, but that made runtime-inserted nodes unstyleable: the
        // rules were gone, so nothing could ever re-run the cascade for them —
        // see e2e/bug-inserted-node-no-author-css.json).
41732
        css_property_cache.retained_author_css = css;
        // Apply UA defaults + compute inherited values so consumers that
        // read `css_property_cache.computed_values` (the web/HTML
        // renderer in `dll/src/web/html_render.rs`) see resolved
        // properties. The compact cache below stores the same info in
        // a different layout for the desktop renderer; computed_values
        // is the "tall" form that the web renderer's CSS emitter
        // (`emit_css_from_cache`) walks per node.
41732
        css_property_cache.apply_ua_css(compact_dom.node_data.as_ref().internal);
41732
        css_property_cache.compute_inherited_values(
41732
            node_hierarchy.as_container().internal,
41732
            compact_dom.node_data.as_ref().internal,
        );
41732
        let prev_font_hashes: Vec<u64> = css_property_cache
41732
            .compact_cache
41732
            .as_ref()
41732
            .map(|c| c.prev_font_hashes.clone())
41732
            .unwrap_or_default();
41732
        let compact = css_property_cache.build_compact_cache_with_inheritance(
41732
            compact_dom.node_data.as_ref().internal,
41732
            node_hierarchy.as_container().internal,
41732
            &prev_font_hashes,
        );
41732
        css_property_cache.compact_cache = Some(compact);
41732
        let pre_prune = if cascade_dbg {
            Some(css_property_cache.memory_breakdown())
        } else {
41732
            None
        };
41732
        css_property_cache.prune_compact_normal_props();
41732
        if let Some(pre) = pre_prune {
            let post = css_property_cache.memory_breakdown();
            #[cfg(feature = "std")]
            eprintln!(
                "[PRUNE] css_props {} → {} KiB  cascaded {} → {} KiB  (saved {} KiB)",
                pre.css_props_bytes / 1024,
                post.css_props_bytes / 1024,
                pre.cascaded_props_bytes / 1024,
                post.cascaded_props_bytes / 1024,
                (pre.total_bytes().saturating_sub(post.total_bytes())) / 1024
            );
            #[cfg(not(feature = "std"))]
            let _ = post;
41732
        }
41732
        let tag_ids =
41732
            css_property_cache.generate_tag_ids(&compact_dom.node_data.as_ref(), &node_hierarchy);
41732
        if cascade_dbg {
            let bd = css_property_cache.memory_breakdown();
            #[cfg(feature = "std")]
            eprintln!(
                "[CASCADE] {} nodes  cascaded_props={} KiB  css_props={} KiB  compact={} KiB  \
                 computed={} KiB  total={} KiB",
                node_count,
                bd.cascaded_props_bytes / 1024,
                bd.css_props_bytes / 1024,
                bd.compact_cache_bytes / 1024,
                bd.computed_values_bytes / 1024,
                bd.total_bytes() / 1024
            );
            #[cfg(not(feature = "std"))]
            let _ = bd;
41732
        }
        // Collect callback/dataset nodes in a single pass (avoids 3 separate 50K scans).
        // For XHTML-parsed DOMs with no callbacks, this early-exits immediately.
41732
        let has_any_callbacks = compact_dom
41732
            .node_data
41732
            .as_ref()
41732
            .internal
41732
            .iter()
260959
            .any(|c| !c.get_callbacks().is_empty() || c.get_dataset().is_some());
41732
        let (nodes_with_window_callbacks, nodes_with_datasets) = if has_any_callbacks {
16668
            let mut win_cbs = Vec::new();
16668
            let mut datasets = Vec::new();
623220
            for (node_id, c) in compact_dom.node_data.as_ref().internal.iter().enumerate() {
623220
                let cbs = c.get_callbacks();
623220
                let has_dataset = c.get_dataset().is_some();
623220
                if !cbs.is_empty() || has_dataset {
111180
                    datasets.push(NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(
111180
                        node_id,
111180
                    ))));
512040
                }
799164
                for cb in cbs {
176376
                    if let EventFilter::Window(_) = cb.event {
432
                        win_cbs.push(NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(
432
                            node_id,
432
                        ))));
432
                        break;
175944
                    }
                }
            }
16668
            (win_cbs, datasets)
        } else {
25064
            (Vec::new(), Vec::new())
        };
41732
        let mut styled_dom = Self {
41732
            root: NodeHierarchyItemId::from_crate_internal(Some(compact_dom.root)),
41732
            node_hierarchy,
41732
            node_data: compact_dom.node_data.internal.into(),
41732
            cascade_info: html_tree.internal.into(),
41732
            styled_nodes: styled_nodes.into(),
41732
            tag_ids_to_node_ids: tag_ids.into(),
41732
            nodes_with_window_callbacks: nodes_with_window_callbacks.into(),
41732
            nodes_with_datasets: nodes_with_datasets.into(),
41732
            non_leaf_nodes,
41732
            css_property_cache: CssPropertyCachePtr::new(css_property_cache),
41732
            dom_id: DomId::ROOT_ID,
41732
        };
        #[cfg(feature = "table_layout")]
        if let Err(_e) = crate::dom_table::generate_anonymous_table_elements(&mut styled_dom) {}
41732
        styled_dom
41732
    }
    /// Creates a `StyledDom` from a recursive Dom tree with deferred CSS.
    ///
    /// This is the Phase 7.2 entry point: the layout callback returns a recursive
    /// `Dom` with `css: Vec<Css>` on each node. This function:
    ///
    /// 1. Collects all CSS objects from the recursive tree
    /// 2. Flattens the Dom into contiguous arrays (`CompactDom`)
    /// 3. Merges all CSS objects and runs a single cascade pass
    /// 4. Runs `apply_ua_css` -> `compute_inherited_values` -> `build_compact_cache`
    /// 5. Generates anonymous table elements
    #[must_use]
18015
    pub fn create_from_dom(dom: Dom) -> Self {
18015
        Self::create_from_dom_with_context(dom, None)
18015
    }
    /// [`Self::create_from_dom`] cascading under a known window context from
    /// the first pass — see [`Self::create_with_context`].
    #[must_use]
19252
    pub fn create_from_dom_with_context(
19252
        mut dom: Dom,
19252
        context: Option<azul_css::dynamic_selector::DynamicSelectorContext>,
19252
    ) -> Self {
        use azul_css::css::Css;
        // #47: scope each node's inline css to its subtree BEFORE collecting, so a
        // non-root node's with_css cannot leak to the whole tree. Uses the same
        // pre-order ids the flatten (convert_dom_into_compact_dom) will assign;
        // needs estimated_total_children populated first.
19252
        dom.fixup_children_estimated();
19252
        let mut next_scope_id = 0usize;
19252
        scope_inline_css(&mut dom, &mut next_scope_id);
        // 1. Collect all CSS objects from the recursive Dom tree (now scoped)
19252
        let mut all_css = Vec::new();
19252
        collect_css_from_dom(&dom, &mut all_css);
        // 2. Merge all CSS objects into one combined Css
19252
        let mut combined_css = if all_css.is_empty() {
8993
            Css::empty()
        } else {
10259
            let mut combined_rules: Vec<azul_css::css::CssRuleBlock> = Vec::new();
10259
            let mut combined_keyframes: Vec<azul_css::css::Keyframes> = Vec::new();
128783
            for css in all_css {
118524
                combined_rules.extend(css.rules.into_library_owned_vec());
118524
                combined_keyframes.extend(css.keyframes.into_library_owned_vec());
118524
            }
10259
            let mut css = Css::new(combined_rules);
10259
            css.keyframes = combined_keyframes.into();
10259
            css
        };
        // 3. Strip CSS from all Dom nodes before flattening (CSS is already collected, don't need
        //    it in the flat tree)
19252
        strip_css_from_dom(&mut dom);
        // 4. Use existing StyledDom::create to flatten + cascade
19252
        Self::create_with_context(&mut dom, combined_css, context)
19252
    }
    /// Appends another `StyledDom` as a child to the `self.root`
    /// without re-styling the DOM itself
235
    pub fn append_child(&mut self, other: Self) {
235
        let self_root_id = self.root.into_crate_internal().unwrap_or(NodeId::ZERO);
235
        let current_root_children_count = self_root_id
235
            .az_children(&self.node_hierarchy.as_container())
235
            .count();
235
        self.append_child_with_index(other, current_root_children_count);
235
        self.finalize_non_leaf_nodes();
235
    }
    /// Optimized version of `append_child` that takes the child index directly
    /// instead of counting existing children (O(1) instead of O(n))
242
    pub fn append_child_with_index(&mut self, mut other: Self, child_index: usize) {
        // shift all the node ids in other by self.len()
242
        let self_len = self.node_hierarchy.as_ref().len();
242
        let other_len = other.node_hierarchy.as_ref().len();
242
        let self_root_id = self.root.into_crate_internal().unwrap_or(NodeId::ZERO);
242
        let other_root_id = other.root.into_crate_internal().unwrap_or(NodeId::ZERO);
        // Use provided index instead of counting children
242
        other.cascade_info.as_mut()[other_root_id.index()].index_in_parent =
242
            u32::try_from(child_index).unwrap_or(u32::MAX);
242
        other.cascade_info.as_mut()[other_root_id.index()].is_last_child = true;
242
        self.cascade_info.append(&mut other.cascade_info);
        // adjust node hierarchy
384
        for other in other.node_hierarchy.as_mut().iter_mut() {
384
            if other.parent != 0 {
142
                other.parent += self_len;
242
            }
384
            if other.previous_sibling != 0 {
4
                other.previous_sibling += self_len;
380
            }
384
            if other.next_sibling != 0 {
4
                other.next_sibling += self_len;
380
            }
384
            if other.last_child != 0 {
138
                other.last_child += self_len;
246
            }
        }
242
        other.node_hierarchy.as_container_mut()[other_root_id].parent =
242
            NodeId::into_raw(&Some(self_root_id));
242
        let current_last_child = self.node_hierarchy.as_container()[self_root_id].last_child_id();
242
        other.node_hierarchy.as_container_mut()[other_root_id].previous_sibling =
242
            NodeId::into_raw(&current_last_child);
242
        if let Some(current_last) = current_last_child {
161
            if self.node_hierarchy.as_container_mut()[current_last]
161
                .next_sibling_id()
161
                .is_some()
            {
                self.node_hierarchy.as_container_mut()[current_last].next_sibling +=
                    other_root_id.index() + other_len;
161
            } else {
161
                self.node_hierarchy.as_container_mut()[current_last].next_sibling =
161
                    NodeId::into_raw(&Some(NodeId::new(self_len + other_root_id.index())));
161
            }
81
        }
242
        self.node_hierarchy.as_container_mut()[self_root_id].last_child =
242
            NodeId::into_raw(&Some(NodeId::new(self_len + other_root_id.index())));
242
        self.node_hierarchy.append(&mut other.node_hierarchy);
242
        self.node_data.append(&mut other.node_data);
242
        self.styled_nodes.append(&mut other.styled_nodes);
242
        self.get_css_property_cache_mut()
242
            .append(other.get_css_property_cache_mut());
        // Tag IDs are globally unique (AtomicUsize counter) and never collide,
        // so we only shift node_id (which changes when DOMs are merged).
356
        for tag_id_node_id in &mut other.tag_ids_to_node_ids {
114
            tag_id_node_id.node_id.inner += self_len;
114
        }
242
        self.tag_ids_to_node_ids
242
            .append(&mut other.tag_ids_to_node_ids);
242
        for nid in &mut other.nodes_with_window_callbacks {
            nid.inner += self_len;
        }
242
        self.nodes_with_window_callbacks
242
            .append(&mut other.nodes_with_window_callbacks);
242
        for nid in &mut other.nodes_with_datasets {
            nid.inner += self_len;
        }
242
        self.nodes_with_datasets
242
            .append(&mut other.nodes_with_datasets);
        // edge case: if the other StyledDom consists of only one node
        // then it is not a parent itself
242
        if other_len != 1 {
257
            for other_non_leaf_node in &mut other.non_leaf_nodes {
138
                other_non_leaf_node.node_id.inner += self_len;
138
                other_non_leaf_node.depth += 1;
138
            }
119
            self.non_leaf_nodes.append(&mut other.non_leaf_nodes);
            // NOTE: Sorting deferred - call finalize_non_leaf_nodes() after all appends
123
        }
242
    }
    /// Call this after all `append_child_with_index` operations are complete
    /// to sort `non_leaf_nodes` by depth (required for correct rendering)
239
    pub fn finalize_non_leaf_nodes(&mut self) {
246
        self.non_leaf_nodes.sort_by(|a, b| a.depth.cmp(&b.depth));
239
    }
    /// Same as `append_child()`, but as a builder method
    #[must_use]
1
    pub fn with_child(mut self, other: Self) -> Self {
1
        self.append_child(other);
1
        self
1
    }
    /// Sets the context menu for the root node
2
    pub fn set_context_menu(&mut self, context_menu: Menu) {
2
        if let Some(root_id) = self.root.into_crate_internal() {
2
            self.node_data.as_container_mut()[root_id].set_context_menu(context_menu);
2
        }
2
    }
    /// Builder method for setting the context menu
    #[must_use]
1
    pub fn with_context_menu(mut self, context_menu: Menu) -> Self {
1
        self.set_context_menu(context_menu);
1
        self
1
    }
    /// Sets the menu bar for the root node
2
    pub fn set_menu_bar(&mut self, menu_bar: Menu) {
2
        if let Some(root_id) = self.root.into_crate_internal() {
2
            self.node_data.as_container_mut()[root_id].set_menu_bar(menu_bar);
2
        }
2
    }
    /// Builder method for setting the menu bar
    #[must_use]
1
    pub fn with_menu_bar(mut self, menu_bar: Menu) -> Self {
1
        self.set_menu_bar(menu_bar);
1
        self
1
    }
    /// Re-compute inherited CSS values and rebuild the compact layout cache.
    ///
    /// This MUST be called after `append_child()` merges multiple `StyledDom`s.
    /// `append_child()` concatenates the CSS property caches but does NOT
    /// re-run inheritance or rebuild the compact cache. This means:
    ///
    /// 1. **Broken inheritance**: Inherited properties (`color`, `font-size`, `direction`) from the
    ///    parent DOM do not flow into appended subtrees.
    /// 2. **Stale compact cache**: The child's tier 1/2/2b entries still reflect the child's
    ///    isolated cascade, not the composed tree.
    ///
    /// Calling this method after all `append_child()` calls fixes both issues
    /// by re-running a full depth-first inheritance pass and rebuilding the
    /// compact cache from scratch on the composed tree.
1636
    pub fn recompute_inheritance_and_compact_cache(&mut self) {
1636
        cascade_trace(|| "compact cache REBUILT from css_props".to_string());
        // Use the _with_inheritance variant: it does inheritance inline (via
        // parent-compact-field copy) AND populates hot_flags via
        // apply_css_property_to_compact.  The plain build_compact_cache would
        // leave HOT_FLAG_HAS_BACKGROUND / HAS_CLIP_PATH / extra_flags at 0,
        // causing renderer negative fast-paths to skip paint (regression
        // introduced by ff059052b).  No SIGABRT risk — _with_inheritance
        // never pushes to the flat cascaded_props storage.
1636
        let prev_font_hashes: Vec<u64> = self
1636
            .css_property_cache
1636
            .downcast_mut()
1636
            .compact_cache
1636
            .as_ref()
1636
            .map(|c| c.prev_font_hashes.clone())
1636
            .unwrap_or_default();
1636
        let compact = self
1636
            .css_property_cache
1636
            .downcast_mut()
1636
            .build_compact_cache_with_inheritance(
1636
                self.node_data.as_container().internal,
1636
                self.node_hierarchy.as_container().internal,
1636
                &prev_font_hashes,
            );
1636
        self.css_property_cache.downcast_mut().compact_cache = Some(compact);
1636
        let cache = self.css_property_cache.downcast_mut();
1636
        cache.cascade_epoch = cache.cascade_epoch.wrapping_add(1);
1636
    }
    /// Re-applies CSS styles to the existing DOM structure.
    /// Grow retained author-CSS subtree scopes to cover a node just appended under
    /// `parent`. Mount/`with_css` rules carry a `Root([start, end])` scope
    /// (`push_front_scope`) that only matches nodes within a node's ORIGINAL subtree
    /// range, so a node appended afterwards falls outside every scope and
    /// `restyle_retained` cannot match it. Appending under `parent` (rightmost-spine
    /// only, so subtrees stay contiguous in the flat arena) grows `parent`'s and its
    /// ancestors' subtrees; bump the inclusive `end` of every scope that already
    /// covers `parent` out to the new node.
    #[allow(clippy::similar_names)] // new_node/parent and the p/n index locals read clearly in
                                    // context
2
    pub fn extend_author_scopes_for_appended(&mut self, new_node: NodeId, parent: NodeId) {
        use azul_css::css::CssPathSelector;
2
        let p = parent.index();
2
        let n = new_node.index();
2
        let cache = self.css_property_cache.downcast_mut();
6
        for rule in cache.retained_author_css.rules.as_mut() {
6
            let mut sels = rule.path.selectors.as_ref().to_vec();
6
            let mut changed = false;
18
            for sel in &mut sels {
12
                if let CssPathSelector::Root(range) = sel {
6
                    if range.contains(p) && range.end < n {
6
                        range.end = n;
6
                        changed = true;
6
                    }
6
                }
            }
6
            if changed {
6
                rule.path.selectors = sels.into();
6
            }
        }
2
    }
    /// Re-run the author cascade from the stylesheet retained at creation /
    /// last `restyle` (`CssPropertyCache::retained_author_css`). Call after a
    /// structural DOM mutation (e.g. inserting a node) so new nodes receive
    /// author CSS; a no-op when no author stylesheet was ever attached.
    /// The PER-TICK override channel: write `user_overridden_properties`
    /// WITHOUT recomputing inheritance or the compact cache. Sound only when
    /// the caller supplies the pixels itself (the transition driver patches
    /// the display list with the interpolated value directly) - every other
    /// caller wants [`Self::restyle_user_property`]. At t=1 the override is
    /// removed and the (correctly cascaded) target shows through.
    ///
    /// Deliberately does NOT bump `CssPropertyCache::cascade_epoch`: the
    /// display-list cache keys on the epoch, and this channel runs every
    /// tick of a transition with the caller patching the list itself.
62
    pub fn set_user_property_override_fast(
62
        &mut self,
62
        node_id: &NodeId,
62
        new_properties: &[CssProperty],
62
    ) {
62
        let node_count = self.node_data.as_ref().len();
62
        if node_id.index() >= node_count {
            return;
62
        }
62
        let cache = self.get_css_property_cache_mut();
62
        if cache.user_overridden_properties.len() < node_count {
            cache
                .user_overridden_properties
                .resize(node_count, Vec::new());
62
        }
124
        for new_prop in new_properties {
62
            let prop_type = new_prop.get_type();
62
            let vec = &mut cache.user_overridden_properties[node_id.index()];
62
            if new_prop.is_initial() {
1
                if let Ok(idx) = vec.binary_search_by_key(&prop_type, |(k, _)| *k) {
1
                    vec.remove(idx);
1
                }
            } else {
61
                match vec.binary_search_by_key(&prop_type, |(k, _)| *k) {
61
                    Ok(idx) => vec[idx].1 = new_prop.clone(),
                    Err(idx) => vec.insert(idx, (prop_type, new_prop.clone())),
                }
            }
        }
62
    }
225
    pub fn restyle_retained(&mut self) {
225
        let css = self
225
            .css_property_cache
225
            .downcast_mut()
225
            .retained_author_css
225
            .clone();
225
        if css.is_empty() {
            return;
225
        }
225
        self.restyle(css);
225
    }
229
    pub fn restyle(&mut self, mut css: Css) {
        // NOTE: the tag_ids returned by `cache.restyle` here are generated from
        // the STALE `compact_cache` (display/overflow reads) and are intentionally
        // discarded — we regenerate them below AFTER the compact cache and
        // inheritance have been recomputed (audit styled_dom.rs:1404/1426).
229
        let _stale_tag_ids = self.css_property_cache.downcast_mut().restyle(
229
            &mut css,
229
            &self.node_data.as_container(),
229
            &self.node_hierarchy,
229
            &self.non_leaf_nodes,
229
            &self.cascade_info.as_container(),
        );
        // Keep the stylesheet for later structural restyles (inserted nodes).
229
        self.css_property_cache.downcast_mut().retained_author_css = css;
229
        self.recascade_ua_inheritance_and_compact();
229
    }
    /// The context-dependent tail of [`Self::restyle`], on its own: UA
    /// defaults → inheritance → compact cache → resolved font sizes →
    /// hit-test tags. Everything after the author cascade, which is the part
    /// that does NOT depend on the window context unless the stylesheet has
    /// conditional rules (`set_dynamic_selector_context` re-runs the author
    /// cascade separately for those).
    ///
    /// This is what a theme flip runs. Before it existed, a flip rebuilt the
    /// compact cache only, so `cascaded_props` and `computed_values` — the
    /// slow path's and the display list's sources — kept the answers of the
    /// context the DOM was CREATED under, forever: root cause R2 of the
    /// theme-chain analysis (2026-09-12), the black-label-on-dark family.
8559
    pub fn recascade_ua_inheritance_and_compact(&mut self) {
8559
        cascade_trace(|| "UA + inheritance + compact RECASCADED".to_string());
        // Apply UA CSS properties before computing inheritance (strips and
        // re-answers its own previous entries, see `apply_ua_css`).
8559
        self.css_property_cache
8559
            .downcast_mut()
8559
            .apply_ua_css(self.node_data.as_container().internal);
        // Compute inherited values after restyle and apply_ua_css (resolves em, %, etc.)
8559
        self.css_property_cache
8559
            .downcast_mut()
8559
            .compute_inherited_values(
8559
                self.node_hierarchy.as_container().internal,
8559
                self.node_data.as_container().internal,
            );
        // The old compact_cache was built from the pre-restyle CSS. If we do not
        // rebuild it, layout-hot properties (display/overflow/background/clip,
        // resolved font sizes) keep their stale values and the restyle silently
        // no-ops for them. Drop it, rebuild via the _with_inheritance path (which
        // repopulates hot_flags), and invalidate the cached resolved font sizes.
8559
        let prev_font_hashes: Vec<u64> = self
8559
            .css_property_cache
8559
            .downcast_mut()
8559
            .compact_cache
8559
            .as_ref()
8559
            .map(|c| c.prev_font_hashes.clone())
8559
            .unwrap_or_default();
8559
        self.css_property_cache.downcast_mut().compact_cache = None;
8559
        let compact = self
8559
            .css_property_cache
8559
            .downcast_mut()
8559
            .build_compact_cache_with_inheritance(
8559
                self.node_data.as_container().internal,
8559
                self.node_hierarchy.as_container().internal,
8559
                &prev_font_hashes,
            );
8559
        self.css_property_cache.downcast_mut().compact_cache = Some(compact);
8559
        self.css_property_cache
8559
            .downcast_mut()
8559
            .invalidate_resolved_font_sizes();
        // Regenerate tag_ids from the freshly rebuilt compact cache so the
        // hit-test map reflects the post-restyle display/overflow values.
8559
        let new_tag_ids = self
8559
            .css_property_cache
8559
            .downcast_mut()
8559
            .generate_tag_ids(&self.node_data.as_container(), &self.node_hierarchy);
8559
        self.tag_ids_to_node_ids = new_tag_ids.into();
8559
    }
    /// Returns the total number of nodes in this `StyledDom`.
    #[inline]
    #[must_use]
593
    pub const fn node_count(&self) -> usize {
593
        self.node_data.len()
593
    }
    /// Returns an immutable reference to the CSS property cache.
    #[inline]
    #[must_use]
2022984
    pub fn get_css_property_cache(&self) -> &CssPropertyCache {
2022984
        &self.css_property_cache.ptr
2022984
    }
    /// Returns a mutable reference to the CSS property cache.
    #[inline]
16138
    pub fn get_css_property_cache_mut(&mut self) -> &mut CssPropertyCache {
16138
        &mut self.css_property_cache.ptr
16138
    }
    /// Returns the current state (hover, active, focus) of a styled node.
    #[inline]
    #[must_use]
31
    pub fn get_styled_node_state(&self, node_id: &NodeId) -> StyledNodeState {
31
        self.styled_nodes.as_container()[*node_id].styled_node_state
31
    }
    /// Updates hover state for nodes and returns changed CSS properties.
    #[must_use]
157
    pub fn restyle_nodes_hover(&mut self, nodes: &[NodeId], new_hover_state: bool) -> RestyleNodes {
157
        self.restyle_nodes_state(
157
            nodes,
157
            new_hover_state,
207
            |state, val| state.hover = val,
157
            azul_css::dynamic_selector::PseudoStateType::Hover,
        )
157
    }
    /// Updates active state for nodes and returns changed CSS properties.
    #[must_use]
98
    pub fn restyle_nodes_active(
98
        &mut self,
98
        nodes: &[NodeId],
98
        new_active_state: bool,
98
    ) -> RestyleNodes {
98
        self.restyle_nodes_state(
98
            nodes,
98
            new_active_state,
96
            |state, val| state.active = val,
98
            azul_css::dynamic_selector::PseudoStateType::Active,
        )
98
    }
    /// Updates focus state for nodes and returns changed CSS properties.
    #[must_use]
270
    pub fn restyle_nodes_focus(&mut self, nodes: &[NodeId], new_focus_state: bool) -> RestyleNodes {
270
        self.restyle_nodes_state(
270
            nodes,
270
            new_focus_state,
269
            |state, val| state.focused = val,
270
            azul_css::dynamic_selector::PseudoStateType::Focus,
        )
270
    }
    /// `:seat-focus` on/off for `nodes` (9b-ii-a-i-d-iii-a).
11
    pub fn restyle_nodes_seat_focus(&mut self, nodes: &[NodeId], on: bool) -> RestyleNodes {
11
        self.restyle_nodes_state(
11
            nodes,
11
            on,
11
            |state, val| state.seat_focused = val,
11
            azul_css::dynamic_selector::PseudoStateType::SeatFocus,
        )
11
    }
    /// A non-primary seat's focus moved: `lost` drops `:seat-focus`, `gained`
    /// takes it. Same result classification as `restyle_on_state_change`.
10
    pub fn restyle_on_seat_focus_change(
10
        &mut self,
10
        lost: Option<NodeId>,
10
        gained: Option<NodeId>,
10
    ) -> RestyleResult {
10
        let mut result = RestyleResult {
10
            gpu_only_changes: true,
10
            ..RestyleResult::default()
10
        };
11
        let mut process = |changes: RestyleNodes, result: &mut RestyleResult| {
13
            for (node_id, props) in changes {
4
                for change in &props {
2
                    let prop_type = change.current_prop.get_type();
2
                    let scope = prop_type.relayout_scope(true);
2
                    if scope > result.max_relayout_scope {
                        result.max_relayout_scope = scope;
2
                    }
2
                    if scope != RelayoutScope::None {
                        result.needs_layout = true;
                        result.gpu_only_changes = false;
2
                    }
2
                    if !prop_type.is_gpu_only_property() {
2
                        result.gpu_only_changes = false;
2
                    }
2
                    result.needs_display_list = true;
                }
2
                result
2
                    .changed_nodes
2
                    .entry(node_id)
2
                    .or_default()
2
                    .extend(props);
            }
11
        };
10
        if let Some(old) = lost {
5
            let changes = self.restyle_nodes_seat_focus(&[old], false);
5
            process(changes, &mut result);
5
        }
10
        if let Some(new) = gained {
6
            let changes = self.restyle_nodes_seat_focus(&[new], true);
6
            process(changes, &mut result);
6
        }
10
        result
10
    }
    /// Generic restyle method parameterized by the state field and pseudo-state type.
536
    fn restyle_nodes_state(
536
        &mut self,
536
        nodes: &[NodeId],
536
        new_state_value: bool,
536
        set_state: impl Fn(&mut StyledNodeState, bool),
536
        pseudo_state_type: azul_css::dynamic_selector::PseudoStateType,
536
    ) -> RestyleNodes {
        // Drop any stale NodeIds that no longer index into this DOM (e.g. left
        // over from a previous, larger tree). Indexing styled_nodes / node_data
        // with an out-of-range id would panic. Filtering here keeps the
        // downstream zip with `old_node_states` aligned.
536
        let node_count = self.node_count();
536
        let nodes: Vec<NodeId> = nodes
536
            .iter()
536
            .copied()
592
            .filter(|nid| nid.index() < node_count)
536
            .collect();
        // save the old node state
536
        let old_node_states = nodes
536
            .iter()
589
            .map(|nid| self.styled_nodes.as_container()[*nid].styled_node_state)
536
            .collect::<Vec<_>>();
1119
        for nid in &nodes {
583
            set_state(
583
                &mut self.styled_nodes.as_container_mut()[*nid].styled_node_state,
583
                new_state_value,
583
            );
583
        }
536
        let css_property_cache = self.get_css_property_cache();
536
        let styled_nodes = self.styled_nodes.as_container();
536
        let node_data = self.node_data.as_container();
        // scan all properties that could have changed because of addition / removal
536
        let v = nodes
536
            .iter()
536
            .zip(old_node_states.iter())
589
            .filter_map(|(node_id, old_node_state)| {
583
                let mut keys_normal: Vec<_> = CssPropertyCache::prop_types_for_state(
583
                    css_property_cache.css_props.get_slice(node_id.index()),
583
                    pseudo_state_type,
583
                ).collect();
583
                let mut keys_inherited: Vec<_> = CssPropertyCache::prop_types_for_state(
583
                    css_property_cache.cascaded_props.get_slice(node_id.index()),
583
                    pseudo_state_type,
583
                ).collect();
583
                let keys_inline: Vec<CssPropertyType> = {
                    use azul_css::dynamic_selector::DynamicSelector;
583
                    node_data[*node_id]
583
                        .style
583
                        .iter_inline_properties()
1932
                        .filter_map(|(prop, conds)| {
1824
                            let matches = conds.as_slice().iter().any(|c| {
1349
                                matches!(c, DynamicSelector::PseudoState(pst) if *pst == pseudo_state_type)
1349
                            });
1824
                            if matches {
475
                                Some(prop.get_type())
                            } else {
1349
                                None
                            }
1824
                        })
583
                        .collect()
                };
583
                let mut keys_inline_ref: Vec<_> = keys_inline.iter().collect();
583
                keys_normal.append(&mut keys_inherited);
583
                keys_normal.append(&mut keys_inline_ref);
583
                let node_properties_that_could_have_changed = keys_normal;
583
                if node_properties_that_could_have_changed.is_empty() {
106
                    return None;
477
                }
477
                let new_node_state = &styled_nodes[*node_id].styled_node_state;
477
                let node_data = &node_data[*node_id];
477
                let changes = node_properties_that_could_have_changed
477
                    .into_iter()
477
                    .filter_map(|prop| {
                        // calculate both the old and the new state
477
                        let old = css_property_cache.get_property_slow(
477
                            node_data,
477
                            node_id,
477
                            old_node_state,
477
                            prop,
                        );
477
                        let new = css_property_cache.get_property_slow(
477
                            node_data,
477
                            node_id,
477
                            new_node_state,
477
                            prop,
                        );
477
                        if old == new {
57
                            None
                        } else {
                            Some(ChangedCssProperty {
420
                                previous_state: *old_node_state,
420
                                previous_prop: old.map_or_else(|| CssProperty::auto(*prop), Clone::clone),
420
                                current_state: *new_node_state,
420
                                current_prop: new.map_or_else(|| CssProperty::auto(*prop), Clone::clone),
                            })
                        }
477
                    })
477
                    .collect::<Vec<_>>();
477
                if changes.is_empty() {
57
                    None
                } else {
420
                    Some((*node_id, changes))
                }
583
            })
536
            .collect::<Vec<_>>();
536
        v.into_iter().collect()
536
    }
    /// Unified entry point for all CSS restyle operations.
    ///
    /// This function synchronizes the `StyledNodeState` with runtime state
    /// and computes which CSS properties have changed. It determines whether
    /// layout, display list, or GPU-only updates are needed.
    ///
    /// # Arguments
    /// * `focus_changes` - Nodes gaining/losing focus
    /// * `hover_changes` - Nodes gaining/losing hover
    /// * `active_changes` - Nodes gaining/losing active (mouse down)
    ///
    /// # Returns
    /// * `RestyleResult` containing changed nodes and what needs updating
    #[must_use]
423
    pub fn restyle_on_state_change(
423
        &mut self,
423
        focus_changes: Option<FocusChange>,
423
        hover_changes: Option<HoverChange>,
423
        active_changes: Option<ActiveChange>,
423
    ) -> RestyleResult {
        // Start with GPU-only assumption; refined below as changes are analyzed.
423
        let mut result = RestyleResult {
423
            gpu_only_changes: true,
423
            ..RestyleResult::default()
423
        };
        // Helper closure to merge changes and analyze property categories
516
        let mut process_changes = |changes: RestyleNodes| {
934
            for (node_id, props) in changes {
836
                for change in &props {
418
                    let prop_type = change.current_prop.get_type();
                    // Use the granular RelayoutScope instead of the binary
                    // can_trigger_relayout(). We pass node_is_ifc_member = true
                    // conservatively: this means font/text property changes will
                    // produce IfcOnly (rather than None). Phase 2c can refine
                    // this by checking whether the node actually participates
                    // in an IFC.
418
                    let scope = prop_type.relayout_scope(/* node_is_ifc_member */ true);
                    // Track the highest scope seen
418
                    if scope > result.max_relayout_scope {
19
                        result.max_relayout_scope = scope;
399
                    }
                    // Any scope above None triggers layout
418
                    if scope != RelayoutScope::None {
19
                        result.needs_layout = true;
19
                        result.gpu_only_changes = false;
399
                    }
                    // Check if this is a GPU-only property
418
                    if !prop_type.is_gpu_only_property() {
399
                        result.gpu_only_changes = false;
399
                    }
                    // Any visual change needs display list update (unless GPU-only)
418
                    result.needs_display_list = true;
                }
418
                result
418
                    .changed_nodes
418
                    .entry(node_id)
418
                    .or_default()
418
                    .extend(props);
            }
516
        };
        // 1. Process focus changes
423
        if let Some(focus) = focus_changes {
236
            if let Some(old) = focus.lost_focus {
51
                let changes = self.restyle_nodes_focus(&[old], false);
51
                process_changes(changes);
186
            }
236
            if let Some(new) = focus.gained_focus {
216
                let changes = self.restyle_nodes_focus(&[new], true);
216
                process_changes(changes);
216
            }
187
        }
        // 2. Process hover changes
423
        if let Some(hover) = hover_changes {
149
            if !hover.left_nodes.is_empty() {
22
                let changes = self.restyle_nodes_hover(&hover.left_nodes, false);
22
                process_changes(changes);
127
            }
149
            if !hover.entered_nodes.is_empty() {
130
                let changes = self.restyle_nodes_hover(&hover.entered_nodes, true);
130
                process_changes(changes);
130
            }
274
        }
        // 3. Process active changes
423
        if let Some(active) = active_changes {
96
            if !active.deactivated.is_empty() {
20
                let changes = self.restyle_nodes_active(&active.deactivated, false);
20
                process_changes(changes);
77
            }
96
            if !active.activated.is_empty() {
77
                let changes = self.restyle_nodes_active(&active.activated, true);
77
                process_changes(changes);
77
            }
327
        }
        // If no changes, reset display_list flag
423
        if result.changed_nodes.is_empty() {
62
            result.needs_display_list = false;
62
            result.gpu_only_changes = false;
404
        }
        // If layout is needed, display list is also needed
423
        if result.needs_layout {
19
            result.needs_display_list = true;
19
            result.gpu_only_changes = false;
404
        }
423
        result
423
    }
    /// Overrides CSS properties for a single node from user code (typically a
    /// callback). Writes into `CssPropertyCache::user_overridden_properties`,
    /// which `get_property_slow` / `get_property_fast` / `get_computed_value`
    /// consult at higher priority than the static CSS cascade - making this
    /// the fast path for animating a handful of properties per frame.
    ///
    /// Passing `CssProperty::Initial` for a property removes any override for
    /// that type, restoring the cascaded value. Returns the set of
    /// `ChangedCssProperty` entries the caller can feed into the incremental
    /// restyle pipeline.
    #[must_use]
1623
    pub fn restyle_user_property(
1623
        &mut self,
1623
        node_id: &NodeId,
1623
        new_properties: &[CssProperty],
1623
    ) -> RestyleNodes {
1623
        let mut map = BTreeMap::default();
1623
        if new_properties.is_empty() {
1
            return map;
1622
        }
1622
        let node_count = self.node_data.as_ref().len();
1622
        if node_id.index() >= node_count {
1
            return map;
1621
        }
1621
        let node_data = self.node_data.as_container();
1621
        let node_data = &node_data[*node_id];
1621
        let node_states = &self.styled_nodes.as_container();
1621
        let old_node_state = &node_states[*node_id].styled_node_state;
1621
        let changes: Vec<ChangedCssProperty> = {
1621
            let css_property_cache = self.get_css_property_cache();
1621
            new_properties
1621
                .iter()
1621
                .filter_map(|new_prop| {
1621
                    let old_prop = css_property_cache.get_property_slow(
1621
                        node_data,
1621
                        node_id,
1621
                        old_node_state,
1621
                        &new_prop.get_type(),
                    );
1621
                    let old_prop = old_prop
1621
                        .map_or_else(|| CssProperty::auto(new_prop.get_type()), Clone::clone);
1621
                    if old_prop == *new_prop {
141
                        None
                    } else {
1480
                        Some(ChangedCssProperty {
1480
                            previous_state: *old_node_state,
1480
                            previous_prop: old_prop,
1480
                            // overriding a user property does not change the state
1480
                            current_state: *old_node_state,
1480
                            current_prop: new_prop.clone(),
1480
                        })
                    }
1621
                })
1621
                .collect()
        };
1621
        let css_property_cache_mut = self.get_css_property_cache_mut();
        // user_overridden_properties is built lazily (empty after StyledDom
        // construction). Grow to cover this node_id before indexing so the
        // override path works on any DOM, not just ones that already have
        // overrides from a prior mutation.
1621
        if css_property_cache_mut.user_overridden_properties.len() < node_count {
75
            css_property_cache_mut
75
                .user_overridden_properties
75
                .resize(node_count, Vec::new());
1546
        }
3242
        for new_prop in new_properties {
1621
            let prop_type = new_prop.get_type();
1621
            let vec = &mut css_property_cache_mut.user_overridden_properties[node_id.index()];
1621
            if new_prop.is_initial() {
                // CssProperty::Initial = remove overridden property
113
                if let Ok(idx) = vec.binary_search_by_key(&prop_type, |(k, _)| *k) {
112
                    vec.remove(idx);
112
                }
            } else {
1508
                match vec.binary_search_by_key(&prop_type, |(k, _)| *k) {
1348
                    Ok(idx) => vec[idx].1 = new_prop.clone(),
160
                    Err(idx) => vec.insert(idx, (prop_type, new_prop.clone())),
                }
            }
        }
        // The compact cache is a precomputed per-node array that the layout
        // getters read on their FAST PATH (`get_display`, `get_width`, ...)
        // BEFORE consulting `user_overridden_properties`. An override that
        // changes geometry would therefore be written, reported as changed,
        // and then ignored by layout — which is why a runtime
        // `display: none -> flex` patch (combobox list, popover, ribbon
        // gallery panel) left the node at zero size and invisible.
        //
        // REBUILD the cache rather than merely dropping it. The builder's
        // per-node walk applies `user_overridden_properties` as its last
        // step, so the rebuilt cache reflects the patch — and every consumer
        // that treats the compact cache as the source of truth keeps
        // working. Leaving it `None` until "the next full cascade" was a
        // trap: the font phase derives its requirements (font-stack
        // signature, font chains, the GC keep-set) from this cache, so the
        // very relayout that applies the patch resolved an EMPTY font world
        // — the chain cache was replaced with nothing and the patched-in
        // subtree's text laid out at zero size (the gallery panel opened as
        // an 18px blank strip). Overrides are user-interaction-rate, so the
        // rebuild is not a per-frame cost; the animation channel
        // (colour/opacity/transform) keeps the fast path untouched.
        // INHERITED paint props need the recompute too: a `color` override on
        // a container is READ by its text children through the precomputed
        // inheritance tables, so skipping the recompute left descendants at
        // the stale colour — a colour transition on a DIV animated nothing
        // visible (found by the css_anim_perf_transition damage law). The
        // per-tick animation channel avoids this whole fn via
        // `set_user_property_override_fast` + display-list patching.
1621
        if new_properties
1621
            .iter()
1621
            .any(|p| p.get_type().can_trigger_relayout() || p.get_type().is_inheritable())
1493
        {
1493
            self.recompute_inheritance_and_compact_cache();
1493
            self.get_css_property_cache_mut()
1493
                .invalidate_resolved_font_sizes();
1493
        }
        // The override layer is part of the resolved style whether or not the
        // compact cache was rebuilt above: a `color` override on a text node
        // changes what the display list paints without touching geometry.
1621
        let cache = self.get_css_property_cache_mut();
1621
        cache.cascade_epoch = cache.cascade_epoch.wrapping_add(1);
1621
        if !changes.is_empty() {
1480
            map.insert(*node_id, changes);
1480
        }
1621
        map
1623
    }
    /// Provide (or update) the window's `DynamicSelectorContext` - viewport
    /// size, theme, OS, media type - for this DOM's cascade.
    ///
    /// Inline conditional properties (`CssPropertyWithConditions` with
    /// viewport/@media/theme/OS selectors) evaluate against this context in
    /// BOTH production readers: `get_property_slow` (per lookup) and the
    /// compact-cache builder (at build time). A `StyledDom` created without
    /// one (`create` / `create_from_dom`) has NO context - non-pseudo
    /// conditions do not apply until a window adopts the DOM and calls this,
    /// which the layout funnel (`LayoutWindow::layout_and_generate_display_list`)
    /// does before every pass; one created through `create_with_context`
    /// (what the funnel's own producer, `LayoutWindow::style_user_dom_for`,
    /// uses) already cascaded under it.
    ///
    /// A context change re-runs exactly the parts of the cascade that read
    /// the context (theme-chain analysis 2026-09-12, item 1 — "a theme flip
    /// is a restyle"):
    ///
    /// * the author cascade, when the retained stylesheet has conditional rules (`@theme` /
    ///   `@media` / `@os` blocks, `env()` values) — those are baked at cascade time, so nothing
    ///   short of re-running it can move them; `restyle_retained` includes the tail below;
    /// * otherwise the tail — UA defaults, inheritance, compact cache, tags
    ///   ([`Self::recascade_ua_inheritance_and_compact`]) — when the THEME changed (the UA colour
    ///   defaults are themed) or when any node's resting style carries a conditional declaration
    ///   (`has_dynamic_conditions`: viewport / OS / theme selectors on inline properties, evaluated
    ///   by the compact builder and by the inheritance walk).
    ///
    /// For the common condition-free DOM under an unchanged theme a context
    /// change (a resize, a focus flip) costs one bool read. A DOM created
    /// with the context already installed (`create_with_context`) pays
    /// nothing at all here: the offer compares equal and returns.
10856
    pub fn set_dynamic_selector_context(
10856
        &mut self,
10856
        context: azul_css::dynamic_selector::DynamicSelectorContext,
10856
    ) {
        // Decided before the context is replaced; `None` (no window yet)
        // counts as a flip — the no-context cascade answered the light UA
        // table and dropped every conditional declaration, and only a
        // re-run can tell whether the real context agrees.
        let theme_changed;
        {
10856
            let cache = self.get_css_property_cache_mut();
10856
            let same = cache.dynamic_context.as_deref() == Some(&context);
10856
            cascade_trace(|| format!("dynamic context offered, unchanged={same}"));
10856
            if same {
2175
                return;
8681
            }
8681
            theme_changed = cache
8681
                .dynamic_context
8681
                .as_deref()
8681
                .is_none_or(|c| c.theme != context.theme);
8681
            cache.dynamic_context = Some(Box::new(context));
            // A new generation even when nothing below re-runs: a context
            // change is a cascade input, and the DL cache keys on this.
8681
            cache.cascade_epoch = cache.cascade_epoch.wrapping_add(1);
        }
        // Author-css @-rule conditions are baked at CASCADE time (restyle
        // drops non-matching rule blocks), so a context change must re-run
        // the author cascade — rebuilding the compact cache alone would
        // keep the stale rule selection. Only DOMs whose stylesheet
        // actually has conditional rules pay this. `env()` values are baked
        // the same way (resolved against the context's safe-area insets),
        // so a stylesheet using them counts as conditional too.
8681
        let author_conditional = self
8681
            .get_css_property_cache()
8681
            .retained_author_css
8681
            .rules
8681
            .as_ref()
8681
            .iter()
8681
            .any(azul_css::css::CssRuleBlock::depends_on_dynamic_context);
8681
        if author_conditional {
            // Full: author cascade + the tail. (`restyle_retained` is a no-op
            // for an empty sheet, but an empty sheet has no conditional
            // rules, so this arm is never reached with one.)
223
            self.restyle_retained();
223
            return;
8458
        }
8458
        let needs_recascade = theme_changed
212
            || self
212
                .get_css_property_cache()
212
                .compact_cache
212
                .as_ref()
212
                .is_none_or(|cc| cc.has_dynamic_conditions);
8458
        if needs_recascade {
8330
            self.recascade_ua_inheritance_and_compact();
8330
        }
10856
    }
    /// The viewport-size thresholds (widths, heights, logical px) at which
    /// any conditional styling in this DOM can flip: the author
    /// stylesheet's `@media (min-/max-width/height)` bounds plus every
    /// inline conditional property's `ViewportWidth`/`ViewportHeight`
    /// bounds (harvested by the compact-cache builder). Sorted, deduped.
    ///
    /// `None` when the compact cache has not been built yet (no styling
    /// pass) - callers should treat that as "unknown" and fall back to a
    /// conservative policy. The engine's resize decision uses this instead
    /// of the old hardcoded `CSS_BREAKPOINTS` guess list, which failed both
    /// ways: a widget breakpoint like the ribbon's 720px was not on it (so
    /// shrinking onto the mobile layout never regenerated), and its eight
    /// guessed thresholds fired ~66ms full regenerations on every drag
    /// across 640/768/1024/...
    #[must_use]
11
    pub fn viewport_breakpoints(&self) -> Option<(Vec<f32>, Vec<f32>)> {
11
        let cache = self.get_css_property_cache();
11
        let cc = cache.compact_cache.as_ref()?;
11
        let (mut w, mut h) = cache.retained_author_css.viewport_breakpoints();
11
        w.extend(cc.inline_viewport_w.iter().copied().map(f32::from_bits));
11
        h.extend(cc.inline_viewport_h.iter().copied().map(f32::from_bits));
11
        w.sort_by_key(|v| v.to_bits());
11
        w.dedup_by_key(|v| v.to_bits());
11
        h.sort_by_key(|v| v.to_bits());
11
        h.dedup_by_key(|v| v.to_bits());
11
        Some((w, h))
11
    }
    /// Migrate runtime CSS overrides (`user_overridden_properties`) from a
    /// previous generation's property cache onto this DOM, following the
    /// reconciliation node matches.
    ///
    /// State follows node identity across a `RefreshDom` rebuild - exactly
    /// like datasets (`diff::transfer_states`), scroll offsets and text
    /// cursors already do. Without this, every runtime patch
    /// (`set_css_property`) silently reverted on the next app-driven DOM
    /// rebuild: the ribbon's collapsed band and an open combobox/gallery
    /// panel "un-toggled" whenever any callback returned `RefreshDom` (the
    /// ribbon's own tab-click does), because the fresh cascade knows nothing
    /// of the old override layer.
    ///
    /// Rebuilds the compact cache when anything migrated, so the layout fast
    /// path sees the carried-over values immediately.
26
    pub fn migrate_user_overrides_from(
26
        &mut self,
26
        old_cache: &CssPropertyCache,
26
        node_moves: &[crate::diff::NodeMove],
26
    ) {
26
        let node_count = self.node_data.as_ref().len();
26
        let mut migrated_any = false;
244
        for m in node_moves {
218
            let Some(old_vec) = old_cache
218
                .user_overridden_properties
218
                .get(m.old_node_id.index())
218
                .filter(|v| !v.is_empty())
            else {
218
                continue;
            };
            let new_idx = m.new_node_id.index();
            if new_idx >= node_count {
                continue;
            }
            let old_vec = old_vec.clone();
            let cache = self.get_css_property_cache_mut();
            if cache.user_overridden_properties.len() < node_count {
                cache
                    .user_overridden_properties
                    .resize(node_count, Vec::new());
            }
            cache.user_overridden_properties[new_idx] = old_vec;
            migrated_any = true;
        }
26
        if migrated_any {
            self.recompute_inheritance_and_compact_cache();
            self.get_css_property_cache_mut()
                .invalidate_resolved_font_sizes();
26
        }
26
    }
    /// Reconstruct a plain [`Dom`](crate::dom::Dom) from a subtree of this
    /// styled DOM by cloning each node's [`NodeData`](crate::dom::NodeData)
    /// (ids/classes, inline CSS, callbacks, dataset - `RefAny`/`ImageRef`
    /// fields are refcounted handles, so nothing heavy is copied).
    ///
    /// `root`: the subtree root, or `None` for the DOM's root node.
    ///
    /// The returned `Dom` CARRIES THE STYLESHEETS: the cascade retains the
    /// author CSS (`CssPropertyCache::retained_author_css`), and it is
    /// re-attached to the returned root's `css` field - re-styling the
    /// reconstruction reproduces the on-screen cascade. For a NON-root
    /// subtree this is an approximation: selectors that depended on
    /// ancestors OUTSIDE the subtree (descendant combinators through cut-off
    /// parents, `:nth-child` against removed siblings) may match differently
    /// in the new document. When exact pixel parity matters, hand the whole
    /// `StyledDom` clone to the consumer instead (e.g.
    /// `Pdf::from_styled_dom_with_resources`), which skips re-cascading
    /// entirely.
    #[must_use]
12
    pub fn reconstruct_dom_subtree(&self, root: Option<NodeId>) -> Dom {
        use crate::dom::NodeData;
12
        let hierarchy = self.node_hierarchy.as_container();
12
        let node_data = self.node_data.as_container();
12
        let root_id = root.unwrap_or(NodeId::ZERO);
108
        let make_dom = |id: NodeId| -> Dom {
108
            Dom {
108
                root: node_data
108
                    .get(id)
108
                    .cloned()
108
                    .unwrap_or_else(NodeData::create_div),
108
                children: Vec::new().into(),
108
                css: Vec::new().into(),
108
                estimated_total_children: 0,
108
            }
108
        };
        // Iterative post-order: a node is folded into its parent via
        // `add_child` (which maintains `estimated_total_children`) once all
        // of its own children are assembled, so arbitrary depth cannot
        // overflow the stack.
12
        let mut result_stack: Vec<Dom> = vec![make_dom(root_id)];
12
        let mut visit_stack: Vec<(NodeId, Option<NodeId>)> = vec![(
12
            root_id,
12
            hierarchy
12
                .get(root_id)
12
                .and_then(|n| n.first_child_id(root_id)),
        )];
204
        while let Some((node, next_child)) = visit_stack.pop() {
204
            if let Some(child) = next_child {
                // Come back to `node` for the sibling AFTER `child`,
                // then descend into `child`.
96
                let sibling = hierarchy
96
                    .get(child)
96
                    .and_then(NodeHierarchyItem::next_sibling_id);
96
                visit_stack.push((node, sibling));
96
                result_stack.push(make_dom(child));
96
                visit_stack.push((
96
                    child,
96
                    hierarchy.get(child).and_then(|c| c.first_child_id(child)),
                ));
            } else {
108
                let Some(finished) = result_stack.pop() else {
                    break;
                };
108
                if let Some(parent) = result_stack.last_mut() {
96
                    parent.add_child(finished);
96
                } else {
12
                    let mut finished = finished;
12
                    let author_css = self.get_css_property_cache().retained_author_css.clone();
12
                    if !author_css.is_empty() {
12
                        finished.css = vec![author_css].into();
12
                    }
12
                    return finished;
                }
            }
        }
        // Unreachable for a well-formed hierarchy; degrade to an empty div.
        Dom::create_div()
12
    }
    /// Returns a HTML-formatted version of the DOM for easier debugging.
    ///
    /// For example, a DOM with a parent div containing a child div would return:
    ///
    /// ```xml,no_run,ignore
    /// <div id="hello">
    ///      <div id="test" />
    /// </div>
    /// ```
    #[must_use]
16
    pub fn get_html_string(&self, custom_head: &str, custom_body: &str, test_mode: bool) -> String {
16
        let css_property_cache = self.get_css_property_cache();
16
        let mut output = String::new();
        // After which nodes should a close tag be printed?
16
        let mut should_print_close_tag_after_node: BTreeMap<NodeId, Vec<(NodeId, usize)>> =
16
            BTreeMap::new();
16
        let should_print_close_tag_debug = self
16
            .non_leaf_nodes
16
            .iter()
46
            .filter_map(|p| {
46
                let parent_node_id = p.node_id.into_crate_internal()?;
46
                let mut total_last_child = None;
46
                recursive_get_last_child(
46
                    parent_node_id,
46
                    self.node_hierarchy.as_ref(),
46
                    &mut total_last_child,
                );
46
                let total_last_child = total_last_child?;
45
                Some((parent_node_id, (total_last_child, p.depth)))
46
            })
16
            .collect::<BTreeMap<_, _>>();
61
        for (parent_id, (last_child, parent_depth)) in should_print_close_tag_debug {
45
            should_print_close_tag_after_node
45
                .entry(last_child)
45
                .or_default()
45
                .push((parent_id, parent_depth));
45
        }
16
        let mut all_node_depths = self
16
            .non_leaf_nodes
16
            .iter()
46
            .filter_map(|p| {
46
                let parent_node_id = p.node_id.into_crate_internal()?;
46
                Some((parent_node_id, p.depth))
46
            })
16
            .collect::<BTreeMap<_, _>>();
46
        for (parent_node_id, parent_depth) in self
16
            .non_leaf_nodes
16
            .iter()
46
            .filter_map(|p| Some((p.node_id.into_crate_internal()?, p.depth)))
        {
315
            for child_id in parent_node_id.az_children(&self.node_hierarchy.as_container()) {
315
                all_node_depths.insert(child_id, parent_depth + 1);
315
            }
        }
331
        for node_id in self.node_hierarchy.as_container().linear_iter() {
            // A single-node DOM (or any node not reached as a non-leaf parent or
            // one of their children, e.g. a lone root) has no entry here; treat
            // its depth as 0 instead of panic-indexing the map.
331
            let depth = all_node_depths.get(&node_id).copied().unwrap_or(0);
331
            let node_data = &self.node_data.as_container()[node_id];
331
            let node_state = &self.styled_nodes.as_container()[node_id].styled_node_state;
331
            let tabs = String::from("    ").repeat(depth);
331
            output.push_str("\r\n");
331
            output.push_str(&tabs);
331
            output.push_str(&node_data.debug_print_start(css_property_cache, &node_id, node_state));
331
            if let Some(content) = node_data.get_node_type().format().as_ref() {
65
                output.push_str(content);
276
            }
331
            let node_has_children = self.node_hierarchy.as_container()[node_id]
331
                .first_child_id(node_id)
331
                .is_some();
331
            if !node_has_children {
286
                let node_data = &self.node_data.as_container()[node_id];
286
                output.push_str(&node_data.debug_print_end());
286
            }
331
            if let Some(close_tag_vec) = should_print_close_tag_after_node.get(&node_id) {
34
                let mut close_tag_vec = close_tag_vec.clone();
34
                close_tag_vec.sort_by(|a, b| b.1.cmp(&a.1)); // sort by depth descending
79
                for (close_tag_parent_id, close_tag_depth) in close_tag_vec {
45
                    let node_data = &self.node_data.as_container()[close_tag_parent_id];
45
                    let tabs = String::from("    ").repeat(close_tag_depth);
45
                    output.push_str("\r\n");
45
                    output.push_str(&tabs);
45
                    output.push_str(&node_data.debug_print_end());
45
                }
297
            }
        }
16
        if test_mode {
15
            output
        } else {
1
            format!(
1
                "
1
                <html>
1
                    <head>
1
                    <style>* {{ margin:0px; padding:0px; }}</style>
1
                    {custom_head}
1
                    </head>
1
                {output}
1
                {custom_body}
1
                </html>
1
            "
            )
        }
16
    }
    /// Returns nodes grouped by their rendering order (respects z-index and position).
    #[must_use]
2
    pub fn get_rects_in_rendering_order(&self) -> ContentGroup {
2
        Self::determine_rendering_order(
2
            self.non_leaf_nodes.as_ref(),
2
            &self.node_hierarchy.as_container(),
2
            &self.styled_nodes.as_container(),
2
            &self.node_data.as_container(),
2
            self.get_css_property_cache(),
        )
2
    }
    /// Returns the rendering order of the items (the rendering
    /// order doesn't have to be the original order)
3
    fn determine_rendering_order(
3
        non_leaf_nodes: &[ParentWithNodeDepth],
3
        node_hierarchy: &NodeDataContainerRef<'_, NodeHierarchyItem>,
3
        styled_nodes: &NodeDataContainerRef<'_, StyledNode>,
3
        node_data_container: &NodeDataContainerRef<'_, NodeData>,
3
        css_property_cache: &CssPropertyCache,
3
    ) -> ContentGroup {
3
        let children_sorted = non_leaf_nodes
3
            .iter()
3
            .filter_map(|parent| {
                Some((
3
                    parent.node_id,
3
                    sort_children_by_position(
3
                        parent.node_id.into_crate_internal()?,
3
                        node_hierarchy,
3
                        styled_nodes,
3
                        node_data_container,
3
                        css_property_cache,
                    ),
                ))
3
            })
3
            .collect::<Vec<_>>();
3
        let children_sorted: BTreeMap<NodeHierarchyItemId, Vec<NodeHierarchyItemId>> =
3
            children_sorted.into_iter().collect();
3
        let mut root_content_group = ContentGroup {
3
            root: NodeHierarchyItemId::from_crate_internal(Some(NodeId::ZERO)),
3
            children: Vec::new().into(),
3
        };
3
        fill_content_group_children(&mut root_content_group, &children_sorted);
3
        root_content_group
3
    }
    /// Replaces this `StyledDom` with default and returns the old value.
    #[must_use]
1
    pub fn swap_with_default(&mut self) -> Self {
1
        let mut new = Self::default();
1
        core::mem::swap(self, &mut new);
1
        new
1
    }
}
/// Same as `Dom`, but arena-based for more efficient memory layout and faster traversal.
#[derive(Debug, PartialEq, PartialOrd, Eq)]
pub struct CompactDom {
    /// The arena containing the hierarchical relationships (parent, child, sibling) of all nodes.
    pub node_hierarchy: NodeHierarchy,
    /// The arena containing the actual data (`NodeData`) for each node.
    pub node_data: NodeDataContainer<NodeData>,
    /// The ID of the root node of the DOM tree.
    pub root: NodeId,
}
impl CompactDom {
    /// Returns the number of nodes in this DOM.
    #[inline]
    #[must_use]
41738
    pub fn len(&self) -> usize {
41738
        self.node_hierarchy.as_ref().len()
41738
    }
    /// Returns `true` if this DOM has no nodes.
    #[inline]
    #[must_use]
3
    pub fn is_empty(&self) -> bool {
3
        self.node_hierarchy.as_ref().is_empty()
3
    }
}
impl From<Dom> for CompactDom {
38116
    fn from(dom: Dom) -> Self {
38116
        convert_dom_into_compact_dom(dom)
38116
    }
}
/// Converts a tree-based Dom into an arena-based `CompactDom` for efficient traversal.
#[must_use]
38558
pub fn convert_dom_into_compact_dom(mut dom: Dom) -> CompactDom {
    // note: somehow convert this into a non-recursive form later on!
757683
    fn convert_dom_into_compact_dom_internal(
757683
        dom: &mut Dom,
757683
        node_hierarchy: &mut [Node],
757683
        node_data: &mut Vec<NodeData>,
757683
        parent_node_id: NodeId,
757683
        node: Node,
757683
        cur_node_id: &mut usize,
757683
    ) {
        // - parent [0]
        //    - child [1]
        //    - child [2]
        //        - child of child 2 [2]
        //        - child of child 2 [4]
        //    - child [5]
        //    - child [6]
        //        - child of child 4 [7]
        // Write node into the arena here!
757683
        node_hierarchy[parent_node_id.index()] = node;
        // MOVE the node's inline `style` AND its `extra` (NodeDataExt) box instead of relying on
        // copy_special's `self.style.clone()` / `self.extra.clone()`. Both derived Clones lower to
        // indirect-jump jump tables that remill mis-lifts on the web backend: CssProperty's clone
        // comes back with discriminant 0 (drops simple inline CSS) and for COMPLEX values
        // (AzButton's gradient; the NodeDataExt attributes Vec) the mis-lifted clone
        // reads/writes wrong-sized data, which clobbers the adjacent `style` temporary →
        // "memory access out of bounds" later in the cascade (StyledDom::create → restyle's
        // inheritance loop reads the corrupted style). 2026-06-02:
        // copy_special_moving_complex mem::takes BOTH style+extra before copy_special, so
        // copy_special clones an EMPTY style + None extra (no broken clone runs) and
        // restores them after. (Extra was added after the AzButton ids/classes node — which
        // lazily allocates NodeDataExt — OOB'd even with the style-only take.) The Dom is
        // consumed here, so the move is correct.
757683
        let copy = dom.root.copy_special_moving_complex();
757683
        node_data[parent_node_id.index()] = copy;
757683
        *cur_node_id += 1;
757683
        let mut previous_sibling_id = None;
757683
        let children_len = dom.children.len();
757683
        for (child_index, child_dom) in dom.children.as_mut().iter_mut().enumerate() {
719125
            let child_node_id = NodeId::new(*cur_node_id);
719125
            let is_last_child = (child_index + 1) == children_len;
719125
            let child_dom_is_empty = child_dom.children.is_empty();
719125
            let child_node = Node {
719125
                parent: Some(parent_node_id),
719125
                previous_sibling: previous_sibling_id,
719125
                next_sibling: if is_last_child {
403796
                    None
                } else {
315329
                    Some(child_node_id + child_dom.estimated_total_children + 1)
                },
719125
                last_child: if child_dom_is_empty {
352284
                    None
                } else {
366841
                    Some(child_node_id + child_dom.estimated_total_children)
                },
            };
719125
            previous_sibling_id = Some(child_node_id);
            // recurse BEFORE adding the next child
719125
            convert_dom_into_compact_dom_internal(
719125
                child_dom,
719125
                node_hierarchy,
719125
                node_data,
719125
                child_node_id,
719125
                child_node,
719125
                cur_node_id,
            );
        }
        // AUTHORITATIVE last_child. The per-child `last_child` set at construction used
        // `child_node_id + estimated_total_children`, which is the last node of the
        // whole SUBTREE (its deepest descendant), NOT the last DIRECT child — wrong
        // whenever that last child has children of its own. It corrupted `last_child_id()`
        // and, through it, append_child (which spliced onto the wrong node). The loop
        // above already tracked `previous_sibling_id`, which now holds the real last
        // direct child (None if there were none), so overwrite with it. This runs for
        // every node including the root, so it also corrects the root's own computation.
757683
        node_hierarchy[parent_node_id.index()].last_child = previous_sibling_id;
757683
    }
    // Pre-allocate all nodes (+ 1 root node)
38558
    let sum_nodes = dom.fixup_children_estimated();
38558
    let mut node_hierarchy = vec![Node::ROOT; sum_nodes + 1];
38558
    let mut node_data = vec![NodeData::create_div(); sum_nodes + 1];
38558
    let mut cur_node_id = 0;
38558
    let root_node_id = NodeId::ZERO;
38558
    let root_node = Node {
38558
        parent: None,
38558
        previous_sibling: None,
38558
        next_sibling: None,
38558
        last_child: if dom.children.is_empty() {
1603
            None
        } else {
36955
            Some(root_node_id + dom.estimated_total_children)
        },
    };
38558
    convert_dom_into_compact_dom_internal(
38558
        &mut dom,
38558
        &mut node_hierarchy,
38558
        &mut node_data,
38558
        root_node_id,
38558
        root_node,
38558
        &mut cur_node_id,
    );
38558
    CompactDom {
38558
        node_hierarchy: NodeHierarchy {
38558
            internal: node_hierarchy,
38558
        },
38558
        node_data: NodeDataContainer {
38558
            internal: node_data,
38558
        },
38558
        root: root_node_id,
38558
    }
38558
}
/// #47: scope every node's inline css to its own subtree. Walks the tree in the
/// SAME pre-order `convert_dom_into_compact_dom` uses to assign flat `NodeIds`, so the
/// `[flat_id, flat_id + estimated_total_children]` range pushed onto each rule (via
/// `CssPath::push_front_scope`) matches the ids the cascade will later see. After
/// this, a node's `with_css`/`set_css` rules can only match nodes inside its subtree;
/// they can no longer leak to the whole tree. `fixup_children_estimated()` must
/// have run first so `estimated_total_children` is populated/exact.
1164286
fn scope_inline_css(dom: &mut Dom, next_id: &mut usize) {
1164286
    let start = *next_id;
1164286
    let end = start + dom.estimated_total_children;
1164286
    for css in dom.css.as_mut().iter_mut() {
172666
        for rule in css.rules.as_mut().iter_mut() {
172666
            // Bare-decl wrappers (INLINE priority, from set_css/with_css
172666
            // selector-less declarations) are scoped node-only so a non-root
172666
            // background can't leak to descendants (#47). A stylesheet's
172666
            // `* { ... }` (AUTHOR/UA priority) scopes to the SUBTREE - the
172666
            // classic `* { margin: 0 }` reset must reach every element of the
172666
            // mounted document, not just the mount root.
172666
            let node_only = rule.priority >= azul_css::css::rule_priority::INLINE;
172666
            rule.path.push_front_scope_for(start, end, node_only);
172666
        }
    }
1164286
    *next_id += 1;
1164286
    for child in dom.children.as_mut().iter_mut() {
1106914
        scope_inline_css(child, next_id);
1106914
    }
1164286
}
/// Recursively collect all CSS objects from a Dom tree (depth-first).
/// Inner (deeper) CSS objects come first, outer (shallower) CSS objects come last.
/// This means outer CSS has higher cascade priority when applied in order.
1164286
fn collect_css_from_dom(dom: &Dom, out: &mut Vec<Css>) {
    // First, recurse into children (inner CSS = lower priority)
2271201
    for child in &dom.children {
1106915
        collect_css_from_dom(child, out);
1106915
    }
    // Then, add this node's CSS objects (outer CSS = higher priority)
1336009
    for css in &dom.css {
171723
        out.push(css.clone());
171723
    }
1164286
}
/// Recursively strip CSS from all Dom nodes (sets css to empty vec).
/// Called after collecting CSS so the `CompactDom` doesn't carry CSS data.
1164282
fn strip_css_from_dom(dom: &mut Dom) {
1164282
    dom.css = Vec::new().into();
1164282
    for child in dom.children.as_mut().iter_mut() {
1106912
        strip_css_from_dom(child);
1106912
    }
1164282
}
13
fn fill_content_group_children(
13
    group: &mut ContentGroup,
13
    children_sorted: &BTreeMap<NodeHierarchyItemId, Vec<NodeHierarchyItemId>>,
13
) {
13
    if let Some(c) = children_sorted.get(&group.root) {
        // returns None for leaf nodes
5
        group.children = c
5
            .iter()
5
            .map(|child| ContentGroup {
8
                root: *child,
8
                children: Vec::new().into(),
8
            })
5
            .collect::<Vec<ContentGroup>>()
5
            .into();
8
        for c in group.children.as_mut() {
8
            fill_content_group_children(c, children_sorted);
8
        }
8
    }
13
}
5
fn sort_children_by_position(
5
    parent: NodeId,
5
    node_hierarchy: &NodeDataContainerRef<'_, NodeHierarchyItem>,
5
    rectangles: &NodeDataContainerRef<'_, StyledNode>,
5
    node_data_container: &NodeDataContainerRef<'_, NodeData>,
5
    css_property_cache: &CssPropertyCache,
5
) -> Vec<NodeHierarchyItemId> {
    use azul_css::props::layout::LayoutPosition::Absolute;
5
    let children_positions = parent
5
        .az_children(node_hierarchy)
8
        .map(|nid| {
8
            let position = css_property_cache
8
                .get_position(
8
                    &node_data_container[nid],
8
                    &nid,
8
                    &rectangles[nid].styled_node_state,
                )
8
                .and_then(|p| (*p).get_property_or_default())
8
                .unwrap_or_default();
8
            let id = NodeHierarchyItemId::from_crate_internal(Some(nid));
8
            (id, position)
8
        })
5
        .collect::<Vec<_>>();
5
    let mut not_absolute_children = children_positions
5
        .iter()
8
        .filter_map(|(node_id, position)| {
8
            if *position == Absolute {
                None
            } else {
8
                Some(*node_id)
            }
8
        })
5
        .collect::<Vec<_>>();
5
    let mut absolute_children = children_positions
5
        .iter()
8
        .filter_map(|(node_id, position)| {
8
            if *position == Absolute {
                Some(*node_id)
            } else {
8
                None
            }
8
        })
5
        .collect::<Vec<_>>();
    // Append the position:absolute children after the regular children
5
    not_absolute_children.append(&mut absolute_children);
5
    not_absolute_children
5
}
// calls get_last_child() recursively until the last child of the last child of the ... has been
// found
107
fn recursive_get_last_child(
107
    node_id: NodeId,
107
    node_hierarchy: &[NodeHierarchyItem],
107
    target: &mut Option<NodeId>,
107
) {
107
    match node_hierarchy[node_id.index()].last_child_id() {
49
        None => (),
58
        Some(s) => {
58
            *target = Some(s);
58
            recursive_get_last_child(s, node_hierarchy, target);
58
        }
    }
107
}
// ============================================================================
// DOM TRAVERSAL FOR MULTI-NODE SELECTION
// ============================================================================
/// Determine if `node_a` comes before `node_b` in document order.
///
/// Document order is defined as pre-order depth-first traversal order.
/// This is equivalent to the order nodes appear in HTML source.
///
/// ## Algorithm
/// 1. Find the path from root to each node
/// 2. Find the Lowest Common Ancestor (LCA)
/// 3. At the divergence point, the child that appears first in sibling order comes first
#[must_use]
25
pub fn is_before_in_document_order(
25
    hierarchy: &NodeHierarchyItemVec,
25
    node_a: NodeId,
25
    node_b: NodeId,
25
) -> bool {
25
    if node_a == node_b {
7
        return false;
18
    }
18
    let hierarchy = hierarchy.as_container();
    // Get paths from root to each node (stored as root-first order)
18
    let path_a = get_path_to_root(&hierarchy, node_a);
18
    let path_b = get_path_to_root(&hierarchy, node_b);
    // Find divergence point (last common ancestor)
18
    let min_len = path_a.len().min(path_b.len());
24
    for i in 0..min_len {
24
        if path_a[i] != path_b[i] {
            // Found divergence - check which sibling comes first
4
            let child_towards_a = path_a[i];
4
            let child_towards_b = path_b[i];
            // A smaller NodeId index means it was created earlier in DOM construction,
            // which means it comes first in document order for siblings
4
            return child_towards_a.index() < child_towards_b.index();
20
        }
    }
    // One path is a prefix of the other - the shorter path (ancestor) comes first
14
    path_a.len() < path_b.len()
25
}
/// Get the path from root to a node, returned in root-first order.
39
fn get_path_to_root(
39
    hierarchy: &NodeDataContainerRef<'_, NodeHierarchyItem>,
39
    node: NodeId,
39
) -> Vec<NodeId> {
39
    let mut path = Vec::new();
39
    let mut current = Some(node);
110
    while let Some(node_id) = current {
71
        path.push(node_id);
71
        current = hierarchy
71
            .get(node_id)
71
            .and_then(NodeHierarchyItem::parent_id);
71
    }
    // Reverse to get root-first order
39
    path.reverse();
39
    path
39
}
/// Collect all nodes between start and end (inclusive) in document order.
///
/// This performs a pre-order depth-first traversal starting from the root,
/// collecting nodes once we've seen `start` and stopping at `end`.
///
/// ## Parameters
/// * `hierarchy` - The node hierarchy
/// * `start_node` - First node in document order
/// * `end_node` - Last node in document order
///
/// ## Returns
/// Vector of `NodeIds` in document order, from start to end (inclusive)
#[must_use]
7
pub fn collect_nodes_in_document_order(
7
    hierarchy: &NodeHierarchyItemVec,
7
    start_node: NodeId,
7
    end_node: NodeId,
7
) -> Vec<NodeId> {
7
    if start_node == end_node {
2
        return vec![start_node];
5
    }
5
    let hierarchy_container = hierarchy.as_container();
5
    let hierarchy_slice = hierarchy.as_ref();
5
    let mut result = Vec::new();
5
    let mut in_range = false;
    // Pre-order DFS using a stack
    // We need to traverse in document order, which is pre-order DFS
5
    let mut stack: Vec<NodeId> = vec![NodeId::ZERO]; // Start from root
17
    while let Some(current) = stack.pop() {
        // Check if we've entered the range
16
        if current == start_node {
4
            in_range = true;
12
        }
        // Collect if in range
16
        if in_range {
12
            result.push(current);
12
        }
        // Check if we've exited the range
16
        if current == end_node {
4
            break;
12
        }
        // Push children in reverse order so they pop in correct order
        // (first child should be processed first)
12
        if let Some(item) = hierarchy_container.get(current) {
            // Get first child
12
            if let Some(first_child) = item.first_child_id(current) {
                // Collect all children by following next_sibling
6
                let mut children = Vec::new();
6
                let mut child = Some(first_child);
20
                while let Some(child_id) = child {
14
                    children.push(child_id);
14
                    child = hierarchy_container
14
                        .get(child_id)
14
                        .and_then(NodeHierarchyItem::next_sibling_id);
14
                }
                // Push in reverse order for correct DFS order
14
                for child_id in children.into_iter().rev() {
14
                    stack.push(child_id);
14
                }
6
            }
        }
    }
5
    result
7
}
/// Check if two `StyledDom`s are structurally equivalent for layout purposes.
///
/// Returns `true` if the DOMs have the same structure, node types, classes,
/// IDs, inline styles, and callback event registrations - meaning the
/// layout output would be identical.
///
/// Image callback nodes are compared by function pointer and `RefAny` type ID
/// rather than heap pointer, since each `layout()` call creates new `ImageRef`
/// allocations even when the callback is the same.
///
/// This is used to short-circuit the expensive layout pipeline when the DOM
/// hasn't actually changed (e.g., an animation timer fires but only the GL
/// texture content changed, not the DOM structure).
#[must_use]
9
pub fn is_layout_equivalent(old: &StyledDom, new: &StyledDom) -> bool {
    use crate::{dom::NodeType, resources::DecodedImage};
    // Quick check: node count must match
9
    let old_nodes = old.node_data.as_ref();
9
    let new_nodes = new.node_data.as_ref();
9
    if old_nodes.len() != new_nodes.len() {
2
        return false;
7
    }
    // Check hierarchy (parent/child/sibling structure)
7
    let old_hier = old.node_hierarchy.as_ref();
7
    let new_hier = new.node_hierarchy.as_ref();
7
    if old_hier.len() != new_hier.len() {
        return false;
7
    }
7
    if old_hier != new_hier {
1
        return false;
6
    }
    // Per-node comparison
15
    for (old_node, new_node) in old_nodes.iter().zip(new_nodes.iter()) {
        // Compare node type discriminant
15
        if core::mem::discriminant(&old_node.node_type)
15
            != core::mem::discriminant(&new_node.node_type)
        {
            return false;
15
        }
        // Compare node type content (with special handling for image callbacks)
15
        match (&old_node.node_type, &new_node.node_type) {
            (NodeType::Image(old_img), NodeType::Image(new_img)) => {
                match (old_img.get_data(), new_img.get_data()) {
                    (DecodedImage::Callback(old_cb), DecodedImage::Callback(new_cb)) => {
                        // Compare callback function pointer (stable across frames)
                        if old_cb.callback.cb != new_cb.callback.cb {
                            return false;
                        }
                        // Compare RefAny type ID (not instance pointer)
                        if old_cb.refany.get_type_id() != new_cb.refany.get_type_id() {
                            return false;
                        }
                    }
                    _ => {
                        // Raw images / GL textures: compare by pointer identity
                        if old_img != new_img {
                            return false;
                        }
                    }
                }
            }
            _ => {
15
                if old_node.node_type != new_node.node_type {
                    return false;
15
                }
            }
        }
        // Compare IDs and classes (now stored in attributes as AttributeType::Id/Class)
        {
            use crate::dom::AttributeType;
15
            let old_ids_classes: Vec<_> = old_node
15
                .attributes()
15
                .as_ref()
15
                .iter()
15
                .filter(|a| matches!(a, AttributeType::Id(_) | AttributeType::Class(_)))
15
                .collect();
15
            let new_ids_classes: Vec<_> = new_node
15
                .attributes()
15
                .as_ref()
15
                .iter()
15
                .filter(|a| matches!(a, AttributeType::Id(_) | AttributeType::Class(_)))
15
                .collect();
15
            if old_ids_classes != new_ids_classes {
1
                return false;
14
            }
        }
        // Compare inline CSS (direct layout input)
14
        if old_node.style != new_node.style {
            return false;
14
        }
        // Compare callback event types (affects hit-test tags)
        // We compare only event types, not function pointers or data
14
        let old_cbs = old_node.callbacks.as_ref();
14
        let new_cbs = new_node.callbacks.as_ref();
14
        if old_cbs.len() != new_cbs.len() {
            return false;
14
        }
14
        for (old_cb, new_cb) in old_cbs.iter().zip(new_cbs.iter()) {
            if old_cb.event != new_cb.event {
                return false;
            }
        }
        // Compare attributes (some affect layout, e.g. colspan)
14
        if old_node.attributes().as_ref() != new_node.attributes().as_ref() {
            return false;
14
        }
    }
    // Compare styled node states (hover/focus/active flags affect CSS resolution)
5
    let old_styled = old.styled_nodes.as_ref();
5
    let new_styled = new.styled_nodes.as_ref();
5
    if old_styled.len() != new_styled.len() {
        return false;
5
    }
5
    if old_styled != new_styled {
1
        return false;
4
    }
4
    true
9
}
#[cfg(test)]
#[path = "styled_dom_test.rs"]
mod styled_dom_test;