1
//! Handling Viewport Resizing and Layout Thrashing
2
//!
3
//! The viewport size is a fundamental input to the entire layout process.
4
//! A change in viewport size must trigger a relayout.
5
//!
6
//! 1. The `layout_document` function takes the `viewport` as an argument. The `LayoutCache` stores
7
//!    the `viewport` from the previous frame.
8
//! 2. The `reconcile_and_invalidate` function detects that the viewport has changed size
9
//! 3. This single change—marking the root as a layout root—forces a full top-down pass
10
//!    (`calculate_layout_for_subtree` starting from the root). This correctly recalculates all
11
//!    percentage-based sizes and repositions all elements according to the new viewport dimensions.
12
//! 4. The intrinsic size calculation (bottom-up) can often be skipped, as it's independent of the
13
//!    container size, which is a significant optimization.
14

            
15
use std::{
16
    collections::{BTreeMap, BTreeSet, HashMap},
17
    hash::{DefaultHasher, Hash, Hasher},
18
};
19

            
20
use crate::solver3::layout_tree::LayoutNodeId;
21

            
22
/// Floating-point comparison epsilon for cache size lookups.
23
/// Controls the tolerance for cache hit matching in the per-node multi-slot cache.
24
const CACHE_SIZE_EPSILON: f32 = 0.1;
25

            
26
use azul_core::{
27
    diff::NodeDataFingerprint,
28
    dom::{FormattingContext, NodeId, NodeType},
29
    geom::{LogicalPosition, LogicalRect, LogicalSize},
30
    styled_dom::{StyledDom, StyledNode},
31
};
32
use azul_css::{
33
    css::CssPropertyValue,
34
    props::{
35
        layout::{LayoutDisplay, LayoutHeight, LayoutOverflow, LayoutPosition, LayoutWritingMode},
36
        property::{CssProperty, CssPropertyType},
37
        style::StyleTextAlign,
38
    },
39
    LayoutDebugMessage, LayoutDebugMessageType,
40
};
41

            
42
use crate::{
43
    font_traits::{FontLoaderTrait, ParsedFontTrait, TextLayoutCache},
44
    solver3::{
45
        fc::{self, layout_formatting_context, LayoutConstraints, OverflowBehavior},
46
        geometry::PositionedRectangle,
47
        getters::{
48
            get_css_height, get_display_property, get_overflow_x, get_overflow_y,
49
            get_scrollbar_gutter_property, get_text_align, get_white_space_property,
50
            get_writing_mode, MultiValue,
51
        },
52
        layout_tree::{
53
            get_display_type, is_block_level, AnonymousBoxType, DirtyFlag, LayoutNode,
54
            LayoutNodeHot, LayoutTreeBuilder, SubtreeHash,
55
        },
56
        positioning::get_position_type,
57
        scrollbar::ScrollbarRequirements,
58
        sizing::calculate_used_size_for_node,
59
        LayoutContext, LayoutError, LayoutTree, Result,
60
    },
61
    text3::cache::AvailableSpace as Text3AvailableSpace,
62
};
63

            
64
// ============================================================================
65
// Per-Node Multi-Slot Cache (inspired by Taffy's 9+1 slot cache architecture)
66
//
67
// Instead of a global BTreeMap keyed by (node_index, available_size), each node
68
// gets its own deterministic cache with 9 measurement slots + 1 full layout slot.
69
// This eliminates O(log n) lookups, prevents slot collisions between MinContent/
70
// MaxContent/Definite measurements, and cleanly separates sizing from positioning.
71
//
72
// Reference: https://github.com/DioxusLabs/taffy — Cache struct in src/tree/cache.rs
73
// Azul improvement: cache is EXTERNAL (Vec<NodeCache> parallel to LayoutTree.nodes)
74
// rather than stored on the node, keeping LayoutNode slim and avoiding &mut tree
75
// for cache operations.
76
// ============================================================================
77

            
78
/// Determines whether `calculate_layout_for_subtree` should only compute
79
/// the node's size (for parent's sizing pass) or perform full layout
80
/// including child positioning.
81
///
82
/// Inspired by Taffy's `RunMode` enum. The two-mode approach enables the
83
/// classic CSS two-pass layout: Pass 1 (`ComputeSize`) measures all children,
84
/// Pass 2 (`PerformLayout`) positions them using the measured sizes.
85
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86
pub enum ComputeMode {
87
    /// Only compute the node's border-box size and baseline.
88
    /// Does NOT store child positions. Used in BFC Pass 1 (sizing).
89
    ComputeSize,
90
    /// Compute size AND position all children.
91
    /// Stores the full layout result including child positions.
92
    /// Used in BFC Pass 2 (positioning) and as the final layout step.
93
    PerformLayout,
94
}
95

            
96
/// Constraint classification for deterministic cache slot selection.
97
///
98
/// Inspired by Taffy's `AvailableSpace` enum. Each constraint type maps to a
99
/// different cache slot, preventing collisions between e.g. `MinContent` and
100
/// Definite measurements of the same node.
101
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102
pub enum AvailableWidthType {
103
    /// A definite pixel value (or percentage resolved to pixels).
104
    Definite,
105
    /// Shrink-to-fit: the smallest size that doesn't cause overflow.
106
    MinContent,
107
    /// Use all available space: the largest size the content can use.
108
    MaxContent,
109
}
110

            
111
/// Cache entry for sizing (`ComputeSize` mode) — stores NO positions.
112
///
113
/// This is the lightweight entry stored in the 9 measurement slots.
114
/// It records what constraints were provided and what size resulted,
115
/// enabling Taffy's "result matches request" optimization.
116
#[derive(Copy, Debug, Clone)]
117
pub struct SizingCacheEntry {
118
    /// The available size that was provided as input.
119
    pub available_size: LogicalSize,
120
    /// The computed border-box size (output).
121
    pub result_size: LogicalSize,
122
    /// Baseline for inline alignment (if applicable).
123
    pub baseline: Option<f32>,
124
    /// First child's escaped top margin (CSS 2.2 § 8.3.1).
125
    pub escaped_top_margin: Option<f32>,
126
    /// Last child's escaped bottom margin (CSS 2.2 § 8.3.1).
127
    pub escaped_bottom_margin: Option<f32>,
128
}
129

            
130
/// Cache entry for full layout (`PerformLayout` mode).
131
///
132
/// This is the single "final layout" slot. It includes child positions
133
/// (relative to parent's content-box) and overflow/scrollbar info.
134
#[derive(Debug, Clone)]
135
pub struct LayoutCacheEntry {
136
    /// The available size that was provided as input.
137
    pub available_size: LogicalSize,
138
    /// The computed border-box size (output).
139
    pub result_size: LogicalSize,
140
    /// Content overflow size (for scrolling).
141
    pub content_size: LogicalSize,
142
    /// Child positions relative to parent's content-box (NOT absolute).
143
    pub child_positions: Vec<(usize, LogicalPosition)>,
144
    /// First child's escaped top margin.
145
    pub escaped_top_margin: Option<f32>,
146
    /// Last child's escaped bottom margin.
147
    pub escaped_bottom_margin: Option<f32>,
148
    /// Scrollbar requirements for this node.
149
    pub scrollbar_info: ScrollbarRequirements,
150
}
151

            
152
/// Per-node cache entry with 9 measurement slots + 1 full layout slot.
153
///
154
/// Inspired by Taffy's `Cache` struct (9+1 slots per node). The deterministic
155
/// slot index is computed from the constraint combination, so entries never
156
/// clobber each other (unlike the old global `BTreeMap` where fixed-point
157
/// collisions were possible).
158
///
159
/// NOT stored on `LayoutNode` — lives in the external `LayoutCacheMap`.
160
#[derive(Debug, Clone)]
161
pub struct NodeCache {
162
    /// 9 measurement slots (Taffy's deterministic scheme):
163
    /// - Slot 0: both dimensions known
164
    /// - Slots 1-2: only width known (MaxContent/Definite vs `MinContent`)
165
    /// - Slots 3-4: only height known (MaxContent/Definite vs `MinContent`)
166
    /// - Slots 5-8: neither known (2×2 combos of width/height constraint types)
167
    pub measure_entries: [Option<SizingCacheEntry>; 9],
168

            
169
    /// 1 full layout slot (with child positions, overflow, baseline).
170
    /// Only populated after `PerformLayout`, not after `ComputeSize`.
171
    pub layout_entry: Option<LayoutCacheEntry>,
172

            
173
    /// Fast check for dirty propagation (Taffy optimization).
174
    /// When true, all slots are empty — ancestors are also dirty.
175
    pub is_empty: bool,
176

            
177
    /// The containing block this node was last laid out against. It is the
178
    /// PARENT's input to this node, not a result of the node's own content,
179
    /// so [`Self::clear`] keeps it.
180
    ///
181
    /// A dirty subtree re-solved on its own — a layout root below the tree
182
    /// root — must be handed the block its parent's pass handed it. The
183
    /// parent's final used size is not that block: an auto-height parent has
184
    /// grown by its overflowing content. A `height: 100%` body under an
185
    /// `<html>` that also holds a menu bar resolved against the viewport in
186
    /// the full pass and against the taller html in the partial one.
187
    pub last_containing_block: Option<super::geometry::ContainingBlock>,
188
}
189

            
190
impl Default for NodeCache {
191
304984
    fn default() -> Self {
192
304984
        Self {
193
304984
            measure_entries: [None, None, None, None, None, None, None, None, None],
194
304984
            layout_entry: None,
195
304984
            is_empty: true, // fresh cache is empty/dirty
196
304984
            last_containing_block: None,
197
304984
        }
198
304984
    }
199
}
200

            
201
impl NodeCache {
202
    /// Clear all cache entries, marking this node as dirty.
203
    ///
204
    /// `last_containing_block` survives: it describes the parent, which a
205
    /// dirty mark on this node does not change.
206
9808
    pub fn clear(&mut self) {
207
9808
        self.measure_entries = [None, None, None, None, None, None, None, None, None];
208
9808
        self.layout_entry = None;
209
9808
        self.is_empty = true;
210
9808
    }
211

            
212
    /// Compute the deterministic slot index from constraint dimensions.
213
    ///
214
    /// This is Taffy's slot selection scheme: given whether width/height are
215
    /// "known" (definite constraint provided by parent) and what type of
216
    /// constraint applies to the unknown dimension(s), we get a unique slot 0–8.
217
    ///
218
    /// TODO(superplan): currently unused — the layout cache only ever touches
219
    /// slot 0 (see the `get_size(0, ..)` / `store_size(0, ..)` call sites). This
220
    /// is the intended entry point for wiring the full 9-slot scheme.
221
    #[must_use]
222
101007
    pub fn slot_index(
223
101007
        width_known: bool,
224
101007
        height_known: bool,
225
101007
        width_type: AvailableWidthType,
226
101007
        height_type: AvailableWidthType,
227
101007
    ) -> usize {
228
101007
        match (width_known, height_known) {
229
86761
            (true, true) => 0,
230
            (true, false) => {
231
10190
                if width_type == AvailableWidthType::MinContent {
232
45
                    2
233
                } else {
234
10145
                    1
235
                }
236
            }
237
            (false, true) => {
238
138
                if height_type == AvailableWidthType::MinContent {
239
44
                    4
240
                } else {
241
94
                    3
242
                }
243
            }
244
            (false, false) => {
245
3918
                let w = usize::from(width_type == AvailableWidthType::MinContent);
246
3918
                let h = usize::from(height_type == AvailableWidthType::MinContent);
247
3918
                5 + w * 2 + h
248
            }
249
        }
250
101007
    }
251

            
252
    /// Classify a CONCRETE containing-block size into (measurement slot,
253
    /// canonicalized key). The call sites only have resolved `f32`s — the
254
    /// availability enums are gone by this depth — so "indefinite" is
255
    /// detected by value: non-finite or the ≥1e9 sentinel family.
256
    ///
257
    /// WHY THIS EXISTS (2026-08-08, measured on big.md): with everything
258
    /// collapsed onto slot 0, ~507 nodes were each sized TWICE per pass —
259
    /// the measure visit under an INDEFINITE height and the final visit
260
    /// under the resolved height — and the single slot ping-ponged between
261
    /// the two keys: 506 `h_qinf` + 508 `h_sinf` misses, a structural 100%
262
    /// miss rate on a pass where nothing changed. Separate slots per
263
    /// known/unknown combination make both visits hit from the second pass
264
    /// on; canonicalizing the indefinite axis to `f32::MAX` keeps the
265
    /// epsilon compare meaningful (`INFINITY - INFINITY` is NaN, which
266
    /// fails every `<` test and would turn a same-key lookup into a miss).
267
    #[must_use]
268
100500
    pub fn classify_size_key(containing_block_size: LogicalSize) -> (usize, LogicalSize) {
269
        const INDEFINITE: f32 = 1.0e9;
270
100500
        let w = containing_block_size.width;
271
100500
        let h = containing_block_size.height;
272
100500
        let w_known = w.is_finite() && w.abs() < INDEFINITE;
273
100500
        let h_known = h.is_finite() && h.abs() < INDEFINITE;
274
100500
        let slot = Self::slot_index(
275
100500
            w_known,
276
100500
            h_known,
277
100500
            AvailableWidthType::Definite,
278
100500
            AvailableWidthType::Definite,
279
        );
280
100500
        let key = LogicalSize {
281
100500
            width: if w_known { w } else { f32::MAX },
282
100500
            height: if h_known { h } else { f32::MAX },
283
        };
284
100500
        (slot, key)
285
100500
    }
286

            
287
    /// Look up a sizing cache entry, implementing Taffy's "result matches request"
288
    /// optimization: if the caller provides the result size as a known dimension
289
    /// (common in Pass1→Pass2 transitions), it's still a cache hit.
290
    #[must_use]
291
47936
    pub fn get_size(&self, slot: usize, known_dims: LogicalSize) -> Option<&SizingCacheEntry> {
292
47936
        if let Some(entry) = self.measure_entries[slot].as_ref() {
293
            // Exact match on input constraints
294
13061
            if (known_dims.width - entry.available_size.width).abs() < CACHE_SIZE_EPSILON
295
8887
                && (known_dims.height - entry.available_size.height).abs() < CACHE_SIZE_EPSILON
296
            {
297
8885
                return Some(entry);
298
4176
            }
299
34875
        }
300
        // "Result matches request" — if the caller provides the result size
301
        // as a known dimension, it's still a hit. This is the key optimization
302
        // that makes two-pass layout O(n): Pass 1 measures a node, Pass 2
303
        // provides the measured size as a constraint → automatic cache hit.
304
        // Valid only for a fully-definite query (both axes are real lengths),
305
        // and the matching entry may live in ANY slot — pass 1 stored its
306
        // result under the measure-constraint slot, not the definite one.
307
39051
        if known_dims.width < 1.0e9 && known_dims.height < 1.0e9 {
308
32778
            for entry in self.measure_entries.iter().flatten() {
309
6491
                if (known_dims.width - entry.result_size.width).abs() < CACHE_SIZE_EPSILON
310
2012
                    && (known_dims.height - entry.result_size.height).abs() < CACHE_SIZE_EPSILON
311
                {
312
12
                    return Some(entry);
313
6479
                }
314
            }
315
6273
        }
316
39039
        None
317
47936
    }
318

            
319
    /// Store a sizing result in the given slot.
320
52693
    pub const fn store_size(&mut self, slot: usize, entry: SizingCacheEntry) {
321
52693
        self.measure_entries[slot] = Some(entry);
322
52693
        self.is_empty = false;
323
52693
    }
324

            
325
    /// Look up the full layout cache entry.
326
    #[must_use]
327
52844
    pub fn get_layout(&self, known_dims: LogicalSize) -> Option<&LayoutCacheEntry> {
328
52844
        let entry = self.layout_entry.as_ref()?;
329
7695
        if (known_dims.width - entry.available_size.width).abs() < CACHE_SIZE_EPSILON
330
2403
            && (known_dims.height - entry.available_size.height).abs() < CACHE_SIZE_EPSILON
331
        {
332
172
            return Some(entry);
333
7523
        }
334
        // "Result matches request" for layout too
335
7523
        if (known_dims.width - entry.result_size.width).abs() < CACHE_SIZE_EPSILON
336
2011
            && (known_dims.height - entry.result_size.height).abs() < CACHE_SIZE_EPSILON
337
        {
338
11
            return Some(entry);
339
7512
        }
340
7512
        None
341
52844
    }
342

            
343
    /// Store a full layout result.
344
52659
    pub fn store_layout(&mut self, entry: LayoutCacheEntry) {
345
52659
        self.layout_entry = Some(entry);
346
52659
        self.is_empty = false;
347
52659
    }
348
}
349

            
350
/// External layout cache, parallel to `LayoutTree.nodes`.
351
///
352
/// `cache_map.entries[i]` holds the cache for `LayoutTree.nodes[i]`.
353
/// Stored on `LayoutCache` (persists across frames).
354
///
355
/// This is Azul's improvement over Taffy's on-node cache:
356
/// - `LayoutNode` stays slim (0 bytes overhead)
357
/// - No `&mut tree` needed to read/write cache entries
358
/// - Cache can be resized independently after reconciliation
359
/// - O(1) indexed lookup (Vec) instead of O(log n) (`BTreeMap`)
360
#[derive(Debug, Clone, Default)]
361
pub struct LayoutCacheMap {
362
    pub entries: Vec<NodeCache>,
363
}
364

            
365
impl LayoutCacheMap {
366
    /// Resize to match tree length after reconciliation.
367
    /// New nodes get empty (dirty) caches. Removed nodes' caches are dropped.
368
9195
    pub fn resize_to_tree(&mut self, tree_len: usize) {
369
9195
        self.entries.resize_with(tree_len, NodeCache::default);
370
9195
    }
371

            
372
    /// O(1) lookup by layout tree index.
373
    #[inline]
374
    #[must_use]
375
18
    pub fn get(&self, node_index: usize) -> &NodeCache {
376
18
        &self.entries[node_index]
377
18
    }
378

            
379
    /// O(1) mutable lookup by layout tree index.
380
    #[inline]
381
105308
    pub fn get_mut(&mut self, node_index: usize) -> &mut NodeCache {
382
105308
        &mut self.entries[node_index]
383
105308
    }
384

            
385
    /// Invalidate a node and propagate dirty flags upward through ancestors.
386
    ///
387
    /// Implements Taffy's early-stop optimization: propagation halts at the
388
    /// first ancestor whose cache is already empty (i.e., already dirty).
389
    /// This prevents redundant O(depth) propagation when multiple children
390
    /// of the same parent are dirtied.
391
244484
    pub fn mark_dirty(&mut self, node_index: usize, tree: &[LayoutNodeHot]) {
392
244484
        if node_index >= self.entries.len() {
393
2
            return;
394
244482
        }
395
244482
        let cache = &mut self.entries[node_index];
396
244482
        if cache.is_empty {
397
240485
            return; // Already dirty → ancestors are too
398
3997
        }
399
3997
        cache.clear();
400

            
401
        // Propagate upward (Taffy's early-stop optimization)
402
3997
        let mut current = tree.get(node_index).and_then(|n| n.parent);
403
4156
        while let Some(parent_idx) = current {
404
3087
            if parent_idx >= self.entries.len() {
405
1
                break;
406
3086
            }
407
3086
            let parent_cache = &mut self.entries[parent_idx];
408
3086
            if parent_cache.is_empty {
409
2927
                break; // Stop early — ancestor already dirty
410
159
            }
411
159
            parent_cache.clear();
412
159
            current = tree.get(parent_idx).and_then(|n| n.parent);
413
        }
414
244484
    }
415
}
416

            
417
/// The persistent cache that holds the layout state between frames.
418
// Independent per-pass state FLAGS, not a state machine to enum-ify: each
419
// bool is set by a different stage and read by a different consumer.
420
#[allow(clippy::struct_excessive_bools)]
421
#[derive(Debug, Clone, Default)]
422
pub struct LayoutCache {
423
    /// The fully laid-out tree from the previous frame. This is our primary cache.
424
    pub tree: Option<LayoutTree>,
425
    /// One-shot latch: the next `layout_document` call is a RESIZE-ONLY
426
    /// relayout of the SAME `StyledDom` object (set by the dll's
427
    /// `incremental_relayout_for_resize`, consumed unconditionally at entry).
428
    /// Skips reconcile + `cache_map` remap wholesale — see the Step-1 branch
429
    /// in `layout_document` for the contract and the dom-id sanity guard.
430
    pub resize_only_hint: bool,
431
    /// Census: did the LAST `layout_document` take the resize-only
432
    /// reconcile-skip branch? The external observable that distinguishes
433
    /// "skipped the walk" from "walked and found everything clean" (both
434
    /// produce identical pixels and identical reuse censuses).
435
    pub last_reconcile_was_skipped: bool,
436
    /// The last reconcile RAN and preserved the tree's structure exactly —
437
    /// zero fresh nodes, zero drops, indices stable. Content changes (a text
438
    /// edit reflowing its IFC) land here, and it is what lets the per-IFC
439
    /// display-list patch engage for them: unchanged nodes splice their
440
    /// items from the previous DL, only reflowed IFCs re-emit.
441
    pub last_reconcile_structure_preserved: bool,
442
    /// Whether the last display-list BUILD went through the per-IFC patch
443
    /// (splice + re-emit) rather than a full emission — the honest marker
444
    /// the `dl_text_patch` law reads.
445
    pub last_build_was_patched: bool,
446
    /// The PRECISE damage of the last patched build (logical px): old ∪ new
447
    /// bounds of every re-emitted or moved/resized node. A patched build may
448
    /// change the ITEM COUNT (the new text emits different runs), which
449
    /// makes the renderer's old-vs-new item diff bail to a full repaint —
450
    /// but the patch knows exactly what it touched, so the renderers prefer
451
    /// this when the diff gives up. `None` after a full emission.
452
    pub last_patch_damage: Option<Vec<LogicalRect>>,
453
    /// Monotonic count of display-list BUILDS, full or patched.
454
    ///
455
    /// A renderer
456
    /// remembers the value it last presented against, so
457
    /// [`Self::pending_patch_damage`] can hand it the damage of EVERY
458
    /// patched build since — not just the last one.
459
    pub build_seq: u64,
460
    /// `build_seq` of the last FULL emission (0 = none yet).
461
    ///
462
    /// A renderer that
463
    /// has not presented that build cannot use the patch log in its place:
464
    /// its own item diff against the list it last presented is the
465
    /// authority, and when that bails it repaints in full.
466
    pub last_full_build_seq: u64,
467
    /// `(build_seq, damage)` of the patched builds since the last full
468
    /// emission, oldest first.
469
    ///
470
    /// WHY A LOG: two patched builds can land between two presents — a
471
    /// callback's `set_css_property` patch followed, in the same pass, by
472
    /// the `RefreshDom` it returns (a structure-preserved relayout is a
473
    /// patched build too). Each build's damage is relative to the LAYOUT
474
    /// before it, so the second knows nothing about the rect the first
475
    /// vacated; when `last_patch_damage` was simply overwritten and the
476
    /// renderer's item diff bailed (the rebuild changed the item count),
477
    /// that rect was never repainted — the slider dragged a trail of
478
    /// thumbs. Cleared by every full emission (its item diff against the
479
    /// last presented list covers everything); bounded, and a renderer that
480
    /// fell behind the window repaints in full.
481
    pub patch_damage_log: Vec<(u64, Vec<LogicalRect>)>,
482
    /// The `DynamicSelectorContext` the cached display list was BUILT under.
483
    /// The structure-preserved patch arm requires the current context to be
484
    /// EQUAL: a cascade-external flip (viewport crossing an @media bound, a
485
    /// theme/OS change) restyles reused nodes without touching `NodeData` or
486
    /// `css_dirty`, so spliced items would serve the OLD styles (the
487
    /// blue-desktop-box-after-crossing-to-mobile bug).
488
    pub last_dynamic_context: Option<azul_css::dynamic_selector::DynamicSelectorContext>,
489
    /// `CssPropertyCache::cascade_epoch` of the DOM the cached display list
490
    /// was BUILT from. The structure-preserved patch arm requires the
491
    /// current DOM's epoch to be EQUAL — this subsumes the context equality
492
    /// above (every accepted context change bumps the epoch) and also
493
    /// catches restyles and user overrides, which leave the context alone.
494
    /// `last_dynamic_context` stays for the `AZ_PATCH_DEBUG` diagnostics.
495
    pub last_cascade_epoch: u64,
496
    /// `used_size` of every layout node as of the PREVIOUS pass — captured at
497
    /// the resize-skip branch (the pass overwrites `used_size` in the shared
498
    /// tree object). DL patching diffs these against the new sizes: a node
499
    /// whose size changed must re-emit its items (a translated background
500
    /// rect would be the wrong SIZE, not just the wrong place).
501
    pub previous_sizes: Vec<Option<LogicalSize>>,
502
    /// GRANULAR DIFF channel (task #15b, one-shot): per flattened `NodeId`,
503
    /// `true` = the pre-cascade DOM fingerprints proved this node AND every
504
    /// ancestor unchanged on BOTH tiers (structure + style). Reconcile may
505
    /// then reuse the old node's fingerprint after a cheap state-hash check
506
    /// instead of re-hashing node content — the diff feeds the later
507
    /// stages instead of being thrown away. Set by the dll's full-produce
508
    /// arm; consumed (taken) by `reconcile_and_invalidate`.
509
    pub dom_diff_clean: Option<Vec<bool>>,
510
    /// Census: fingerprint computations skipped via `dom_diff_clean` in the
511
    /// LAST reconcile — the external observable for the channel's tests.
512
    pub last_fingerprint_skips: usize,
513
    /// Presentation hint of the LAST pass, set ONLY when the DL patch fired:
514
    /// the dominant translation + exceptions. The CPU compositor turns it
515
    /// into a retained-pixmap blit + strip repaint (round 3). One-shot in
516
    /// spirit — the consumer must guard against re-application on the SAME
517
    /// display list (buffers-held retries re-run the present path).
518
    pub last_patch_move: Option<super::display_list::PatchMoveSummary>,
519
    /// Reconciliation census of the LAST pass: how many nodes were CLONED
520
    /// from the previous tree (warm shaped-text + intrinsic caches carried
521
    /// forward) vs built FRESH (no warm data). This pair is what makes cache
522
    /// reuse TESTABLE from outside solver3: `resize_relayout_bug.rs` asserts
523
    /// a same-DOM viewport resize reuses every node — the regression that
524
    /// motivated it (`old_tree = None` on any viewport change) re-shaped 917
525
    /// paragraphs and re-measured 1112 intrinsic widths per resize while
526
    /// every test still passed, because rebuilt-from-scratch produces the
527
    /// same pixels as reused, just ~130 ms slower.
528
    pub last_reconcile_reused: usize,
529
    /// See [`Self::last_reconcile_reused`].
530
    pub last_reconcile_fresh: usize,
531
    /// How many nodes the LAST pass actually recomputed intrinsic sizes for
532
    /// (the `intrinsic_dirty` set at the final `calculate_intrinsic_sizes`
533
    /// call). Same testability rationale as the reconcile census: the
534
    /// scrollbar-reflow loop used to mark EVERY node intrinsic-dirty
535
    /// (`(0..len).collect()`) — 75 ms re-measuring a whole document whose
536
    /// content had not changed — and no pixel test could see it, because
537
    /// recomputed intrinsics equal reused intrinsics.
538
    pub last_intrinsic_dirty: usize,
539
    /// The final, absolute positions of all nodes from the previous frame.
540
    pub calculated_positions: super::PositionVec,
541
    /// The viewport size from the last layout pass, used to detect resizes.
542
    pub viewport: Option<LogicalRect>,
543
    /// Stable scroll IDs computed from `node_data_hash` (layout index -> scroll ID)
544
    pub scroll_ids: HashMap<LayoutNodeId, u64>,
545
    /// Mapping from scroll ID to DOM `NodeId` for hit testing
546
    pub scroll_id_to_node_id: HashMap<u64, NodeId>,
547
    /// CSS counter values for each node and counter name.
548
    /// Key: (`layout_index`, `counter_name`), Value: counter value
549
    /// This stores the computed counter values after processing counter-reset and
550
    /// counter-increment.
551
    pub counters: HashMap<(usize, String), i32>,
552
    /// Cache of positioned floats for each BFC node (`layout_index` -> `FloatingContext`).
553
    /// This persists float positions across multiple layout passes, ensuring IFC
554
    /// children always have access to correct float exclusions even when layout is
555
    /// recalculated.
556
    pub float_cache: HashMap<usize, fc::FloatingContext>,
557
    /// Per-node multi-slot cache (inspired by Taffy's 9+1 architecture).
558
    /// External to `LayoutTree` — indexed by node index for O(1) lookup.
559
    /// Persists across frames; resized after reconciliation.
560
    pub cache_map: LayoutCacheMap,
561
    /// Snapshot of `calculated_positions` from the previous frame, used by the
562
    /// compositor to compute damage rects (old bounds vs new bounds).
563
    pub previous_positions: super::PositionVec,
564
    /// Cached display list keyed by `(root_subtree_hash, viewport)`.
565
    /// When the reconciled tree has the same root `subtree_hash` AND
566
    /// the same viewport as the cached one, the display list is
567
    /// returned as-is — skipping layout, positioning, and
568
    /// display-list generation entirely. Cleared whenever
569
    /// `mark_dirty` fires on any node (since the root's upstream
570
    /// invalidation chain clears its ancestors).
571
    /// The third key component (`u64`) is the GPU-key-population fingerprint
572
    /// (`GpuValueCache::dl_emission_fingerprint`): the emitted list is a
573
    /// function of which nodes carry transform/opacity keys, and diff-driven
574
    /// animation mints keys AFTER a layout pass — matching on (hash, viewport)
575
    /// alone served the pre-key list back and made animations invisible.
576
    /// The fourth (`u64`) is the scroll GEOMETRY fingerprint
577
    /// (`scroll_geometry_fingerprint`): scrollbar necessity/track layout and
578
    /// the `VirtualView` placeholder consume the `ScrollManager` snapshot, and a
579
    /// `VirtualView`'s published virtual size arrives ONLY through it — matching
580
    /// without it served the pre-publication list (no scrollbar) forever. Live
581
    /// scroll OFFSETS are deliberately excluded: they are GPU-animated so that
582
    /// scrolling never re-emits the list.
583
    /// Key = (root subtree hash, viewport, GPU-key-population fingerprint,
584
    /// scroll-geometry fingerprint, DL-INPUT fingerprint, list). The fifth
585
    /// component covers the inputs `layout_document` takes besides the DOM
586
    /// that change the emitted list: caret visibility + locations, text
587
    /// selections, IME preedit (`dl_input_fingerprint`). Without it a
588
    /// relayout right after a click served the PRE-CARET list verbatim - the
589
    /// caret only appeared when a blink tick rebuilt (2026-08-31).
590
    pub cached_display_list: Option<(
591
        SubtreeHash,
592
        LogicalRect,
593
        u64,
594
        u64,
595
        u64,
596
        std::sync::Arc<super::display_list::DisplayList>,
597
    )>,
598
    /// Raw pointer of the `StyledDom` from the previous layout pass.
599
    ///
600
    /// DIAGNOSTICS ONLY. This used to describe a fast path — same pointer plus
601
    /// same viewport means skip reconcile and return the cached display list —
602
    /// and that path was removed as unsound: each `regenerate_layout` builds a
603
    /// fresh `StyledDom`, and once the previous one is dropped the allocator
604
    /// frequently hands the new, DIFFERENT dom the same address, so a pointer
605
    /// match does not prove the content is unchanged. `layout_document`'s Step 0
606
    /// carries the full reasoning. The content-based skip that replaced it is
607
    /// the Step 1.1 structural-identity cache (root `subtree_hash` + viewport),
608
    /// which address reuse cannot fool. Do not reintroduce a pointer fast path.
609
    pub prev_dom_ptr: usize,
610
    pub prev_viewport: LogicalRect,
611
}
612

            
613
/// Approximate heap-byte breakdown of the solver3 `LayoutCache`.
614
#[derive(Copy, Debug, Clone, Default)]
615
pub struct Solver3CacheMemoryReport {
616
    pub tree_bytes: usize,
617
    pub tree_report: Option<super::layout_tree::LayoutTreeMemoryReport>,
618
    pub calculated_positions_bytes: usize,
619
    pub previous_positions_bytes: usize,
620
    pub scroll_ids_bytes: usize,
621
    pub scroll_id_to_node_id_bytes: usize,
622
    pub counters_bytes: usize,
623
    pub float_cache_bytes: usize,
624
    pub cache_map_bytes: usize,
625
    pub cached_display_list_bytes: usize,
626
    /// `GlyphInstance`s inside the cached DL's `Text` items — the offset
627
    /// COPIES of `glyph_runs` instances. Counter, not a byte total (the
628
    /// bytes are inside `cached_display_list_bytes`).
629
    pub cached_display_list_text_instances: usize,
630
    /// Item slots in the cached DL (each costs `size_of::<DisplayListItem>()`
631
    /// inline). Counter, not a byte total.
632
    pub cached_display_list_items: usize,
633
}
634

            
635
impl Solver3CacheMemoryReport {
636
    #[must_use]
637
5
    pub const fn total_bytes(&self) -> usize {
638
5
        self.tree_bytes
639
5
            + self.calculated_positions_bytes
640
5
            + self.previous_positions_bytes
641
5
            + self.scroll_ids_bytes
642
5
            + self.scroll_id_to_node_id_bytes
643
5
            + self.counters_bytes
644
5
            + self.float_cache_bytes
645
5
            + self.cache_map_bytes
646
5
            + self.cached_display_list_bytes
647
5
    }
648
}
649

            
650
/// What a renderer that last presented against `build_seq == consumed` still
651
/// has to repaint from patched builds, per [`LayoutCache::pending_patch_damage`].
652
#[derive(Debug, Clone, PartialEq)]
653
pub enum PendingPatchDamage {
654
    /// Nothing was built since the renderer's last present.
655
    None,
656
    /// Every build since then was patched, the chain is complete, and this
657
    /// is the union of their damage.
658
    Rects(Vec<LogicalRect>),
659
    /// A FULL emission happened since the renderer's last present.
660
    ///
661
    /// The log
662
    /// cannot stand in for that: the renderer's item diff against the list
663
    /// it last presented is the authority, and when that bails it repaints
664
    /// in full.
665
    FullBuildSincePresent,
666
    /// The renderer fell further behind than the log keeps: the damage is
667
    /// not known, repaint in full.
668
    Unknown,
669
}
670

            
671
/// How many patched builds the log keeps. A renderer presents after nearly
672
/// every build, so this is a bound on a pathological run of layouts between
673
/// presents, not a working set.
674
pub const PATCH_DAMAGE_LOG_CAP: usize = 16;
675

            
676
impl LayoutCache {
677
    /// A FULL emission happened: nothing patched is pending any more.
678
5971
    pub fn record_full_emission(&mut self) {
679
5971
        self.build_seq = self.build_seq.wrapping_add(1);
680
5971
        self.last_full_build_seq = self.build_seq;
681
5971
        self.last_build_was_patched = false;
682
5971
        self.last_patch_damage = None;
683
        // The mover blit belongs to the PATCHED list it was computed for; a
684
        // full emission invalidates it exactly like the patch rects. Callers
685
        // used to clear this themselves (regenerate_display_list_for_dom
686
        // does), but the Step-1.1 cache-hit and early-exit paths called only
687
        // this function and left a stale TranslateHint armed - neutralized
688
        // today by the Arc-pointer guard, but nothing pinned that.
689
5971
        self.last_patch_move = None;
690
5971
        self.patch_damage_log.clear();
691
5971
    }
692

            
693
    /// Record a PATCHED build's damage: the latest goes to `last_patch_damage`
694
    /// (what the frame report and the debug traces read) AND onto the log a
695
    /// renderer drains through [`Self::pending_patch_damage`].
696
45
    pub fn record_patch_damage(&mut self, rects: Vec<LogicalRect>) {
697
45
        self.build_seq = self.build_seq.wrapping_add(1);
698
45
        self.patch_damage_log.push((self.build_seq, rects.clone()));
699
45
        if self.patch_damage_log.len() > PATCH_DAMAGE_LOG_CAP {
700
26
            let excess = self.patch_damage_log.len() - PATCH_DAMAGE_LOG_CAP;
701
26
            self.patch_damage_log.drain(..excess);
702
26
        }
703
45
        self.last_patch_damage = Some(rects);
704
45
    }
705

            
706
    /// The damage of every patched build after the one a renderer last
707
    /// presented against (`consumed` = the `build_seq` it saw then).
708
    #[must_use]
709
21
    pub fn pending_patch_damage(&self, consumed: u64) -> PendingPatchDamage {
710
21
        if self.build_seq == consumed {
711
10
            return PendingPatchDamage::None;
712
11
        }
713
11
        if self.last_full_build_seq > consumed {
714
1
            return PendingPatchDamage::FullBuildSincePresent;
715
10
        }
716
        // Every build since `consumed` was patched, and the log is
717
        // consecutive from the last full emission on — so the chain is
718
        // complete exactly when its first entry is still logged.
719
10
        match self.patch_damage_log.first() {
720
10
            Some((oldest, _)) if *oldest <= consumed.wrapping_add(1) => {}
721
1
            _ => return PendingPatchDamage::Unknown,
722
        }
723
9
        let mut rects = Vec::new();
724
39
        for (seq, r) in &self.patch_damage_log {
725
30
            if *seq > consumed {
726
11
                rects.extend_from_slice(r);
727
22
            }
728
        }
729
9
        PendingPatchDamage::Rects(rects)
730
21
    }
731

            
732
    /// Drop all incremental-reuse state so the next `layout_document` lays the
733
    /// DOM out from scratch (cold path), as if no previous frame existed.
734
    ///
735
    /// Required before laying out a DOM whose `NodeIds` are NOT a stable evolution
736
    /// of whatever this (shared) cache last held — namely `VirtualView` / iframe
737
    /// child DOMs, which their callbacks rebuild wholesale on every invocation.
738
    /// Incremental reconciliation matches/reuses subtrees by `NodeId` + subtree
739
    /// hash; on a wholesale rebuild those `NodeIds` are reassigned, so reusing the
740
    /// prior tree can graft `NodeIds` that no longer exist in the new `StyledDom`
741
    /// (panic: out-of-bounds `node_data` index when the DOM shrinks — e.g. the map
742
    /// dropping tiles on zoom-out).
743
1227
    pub fn reset_incremental(&mut self) {
744
1227
        self.tree = None;
745
1227
        self.cache_map = LayoutCacheMap::default();
746
1227
        self.cached_display_list = None;
747
1227
        self.prev_dom_ptr = 0;
748
1227
        self.counters.clear();
749
1227
        self.float_cache.clear();
750
1227
    }
751

            
752
    /// Approximate heap bytes retained by this `LayoutCache`.
753
    #[must_use]
754
3
    pub fn memory_report(&self) -> Solver3CacheMemoryReport {
755
3
        let tree_report = self.tree.as_ref().map(LayoutTree::memory_report);
756
3
        let tree_bytes = tree_report
757
3
            .as_ref()
758
3
            .map_or(0, super::layout_tree::LayoutTreeMemoryReport::total_bytes);
759
        // cache_map: Vec<NodeCache>; NodeCache has 9 Option<SizingCacheEntry>
760
        // + 1 Option<LayoutCacheEntry>. Count filled layout entries' child_positions.
761
3
        let mut cache_map_bytes = self.cache_map.entries.capacity() * size_of::<NodeCache>();
762
7
        for e in &self.cache_map.entries {
763
4
            if let Some(le) = &e.layout_entry {
764
                cache_map_bytes +=
765
                    le.child_positions.capacity() * size_of::<(usize, LogicalPosition)>();
766
4
            }
767
        }
768
3
        let cached_dl = self
769
3
            .cached_display_list
770
3
            .as_ref()
771
3
            .map_or((0, 0, 0), |(_, _, _, _, _, dl)| dl.retained_bytes());
772
        Solver3CacheMemoryReport {
773
3
            tree_bytes,
774
3
            tree_report,
775
3
            calculated_positions_bytes: self.calculated_positions.len()
776
3
                * size_of::<LogicalPosition>(),
777
3
            previous_positions_bytes: self.previous_positions.len() * size_of::<LogicalPosition>(),
778
3
            scroll_ids_bytes: self.scroll_ids.len() * (size_of::<usize>() + size_of::<u64>()),
779
3
            scroll_id_to_node_id_bytes: self.scroll_id_to_node_id.len()
780
3
                * (size_of::<u64>() + size_of::<NodeId>()),
781
3
            counters_bytes: self
782
3
                .counters
783
3
                .iter()
784
3
                .map(|((_, name), _)| {
785
1
                    size_of::<(usize, String)>() + size_of::<i32>() + name.capacity()
786
1
                })
787
3
                .sum(),
788
3
            float_cache_bytes: self.float_cache.len() * 256, // conservative per-FC
789
3
            cache_map_bytes,
790
            // Real walk — this was a FLAT 2048 guess, which hid the DL's
791
            // per-Text-item glyph copies (20 B/painted glyph) entirely.
792
3
            cached_display_list_bytes: cached_dl.0,
793
3
            cached_display_list_text_instances: cached_dl.1,
794
3
            cached_display_list_items: cached_dl.2,
795
        }
796
3
    }
797
}
798

            
799
/// The result of a reconciliation pass.
800
#[derive(Debug, Default)]
801
pub struct ReconciliationResult {
802
    /// Set of nodes whose intrinsic size needs to be recalculated (bottom-up pass).
803
    pub intrinsic_dirty: BTreeSet<usize>,
804
    /// Set of layout roots whose subtrees need a new top-down layout pass.
805
    pub layout_roots: BTreeSet<usize>,
806
    /// Set of nodes that only need a paint/display-list update (no relayout).
807
    pub paint_dirty: BTreeSet<usize>,
808
    /// Nodes CLONED from the previous tree, warm data (shaped text, intrinsic
809
    /// widths) and all. The observable half of cache reuse — see
810
    /// [`LayoutCache::last_reconcile_reused`] for why this is load-bearing.
811
    pub reused_nodes: usize,
812
    /// Nodes built fresh (`create_node_from_dom`): genuinely new or
813
    /// Layout-dirty, with NO warm data. On a same-DOM relayout (a pure
814
    /// resize) this being anything but 0 means warm caches were thrown away.
815
    pub fresh_nodes: usize,
816
    /// The INDICES of those fresh nodes — the display-list patch re-emits
817
    /// exactly these (their previous items describe content that no longer
818
    /// exists: an edited text run, a same-count replace), instead of the
819
    /// whole intrinsic-dirty ancestor chain whose items are unchanged.
820
    pub fresh_indices: BTreeSet<usize>,
821
    /// Fingerprint computations skipped because the pre-cascade DOM diff
822
    /// proved the node (and its ancestors) unchanged. See
823
    /// `LayoutCache::dom_diff_clean`.
824
    pub fingerprint_skips: usize,
825
}
826

            
827
impl ReconciliationResult {
828
    /// Checks if any layout or paint work is needed.
829
    #[must_use]
830
10457
    pub fn is_clean(&self) -> bool {
831
10457
        self.intrinsic_dirty.is_empty()
832
502
            && self.layout_roots.is_empty()
833
112
            && self.paint_dirty.is_empty()
834
10457
    }
835

            
836
    /// Returns true if full layout work is needed for at least one node.
837
    #[must_use]
838
34
    pub fn needs_layout(&self) -> bool {
839
34
        !self.intrinsic_dirty.is_empty() || !self.layout_roots.is_empty()
840
34
    }
841

            
842
    /// Returns true if only paint work is needed (no layout).
843
    #[must_use]
844
16
    pub fn needs_paint_only(&self) -> bool {
845
16
        !self.needs_layout() && !self.paint_dirty.is_empty()
846
16
    }
847
}
848

            
849
/// Lift each layout root to the container that decides its slot.
850
///
851
/// A dirty FLEX / GRID ITEM cannot be laid out on its own: its size is
852
/// decided by its container's flex algorithm, and its siblings' slots move
853
/// with it. The same holds for an INLINE-LEVEL box (an inline-block, an
854
/// inline replaced element): its box sits on a line the parent's inline
855
/// formatting context lays out, and a size change re-breaks that line.
856
/// Promote such a root to its container, walking up through nested
857
/// containers (a flex item inside a flex item; an inline-block inside a
858
/// flex row). Block-flow siblings need no promotion: `reposition_clean_subtrees`
859
/// re-stacks them after the root is re-solved.
860
///
861
/// `node` yields a node's parent and formatting context; the reconcile calls
862
/// this on its tree builder, the css-dirty channel on the built tree - the
863
/// two producers of layout roots, which used to disagree (only the reconcile
864
/// promoted, so a `width` change delivered through the css-dirty channel
865
/// re-solved a flex item in place while its siblings kept their slots).
866
9560
pub(crate) fn promote_layout_roots_to_containers(
867
9560
    roots: &BTreeSet<usize>,
868
9560
    node: impl Fn(usize) -> Option<(Option<usize>, FormattingContext)>,
869
9560
) -> BTreeSet<usize> {
870
9560
    roots
871
9560
        .iter()
872
212421
        .map(|&idx| {
873
212421
            let mut root = idx;
874
1113559
            while let Some((Some(parent), own_fc)) = node(root) {
875
1090022
                let parent_fc = node(parent).map(|(_, fc)| fc);
876
                // Inline-level by its OWN context (an inline box, an
877
                // inline-block) — or by where it SITS: a box whose parent
878
                // establishes an inline formatting context is on one of that
879
                // context's lines whatever it establishes itself (an
880
                // `inline-flex` button, an `inline-grid`, a replaced element).
881
                // The own-context test alone missed exactly those: an
882
                // inline-flex button dirtied by a colour twin was re-solved
883
                // as its own root, under a definite containing-block height
884
                // the line would never have given it, and grew by its
885
                // line-height.
886
1090022
                let inline_level = matches!(
887
1090022
                    own_fc,
888
                    FormattingContext::Inline | FormattingContext::InlineBlock
889
895386
                ) || matches!(parent_fc, Some(FormattingContext::Inline));
890
1090022
                let parent_is_flex_or_grid = matches!(
891
1090022
                    parent_fc,
892
                    Some(FormattingContext::Flex | FormattingContext::Grid)
893
                );
894
1090022
                if !inline_level && !parent_is_flex_or_grid {
895
188884
                    break;
896
901138
                }
897
901138
                root = parent;
898
            }
899
212421
            root
900
212421
        })
901
9560
        .collect()
902
9560
}
903

            
904
/// After dirty subtrees are laid out, this repositions their clean siblings
905
/// without recalculating their internal layout. This is a critical optimization.
906
///
907
/// This function acts as a dispatcher, inspecting the parent's formatting context
908
/// and calling the appropriate repositioning algorithm. For complex layout modes
909
/// like Flexbox or Grid, this optimization is skipped, as a full relayout is
910
/// often required to correctly recalculate spacing and sizing for all siblings.
911
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
912
                                  // (or cross-type bindings that can't merge)
913
10456
pub fn reposition_clean_subtrees(
914
10456
    styled_dom: &StyledDom,
915
10456
    tree: &LayoutTree,
916
10456
    layout_roots: &BTreeSet<usize>,
917
10456
    calculated_positions: &mut super::PositionVec,
918
10456
) {
919
    // Find the unique parents of all dirty layout roots. These are the containers
920
    // where sibling positions need to be adjusted.
921
10456
    let mut parents_to_reposition = BTreeSet::new();
922
20953
    for &root_idx in layout_roots {
923
10497
        if let Some(parent_idx) = tree.get(LayoutNodeId::new(root_idx)).and_then(|n| n.parent) {
924
601
            parents_to_reposition.insert(parent_idx);
925
9896
        }
926
    }
927

            
928
11057
    for parent_idx in parents_to_reposition {
929
601
        let Some(parent_node) = tree.get(LayoutNodeId::new(parent_idx)) else {
930
            continue;
931
        };
932

            
933
        // Dispatch to the correct repositioning logic based on the parent's layout mode.
934
601
        match parent_node.formatting_context {
935
            // Cases that use simple block-flow stacking can be optimized.
936
600
            FormattingContext::Block { .. } | FormattingContext::TableRowGroup => {
937
600
                reposition_block_flow_siblings(
938
600
                    styled_dom,
939
600
                    parent_idx,
940
600
                    tree,
941
600
                    layout_roots,
942
600
                    calculated_positions,
943
600
                );
944
600
            }
945

            
946
1
            FormattingContext::Flex | FormattingContext::Grid => {
947
1
                // Taffy handles this, so if a child is dirty, the parent would have
948
1
                // already been marked as a layout_root and re-laid out by Taffy.
949
1
                // We do nothing here for Flex or Grid.
950
1
            }
951

            
952
            FormattingContext::Table | FormattingContext::TableRow => {
953
                // TODO: Table layout is interdependent. A change in one cell's size
954
                // can affect the entire column's width or row's height, requiring a
955
                // full relayout of the table. This optimization is skipped.
956
            }
957

            
958
            // Other contexts either don't contain children in a way that this
959
            // optimization applies (e.g., Inline, TableCell) or are handled by other
960
            // layout mechanisms (e.g., OutOfFlow).
961
            _ => { /* Do nothing */ }
962
        }
963
    }
964
10456
}
965

            
966
/// Convert `LayoutOverflow` to `OverflowBehavior`
967
/// CSS Overflow Module Level 3: initial value of `overflow` is `visible`.
968
// +spec:overflow:3a6297 - initial value 'visible', maps hidden/scroll/auto overflow behaviors
969
1194610
pub(crate) fn to_overflow_behavior(overflow: MultiValue<LayoutOverflow>) -> fc::OverflowBehavior {
970
1194610
    match overflow.unwrap_or(LayoutOverflow::Visible) {
971
1168096
        LayoutOverflow::Visible => fc::OverflowBehavior::Visible,
972
20538
        LayoutOverflow::Hidden | LayoutOverflow::Clip => fc::OverflowBehavior::Hidden,
973
520
        LayoutOverflow::Scroll => fc::OverflowBehavior::Scroll,
974
5456
        LayoutOverflow::Auto => fc::OverflowBehavior::Auto,
975
    }
976
1194610
}
977

            
978
/// Convert `StyleTextAlign` to `fc::TextAlign`
979
// +spec:text-alignment-spacing:43ea0a - text-align-all shorthand: aligns all lines except last
980
// (overridden by text-align-last)
981
53253
const fn style_text_align_to_fc(text_align: StyleTextAlign) -> fc::TextAlign {
982
53253
    match text_align {
983
53239
        StyleTextAlign::Start | StyleTextAlign::Left => fc::TextAlign::Start,
984
2
        StyleTextAlign::End | StyleTextAlign::Right => fc::TextAlign::End,
985
1
        StyleTextAlign::Center => fc::TextAlign::Center,
986
11
        StyleTextAlign::Justify => fc::TextAlign::Justify,
987
    }
988
53253
}
989

            
990
/// Collects DOM child IDs from the node hierarchy into a Vec.
991
///
992
/// This is a helper function that flattens the sibling iteration into a simple loop.
993
/// Children with `display: none` are filtered out since they generate no boxes.
994
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/counter/fixed-point cast
995
#[must_use]
996
260729
pub fn collect_children_dom_ids(styled_dom: &StyledDom, parent_dom_id: NodeId) -> Vec<NodeId> {
997
    // The same child list the tree builder lays out (`layout_children`:
998
    // DOM children, minus inline transient windows grafted elsewhere, plus
999
    // the ones grafted onto this parent) - so a panel dropped onto another
    // zone reads as a STRUCTURAL change here and its old position is not
    // kept. Then the display:none filter.
    // +spec:display-property:9f02c6 - display:none elements generate no boxes
    // +spec:display-property:3b507e - display:none excludes subtree from box tree
260729
    let children: Vec<NodeId> =
260729
        crate::solver3::layout_tree::layout_children(styled_dom, parent_dom_id)
260729
            .into_iter()
270617
            .filter(|&child_id| get_display_type(styled_dom, child_id) != LayoutDisplay::None)
260729
            .collect();
    // DEBUG (2026-06-02 children-None): record collected child count per parent
    // @0x40540+parent*4 (0xCC00_00NN). N=0 with first_child Some ⇒ get_display_type
    // mis-lift skipped them; N>0 ⇒ walk works. REVERT before commit.
    unsafe {
260729
        let pi = parent_dom_id.index();
260729
        if pi < 8 {
47118
            crate::az_mark(
47118
                (0x40540 + pi * 4) as u32,
47118
                (0xCC00_0000u32 | (children.len() as u32 & 0xffff)),
47118
            );
214218
        }
    }
260729
    children
260729
}
/// Repositions clean children within a simple block-flow layout (like a BFC or a
/// table-row-group). It stacks children along the main axis, preserving their
/// previously calculated cross-axis alignment.
601
pub fn reposition_block_flow_siblings(
601
    styled_dom: &StyledDom,
601
    parent_idx: usize,
601
    tree: &LayoutTree,
601
    layout_roots: &BTreeSet<usize>,
601
    calculated_positions: &mut super::PositionVec,
601
) {
601
    let Some(parent_node) = tree.get(LayoutNodeId::new(parent_idx)) else {
        return;
    };
601
    let dom_id = parent_node.dom_node_id.unwrap_or(NodeId::ZERO);
601
    let styled_node_state = styled_dom
601
        .styled_nodes
601
        .as_container()
601
        .get(dom_id)
601
        .map(|n| n.styled_node_state)
601
        .unwrap_or_default();
601
    let writing_mode = get_writing_mode(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
601
    let parent_pos = calculated_positions
601
        .get(parent_idx)
601
        .copied()
601
        .unwrap_or_default();
601
    let parent_bp = parent_node.box_props.unpack();
601
    let content_box_origin = LogicalPosition::new(
601
        parent_pos.x + parent_bp.padding.left,
601
        parent_pos.y + parent_bp.padding.top,
    );
601
    let mut main_pen = 0.0;
612
    for &child_idx in tree.children(parent_idx) {
612
        let Some(child_node) = tree.get(LayoutNodeId::new(child_idx)) else {
            continue;
        };
612
        let child_size = child_node.used_size.unwrap_or_default();
612
        let child_bp = child_node.box_props.unpack();
612
        let child_main_sum = child_bp.margin.main_sum(writing_mode);
612
        let margin_box_main_size = child_size.main(writing_mode) + child_main_sum;
612
        if layout_roots.contains(&child_idx) {
            // This child was DIRTY and has been correctly repositioned.
            // Update the pen to the position immediately after this child.
600
            let new_pos = match calculated_positions.get(child_idx) {
600
                Some(p) => *p,
                None => continue,
            };
600
            let main_axis_offset = if writing_mode.is_vertical() {
                new_pos.x - content_box_origin.x
            } else {
600
                new_pos.y - content_box_origin.y
            };
600
            main_pen = main_axis_offset
600
                + child_size.main(writing_mode)
600
                + child_bp.margin.main_end(writing_mode);
        } else {
            // This child is *clean*. Calculate its new position and shift its
            // entire subtree.
12
            let old_pos = match calculated_positions.get(child_idx) {
12
                Some(p) => *p,
                None => continue,
            };
12
            let child_main_start = child_bp.margin.main_start(writing_mode);
12
            let new_main_pos = main_pen + child_main_start;
12
            let old_relative_pos = tree
12
                .warm(LayoutNodeId::new(child_idx))
12
                .and_then(|w| w.relative_position)
12
                .unwrap_or_default();
12
            let cross_pos = if writing_mode.is_vertical() {
                old_relative_pos.y
            } else {
12
                old_relative_pos.x
            };
12
            let new_relative_pos =
12
                LogicalPosition::from_main_cross(new_main_pos, cross_pos, writing_mode);
12
            let new_absolute_pos = LogicalPosition::new(
12
                content_box_origin.x + new_relative_pos.x,
12
                content_box_origin.y + new_relative_pos.y,
            );
12
            if old_pos != new_absolute_pos {
2
                let delta = LogicalPosition::new(
2
                    new_absolute_pos.x - old_pos.x,
2
                    new_absolute_pos.y - old_pos.y,
2
                );
2
                shift_subtree_position(child_idx, delta, tree, calculated_positions);
12
            }
12
            main_pen += margin_box_main_size;
        }
    }
601
}
/// Helper to recursively shift the absolute position of a node and all its descendants.
521
fn shift_subtree_position(
521
    node_idx: usize,
521
    delta: LogicalPosition,
521
    tree: &LayoutTree,
521
    calculated_positions: &mut super::PositionVec,
521
) {
521
    if let Some(pos) = calculated_positions.get_mut(node_idx) {
516
        pos.x += delta.x;
516
        pos.y += delta.y;
516
    }
521
    if let Some(node) = tree.get(LayoutNodeId::new(node_idx)) {
519
        let children = tree.children(node_idx).to_vec();
1030
        for &child_idx in &children {
511
            shift_subtree_position(child_idx, delta, tree, calculated_positions);
511
        }
2
    }
521
}
/// Compares the new DOM against the cached tree, creating a new tree
/// and identifying which parts need to be re-laid out.
/// Count how many of the supplied DOM children would actually end up
/// in the layout tree. Mirrors the filters applied by
/// `LayoutTreeBuilder::build_recursive` so reconciliation can compare
/// like-for-like:
///
/// - `display: none` nodes are skipped entirely.
/// - In table structural contexts (table, row-group, row) whitespace text nodes are skipped (CSS
///   2.2 §17.2.1, matches `should_skip_for_table_structure`).
/// - Whitespace-only inline runs that sit between block siblings collapse to zero boxes (CSS 2.2
///   §9.2.2.1).
///
/// The first two rules drop children unconditionally; the third only
/// fires on siblings surrounding a block-level child, so we detect it
/// by walking the run pairs. We do not build the runs — just count
/// survivors.
260727
fn layout_relevant_child_count(
260727
    styled_dom: &StyledDom,
260727
    children: &[NodeId],
260727
    parent_id: NodeId,
260727
) -> usize {
    use super::{
        getters::{get_display_property, MultiValue},
        layout_tree::{is_block_level, is_whitespace_only_text},
    };
260727
    let parent_display = match get_display_property(styled_dom, Some(parent_id)) {
260727
        MultiValue::Exact(d) => d,
        _ => LayoutDisplay::Block,
    };
    // Table-structural parents drop whitespace per CSS 2.2 section 17.2.1;
    // flex/grid containers drop it per css-flexbox-1 section 4 /
    // css-grid-1 section 6 (whitespace-only anonymous items are not
    // rendered).
260727
    let is_table_structural = matches!(
260727
        parent_display,
        LayoutDisplay::Table
            | LayoutDisplay::InlineTable
            | LayoutDisplay::TableRowGroup
            | LayoutDisplay::TableHeaderGroup
            | LayoutDisplay::TableFooterGroup
            | LayoutDisplay::TableRow
            | LayoutDisplay::Flex
            | LayoutDisplay::InlineFlex
            | LayoutDisplay::Grid
            | LayoutDisplay::InlineGrid
    );
260727
    let has_any_block_child = children.iter().any(|&id| is_block_level(styled_dom, id));
260727
    let mut count = 0usize;
    // When parent has any block child, whitespace-only inline runs
    // surrounding blocks collapse. We approximate that by skipping
    // whitespace text whenever any block sibling exists.
260727
    let collapse_inline_whitespace = has_any_block_child;
529468
    for &id in children {
        // display:none drops
268741
        let display = match get_display_property(styled_dom, Some(id)) {
268741
            MultiValue::Exact(d) => d,
            _ => LayoutDisplay::Block,
        };
268741
        if matches!(display, LayoutDisplay::None) {
1
            continue;
268740
        }
        // Table-structural whitespace drops.
268740
        if is_table_structural && is_whitespace_only_text(styled_dom, id) {
284
            continue;
268456
        }
        // Whitespace-only inline run collapse when mixed with blocks.
268456
        if collapse_inline_whitespace
178784
            && !is_block_level(styled_dom, id)
35396
            && is_whitespace_only_text(styled_dom, id)
        {
16891
            continue;
251565
        }
251565
        count += 1;
    }
260727
    count
260727
}
/// # Errors
///
/// Returns a `LayoutError` if layout reconciliation fails.
8960
pub fn reconcile_and_invalidate<T: ParsedFontTrait>(
8960
    ctx: &mut LayoutContext<'_, T>,
8960
    cache: &LayoutCache,
8960
    viewport: LogicalRect,
8960
    // GRANULAR DIFF (see LayoutCache::dom_diff_clean) — taken by the
8960
    // caller (this fn only has &cache) and moved in.
8960
    dom_diff_clean: Option<Vec<bool>>,
8960
) -> Result<(LayoutTree, ReconciliationResult)> {
8960
    let _probe_outer = crate::probe::Probe::span("reconcile_and_invalidate");
8960
    let mut new_tree_builder = LayoutTreeBuilder::new(ctx.viewport_size);
8960
    let mut recon_result = ReconciliationResult::default();
    // A viewport SIZE change invalidates every VIEWPORT-DEPENDENT computed
    // size — and nothing else. The old code dropped the ENTIRE cached tree
    // here (`old_tree = None`), which made every node reconcile as brand-new
    // (`recon_old_tree_none` 1209/1209 on a same-DOM resize) and threw away
    // every warm handle with it: measured on big.md, ~54 ms of re-SHAPING
    // (917 `text_shape_stage` calls — shaping does not depend on the
    // viewport) plus ~75 ms of intrinsic-width recomputation (also
    // viewport-independent) per resize, ~130 ms of a 246 ms pass re-deriving
    // bit-identical results. That was the single largest reason a drag-resize
    // could not approach interactive rates (scripts/RSS_MAP §36,
    // ICON_CACHE_AND_RELAYOUT_REUSE §4).
    //
    // KEEPING the tree is sound because the things that DO depend on the
    // viewport re-derive through keys, not through tree identity:
    //
    //   * size/layout cache slots are KEYED by `containing_block_size`
    //     (`NodeCache::get_size/get_layout`) — the new viewport enters as the root containing block
    //     and every affected chain misses its key and recomputes. This is exactly the mechanism
    //     that fixed #9 "grey on resize" (an abs-positioned node's containing block IS the
    //     viewport, so its key changes); dropping the whole tree on top of it was belt-and-braces
    //     from before the keys existed.
    //   * conditional (@media-style) properties evaluate per pass against the dynamic-selector
    //     context (`style_cache` is rebuilt per `LayoutContext`), and shaping keys carry the
    //     RESOLVED font size — a viewport-relative font re-shapes via its changed content hash.
    //   * `layout_roots.insert(0)` below still forces the full top-down layout pass at the new
    //     size; reconciliation merely decides what that pass may REUSE (shaped runs, intrinsic
    //     widths), not whether it runs.
8960
    let viewport_resized = cache.viewport.is_none_or(|v| v.size != viewport.size);
8960
    let old_tree = cache.tree.as_ref();
8960
    if viewport_resized {
7250
        recon_result.layout_roots.insert(0); // Root is always index 0
7250
    }
8960
    let root_dom_id = ctx
8960
        .styled_dom
8960
        .root
8960
        .into_crate_internal()
8960
        .unwrap_or(NodeId::ZERO);
8960
    let clean_slice: Option<&[bool]> = dom_diff_clean
8960
        .as_deref()
8960
        .filter(|c| c.len() == ctx.styled_dom.node_data.as_ref().len());
8960
    let root_idx = reconcile_recursive(
8960
        ctx.styled_dom,
8960
        root_dom_id,
8960
        old_tree.map(|t| t.root),
8960
        None,
8960
        old_tree,
8960
        &mut new_tree_builder,
8960
        &mut recon_result,
8960
        ctx.debug_messages,
        false, // the root has no ancestor whose restyle could reach it
8960
        clean_slice,
    )?;
    // A dirty FLEX / GRID ITEM cannot be laid out on its own: its size is
    // decided by its container's flex algorithm, and its siblings' slots
    // move with it. Promote such a root to its container (walking up through
    // nested flex/grid containers). Without this the item was re-solved as
    // a standalone root with its own `min-height` while the container kept
    // the slot it had reserved from the item's content size — the TextArea
    // painted 64 px into a 36 px slot, over the widget beneath it. (The
    // `reposition_clean_subtrees` comment always claimed the parent would
    // "already be a layout root"; now it is.)
8960
    let promoted_layout_roots =
2201023
        promote_layout_roots_to_containers(&recon_result.layout_roots, |idx| {
2201023
            new_tree_builder
2201023
                .get(idx)
2201023
                .map(|n| (n.parent, n.formatting_context))
2201023
        });
8960
    recon_result.layout_roots = promoted_layout_roots;
    // Clean up layout roots: if a parent is a layout root, its children don't need to be.
8960
    let final_layout_roots = recon_result
8960
        .layout_roots
8960
        .iter()
17408
        .filter(|&&idx| {
17408
            let mut current = new_tree_builder.get(idx).and_then(|n| n.parent);
19001
            while let Some(p_idx) = current {
11109
                if recon_result.layout_roots.contains(&p_idx) {
9516
                    return false;
1593
                }
1593
                current = new_tree_builder.get(p_idx).and_then(|n| n.parent);
            }
7892
            true
17408
        })
8960
        .copied()
8960
        .collect();
8960
    recon_result.layout_roots = final_layout_roots;
8960
    new_tree_builder.apply_split_previews(ctx.content_overlay, ctx.styled_dom);
8960
    let new_tree = new_tree_builder.build(root_idx);
    // layout_document's step marker is stuck at 1 (post-`?` not reached), the
    // lifted `?` mis-discriminated this Ok as Err (niche-Result mis-lift).
8960
    {
8960
        let _ = (0xCC00_0001u32);
8960
    }
8960
    assert_dom_ids_are_in_range(&new_tree, ctx.styled_dom);
8960
    Ok((new_tree, recon_result))
8960
}
/// Every `dom_node_id` in a freshly reconciled tree must address a node of
/// the `StyledDom` it was reconciled against.
///
/// WHY THIS IS AN ASSERTION AND NOT A `Result`. A tree that survives with a
/// stale id does not fail — it succeeds at describing the WRONG node. Some
/// thirty display-list sites, the style getters, the hit-test areas and the
/// damage attribution all read `styled_dom` through this id, and each one
/// silently returns another node's data. The reported symptom was a ribbon
/// tab click repainting rects belonging to unrelated nodes; the only reason
/// it was ever caught is that `compute_counters` happened to index far
/// enough out of range to trip a bounds check. Checking the invariant once,
/// here, converts that whole class of silent corruption into one failure
/// that names the node.
///
/// Cost: one comparison per layout node, against a pass that does real work
/// per node.
9086
fn assert_dom_ids_are_in_range(tree: &LayoutTree, styled_dom: &StyledDom) {
9086
    let dom_len = styled_dom.node_data.as_container().internal.len();
262517
    for idx in 0..tree.nodes.len() {
262517
        let Some(dom_id) = tree.get(LayoutNodeId::new(idx)).and_then(|n| n.dom_node_id) else {
172
            continue;
        };
262345
        assert!(
262345
            dom_id.index() < dom_len,
            "layout node {idx} claims DOM node {} but the StyledDom it was reconciled against has \
             only {dom_len} nodes. A layout node's identity must come from the DOM node it was \
             reconciled AGAINST, never from one it merely reused measurements from (see \
             `clone_node_from_old`).",
            dom_id.index(),
        );
    }
260725
    for dom_id in tree.dom_to_layout.keys() {
260725
        assert!(
260725
            dom_id.index() < dom_len,
            "dom_to_layout maps DOM node {} but the StyledDom has only {dom_len} nodes - a lookup \
             through this map would hand out a layout index for a node that does not exist",
            dom_id.index(),
        );
    }
9086
}
/// CSS 2.2 § 9.2.2.1: Checks whether an inline run consists entirely of
/// whitespace-only text nodes, in which case it should NOT generate an
/// anonymous IFC wrapper in a BFC mixed-content context.
///
/// This prevents whitespace between block elements from creating empty
/// anonymous blocks that take up vertical space (regression c33e94b0).
///
/// Exception: if the parent (or any ancestor) has `white-space: pre`,
/// `pre-wrap`, or `pre-line`, whitespace IS significant and the wrapper
/// must still be created.
16964
fn is_whitespace_only_inline_run(
16964
    styled_dom: &StyledDom,
16964
    inline_run: &[(usize, NodeId)],
16964
    parent_dom_id: NodeId,
16964
) -> bool {
    use azul_css::props::style::text::StyleWhiteSpace;
16964
    if inline_run.is_empty() {
1
        return true;
16963
    }
    // Check if the parent preserves whitespace
16963
    let parent_state = &styled_dom.styled_nodes.as_container()[parent_dom_id].styled_node_state;
16963
    let white_space = match get_white_space_property(styled_dom, parent_dom_id, parent_state) {
16948
        MultiValue::Exact(ws) => Some(ws),
15
        _ => None,
    };
    // If white-space preserves whitespace, don't strip
16902
    if matches!(
16948
        white_space,
        Some(StyleWhiteSpace::Pre | StyleWhiteSpace::PreWrap | StyleWhiteSpace::PreLine)
    ) {
61
        return false;
16902
    }
    // Check that every node in the run is a whitespace-only text node
16902
    let binding = styled_dom.node_data.as_container();
33763
    for &(_, dom_id) in inline_run {
16967
        if let Some(data) = binding.get(dom_id) {
16967
            match data.get_node_type() {
16908
                NodeType::Text(text) => {
16908
                    let s = text.as_str();
16908
                    if !s
16908
                        .chars()
27544
                        .all(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0C'))
                    {
47
                        return false; // Non-whitespace text → must create wrapper
16861
                    }
                }
                _ => {
59
                    return false; // Non-text inline element → must create wrapper
                }
            }
        }
    }
16796
    true // All nodes are whitespace-only text
16964
}
/// Ordinal-match a freshly created anonymous inline wrapper to the old
/// parent's Nth anon wrapper and, when the run's children are IDENTICAL
/// (same dom ids, same order), carry the warm caches forward.
///
/// Anonymous wrappers have no `dom_node_id`, so ordinary reconciliation
/// cannot see them — every reconcile pass recreated them cold and flipped
/// their parent to `children_are_different = true` UNCONDITIONALLY, which put
/// every paragraph's parent into `intrinsic_dirty` + `layout_roots` on EVERY
/// pass (measured on big.md: 240 intrinsic IFC roots and 112 inline-content
/// re-collections per resize with a bit-identical DOM, ~12 ms). The ordinal
/// IS the identity: wrappers exist only for inline runs, runs are ordered by
/// child position, so the Nth wrapper under a node corresponds to the Nth run
/// — the same matching `layout_document`'s `cache_map` remap already performs
/// post-hoc for the size caches.
///
/// Only SELF-VALIDATING or content-derived caches are carried:
/// `inline_content_cache` re-validates itself against the subtree
/// fingerprint, and `intrinsic_sizes` are content-derived with the children
/// verified identical. Layout-derived state (`inline_layout_result`, used
/// sizes, baselines) stays `None` and re-derives through the CB-size-keyed
/// caches like any other clean node.
///
/// "Self-validating" is not the whole story, and the gap is worth naming: a
/// collection containing an atomic inline child also STANDS FOR that child's
/// layout, because the collection call is what sizes it — and that layout is
/// exactly the layout-derived state the line above deliberately drops. The
/// fingerprint cannot see this; it describes content, not whether anything has
/// been laid out. `layout_ifc` therefore re-checks that precondition where it
/// USES the cache (`atomic_inline_children_are_laid_out`), which is the only
/// place that can know, and the reason this function can go on carrying the
/// cache for the case it was measured on.
///
/// Returns whether the wrapper matched; the caller folds `!matched` into
/// `children_are_different` instead of flipping it unconditionally. A DIRTY
/// child inside a matched run still invalidates through that child's own
/// `mark_dirty` propagation — matching the wrapper never masks content edits.
162
fn try_reuse_anon_wrapper(
162
    old_tree: Option<&LayoutTree>,
162
    old_parent_idx: Option<usize>,
162
    anon_ordinal: usize,
162
    inline_run: &[(usize, NodeId)],
162
    new_tree_builder: &mut LayoutTreeBuilder,
162
    anon_idx: usize,
162
) -> bool {
162
    let (Some(t), Some(op)) = (old_tree, old_parent_idx) else {
117
        return false;
    };
    // Children live on the TREE (hot/warm/cold split), not the node struct.
45
    let Some(old_anon) = t
45
        .children(op)
45
        .iter()
45
        .copied()
79
        .filter(|&c| {
79
            t.cold(LayoutNodeId::new(c))
79
                .is_some_and(|cold| cold.anonymous_type == Some(AnonymousBoxType::InlineWrapper))
79
        })
45
        .nth(anon_ordinal)
    else {
1
        return false;
    };
44
    let old_anon_children = t.children(old_anon);
44
    if old_anon_children.len() != inline_run.len() {
        return false;
44
    }
44
    let ids_match = old_anon_children
44
        .iter()
44
        .zip(inline_run.iter())
106
        .all(|(&oc, &(_, nid))| {
106
            t.get(LayoutNodeId::new(oc)).and_then(|n| n.dom_node_id) == Some(nid)
106
        });
44
    if !ids_match {
        return false;
44
    }
44
    if let (Some(old_warm), Some(new_node)) = (
44
        t.warm(LayoutNodeId::new(old_anon)),
44
        new_tree_builder.get_mut(anon_idx),
44
    ) {
44
        // Carried unconditionally: `layout_ifc` re-checks the cache's OTHER
44
        // precondition (that the atomic inline children it stands for are laid
44
        // out in this tree) at the point of use, and re-collects if they are
44
        // not. See `atomic_inline_children_are_laid_out` in `fc.rs`.
44
        new_node
44
            .inline_content_cache
44
            .clone_from(&old_warm.inline_content_cache);
44
        new_node.intrinsic_sizes = old_warm.intrinsic_sizes;
44
    }
44
    true
162
}
/// Recursively traverses the new DOM and old tree, building a new tree and marking dirty nodes.
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/counter/fixed-point cast
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Errors
///
/// Returns a `LayoutError` if recursive reconciliation fails.
260725
pub fn reconcile_recursive(
260725
    styled_dom: &StyledDom,
260725
    new_dom_id: NodeId,
260725
    old_tree_idx: Option<usize>,
260725
    new_parent_idx: Option<usize>,
260725
    old_tree: Option<&LayoutTree>,
260725
    new_tree_builder: &mut LayoutTreeBuilder,
260725
    recon: &mut ReconciliationResult,
260725
    debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
260725
    ancestor_style_changed: bool,
260725
    // GRANULAR DIFF: per-NodeId "self+ancestors unchanged on both
260725
    // pre-cascade tiers". None = no diff available (full fingerprinting).
260725
    dom_diff_clean: Option<&[bool]>,
260725
) -> Result<usize> {
    // Cache the env check in a `OnceLock<bool>`: this branch
    // fires once per dirty node (hundreds on cold layout),
    // and a direct `env::var` is a mutex + hashmap lookup
    // on macOS (~100 ns/call) even when the env var is unset.
    static FP_DUMP_ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
260725
    let node_data = &styled_dom.node_data.as_container()[new_dom_id];
260725
    let old_cold =
260725
        old_tree.and_then(|t| old_tree_idx.and_then(|idx| t.cold(LayoutNodeId::new(idx))));
260725
    match (
260725
        old_tree.is_some(),
260725
        old_tree_idx.is_some(),
260725
        old_cold.is_some(),
260725
    ) {
209012
        (false, _, _) => drop(crate::probe::Probe::span("recon_old_tree_none")),
446
        (true, false, _) => drop(crate::probe::Probe::span("recon_old_idx_none")),
        (true, true, false) => drop(crate::probe::Probe::span("recon_cold_none")),
51267
        (true, true, true) => drop(crate::probe::Probe::span("recon_cold_some")),
    }
    // Compute the new multi-field fingerprint instead of a single hash —
    // UNLESS the pre-cascade DOM diff proved this node (and its ancestors)
    // unchanged on both tiers. The diff cannot see runtime STATE
    // (hover/focus applied after produce), so a skip still requires the
    // state hash to match the old fingerprint; content/inline/attr hashing
    // (the expensive part) is what gets skipped.
260725
    let diff_clean_here = dom_diff_clean
260725
        .and_then(|c| c.get(new_dom_id.index()))
260725
        .copied()
260725
        .unwrap_or(false);
260725
    let new_fingerprint = {
260725
        let mut reused: Option<NodeDataFingerprint> = None;
260725
        if diff_clean_here {
30
            if let Some(old_c) = old_cold {
30
                let state_hash = {
                    use core::hash::{Hash, Hasher};
30
                    let mut h = DefaultHasher::new();
30
                    if let Some(st) = styled_dom
30
                        .styled_nodes
30
                        .as_container()
30
                        .get(new_dom_id)
30
                        .map(|n| &n.styled_node_state)
30
                    {
30
                        st.hash(&mut h);
30
                    }
30
                    h.finish()
                };
30
                if state_hash == old_c.node_data_fingerprint.state_hash {
30
                    recon.fingerprint_skips += 1;
30
                    drop(crate::probe::Probe::span("fingerprint_skipped_by_diff"));
30
                    reused = Some(old_c.node_data_fingerprint);
30
                }
            }
260695
        }
260725
        if let Some(fp) = reused {
30
            fp
        } else {
260695
            let _p = crate::probe::Probe::span("fingerprint_compute");
260695
            NodeDataFingerprint::compute(
260695
                node_data,
260695
                styled_dom
260695
                    .styled_nodes
260695
                    .as_container()
260695
                    .get(new_dom_id)
260695
                    .map(|n| &n.styled_node_state),
            )
        }
    };
    // Compare fingerprints to determine what changed (Layout, Paint, or Nothing).
260725
    let dirty_flag = old_cold.map_or_else(
209458
        || {
209458
            drop(crate::probe::Probe::span("fp_new_node"));
209458
            DirtyFlag::Layout // new node → full layout
209458
        },
51267
        |old_c| {
51267
            let change_set = old_c.node_data_fingerprint.diff(&new_fingerprint);
51267
            if change_set.needs_layout() {
658
                drop(crate::probe::Probe::span("fp_needs_layout"));
658
                let enabled =
658
                    *FP_DUMP_ENABLED.get_or_init(|| std::env::var_os("AZ_FP_DUMP").is_some());
658
                if enabled {
                    use std::sync::atomic::{AtomicUsize, Ordering};
                    static DUMPED: AtomicUsize = AtomicUsize::new(0);
                    let n = DUMPED.fetch_add(1, Ordering::Relaxed);
                    if n < 10 {
                        eprintln!(
                            "[fp_diff {n}] dom={} old={:?} new={:?}",
                            new_dom_id.index(),
                            old_c.node_data_fingerprint,
                            new_fingerprint,
                        );
                    }
658
                }
658
                DirtyFlag::Layout
50609
            } else if change_set.needs_paint() {
10
                drop(crate::probe::Probe::span("fp_needs_paint"));
10
                DirtyFlag::Paint
            } else {
50599
                drop(crate::probe::Probe::span("fp_clean"));
50599
                DirtyFlag::None
            }
51267
        },
    );
    // INHERITANCE. `NodeDataFingerprint` describes ONE node: content,
    // state, inline CSS, classes, callbacks, attributes. Nothing in it
    // mentions the parent - so a child whose own data is untouched compares
    // CLEAN even when the style it INHERITS changed underneath it, and gets
    // cloned complete with the `inline_layout_result` that has the old
    // computed colour shaped into its glyphs. `layout_ifc` is then never
    // re-entered for that node, so the IFC content hash - which DOES
    // include colour - never gets a chance to reject the stale layout, and
    // the display-list builder paints straight out of it.
    //
    // Traced on the ribbon: clicking tab 1 makes tab 0's header
    // Layout-dirty (its classes and inline props both change) but leaves
    // its child text node at DirtyFlag::None, and the deactivated tab's
    // label keeps painting Word-blue #2B579A instead of #444444.
    //
    // A node re-cascades its descendants when the parts of its fingerprint
    // that can change a COMPUTED INHERITED value move: inline CSS (declares
    // them), ids/classes (select the rules that declare them), and the
    // styled state (:hover/:focus/:active variants). Content, callbacks and
    // attributes cannot, so a plain text edit still invalidates only its
    // own node and the incremental-edit path is untouched.
260725
    let own_style_changed = old_cold.is_none_or(|old_c| {
51267
        let old_fp = &old_c.node_data_fingerprint;
51267
        old_fp.inline_css_hash != new_fingerprint.inline_css_hash
51102
            || old_fp.ids_classes_hash != new_fingerprint.ids_classes_hash
51086
            || old_fp.state_hash != new_fingerprint.state_hash
51267
    });
260725
    let subtree_style_changed = ancestor_style_changed || own_style_changed;
    // An ancestor's restyle forces a REBUILD rather than a clone: the clone
    // is what carries the stale inline layout, so marking it paint-dirty
    // would repaint the wrong colour rather than re-resolve it.
    //
    // Only TEXT nodes need it. The staleness lives in shaped glyphs, which
    // only text produces; every other node re-reads its own computed style
    // from the cascade when the display list is built, and the cascade is
    // already correct (verified: the deactivated tab's DIV painted the right
    // background while its text child painted the old colour). Restricting
    // the rebuild to text nodes keeps the cost off the rest of the tree.
    // Measured (layout/tests/frame_perf.rs, release), baseline / unrestricted
    // / text-only:
    //   idle    19.35 / 20.11 / 19.25 ms
    //   resize  33.59 / 35.19 / 33.01 ms
    //   cold   140.97 / 148.01 / 137.12 ms
    // i.e. the unrestricted form cost 4-5%; restricted to text it is flat.
260725
    let dirty_flag =
260725
        if ancestor_style_changed && matches!(node_data.get_node_type(), NodeType::Text(_)) {
67697
            DirtyFlag::Layout
        } else {
193028
            dirty_flag
        };
260725
    let is_dirty = dirty_flag >= DirtyFlag::Paint;
    // M12.7: `|| old_tree.is_none()` — on COLD layout there is no old tree to
    // clone, so we MUST create a fresh node; taking the else-branch would hit
    // `ok_or(InvalidTree)` on a None old_tree. This is both semantically correct
    // AND robust against a mis-lifted `dirty_flag`/Option match (the suspected
    // niche-enum mis-discriminant) wrongly steering cold nodes into the else.
260725
    let new_node_idx = if dirty_flag >= DirtyFlag::Layout || old_tree.is_none() {
210120
        {
210120
            let _ = (0xBB00_0001u32);
210120
        }
210120
        recon.fresh_nodes += 1;
210120
        let idx = new_tree_builder.create_node_from_dom(
210120
            styled_dom,
210120
            new_dom_id,
210120
            new_parent_idx,
210120
            debug_messages,
        );
210120
        recon.fresh_indices.insert(idx);
        // Blockify replaced/inline flex-or-grid items (CSS Display 3 §2.7). The
        // full `process_node` build does this; this incremental path called
        // `create_node_from_dom` directly and skipped it, so a flex-item <img>
        // (e.g. the AzulPaint canvas) stayed inline and ignored flex-grow.
210120
        new_tree_builder.blockify_node_display(styled_dom, new_dom_id, idx, new_parent_idx);
210120
        idx
    } else {
50605
        {
50605
            let _ = (0xBB00_0002u32);
50605
        }
50605
        recon.reused_nodes += 1;
        // Paint-only or clean: clone the old node (preserving layout cache)
50605
        let old_full_node = old_tree
50605
            .and_then(|t| old_tree_idx.and_then(|idx| t.get_full_node(idx)))
50605
            .ok_or(LayoutError::InvalidTree)?;
        // The clone reuses the OLD node's measurements under the NEW node's
        // identity: `old_tree_idx` may have come from the positional
        // fallback below, in which case `old_full_node.dom_node_id` names a
        // different (or, after the DOM shrank, a nonexistent) node.
50605
        let mut idx =
50605
            new_tree_builder.clone_node_from_old(&old_full_node, new_parent_idx, Some(new_dom_id));
        // If paint-only change, update the fingerprint and dirty flag
50605
        if dirty_flag == DirtyFlag::Paint {
10
            if let Some(cloned) = new_tree_builder.get_mut(idx) {
10
                cloned.node_data_fingerprint = new_fingerprint;
10
                cloned.dirty_flag = DirtyFlag::Paint;
10
            }
50595
        }
50605
        idx
    };
    // reconcile_recursive sees it. 0 = correct (the first node); 64 (matching the
    // build-marker root_idx) = the usize return mis-reads here.
260725
    {
260725
        let _ = (0xAB00_0000u32 | (new_node_idx as u32 & 0xffff));
260725
    }
    // CRITICAL: For list-items, create a ::marker pseudo-element as the first child
    // This must be done after the node is created but before processing children
    // Per CSS Lists Module Level 3, ::marker is generated as the first child of list-items
    {
        use crate::solver3::getters::get_display_property;
260725
        let display = get_display_property(styled_dom, Some(new_dom_id)).exact();
260725
        if matches!(display, Some(LayoutDisplay::ListItem)) {
1580
            // Create ::marker pseudo-element for this list-item
1580
            new_tree_builder.create_marker_pseudo_element(styled_dom, new_dom_id, new_node_idx);
259145
        }
    }
    // Reconcile children to check for structural changes and build the new tree structure.
260725
    let mut new_children_dom_ids: Vec<_> = collect_children_dom_ids(styled_dom, new_dom_id);
    // CSS 2.2 §17.2.1: Filter whitespace-only text nodes from table structural elements
    // (table, row-group, row). Without this, the reconciler sees them as "inline" children
    // mixed with block-level <td>/<th>, triggering incorrect anonymous IFC wrapping.
    // The layout tree builder already does this via should_skip_for_table_structure().
    {
        use super::getters::{get_display_property, MultiValue};
260725
        let parent_display = match get_display_property(styled_dom, Some(new_dom_id)) {
260725
            MultiValue::Exact(d) => d,
            _ => LayoutDisplay::Block,
        };
259915
        if matches!(
260725
            parent_display,
            LayoutDisplay::Table
                | LayoutDisplay::InlineTable
                | LayoutDisplay::TableRowGroup
                | LayoutDisplay::TableHeaderGroup
                | LayoutDisplay::TableFooterGroup
                | LayoutDisplay::TableRow
        ) {
810
            new_children_dom_ids
1380
                .retain(|&id| !super::layout_tree::is_whitespace_only_text(styled_dom, id));
259915
        }
    }
    // Compute both positional and DOM-keyed lookups for the old
    // tree's children. The DOM-keyed map is authoritative for
    // reconciliation (positional drifts every time the layout-tree
    // builder drops a DOM child — whitespace text, display:none,
    // table-structural whitespace — or inserts an anonymous
    // wrapper that isn't in the DOM).
260725
    let old_children_indices: Vec<usize> = old_tree
260725
        .and_then(|t| old_tree_idx.map(|idx| t.children(idx).to_vec()))
260725
        .unwrap_or_default();
260725
    let old_children_by_dom: BTreeMap<NodeId, usize> = old_tree
260725
        .and_then(|t| old_tree_idx.map(|idx| {
51267
            t.children(idx).iter()
                // Pseudo-element nodes (::marker on list items) are
                // layout-SYNTHESIZED children that carry their originating
                // node's dom id without being DOM children. Counting them made
                // every <li> compare old=2 vs new=1 and flip
                // `children_are_different` on every reconcile (360 clean
                // parents re-dirtied per resize on big.md — the whole list
                // content re-measured each pass); keying them into the by-dom
                // map could also alias a marker as its own host during lookup.
51267
                .filter(|&&cidx| t.warm(LayoutNodeId::new(cidx)).is_none_or(|w| w.pseudo_element.is_none()))
51267
                .filter_map(|&cidx| t.get(LayoutNodeId::new(cidx)).and_then(|n| n.dom_node_id).map(|did| (did, cidx)))
51267
                .collect()
51267
        }))
260725
        .unwrap_or_default();
    // Count of old layout children that correspond to a real DOM node. The
    // old tree hides inline children UNDER anonymous wrappers, so the direct
    // children alone under-count every mixed-content parent (a wrapper is one
    // layout child holding N dom children) — the initializer then compared
    // old=1 against new=2 for a plain [text, div] parent and flipped
    // `children_are_different` on EVERY reconcile. That wrongness was masked
    // for as long as the wrapper sites flipped the flag unconditionally
    // anyway; ordinal-matched wrapper reuse unmasked it. Flatten wrappers:
    // count their dom-id'd children as if they were direct.
260725
    let old_layout_relevant_count = old_children_by_dom.len()
260725
        + old_tree.zip(old_tree_idx).map_or(0, |(t, oidx)| {
51267
            t.children(oidx)
51267
                .iter()
51267
                .copied()
51267
                .filter(|&c| {
50851
                    t.cold(LayoutNodeId::new(c)).is_some_and(|cold| {
50851
                        cold.anonymous_type == Some(AnonymousBoxType::InlineWrapper)
50851
                    })
50851
                })
51267
                .map(|w| {
44
                    t.children(w)
44
                        .iter()
106
                        .filter(|&&cc| {
106
                            t.get(LayoutNodeId::new(cc))
106
                                .and_then(|n| n.dom_node_id)
106
                                .is_some()
106
                        })
44
                        .count()
44
                })
51267
                .sum::<usize>()
51267
        });
    // Filter new DOM children to the subset the layout-tree builder
    // would actually emit. This mirrors `should_skip_for_table_structure`
    // and the `is_whitespace_only_inline_run` logic. Without this
    // filter, `children_are_different` fires on every reconcile
    // because the DOM has whitespace text nodes the layout tree
    // drops.
260725
    let new_layout_relevant_count =
260725
        layout_relevant_child_count(styled_dom, &new_children_dom_ids, new_dom_id);
260725
    if std::env::var_os("AZ_RECON_DEBUG").is_some()
        && old_tree.is_some()
        && new_layout_relevant_count != old_layout_relevant_count
    {
        eprintln!(
            "[recon] COUNT MISMATCH parent dom {:?}: old_relevant={} new_relevant={} \
             (direct_old={})",
            new_dom_id.index(),
            old_layout_relevant_count,
            new_layout_relevant_count,
            old_children_by_dom.len(),
        );
260725
    }
260725
    let mut children_are_different = new_layout_relevant_count != old_layout_relevant_count;
260725
    let mut new_child_hashes = Vec::new();
    // +spec:display-property:42f9c0 - anonymous block boxes wrap inline runs when block container
    // has mixed block/inline children CSS 2.2 Section 9.2.1.1: Anonymous Block Boxes
    // When a block container has mixed block/inline children, we must:
    // 1. Wrap consecutive inline children in anonymous block boxes
    // 2. Leave block-level children as direct children
260725
    let has_block_child = new_children_dom_ids
260725
        .iter()
260725
        .any(|&id| is_block_level(styled_dom, id));
    // CSS Flexbox §4 / Grid §6: every in-flow child of a flex/grid container
    // becomes a (blockified) flex/grid item. Anonymous-block wrapping of inline
    // runs is a BLOCK-container concept and must NOT apply here — otherwise an
    // inline-level child (e.g. an <img> with flex-grow, default display
    // inline-block) gets wrapped in an anonymous IFC block, so it's no longer a
    // direct flex item and its flex-grow is ignored (laid out 300×0). Processing
    // each child directly lets `blockify_node_display` (in create_node_from_dom)
    // see the flex/grid parent and blockify the child into a real flex item.
260725
    let parent_is_flex_or_grid = matches!(
260725
        get_display_type(styled_dom, new_dom_id),
        LayoutDisplay::Flex
            | LayoutDisplay::InlineFlex
            | LayoutDisplay::Grid
            | LayoutDisplay::InlineGrid
    );
260725
    if !has_block_child || parent_is_flex_or_grid {
        // All children are inline (block container) OR the parent is a flex/grid
        // container (all children are direct items) — no anonymous boxes needed.
        // Process each child directly.
246312
        for (i, &new_child_dom_id) in new_children_dom_ids.iter().enumerate() {
            // css-flexbox-1 section 4 / css-grid-1 section 6: an anonymous
            // flex/grid item that contains only white space is not rendered.
            // Without this, every newline between a grid container's <div>
            // children became a real grid item and consumed an auto-placement
            // cell (grid-minmax-fr-001 rendered 0-height phantom items and
            // pushed real items into implicit rows).
211468
            if parent_is_flex_or_grid
126216
                && super::layout_tree::is_whitespace_only_text(styled_dom, new_child_dom_id)
            {
284
                continue;
211184
            }
            // DOM-ID match rather than positional — tree builder
            // may have dropped some DOM children (whitespace text
            // nodes) so positional drift mis-aligns the cache.
            // DOM-id match only: positional fallback would align
            // anonymous wrappers against real DOM nodes and trigger
            // spurious fingerprint mismatches (see fp_diff dump).
211184
            let old_child_idx = old_children_by_dom.get(&new_child_dom_id).copied();
211184
            let reconciled_child_idx = reconcile_recursive(
211184
                styled_dom,
211184
                new_child_dom_id,
211184
                old_child_idx,
211184
                Some(new_node_idx),
211184
                old_tree,
211184
                new_tree_builder,
211184
                recon,
211184
                debug_messages,
211184
                subtree_style_changed,
211184
                dom_diff_clean,
            )?;
211184
            if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
211184
                new_child_hashes.push(child_node.subtree_hash.0);
211184
            }
211184
            if old_tree.and_then(|t| {
29167
                t.cold(LayoutNodeId::new(old_child_idx?))
28847
                    .map(|n| n.subtree_hash)
211184
            }) != new_tree_builder
211184
                .get(reconciled_child_idx)
211184
                .map(|n| n.subtree_hash)
184598
            {
184598
                children_are_different = true;
184598
            }
        }
    } else {
        // Mixed content: block and inline children
        // We must create anonymous block boxes around consecutive inline runs
14413
        if let Some(msgs) = debug_messages.as_mut() {
10936
            msgs.push(LayoutDebugMessage::info(format!(
10936
                "[reconcile_recursive] Mixed content in node {}: creating anonymous IFC wrappers",
10936
                new_dom_id.index()
10936
            )));
11006
        }
14413
        let mut inline_run: Vec<(usize, NodeId)> = Vec::new(); // (dom_child_index, dom_id)
                                                               // Which inline run (== which
                                                               // anon-wrapper ordinal) we're on —
                                                               // the
                                                               // identity try_reuse_anon_wrapper
                                                               // matches against the old tree.
14413
        let mut anon_ordinal: usize = 0;
57270
        for (i, &new_child_dom_id) in new_children_dom_ids.iter().enumerate() {
57270
            if is_block_level(styled_dom, new_child_dom_id) {
                // End current inline run if any
40197
                if !inline_run.is_empty() {
                    // CSS 2.2 § 9.2.2.1: If the inline run consists entirely of
                    // whitespace-only text nodes (and white-space doesn't preserve it),
                    // skip creating the anonymous IFC wrapper. This prevents inter-block
                    // whitespace from creating empty blocks that take up vertical space.
                    // +spec:display-property:bef3fc - anonymous blocks of only collapsible
                    // whitespace removed from rendering tree
15966
                    if is_whitespace_only_inline_run(styled_dom, &inline_run, new_dom_id) {
15872
                        if let Some(msgs) = debug_messages.as_mut() {
547
                            msgs.push(LayoutDebugMessage::info(format!(
547
                                "[reconcile_recursive] Skipping whitespace-only inline run ({} \
547
                                 nodes) between blocks in node {}",
547
                                inline_run.len(),
547
                                new_dom_id.index()
547
                            )));
15707
                        }
15872
                        inline_run.clear();
                    } else {
                        // Create anonymous IFC wrapper for the inline run
                        // This wrapper establishes an Inline Formatting Context
94
                        let anon_idx = new_tree_builder.create_anonymous_node(
94
                            new_node_idx,
94
                            AnonymousBoxType::InlineWrapper,
94
                            FormattingContext::Inline, // IFC for inline content
                        );
94
                        let anon_reused = try_reuse_anon_wrapper(
94
                            old_tree,
94
                            old_tree_idx,
94
                            anon_ordinal,
94
                            &inline_run,
94
                            new_tree_builder,
94
                            anon_idx,
                        );
94
                        anon_ordinal += 1;
94
                        if let Some(msgs) = debug_messages.as_mut() {
91
                            msgs.push(LayoutDebugMessage::info(format!(
91
                                "[reconcile_recursive] Created anonymous IFC wrapper \
91
                                 (layout_idx={}) for {} inline children: {:?}",
                                anon_idx,
91
                                inline_run.len(),
91
                                inline_run
91
                                    .iter()
113
                                    .map(|(_, id)| id.index())
91
                                    .collect::<Vec<_>>()
                            )));
3
                        }
                        // Process each inline child under the anonymous wrapper
                        #[allow(clippy::iter_with_drain)]
                        // accumulator Vec reused across runs; drain(..) empties it while retaining
                        // the allocation
119
                        for (pos, inline_dom_id) in inline_run.drain(..) {
                            // Inline children live under the anon wrapper
                            // in the old tree, so the parent's direct
                            // `old_children_by_dom` map won't hit them.
                            // Fall through to the global `dom_to_layout`
                            // map; we don't care which anon wrapper they
                            // were under, only that their cold data
                            // (fingerprint) gets matched correctly.
119
                            let old_child_idx = old_children_by_dom
119
                                .get(&inline_dom_id)
119
                                .copied()
119
                                .or_else(|| {
118
                                    old_tree
118
                                        .and_then(|t| t.dom_to_layout.get(&inline_dom_id))
118
                                        .and_then(|v| v.first().copied().map(LayoutNodeId::index))
118
                                });
119
                            let reconciled_child_idx = reconcile_recursive(
119
                                styled_dom,
119
                                inline_dom_id,
119
                                old_child_idx,
119
                                Some(anon_idx), // Parent is the anonymous wrapper
119
                                old_tree,
119
                                new_tree_builder,
119
                                recon,
119
                                debug_messages,
119
                                subtree_style_changed,
119
                                dom_diff_clean,
                            )?;
119
                            if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
119
                                new_child_hashes.push(child_node.subtree_hash.0);
119
                            }
                        }
                        // NOTE: We intentionally do NOT unconditionally
                        // mark the anonymous wrapper as intrinsic_dirty
                        // here. If any of the inline children are
                        // themselves dirty, their own `mark_dirty` call
                        // propagates upward through this wrapper, so
                        // wrappers whose content is unchanged keep their
                        // cached layout. `children_are_different` flips the
                        // parent to layout-dirty ONLY when the wrapper is
                        // genuinely new / its run changed — the previous
                        // unconditional `= true` here re-dirtied every
                        // paragraph's parent on every reconcile (see
                        // try_reuse_anon_wrapper).
94
                        if !anon_reused {
83
                            if std::env::var_os("AZ_RECON_DEBUG").is_some() {
                                eprintln!(
                                    "[recon] mid-loop wrapper ord {} NOT reused (run len {})",
                                    anon_ordinal - 1,
                                    inline_run.len()
                                );
83
                            }
83
                            children_are_different = true;
11
                        }
                    } // end else (non-whitespace run)
24231
                }
                // Process block-level child directly under parent
40197
                let old_child_idx = old_children_by_dom
40197
                    .get(&new_child_dom_id)
40197
                    .copied()
40197
                    .or_else(|| old_children_indices.get(i).copied());
40197
                let reconciled_child_idx = reconcile_recursive(
40197
                    styled_dom,
40197
                    new_child_dom_id,
40197
                    old_child_idx,
40197
                    Some(new_node_idx),
40197
                    old_tree,
40197
                    new_tree_builder,
40197
                    recon,
40197
                    debug_messages,
40197
                    subtree_style_changed,
40197
                    dom_diff_clean,
                )?;
40197
                if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
40197
                    new_child_hashes.push(child_node.subtree_hash.0);
40197
                }
40197
                if old_tree.and_then(|t| {
20557
                    t.cold(LayoutNodeId::new(old_child_idx?))
20526
                        .map(|n| n.subtree_hash)
40197
                }) != new_tree_builder
40197
                    .get(reconciled_child_idx)
40197
                    .map(|n| n.subtree_hash)
                {
22172
                    if std::env::var_os("AZ_RECON_DEBUG").is_some() {
                        eprintln!(
                            "[recon] block child dom {:?} under parent dom {:?} hash MISMATCH \
                             warm_pass={} old_idx={:?} (old {:?} vs new {:?})",
                            new_child_dom_id.index(),
                            new_dom_id.index(),
                            old_tree.is_some(),
                            old_child_idx,
                            old_tree.and_then(|t| t
                                .cold(LayoutNodeId::new(old_child_idx.unwrap_or(usize::MAX)))
                                .map(|n| n.subtree_hash)),
                            new_tree_builder
                                .get(reconciled_child_idx)
                                .map(|n| n.subtree_hash),
                        );
22172
                    }
22172
                    children_are_different = true;
18025
                }
17073
            } else {
17073
                // Inline-level child - add to current run
17073
                inline_run.push((i, new_child_dom_id));
17073
            }
        }
        // Process any remaining inline run at the end
14413
        if !inline_run.is_empty() {
            // CSS 2.2 § 9.2.2.1: Skip whitespace-only trailing inline runs
990
            if is_whitespace_only_inline_run(styled_dom, &inline_run, new_dom_id) {
922
                if let Some(msgs) = debug_messages.as_mut() {
246
                    msgs.push(LayoutDebugMessage::info(format!(
246
                        "[reconcile_recursive] Skipping trailing whitespace-only inline run ({} \
246
                         nodes) in node {}",
246
                        inline_run.len(),
246
                        new_dom_id.index()
246
                    )));
846
                }
                // Don't create a wrapper — just drop the run
            } else {
68
                let anon_idx = new_tree_builder.create_anonymous_node(
68
                    new_node_idx,
68
                    AnonymousBoxType::InlineWrapper,
68
                    FormattingContext::Inline, // IFC for inline content
                );
68
                let anon_reused = try_reuse_anon_wrapper(
68
                    old_tree,
68
                    old_tree_idx,
68
                    anon_ordinal,
68
                    &inline_run,
68
                    new_tree_builder,
68
                    anon_idx,
                );
68
                anon_ordinal += 1;
68
                if let Some(msgs) = debug_messages.as_mut() {
51
                    msgs.push(LayoutDebugMessage::info(format!(
51
                        "[reconcile_recursive] Created trailing anonymous IFC wrapper \
51
                         (layout_idx={}) for {} inline children: {:?}",
                        anon_idx,
51
                        inline_run.len(),
51
                        inline_run
51
                            .iter()
112
                            .map(|(_, id)| id.index())
51
                            .collect::<Vec<_>>()
                    )));
17
                }
                #[allow(clippy::iter_with_drain)]
                // accumulator Vec reused across runs; drain(..) empties it while retaining the
                // allocation
139
                for (pos, inline_dom_id) in inline_run.drain(..) {
139
                    let old_child_idx = old_children_by_dom.get(&inline_dom_id).copied();
139
                    let reconciled_child_idx = reconcile_recursive(
139
                        styled_dom,
139
                        inline_dom_id,
139
                        old_child_idx,
139
                        Some(anon_idx),
139
                        old_tree,
139
                        new_tree_builder,
139
                        recon,
139
                        debug_messages,
139
                        subtree_style_changed,
139
                        dom_diff_clean,
                    )?;
139
                    if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
139
                        new_child_hashes.push(child_node.subtree_hash.0);
139
                    }
                }
                // See note in main mixed-content branch: rely on
                // children's own mark_dirty to propagate upward rather
                // than invalidating the whole wrapper each reconcile.
68
                if !anon_reused {
35
                    if std::env::var_os("AZ_RECON_DEBUG").is_some() {
                        eprintln!(
                            "[recon] trailing wrapper ord {} NOT reused",
                            anon_ordinal - 1
                        );
35
                    }
35
                    children_are_different = true;
33
                }
            } // end else (non-whitespace trailing run)
13423
        }
    }
    // After reconciling children, calculate this node's full subtree hash.
    // Use a combined hash of the fingerprint fields for the subtree hash.
260725
    let node_self_hash = {
        use std::hash::{DefaultHasher, Hash, Hasher};
260725
        let mut h = DefaultHasher::new();
260725
        new_fingerprint.hash(&mut h);
260725
        h.finish()
    };
260725
    let final_subtree_hash = calculate_subtree_hash(node_self_hash, &new_child_hashes);
260725
    if let Some(current_node) = new_tree_builder.get_mut(new_node_idx) {
260725
        current_node.subtree_hash = final_subtree_hash;
260725
    }
    // Classify this node into the appropriate dirty set based on what changed.
260725
    if dirty_flag >= DirtyFlag::Layout || children_are_different {
        // Runtime-gated classification trace: names WHY a node went dirty,
        // which is the question every reconcile investigation starts with.
213298
        if std::env::var_os("AZ_RECON_DEBUG").is_some() {
            eprintln!(
                "[recon] intrinsic_dirty += layout_idx {} (dom {:?}, flag {:?}, children_diff {})",
                new_node_idx,
                new_dom_id.index(),
                dirty_flag,
                children_are_different
            );
213298
        }
213298
        recon.intrinsic_dirty.insert(new_node_idx);
213298
        recon.layout_roots.insert(new_node_idx);
47427
    } else if dirty_flag == DirtyFlag::Paint {
4
        recon.paint_dirty.insert(new_node_idx);
47423
    }
260725
    Ok(new_node_idx)
260725
}
/// Result of `prepare_layout_context`: contains the layout constraints and
/// intermediate values needed for `calculate_layout_for_subtree`.
struct PreparedLayoutContext<'a> {
    constraints: LayoutConstraints<'a>,
    /// DOM ID for the node. None for anonymous boxes.
    dom_id: Option<NodeId>,
    writing_mode: LayoutWritingMode,
    final_used_size: LogicalSize,
    box_props: crate::solver3::geometry::BoxProps,
}
/// Prepares the layout context for a single node by calculating its used size
/// and building the layout constraints for its children.
///
/// For anonymous boxes (no `dom_node_id`), we use default values and inherit
/// from the containing block.
40611
fn prepare_layout_context<'a, T: ParsedFontTrait>(
40611
    ctx: &LayoutContext<'a, T>,
40611
    tree: &LayoutTree,
40611
    node_index: usize,
40611
    cb: &super::geometry::ContainingBlock,
40611
) -> Result<PreparedLayoutContext<'a>> {
    // Legacy view for the consumers below that are still keyed on the
    // flattened form (cache slots, LayoutConstraints). Sizing itself gets the
    // TYPED cb so no arm of it can do arithmetic on a sentinel.
40611
    let containing_block_size = cb.flattened();
40611
    let node = tree
40611
        .get(LayoutNodeId::new(node_index))
40611
        .ok_or(LayoutError::InvalidTree)?;
40611
    let warm = tree
40611
        .warm(LayoutNodeId::new(node_index))
40611
        .ok_or(LayoutError::InvalidTree)?;
40611
    let dom_id = node.dom_node_id; // Can be None for anonymous boxes
    // Phase 1: Calculate this node's provisional used size
    // This size is based on the node's CSS properties (width, height, etc.) and
    // its containing block. If height is 'auto', this is a temporary value.
40611
    let intrinsic = warm.intrinsic_sizes.unwrap_or_default();
40611
    let final_used_size = calculate_used_size_for_node(
40611
        ctx.styled_dom,
40611
        dom_id, // Now Option<NodeId>
40611
        cb,
40611
        intrinsic,
40611
        &node.box_props.unpack(),
40611
        &ctx.viewport_size,
    )?;
    // Phase 2: Layout children using a formatting context
    // Use pre-computed styles from LayoutNodeWarm instead of repeated lookups
40611
    let writing_mode = warm.computed_style.writing_mode;
40611
    let text_align = warm.computed_style.text_align;
40611
    let display = warm.computed_style.display;
40611
    let overflow_y = warm.computed_style.overflow_y;
    // Check if height is auto (no explicit height set)
40611
    let height_is_auto = warm.computed_style.height.is_none();
40611
    let available_size_for_children = if height_is_auto {
        // Height is auto - use containing block size as available size
31914
        let inner_size = node.box_props.inner_size(final_used_size, writing_mode);
        // For inline elements (display: inline), the available width comes from
        // the containing block, not from the element's own intrinsic size.
        // CSS 2.2 § 10.3.1: Inline, non-replaced elements use containing block width.
31914
        let available_width = match display {
1797
            LayoutDisplay::Inline => containing_block_size.width,
30117
            _ => inner_size.width,
        };
31914
        LogicalSize {
31914
            width: available_width,
31914
            // Use containing block height!
31914
            height: containing_block_size.height,
31914
        }
    } else {
        // Height is explicit - use inner size (after padding/border)
8697
        node.box_props.inner_size(final_used_size, writing_mode)
    };
    // NOTE: Scrollbar reservation is handled inside layout_bfc() where it subtracts
    // scrollbar width from children_containing_block_size. We do NOT subtract here
    // to avoid double-subtraction (layout_bfc already handles both the used_size
    // and available_size code paths).
40611
    let wm_ctx = crate::solver3::geometry::WritingModeContext::new(
40611
        writing_mode,
40611
        warm.computed_style.direction,
40611
        warm.computed_style.text_orientation,
    );
40611
    let constraints = LayoutConstraints {
40611
        available_size: available_size_for_children,
40611
        bfc_state: None,
40611
        writing_mode,
40611
        writing_mode_ctx: wm_ctx,
40611
        text_align: style_text_align_to_fc(text_align),
40611
        containing_block_size,
40611
        available_width_type: Text3AvailableSpace::Definite(available_size_for_children.width),
40611
        fragmentainer: None,
40611
    };
40611
    Ok(PreparedLayoutContext {
40611
        constraints,
40611
        dom_id,
40611
        writing_mode,
40611
        final_used_size,
40611
        box_props: node.box_props.unpack(),
40611
    })
40611
}
/// Core scrollbar info computation: given pre-computed content and container sizes plus
/// a DOM node for style look-up, determines whether scrollbars are needed.
///
/// This is the single source of truth for scrollbar detection AT LAYOUT TIME.
/// Both the BFC path (`compute_scrollbar_info`) and the Taffy flex/grid path
/// (`compute_child_layout` in `taffy_bridge.rs`) call this function, ensuring
/// consistent behaviour. A `VirtualView`'s scrollable extent is not known yet
/// when this runs — [`apply_virtual_scroll_necessity`] amends the result after
/// layout and is the only other place a necessity flag is ever raised.
///
/// For paged media (PDF), scrollbars are never added since they don't exist in print.
398918
pub fn compute_scrollbar_info_core<T: ParsedFontTrait>(
398918
    ctx: &LayoutContext<'_, T>,
398918
    dom_id: NodeId,
398918
    styled_node_state: &azul_core::styled_dom::StyledNodeState,
398918
    content_size: LogicalSize,
398918
    container_size: LogicalSize,
398918
) -> ScrollbarRequirements {
    // +spec:overflow:08b60d - non-interactive media: UA may show scroll indicators but we skip them
    // for print
398918
    if ctx.fragmentation_context.is_some() {
1678
        return ScrollbarRequirements::default();
397240
    }
397240
    let overflow_x = get_overflow_x(ctx.styled_dom, dom_id, styled_node_state);
397240
    let overflow_y = get_overflow_y(ctx.styled_dom, dom_id, styled_node_state);
    // Resolve the full scrollbar style **once** and reuse it
    // across the rest of this function + any further calls from
    // the same layout pass via `LayoutContext::scrollbar_style_cache`.
    // Previously we called `get_layout_scrollbar_width_px` (which
    // builds the full scrollbar_style internally, keeps only
    // `reserve_width_px`, then drops it) and then
    // `get_scrollbar_style` again — each build performs 9 cascade
    // walks (track/thumb/button/corner/width/color/visibility/
    // fade-delay/fade-duration). With the memo, subsequent calls
    // on the same (dom_id, state) are a HashMap hit.
397240
    let scrollbar_style =
397240
        crate::solver3::getters::get_scrollbar_style_cached(ctx, dom_id, styled_node_state);
397240
    let scrollbar_width_px = scrollbar_style.reserve_width_px;
397240
    let mut reqs = fc::check_scrollbar_necessity(
397240
        content_size,
397240
        container_size,
397240
        to_overflow_behavior(overflow_x),
397240
        to_overflow_behavior(overflow_y),
397240
        scrollbar_width_px,
    );
397240
    reqs.visual_width_px = scrollbar_style.visual_width_px;
    // +spec:overflow:e90f12 - scrollbar-gutter reserves space independently of scrollbar presence
    // +spec:overflow:e8a828 - scrollbar-gutter affects gutter presence at the box's inline edges
    // +spec:overflow:3a6966 - classic scrollbar gutter width == scrollbar width; overlay scrollbars
    // have no gutter
    //
    // NOT modeled: the non-normative side-selection note (overflow:3c44cc,
    // "which side a scrollbar appears on MAY depend on OS conventions or
    // bidirectionality") - the gutter is hardcoded to the physical right via
    // the width-only shrink. A "may", so the fixed choice is conformant; a
    // bidi-aware side needs writing-mode plumbing through ScrollbarReqs.
    //
    // scrollbar-gutter only applies to scroll containers (overflow: auto or scroll).
    // "stable" reserves gutter on the inline-end edge even if no scrollbar is needed.
    // "stable both-edges" reserves gutter on both inline edges.
397240
    let scrollbar_gutter = get_scrollbar_gutter_property(ctx.styled_dom, dom_id, styled_node_state)
397240
        .unwrap_or(azul_css::props::layout::overflow::StyleScrollbarGutter::Auto);
397240
    let ob_y = to_overflow_behavior(overflow_y);
397240
    let is_scroll_container = matches!(
397240
        ob_y,
        fc::OverflowBehavior::Scroll | fc::OverflowBehavior::Auto
    );
397240
    if is_scroll_container {
        use azul_css::props::layout::overflow::StyleScrollbarGutter;
1668
        match scrollbar_gutter {
            StyleScrollbarGutter::Stable => {
                // Reserve gutter on inline-end even if no scrollbar is currently needed
                if !reqs.needs_vertical {
                    reqs.scrollbar_width = scrollbar_width_px;
                }
            }
            StyleScrollbarGutter::StableBothEdges => {
                // Reserve gutter on both inline edges
                reqs.scrollbar_width = scrollbar_width_px * 2.0;
            }
1668
            StyleScrollbarGutter::Auto => {
1668
                // Default: gutter only present when scrollbar is present (already handled)
1668
            }
        }
395572
    }
397240
    reqs
398918
}
/// Amends a node's [`ScrollbarRequirements`] with the `VirtualView` virtual
/// scroll size — the half of the necessity decision that only exists AFTER
/// layout.
///
/// `compute_scrollbar_info_core` decides from the LAID-OUT content size. A
/// `VirtualView` is a replaced element with no flow content, so its laid-out
/// content IS its viewport: `overflow: auto` can never fire for it, and the real
/// scrollable extent lives in `ScrollManager`'s `virtual_scroll_size`, which the
/// `VirtualView` callback publishes strictly after the layout pass that would
/// need to read it.
///
/// This is the ONE place that compares the two. Every consumer of
/// `needs_horizontal` / `needs_vertical` must reach the answer through it, or
/// the paint side and the GPU thumb updater disagree — a painted bar whose thumb
/// never moves. Two callers:
///
/// * `display_list::paint_scrollbars`, which cannot read a post-layout write-back: the display list
///   is built inside the very layout pass that recomputes `warm.scrollbar_info` from scratch; and
/// * `shell2::common::layout::register_scroll_nodes`, which stores the amended value back into
///   `warm.scrollbar_info`, so that `GpuStateManager::update_scrollbar_transforms`, the
///   `ScrollManager` registration and the hit-test scrollbar states all see the same answer.
///
/// `virtual_content_size` is `ScrollPosition::children_rect.size` — the same
/// number the thumb geometry is built from, so "is there a bar" and "how long is
/// its thumb" can never come from different sizes. `padding_box_size` is the
/// node's border box minus its borders: a `VirtualView` renders its child DOM
/// into its bounds, so that IS its viewport, and there is no flow content to
/// inset by padding.
///
/// Only the two booleans move. Layout has already run, so raising
/// `scrollbar_width` / `scrollbar_height` here would desync the paint from the
/// clip rect that reserved no gutter — an `auto` `VirtualView`'s bar overlays the
/// viewport's inner edge, while `overflow: scroll` keeps reserving its gutter at
/// layout time. Nothing is ever lowered: a bar layout already asked for stays.
///
/// Returns `true` if a flag was raised.
2538
pub fn apply_virtual_scroll_necessity(
2538
    styled_dom: &StyledDom,
2538
    dom_id: NodeId,
2538
    virtual_content_size: LogicalSize,
2538
    padding_box_size: LogicalSize,
2538
    reqs: &mut ScrollbarRequirements,
2538
) -> bool {
2538
    let is_virtual_view = styled_dom
2538
        .node_data
2538
        .as_container()
2538
        .get(dom_id)
2538
        .is_some_and(azul_core::dom::NodeData::is_virtual_view_node);
2538
    if !is_virtual_view {
1238
        return false;
1300
    }
1300
    apply_content_scroll_necessity(
1300
        styled_dom,
1300
        dom_id,
1300
        virtual_content_size,
1300
        padding_box_size,
1300
        reqs,
    )
2538
}
/// The axis-raising core of [`apply_virtual_scroll_necessity`], without the
/// `VirtualView` gate: raise `needs_horizontal` / `needs_vertical` when the
/// node's resolved `overflow-x`/`overflow-y` allows user scrolling and
/// `content_size` exceeds the padding box.
///
/// `register_scroll_nodes` also calls this for ORDINARY nodes, because a text
/// edit can grow an IFC's content after layout: `reshape_text_node` re-runs
/// text3 and refreshes `overflow_content_size`, but nothing re-runs the
/// Phase-3 `compute_scrollbar_info` pass — so a single-line text input whose
/// value outgrew the field would keep `needs_horizontal == false` forever and
/// never register the scroll box the caret-reveal needs. For nodes whose
/// content did NOT change after layout this is a no-op (both sides read the
/// same `overflow_content_size` Phase 3 wrote). Nothing is ever lowered.
///
/// Returns `true` if a flag was raised.
168797
pub fn apply_content_scroll_necessity(
168797
    styled_dom: &StyledDom,
168797
    dom_id: NodeId,
168797
    content_size: LogicalSize,
168797
    padding_box_size: LogicalSize,
168797
    reqs: &mut ScrollbarRequirements,
168797
) -> bool {
    // Same tolerance as `check_scrollbar_necessity`: a sub-pixel difference must
    // not raise a bar.
    const EPSILON: f32 = 1.0;
168797
    let virtual_content_size = content_size;
168797
    let node_state = styled_dom
168797
        .styled_nodes
168797
        .as_container()
168797
        .get(dom_id)
168797
        .map(|n| n.styled_node_state)
168797
        .unwrap_or_default();
168797
    let raw_overflow_x = get_overflow_x(styled_dom, dom_id, &node_state);
168797
    let raw_overflow_y = get_overflow_y(styled_dom, dom_id, &node_state);
168797
    let overflow_x = raw_overflow_x.resolve_computed(&raw_overflow_y);
168797
    let overflow_y = raw_overflow_y.resolve_computed(&raw_overflow_x);
168797
    let raise_horizontal = !reqs.needs_horizontal
168503
        && overflow_x.allows_user_scrolling()
1562
        && virtual_content_size.width > padding_box_size.width + EPSILON;
168797
    if raise_horizontal {
1
        reqs.needs_horizontal = true;
168796
    }
168797
    let raise_vertical = !reqs.needs_vertical
168082
        && overflow_y.allows_user_scrolling()
903
        && virtual_content_size.height > padding_box_size.height + EPSILON;
168797
    if raise_vertical {
293
        reqs.needs_vertical = true;
168504
    }
168797
    raise_horizontal || raise_vertical
168797
}
/// Determines scrollbar requirements for a node based on content overflow.
///
/// Convenience wrapper around `compute_scrollbar_info_core` for the BFC layout path,
/// where the container size is derived from `box_props.inner_size(final_used_size, …)`.
40466
fn compute_scrollbar_info<T: ParsedFontTrait>(
40466
    ctx: &LayoutContext<'_, T>,
40466
    dom_id: NodeId,
40466
    styled_node_state: &azul_core::styled_dom::StyledNodeState,
40466
    content_size: LogicalSize,
40466
    box_props: &crate::solver3::geometry::BoxProps,
40466
    final_used_size: LogicalSize,
40466
    writing_mode: LayoutWritingMode,
40466
) -> ScrollbarRequirements {
40466
    let container_size = box_props.inner_size(final_used_size, writing_mode);
40466
    compute_scrollbar_info_core(ctx, dom_id, styled_node_state, content_size, container_size)
40466
}
/// Checks if scrollbars changed compared to previous layout and if reflow is needed.
///
/// Detects both addition AND removal of scrollbars. Oscillation (add → remove → add)
/// is prevented by the outer layout loop's iteration limit (`loop_count > 10` in mod.rs),
/// not by suppressing removal detection here. This allows scrollbars to correctly
/// disappear when content shrinks or the window is resized larger.
///
/// A flip only counts when at least one of the two states RESERVES layout space —
/// the same criterion the no-previous-info arm has always used
/// (`ScrollbarRequirements::needs_reflow`). What a reflow buys is a corrected
/// available width/height (`layout_bfc`'s `scrollbar_reservation`, and
/// `shrink_size` below), so two zero-reservation states cannot need one. This
/// keeps overlay scrollbars (macOS-style, `reserve_width_px == 0`) from paying a
/// full extra layout pass every time a bar appears, and it is what stops
/// [`apply_virtual_scroll_necessity`]'s post-layout amendment — which raises
/// flags without reserving anything — from asking for one on every single pass
/// over an `overflow: auto` `VirtualView`.
53261
fn check_scrollbar_change(
53261
    tree: &LayoutTree,
53261
    node_index: usize,
53261
    scrollbar_info: &ScrollbarRequirements,
53261
    skip_scrollbar_check: bool,
53261
) -> bool {
53261
    if skip_scrollbar_check {
13686
        return false;
39575
    }
39575
    let Some(warm_node) = tree.warm(LayoutNodeId::new(node_index)) else {
2
        return false;
    };
39573
    warm_node.scrollbar_info.as_ref().map_or_else(
27366
        || scrollbar_info.needs_reflow(),
12207
        |old_info| {
            // Trigger reflow if scrollbar state changed in either direction
12207
            let horizontal_changed = old_info.needs_horizontal != scrollbar_info.needs_horizontal;
12207
            let vertical_changed = old_info.needs_vertical != scrollbar_info.needs_vertical;
12207
            (horizontal_changed || vertical_changed)
36
                && (old_info.needs_reflow() || scrollbar_info.needs_reflow())
12207
        },
    )
53261
}
/// Calculates the content-box position from a margin-box position.
///
/// The content-box is offset from the margin-box by border + padding.
/// Margin is NOT added here because `containing_block_pos` already accounts for it.
104033
fn calculate_content_box_pos(
104033
    containing_block_pos: LogicalPosition,
104033
    box_props: &crate::solver3::geometry::BoxProps,
104033
) -> LogicalPosition {
104033
    LogicalPosition::new(
104033
        containing_block_pos.x + box_props.border.left + box_props.padding.left,
104033
        containing_block_pos.y + box_props.border.top + box_props.padding.top,
    )
104033
}
/// Emits debug logging for content-box calculation if debug messages are enabled.
40611
fn log_content_box_calculation<T: ParsedFontTrait>(
40611
    ctx: &mut LayoutContext<'_, T>,
40611
    node_index: usize,
40611
    current_node: &LayoutNodeHot,
40611
    containing_block_pos: LogicalPosition,
40611
    self_content_box_pos: LogicalPosition,
40611
) {
40611
    let Some(debug_msgs) = ctx.debug_messages.as_mut() else {
10235
        return;
    };
30376
    let dom_name = current_node
30376
        .dom_node_id
30376
        .and_then(|id| {
30249
            ctx.styled_dom
30249
                .node_data
30249
                .as_container()
30249
                .internal
30249
                .get(id.index())
30249
        })
30376
        .map_or_else(|| "Unknown".to_string(), |n| format!("{:?}", n.node_type));
30376
    let cbp = current_node.box_props.unpack();
30376
    debug_msgs.push(LayoutDebugMessage::new(
30376
        LayoutDebugMessageType::PositionCalculation,
30376
        format!(
30376
            "[CONTENT BOX {}] {} - margin-box pos=({:.2}, {:.2}) + border=({:.2},{:.2}) + \
30376
             padding=({:.2},{:.2}) = content-box pos=({:.2}, {:.2})",
            node_index,
            dom_name,
            containing_block_pos.x,
            containing_block_pos.y,
            cbp.border.left,
            cbp.border.top,
            cbp.padding.left,
            cbp.padding.top,
            self_content_box_pos.x,
            self_content_box_pos.y
        ),
    ));
40611
}
/// Emits debug logging for child positioning if debug messages are enabled.
39153
fn log_child_positioning<T: ParsedFontTrait>(
39153
    ctx: &mut LayoutContext<'_, T>,
39153
    child_index: usize,
39153
    child_node: &LayoutNodeHot,
39153
    self_content_box_pos: LogicalPosition,
39153
    child_relative_pos: LogicalPosition,
39153
    child_absolute_pos: LogicalPosition,
39153
) {
    // Gate FIRST — this used to compute `child_dom_name` (a String allocation
    // plus a `{:?}` Debug of the whole NodeType enum) before checking whether
    // debug messages are even enabled, i.e. on EVERY child of EVERY node in
    // EVERY layout. Besides the wasted work on desktop, on the web-lift path
    // that Debug chain reaches `hyphenation_commons::dictionary::trie`'s Debug,
    // which reads through `std::io::Read` — a Leaf stub in wasm — so the
    // formatter returned Err and `format_inner`'s `.expect` aborted the whole
    // solve. `log_content_box_calculation` above already gates first; mirror it.
39153
    let Some(debug_msgs) = ctx.debug_messages.as_mut() else {
14838
        return;
    };
24315
    let child_dom_name = child_node
24315
        .dom_node_id
24315
        .and_then(|id| {
24185
            ctx.styled_dom
24185
                .node_data
24185
                .as_container()
24185
                .internal
24185
                .get(id.index())
24185
        })
24315
        .map_or_else(|| "Unknown".to_string(), |n| format!("{:?}", n.node_type));
24315
    debug_msgs.push(LayoutDebugMessage::new(
24315
        LayoutDebugMessageType::PositionCalculation,
24315
        format!(
24315
            "[CHILD POS {}] {} - parent content-box=({:.2}, {:.2}) + relative=({:.2}, {:.2}) + \
24315
             margin=({:.2}, {:.2}) = absolute=({:.2}, {:.2})",
            child_index,
            child_dom_name,
            self_content_box_pos.x,
            self_content_box_pos.y,
            child_relative_pos.x,
            child_relative_pos.y,
24315
            child_node.box_props.unpack().margin.left,
24315
            child_node.box_props.unpack().margin.top,
            child_absolute_pos.x,
            child_absolute_pos.y
        ),
    ));
39153
}
/// Processes a single in-flow child: sets position and recurses.
///
/// For Flex/Grid containers, Taffy has already laid out the children completely.
/// We only recurse to position their grandchildren.
/// For Block/Inline/Table, `layout_bfc/layout_ifc` already laid out children in Pass 1.
/// We only need to set absolute positions and recurse for positioning grandchildren.
39153
fn process_inflow_child<T: ParsedFontTrait>(
39153
    ctx: &mut LayoutContext<'_, T>,
39153
    tree: &mut LayoutTree,
39153
    text_cache: &TextLayoutCache,
39153
    child_index: usize,
39153
    child_relative_pos: LogicalPosition,
39153
    self_content_box_pos: LogicalPosition,
39153
    inner_size_after_scrollbars: LogicalSize,
39153
    writing_mode: LayoutWritingMode,
39153
    is_flex_or_grid: bool,
39153
    calculated_positions: &mut super::PositionVec,
39153
    reflow_needed_for_scrollbars: bool,
39153
    float_cache: &HashMap<usize, fc::FloatingContext>,
39153
) -> Result<()> {
    // Set relative position on child
    // child_relative_pos is [CoordinateSpace::Parent] - relative to parent's content-box
39153
    let child_warm = tree
39153
        .warm_mut(LayoutNodeId::new(child_index))
39153
        .ok_or(LayoutError::InvalidTree)?;
39153
    child_warm.relative_position = Some(child_relative_pos);
    // Calculate absolute position
    // self_content_box_pos is [CoordinateSpace::Window] - absolute position of parent's content-box
    // child_absolute_pos becomes [CoordinateSpace::Window] - absolute window position of child
39153
    let child_absolute_pos = LogicalPosition::new(
39153
        self_content_box_pos.x + child_relative_pos.x,
39153
        self_content_box_pos.y + child_relative_pos.y,
    );
    // Debug logging
    {
39153
        let child_node = tree
39153
            .get(LayoutNodeId::new(child_index))
39153
            .ok_or(LayoutError::InvalidTree)?;
39153
        log_child_positioning(
39153
            ctx,
39153
            child_index,
39153
            child_node,
39153
            self_content_box_pos,
39153
            child_relative_pos,
39153
            child_absolute_pos,
        );
    }
    // calculated_positions stores [CoordinateSpace::Window] - absolute positions
39153
    super::pos_set(calculated_positions, child_index, child_absolute_pos);
    // Get child's properties for recursion
39153
    let child_node = tree
39153
        .get(LayoutNodeId::new(child_index))
39153
        .ok_or(LayoutError::InvalidTree)?;
39153
    let child_bp = child_node.box_props.unpack();
39153
    let child_content_box_pos = calculate_content_box_pos(child_absolute_pos, &child_bp);
39153
    let child_inner_size =
39153
        child_bp.inner_size(child_node.used_size.unwrap_or_default(), writing_mode);
39153
    let child_children: Vec<usize> = tree.children(child_index).to_vec();
39153
    let child_fc = child_node.formatting_context;
    // Recurse to position grandchildren
    // OPTIMIZATION: For BFC/IFC children, layout_bfc/layout_ifc already computed their layout.
    // We just need to set absolute positions for descendants.
    // Only recurse if child has children to position.
39153
    if !child_children.is_empty() {
34792
        if is_flex_or_grid {
            // For Flex/Grid: Taffy already set used_size. Only recurse for grandchildren.
5203
            position_flex_child_descendants(
5203
                tree,
5203
                child_index,
5203
                child_content_box_pos,
5203
                child_inner_size,
5203
                calculated_positions,
            )?;
29589
        } else {
29589
            // For Block/Inline/Table: The formatting context already laid out children.
29589
            // Recursively position grandchildren using their cached layout data.
29589
            position_bfc_child_descendants(
29589
                tree,
29589
                child_index,
29589
                child_content_box_pos,
29589
                calculated_positions,
29589
            );
29589
        }
4361
    }
39153
    Ok(())
39153
}
/// Recursively positions descendants of a BFC/IFC child without re-computing layout.
/// The layout was already computed by `layout_bfc/layout_ifc`.
/// We only need to convert relative positions to absolute positions.
332266
pub(super) fn position_bfc_child_descendants(
332266
    tree: &LayoutTree,
332266
    node_index: usize,
332266
    content_box_pos: LogicalPosition,
332266
    calculated_positions: &mut super::PositionVec,
332266
) {
332266
    let Some(node) = tree.get(LayoutNodeId::new(node_index)) else {
1
        return;
    };
332265
    for &child_index in tree.children(node_index) {
289688
        let Some(child_node) = tree.get(LayoutNodeId::new(child_index)) else {
            continue;
        };
        // Use the relative_position that was set during formatting context layout
289688
        let child_rel_pos = tree
289688
            .warm(LayoutNodeId::new(child_index))
289688
            .and_then(|w| w.relative_position)
289688
            .unwrap_or_default();
289688
        let child_abs_pos = LogicalPosition::new(
289688
            content_box_pos.x + child_rel_pos.x,
289688
            content_box_pos.y + child_rel_pos.y,
        );
289688
        super::pos_set(calculated_positions, child_index, child_abs_pos);
        // Calculate child's content-box position for recursion
289688
        let cbp = child_node.box_props.unpack();
289688
        let child_content_box_pos = LogicalPosition::new(
289688
            child_abs_pos.x + cbp.border.left + cbp.padding.left,
289688
            child_abs_pos.y + cbp.border.top + cbp.padding.top,
        );
        // Recurse to grandchildren
289688
        position_bfc_child_descendants(
289688
            tree,
289688
            child_index,
289688
            child_content_box_pos,
289688
            calculated_positions,
        );
    }
332266
}
/// Processes out-of-flow children (absolute/fixed positioned elements).
///
/// Out-of-flow elements don't appear in `layout_output.positions` but still need
/// a static position for when no explicit offsets are specified. This sets their
/// static position to the parent's content-box origin.
40611
fn process_out_of_flow_children<T: ParsedFontTrait>(
40611
    ctx: &mut LayoutContext<'_, T>,
40611
    tree: &mut LayoutTree,
40611
    text_cache: &mut TextLayoutCache,
40611
    node_index: usize,
40611
    self_content_box_pos: LogicalPosition,
40611
    cb: &super::geometry::ContainingBlock,
40611
    calculated_positions: &mut super::PositionVec,
40611
    reflow_needed_for_scrollbars: &mut bool,
40611
    float_cache: &mut HashMap<usize, fc::FloatingContext>,
40611
) -> Result<()> {
    // Collect out-of-flow children (those not already positioned)
40611
    let out_of_flow_children: Vec<(usize, Option<NodeId>)> = {
40611
        let current_node = tree
40611
            .get(LayoutNodeId::new(node_index))
40611
            .ok_or(LayoutError::InvalidTree)?;
40611
        tree.children(node_index)
40611
            .iter()
60391
            .filter_map(|&child_index| {
60337
                if super::pos_contains(calculated_positions, child_index) {
38214
                    return None;
22123
                }
22123
                let child = tree.get(LayoutNodeId::new(child_index))?;
22123
                Some((child_index, child.dom_node_id))
60337
            })
40611
            .collect()
    };
62734
    for (child_index, child_dom_id_opt) in out_of_flow_children {
22123
        let Some(child_dom_id) = child_dom_id_opt else {
            continue;
        };
22123
        let position_type = get_position_type(ctx.styled_dom, Some(child_dom_id));
22123
        if position_type != LayoutPosition::Absolute && position_type != LayoutPosition::Fixed {
20006
            continue;
2117
        }
        // Set static position to parent's content-box origin
2117
        super::pos_set(calculated_positions, child_index, self_content_box_pos);
        // Perform full layout for the absolutely positioned child so its
        // inline_layout_result is populated (text rendering needs this).
        // The containing block for abs-pos is the parent's padding box.
2117
        calculate_layout_for_subtree(
2117
            ctx,
2117
            tree,
2117
            text_cache,
2117
            child_index,
2117
            self_content_box_pos,
2117
            cb,
2117
            calculated_positions,
2117
            reflow_needed_for_scrollbars,
2117
            float_cache,
2117
            ComputeMode::PerformLayout,
        )?;
    }
40611
    Ok(())
40611
}
/// Recursive, top-down pass to calculate used sizes and positions for a given subtree.
/// This is the single, authoritative function for in-flow layout.
///
/// Uses the per-node multi-slot cache (inspired by Taffy's 9+1 architecture) to
/// avoid O(n²) complexity. Each node has 9 measurement slots + 1 full layout slot.
///
/// ## Two-Mode Architecture (CSS Two-Pass Layout)
///
/// `compute_mode` determines behavior:
///
/// - **`ComputeSize`** (BFC Pass 1 — sizing): Computes only the node's border-box size. On cache
///   hit from measurement slots, sets `used_size` and returns immediately — no child positioning.
///   This is the key to O(n) two-pass BFC: Pass 1 fills measurement caches cheaply.
///
/// - **`PerformLayout`** (BFC Pass 2 — positioning): Computes size AND positions all children. On
///   cache hit from layout slot, applies cached child positions recursively. When Pass 2 provides
///   the same constraints as Pass 1, the "result matches request" optimization triggers automatic
///   cache hits.
///
/// ## Cache Hit Rates (Taffy's "result matches request" optimization)
///
/// When Pass 1 measures a node with `available_size` A and gets `result_size` R,
/// then Pass 2 provides R as a `known_dimension`, `get_size()` / `get_layout()`
/// recognize R == `cached.result_size` as a cache hit. This is the fundamental
/// mechanism ensuring O(n) total complexity across both passes.
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher HashMap/HashSet
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Errors
///
/// Returns a `LayoutError` if laying out the subtree fails.
48058
pub fn calculate_layout_for_subtree<T: ParsedFontTrait>(
48058
    ctx: &mut LayoutContext<'_, T>,
48058
    tree: &mut LayoutTree,
48058
    text_cache: &mut TextLayoutCache,
48058
    node_index: usize,
48058
    containing_block_pos: LogicalPosition,
48058
    cb: &super::geometry::ContainingBlock,
48058
    calculated_positions: &mut super::PositionVec,
48058
    reflow_needed_for_scrollbars: &mut bool,
48058
    float_cache: &mut HashMap<usize, fc::FloatingContext>,
48058
    compute_mode: ComputeMode,
48058
) -> Result<()> {
48058
    calculate_layout_for_subtree_fragment(
48058
        ctx,
48058
        tree,
48058
        text_cache,
48058
        node_index,
48058
        containing_block_pos,
48058
        cb,
48058
        calculated_positions,
48058
        reflow_needed_for_scrollbars,
48058
        float_cache,
48058
        compute_mode,
48058
        None,
48058
        None,
    )
48058
}
/// [`calculate_layout_for_subtree`] + the K30b fragment channel: `fragment`
/// arms this subtree's fragmentainer (space + optional resume token, riding
/// `LayoutConstraints.fragmentainer` — design §4.3/4.4); `fragment_out`
/// receives the subtree's outgoing [`BreakToken`], `None` = finished.
/// Existing callers use the plain wrapper (both channels `None` — the
/// continuous path is bit-identical by construction).
#[allow(clippy::too_many_arguments)]
48118
pub fn calculate_layout_for_subtree_fragment<T: ParsedFontTrait>(
48118
    ctx: &mut LayoutContext<'_, T>,
48118
    tree: &mut LayoutTree,
48118
    text_cache: &mut TextLayoutCache,
48118
    node_index: usize,
48118
    containing_block_pos: LogicalPosition,
48118
    cb: &super::geometry::ContainingBlock,
48118
    calculated_positions: &mut super::PositionVec,
48118
    reflow_needed_for_scrollbars: &mut bool,
48118
    float_cache: &mut HashMap<usize, fc::FloatingContext>,
48118
    compute_mode: ComputeMode,
48118
    fragment: Option<fc::FragmentainerSpace<'_>>,
48118
    mut fragment_out: Option<&mut Option<crate::solver3::break_token::BreakToken>>,
48118
) -> Result<()> {
    // Legacy flattened view for the cache keys and the not-yet-migrated
    // consumers in this body; the typed `cb` travels to sizing and recursion.
48118
    let containing_block_size = cb.flattened();
    // [g147b az-web-lift DIAG] per-node calculate_layout_for_subtree entry (0x60980+slot): records
    // the last compute_mode that reached this node (PerformLayout=2 wins, runs after
    // ComputeSize=1). If a div shows 0x...0002 here but its layout_formatting_context marker
    // (0x609A0+) is UNSET → positioning reached calculate but short-circuited (cache hit)
    // before dispatching to the formatting context.
    #[cfg(feature = "web_lift")]
    unsafe {
        let m = match compute_mode {
            ComputeMode::PerformLayout => 0xC0DE0002u32,
            _ => 0xC0DE0001u32,
        };
        crate::az_mark((0x60980 + (node_index & 7) * 4) as u32, (m) as u32);
    }
48118
    let _probe = match compute_mode {
35790
        ComputeMode::ComputeSize => crate::probe::Probe::span("size_node"),
12328
        ComputeMode::PerformLayout => crate::probe::Probe::span("pos_node"),
    };
    // HIT path; 0x60 = reached cache-miss compute.) Distinguishes stub/not-entered vs an
    // early Err in the cache-check vs the compute path.
    // === PER-NODE CACHE CHECK (Taffy-inspired 9+1 slot cache) ===
    //
    // Two-mode cache lookup (CSS two-pass architecture):
    //
    // ComputeSize (Pass 1 — sizing):
    //   1. Check measurement slots (get_size) → if hit, set used_size and return. No child
    //      positioning needed — we only need the node's border-box size.
    //   2. Fall back to layout slot → if hit, extract size from full layout result.
    //
    // PerformLayout (Pass 2 — positioning):
    //   1. Check layout slot (get_layout) → if hit, apply cached child positions.
    //   2. No fallback to measurement slots (we need full positions, not just size).
    //
    // This split is critical for O(n) two-pass BFC:
    // - Pass 1 populates measurement slots (cheap: no absolute positioning)
    // - Pass 2 hits layout slot or re-computes with positions
    // NG rule (design doc §1.3 / research §2.1): the layout-result cache is
    // BYPASSED for fragment passes — the fragmentainer (remaining extent +
    // resume token) is not part of the cache key, so a hit would return the
    // CONTINUOUS geometry and silently skip breaking. Fragment results are
    // also never STORED (they would poison the continuous cache).
    // Both modes: a block container sizes its in-flow children in its
    // Pass 1 (`ComputeSize`) against the block that decides their size, and
    // only applies positions afterwards. Flex and grid items never pass
    // through here (taffy lays them out directly), and a dirty flex item is
    // promoted to its container before it could be a layout root.
48118
    if fragment.is_none() && node_index < ctx.cache_map.entries.len() {
48058
        ctx.cache_map.entries[node_index].last_containing_block = Some(*cb);
48058
    }
48118
    if fragment.is_none() && node_index < ctx.cache_map.entries.len() {
48058
        match compute_mode {
            ComputeMode::ComputeSize => {
                // ComputeSize: check the measurement slot for THIS constraint
                // shape (Taffy's 9-slot scheme, wired 2026-08-08). The measure
                // visit (indefinite height) and the final visit (definite
                // height) land in different slots, so neither evicts the
                // other — the slot-0 collapse made every visit a miss.
35757
                let (size_slot, size_key) = NodeCache::classify_size_key(containing_block_size);
35757
                let sizing_hit = ctx.cache_map.entries[node_index]
35757
                    .get_size(size_slot, size_key)
35757
                    .copied();
35757
                if let Some(cached_sizing) = sizing_hit {
                    // SIZING CACHE HIT — set used_size and return immediately.
                    // No child positioning needed in ComputeSize mode.
7346
                    drop(crate::probe::Probe::span("size_cache_hit_sizing"));
7346
                    if let Some(node) = tree.get_mut(LayoutNodeId::new(node_index)) {
7346
                        node.used_size = Some(cached_sizing.result_size);
7346
                    }
7346
                    if let Some(warm) = tree.warm_mut(LayoutNodeId::new(node_index)) {
7346
                        warm.escaped_top_margin = cached_sizing.escaped_top_margin;
7346
                        warm.escaped_bottom_margin = cached_sizing.escaped_bottom_margin;
7346
                        warm.baseline = cached_sizing.baseline;
7346
                    }
7346
                    return Ok(());
28411
                }
                // Fall through to layout slot check
28411
                let layout_hit = ctx.cache_map.entries[node_index]
28411
                    .get_layout(containing_block_size)
28411
                    .cloned();
28411
                if let Some(cached_layout) = layout_hit {
                    // Layout slot hit in ComputeSize mode — extract size only
                    drop(crate::probe::Probe::span("size_cache_hit_layout"));
                    if let Some(node) = tree.get_mut(LayoutNodeId::new(node_index)) {
                        node.used_size = Some(cached_layout.result_size);
                    }
                    if let Some(warm) = tree.warm_mut(LayoutNodeId::new(node_index)) {
                        warm.overflow_content_size = Some(cached_layout.content_size);
                        warm.scrollbar_info = Some(cached_layout.scrollbar_info);
                    }
                    return Ok(());
28411
                }
                // [g147c az-web-lift DIAG] ComputeSize cache MISS for this node (0x60A60+slot): the
                // compute path WILL run → layout_formatting_context should fire. If a div is sized
                // by Pass-1 (0x60A40 set) but this miss-flag is UNSET →
                // calculate(child,ComputeSize) hit the cache instead (so
                // layout_formatting_context/layout_ifc were skipped).
                #[cfg(feature = "web_lift")]
                unsafe {
                    crate::az_mark((0x60A60 + (node_index & 7) * 4) as u32, (0xC0DE0001) as u32);
                }
                // Miss triage (AZ_PROFILE=cpu): a steady-state resize showed
                // 1020/1020 misses — this names WHICH failure it is. "empty"
                // = slot never stored / cleared (invalidation or remap loss);
                // "sizekey" = an entry exists but was stored under different
                // constraints (the slot-0 collapse overwriting, or a genuine
                // containing-block change); "laykey" = only the layout slot
                // exists and its key mismatches.
                {
28411
                    let e = &ctx.cache_map.entries[node_index];
28411
                    let reason = if let Some(m) = e.measure_entries[size_slot].as_ref() {
4134
                        let dw = (size_key.width - m.available_size.width).abs();
4134
                        let dh = (size_key.height - m.available_size.height).abs();
4134
                        if dw >= CACHE_SIZE_EPSILON && dh >= CACHE_SIZE_EPSILON {
149
                            "size_cache_miss_sizekey_both"
3985
                        } else if dw >= CACHE_SIZE_EPSILON {
3985
                            "size_cache_miss_sizekey_w"
                        } else {
                            // Which SIDE of the height pair is the indefinite
                            // sentinel? q∞/s∞ = the measure-vs-final ping-pong
                            // (one slot alternating between an indefinite
                            // measure query and a definite final query);
                            // finite/finite = a genuinely changed containing
                            // block height.
                            const BIG: f32 = 1.0e9;
                            let qi = size_key.height >= BIG || !size_key.height.is_finite();
                            let si = m.available_size.height >= BIG
                                || !m.available_size.height.is_finite();
                            match (qi, si) {
                                (true, false) => "size_cache_miss_sizekey_h_qinf",
                                (false, true) => "size_cache_miss_sizekey_h_sinf",
                                (true, true) => "size_cache_miss_sizekey_h_bothinf",
                                (false, false) => "size_cache_miss_sizekey_h_finite",
                            }
                        }
24277
                    } else if e.layout_entry.is_some() {
2198
                        "size_cache_miss_laykey"
                    } else {
22079
                        "size_cache_miss_empty"
                    };
28411
                    drop(crate::probe::Probe::span(reason));
                }
28411
                drop(crate::probe::Probe::span("size_cache_miss"));
            }
            ComputeMode::PerformLayout => {
                // PerformLayout: check layout slot (the single "full layout" slot)
12301
                let layout_hit = ctx.cache_map.entries[node_index]
12301
                    .get_layout(containing_block_size)
12301
                    .cloned();
12301
                if let Some(cached_layout) = layout_hit {
161
                    drop(crate::probe::Probe::span("pos_cache_hit"));
                    // LAYOUT CACHE HIT — apply cached results with child positions
161
                    if let Some(node) = tree.get_mut(LayoutNodeId::new(node_index)) {
161
                        node.used_size = Some(cached_layout.result_size);
161
                    }
161
                    if let Some(warm) = tree.warm_mut(LayoutNodeId::new(node_index)) {
161
                        warm.overflow_content_size = Some(cached_layout.content_size);
161
                        warm.scrollbar_info = Some(cached_layout.scrollbar_info);
161
                    }
161
                    let box_props = tree
161
                        .get(LayoutNodeId::new(node_index))
161
                        .map(|n| n.box_props.unpack())
161
                        .unwrap_or_default();
161
                    let writing_mode = tree
161
                        .warm(LayoutNodeId::new(node_index))
161
                        .map(|w| w.computed_style.writing_mode)
161
                        .unwrap_or_default();
161
                    let self_content_box_pos =
161
                        calculate_content_box_pos(containing_block_pos, &box_props);
                    // Apply cached child positions and recurse
161
                    let result_size = cached_layout.result_size;
723
                    for (child_index, child_relative_pos) in &cached_layout.child_positions {
562
                        let child_abs_pos = LogicalPosition::new(
562
                            self_content_box_pos.x + child_relative_pos.x,
562
                            self_content_box_pos.y + child_relative_pos.y,
                        );
562
                        super::pos_set(calculated_positions, *child_index, child_abs_pos);
562
                        let inner = box_props.inner_size(result_size, writing_mode);
                        // Subtract scrollbar reservation from the available size
                        // passed to children. This mirrors what layout_bfc does in
                        // the MISS path — without it, a reflow-loop cache hit
                        // would hand children the full content-box width, ignoring
                        // any vertical/horizontal scrollbar that was detected.
562
                        let child_available_size = cached_layout.scrollbar_info.shrink_size(inner);
                        // A cache-hit parent has a RESOLVED content box, so the
                        // children's containing block is fully definite.
562
                        let child_cb =
562
                            super::geometry::ContainingBlock::definite(child_available_size);
562
                        calculate_layout_for_subtree(
562
                            ctx,
562
                            tree,
562
                            text_cache,
562
                            *child_index,
562
                            child_abs_pos,
562
                            &child_cb,
562
                            calculated_positions,
562
                            reflow_needed_for_scrollbars,
562
                            float_cache,
562
                            compute_mode,
                        )?;
                    }
161
                    return Ok(());
12140
                }
            }
        }
60
    }
    // === CACHE MISS — compute layout ===
40611
    if compute_mode == ComputeMode::PerformLayout {
12167
        drop(crate::probe::Probe::span("pos_cache_miss"));
28444
    }
    // returned Ok; 0x64 = layout_formatting_context returned Ok. Last value before the
    // Err pins the failing phase (fires per recursive node; bare body is shallow).
    // Phase 1: Prepare layout context (calculate used size, constraints)
    let PreparedLayoutContext {
40611
        mut constraints,
40611
        dom_id,
40611
        writing_mode,
40611
        mut final_used_size,
40611
        box_props,
    } = {
40611
        let _p = crate::probe::Probe::span("prepare_layout_context");
40611
        prepare_layout_context(ctx, tree, node_index, cb)?
    };
    // K30b: arm this subtree's fragmentainer (None on the continuous path).
40611
    if let Some(fs) = fragment {
60
        constraints.fragmentainer = Some(fs);
40551
    }
    // Phase 1.5: Update used_size BEFORE calling layout_formatting_context.
    //
    // When a node is cloned from the old tree (clone_node_from_old), its used_size
    // retains the value from the previous layout pass. If the containing block changed
    // (e.g. viewport resize), the stale used_size would cause layout_bfc() to compute
    // an incorrect children_containing_block_size. By updating used_size here, we ensure
    // that layout_bfc reads the freshly resolved size from prepare_layout_context.
    {
40611
        let is_table_cell = tree
40611
            .get(LayoutNodeId::new(node_index))
40611
            .is_some_and(|n| matches!(n.formatting_context, FormattingContext::TableCell));
40611
        if !is_table_cell {
38091
            if let Some(node) = tree.get_mut(LayoutNodeId::new(node_index)) {
38091
                node.used_size = Some(final_used_size);
38091
            }
2520
        }
    }
    // Phase 2: Layout children using the formatting context
40611
    let layout_result = {
40611
        let _p = crate::probe::Probe::span("layout_formatting_context");
40611
        layout_formatting_context(ctx, tree, text_cache, node_index, &constraints, float_cache)?
    };
    // K30b: hand the subtree's resume state up (None = finished).
40611
    if let Some(slot) = fragment_out {
60
        slot.clone_from(&layout_result.outgoing_token);
40551
    }
40611
    let content_size = layout_result.output.overflow_size;
    // If layout_formatting_context adjusted this node's used_size (e.g.
    // layout_flex_grid auto-applying box-sizing:border-box on the root),
    // propagate that back into final_used_size so Phase 3 (scrollbars),
    // Phase 4 (final write), and the self_content_box_pos calculation all
    // see the same border-box that the children were laid out inside.
40611
    if let Some(adjusted) = tree
40611
        .get(LayoutNodeId::new(node_index))
40611
        .and_then(|n| n.used_size)
39671
    {
39671
        final_used_size = adjusted;
39671
    }
    // Phase 2.5: Resolve 'auto' main-axis size based on content
    // For anonymous boxes, use default styled node state
40611
    let styled_node_state = dom_id
40611
        .and_then(|id| ctx.styled_dom.styled_nodes.as_container().get(id).cloned())
40611
        .map(|n| n.styled_node_state)
40611
        .unwrap_or_default();
40611
    let css_height: MultiValue<LayoutHeight> = match dom_id {
40466
        Some(id) => get_css_height(ctx.styled_dom, id, &styled_node_state),
145
        None => MultiValue::Auto, // Anonymous boxes have auto height
    };
    // +spec:overflow:44ef3b - scroll container detection: overflow scroll/auto makes box a scroll
    // container A box whose BLOCK (height) axis scrolls must NOT expand to fit content —
    // its height comes from the containing block and the overflow scrolls. But
    // that gate is per-AXIS: `overflow-x` / `overflow-y` are PHYSICAL, so only a
    // VERTICAL scroll container (`overflow-y: scroll|auto`) fixes the height.
    // A purely HORIZONTAL scroll container — e.g. a single-line text field with
    // `overflow-x: auto, overflow-y: hidden` — must still grow its height to the
    // text line. Gating on EITHER axis collapsed such a field to zero height, so
    // its overflowing line was never measured and it never became a scroll box
    // the caret-reveal could shift (the append-only caret bug).
    //
    // Exception: if the containing block height is infinite (unconstrained),
    // we must still grow, since you can't scroll inside an infinitely tall box.
40611
    let scrolls_vertically = dom_id.is_some_and(|id| {
40466
        let ov_y = get_overflow_y(ctx.styled_dom, id, &styled_node_state);
39964
        matches!(
40460
            ov_y,
            MultiValue::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto)
        )
40466
    });
40611
    if should_use_content_height(&css_height) {
31914
        let skip_expansion = scrolls_vertically
1
            && containing_block_size.height.is_finite()
1
            && containing_block_size.height > 0.0;
31914
        if !skip_expansion {
31913
            final_used_size = apply_content_based_height(
31913
                final_used_size,
31913
                content_size,
31913
                tree,
31913
                node_index,
31913
                writing_mode,
            )?;
1
        }
8697
    }
    // Phase 3: Scrollbar handling
    // Anonymous boxes don't have scrollbars
40611
    let skip_scrollbar_check = ctx.fragmentation_context.is_some();
40611
    let scrollbar_info = dom_id.map_or_else(ScrollbarRequirements::default, |id| {
40466
        compute_scrollbar_info(
40466
            ctx,
40466
            id,
40466
            &styled_node_state,
40466
            content_size,
40466
            &box_props,
40466
            final_used_size,
40466
            writing_mode,
        )
40466
    });
40611
    if check_scrollbar_change(tree, node_index, &scrollbar_info, skip_scrollbar_check) {
368
        *reflow_needed_for_scrollbars = true;
40243
    }
40611
    let merged_scrollbar_info = scrollbar_info;
40611
    let content_box_size = box_props.inner_size(final_used_size, writing_mode);
40611
    let inner_size_after_scrollbars = merged_scrollbar_info.shrink_size(content_box_size);
    // Phase 4: Update this node's state
40611
    let self_content_box_pos = {
        {
40611
            let current_node = tree
40611
                .get_mut(LayoutNodeId::new(node_index))
40611
                .ok_or(LayoutError::InvalidTree)?;
            // Table cells get their size from the table layout algorithm, don't overwrite
40611
            let is_table_cell = matches!(
40611
                current_node.formatting_context,
                FormattingContext::TableCell
            );
40611
            if !is_table_cell || current_node.used_size.is_none() {
39031
                current_node.used_size = Some(final_used_size);
39031
            }
        }
        // Update warm fields
40611
        if let Some(warm) = tree.warm_mut(LayoutNodeId::new(node_index)) {
40611
            warm.scrollbar_info = Some(merged_scrollbar_info);
40611
            // Store overflow content size for scroll frame calculation
40611
            // +spec:overflow:f28d6a - hanging glyphs should be ink overflow, not scrollable
40611
            // overflow (not yet subtracted from content_size)
40611
            warm.overflow_content_size = Some(content_size);
40611
        }
        // self_content_box_pos is [CoordinateSpace::Window] - the absolute position of this node's
        // content-box
40611
        let current_node = tree
40611
            .get(LayoutNodeId::new(node_index))
40611
            .ok_or(LayoutError::InvalidTree)?;
40611
        let current_bp = current_node.box_props.unpack();
40611
        let pos = calculate_content_box_pos(containing_block_pos, &current_bp);
40611
        log_content_box_calculation(ctx, node_index, current_node, containing_block_pos, pos);
40611
        pos
    };
    // Phase 5: Determine formatting context type
40611
    let is_flex_or_grid = {
40611
        let node = tree
40611
            .get(LayoutNodeId::new(node_index))
40611
            .ok_or(LayoutError::InvalidTree)?;
36941
        matches!(
40611
            node.formatting_context,
            FormattingContext::Flex | FormattingContext::Grid
        )
    };
    // Phase 6: Process in-flow children
    // Positions in layout_result.output.positions are [CoordinateSpace::Parent] - relative to this
    // node's content-box
40611
    let positions: Vec<_> = layout_result
40611
        .output
40611
        .positions
40611
        .iter()
40611
        .map(|(&idx, &pos)| (idx, pos))
40611
        .collect();
    // Store child positions for cache
40611
    let child_positions_for_cache: Vec<(usize, LogicalPosition)> = positions.clone();
79764
    for (child_index, child_relative_pos) in positions {
39153
        process_inflow_child(
39153
            ctx,
39153
            tree,
39153
            text_cache,
39153
            child_index,
39153
            child_relative_pos,
39153
            self_content_box_pos,
39153
            inner_size_after_scrollbars,
39153
            writing_mode,
39153
            is_flex_or_grid,
39153
            calculated_positions,
39153
            *reflow_needed_for_scrollbars,
39153
            float_cache,
        )?;
    }
    // Phase 7: Process out-of-flow children (absolute/fixed). The node's own
    // used size is resolved by now, so the abs-pos containing block is
    // definite regardless of the constraint this node was measured under.
40611
    process_out_of_flow_children(
40611
        ctx,
40611
        tree,
40611
        text_cache,
40611
        node_index,
40611
        self_content_box_pos,
40611
        &super::geometry::ContainingBlock::definite(inner_size_after_scrollbars),
40611
        calculated_positions,
40611
        reflow_needed_for_scrollbars,
40611
        float_cache,
    )?;
    // === STORE RESULT IN PER-NODE CACHE (Taffy-inspired 9+1 slot cache) ===
    // Store both the full layout entry and a sizing measurement entry.
    // This enables O(n) two-pass BFC: Pass 1 populates cache, Pass 2 reads it.
    // Fragment passes never store (NG rule, same as the hit-side gate above:
    // fragment geometry would poison the continuous cache).
40611
    if fragment.is_none() && node_index < ctx.cache_map.entries.len() {
40551
        let warm_ref = tree.warm(LayoutNodeId::new(node_index));
40551
        let baseline = warm_ref.and_then(|n| n.baseline);
40551
        let escaped_top = warm_ref.and_then(|n| n.escaped_top_margin);
40551
        let escaped_bottom = warm_ref.and_then(|n| n.escaped_bottom_margin);
        // Store in the layout slot (PerformLayout result)
40551
        ctx.cache_map
40551
            .get_mut(node_index)
40551
            .store_layout(LayoutCacheEntry {
40551
                available_size: containing_block_size,
40551
                result_size: final_used_size,
40551
                content_size,
40551
                child_positions: child_positions_for_cache,
40551
                escaped_top_margin: escaped_top,
40551
                escaped_bottom_margin: escaped_bottom,
40551
                scrollbar_info: merged_scrollbar_info,
40551
            });
        // Also store in the measurement slot matching THIS constraint shape
        // (same classification as the lookup — the measure visit and the
        // final visit must land in different slots or they evict each other
        // every pass). The canonicalized key replaces the raw containing
        // block so an indefinite axis compares equal next time.
40551
        let (size_slot, size_key) = NodeCache::classify_size_key(containing_block_size);
40551
        ctx.cache_map.get_mut(node_index).store_size(
40551
            size_slot,
40551
            SizingCacheEntry {
40551
                available_size: size_key,
40551
                result_size: final_used_size,
40551
                baseline,
40551
                escaped_top_margin: escaped_top,
40551
                escaped_bottom_margin: escaped_bottom,
40551
            },
        );
60
    }
40611
    Ok(())
48118
}
/// Recursively set static positions for out-of-flow descendants without doing layout
/// Recursively positions descendants of Flex/Grid children.
///
/// When a Flex container lays out its children via Taffy, the children have their
/// `used_size` and `relative_position` set, but their GRANDCHILDREN don't have positions
/// in `calculated_positions` yet. This function traverses down the tree and positions
/// all descendants properly.
179526
fn position_flex_child_descendants(
179526
    tree: &mut LayoutTree,
179526
    node_index: usize,
179526
    content_box_pos: LogicalPosition,
179526
    available_size: LogicalSize,
179526
    calculated_positions: &mut super::PositionVec,
179526
) -> Result<()> {
179526
    let children: Vec<usize> = tree.children(node_index).to_vec();
353703
    for &child_index in &children {
174178
        let child_node = tree
174178
            .get(LayoutNodeId::new(child_index))
174178
            .ok_or(LayoutError::InvalidTree)?;
174177
        let child_rel_pos = tree
174177
            .warm(LayoutNodeId::new(child_index))
174177
            .and_then(|w| w.relative_position)
174177
            .unwrap_or_default();
174177
        let child_abs_pos = LogicalPosition::new(
174177
            content_box_pos.x + child_rel_pos.x,
174177
            content_box_pos.y + child_rel_pos.y,
        );
        // Insert position
174177
        super::pos_set(calculated_positions, child_index, child_abs_pos);
        // Get child's content box for recursion
174177
        let cbp = child_node.box_props.unpack();
174177
        let child_writing_mode = tree
174177
            .warm(LayoutNodeId::new(child_index))
174177
            .map(|w| w.computed_style.writing_mode)
174177
            .unwrap_or_default();
174177
        let child_content_box = LogicalPosition::new(
174177
            child_abs_pos.x + cbp.border.left + cbp.padding.left,
174177
            child_abs_pos.y + cbp.border.top + cbp.padding.top,
        );
174177
        let child_inner_size =
174177
            cbp.inner_size(child_node.used_size.unwrap_or_default(), child_writing_mode);
        // Recurse
174177
        position_flex_child_descendants(
174177
            tree,
174177
            child_index,
174177
            child_content_box,
174177
            child_inner_size,
174177
            calculated_positions,
        )?;
    }
179525
    Ok(())
179526
}
/// Checks if the given CSS height value should use content-based sizing
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
                                  // (or cross-type bindings that can't merge)
53270
fn should_use_content_height(css_height: &MultiValue<LayoutHeight>) -> bool {
53270
    match css_height {
        MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => {
            // Auto/Initial/Inherit height should use content-based sizing
40062
            true
        }
13208
        MultiValue::Exact(height) => match height {
            LayoutHeight::Auto => {
                // Auto height should use content-based sizing
1
                true
            }
13203
            LayoutHeight::Px(px) => {
                // Check if it's zero or if it has explicit value
                // If it's a percentage or em, it's not auto
                use azul_css::props::basic::{pixel::PixelValue, SizeMetric};
13203
                px == &PixelValue::zero()
13201
                    || (px.metric != SizeMetric::Px
1010
                        && px.metric != SizeMetric::Percent
8
                        && px.metric != SizeMetric::Em
7
                        && px.metric != SizeMetric::Rem)
            }
            LayoutHeight::MinContent | LayoutHeight::MaxContent | LayoutHeight::FitContent(_) => {
                // These are content-based, so they should use the content size
3
                true
            }
            LayoutHeight::Calc(_) => {
                // Calc expressions are not auto, they compute to a specific value
1
                false
            }
        },
    }
53270
}
/// Applies content-based height sizing to a node
///
/// **Note**: This function respects min-height/max-height constraints from Phase 1.
///
/// According to CSS 2.2 § 10.7, when height is 'auto', the final height must be
/// `max(min_height`, `min(content_height`, `max_height`)).
///
/// The `used_size` parameter already contains the size constrained by
/// min-height/max-height from the initial sizing pass. We must take the
/// maximum of this constrained size and the new content-based size to ensure
/// min-height is not lost.
40070
fn apply_content_based_height(
40070
    mut used_size: LogicalSize,
40070
    content_size: LogicalSize,
40070
    tree: &LayoutTree,
40070
    node_index: usize,
40070
    writing_mode: LayoutWritingMode,
40070
) -> Result<LogicalSize> {
40070
    let node = tree
40070
        .get(LayoutNodeId::new(node_index))
40070
        .ok_or(LayoutError::InvalidTree)?;
40068
    let node_props = node.box_props.unpack();
    // `content_size` is `LayoutOutput::overflow_size`, and that is NOT the
    // same extent in every formatting context (`atomic_inline_auto_height`
    // in `fc.rs` tells the same story for atomic inlines): `layout_bfc`
    // reports the CONTENT box, so padding and border are added to reach the
    // border box; `layout_flex_grid` reports taffy's `content_size` with
    // only the leading border stripped — the padding is still inside it,
    // deliberately, because the scrollbar geometry measures in the padding
    // box. Adding the padding to THAT counts it twice: an `inline-flex`
    // button with `padding: 6px 12px` laid out as a BLOCK-level child — of a
    // `flow-root` box, or of a replaced element's interior run (the opengl
    // example's `Button` over its canvas) — came out 40 px instead of the
    // 28 px taffy had sized it to, with its label centred in the 28.
40068
    let main_axis_extra = match node.formatting_context {
        FormattingContext::Flex | FormattingContext::Grid => {
2174
            node_props.border.main_sum(writing_mode)
        }
37894
        _ => node_props.padding.main_sum(writing_mode) + node_props.border.main_sum(writing_mode),
    };
    // CRITICAL: 'old_main_size' holds the size constrained by min-height/max-height from Phase 1
40068
    let old_main_size = used_size.main(writing_mode);
40068
    let new_main_size = content_size.main(writing_mode) + main_axis_extra;
    // Final size = max(min_height_constrained_size, content_size)
    // This ensures that min-height is respected even when content is smaller
40068
    let final_main_size = old_main_size.max(new_main_size);
40068
    used_size = used_size.with_main(writing_mode, final_main_size);
40068
    Ok(used_size)
40070
}
// hash_styled_node_data() removed — replaced by NodeDataFingerprint::compute()
260744
fn calculate_subtree_hash(node_self_hash: u64, child_hashes: &[u64]) -> SubtreeHash {
260744
    let mut hasher = DefaultHasher::new();
260744
    node_self_hash.hash(&mut hasher);
260744
    child_hashes.hash(&mut hasher);
260744
    SubtreeHash(hasher.finish())
260744
}
/// Computes CSS counter values for all nodes in the layout tree.
///
/// This function traverses the tree in document order and processes counter-reset
/// and counter-increment properties. The computed values are stored in cache.counters.
///
/// CSS counters work with a stack-based scoping model:
/// - `counter-reset` creates a new scope and sets the counter to a value
/// - `counter-increment` increments the counter in the current scope
/// - When leaving a subtree, counter scopes are popped
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher
                                  // HashMap/HashSet
10444
pub fn compute_counters(
10444
    styled_dom: &StyledDom,
10444
    tree: &LayoutTree,
10444
    counters: &mut HashMap<(usize, String), i32>,
10444
) {
    // Track counter stacks: counter_name -> Vec<value>
    // Each entry in the Vec represents a nested scope
10444
    let mut counter_stacks: HashMap<String, Vec<i32>> = HashMap::new();
    // Stack to track which counters were reset at each tree level
    // When we pop back up the tree, we need to pop these counter scopes
10444
    let mut scope_stack: Vec<Vec<String>> = Vec::new();
10444
    compute_counters_recursive(
10444
        styled_dom,
10444
        tree,
10444
        tree.root,
10444
        counters,
10444
        &mut counter_stacks,
10444
        &mut scope_stack,
    );
10444
}
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
273674
fn compute_counters_recursive(
273674
    styled_dom: &StyledDom,
273674
    tree: &LayoutTree,
273674
    node_idx: usize,
273674
    counters: &mut HashMap<(usize, String), i32>,
273674
    counter_stacks: &mut HashMap<String, Vec<i32>>,
273674
    scope_stack: &mut Vec<Vec<String>>,
273674
) {
273674
    let Some(node) = tree.get(LayoutNodeId::new(node_idx)) else {
1
        return;
    };
    // Skip pseudo-elements (::marker, ::before, ::after) for counter processing
    // Pseudo-elements inherit counter values from their parent element
    // but don't participate in counter-reset or counter-increment themselves
273673
    if tree
273673
        .warm(LayoutNodeId::new(node_idx))
273673
        .and_then(|w| w.pseudo_element.as_ref())
273673
        .is_some()
    {
        // Store the parent's counter values for this pseudo-element
        // so it can be looked up during marker text generation
1560
        if let Some(parent_idx) = node.parent {
            // Copy all counter values from parent to this pseudo-element
1560
            let parent_counters: Vec<_> = counters
1560
                .iter()
8060
                .filter(|((idx, _), _)| *idx == parent_idx)
1560
                .map(|((_, name), &value)| (name.clone(), value))
1560
                .collect();
3120
            for (counter_name, value) in parent_counters {
1560
                counters.insert((node_idx, counter_name), value);
1560
            }
        }
        // Don't recurse to children of pseudo-elements
        // (pseudo-elements shouldn't have children in normal circumstances)
1560
        return;
272113
    }
    // Only process real DOM nodes, not anonymous boxes
272113
    let Some(dom_id) = node.dom_node_id else {
        // For anonymous boxes, just recurse to children
406
        for &child_idx in tree.children(node_idx) {
406
            compute_counters_recursive(
406
                styled_dom,
406
                tree,
406
                child_idx,
406
                counters,
406
                counter_stacks,
406
                scope_stack,
406
            );
406
        }
243
        return;
    };
271870
    let node_data = &styled_dom.node_data.as_container()[dom_id];
271870
    let node_state = &styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
271870
    let cache = &styled_dom.css_property_cache.ptr;
    // Track which counters we reset at this level (for cleanup later)
271870
    let mut reset_counters_at_this_level = Vec::new();
    // CSS Lists §3: display: list-item automatically increments the "list-item" counter
    // Check if this is a list-item
271870
    let display = {
        use crate::solver3::getters::get_display_property;
271870
        get_display_property(styled_dom, Some(dom_id)).exact()
    };
271870
    let is_list_item = matches!(display, Some(LayoutDisplay::ListItem));
    // FAST PATH: almost no nodes declare counter-reset/counter-increment.
    // Single-bit check in compact cache lets us skip two cascade walks per node.
271870
    let has_counter_css = node_state.is_normal()
271859
        && cache
271859
            .compact_cache
271859
            .as_ref()
271859
            .is_none_or(|cc| cc.has_counter(dom_id.index()));
    // Process counter-reset (now properly typed)
271870
    let counter_reset = if has_counter_css {
531
        cache
531
            .get_counter_reset(node_data, &dom_id, node_state)
531
            .and_then(|v| v.get_property())
    } else {
271339
        None
    };
271870
    if let Some(counter_reset) = counter_reset {
530
        let counter_name_str = counter_reset.counter_name.as_str();
530
        if counter_name_str != "none" {
530
            let counter_name = counter_name_str.to_string();
530
            let reset_value = counter_reset.value;
530

            
530
            // Reset the counter by pushing a new scope
530
            counter_stacks
530
                .entry(counter_name.clone())
530
                .or_default()
530
                .push(reset_value);
530
            reset_counters_at_this_level.push(counter_name);
530
        }
271340
    }
    // Process counter-increment (now properly typed)
271870
    let counter_inc = if has_counter_css {
531
        cache
531
            .get_counter_increment(node_data, &dom_id, node_state)
531
            .and_then(|v| v.get_property())
    } else {
271339
        None
    };
271870
    if let Some(counter_inc) = counter_inc {
        let counter_name_str = counter_inc.counter_name.as_str();
        if counter_name_str != "none" {
            let counter_name = counter_name_str.to_string();
            let inc_value = counter_inc.value;
            // Increment the counter in the current scope
            let stack = counter_stacks.entry(counter_name).or_default();
            if stack.is_empty() {
                // Auto-initialize if counter doesn't exist
                stack.push(inc_value);
            } else if let Some(current) = stack.last_mut() {
                *current += inc_value;
            }
        }
271870
    }
    // CSS Lists §3: display: list-item automatically increments "list-item" counter
271870
    if is_list_item {
1562
        let counter_name = "list-item".to_string();
1562
        let stack = counter_stacks.entry(counter_name).or_default();
1562
        if stack.is_empty() {
11
            // Auto-initialize if counter doesn't exist
11
            stack.push(1);
1551
        } else if let Some(current) = stack.last_mut() {
1551
            *current += 1;
1551
        }
270308
    }
    // Store the current counter values for this node
271870
    for (counter_name, stack) in counter_stacks.iter() {
30592
        if let Some(&value) = stack.last() {
3732
            counters.insert((node_idx, counter_name.clone()), value);
26862
        }
    }
    // Push scope tracking for cleanup
271870
    scope_stack.push(reset_counters_at_this_level.clone());
    // Recurse to children
271870
    for &child_idx in tree.children(node_idx) {
262824
        compute_counters_recursive(
262824
            styled_dom,
262824
            tree,
262824
            child_idx,
262824
            counters,
262824
            counter_stacks,
262824
            scope_stack,
262824
        );
262824
    }
    // Pop counter scopes that were created at this level
271870
    if let Some(reset_counters) = scope_stack.pop() {
272400
        for counter_name in reset_counters {
530
            if let Some(stack) = counter_stacks.get_mut(&counter_name) {
530
                stack.pop();
530
            }
        }
    }
273674
}
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod autotest_generated {
    use azul_core::dom::{Dom, IdOrClass};
    use azul_css::props::{
        basic::{pixel::PixelValue, SizeMetric},
        layout::dimensions::CalcAstItemVec,
    };
    use super::*;
    use crate::solver3::{
        display_list::DisplayList,
        geometry::{EdgeSizes, MarginAuto, PackedBoxProps, ResolvedBoxProps},
        layout_tree::{LayoutNodeCold, LayoutNodeWarm},
        pos_get, PositionVec, POSITION_UNSET,
    };
    // ------------------------------------------------------------------
    // Fixtures
    // ------------------------------------------------------------------
    fn size(w: f32, h: f32) -> LogicalSize {
        LogicalSize::new(w, h)
    }
    fn pos(x: f32, y: f32) -> LogicalPosition {
        LogicalPosition::new(x, y)
    }
    fn sizing_entry(available: LogicalSize, result: LogicalSize) -> SizingCacheEntry {
        SizingCacheEntry {
            available_size: available,
            result_size: result,
            baseline: None,
            escaped_top_margin: None,
            escaped_bottom_margin: None,
        }
    }
    fn layout_entry(available: LogicalSize, result: LogicalSize) -> LayoutCacheEntry {
        LayoutCacheEntry {
            available_size: available,
            result_size: result,
            content_size: result,
            child_positions: Vec::new(),
            escaped_top_margin: None,
            escaped_bottom_margin: None,
            scrollbar_info: ScrollbarRequirements::default(),
        }
    }
    fn edges(top: f32, right: f32, bottom: f32, left: f32) -> EdgeSizes {
        EdgeSizes {
            top,
            right,
            bottom,
            left,
        }
    }
    fn box_props(margin: EdgeSizes, border: EdgeSizes, padding: EdgeSizes) -> ResolvedBoxProps {
        ResolvedBoxProps {
            margin,
            padding,
            border,
            margin_auto: MarginAuto::default(),
        }
    }
    fn zero_box_props() -> ResolvedBoxProps {
        box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(0.0, 0.0, 0.0, 0.0),
            edges(0.0, 0.0, 0.0, 0.0),
        )
    }
    fn hot(
        parent: Option<usize>,
        dom_node_id: Option<NodeId>,
        used_size: Option<LogicalSize>,
        bp: &ResolvedBoxProps,
    ) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: PackedBoxProps::pack(bp),
            dom_node_id,
            used_size,
            formatting_context: FormattingContext::Block {
                establishes_new_context: false,
            },
            parent,
        }
    }
    /// Plain hot node with no box props and no DOM id.
    fn plain(parent: Option<usize>) -> LayoutNodeHot {
        hot(parent, None, Some(size(0.0, 0.0)), &zero_box_props())
    }
    /// Builds a `LayoutTree` from hot nodes + per-node child lists.
    /// `child_lists[i]` are the children of node `i`.
    fn build_tree(
        nodes: Vec<LayoutNodeHot>,
        warm: Vec<LayoutNodeWarm>,
        child_lists: &[Vec<usize>],
    ) -> LayoutTree {
        let n = nodes.len();
        let mut children_arena: Vec<usize> = Vec::new();
        let mut children_offsets: Vec<(u32, u32)> = Vec::with_capacity(n);
        for cl in child_lists {
            let start = u32::try_from(children_arena.len()).unwrap();
            children_arena.extend_from_slice(cl);
            children_offsets.push((start, u32::try_from(cl.len()).unwrap()));
        }
        while children_offsets.len() < n {
            children_offsets.push((0, 0));
        }
        LayoutTree {
            nodes,
            warm,
            cold: vec![LayoutNodeCold::default(); n],
            root: 0,
            dom_to_layout: BTreeMap::new(),
            children_arena,
            children_offsets,
            subtree_needs_intrinsic: Vec::new(),
        }
    }
    fn warm_default(n: usize) -> Vec<LayoutNodeWarm> {
        vec![LayoutNodeWarm::default(); n]
    }
    fn div_class(class: &str) -> Dom {
        Dom::create_div().with_ids_and_classes(vec![IdOrClass::Class(class.into())].into())
    }
    fn styled(dom: Dom, css_str: &str) -> StyledDom {
        let mut dom = dom;
        let (css, _warnings) = azul_css::parser2::new_from_str(css_str);
        StyledDom::create(&mut dom, css)
    }
    /// `body(0) > .p(1) > [ text " \n\t"(2), text "hi"(3), div(4), text NBSP(5) ]`
    ///
    /// DOM ids follow the depth-first pre-order numbering of `CompactDom`.
    fn whitespace_dom(css_str: &str) -> StyledDom {
        styled(
            Dom::create_body().with_child(
                div_class("p")
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                        " \n\t",
                    ))
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                        "hi",
                    ))
                    .with_child(Dom::create_div())
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                        "\u{00A0}",
                    )),
            ),
            css_str,
        )
    }
    // ==================================================================
    // NodeCache — slot cache (numeric / round-trip)
    // ==================================================================
    #[test]
    fn nodecache_default_is_empty_and_never_hits() {
        let c = NodeCache::default();
        assert!(c.is_empty);
        assert!(c.layout_entry.is_none());
        assert!(c.measure_entries.iter().all(Option::is_none));
        for slot in 0..9 {
            assert!(c.get_size(slot, size(0.0, 0.0)).is_none());
            assert!(c.get_size(slot, size(100.0, 100.0)).is_none());
        }
        assert!(c.get_layout(size(0.0, 0.0)).is_none());
    }
    #[test]
    fn nodecache_store_size_then_exact_lookup_round_trips() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(200.0, 100.0), size(50.0, 40.0)));
        assert!(!c.is_empty);
        let hit = c.get_size(0, size(200.0, 100.0)).expect("exact hit");
        assert_eq!(hit.available_size, size(200.0, 100.0));
        assert_eq!(hit.result_size, size(50.0, 40.0));
    }
    #[test]
    fn nodecache_get_size_result_matches_request() {
        // Taffy's key optimization: Pass 2 hands back the size Pass 1 produced.
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(200.0, 100.0), size(50.0, 40.0)));
        let hit = c
            .get_size(0, size(50.0, 40.0))
            .expect("result-matches-request hit");
        assert_eq!(hit.result_size, size(50.0, 40.0));
        // A size matching neither the request nor the result must miss.
        assert!(c.get_size(0, size(51.0, 41.0)).is_none());
    }
    #[test]
    fn nodecache_get_size_epsilon_boundary() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(100.0, 100.0), size(10.0, 10.0)));
        // Sub-epsilon drift on either axis is still a hit (CACHE_SIZE_EPSILON = 0.1).
        assert!(c.get_size(0, size(100.05, 99.95)).is_some());
        // A drift clearly past the epsilon is a miss on both the request and the
        // result comparison. (The exact `== EPSILON` boundary is deliberately not
        // asserted: `100.1f32 - 100.0f32` rounds to 0.09999847, just under it.)
        assert!(c.get_size(0, size(100.2, 100.0)).is_none());
        assert!(c.get_size(0, size(100.0, 99.5)).is_none());
    }
    #[test]
    fn nodecache_get_size_nan_request_misses_instead_of_panicking() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(100.0, 100.0), size(10.0, 10.0)));
        // NaN - x = NaN, and every NaN comparison is false → miss, not a hit.
        assert!(c.get_size(0, size(f32::NAN, 100.0)).is_none());
        assert!(c.get_size(0, size(100.0, f32::NAN)).is_none());
        assert!(c.get_size(0, size(f32::NAN, f32::NAN)).is_none());
    }
    #[test]
    fn nodecache_nan_and_infinite_entries_are_unreachable() {
        // An entry stored with a non-finite available/result size can never be
        // hit again (inf - inf = NaN, NaN - NaN = NaN) — the node simply gets
        // re-measured. That is safe, but it means such slots are dead weight.
        let mut c = NodeCache::default();
        c.store_size(
            0,
            sizing_entry(
                size(f32::INFINITY, f32::INFINITY),
                size(f32::INFINITY, f32::INFINITY),
            ),
        );
        assert!(c.get_size(0, size(f32::INFINITY, f32::INFINITY)).is_none());
        c.store_size(
            1,
            sizing_entry(size(f32::NAN, f32::NAN), size(f32::NAN, f32::NAN)),
        );
        assert!(c.get_size(1, size(f32::NAN, f32::NAN)).is_none());
        // ...but the cache still reports itself as populated.
        assert!(!c.is_empty);
    }
    #[test]
    fn nodecache_handles_zero_and_negative_sizes() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(0.0, 0.0), size(0.0, 0.0)));
        assert!(c.get_size(0, size(0.0, 0.0)).is_some());
        assert!(c.get_size(0, size(-0.0, -0.0)).is_some());
        c.store_size(1, sizing_entry(size(-100.0, -50.0), size(-1.0, -1.0)));
        let hit = c
            .get_size(1, size(-100.0, -50.0))
            .expect("negative sizes are deterministic");
        assert_eq!(hit.result_size, size(-1.0, -1.0));
    }
    #[test]
    fn nodecache_extreme_finite_sizes_do_not_panic() {
        let mut c = NodeCache::default();
        c.store_size(
            0,
            sizing_entry(size(f32::MAX, f32::MIN), size(f32::MAX, f32::MIN)),
        );
        // MAX - MAX == 0 → exact hit; no overflow panic on the subtraction.
        assert!(c.get_size(0, size(f32::MAX, f32::MIN)).is_some());
        // MIN - MAX overflows to -inf, abs() = inf, inf < 0.1 is false → miss.
        assert!(c.get_size(0, size(f32::MIN, f32::MAX)).is_none());
    }
    #[test]
    fn nodecache_slots_are_independent() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(1.0, 1.0), size(9.0, 9.0)));
        c.store_size(8, sizing_entry(size(2.0, 2.0), size(7.0, 7.0)));
        assert!(c.get_size(0, size(1.0, 1.0)).is_some());
        assert!(c.get_size(8, size(2.0, 2.0)).is_some());
        // No cross-talk between slots on the AVAILABLE-SIZE key: a query
        // whose constraints were stored in another slot does not hit here
        // (result sizes chosen so the result-matches fallback stays silent).
        assert!(c.get_size(0, size(2.0, 2.0)).is_none());
        assert!(c.get_size(8, size(1.0, 1.0)).is_none());
        assert!(c.get_size(4, size(1.0, 1.0)).is_none());
    }
    #[test]
    fn nodecache_result_match_crosses_slots_for_definite_queries() {
        // The pass1→pass2 handoff (2026-08-08 slot wiring): pass 1 measures
        // under an indefinite constraint and stores in a MEASURE slot; pass 2
        // queries with the measured result as a DEFINITE constraint — which
        // classifies to a different slot. "Result matches request" must
        // therefore scan ALL slots (Taffy's Cache::get does the same), or
        // wiring the 9 slots would have traded the eviction bug for a
        // permanent pass-2 miss.
        let mut c = NodeCache::default();
        // Stored under slot 1 (definite width, indefinite height).
        c.store_size(1, sizing_entry(size(100.0, f32::MAX), size(100.0, 40.0)));
        // Pass 2 asks with the RESULT as a fully-definite constraint → slot 0
        // is empty, but the slot-1 entry's result matches the request.
        let hit = c
            .get_size(0, size(100.0, 40.0))
            .expect("cross-slot result match");
        assert_eq!(hit.result_size, size(100.0, 40.0));
        // An INDEFINITE query never takes the fallback: only exact key hits.
        assert!(c.get_size(0, size(100.0, f32::MAX)).is_none());
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn nodecache_get_size_slot_out_of_range_panics() {
        // There are exactly 9 measurement slots; slot 9 is a caller bug and is
        // reported as an index panic rather than silently returning None.
        let c = NodeCache::default();
        let _ = c.get_size(9, size(0.0, 0.0));
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn nodecache_store_size_slot_out_of_range_panics() {
        let mut c = NodeCache::default();
        c.store_size(9, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
    }
    #[test]
    fn nodecache_layout_slot_round_trips_and_matches_result() {
        let mut c = NodeCache::default();
        c.store_layout(layout_entry(size(800.0, 600.0), size(800.0, 123.0)));
        assert!(!c.is_empty);
        assert!(c.get_layout(size(800.0, 600.0)).is_some());
        // "Result matches request" applies to the layout slot too.
        let hit = c
            .get_layout(size(800.0, 123.0))
            .expect("result-matches-request");
        assert_eq!(hit.result_size, size(800.0, 123.0));
        assert!(c.get_layout(size(400.0, 300.0)).is_none());
        assert!(c.get_layout(size(f32::NAN, f32::NAN)).is_none());
    }
    #[test]
    fn nodecache_clear_wipes_every_slot() {
        let mut c = NodeCache::default();
        for slot in 0..9 {
            c.store_size(slot, sizing_entry(size(10.0, 10.0), size(10.0, 10.0)));
        }
        c.store_layout(layout_entry(size(10.0, 10.0), size(10.0, 10.0)));
        assert!(!c.is_empty);
        c.clear();
        assert!(c.is_empty);
        assert!(c.layout_entry.is_none());
        assert!(c.measure_entries.iter().all(Option::is_none));
        assert!(c.get_size(0, size(10.0, 10.0)).is_none());
        assert!(c.get_layout(size(10.0, 10.0)).is_none());
        // Clearing twice is harmless.
        c.clear();
        assert!(c.is_empty);
    }
    #[test]
    fn slot_index_always_lands_in_range_and_partitions_the_unknown_case() {
        use AvailableWidthType::{Definite, MaxContent, MinContent};
        let types = [Definite, MinContent, MaxContent];
        for &wt in &types {
            for &ht in &types {
                for wk in [true, false] {
                    for hk in [true, false] {
                        let slot = NodeCache::slot_index(wk, hk, wt, ht);
                        assert!(slot < 9, "slot {slot} out of the 9-slot range");
                    }
                }
            }
        }
        // Both known → always slot 0, regardless of the constraint types.
        for &wt in &types {
            for &ht in &types {
                assert_eq!(NodeCache::slot_index(true, true, wt, ht), 0);
            }
        }
        // Neither known → the 4 MinContent combos partition slots 5..=8.
        let mut neither: Vec<usize> = Vec::new();
        for &wt in &[Definite, MinContent] {
            for &ht in &[Definite, MinContent] {
                neither.push(NodeCache::slot_index(false, false, wt, ht));
            }
        }
        neither.sort_unstable();
        assert_eq!(neither, vec![5, 6, 7, 8]);
    }
    #[test]
    fn slot_index_collapses_definite_and_maxcontent_onto_one_slot() {
        use AvailableWidthType::{Definite, MaxContent, MinContent};
        // Documented: "MaxContent/Definite vs MinContent" share a slot.
        assert_eq!(
            NodeCache::slot_index(true, false, Definite, Definite),
            NodeCache::slot_index(true, false, MaxContent, Definite)
        );
        assert_ne!(
            NodeCache::slot_index(true, false, Definite, Definite),
            NodeCache::slot_index(true, false, MinContent, Definite)
        );
    }
    #[test]
    fn slot_index_keys_the_single_unknown_axis_off_the_known_axis_type() {
        use AvailableWidthType::{Definite, MinContent};
        // BEHAVIOUR PIN (deviates from Taffy): when only the width is known, the
        // slot is chosen from `width_type` — the type of the *known* axis — even
        // though the doc comment says it keys off "the unknown dimension(s)".
        // Taffy keys slot 1/2 off the height (the unknown axis) here. Same for
        // the mirrored (false, true) case, which keys off `height_type`.
        // Consequence: the height's MinContent-ness cannot select slot 2 at all,
        // so a MinContent and a Definite height measurement would collide in a
        // single slot once slots 1-8 are wired up (they are unused today).
        assert_eq!(NodeCache::slot_index(true, false, Definite, MinContent), 1);
        assert_eq!(NodeCache::slot_index(true, false, MinContent, Definite), 2);
        assert_eq!(NodeCache::slot_index(false, true, MinContent, Definite), 3);
        assert_eq!(NodeCache::slot_index(false, true, Definite, MinContent), 4);
    }
    // ==================================================================
    // LayoutCacheMap
    // ==================================================================
    #[test]
    fn cachemap_resize_to_tree_grows_shrinks_and_zeroes() {
        let mut m = LayoutCacheMap::default();
        assert!(m.entries.is_empty());
        m.resize_to_tree(0);
        assert!(m.entries.is_empty());
        m.resize_to_tree(3);
        assert_eq!(m.entries.len(), 3);
        assert!(m.entries.iter().all(|e| e.is_empty));
        // Populated entries survive a grow; new entries are dirty.
        m.get_mut(1)
            .store_size(0, sizing_entry(size(5.0, 5.0), size(5.0, 5.0)));
        m.resize_to_tree(5);
        assert_eq!(m.entries.len(), 5);
        assert!(!m.get(1).is_empty);
        assert!(m.get(4).is_empty);
        // Shrink drops the tail.
        m.resize_to_tree(1);
        assert_eq!(m.entries.len(), 1);
        m.resize_to_tree(0);
        assert!(m.entries.is_empty());
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn cachemap_get_out_of_range_panics() {
        let m = LayoutCacheMap::default();
        let _ = m.get(0);
    }
    #[test]
    fn cachemap_mark_dirty_out_of_range_index_is_a_noop() {
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(2);
        m.get_mut(0)
            .store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        m.mark_dirty(99, &[]);
        m.mark_dirty(usize::MAX, &[]);
        // Guard clause hit: nothing was touched.
        assert!(!m.get(0).is_empty);
        assert_eq!(m.entries.len(), 2);
    }
    #[test]
    fn cachemap_mark_dirty_propagates_up_the_ancestor_chain() {
        // 0 <- 1 <- 2
        let tree = vec![plain(None), plain(Some(0)), plain(Some(1))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        for i in 0..3 {
            m.get_mut(i)
                .store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        }
        m.mark_dirty(2, &tree);
        assert!(m.get(2).is_empty);
        assert!(m.get(1).is_empty);
        assert!(m.get(0).is_empty);
    }
    #[test]
    fn cachemap_mark_dirty_stops_at_the_first_dirty_ancestor() {
        // 0 (clean) <- 1 (already dirty) <- 2 (clean)
        let tree = vec![plain(None), plain(Some(0)), plain(Some(1))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        m.get_mut(0)
            .store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        m.get_mut(2)
            .store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        m.mark_dirty(2, &tree);
        assert!(m.get(2).is_empty);
        assert!(m.get(1).is_empty);
        // Early stop: the grandparent keeps its cached entry.
        assert!(!m.get(0).is_empty);
    }
    #[test]
    fn cachemap_mark_dirty_on_an_already_dirty_node_leaves_ancestors_alone() {
        let tree = vec![plain(None), plain(Some(0))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(2);
        m.get_mut(0)
            .store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        // entry 1 is fresh → already dirty
        m.mark_dirty(1, &tree);
        assert!(m.get(1).is_empty);
        assert!(!m.get(0).is_empty);
    }
    #[test]
    fn cachemap_mark_dirty_terminates_on_cyclic_parent_links() {
        // A malformed tree (0 <-> 1, and 2 as its own parent) must not spin
        // forever: the `is_empty` early-stop breaks every cycle after one lap.
        let tree = vec![plain(Some(1)), plain(Some(0)), plain(Some(2))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        for i in 0..3 {
            m.get_mut(i)
                .store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        }
        m.mark_dirty(0, &tree);
        assert!(m.get(0).is_empty);
        assert!(m.get(1).is_empty);
        m.mark_dirty(2, &tree);
        assert!(m.get(2).is_empty);
    }
    #[test]
    fn cachemap_mark_dirty_survives_a_tree_that_disagrees_with_the_cache() {
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        for i in 0..3 {
            m.get_mut(i)
                .store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        }
        // Tree shorter than the cache: parent lookup returns None → stop.
        let short_tree = vec![plain(None)];
        m.mark_dirty(2, &short_tree);
        assert!(m.get(2).is_empty);
        assert!(!m.get(0).is_empty);
        // Parent index past the end of the cache: break, don't index-panic.
        let dangling = vec![plain(Some(usize::MAX)), plain(None), plain(None)];
        m.mark_dirty(0, &dangling);
        assert!(m.get(0).is_empty);
    }
    // ==================================================================
    // Solver3CacheMemoryReport / LayoutCache (getters)
    // ==================================================================
    #[test]
    fn memory_report_total_bytes_sums_every_field_exactly_once() {
        assert_eq!(Solver3CacheMemoryReport::default().total_bytes(), 0);
        // Distinct powers of two: a missing or double-counted field shows up as
        // a wrong total rather than an accidental coincidence.
        let r = Solver3CacheMemoryReport {
            tree_bytes: 1,
            tree_report: None,
            calculated_positions_bytes: 2,
            previous_positions_bytes: 4,
            scroll_ids_bytes: 8,
            scroll_id_to_node_id_bytes: 16,
            counters_bytes: 32,
            float_cache_bytes: 64,
            cache_map_bytes: 128,
            cached_display_list_bytes: 256,
            // Counters, not byte totals — must NOT contribute.
            cached_display_list_text_instances: 512,
            cached_display_list_items: 1024,
        };
        assert_eq!(r.total_bytes(), 511);
    }
    #[test]
    fn memory_report_of_a_default_cache_is_all_zero() {
        let cache = LayoutCache::default();
        let r = cache.memory_report();
        assert_eq!(r.total_bytes(), 0);
        assert_eq!(r.tree_bytes, 0);
        assert!(r.tree_report.is_none());
        assert_eq!(r.cache_map_bytes, 0);
        assert_eq!(r.cached_display_list_bytes, 0);
    }
    #[test]
    fn memory_report_accounts_for_populated_state() {
        let mut cache = LayoutCache::default();
        cache.cache_map.resize_to_tree(4);
        cache.calculated_positions = vec![pos(1.0, 2.0), pos(3.0, 4.0), pos(5.0, 6.0)];
        cache.previous_positions = vec![pos(0.0, 0.0)];
        cache.counters.insert((0, "list-item".to_string()), 7);
        cache.float_cache.insert(0, fc::FloatingContext::default());
        cache.scroll_ids.insert(LayoutNodeId::new(0), 42);
        cache.scroll_id_to_node_id.insert(42, NodeId::ZERO);
        // A DL with one Text item: the walk must count the item slot AND
        // its glyph Vec heap — this was a flat 2048 guess before, which
        // hid every cached DL's real size (the per-glyph copies).
        let glyphs = vec![azul_core::ui_solver::GlyphInstance::default(); 5];
        let glyph_heap = glyphs.capacity() * size_of::<azul_core::ui_solver::GlyphInstance>();
        let mut dl = DisplayList::default();
        dl.items
            .push(crate::solver3::display_list::DisplayListItem::Text {
                glyphs,
                font_hash: crate::text3::cache::FontHash::from_hash(1),
                font_size_px: 16.0,
                color: azul_css::props::basic::ColorU::BLACK,
                clip_rect: crate::solver3::display_list::WindowLogicalRect(LogicalRect::new(
                    pos(0.0, 0.0),
                    size(10.0, 10.0),
                )),
                source_node_index: None,
            });
        let dl_expected = dl.retained_bytes();
        cache.cached_display_list = Some((
            SubtreeHash(1),
            LogicalRect::new(pos(0.0, 0.0), size(10.0, 10.0)),
            0,
            0,
            0,
            std::sync::Arc::new(dl),
        ));
        let r = cache.memory_report();
        assert!(r.cache_map_bytes >= 4 * size_of::<NodeCache>());
        assert_eq!(
            r.calculated_positions_bytes,
            3 * size_of::<LogicalPosition>()
        );
        assert_eq!(r.previous_positions_bytes, size_of::<LogicalPosition>());
        assert!(r.counters_bytes >= "list-item".len());
        assert_eq!(r.float_cache_bytes, 256);
        assert_eq!(r.cached_display_list_bytes, dl_expected.0);
        assert_eq!(r.cached_display_list_text_instances, 5);
        assert_eq!(dl_expected.1, 5);
        assert_eq!(r.cached_display_list_items, 1);
        assert_eq!(dl_expected.2, 1);
        assert!(
            r.cached_display_list_bytes
                >= size_of::<crate::solver3::display_list::DisplayListItem>() + glyph_heap,
            "the Text item slot and its glyph heap must both be visible (got {}, item {}, glyphs \
             {glyph_heap})",
            r.cached_display_list_bytes,
            size_of::<crate::solver3::display_list::DisplayListItem>(),
        );
        assert_eq!(
            r.total_bytes(),
            r.tree_bytes
                + r.calculated_positions_bytes
                + r.previous_positions_bytes
                + r.scroll_ids_bytes
                + r.scroll_id_to_node_id_bytes
                + r.counters_bytes
                + r.float_cache_bytes
                + r.cache_map_bytes
                + r.cached_display_list_bytes
        );
    }
    /// The patch-damage LOG: a renderer that presented before two patched
    /// builds gets BOTH builds' damage (the first's vacated rect was the
    /// slider's thumb trail); a full emission in between hands authority
    /// back to the renderer's own diff; falling off the log means "repaint
    /// in full"; and nothing pending is nothing pending.
    #[test]
    fn pending_patch_damage_unions_every_patched_build_since_the_last_present() {
        let r = |x: f32| LogicalRect::new(pos(x, 0.0), size(16.0, 16.0));
        let mut cache = LayoutCache::default();
        assert_eq!(cache.pending_patch_damage(0), PendingPatchDamage::None);
        // The renderer presented against build 0. Then: a css patch (moves
        // the thumb 100 -> 120) and, in the same pass, the RefreshDom's
        // structure-preserved relayout (damages the caption + the thumb's
        // CURRENT rect only — it never saw 100).
        cache.record_patch_damage(vec![r(100.0), r(120.0)]);
        cache.record_patch_damage(vec![r(300.0), r(120.0)]);
        assert_eq!(
            cache.pending_patch_damage(0),
            PendingPatchDamage::Rects(vec![r(100.0), r(120.0), r(300.0), r(120.0)]),
            "the first build's vacated rect must survive the second build"
        );
        assert_eq!(
            cache.last_patch_damage,
            Some(vec![r(300.0), r(120.0)]),
            "the slot still reports the LAST build, for the frame report"
        );
        // Presented against build 2: nothing pending; a third patch is
        // pending on its own.
        assert_eq!(cache.pending_patch_damage(2), PendingPatchDamage::None);
        cache.record_patch_damage(vec![r(140.0)]);
        assert_eq!(
            cache.pending_patch_damage(2),
            PendingPatchDamage::Rects(vec![r(140.0)])
        );
        // A full emission retires the log: a renderer that has not seen it
        // must trust its own diff, and one that has sees nothing pending.
        cache.record_full_emission();
        assert_eq!(
            cache.pending_patch_damage(2),
            PendingPatchDamage::FullBuildSincePresent
        );
        assert_eq!(cache.pending_patch_damage(4), PendingPatchDamage::None);
        assert!(cache.last_patch_damage.is_none());
        assert!(!cache.last_build_was_patched);
        // Patches after the full emission chain from it.
        cache.record_patch_damage(vec![r(1.0)]);
        cache.record_patch_damage(vec![r(2.0)]);
        assert_eq!(
            cache.pending_patch_damage(4),
            PendingPatchDamage::Rects(vec![r(1.0), r(2.0)])
        );
        assert_eq!(
            cache.pending_patch_damage(5),
            PendingPatchDamage::Rects(vec![r(2.0)])
        );
        // Falling off the bounded log means the damage is unknown.
        for i in 0..40 {
            cache.record_patch_damage(vec![r(i as f32)]);
        }
        assert_eq!(cache.pending_patch_damage(4), PendingPatchDamage::Unknown);
        let seq = cache.build_seq;
        assert!(
            matches!(cache.pending_patch_damage(seq - 1), PendingPatchDamage::Rects(ref v) if v.len() == 1)
        );
    }
    #[test]
    fn reset_incremental_drops_reuse_state_keeps_the_rest_and_is_idempotent() {
        let mut cache = LayoutCache {
            tree: Some(build_tree(vec![plain(None)], warm_default(1), &[vec![]])),
            ..Default::default()
        };
        cache.cache_map.resize_to_tree(2);
        cache.cached_display_list = Some((
            SubtreeHash(9),
            LogicalRect::new(pos(0.0, 0.0), size(1.0, 1.0)),
            0,
            0,
            0,
            std::sync::Arc::new(DisplayList::default()),
        ));
        cache.prev_dom_ptr = 0xDEAD_BEEF;
        cache.counters.insert((0, "c".to_string()), 1);
        cache.float_cache.insert(0, fc::FloatingContext::default());
        // Not incremental-reuse state — must survive.
        cache.calculated_positions = vec![pos(1.0, 2.0)];
        cache.scroll_ids.insert(LayoutNodeId::new(0), 5);
        cache.viewport = Some(LogicalRect::new(pos(0.0, 0.0), size(800.0, 600.0)));
        cache.reset_incremental();
        assert!(cache.tree.is_none());
        assert!(cache.cache_map.entries.is_empty());
        assert!(cache.cached_display_list.is_none());
        assert_eq!(cache.prev_dom_ptr, 0);
        assert!(cache.counters.is_empty());
        assert!(cache.float_cache.is_empty());
        assert_eq!(cache.calculated_positions.len(), 1);
        assert_eq!(cache.scroll_ids.len(), 1);
        assert!(cache.viewport.is_some());
        // Idempotent: a second reset on the already-cold cache is a no-op.
        cache.reset_incremental();
        assert!(cache.tree.is_none());
        // Only the two retained fields (1 position + 1 scroll id) still cost bytes.
        assert_eq!(
            cache.memory_report().total_bytes(),
            size_of::<LogicalPosition>() + size_of::<usize>() + size_of::<u64>()
        );
    }
    // ==================================================================
    // ReconciliationResult (predicates)
    // ==================================================================
    #[test]
    fn reconciliation_result_default_is_clean() {
        let r = ReconciliationResult::default();
        assert!(r.is_clean());
        assert!(!r.needs_layout());
        assert!(!r.needs_paint_only());
    }
    #[test]
    fn reconciliation_result_predicates_hold_over_every_combination() {
        for intrinsic in [false, true] {
            for roots in [false, true] {
                for paint in [false, true] {
                    let mut r = ReconciliationResult::default();
                    if intrinsic {
                        r.intrinsic_dirty.insert(0);
                    }
                    if roots {
                        r.layout_roots.insert(usize::MAX);
                    }
                    if paint {
                        r.paint_dirty.insert(7);
                    }
                    let expect_layout = intrinsic || roots;
                    assert_eq!(r.needs_layout(), expect_layout);
                    assert_eq!(r.is_clean(), !intrinsic && !roots && !paint);
                    assert_eq!(r.needs_paint_only(), !expect_layout && paint);
                    // Invariants: clean ⇒ no work; layout and paint-only are exclusive.
                    assert!(!(r.is_clean() && (r.needs_layout() || r.needs_paint_only())));
                    assert!(!(r.needs_layout() && r.needs_paint_only()));
                }
            }
        }
    }
    // ==================================================================
    // to_overflow_behavior / style_text_align_to_fc (mapping tables)
    // ==================================================================
    #[test]
    fn to_overflow_behavior_maps_every_layout_overflow_variant() {
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Visible)),
            OverflowBehavior::Visible
        );
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Hidden)),
            OverflowBehavior::Hidden
        );
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Scroll)),
            OverflowBehavior::Scroll
        );
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Auto)),
            OverflowBehavior::Auto
        );
        // BEHAVIOUR PIN: `overflow: clip` is folded into Hidden, so the distinct
        // `OverflowBehavior::Clip` variant is never produced here. Clip differs
        // from hidden in CSS Overflow 3 (no scroll container, no scrollport), so
        // a `clip` box is currently treated as a (non-scrollable) hidden box.
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Clip)),
            OverflowBehavior::Hidden
        );
    }
    #[test]
    fn to_overflow_behavior_falls_back_to_the_initial_value() {
        // CSS Overflow 3: initial value is `visible`. Auto/Initial/Inherit here
        // are the *CSS-wide keyword* arms of MultiValue, not `overflow: auto`.
        for mv in [MultiValue::Auto, MultiValue::Initial, MultiValue::Inherit] {
            assert_eq!(to_overflow_behavior(mv), OverflowBehavior::Visible);
        }
    }
    #[test]
    fn overflow_auto_keyword_is_a_typed_value_not_a_css_wide_keyword() {
        // Regression guard: if `overflow: auto` were parsed as the generic
        // CSS-wide `auto` keyword it would arrive as MultiValue::Auto and
        // to_overflow_behavior would silently downgrade it to Visible — i.e. no
        // scrollbars at all. It must arrive as Exact(LayoutOverflow::Auto).
        let sd = styled(
            Dom::create_body().with_child(div_class("s")),
            ".s { overflow-x: auto; overflow-y: scroll; }",
        );
        let id = NodeId::new(1);
        let state = sd.styled_nodes.as_container()[id].styled_node_state;
        assert_eq!(
            to_overflow_behavior(get_overflow_x(&sd, id, &state)),
            OverflowBehavior::Auto
        );
        assert_eq!(
            to_overflow_behavior(get_overflow_y(&sd, id, &state)),
            OverflowBehavior::Scroll
        );
    }
    #[test]
    fn style_text_align_to_fc_maps_every_variant() {
        // fc::TextAlign has no PartialEq, so match on the variant.
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Start),
            fc::TextAlign::Start
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Left),
            fc::TextAlign::Start
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::End),
            fc::TextAlign::End
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Right),
            fc::TextAlign::End
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Center),
            fc::TextAlign::Center
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Justify),
            fc::TextAlign::Justify
        ));
    }
    // ==================================================================
    // should_use_content_height (predicate)
    // ==================================================================
    #[test]
    fn should_use_content_height_for_css_wide_keywords_and_auto() {
        assert!(should_use_content_height(&MultiValue::Auto));
        assert!(should_use_content_height(&MultiValue::Initial));
        assert!(should_use_content_height(&MultiValue::Inherit));
        assert!(should_use_content_height(&MultiValue::Exact(
            LayoutHeight::Auto
        )));
    }
    #[test]
    fn should_use_content_height_is_false_for_definite_lengths() {
        for pv in [
            PixelValue::px(100.0),
            PixelValue::px(-10.0),
            PixelValue::percent(50.0),
            PixelValue::percent(0.0),
            PixelValue::em(2.0),
            PixelValue::rem(2.0),
        ] {
            assert!(
                !should_use_content_height(&MultiValue::Exact(LayoutHeight::Px(pv))),
                "expected a definite height for {pv:?}"
            );
        }
    }
    #[test]
    fn should_use_content_height_treats_zero_px_as_content_based() {
        // BEHAVIOUR PIN: `height: 0px` is indistinguishable from `auto` here, so
        // an explicitly zero-height box falls back to content sizing.
        assert!(should_use_content_height(&MultiValue::Exact(
            LayoutHeight::Px(PixelValue::zero())
        )));
        assert!(should_use_content_height(&MultiValue::Exact(
            LayoutHeight::Px(PixelValue::px(0.0))
        )));
        // ...but `height: 0%` is NOT (its metric is Percent, not Px).
        assert!(!should_use_content_height(&MultiValue::Exact(
            LayoutHeight::Px(PixelValue::percent(0.0))
        )));
    }
    #[test]
    fn should_use_content_height_treats_non_px_metrics_as_content_based() {
        // BEHAVIOUR PIN (suspected bug): only Px/Percent/Em/Rem are recognised as
        // definite. Every other metric — pt, vh, vw, cm, in, mm — is reported as
        // content-based, so `height: 100vh` behaves like a *minimum* height (see
        // apply_content_based_height, which takes max(used, content)) instead of
        // a definite one.
        for metric in [
            SizeMetric::Pt,
            SizeMetric::Vh,
            SizeMetric::Vw,
            SizeMetric::Cm,
            SizeMetric::Mm,
            SizeMetric::In,
        ] {
            let pv = PixelValue::from_metric(metric, 100.0);
            assert!(
                should_use_content_height(&MultiValue::Exact(LayoutHeight::Px(pv))),
                "{metric:?} is currently treated as content-based"
            );
        }
    }
    #[test]
    fn should_use_content_height_for_intrinsic_keywords_but_not_calc() {
        assert!(should_use_content_height(&MultiValue::Exact(
            LayoutHeight::MinContent
        )));
        assert!(should_use_content_height(&MultiValue::Exact(
            LayoutHeight::MaxContent
        )));
        assert!(should_use_content_height(&MultiValue::Exact(
            LayoutHeight::FitContent(PixelValue::px(10.0))
        )));
        // calc() resolves to a definite value.
        assert!(!should_use_content_height(&MultiValue::Exact(
            LayoutHeight::Calc(CalcAstItemVec::from_vec(Vec::new()))
        )));
    }
    // ==================================================================
    // apply_content_based_height (numeric)
    // ==================================================================
    fn one_node_tree_with(bp: &ResolvedBoxProps) -> LayoutTree {
        build_tree(
            vec![hot(None, None, Some(size(100.0, 100.0)), bp)],
            warm_default(1),
            &[vec![]],
        )
    }
    #[test]
    fn apply_content_based_height_keeps_the_larger_of_min_height_and_content() {
        let bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(0.0, 0.0, 0.0, 0.0),
            edges(10.0, 0.0, 10.0, 0.0), // padding: 20px on the block axis
        );
        let tree = one_node_tree_with(&bp);
        let wm = LayoutWritingMode::HorizontalTb;
        // Content (50 + 20 padding = 70) is smaller than the min-height-constrained
        // 100 → the Phase-1 size wins (CSS 2.2 § 10.7).
        let out = apply_content_based_height(size(100.0, 100.0), size(0.0, 50.0), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(out, size(100.0, 100.0));
        // Content wins when it is taller.
        let out = apply_content_based_height(size(100.0, 40.0), size(0.0, 50.0), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(out, size(100.0, 70.0));
    }
    /// `overflow_size` is a PADDING-box extent for a flex or grid container
    /// (taffy's `content_size` minus the leading border) and a CONTENT-box
    /// extent for everything else, so only the border is added back for the
    /// former. The opengl example's button (`inline-flex`, `padding: 6px
    /// 12px`, a 1 px border) over its canvas came out 40 px instead of 28.
    #[test]
    fn apply_content_based_height_adds_only_the_border_to_a_flex_containers_padding_box() {
        let bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(1.0, 1.0, 1.0, 1.0),
            edges(6.0, 12.0, 6.0, 12.0),
        );
        let wm = LayoutWritingMode::HorizontalTb;
        let mut tree = one_node_tree_with(&bp);
        // A block container: 26 px of content + 12 padding + 2 border.
        let out = apply_content_based_height(size(292.0, 0.0), size(0.0, 26.0), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(out.height, 40.0);
        // The same box as a flex container: the 26 px ARE the padding box.
        tree.get_mut(LayoutNodeId::new(0))
            .expect("node 0")
            .formatting_context = FormattingContext::Flex;
        let out = apply_content_based_height(size(292.0, 0.0), size(0.0, 26.0), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(
            out.height, 28.0,
            "a flex container's padding is inside taffy's extent already — adding it again is the \
             12 px every padded button gained as a block-level child"
        );
    }
    #[test]
    fn apply_content_based_height_at_zero_and_in_vertical_writing_modes() {
        let tree = one_node_tree_with(&zero_box_props());
        let out = apply_content_based_height(
            size(0.0, 0.0),
            size(0.0, 0.0),
            &tree,
            0,
            LayoutWritingMode::HorizontalTb,
        )
        .expect("valid node");
        assert_eq!(out, size(0.0, 0.0));
        // Vertical writing mode: the main axis is the *width*.
        let out = apply_content_based_height(
            size(10.0, 80.0),
            size(50.0, 0.0),
            &tree,
            0,
            LayoutWritingMode::VerticalRl,
        )
        .expect("valid node");
        assert_eq!(out, size(50.0, 80.0));
    }
    #[test]
    fn apply_content_based_height_does_not_propagate_nan() {
        let tree = one_node_tree_with(&zero_box_props());
        let wm = LayoutWritingMode::HorizontalTb;
        // f32::max ignores a NaN operand, so a NaN content size cannot poison the
        // used size — the Phase-1 height survives.
        let out = apply_content_based_height(size(100.0, 40.0), size(0.0, f32::NAN), &tree, 0, wm)
            .expect("valid node");
        assert!(!out.height.is_nan());
        assert_eq!(out.height, 40.0);
        // ...and symmetrically, a NaN used size is replaced by the content size.
        let out = apply_content_based_height(size(100.0, f32::NAN), size(0.0, 50.0), &tree, 0, wm)
            .expect("valid node");
        assert!(!out.height.is_nan());
        assert_eq!(out.height, 50.0);
    }
    #[test]
    fn apply_content_based_height_saturates_at_infinity_and_rejects_bad_indices() {
        let tree = one_node_tree_with(&zero_box_props());
        let wm = LayoutWritingMode::HorizontalTb;
        let out =
            apply_content_based_height(size(10.0, 10.0), size(0.0, f32::INFINITY), &tree, 0, wm)
                .expect("valid node");
        assert!(out.height.is_infinite() && out.height.is_sign_positive());
        // A huge finite content size stays finite (no overflow panic).
        let out = apply_content_based_height(size(10.0, 10.0), size(0.0, f32::MAX), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(out.height, f32::MAX);
        // Out-of-range node → Err, not a panic.
        assert!(apply_content_based_height(size(1.0, 1.0), size(1.0, 1.0), &tree, 1, wm).is_err());
        assert!(
            apply_content_based_height(size(1.0, 1.0), size(1.0, 1.0), &tree, usize::MAX, wm)
                .is_err()
        );
    }
    // ==================================================================
    // calculate_subtree_hash (numeric / round-trip-ish)
    // ==================================================================
    #[test]
    fn subtree_hash_is_deterministic() {
        let a = calculate_subtree_hash(42, &[1, 2, 3]);
        let b = calculate_subtree_hash(42, &[1, 2, 3]);
        assert_eq!(a, b);
        assert_eq!(a, calculate_subtree_hash(42, &[1, 2, 3]));
    }
    #[test]
    fn subtree_hash_depends_on_child_order_and_arity() {
        let base = calculate_subtree_hash(1, &[10, 20]);
        assert_ne!(
            base,
            calculate_subtree_hash(1, &[20, 10]),
            "order must matter"
        );
        assert_ne!(
            base,
            calculate_subtree_hash(1, &[10, 20, 30]),
            "arity must matter"
        );
        assert_ne!(
            base,
            calculate_subtree_hash(1, &[10]),
            "a dropped child must matter"
        );
        assert_ne!(
            base,
            calculate_subtree_hash(2, &[10, 20]),
            "self hash must matter"
        );
    }
    #[test]
    fn subtree_hash_distinguishes_no_children_from_a_zero_child() {
        // Length is folded in (slice Hash writes the length), so an empty child
        // list is not confusable with a single 0-hash child.
        assert_ne!(
            calculate_subtree_hash(0, &[]),
            calculate_subtree_hash(0, &[0])
        );
        assert_ne!(
            calculate_subtree_hash(0, &[0]),
            calculate_subtree_hash(0, &[0, 0])
        );
    }
    #[test]
    fn subtree_hash_does_not_swap_self_hash_and_child_hash() {
        assert_ne!(
            calculate_subtree_hash(7, &[9]),
            calculate_subtree_hash(9, &[7])
        );
    }
    #[test]
    fn subtree_hash_handles_extremes_and_large_child_lists() {
        let extremes = calculate_subtree_hash(u64::MAX, &[u64::MAX, 0, u64::MAX]);
        assert_eq!(
            extremes,
            calculate_subtree_hash(u64::MAX, &[u64::MAX, 0, u64::MAX])
        );
        assert_ne!(extremes, calculate_subtree_hash(0, &[0, 0, 0]));
        // 10k children: no overflow, no panic, still deterministic.
        let many: Vec<u64> = (0..10_000).collect();
        assert_eq!(
            calculate_subtree_hash(1, &many),
            calculate_subtree_hash(1, &many)
        );
    }
    // ==================================================================
    // calculate_content_box_pos (numeric)
    // ==================================================================
    #[test]
    fn content_box_pos_adds_border_and_padding_but_not_margin() {
        let bp = box_props(
            edges(999.0, 999.0, 999.0, 999.0), // margin must be ignored
            edges(2.0, 0.0, 0.0, 3.0),         // border top/left
            edges(5.0, 0.0, 0.0, 7.0),         // padding top/left
        );
        let out = calculate_content_box_pos(pos(10.0, 20.0), &bp);
        assert_eq!(out, pos(10.0 + 3.0 + 7.0, 20.0 + 2.0 + 5.0));
        // Zero box props → identity.
        assert_eq!(
            calculate_content_box_pos(pos(4.0, 5.0), &zero_box_props()),
            pos(4.0, 5.0)
        );
    }
    #[test]
    fn content_box_pos_with_negative_edges_shifts_backwards() {
        let bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(-1.0, 0.0, 0.0, -2.0),
            edges(-3.0, 0.0, 0.0, -4.0),
        );
        assert_eq!(
            calculate_content_box_pos(pos(0.0, 0.0), &bp),
            pos(-6.0, -4.0)
        );
    }
    #[test]
    fn content_box_pos_with_non_finite_edges_is_deterministic() {
        let nan_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(f32::NAN, 0.0, 0.0, f32::NAN),
            edges(0.0, 0.0, 0.0, 0.0),
        );
        let out = calculate_content_box_pos(pos(1.0, 1.0), &nan_bp);
        assert!(
            out.x.is_nan() && out.y.is_nan(),
            "NaN edges propagate, no panic"
        );
        // +inf border with a -inf containing block → NaN, still no panic.
        let inf_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(f32::INFINITY, 0.0, 0.0, f32::INFINITY),
            edges(0.0, 0.0, 0.0, 0.0),
        );
        let out = calculate_content_box_pos(pos(f32::NEG_INFINITY, f32::NEG_INFINITY), &inf_bp);
        assert!(out.x.is_nan() && out.y.is_nan());
        // Saturation rather than wrap-around at the top of the f32 range.
        let max_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(f32::MAX, 0.0, 0.0, f32::MAX),
            edges(f32::MAX, 0.0, 0.0, f32::MAX),
        );
        let out = calculate_content_box_pos(pos(f32::MAX, f32::MAX), &max_bp);
        assert!(out.x.is_infinite() && out.x.is_sign_positive());
        assert!(out.y.is_infinite() && out.y.is_sign_positive());
    }
    // ==================================================================
    // check_scrollbar_change (numeric / predicate)
    // ==================================================================
    fn scrollbars(h: bool, v: bool, w: f32) -> ScrollbarRequirements {
        ScrollbarRequirements {
            needs_horizontal: h,
            needs_vertical: v,
            scrollbar_width: w,
            scrollbar_height: w,
            visual_width_px: w,
        }
    }
    fn tree_with_scrollbar_info(info: Option<ScrollbarRequirements>) -> LayoutTree {
        let mut warm = warm_default(1);
        warm[0].scrollbar_info = info;
        build_tree(vec![plain(None)], warm, &[vec![]])
    }
    #[test]
    fn check_scrollbar_change_skip_flag_short_circuits_everything() {
        let tree = tree_with_scrollbar_info(Some(scrollbars(false, false, 0.0)));
        // Even a full add of both scrollbars is suppressed by the skip flag.
        assert!(!check_scrollbar_change(
            &tree,
            0,
            &scrollbars(true, true, 16.0),
            true
        ));
    }
    #[test]
    fn check_scrollbar_change_out_of_range_node_is_false() {
        let tree = tree_with_scrollbar_info(None);
        assert!(!check_scrollbar_change(
            &tree,
            1,
            &scrollbars(true, true, 16.0),
            false
        ));
        assert!(!check_scrollbar_change(
            &tree,
            usize::MAX,
            &scrollbars(true, true, 16.0),
            false
        ));
    }
    #[test]
    fn check_scrollbar_change_without_previous_info_uses_needs_reflow() {
        let tree = tree_with_scrollbar_info(None);
        // No reserved space → nothing to reflow for.
        assert!(!check_scrollbar_change(
            &tree,
            0,
            &scrollbars(true, true, 0.0),
            false
        ));
        // Reserved space → reflow.
        assert!(check_scrollbar_change(
            &tree,
            0,
            &scrollbars(false, false, 16.0),
            false
        ));
        // NaN reserved width: `NaN > 0.0` is false → deterministic `false`, no panic.
        assert!(!check_scrollbar_change(
            &tree,
            0,
            &scrollbars(true, true, f32::NAN),
            false
        ));
    }
    #[test]
    fn check_scrollbar_change_detects_both_addition_and_removal() {
        let had_vertical = tree_with_scrollbar_info(Some(scrollbars(false, true, 16.0)));
        // Removal (vertical true → false) must be detected, not suppressed.
        assert!(check_scrollbar_change(
            &had_vertical,
            0,
            &scrollbars(false, false, 0.0),
            false
        ));
        // Addition of the horizontal bar.
        assert!(check_scrollbar_change(
            &had_vertical,
            0,
            &scrollbars(true, true, 16.0),
            false
        ));
        // No change at all.
        assert!(!check_scrollbar_change(
            &had_vertical,
            0,
            &scrollbars(false, true, 16.0),
            false
        ));
    }
    #[test]
    fn check_scrollbar_change_ignores_width_only_changes() {
        // BEHAVIOUR PIN: only the needs_horizontal/needs_vertical booleans are
        // compared. A scrollbar that keeps existing but changes reserved width
        // (e.g. a restyle from a classic to a thin scrollbar) does not trigger a
        // reflow here.
        let tree = tree_with_scrollbar_info(Some(scrollbars(false, true, 16.0)));
        assert!(!check_scrollbar_change(
            &tree,
            0,
            &scrollbars(false, true, 4.0),
            false
        ));
    }
    #[test]
    fn check_scrollbar_change_ignores_a_flip_between_two_zero_reservation_states() {
        // Overlay scrollbars reserve nothing, so a bar appearing or vanishing
        // cannot change the available space a reflow would recompute. Same for
        // the post-layout `apply_virtual_scroll_necessity` amendment, which
        // raises a flag without reserving a gutter — without this, an
        // `overflow: auto` VirtualView asked for a full extra layout pass on
        // every single pass, forever.
        let overlay_bar = tree_with_scrollbar_info(Some(scrollbars(false, true, 0.0)));
        assert!(!check_scrollbar_change(
            &overlay_bar,
            0,
            &scrollbars(false, false, 0.0),
            false
        ));
        let no_bar = tree_with_scrollbar_info(Some(scrollbars(false, false, 0.0)));
        assert!(!check_scrollbar_change(
            &no_bar,
            0,
            &scrollbars(false, true, 0.0),
            false
        ));
        // A space-reserving bar on EITHER side still forces the reflow.
        assert!(check_scrollbar_change(
            &no_bar,
            0,
            &scrollbars(false, true, 16.0),
            false
        ));
        let classic_bar = tree_with_scrollbar_info(Some(scrollbars(false, true, 16.0)));
        assert!(check_scrollbar_change(
            &classic_bar,
            0,
            &scrollbars(false, false, 0.0),
            false
        ));
    }
    // ==================================================================
    // apply_virtual_scroll_necessity
    // ==================================================================
    /// `body(0) > node(1)`, where node 1 carries `.vv` and the given node type.
    fn dom_with_styled_child(node_type: NodeType, css_str: &str) -> StyledDom {
        styled(
            Dom::create_body().with_child(
                Dom::create_node(node_type)
                    .with_ids_and_classes(vec![IdOrClass::Class("vv".into())].into()),
            ),
            css_str,
        )
    }
    fn no_scrollbars() -> ScrollbarRequirements {
        scrollbars(false, false, 0.0)
    }
    #[test]
    fn apply_virtual_scroll_necessity_raises_the_axis_the_virtual_document_overflows() {
        let dom = dom_with_styled_child(
            NodeType::VirtualView,
            ".vv { overflow-x: hidden; overflow-y: auto; }",
        );
        let mut info = no_scrollbars();
        assert!(apply_virtual_scroll_necessity(
            &dom,
            NodeId::new(1),
            size(100.0, 1000.0),
            size(100.0, 100.0),
            &mut info,
        ));
        assert!(info.needs_vertical);
        assert!(!info.needs_horizontal, "the hidden axis never gains a bar");
        // Layout has already run: no gutter is reserved after the fact.
        assert_eq!(info.scrollbar_width, 0.0);
        assert_eq!(info.scrollbar_height, 0.0);
    }
    #[test]
    fn apply_virtual_scroll_necessity_ignores_everything_that_is_not_a_virtual_view() {
        // Same CSS, same overflowing virtual size — a plain div's necessity is
        // layout's business and must not be second-guessed here.
        let dom = dom_with_styled_child(NodeType::Div, ".vv { overflow: auto; }");
        let mut info = no_scrollbars();
        assert!(!apply_virtual_scroll_necessity(
            &dom,
            NodeId::new(1),
            size(1000.0, 1000.0),
            size(100.0, 100.0),
            &mut info,
        ));
        assert!(!info.needs_vertical && !info.needs_horizontal);
        // An out-of-range node is inert rather than a panic.
        let mut info = no_scrollbars();
        assert!(!apply_virtual_scroll_necessity(
            &dom,
            NodeId::new(9_999),
            size(1000.0, 1000.0),
            size(100.0, 100.0),
            &mut info,
        ));
    }
    #[test]
    fn apply_virtual_scroll_necessity_honours_the_one_pixel_epsilon_and_the_overflow_value() {
        let auto = dom_with_styled_child(NodeType::VirtualView, ".vv { overflow: auto; }");
        // Exactly at the boundary: 101 is NOT > 100 + 1 — same tolerance as
        // check_scrollbar_necessity, so sub-pixel noise cannot flicker a bar.
        let mut info = no_scrollbars();
        assert!(!apply_virtual_scroll_necessity(
            &auto,
            NodeId::new(1),
            size(101.0, 101.0),
            size(100.0, 100.0),
            &mut info,
        ));
        // One pixel past it raises both axes.
        let mut info = no_scrollbars();
        assert!(apply_virtual_scroll_necessity(
            &auto,
            NodeId::new(1),
            size(102.0, 102.0),
            size(100.0, 100.0),
            &mut info,
        ));
        assert!(info.needs_horizontal && info.needs_vertical);
        // `hidden` is a scroll container but not a user-scrollable one: no bar,
        // however large the virtual document is.
        let hidden = dom_with_styled_child(NodeType::VirtualView, ".vv { overflow: hidden; }");
        let mut info = no_scrollbars();
        assert!(!apply_virtual_scroll_necessity(
            &hidden,
            NodeId::new(1),
            size(9999.0, 9999.0),
            size(100.0, 100.0),
            &mut info,
        ));
        assert!(!info.needs_horizontal && !info.needs_vertical);
    }
    #[test]
    fn apply_virtual_scroll_necessity_never_lowers_a_flag_layout_already_raised() {
        // `overflow: scroll` sets needs_* unconditionally at layout time (and
        // reserves the gutter). A virtual size that fits must not undo that.
        let dom = dom_with_styled_child(NodeType::VirtualView, ".vv { overflow-y: scroll; }");
        let mut info = scrollbars(false, true, 16.0);
        assert!(!apply_virtual_scroll_necessity(
            &dom,
            NodeId::new(1),
            size(100.0, 10.0),
            size(100.0, 100.0),
            &mut info,
        ));
        assert!(info.needs_vertical, "the reserved bar survives");
        assert_eq!(
            info.scrollbar_width, 16.0,
            "and keeps its layout reservation"
        );
    }
    // ==================================================================
    // shift_subtree_position (numeric)
    // ==================================================================
    /// 0 -> [1, 2]; 1 -> [3]
    fn shift_fixture() -> (LayoutTree, PositionVec) {
        let tree = build_tree(
            vec![plain(None), plain(Some(0)), plain(Some(0)), plain(Some(1))],
            warm_default(4),
            &[vec![1, 2], vec![3], vec![], vec![]],
        );
        let positions = vec![
            pos(0.0, 0.0),
            pos(10.0, 10.0),
            pos(20.0, 20.0),
            pos(30.0, 30.0),
        ];
        (tree, positions)
    }
    #[test]
    fn shift_subtree_position_zero_delta_is_identity() {
        let (tree, mut positions) = shift_fixture();
        let before = positions.clone();
        shift_subtree_position(0, pos(0.0, 0.0), &tree, &mut positions);
        assert_eq!(positions, before);
    }
    #[test]
    fn shift_subtree_position_moves_the_subtree_and_leaves_siblings_alone() {
        let (tree, mut positions) = shift_fixture();
        shift_subtree_position(1, pos(5.0, -3.0), &tree, &mut positions);
        assert_eq!(positions[0], pos(0.0, 0.0), "parent untouched");
        assert_eq!(positions[1], pos(15.0, 7.0), "shifted node");
        assert_eq!(positions[2], pos(20.0, 20.0), "sibling untouched");
        assert_eq!(positions[3], pos(35.0, 27.0), "descendant follows");
    }
    #[test]
    fn shift_subtree_position_out_of_range_node_is_a_noop() {
        let (tree, mut positions) = shift_fixture();
        let before = positions.clone();
        shift_subtree_position(99, pos(5.0, 5.0), &tree, &mut positions);
        shift_subtree_position(usize::MAX, pos(5.0, 5.0), &tree, &mut positions);
        assert_eq!(positions, before);
    }
    #[test]
    fn shift_subtree_position_skips_nodes_without_a_stored_position() {
        let (tree, _) = shift_fixture();
        // Only node 0 has a position; 1..3 are missing from the vec entirely.
        let mut positions = vec![pos(1.0, 1.0)];
        shift_subtree_position(0, pos(2.0, 2.0), &tree, &mut positions);
        assert_eq!(positions.len(), 1, "the vec is not grown by the shift");
        assert_eq!(positions[0], pos(3.0, 3.0));
    }
    #[test]
    fn shift_subtree_position_leaves_the_unset_sentinel_unset() {
        // POSITION_UNSET is f32::MIN; adding a small delta to it is a no-op at
        // f32 precision, so an un-positioned node stays "unset" after a shift
        // instead of turning into a bogus near-MIN coordinate.
        let (tree, _) = shift_fixture();
        let mut positions = vec![
            pos(0.0, 0.0),
            POSITION_UNSET,
            POSITION_UNSET,
            POSITION_UNSET,
        ];
        shift_subtree_position(0, pos(7.0, 9.0), &tree, &mut positions);
        assert_eq!(pos_get(&positions, 0), Some(pos(7.0, 9.0)));
        assert!(pos_get(&positions, 1).is_none());
        assert!(pos_get(&positions, 3).is_none());
    }
    #[test]
    fn shift_subtree_position_nan_delta_is_confined_to_the_subtree() {
        let (tree, mut positions) = shift_fixture();
        shift_subtree_position(1, pos(f32::NAN, f32::NAN), &tree, &mut positions);
        assert!(positions[1].x.is_nan() && positions[1].y.is_nan());
        assert!(positions[3].x.is_nan(), "NaN reaches the descendant");
        assert!(!positions[2].x.is_nan(), "the sibling is untouched");
        assert_eq!(positions[0], pos(0.0, 0.0));
    }
    #[test]
    fn shift_subtree_position_walks_a_deep_chain_without_blowing_the_stack() {
        const DEPTH: usize = 500;
        let mut nodes = vec![plain(None)];
        let mut child_lists: Vec<Vec<usize>> = vec![vec![1]];
        for i in 1..DEPTH {
            nodes.push(plain(Some(i - 1)));
            child_lists.push(if i + 1 < DEPTH { vec![i + 1] } else { vec![] });
        }
        let tree = build_tree(nodes, warm_default(DEPTH), &child_lists);
        let mut positions = vec![pos(0.0, 0.0); DEPTH];
        shift_subtree_position(0, pos(1.0, 2.0), &tree, &mut positions);
        assert_eq!(positions[0], pos(1.0, 2.0));
        assert_eq!(positions[DEPTH - 1], pos(1.0, 2.0));
    }
    // ==================================================================
    // position_bfc_child_descendants / position_flex_child_descendants
    // ==================================================================
    #[test]
    fn position_bfc_child_descendants_out_of_range_node_is_a_noop() {
        let (tree, mut positions) = shift_fixture();
        let before = positions.clone();
        position_bfc_child_descendants(&tree, 99, pos(1.0, 1.0), &mut positions);
        assert_eq!(positions, before);
    }
    #[test]
    fn position_bfc_child_descendants_converts_relative_to_absolute() {
        // 0 -> [1] -> [2]; node 1 has a 2px border + 3px padding on top/left.
        let bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(2.0, 0.0, 0.0, 2.0),
            edges(3.0, 0.0, 0.0, 3.0),
        );
        let mut warm = warm_default(3);
        warm[1].relative_position = Some(pos(10.0, 20.0));
        warm[2].relative_position = Some(pos(1.0, 1.0));
        let tree = build_tree(
            vec![
                plain(None),
                hot(Some(0), None, Some(size(50.0, 50.0)), &bp),
                plain(Some(1)),
            ],
            warm,
            &[vec![1], vec![2], vec![]],
        );
        let mut positions: PositionVec = Vec::new();
        position_bfc_child_descendants(&tree, 0, pos(100.0, 200.0), &mut positions);
        // child: content-box origin + relative
        assert_eq!(pos_get(&positions, 1), Some(pos(110.0, 220.0)));
        // grandchild: child's own content box (abs + border + padding) + relative
        assert_eq!(
            pos_get(&positions, 2),
            Some(pos(110.0 + 5.0 + 1.0, 220.0 + 5.0 + 1.0))
        );
    }
    #[test]
    fn position_bfc_child_descendants_defaults_a_missing_relative_position_to_the_origin() {
        let tree = build_tree(
            vec![plain(None), plain(Some(0))],
            warm_default(2), // relative_position: None
            &[vec![1], vec![]],
        );
        let mut positions: PositionVec = Vec::new();
        position_bfc_child_descendants(&tree, 0, pos(7.0, 8.0), &mut positions);
        assert_eq!(pos_get(&positions, 1), Some(pos(7.0, 8.0)));
    }
    #[test]
    fn position_flex_child_descendants_rejects_a_dangling_child_index() {
        // children_arena points at a node that does not exist → Err, not a panic.
        let mut tree = build_tree(vec![plain(None)], warm_default(1), &[vec![99]]);
        let mut positions: PositionVec = Vec::new();
        let r = position_flex_child_descendants(
            &mut tree,
            0,
            pos(0.0, 0.0),
            size(100.0, 100.0),
            &mut positions,
        );
        assert!(r.is_err());
    }
    #[test]
    fn position_flex_child_descendants_positions_children_and_grandchildren() {
        let mut warm = warm_default(3);
        warm[1].relative_position = Some(pos(5.0, 5.0));
        warm[2].relative_position = Some(pos(2.0, 2.0));
        let mut tree = build_tree(
            vec![plain(None), plain(Some(0)), plain(Some(1))],
            warm,
            &[vec![1], vec![2], vec![]],
        );
        let mut positions: PositionVec = Vec::new();
        position_flex_child_descendants(
            &mut tree,
            0,
            pos(50.0, 60.0),
            size(100.0, 100.0),
            &mut positions,
        )
        .expect("well-formed tree");
        assert_eq!(pos_get(&positions, 1), Some(pos(55.0, 65.0)));
        assert_eq!(pos_get(&positions, 2), Some(pos(57.0, 67.0)));
    }
    // ==================================================================
    // collect_children_dom_ids / layout_relevant_child_count
    // ==================================================================
    #[test]
    fn collect_children_dom_ids_skips_display_none_children() {
        // body(0) > [ div(1), div.hide(2), div(3) ]
        let sd = styled(
            Dom::create_body()
                .with_child(Dom::create_div())
                .with_child(div_class("hide"))
                .with_child(Dom::create_div()),
            ".hide { display: none; }",
        );
        let children = collect_children_dom_ids(&sd, NodeId::ZERO);
        assert_eq!(children, vec![NodeId::new(1), NodeId::new(3)]);
    }
    #[test]
    fn collect_children_dom_ids_for_leaves_and_unknown_parents_is_empty() {
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        // A leaf has no children.
        assert!(collect_children_dom_ids(&sd, NodeId::new(1)).is_empty());
        // An id past the end of the hierarchy must not panic.
        assert!(collect_children_dom_ids(&sd, NodeId::new(999)).is_empty());
        assert!(collect_children_dom_ids(&sd, NodeId::new(usize::MAX)).is_empty());
    }
    #[test]
    fn layout_relevant_child_count_counts_only_boxes_the_builder_would_emit() {
        // body(0) > [ div(1), text " "(2), div.hide(3) ]
        let sd = styled(
            Dom::create_body()
                .with_child(Dom::create_div())
                .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(" "))
                .with_child(div_class("hide")),
            ".hide { display: none; }",
        );
        let children = [NodeId::new(1), NodeId::new(2), NodeId::new(3)];
        // display:none is dropped, and the whitespace-only inline run between
        // block siblings collapses → only the first div survives.
        assert_eq!(layout_relevant_child_count(&sd, &children, NodeId::ZERO), 1);
        // Empty input → 0, no panic.
        assert_eq!(layout_relevant_child_count(&sd, &[], NodeId::ZERO), 0);
    }
    // ==================================================================
    // is_whitespace_only_inline_run (predicate)
    // ==================================================================
    #[test]
    fn is_whitespace_only_inline_run_empty_run_is_true() {
        let sd = whitespace_dom("");
        assert!(is_whitespace_only_inline_run(&sd, &[], NodeId::new(1)));
    }
    #[test]
    fn is_whitespace_only_inline_run_detects_collapsible_whitespace_text() {
        let sd = whitespace_dom("");
        // " \n\t" — only ASCII whitespace.
        assert!(is_whitespace_only_inline_run(
            &sd,
            &[(0, NodeId::new(2))],
            NodeId::new(1)
        ));
        // "hi" — real text.
        assert!(!is_whitespace_only_inline_run(
            &sd,
            &[(1, NodeId::new(3))],
            NodeId::new(1)
        ));
        // A mixed run is not whitespace-only.
        assert!(!is_whitespace_only_inline_run(
            &sd,
            &[(0, NodeId::new(2)), (1, NodeId::new(3))],
            NodeId::new(1)
        ));
    }
    #[test]
    fn is_whitespace_only_inline_run_rejects_elements_and_non_ascii_spaces() {
        let sd = whitespace_dom("");
        // A <div> in the run is not a text node → wrapper required.
        assert!(!is_whitespace_only_inline_run(
            &sd,
            &[(2, NodeId::new(4))],
            NodeId::new(1)
        ));
        // U+00A0 NO-BREAK SPACE is *not* collapsible whitespace in CSS, and the
        // ASCII-only char set correctly treats it as real content.
        assert!(!is_whitespace_only_inline_run(
            &sd,
            &[(3, NodeId::new(5))],
            NodeId::new(1)
        ));
    }
    #[test]
    fn is_whitespace_only_inline_run_respects_white_space_pre() {
        // With `white-space: pre` on the parent, whitespace is significant and the
        // anonymous IFC wrapper must still be created.
        let sd = whitespace_dom(".p { white-space: pre; }");
        assert!(!is_whitespace_only_inline_run(
            &sd,
            &[(0, NodeId::new(2))],
            NodeId::new(1)
        ));
        // Sanity: the same run collapses without the `pre`.
        let sd = whitespace_dom(".p { white-space: normal; }");
        assert!(is_whitespace_only_inline_run(
            &sd,
            &[(0, NodeId::new(2))],
            NodeId::new(1)
        ));
    }
    // ==================================================================
    // reposition_clean_subtrees / reposition_block_flow_siblings
    // ==================================================================
    #[test]
    fn reposition_clean_subtrees_ignores_empty_and_dangling_roots() {
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        let tree = build_tree(
            vec![
                hot(
                    None,
                    Some(NodeId::ZERO),
                    Some(size(100.0, 100.0)),
                    &zero_box_props(),
                ),
                plain(Some(0)),
            ],
            warm_default(2),
            &[vec![1], vec![]],
        );
        let mut positions = vec![pos(0.0, 0.0), pos(1.0, 1.0)];
        let before = positions.clone();
        // No dirty roots → nothing to reposition.
        reposition_clean_subtrees(&sd, &tree, &BTreeSet::new(), &mut positions);
        assert_eq!(positions, before);
        // A layout root that isn't in the tree must not panic.
        let mut roots = BTreeSet::new();
        roots.insert(99);
        roots.insert(usize::MAX);
        reposition_clean_subtrees(&sd, &tree, &roots, &mut positions);
        assert_eq!(positions, before);
    }
    #[test]
    fn reposition_clean_subtrees_skips_flex_parents() {
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        let mut nodes = vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(100.0, 100.0)),
                &zero_box_props(),
            ),
            plain(Some(0)),
        ];
        nodes[0].formatting_context = FormattingContext::Flex;
        let tree = build_tree(nodes, warm_default(2), &[vec![1], vec![]]);
        let mut positions = vec![pos(0.0, 0.0), pos(1.0, 1.0)];
        let before = positions.clone();
        let mut roots = BTreeSet::new();
        roots.insert(1);
        // Taffy owns flex layout; the sibling-repositioning shortcut is skipped.
        reposition_clean_subtrees(&sd, &tree, &roots, &mut positions);
        assert_eq!(positions, before);
    }
    #[test]
    fn reposition_block_flow_siblings_stacks_clean_children_from_the_content_origin() {
        // body(0) is the parent; children 1 and 2 are clean, 3 is a grandchild.
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        let parent_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(5.0, 5.0, 5.0, 5.0), // border — see the note below
            edges(3.0, 3.0, 3.0, 3.0), // padding
        );
        let tree = build_tree(
            vec![
                hot(
                    None,
                    Some(NodeId::ZERO),
                    Some(size(200.0, 200.0)),
                    &parent_bp,
                ),
                hot(Some(0), None, Some(size(200.0, 50.0)), &zero_box_props()),
                hot(Some(0), None, Some(size(200.0, 30.0)), &zero_box_props()),
                plain(Some(1)),
            ],
            warm_default(4),
            &[vec![1, 2], vec![3], vec![], vec![]],
        );
        let mut positions = vec![
            pos(10.0, 20.0), // parent (border-box origin)
            pos(0.0, 0.0),
            pos(0.0, 0.0),
            pos(0.0, 0.0),
        ];
        reposition_block_flow_siblings(&sd, 0, &tree, &BTreeSet::new(), &mut positions);
        // BEHAVIOUR PIN: the content origin is computed as parent_pos + PADDING
        // only — the parent's border is NOT added, unlike calculate_content_box_pos
        // (which adds border + padding to the same border-box origin). With a
        // bordered parent the clean siblings therefore land 5px up/left of where
        // the full layout pass would put them.
        assert_eq!(positions[1], pos(13.0, 23.0));
        assert_eq!(
            positions[2],
            pos(13.0, 73.0),
            "second child stacked below the first"
        );
        // The grandchild moved with its parent's subtree.
        assert_eq!(positions[3], pos(13.0, 23.0));
    }
    // ==================================================================
    // compute_counters
    // ==================================================================
    #[test]
    fn compute_counters_on_an_empty_or_anonymous_tree_does_not_panic() {
        let sd = styled(Dom::create_body(), "");
        let mut counters: HashMap<(usize, String), i32> = HashMap::new();
        // Root index past the end of the node list.
        let empty = build_tree(Vec::new(), Vec::new(), &[]);
        compute_counters(&sd, &empty, &mut counters);
        assert!(counters.is_empty());
        // Anonymous root (no dom_node_id) with an anonymous child.
        let anon = build_tree(
            vec![plain(None), plain(Some(0))],
            warm_default(2),
            &[vec![1], vec![]],
        );
        compute_counters(&sd, &anon, &mut counters);
        assert!(counters.is_empty());
    }
    #[test]
    fn compute_counters_increments_the_list_item_counter_in_document_order() {
        // body(0) > [ div.li(1), div.li(2) ]
        let sd = styled(
            Dom::create_body()
                .with_child(div_class("li"))
                .with_child(div_class("li")),
            ".li { display: list-item; }",
        );
        let tree = build_tree(
            vec![
                hot(
                    None,
                    Some(NodeId::ZERO),
                    Some(size(100.0, 100.0)),
                    &zero_box_props(),
                ),
                hot(
                    Some(0),
                    Some(NodeId::new(1)),
                    Some(size(100.0, 10.0)),
                    &zero_box_props(),
                ),
                hot(
                    Some(0),
                    Some(NodeId::new(2)),
                    Some(size(100.0, 10.0)),
                    &zero_box_props(),
                ),
            ],
            warm_default(3),
            &[vec![1, 2], vec![], vec![]],
        );
        let mut counters: HashMap<(usize, String), i32> = HashMap::new();
        compute_counters(&sd, &tree, &mut counters);
        // CSS Lists 3 § 3: `display: list-item` auto-increments "list-item".
        assert_eq!(counters.get(&(1, "list-item".to_string())), Some(&1));
        assert_eq!(counters.get(&(2, "list-item".to_string())), Some(&2));
        // The non-list-item root never enters a counter scope.
        assert_eq!(counters.get(&(0, "list-item".to_string())), None);
    }
    #[test]
    fn compute_counters_leaves_plain_elements_alone() {
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        let tree = build_tree(
            vec![
                hot(
                    None,
                    Some(NodeId::ZERO),
                    Some(size(100.0, 100.0)),
                    &zero_box_props(),
                ),
                hot(
                    Some(0),
                    Some(NodeId::new(1)),
                    Some(size(100.0, 10.0)),
                    &zero_box_props(),
                ),
            ],
            warm_default(2),
            &[vec![1], vec![]],
        );
        let mut counters: HashMap<(usize, String), i32> = HashMap::new();
        compute_counters(&sd, &tree, &mut counters);
        assert!(
            counters.is_empty(),
            "no counter-reset/increment → no counters"
        );
    }
}