1
//! Layout tree construction from a styled DOM, including anonymous box generation
2
use std::{
3
    cell::Cell,
4
    collections::BTreeMap,
5
    hash::{Hash, Hasher},
6
    sync::Arc,
7
};
8

            
9
use azul_core::{
10
    diff::NodeDataFingerprint,
11
    spaces::{ContentInset, Inclusivity},
12
};
13

            
14
use crate::text3::cache::UnifiedConstraints;
15

            
16
thread_local! {
17
    /// Per-thread counter for IFC IDs, reset to 0 at the start of each layout
18
    /// pass (see [`IfcId::reset_counter`]).
19
    ///
20
    /// This was previously a process-global `AtomicU32`. Two `layout_document`
21
    /// calls running concurrently on different threads (the `Sync` layout bound
22
    /// permits this) shared that single counter, so their IFC IDs interleaved and
23
    /// collided. A thread-local counter gives each pass its own sequence — a single
24
    /// pass is single-threaded (`LayoutContext` holds non-`Sync` `RefCell` caches),
25
    /// so IDs stay deterministic and stable across frames while never colliding
26
    /// across concurrent passes.
27
    static IFC_ID_COUNTER: Cell<u32> = const { Cell::new(0) };
28
}
29

            
30
/// Unique identifier for an Inline Formatting Context (IFC).
31
///
32
/// An IFC represents a region where inline content (text, inline-blocks, images)
33
/// is laid out together. One IFC can contain content from multiple DOM nodes
34
/// (e.g., `<p>Hello <span>world</span>!</p>` is one IFC with 3 text runs).
35
///
36
/// The ID is generated using a per-thread counter that resets at the start
37
/// of each layout pass. This ensures:
38
/// - IDs are unique within a layout pass
39
/// - The same logical IFC gets the same ID across frames (for selection stability)
40
/// - Concurrent `layout_document` passes on different threads can't collide
41
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
42
pub struct IfcId(pub u32);
43

            
44
impl IfcId {
45
    /// Generate a new unique IFC ID (within the current thread's layout pass).
46
    #[must_use]
47
75808
    pub fn unique() -> Self {
48
75808
        IFC_ID_COUNTER.with(|c| {
49
75808
            let v = c.get();
50
75808
            c.set(v.wrapping_add(1));
51
75808
            Self(v)
52
75808
        })
53
75808
    }
54

            
55
    /// Reset the IFC ID counter. Called at the start of each layout pass.
56
9131
    pub fn reset_counter() {
57
9131
        IFC_ID_COUNTER.with(|c| c.set(0));
58
9131
    }
59
}
60

            
61
/// Tracks a layout node's membership in an Inline Formatting Context.
62
///
63
/// Text nodes don't store their own `inline_layout_result` - instead, they
64
/// participate in their parent's IFC. This struct provides the link from
65
/// a text node back to its IFC's layout data.
66
///
67
/// # Architecture
68
///
69
/// ```text
70
/// DOM:  <p>Hello <span>world</span>!</p>
71
///
72
/// Layout Tree:
73
/// ├── LayoutNode (p) - IFC root
74
/// │   └── inline_layout_result: Some(UnifiedLayout)
75
/// │   └── ifc_id: IfcId(5)
76
/// │
77
/// ├── LayoutNode (::text "Hello ")
78
/// │   └── ifc_membership: Some(IfcMembership { ifc_id: 5, run_index: 0 })
79
/// │
80
/// ├── LayoutNode (span)
81
/// │   └── ifc_membership: Some(IfcMembership { ifc_id: 5, run_index: 1 })
82
/// │   └── LayoutNode (::text "world")
83
/// │       └── ifc_membership: Some(IfcMembership { ifc_id: 5, run_index: 1 })
84
/// │
85
/// └── LayoutNode (::text "!")
86
///     └── ifc_membership: Some(IfcMembership { ifc_id: 5, run_index: 2 })
87
/// ```
88
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89
pub struct IfcMembership {
90
    /// The IFC ID this node's content was laid out in.
91
    pub ifc_id: IfcId,
92
    /// The index of the IFC root `LayoutNode` in the layout tree.
93
    /// Used to quickly find the node with `inline_layout_result`.
94
    pub ifc_root_layout_index: usize,
95
    /// Which run index within the IFC corresponds to this node's text.
96
    /// Maps to `ContentIndex::run_index` in the shaped items.
97
    pub run_index: u32,
98
}
99

            
100
use azul_core::{
101
    dom::{FormattingContext, NodeData, NodeId, NodeType},
102
    geom::{LogicalPosition, LogicalRect, LogicalSize},
103
    styled_dom::StyledDom,
104
};
105
use azul_css::{
106
    codegen::format::GetHash,
107
    corety::LayoutDebugMessage,
108
    css::CssPropertyValue,
109
    props::{
110
        basic::{
111
            pixel::DEFAULT_FONT_SIZE, PhysicalSize, PixelValue, PropertyContext, ResolutionContext,
112
        },
113
        layout::{
114
            LayoutDisplay, LayoutFloat, LayoutHeight, LayoutMaxHeight, LayoutMaxWidth,
115
            LayoutMinHeight, LayoutMinWidth, LayoutOverflow, LayoutPosition, LayoutWidth,
116
            LayoutWritingMode,
117
        },
118
        property::{CssProperty, CssPropertyType},
119
        style::{StyleTextAlign, StyleWhiteSpace},
120
    },
121
};
122
use taffy::{Cache as TaffyCache, Layout, LayoutInput, LayoutOutput};
123

            
124
#[cfg(feature = "text_layout")]
125
use crate::text3;
126
use crate::{
127
    debug_log,
128
    font::parsed::ParsedFont,
129
    font_traits::{FontLoaderTrait, ParsedFontTrait, UnifiedLayout},
130
    solver3::{
131
        geometry::{BoxProps, IntrinsicSizes, PositionedRectangle},
132
        getters::{
133
            get_css_height, get_css_max_height, get_css_max_width, get_css_min_height,
134
            get_css_min_width, get_css_width, get_direction_property as get_direction,
135
            get_display_property, get_float, get_overflow_x, get_overflow_y, get_position,
136
            get_text_align, get_text_orientation_property as get_text_orientation,
137
            get_white_space_property, get_writing_mode, MultiValue,
138
        },
139
        scrollbar::ScrollbarRequirements,
140
        LayoutContext, Result,
141
    },
142
    text3::cache::AvailableSpace,
143
};
144

            
145
/// Represents the invalidation state of a layout node.
146
///
147
/// The states are ordered by severity, allowing for easy "upgrading" of the dirty state.
148
/// A node marked for `Layout` does not also need to be marked for `Paint`.
149
///
150
/// Because this enum derives `PartialOrd` and `Ord`, you can directly compare variants:
151
///
152
/// - `DirtyFlag::Layout > DirtyFlag::Paint` is `true`
153
/// - `DirtyFlag::Paint >= DirtyFlag::None` is `true`
154
/// - `DirtyFlag::Paint < DirtyFlag::Layout` is `true`
155
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
156
pub enum DirtyFlag {
157
    /// The node's layout is valid and no repaint is needed. This is the "clean" state.
158
    #[default]
159
    None,
160
    /// The node's geometry is valid, but its appearance (e.g., color) has changed.
161
    /// Requires a display list update only.
162
    Paint,
163
    /// The node's geometry (size or position) is invalid.
164
    /// Requires a full layout pass and a display list update.
165
    Layout,
166
}
167

            
168
/// A hash that represents the content and style of a node PLUS all of its descendants.
169
/// If two `SubtreeHashes` are equal, their entire subtrees are considered identical for layout
170
/// purposes.
171
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
172
pub struct SubtreeHash(pub u64);
173

            
174
/// Per-item metrics cached from the last IFC layout.
175
///
176
/// These metrics enable incremental IFC relayout (Phase 2 optimization):
177
/// when a single inline item changes, we can check whether its advance width
178
/// changed and potentially skip full line-breaking for unaffected lines.
179
///
180
/// Index in `CachedInlineLayout::item_metrics` matches the item order in
181
/// `UnifiedLayout::items`.
182
#[derive(Copy, Debug, Clone)]
183
pub struct InlineItemMetrics {
184
    /// The DOM `NodeId` of the source node for this item (for dirty checking).
185
    /// `None` for generated content (list markers, hyphens, etc.)
186
    pub source_node_id: Option<NodeId>,
187
    /// Advance width of this item (glyph run width, inline-block width, etc.)
188
    pub advance_width: f32,
189
    /// Advance height contribution from this item to its line box.
190
    pub line_height_contribution: f32,
191
    /// Whether this item can participate in line breaking.
192
    /// `false` for items inside `white-space: nowrap` or `white-space: pre`.
193
    pub can_break: bool,
194
    /// Which line this item was placed on (0-indexed).
195
    pub line_index: u32,
196
    /// X offset within its line.
197
    pub x_offset: f32,
198
}
199

            
200
/// Cached inline layout result with the constraints used to compute it.
201
///
202
/// This structure solves a fundamental architectural problem: inline layouts
203
/// (text wrapping, inline-block positioning) depend on the available width.
204
/// Different layout phases may compute the layout with different widths:
205
///
206
/// 1. **Min-content measurement**: width = `MinContent` (effectively 0)
207
/// 2. **Max-content measurement**: width = `MaxContent` (effectively infinite)
208
/// Cached output of `collect_and_measure_inline_content` (see
209
/// `LayoutNodeWarm::inline_content_cache`).
210
///
211
/// **This memo has a second output that is not in it.** The call it stands for
212
/// does not only collect: it lays out every atomic inline-level child, and that
213
/// layout is written to the TREE. So the struct is only reusable while those
214
/// children are still laid out in the tree being worked on — true for repeat
215
/// visits within one pass (min-content, max-content, definite), false the first
216
/// time an IFC root is visited in a rebuilt tree.
217
///
218
/// The `subtree_fingerprint` cannot see this; it describes content, not whether
219
/// anything has been laid out. `layout_ifc` therefore checks the second
220
/// precondition itself, at the point of use — see
221
/// `atomic_inline_children_are_laid_out` in `fc.rs`. Reuse without that check
222
/// leaves the child at 0x0 while the `InlineShape` here still carries its
223
/// measured size, so text flows around a box that paints and hit-tests as
224
/// nothing.
225
#[derive(Debug, Clone)]
226
pub struct CachedInlineContent {
227
    /// The collected inline content (text runs, atomics, markers).
228
    pub content: Vec<crate::text3::cache::InlineContent>,
229
    /// `ContentIndex` -> child layout-node index, as collection built it.
230
    pub child_map: std::collections::HashMap<crate::text3::cache::ContentIndex, usize>,
231
    /// Validity key: the fingerprints of the IFC root and its descendants,
232
    /// folded in tree order. Anything that changes text, style or structure
233
    /// changes a fingerprint, so an equal key means an identical collection.
234
    pub subtree_fingerprint: u64,
235
    /// Hash of `content` alone, computed ONCE when the collection is (re)built.
236
    ///
237
    /// The per-visit "current content hash" used to re-hash the full inline
238
    /// content on EVERY `layout_ifc` entry — 2 292 hashes × ~12.7 µs ≈ 29 ms
239
    /// per resize relayout on big.md, hashing bytes that by definition had not
240
    /// changed (an equal `subtree_fingerprint` is what admitted the cached
241
    /// collection in the first place). Visits now fold only the seven
242
    /// constraint-level container properties on top of this base.
243
    pub content_hash_base: u64,
244
}
245

            
246
/// 3. **Final layout**: width = `Definite(actual_column_width)`
247
///
248
/// Without tracking which constraints were used, a cached result from phase 1
249
/// would incorrectly be reused in phase 3, causing text to wrap at the wrong
250
/// positions (the root cause of table cell width bugs).
251
///
252
/// By storing the constraints alongside the result, we can:
253
/// - Invalidate the cache when constraints change
254
/// - Keep multiple cached results for different constraint types if needed
255
/// - Ensure the final render always uses a layout computed with correct widths
256
#[derive(Debug, Clone)]
257
pub struct CachedInlineLayout {
258
    /// The computed inline layout.
259
    ///
260
    /// (d6h RETIREMENT) Under `AZ_DENSE_TEXT=1`, when the dense view is
261
    /// retained AND covers every item (pure clusters), this holds a
262
    /// SHARED EMPTY sentinel instead of the real thing — the ~192 B/item
263
    /// sparse retention is the campaign's target. Every production
264
    /// reader is dense-first by d1-d6h; `verify` mode retains BOTH and
265
    /// A/B-asserts; flag-off is unchanged. `overflow` (below) carries
266
    /// the one field the sentinel loses.
267
    pub layout: Arc<UnifiedLayout>,
268
    /// (d6h) The real layout's overflow info, captured at store time —
269
    /// the incremental-relayout guard reads it after the sentinel swap.
270
    pub overflow: crate::text3::cache::OverflowInfo,
271
    /// The available width constraint used to compute this layout.
272
    /// This is the key for cache validity checking.
273
    /// +spec:writing-modes:1dcba2 - "available width" (CSS2.1) = auto size in inline axis
274
    pub available_width: AvailableSpace,
275
    /// Whether this layout was computed with float exclusions.
276
    /// Float-aware layouts should not be overwritten by non-float layouts.
277
    pub has_floats: bool,
278
    /// The full constraints used to compute this layout.
279
    /// Used for quick relayout after text edits without rebuilding from CSS.
280
    pub constraints: Option<UnifiedConstraints>,
281
    /// Glyph runs derived from `layout` at STORE time (a pure function of
282
    /// it — see `get_glyph_runs_simple`). The display-list generator used to
283
    /// re-derive these on EVERY paint of every IFC (the run-grouping walk was
284
    /// the bulk of `dl_inline_text`'s 6.8 ms/resize on big.md); computing them
285
    /// once alongside the layout makes every later paint a lookup. Rides
286
    /// `GlyphSwap` reuse for free — a reused layout is a reused run list.
287
    ///
288
    /// (#25) Stored COMPACT — 8 B/glyph instead of the 20 B `GlyphInstance`
289
    /// (y and size are per-run-uniform in the simple-run contract; deviants
290
    /// ride the exception table). Paint expands into the same offset Vec it
291
    /// always built; `AZ_DENSE_TEXT=verify` roundtrip-gates the encoding.
292
    pub glyph_runs: Arc<Vec<crate::text3::glyphs::CompactGlyphRun>>,
293
    /// Per-item metrics for incremental IFC relayout (Phase 2).
294
    ///
295
    /// Each entry corresponds to one `PositionedItem` in `layout.items`.
296
    /// These metrics enable the IFC relayout decision tree:
297
    /// - Check if a dirty node's `advance_width` changed → skip repositioning if not
298
    /// - Use `can_break` + `line_index` for the nowrap fast path
299
    /// - Use `x_offset` for shifting subsequent items without full line-breaking
300
    pub item_metrics: Vec<InlineItemMetrics>,
301
    /// Cached line break boundaries for incremental relayout.
302
    /// Enables checking if a width change fits on the same line without
303
    /// re-running the full line-breaking algorithm.
304
    pub line_breaks: Option<crate::text3::cache::CachedLineBreaks>,
305
    /// §3.2 step (d5): the ONE cache-stable Arc the display list carries
306
    /// as its `TextLayout` payload. `TextPayload{dense,sparse}` when the
307
    /// dense view is retained, else the `layout` Arc itself (identical
308
    /// to the pre-d5 payload). Built at store time so damage `ptr_eq`
309
    /// stays stable across paints.
310
    pub payload: Arc<dyn std::any::Any + Send + Sync>,
311
    /// §3.2 step (d1): the dense view of `layout`, retained when
312
    /// `AZ_DENSE_TEXT` is active (`glyph_runs` derive from THIS instance).
313
    /// Readers migrate from `layout` onto it one by one; the sparse form
314
    /// retires when the last reader has moved (plan §10.4).
315
    pub dense: Option<Arc<crate::text3::dense::DenseText>>,
316
    /// Hash of the `InlineContent` this layout was shaped from. The Phase 2d
317
    /// fast-path reuse in fc.rs keys cache validity on WIDTH only; without this,
318
    /// a same-width `RefreshDom` whose text CHANGED would reuse the stale shaped
319
    /// layout (#11 stale display list). 0 = unknown ⇒ never fast-path-reuse.
320
    pub inline_content_hash: u64,
321
    /// The STYLE environment this layout was shaped under (fonts, sizes,
322
    /// spacing — not paint-only fields), written only by the fast reshape
323
    /// path (`LayoutWindow::shaping_style_fingerprint`). The incremental
324
    /// patcher pastes new glyphs onto CACHED pen positions, which is only
325
    /// sound when both were shaped under the same style; 0 = unknown
326
    /// (full-layout caches) ⇒ it re-runs stage 4 instead. Pinned by the
327
    /// 2026-08-29 `TextInput` bug: a 16px-seeded reshape met an 11px cache
328
    /// and pasted large glyphs onto short advances every other frame.
329
    pub shaping_style_fp: u64,
330
}
331

            
332
/// §3.2 step (d5): the display list's `TextLayout` payload when the dense
333
/// view is retained — BOTH forms behind one cache-stable Arc, so
334
/// `TextLayout` damage diffing (`Arc::ptr_eq`) keeps firing exactly as
335
/// before. Downcasters try this first and fall back to a bare
336
/// `UnifiedLayout` payload (the flag-off path). The `sparse` half is
337
/// what current consumers read; it empties at the d6 retirement, which
338
/// is when the consumers move onto `dense`.
339
#[derive(Debug)]
340
pub struct TextPayload {
341
    pub dense: Arc<crate::text3::dense::DenseText>,
342
    pub sparse: Arc<UnifiedLayout>,
343
}
344

            
345
/// §3.2 flip step (a): the paint-run computation, routed by `AZ_DENSE_TEXT`.
346
///
347
/// - unset/`0` — the sparse reference walker (production default).
348
/// - `1`      — build [`crate::text3::dense::DenseText`] and walk THAT
349
///   (`get_glyph_runs_simple_dense`), the compact model's first production consumer.
350
/// - `verify` — dense path PLUS an A/B assert against the reference; the e2e corpus run with this
351
///   set is the flip proof over real layouts.
352
///
353
/// Layouts containing combined blocks (tate-chu-yoko) fall back to the
354
/// reference under the flag: the dense model keeps atomics on the sparse
355
/// side by design and the twin would silently DROP their glyphs.
356
167442
fn compute_glyph_runs(
357
167442
    layout: &UnifiedLayout,
358
167442
) -> (
359
167442
    Vec<crate::text3::glyphs::SimpleGlyphRun>,
360
167442
    Option<Arc<crate::text3::dense::DenseText>>,
361
167442
) {
362
167442
    compute_glyph_runs_with_mode(layout, dense_text_mode())
363
167442
}
364

            
365
/// The process-wide `AZ_DENSE_TEXT` mode: 0 off, 1 on, 2 verify.
366
///
367
/// (d7) DEFAULT ON: the dense model is the stored form in production —
368
/// the retirement (d6h) plateaued at 65.2 MB heap vs 73.6 flag-off on
369
/// the 960-line corpus, with the full battery + flag-on corpus +
370
/// flag-on reftests green. `AZ_DENSE_TEXT=0` is the escape hatch;
371
/// `verify` retains both forms and A/B-asserts every dense-first arm.
372
502466
pub(crate) fn dense_text_mode() -> u8 {
373
    static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
374
502466
    *MODE.get_or_init(|| match std::env::var("AZ_DENSE_TEXT").as_deref() {
375
        Ok("0" | "off") => 0,
376
        Ok("verify") => 2,
377
32
        _ => 1,
378
32
    })
379
502466
}
380

            
381
/// #25: converts the transient builder output into the stored compact form.
382
/// Under `AZ_DENSE_TEXT=verify` every run is roundtripped and compared
383
/// BIT-EXACTLY against its original — the same proof obligation the dense
384
/// campaign carried: the stored form must be an encoding, never a rewrite.
385
167442
fn compact_glyph_runs(
386
167442
    runs: Vec<crate::text3::glyphs::SimpleGlyphRun>,
387
167442
) -> Vec<crate::text3::glyphs::CompactGlyphRun> {
388
167442
    let verify = dense_text_mode() == 2;
389
167442
    runs.into_iter()
390
197799
        .map(|r| {
391
197754
            if verify {
392
                let compact = crate::text3::glyphs::CompactGlyphRun::from(r.clone());
393
                assert!(
394
                    crate::text3::glyphs::simple_runs_bit_equal(&compact.expand(), &r),
395
                    "#25 compact glyph-run roundtrip diverged from the original"
396
                );
397
                compact
398
            } else {
399
197754
                crate::text3::glyphs::CompactGlyphRun::from(r)
400
            }
401
197754
        })
402
167442
        .collect()
403
167442
}
404

            
405
/// Testable core of [`compute_glyph_runs`] — `mode` injected so the d1
406
/// retention pin can exercise the dense path without env-var races.
407
167445
fn compute_glyph_runs_with_mode(
408
167445
    layout: &UnifiedLayout,
409
167445
    mode: u8,
410
167445
) -> (
411
167445
    Vec<crate::text3::glyphs::SimpleGlyphRun>,
412
167445
    Option<Arc<crate::text3::dense::DenseText>>,
413
167445
) {
414
    use crate::text3::cache::ShapedItem;
415
167445
    if mode == 0
416
167444
        || layout
417
167444
            .items
418
167444
            .iter()
419
2769392
            .any(|it| matches!(it.item, ShapedItem::CombinedBlock { .. }))
420
    {
421
1
        return (crate::text3::glyphs::get_glyph_runs_simple(layout), None);
422
167444
    }
423
    // §3.2 step (d1): the dense view is RETAINED on the cache entry, not
424
    // rebuilt-and-dropped per walk — the readers migrate onto it one by
425
    // one, and the sparse `layout` retires when the last one has.
426
167444
    let dense = crate::text3::dense::DenseText::from_unified(layout);
427
167444
    let ours = crate::text3::dense::get_glyph_runs_simple_dense(&dense);
428
167444
    if mode == 2 {
429
1
        let reference = crate::text3::glyphs::get_glyph_runs_simple(layout);
430
1
        assert_eq!(
431
1
            reference.len(),
432
1
            ours.len(),
433
            "AZ_DENSE_TEXT=verify: run count diverged"
434
        );
435
1
        for (i, (r, o)) in reference.iter().zip(ours.iter()).enumerate() {
436
            assert!(
437
                r.color == o.color
438
                    && r.background_color == o.background_color
439
                    && r.background_content == o.background_content
440
                    && r.border == o.border
441
                    && r.font_hash == o.font_hash
442
                    && (r.font_size_px - o.font_size_px).abs() < 0.01
443
                    && r.text_decoration == o.text_decoration
444
                    && r.source_node_id == o.source_node_id
445
                    && r.glyphs.len() == o.glyphs.len()
446
                    && r.glyphs.iter().zip(o.glyphs.iter()).all(|(a, b)| {
447
                        a.index == b.index
448
                            && (a.point.x - b.point.x).abs() < 0.01
449
                            && (a.point.y - b.point.y).abs() < 0.01
450
                    }),
451
                "AZ_DENSE_TEXT=verify: run {i} diverged from the reference\n  color {:?}/{:?} bg \
452
                 {:?}/{:?} font_hash {:?}/{:?} size {}/{} deco {:?}/{:?} node {:?}/{:?}\n  glyph \
453
                 count {} vs {}\n  ref glyphs {:?}\n  our glyphs {:?}",
454
                r.color,
455
                o.color,
456
                r.background_color,
457
                o.background_color,
458
                r.font_hash,
459
                o.font_hash,
460
                r.font_size_px,
461
                o.font_size_px,
462
                r.text_decoration,
463
                o.text_decoration,
464
                r.source_node_id,
465
                o.source_node_id,
466
                r.glyphs.len(),
467
                o.glyphs.len(),
468
                r.glyphs
469
                    .iter()
470
                    .map(|g| (g.index, g.point.x, g.point.y))
471
                    .collect::<Vec<_>>(),
472
                o.glyphs
473
                    .iter()
474
                    .map(|g| (g.index, g.point.x, g.point.y))
475
                    .collect::<Vec<_>>(),
476
            );
477
        }
478
167443
    }
479
167444
    (ours, Some(Arc::new(dense)))
480
167445
}
481

            
482
/// §3.2 step (d2): per-item metrics FROM the dense view. Returns None
483
/// unless the layout was PURE clusters (`dense.clusters.len()` must
484
/// equal `layout.items.len()` — the dense builder silently skips
485
/// objects/tabs/breaks/combined blocks, and `item_metrics` is
486
/// index-aligned with ALL items, so a shorter vec would silently
487
/// misalign the incremental-relayout decision tree).
488
///
489
/// Field-for-field vs the sparse extraction (the d2 gate pins this):
490
/// `advance_width` = ClusterCompact.advance (BASE advance == bounds().width
491
/// since the d2 redefinition), `line_height_contribution` = the run's
492
/// resolved line height (== ascent+descent by the half-leading identity),
493
/// `can_break` = true (clusters are never `ShapedItem::Break`), `line_index` =
494
/// `LineRecord.source_index`, `x_offset` = ClusterCompact.x.
495
167442
fn extract_item_metrics_dense(
496
167442
    dense: &crate::text3::dense::DenseText,
497
167442
    item_count: usize,
498
167442
) -> Option<Vec<InlineItemMetrics>> {
499
167442
    if dense.clusters.len() != item_count {
500
945
        return None;
501
166497
    }
502
166497
    let mut out = Vec::with_capacity(dense.clusters.len());
503
166497
    let mut line_iter = dense.lines.iter().peekable();
504
2762457
    for (ci, run) in dense
505
166497
        .runs
506
166497
        .iter()
507
2762457
        .flat_map(|r| (r.clusters.start..r.clusters.end).map(move |i| (i, r)))
508
    {
509
2762457
        let c = &dense.clusters[ci as usize];
510
2791364
        while let Some(l) = line_iter.peek() {
511
2791364
            if ci >= l.clusters.1 {
512
28907
                line_iter.next();
513
28907
            } else {
514
2762457
                break;
515
            }
516
        }
517
2762457
        let line_index = line_iter.peek().map_or(0, |l| l.source_index);
518
2762457
        let m = &run.font_metrics;
519
2762457
        let lh = if m.units_per_em == 0 {
520
14
            0.0
521
        } else {
522
2762443
            run.style
523
2762443
                .line_height
524
2762443
                .resolve_with_metrics(run.style.font_size_px, m)
525
        };
526
2762457
        out.push(InlineItemMetrics {
527
2762457
            source_node_id: (run.source_node != u32::MAX)
528
2762457
                .then(|| NodeId::new(run.source_node as usize)),
529
2762457
            advance_width: c.advance,
530
2762457
            line_height_contribution: lh,
531
            can_break: true,
532
2762457
            line_index,
533
2762457
            x_offset: c.x,
534
        });
535
    }
536
166497
    Some(out)
537
167442
}
538

            
539
impl CachedInlineLayout {
540
    /// Creates a new cached inline layout.
541
    #[must_use]
542
109
    pub fn new(
543
109
        layout: Arc<UnifiedLayout>,
544
109
        available_width: AvailableSpace,
545
109
        has_floats: bool,
546
109
    ) -> Self {
547
109
        let (runs, dense) = compute_glyph_runs(&layout);
548
109
        let glyph_runs = Arc::new(compact_glyph_runs(runs));
549
109
        let item_metrics = Self::choose_item_metrics(&layout, dense.as_deref());
550
109
        let (layout, overflow) = Self::retire_sparse(layout, dense.as_deref());
551
        // Payload built from the STORED form — under the retirement the
552
        // sparse half is the sentinel and consumers expand from dense.
553
109
        let payload = Self::build_payload(&layout, dense.as_ref());
554
109
        Self {
555
109
            layout,
556
109
            overflow,
557
109
            available_width,
558
109
            has_floats,
559
109
            constraints: None,
560
109
            payload,
561
109
            glyph_runs,
562
109
            item_metrics,
563
109
            line_breaks: None,
564
109
            dense,
565
109
            inline_content_hash: 0,
566
109
            shaping_style_fp: 0,
567
109
        }
568
109
    }
569

            
570
    /// Creates a new cached inline layout with full constraints.
571
    #[must_use]
572
167333
    pub fn new_with_constraints(
573
167333
        layout: Arc<UnifiedLayout>,
574
167333
        available_width: AvailableSpace,
575
167333
        has_floats: bool,
576
167333
        constraints: UnifiedConstraints,
577
167333
    ) -> Self {
578
167333
        let available_width_px = match available_width {
579
92862
            AvailableSpace::Definite(w) => w,
580
74471
            _ => f32::MAX,
581
        };
582
167333
        let line_breaks = Some(crate::text3::cache::extract_line_breaks(
583
167333
            &layout.items,
584
167333
            available_width_px,
585
167333
        ));
586
167333
        let (runs, dense) = compute_glyph_runs(&layout);
587
167333
        let glyph_runs = Arc::new(compact_glyph_runs(runs));
588
167333
        let item_metrics = Self::choose_item_metrics(&layout, dense.as_deref());
589
167333
        let (layout, overflow) = Self::retire_sparse(layout, dense.as_deref());
590
        // Payload built from the STORED form — under the retirement the
591
        // sparse half is the sentinel and consumers expand from dense.
592
167333
        let payload = Self::build_payload(&layout, dense.as_ref());
593
167333
        Self {
594
167333
            layout,
595
167333
            overflow,
596
167333
            available_width,
597
167333
            has_floats,
598
167333
            constraints: Some(constraints),
599
167333
            payload,
600
167333
            glyph_runs,
601
167333
            item_metrics,
602
167333
            line_breaks,
603
167333
            dense,
604
167333
            inline_content_hash: 0,
605
167333
            shaping_style_fp: 0,
606
167333
        }
607
167333
    }
608

            
609
    /// (d6h) The stored layout, MATERIALIZED if it is the retirement
610
    /// sentinel: dense expands (exact by the d6h expansion gate) into a
611
    /// transient sparse copy. The universal accessor for readers that
612
    /// measure or walk content; flag-off / verify / non-pure entries
613
    /// return the stored Arc untouched.
614
    #[must_use]
615
107995
    pub fn materialized(&self) -> Arc<UnifiedLayout> {
616
107995
        if self.layout.items.is_empty() {
617
107370
            if let Some(d) = self.dense.as_deref() {
618
107370
                if !d.clusters.is_empty() {
619
107350
                    return Arc::new(UnifiedLayout {
620
107350
                        items: d.to_unified_items(),
621
107350
                        overflow: self.overflow.clone(),
622
107350
                    });
623
20
                }
624
            }
625
625
        }
626
645
        self.layout.clone()
627
107995
    }
628

            
629
    /// (d6h) THE RETIREMENT: under `AZ_DENSE_TEXT=1`, a pure-cluster
630
    /// layout whose dense view is retained stores a SHARED EMPTY
631
    /// sentinel in `layout` — the per-item sparse retention (the
632
    /// campaign's ~192 B/cluster target) drops here. The real overflow
633
    /// info is captured first (the incremental guard reads it).
634
    /// `verify` mode (2) retains BOTH so every dense-first arm keeps
635
    /// A/B-asserting; flag-off (0) is byte-for-byte unchanged.
636
167442
    fn retire_sparse(
637
167442
        layout: Arc<UnifiedLayout>,
638
167442
        dense: Option<&crate::text3::dense::DenseText>,
639
167442
    ) -> (Arc<UnifiedLayout>, crate::text3::cache::OverflowInfo) {
640
167442
        let overflow = layout.overflow.clone();
641
        // Empty layouts are skipped: nothing to save, and the identity
642
        // swap would be pure Arc churn (unit fixtures rely on ptr_eq).
643
167442
        let fully_covered = !layout.items.is_empty()
644
166642
            && dense.is_some_and(|d| d.clusters.len() == layout.items.len());
645
167442
        if dense_text_mode() == 1 && fully_covered {
646
            static EMPTY: std::sync::OnceLock<Arc<UnifiedLayout>> = std::sync::OnceLock::new();
647
165697
            let sentinel = EMPTY
648
165697
                .get_or_init(|| {
649
32
                    Arc::new(UnifiedLayout {
650
32
                        items: Vec::new(),
651
32
                        overflow: crate::text3::cache::OverflowInfo::default(),
652
32
                    })
653
32
                })
654
165697
                .clone();
655
165697
            return (sentinel, overflow);
656
1745
        }
657
1745
        (layout, overflow)
658
167442
    }
659

            
660
    /// (d5) The cache-stable DL payload — see the `payload` field.
661
167442
    fn build_payload(
662
167442
        layout: &Arc<UnifiedLayout>,
663
167442
        dense: Option<&Arc<crate::text3::dense::DenseText>>,
664
167442
    ) -> Arc<dyn std::any::Any + Send + Sync> {
665
167442
        if let Some(d) = dense {
666
167442
            Arc::new(TextPayload {
667
167442
                dense: d.clone(),
668
167442
                sparse: layout.clone(),
669
167442
            })
670
        } else {
671
            let shared: Arc<dyn std::any::Any + Send + Sync> = layout.clone();
672
            shared
673
        }
674
167442
    }
675

            
676
    /// (d2) Metrics source selection: dense when retained AND the layout
677
    /// is pure clusters; sparse otherwise. Under `AZ_DENSE_TEXT=verify` the
678
    /// dense result is A/B-asserted against the sparse extraction.
679
167442
    fn choose_item_metrics(
680
167442
        layout: &UnifiedLayout,
681
167442
        dense: Option<&crate::text3::dense::DenseText>,
682
167442
    ) -> Vec<InlineItemMetrics> {
683
167442
        let Some(d) = dense else {
684
            return Self::extract_item_metrics(layout);
685
        };
686
167442
        let Some(from_dense) = extract_item_metrics_dense(d, layout.items.len()) else {
687
945
            return Self::extract_item_metrics(layout);
688
        };
689
166497
        let verify = std::env::var("AZ_DENSE_TEXT").as_deref() == Ok("verify");
690
166497
        if verify {
691
            let reference = Self::extract_item_metrics(layout);
692
            assert_eq!(
693
                reference.len(),
694
                from_dense.len(),
695
                "d2 verify: metrics count"
696
            );
697
            for (i, (r, o)) in reference.iter().zip(from_dense.iter()).enumerate() {
698
                assert!(
699
                    r.source_node_id == o.source_node_id
700
                        && (r.advance_width - o.advance_width).abs() < 0.01
701
                        && (r.line_height_contribution - o.line_height_contribution).abs() < 0.01
702
                        && r.can_break == o.can_break
703
                        && r.line_index == o.line_index
704
                        && (r.x_offset - o.x_offset).abs() < 0.01,
705
                    "d2 verify: metrics @{i} diverged (ref {r:?} vs dense {o:?})"
706
                );
707
            }
708
166497
        }
709
166497
        from_dense
710
167442
    }
711

            
712
    /// Extracts per-item metrics from a computed `UnifiedLayout`.
713
    ///
714
    /// This is called automatically by the constructors. The metrics
715
    /// enable incremental IFC relayout in Phase 2c/2d by providing
716
    /// cached advance widths, line assignments, and break information
717
    /// for each positioned item.
718
    #[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
719
950
    fn extract_item_metrics(layout: &UnifiedLayout) -> Vec<InlineItemMetrics> {
720
        use crate::text3::cache::{get_item_vertical_metrics_approx, ShapedItem};
721

            
722
950
        layout
723
950
            .items
724
950
            .iter()
725
6941
            .map(|positioned_item| {
726
6941
                let bounds = positioned_item.item.bounds();
727
6941
                let (ascent, descent) = get_item_vertical_metrics_approx(&positioned_item.item);
728

            
729
6941
                let source_node_id = match &positioned_item.item {
730
5450
                    ShapedItem::Cluster(c) => c.source_node_id,
731
                    // Objects (inline-blocks, images) and other generated items
732
                    // don't expose source_node_id directly on ShapedItem.
733
                    // Phase 2c will refine this via the ContentIndex mapping.
734
                    ShapedItem::Object { .. }
735
                    | ShapedItem::CombinedBlock { .. }
736
                    | ShapedItem::Tab { .. }
737
1491
                    | ShapedItem::Break { .. } => None,
738
                };
739

            
740
                // For Phase 2a, default can_break = true for all items.
741
                // Phase 2c will refine this by checking the white-space property
742
                // on the IFC root's style or the item's own style context.
743
                // (Note: text3::StyleProperties doesn't carry white-space;
744
                //  that's resolved at the IFC/BFC boundary level.)
745
6941
                let can_break = !matches!(&positioned_item.item, ShapedItem::Break { .. });
746

            
747
6941
                InlineItemMetrics {
748
6941
                    source_node_id,
749
6941
                    advance_width: bounds.width,
750
6941
                    line_height_contribution: ascent + descent,
751
6941
                    can_break,
752
6941
                    line_index: positioned_item.line_index as u32,
753
6941
                    x_offset: positioned_item.position.x,
754
6941
                }
755
6941
            })
756
950
            .collect()
757
950
    }
758

            
759
    /// Checks if this cached layout is valid for the given constraints.
760
    ///
761
    /// A cached layout is valid if:
762
    /// 1. The available width matches (definite widths must be equal, or both are the same
763
    ///    indefinite type)
764
    /// 2. OR the new request doesn't have floats but the cached one does (keep float-aware layout)
765
    ///
766
    /// The second condition preserves float-aware layouts, which are more "correct" than
767
    /// non-float layouts and shouldn't be overwritten.
768
    #[must_use]
769
210462
    pub fn is_valid_for(&self, new_width: AvailableSpace, new_has_floats: bool) -> bool {
770
        // A cached layout with NO floats must not be reused when the new request DOES
771
        // have floats: the line boxes have to re-wrap around the float exclusions.
772
        // Without this, the two-pass IFC path (no-float sizing pass, then float-aware
773
        // re-layout) reuses the pass-1 no-float line breaks and text ignores the float
774
        // entirely (#19). Mirrors should_replace_with()'s gain-float branch so the two
775
        // stay consistent.
776
210462
        if new_has_floats && !self.has_floats {
777
146
            return false;
778
210316
        }
779

            
780
        // If we have a float-aware layout and the new request doesn't have floats,
781
        // keep the float-aware layout (it's more accurate)
782
210316
        if self.has_floats && !new_has_floats {
783
            // But only if the width constraint type matches
784
36
            return self.width_constraint_matches(new_width);
785
210280
        }
786

            
787
        // Otherwise, require exact width match
788
210280
        self.width_constraint_matches(new_width)
789
210462
    }
790

            
791
    /// Tolerance for comparing definite layout widths (in logical pixels).
792
    /// Sub-pixel differences below this threshold are treated as identical
793
    /// to avoid unnecessary relayout from floating-point rounding.
794
    const LAYOUT_WIDTH_EPSILON: f32 = 0.1;
795

            
796
    /// Checks if the width constraint matches.
797
    #[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input
798
                                      // variant (or cross-type bindings that can't merge)
799
314669
    fn width_constraint_matches(&self, new_width: AvailableSpace) -> bool {
800
314669
        match (self.available_width, new_width) {
801
            // Definite widths must match within a small epsilon
802
159654
            (AvailableSpace::Definite(old), AvailableSpace::Definite(new)) => {
803
159654
                (old - new).abs() < Self::LAYOUT_WIDTH_EPSILON
804
            }
805
            // MinContent matches MinContent
806
10
            (AvailableSpace::MinContent, AvailableSpace::MinContent) => true,
807
            // MaxContent matches MaxContent
808
10
            (AvailableSpace::MaxContent, AvailableSpace::MaxContent) => true,
809
            // Different constraint types don't match
810
154995
            _ => false,
811
        }
812
314669
    }
813

            
814
    /// Determines if this cached layout should be replaced by a new layout.
815
    ///
816
    /// Returns true if the new layout should replace this one.
817
    #[must_use]
818
104451
    pub fn should_replace_with(&self, new_width: AvailableSpace, new_has_floats: bool) -> bool {
819
        // Always replace if we gain float information
820
104451
        if new_has_floats && !self.has_floats {
821
148
            return true;
822
104303
        }
823

            
824
        // Replace if width constraint changed
825
104303
        !self.width_constraint_matches(new_width)
826
104451
    }
827

            
828
    /// Returns a reference to the inner `UnifiedLayout`.
829
    ///
830
    /// This is a convenience method for code that only needs the layout data
831
    /// and doesn't care about the caching metadata.
832
    #[inline]
833
    #[must_use]
834
522
    pub const fn get_layout(&self) -> &Arc<UnifiedLayout> {
835
522
        &self.layout
836
522
    }
837

            
838
    /// Returns a clone of the inner Arc<UnifiedLayout>.
839
    ///
840
    /// This is useful for APIs that need to return an owned reference
841
    /// to the layout without exposing the caching metadata.
842
    #[inline]
843
    #[must_use]
844
2
    pub fn clone_layout(&self) -> Arc<UnifiedLayout> {
845
2
        self.layout.clone()
846
2
    }
847
}
848

            
849
/// A layout tree node representing the CSS box model.
850
///
851
/// ## Memory Layout Optimization (`#[repr(C)]`)
852
///
853
/// Fields are ordered by access frequency (hottest first) to maximize CPU
854
/// cache line utilization during tree traversal. With `#[repr(C)]`, the
855
/// compiler preserves this ordering. The 6 hottest fields (~140 bytes)
856
/// occupy the first 2-3 cache lines (64 bytes each), which are loaded
857
/// first by the hardware prefetcher.
858
///
859
/// | Tier   | Fields                                  | ~Bytes | Accesses |
860
/// |--------|-----------------------------------------|--------|----------|
861
/// | HOT    | `box_props`, `dom_node_id`, children,       |  ~140  |  410+    |
862
/// |        | `used_size`, `formatting_context`, parent    |        |          |
863
/// | WARM   | `intrinsic_sizes..computed_style`          |  ~220  |  ~80     |
864
/// | COLD   | `dirty_flag..is_anonymous`                 |  ~190  |  ~20     |
865
///
866
/// Note: An absolute position is a final paint-time value and shouldn't be
867
/// cached on the node itself, as it can change even if the node's
868
/// layout is clean (e.g., if a sibling changes size). We will calculate
869
/// it in a separate map.
870
#[derive(Debug, Clone)]
871
#[repr(C)]
872
pub struct LayoutNode {
873
    // ── HOT tier: accessed on every node in every layout pass ────────────
874
    // These fields should fit in the first 2-3 cache lines (~128-192 bytes).
875
    /// The resolved box model properties (margin, border, padding)
876
    /// in logical pixels. Cached after first resolution.
877
    /// (148 accesses — hottest field)
878
    pub box_props: BoxProps,
879
    /// Reference back to the original DOM node (None for anonymous boxes)
880
    /// (111 accesses)
881
    pub dom_node_id: Option<NodeId>,
882
    /// Children indices in the layout tree
883
    /// (53 accesses)
884
    pub children: Vec<usize>,
885
    /// The size used during the last layout pass.
886
    /// (43 accesses)
887
    pub used_size: Option<LogicalSize>,
888
    /// The formatting context this node establishes or participates in.
889
    /// (30 accesses)
890
    pub formatting_context: FormattingContext,
891
    /// Parent index (None for root)
892
    /// (25 accesses)
893
    pub parent: Option<usize>,
894

            
895
    // ── WARM tier: frequently accessed but not on every node ─────────────
896
    /// Cached intrinsic sizes (min-content, max-content, etc.)
897
    /// (16 accesses — sizing pass only)
898
    pub intrinsic_sizes: Option<IntrinsicSizes>,
899
    // +spec:display-property:af3a89 - alignment baseline for inline-level boxes
900
    /// The baseline of this box, if applicable, measured from its content-box top edge.
901
    /// (14 accesses — IFC/table alignment)
902
    pub baseline: Option<f32>,
903
    /// Cached inline layout result with the constraints used to compute it.
904
    ///
905
    /// This field stores both the computed layout AND the constraints (available width,
906
    /// float state) under which it was computed. This is essential for correctness:
907
    ///
908
    /// - Table cells are measured multiple times with different widths
909
    /// - Min-content/max-content intrinsic sizing uses special constraint values
910
    /// - The final layout must use the actual available width, not a measurement width
911
    ///
912
    /// By tracking the constraints, we avoid the bug where a min-content measurement
913
    /// (with width=0) would be incorrectly reused for final rendering.
914
    /// (13 accesses — IFC roots / table cells)
915
    /// BOXED (rare-data split, 2026-08-11): populated only on IFC roots /
916
    /// table cells; the 296-B inline Option was paid by EVERY node.
917
    pub inline_layout_result: Option<Box<CachedInlineLayout>>,
918
    /// See [`LayoutNodeWarm::inline_content_cache`]. BOXED likewise (88 B).
919
    pub inline_content_cache: Option<Box<CachedInlineContent>>,
920
    /// Cached scrollbar information (calculated during layout)
921
    /// Used to determine if scrollbars appeared/disappeared requiring reflow
922
    /// (12 accesses — scrollable containers only)
923
    pub scrollbar_info: Option<ScrollbarRequirements>,
924
    /// The position of this node *relative to its parent's content box*.
925
    /// (9 accesses — positioning pass)
926
    pub relative_position: Option<LogicalPosition>,
927
    /// The actual content size (children overflow size) for scrollable containers.
928
    /// This is the size of all content that might need to be scrolled, which can
929
    /// be larger than `used_size` when content overflows the container.
930
    /// (7 accesses — scrollable containers)
931
    pub overflow_content_size: Option<LogicalSize>,
932
    /// Cache for Taffy layout computations for this node.
933
    /// (6 accesses — Taffy bridge)
934
    pub taffy_cache: TaffyCache,
935
    /// Pure min-content / max-content measure results from the taffy bridge
936
    /// (`(min, max)` outer sizes), keyed by NOTHING — a pure content
937
    /// measurement is viewport-independent, so it stays valid until the
938
    /// node's content changes. Invalidated wherever `taffy_cache` is
939
    /// (the intrinsic-dirty ancestor closure). WHY separate from
940
    /// `taffy_cache`: taffy's slot classes collide under the flex
941
    /// algorithm's candidate-width probing (Definite(0)/Definite(w1)/…
942
    /// share a slot and evict each other within one pass), so min/max
943
    /// entries did not survive to the NEXT pass — 312 full min/max-content
944
    /// subtree re-layouts per steady resize on big.md, each re-breaking
945
    /// every IFC line in the subtree AND evicting the Definite entry of
946
    /// the single-slot IFC cache on the way (the 429 `text_layout_flow`
947
    /// calls). (2 accesses — Taffy bridge measure path)
948
    pub measured_content_sizes: (Option<LayoutOutput>, Option<LayoutOutput>),
949
    /// Pre-computed CSS properties needed during layout.
950
    /// Computed once during layout tree build to avoid repeated style lookups.
951
    /// (5 accesses — cache.rs only)
952
    pub computed_style: ComputedLayoutStyle,
953
    /// Pseudo-element type (`::marker`, `::before`, `::after`) if this node is a pseudo-element
954
    /// (5 accesses — pseudo-elements only)
955
    pub pseudo_element: Option<PseudoElement>,
956
    /// Escaped top margin (CSS 2.1 margin collapsing)
957
    /// If this BFC's first child's top margin "escaped" the BFC, this contains
958
    /// the collapsed margin that should be applied by the parent.
959
    /// (4 accesses — BFC margin collapsing)
960
    pub escaped_top_margin: Option<f32>,
961
    /// Escaped bottom margin (CSS 2.1 margin collapsing)\
962
    /// If this BFC's last child's bottom margin "escaped" the BFC, this contains
963
    /// the collapsed margin that should be applied by the parent.
964
    /// (4 accesses)
965
    pub escaped_bottom_margin: Option<f32>,
966
    /// Parent's formatting context (needed to determine if stretch applies)
967
    /// (4 accesses — flex/grid children)
968
    pub parent_formatting_context: Option<FormattingContext>,
969
    /// If this node participates in an IFC (is inline content like text),
970
    /// stores the reference back to the IFC root and the run index.
971
    /// This allows text nodes to find their layout data in the parent's IFC.
972
    /// (3 accesses — text nodes only)
973
    pub ifc_membership: Option<IfcMembership>,
974
    /// The layout tree index of this node's containing block.
975
    /// - For abs-pos elements: nearest positioned (non-static) ancestor
976
    /// - For fixed elements: root / None (viewport)
977
    /// - For normal-flow: parent (None = implicit) Used for clip exemption: abs-pos elements whose
978
    ///   containing block is above an overflow clipper should not be clipped.
979
    pub containing_block_index: Option<usize>,
980

            
981
    // ── COLD tier: construction / reconciliation / debugging only ────────
982
    /// Type of anonymous box (if applicable)
983
    /// (2 accesses)
984
    pub anonymous_type: Option<AnonymousBoxType>,
985
    /// O3-render: when this node is one PART of a structural-split PREVIEW,
986
    /// the flat byte range of the source node's inline content this part
987
    /// displays (`u32::MAX` end = to the end). The IFC build slices its
988
    /// collected content by this range. `None` = the node shows everything
989
    /// (the universal case outside previews).
990
    pub preview_byte_range: Option<(u32, u32)>,
991
    /// Multi-field fingerprint of this node's data (style, text, etc.)
992
    /// for granular change detection during reconciliation.
993
    /// (2 accesses — reconciliation only)
994
    pub node_data_fingerprint: NodeDataFingerprint,
995
    /// A hash of this node's data and all of its descendants. Used for
996
    /// fast reconciliation.
997
    /// (9 accesses — all in cache.rs reconciliation)
998
    pub subtree_hash: SubtreeHash,
999
    /// Dirty flags to track what needs recalculation.
    /// (7 accesses — reconciliation setup)
    pub dirty_flag: DirtyFlag,
    /// Unresolved box model properties (raw CSS values).
    /// These are resolved lazily during layout when containing block is known.
    /// (1 access — initial resolution only)
    pub unresolved_box_props: crate::solver3::geometry::UnresolvedBoxProps,
    /// If this node is an IFC root, stores the IFC ID.
    /// Used to identify which IFC this node's `inline_layout_result` belongs to.
    /// (1 access — IFC creation only)
    pub ifc_id: Option<IfcId>,
}
/// Pre-computed CSS properties needed during layout.
///
/// This struct stores resolved CSS values that are frequently accessed during
/// layout calculations. By computing these once during layout tree construction,
/// we avoid O(n * m) style lookups where n = nodes and m = layout passes.
///
/// All values are resolved to their final form (no 'inherit', 'initial', etc.)
#[derive(Debug, Clone, Default)]
pub struct ComputedLayoutStyle {
    /// CSS `display` property
    pub display: LayoutDisplay,
    /// CSS `position` property
    pub position: LayoutPosition,
    /// CSS `float` property
    pub float: LayoutFloat,
    /// CSS `overflow-x` property
    pub overflow_x: LayoutOverflow,
    /// CSS `overflow-y` property
    pub overflow_y: LayoutOverflow,
    /// CSS `writing-mode` property
    pub writing_mode: azul_css::props::layout::LayoutWritingMode,
    /// CSS `direction` property (ltr/rtl)
    pub direction: azul_css::props::style::StyleDirection,
    /// CSS `text-orientation` property (for vertical writing modes)
    pub text_orientation: azul_css::props::style::effects::StyleTextOrientation,
    /// CSS `width` property (None = auto)
    pub width: Option<azul_css::props::layout::LayoutWidth>,
    /// CSS `height` property (None = auto)
    pub height: Option<azul_css::props::layout::LayoutHeight>,
    /// CSS `min-width` property
    pub min_width: Option<azul_css::props::layout::LayoutMinWidth>,
    /// CSS `min-height` property
    pub min_height: Option<azul_css::props::layout::LayoutMinHeight>,
    /// CSS `max-width` property
    pub max_width: Option<azul_css::props::layout::LayoutMaxWidth>,
    /// CSS `max-height` property
    pub max_height: Option<azul_css::props::layout::LayoutMaxHeight>,
    /// CSS `text-align` property
    pub text_align: StyleTextAlign,
}
// Note: LayoutNode methods that cross hot/warm/cold boundaries have been
// moved to LayoutTree methods (resolve_box_props, get_content_size).
/// CSS pseudo-elements that can be generated
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PseudoElement {
    /// `::marker` pseudo-element for list items
    Marker,
    /// `::before` pseudo-element
    Before,
    /// `::after` pseudo-element
    After,
}
// +spec:display-property:b7f4bf - anonymous inline/block boxes are both called "anonymous boxes"
/// Types of anonymous boxes that can be generated
// +spec:display-property:ae4f16 - anonymous boxes are treated as descendants alongside
// pseudo-elements
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnonymousBoxType {
    /// Anonymous block box wrapping inline content
    InlineWrapper,
    /// O3-render: the SECOND (or later) part of a structural-split preview —
    /// a box with a real `dom_node_id` (the split node, via the
    /// `dom_to_layout` multimap) that displays a byte-slice of its content.
    /// Exists only between recording a split and the app's re-render.
    SplitPreviewPart,
    /// Anonymous box for a list item marker (bullet or number)
    /// DEPRECATED: Use `PseudoElement::Marker` instead
    ListItemMarker,
    /// Anonymous table wrapper
    TableWrapper,
    /// Anonymous table row group (tbody)
    TableRowGroup,
    /// Anonymous table row
    TableRow,
    /// Anonymous table cell
    TableCell,
}
// =============================================================================
// SoA (struct-of-arrays) layout node split for cache performance
// =============================================================================
/// Hot layout node fields — accessed on every node in every layout pass.
///
/// Stored in a separate `Vec` for cache locality. At ~100 bytes per node,
/// 1000 nodes fit in ~100 KB (L2 cache), vs ~550 KB with the monolithic struct.
// ~100B per-node hot type stored/moved in Vecs across every layout pass; kept
// non-Copy on purpose so it isn't silently bulk-copied (Copy would mask the
// cost and churn the many `.clone()` call sites).
#[allow(missing_copy_implementations)]
#[derive(Debug, Clone)]
pub struct LayoutNodeHot {
    /// The resolved box model properties (margin, border, padding)
    /// Stored in packed i16×10 encoding to reduce cache footprint.
    /// Use `box_props.unpack()` to get f32 `ResolvedBoxProps` for computation.
    pub box_props: crate::solver3::geometry::PackedBoxProps,
    /// Reference back to the original DOM node (None for anonymous boxes)
    pub dom_node_id: Option<NodeId>,
    /// The size used during the last layout pass.
    pub used_size: Option<LogicalSize>,
    /// The formatting context this node establishes or participates in.
    pub formatting_context: FormattingContext,
    /// Parent index (None for root)
    pub parent: Option<usize>,
}
/// Warm layout node fields — accessed frequently but not on every node.
///
/// Stored in a separate `Vec`. These fields are accessed during specific
/// layout phases (sizing, IFC, table alignment) but not during the main
/// constraint-solving loop.
#[derive(Debug, Clone, Default)]
pub struct LayoutNodeWarm {
    /// Cached intrinsic sizes (min-content, max-content, etc.)
    pub intrinsic_sizes: Option<IntrinsicSizes>,
    /// The baseline of this box, measured from its content-box top edge.
    pub baseline: Option<f32>,
    /// Cached inline layout result with the constraints used to compute it.
    /// BOXED (rare-data split, 2026-08-11): only IFC roots populate this,
    /// but the 296-B inline Option was paid by EVERY node. 8 B here now.
    pub inline_layout_result: Option<Box<CachedInlineLayout>>,
    /// Cached result of `collect_and_measure_inline_content` for this IFC
    /// root, valid while the subtree's fingerprints are unchanged.
    ///
    /// Collection resolves the FULL cascade (`get_style_properties`) for
    /// every text run and inline span. That ran on every layout — even one
    /// that went on to reuse the cached line layout — and measured 2 ms per
    /// IFC, 32 ms per pagination: the single largest remaining cost after
    /// the line-breaker and font-signature fixes.
    /// BOXED (rare-data split): IFC roots only; was 88 B inline per node.
    pub inline_content_cache: Option<Box<CachedInlineContent>>,
    /// Cached scrollbar information
    pub scrollbar_info: Option<ScrollbarRequirements>,
    /// The position relative to parent's content box.
    pub relative_position: Option<LogicalPosition>,
    /// The actual content size for scrollable containers.
    pub overflow_content_size: Option<LogicalSize>,
    /// Cache for Taffy layout computations.
    pub taffy_cache: TaffyCache,
    /// Pure min/max-content measure results — see the facade field's doc.
    pub measured_content_sizes: (Option<LayoutOutput>, Option<LayoutOutput>),
    /// Pre-computed CSS properties needed during layout.
    pub computed_style: ComputedLayoutStyle,
    /// Pseudo-element type if this node is a pseudo-element
    pub pseudo_element: Option<PseudoElement>,
    /// Escaped top margin (CSS 2.1 margin collapsing)
    pub escaped_top_margin: Option<f32>,
    /// Escaped bottom margin (CSS 2.1 margin collapsing)
    pub escaped_bottom_margin: Option<f32>,
    /// Parent's formatting context
    pub parent_formatting_context: Option<FormattingContext>,
    /// IFC membership for text nodes
    pub ifc_membership: Option<IfcMembership>,
    /// Containing block index for clip exemption
    pub containing_block_index: Option<usize>,
}
/// Cold layout node fields — construction / reconciliation / debugging only.
///
/// Stored in a separate `Vec`. These fields are rarely accessed during layout;
/// mostly used during tree construction, reconciliation, and dirty tracking.
#[derive(Debug, Clone, Default)]
pub struct LayoutNodeCold {
    /// Type of anonymous box (if applicable)
    pub anonymous_type: Option<AnonymousBoxType>,
    /// O3-render: when this node is one PART of a structural-split PREVIEW,
    /// the flat byte range of the source node's inline content this part
    /// displays (`u32::MAX` end = to the end). The IFC build slices its
    /// collected content by this range. `None` = the node shows everything
    /// (the universal case outside previews).
    pub preview_byte_range: Option<(u32, u32)>,
    /// Multi-field fingerprint for granular change detection.
    pub node_data_fingerprint: NodeDataFingerprint,
    /// Hash of this node's data + all descendants.
    pub subtree_hash: SubtreeHash,
    /// Dirty flags for recalculation tracking.
    pub dirty_flag: DirtyFlag,
    /// Unresolved box model properties (raw CSS values).
    pub unresolved_box_props: crate::solver3::geometry::UnresolvedBoxProps,
    /// IFC ID if this node is an IFC root.
    pub ifc_id: Option<IfcId>,
}
impl LayoutNode {
    /// Split this full layout node into hot/warm/cold components.
    /// Used during `LayoutTreeBuilder::build()` to create the `SoA` layout.
    #[must_use]
283368
    pub fn split(self) -> (LayoutNodeHot, LayoutNodeWarm, LayoutNodeCold) {
283368
        (
283368
            LayoutNodeHot {
283368
                box_props: crate::solver3::geometry::PackedBoxProps::pack(&self.box_props),
283368
                dom_node_id: self.dom_node_id,
283368
                used_size: self.used_size,
283368
                formatting_context: self.formatting_context,
283368
                parent: self.parent,
283368
            },
283368
            LayoutNodeWarm {
283368
                intrinsic_sizes: self.intrinsic_sizes,
283368
                baseline: self.baseline,
283368
                inline_layout_result: self.inline_layout_result,
283368
                inline_content_cache: self.inline_content_cache,
283368
                scrollbar_info: self.scrollbar_info,
283368
                relative_position: self.relative_position,
283368
                overflow_content_size: self.overflow_content_size,
283368
                taffy_cache: self.taffy_cache,
283368
                measured_content_sizes: self.measured_content_sizes,
283368
                computed_style: self.computed_style,
283368
                pseudo_element: self.pseudo_element,
283368
                escaped_top_margin: self.escaped_top_margin,
283368
                escaped_bottom_margin: self.escaped_bottom_margin,
283368
                parent_formatting_context: self.parent_formatting_context,
283368
                ifc_membership: self.ifc_membership,
283368
                containing_block_index: self.containing_block_index,
283368
            },
283368
            LayoutNodeCold {
283368
                anonymous_type: self.anonymous_type,
283368
                preview_byte_range: self.preview_byte_range,
283368
                node_data_fingerprint: self.node_data_fingerprint,
283368
                subtree_hash: self.subtree_hash,
283368
                dirty_flag: self.dirty_flag,
283368
                unresolved_box_props: self.unresolved_box_props,
283368
                ifc_id: self.ifc_id,
283368
            },
283368
        )
283368
    }
}
/// How far [`LayoutTree::get_ifc_root_layout_index`] walks up looking for the
/// box that owns an inline descendant's layout. Inline nesting is shallow in
/// practice; the bound only stops a malformed tree from spinning.
const IFC_ANCESTOR_WALK_LIMIT: usize = 64;
/// A position in the LAYOUT tree — distinct from a DOM [`NodeId`] BY TYPE.
///
/// The layout tree interleaves anonymous boxes and splits during
/// construction, so layout indices and DOM indices diverge for any real DOM.
/// Conflating them (`node_id.index()` used as a layout index) froze CPU-path
/// scrolling once (`build_scroll_offset_map`) and is exactly the mistake this
/// newtype turns into a compile error: the ONLY sanctioned ways to obtain a
/// `LayoutNodeId` from a DOM node are [`LayoutTree::dom_to_layout`] and the
/// scroll-id tables. Solver-interior code that produces indices locally wraps
/// them with [`LayoutNodeId::new`] — an explicit, greppable assertion that
/// the value really is a layout index.
///
/// The raw `SoA` vectors (`nodes`, `warm`, `cold`, `children_arena`) stay
/// `usize`-indexed for interior arithmetic; the typed boundary is the
/// accessor surface (`get`/`warm`/`cold`/`get_content_size`/...), which is
/// what map-derived consumer code calls.
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LayoutNodeId(pub usize);
impl LayoutNodeId {
    #[inline]
    #[must_use]
76793707
    pub const fn new(index: usize) -> Self {
76793707
        Self(index)
76793707
    }
    /// The raw vector index. Greppable by design: every `.index()` is a
    /// deliberate exit from the typed space.
    #[inline]
    #[must_use]
77552235
    pub const fn index(self) -> usize {
77552235
        self.0
77552235
    }
}
impl core::fmt::Display for LayoutNodeId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "L{}", self.0)
    }
}
/// The complete layout tree structure.
///
/// Uses a struct-of-arrays (`SoA`) layout for cache performance:
/// - `nodes` (hot): accessed on every node in every layout pass
/// - `warm`: accessed during specific layout phases
/// - `cold`: construction / reconciliation only
#[derive(Debug, Clone)]
pub struct LayoutTree {
    /// Hot layout data — box props, parent, `used_size`, formatting context
    pub nodes: Vec<LayoutNodeHot>,
    /// Warm layout data — intrinsic sizes, baseline, inline layout, etc.
    pub warm: Vec<LayoutNodeWarm>,
    /// Cold layout data — dirty flags, fingerprints, reconciliation data
    pub cold: Vec<LayoutNodeCold>,
    /// Root node index
    pub root: usize,
    /// Mapping from DOM node IDs to layout node indices
    // BTreeMap (not HashMap): std HashMap's RandomState hasher needs an RNG seed
    // that isn't available in the remill-lifted wasm (no getrandom), so inserts
    // silently no-op there — dom_to_layout came back empty (node mapping lost,
    // get_node_size/position returned None → 0-rects). BTreeMap is deterministic,
    // matches the rest of azul-core, and lifts reliably (M12.7).
    pub dom_to_layout: BTreeMap<NodeId, Vec<LayoutNodeId>>,
    /// Flat arena holding all children indices contiguously.
    pub children_arena: Vec<usize>,
    /// Per-node (start, len) into `children_arena`. Indexed by node index.
    pub children_offsets: Vec<(u32, u32)>,
    /// Per-node bit: this node or any descendant establishes a shrink-to-fit
    /// (STF) context whose sizing algorithm reads children's intrinsic sizes
    /// (flex/grid/table/inline-block containers, floats, or abspos elements).
    ///
    /// If `subtree_needs_intrinsic[i]` is false AND no ancestor of `i` is STF
    /// either, the intrinsic sizing pass can skip the entire subtree — nothing
    /// will ever read those values. This is the static-DOM optimization from
    /// §58 Win #3 (the "safely re-enabled Fix C").
    ///
    /// Computed once at tree build time in `generate_layout_tree`. An empty
    /// vec means "assume every subtree needs intrinsics" (safe fallback for
    /// code paths that construct `LayoutTree` without going through the
    /// builder — currently none, but preserves the invariant for tests).
    pub subtree_needs_intrinsic: Vec<bool>,
}
/// Approximate per-field heap-byte breakdown of a [`LayoutTree`].
#[derive(Copy, Debug, Clone, Default)]
pub struct LayoutTreeMemoryReport {
    pub node_count: usize,
    pub hot_bytes: usize,
    pub warm_bytes: usize,
    pub warm_inline_layout_bytes: usize,
    /// Shaped clusters retained across the whole tree. A cluster is one
    /// grapheme, so on Latin text this is roughly the CHARACTER COUNT of
    /// everything laid out — the number that explains `warm.inline`.
    pub shaped_cluster_count: usize,
    /// Shaped glyphs retained. Differs from the cluster count only for
    /// ligatures and combining marks.
    pub shaped_glyph_count: usize,
    /// Bytes of per-cluster heap `String` (each cluster owns a copy of its
    /// own text). Called out separately because it is pure duplication of
    /// text the DOM already holds.
    pub shaped_cluster_text_bytes: usize,
    /// Distinct `Arc<StyleProperties>` allocations the retained glyphs point
    /// at, by pointer identity.
    ///
    /// A document has a handful of distinct text styles (body, headings,
    /// code), so a healthy number here is single digits no matter how many
    /// glyphs there are. A count that tracks the GLYPH count means the
    /// sharing predicate has silently stopped sharing — Stylo hit exactly
    /// this, ending up with 109k `ComputedValues` where 2,200 were expected
    /// because one pseudo-element rule defeated the predicate. At 248 B per
    /// `StyleProperties` that failure is invisible and expensive.
    pub distinct_glyph_style_arcs: usize,
    /// Paint-run cache (`CachedInlineLayout::glyph_runs`): heap bytes of the
    /// retained `Vec<SimpleGlyphRun>` lists, each distinct Arc counted once
    /// (`GlyphSwap` reuse shares them). This is the store-time derivation that
    /// makes every paint a lookup — the retained cost of that trade.
    pub glyph_run_bytes: usize,
    /// Distinct `SimpleGlyphRun`s behind `glyph_run_bytes`.
    pub glyph_run_count: usize,
    /// Total `GlyphInstance`s retained across those runs (the 20 B/each bulk).
    pub glyph_instance_count: usize,
    pub warm_taffy_cache_bytes: usize,
    pub cold_bytes: usize,
    pub dom_to_layout_bytes: usize,
    pub children_arena_bytes: usize,
    pub children_offsets_bytes: usize,
}
impl LayoutTreeMemoryReport {
    #[must_use]
6
    pub const fn total_bytes(&self) -> usize {
6
        self.hot_bytes
6
            + self.warm_bytes
6
            + self.warm_inline_layout_bytes
6
            + self.glyph_run_bytes
6
            + self.warm_taffy_cache_bytes
6
            + self.cold_bytes
6
            + self.dom_to_layout_bytes
6
            + self.children_arena_bytes
6
            + self.children_offsets_bytes
6
    }
}
/// Iterator over a node's ancestor chain — see [`LayoutTree::ancestor_chain`].
///
/// Yields layout indices child-first (nearest ancestor first).
#[derive(Debug)]
pub struct AncestorChain<'a> {
    nodes: &'a [LayoutNodeHot],
    cursor: Option<usize>,
    budget: usize,
}
impl Iterator for AncestorChain<'_> {
    type Item = LayoutNodeId;
23592
    fn next(&mut self) -> Option<Self::Item> {
23592
        if self.budget == 0 {
123
            return None;
23469
        }
23469
        let idx = self.cursor?;
17489
        self.budget -= 1;
17489
        self.cursor = self.nodes.get(idx).and_then(|n| n.parent);
17489
        Some(LayoutNodeId::new(idx))
23592
    }
}
impl LayoutTree {
    /// Approximate heap bytes retained by this `LayoutTree`.
    #[must_use]
11
    pub fn memory_report(&self) -> LayoutTreeMemoryReport {
11
        let mut report = LayoutTreeMemoryReport {
11
            node_count: self.nodes.len(),
11
            hot_bytes: self.nodes.capacity() * size_of::<LayoutNodeHot>(),
11
            warm_bytes: self.warm.capacity() * size_of::<LayoutNodeWarm>(),
11
            cold_bytes: self.cold.capacity() * size_of::<LayoutNodeCold>(),
11
            children_arena_bytes: self.children_arena.capacity() * size_of::<usize>(),
11
            children_offsets_bytes: self.children_offsets.capacity() * size_of::<(u32, u32)>(),
11
            dom_to_layout_bytes: 0,
11
            warm_inline_layout_bytes: 0,
11
            shaped_cluster_count: 0,
11
            shaped_glyph_count: 0,
11
            shaped_cluster_text_bytes: 0,
11
            distinct_glyph_style_arcs: 0,
11
            glyph_run_bytes: 0,
11
            glyph_run_count: 0,
11
            glyph_instance_count: 0,
11
            warm_taffy_cache_bytes: 0,
11
        };
        // HashMap<NodeId, Vec<usize>> — approximate: (key + Vec-header) per entry
        // plus heap for each inner Vec.
11
        let entries = self.dom_to_layout.len();
11
        report.dom_to_layout_bytes = entries * (size_of::<NodeId>() + size_of::<Vec<usize>>());
11
        for v in self.dom_to_layout.values() {
9
            report.dom_to_layout_bytes += v.capacity() * size_of::<usize>();
9
        }
        // Inline layout data lives behind Arc — count Arc heap-shares once
        // per node that has a cached layout. Counted conservatively.
11
        let mut text_arcs: alloc::collections::BTreeSet<usize> =
11
            alloc::collections::BTreeSet::new();
11
        let mut style_arcs: alloc::collections::BTreeSet<usize> =
11
            alloc::collections::BTreeSet::new();
11
        let mut run_arcs: alloc::collections::BTreeSet<usize> = alloc::collections::BTreeSet::new();
32
        for w in &self.warm {
21
            if let Some(cached) = &w.inline_layout_result {
                // The Box allocation itself — CachedInlineLayout is boxed off
                // LayoutNodeWarm, so `warm_bytes` above does NOT include it.
                // This also covers the INLINE `Option<UnifiedConstraints>`.
7
                report.warm_inline_layout_bytes += size_of::<CachedInlineLayout>();
                // Heap Vecs hanging off the inline constraints.
7
                if let Some(c) = &cached.constraints {
                    report.warm_inline_layout_bytes += c.shape_boundaries.capacity()
                        * size_of::<crate::text3::cache::ShapeBoundary>()
                        + c.shape_exclusions.capacity()
                            * size_of::<crate::text3::cache::ShapeBoundary>();
7
                }
                // Cached line breaks (edit fast-path).
7
                if let Some(lb) = &cached.line_breaks {
                    report.warm_inline_layout_bytes += lb.line_ranges.capacity()
                        * size_of::<(usize, usize)>()
                        + lb.line_widths.capacity() * size_of::<f32>();
7
                }
                // The payload Arc: when it is a TextPayload wrapper, that
                // allocation holds two Arc CLONES of buffers counted
                // elsewhere — only its own header is new bytes. When it is
                // the layout Arc itself (flag-off), nothing new to count.
7
                if cached.payload.downcast_ref::<TextPayload>().is_some() {
7
                    report.warm_inline_layout_bytes += size_of::<TextPayload>();
7
                }
                // Paint-run cache — its own report line (see the field doc).
                // Distinct Arcs only: GlyphSwap reuse clones the Arc.
7
                if run_arcs.insert(Arc::as_ptr(&cached.glyph_runs).cast::<u8>() as usize) {
6
                    report.glyph_run_bytes += cached.glyph_runs.capacity()
6
                        * size_of::<crate::text3::glyphs::CompactGlyphRun>();
6
                    for run in cached.glyph_runs.iter() {
4
                        report.glyph_run_bytes += run.glyphs.retained_bytes()
4
                            + run.background_content.capacity()
4
                                * size_of::<azul_css::props::style::StyleBackgroundContent>();
4
                        report.glyph_run_count += 1;
4
                        report.glyph_instance_count += run.glyphs.len();
4
                    }
1
                }
                // Arc<UnifiedLayout> — count the UnifiedLayout header + its items.
7
                report.warm_inline_layout_bytes += size_of::<UnifiedLayout>();
7
                report.warm_inline_layout_bytes += cached.layout.items.capacity()
7
                    * size_of::<crate::text3::cache::PositionedItem>();
7
                report.warm_inline_layout_bytes +=
7
                    cached.item_metrics.capacity() * size_of::<InlineItemMetrics>();
                // (d1): the retained dense view, when AZ_DENSE_TEXT keeps it.
                // Counted per-field so the sparse-vs-dense split is honest
                // during the reader migration (both alive = the transitional
                // cost; the sparse side retires at the end of (d)).
7
                if let Some(d) = &cached.dense {
                    use crate::text3::dense as dn;
7
                    report.warm_inline_layout_bytes += size_of::<dn::DenseText>()
7
                        + d.clusters.capacity() * size_of::<dn::ClusterCompact>()
7
                        + d.runs.capacity() * size_of::<dn::DenseRun>()
7
                        + d.lines.capacity() * size_of::<dn::LineRecord>()
7
                        + d.details.capacity() * size_of::<dn::ClusterDetail>()
7
                        + d.detail_glyphs.capacity() * size_of::<dn::DetailGlyph>();
                }
                // Glyphs and per-cluster text.
                //
                // ONLY the SPILLED glyphs are counted here. `glyphs` is a
                // `SmallVec<[ShapedGlyph; 1]>`, so its first element lives
                // INSIDE the ShapedCluster — which is already counted as part
                // of `PositionedItem` above. Multiplying `capacity()` (which
                // includes the inline slot) by `size_of::<ShapedGlyph>()`
                // double-counted one 96-byte glyph for EVERY cluster: on a
                // 31k-cluster document that inflated the report by ~3 MB, and
                // a memory report that over-reports sends the optimisation
                // work at the wrong target.
7
                for item in &cached.layout.items {
2
                    if let crate::text3::cache::ShapedItem::Cluster(c) = &item.item {
                        let spilled = c.glyphs.capacity().saturating_sub(1);
                        report.warm_inline_layout_bytes +=
                            spilled * size_of::<crate::text3::cache::ShapedGlyph>();
                        // 3c: per-cluster text is a SHARED Arc slice now —
                        // attribute each distinct source Arc's buffer ONCE.
                        if text_arcs.insert(Arc::as_ptr(&c.source_text).cast::<u8>() as usize) {
                            report.warm_inline_layout_bytes += c.source_text.len();
                            report.shaped_cluster_text_bytes += c.source_text.len();
                        }
                        report.shaped_cluster_count += 1;
                        report.shaped_glyph_count += c.glyphs.len();
                        style_arcs.insert(Arc::as_ptr(&c.style) as usize);
2
                    }
                }
14
            }
            // Taffy cache — each slot is an Option, ~50 B empty
21
            report.warm_taffy_cache_bytes += size_of::<TaffyCache>();
        }
11
        report.distinct_glyph_style_arcs = style_arcs.len();
11
        report
11
    }
    /// Returns the children of node `index` as a contiguous slice from the arena.
    #[inline]
    #[must_use]
4946508
    pub fn children(&self, index: usize) -> &[usize] {
4946508
        if let Some(&(start, len)) = self.children_offsets.get(index) {
4946501
            &self.children_arena[(start as usize)..((start as usize) + (len as usize))]
        } else {
7
            &[]
        }
4946508
    }
    /// Get hot layout data for a node (`box_props`, `dom_node_id`, `used_size`, etc.)
    #[inline]
    #[must_use]
55267107
    pub fn get(&self, index: LayoutNodeId) -> Option<&LayoutNodeHot> {
55267107
        self.nodes.get(index.index())
55267107
    }
    /// The left/top step from a node's BORDER box (what `calculated_positions`
    /// and `used_size` describe) to its CONTENT box (what inline layout, and
    /// therefore every caret/selection/hit-test coordinate, is measured in).
    ///
    /// THE single source of `padding.left + border.left` / `padding.top +
    /// border.top` for the pointer pipeline. The display-list builder already
    /// went through `BorderBoxRect::to_content_box` for painting; the two
    /// hit-test producers each open-coded (or, on the `WebRender` side, simply
    /// omitted) this term, which is exactly how they came to disagree.
    ///
    /// An unknown index yields [`ContentInset::ZERO`], matching the
    /// "unpadded, unbordered" default rather than skewing the point.
    #[inline]
    #[must_use]
8091
    pub fn content_inset(&self, index: LayoutNodeId) -> ContentInset {
8091
        self.get(index).map_or(ContentInset::ZERO, |node| {
8091
            let bp = node.box_props.unpack();
8091
            ContentInset::new(
8091
                bp.padding.left + bp.border.left,
8091
                bp.padding.top + bp.border.top,
            )
8091
        })
8091
    }
    /// THE ancestor walk: `index` (only when `inclusivity` says so) followed by
    /// every parent up to the root.
    ///
    /// Five separate hand-rolled versions of this loop used to exist, and each
    /// encoded "does this include the node itself?" in its starting value —
    /// `let mut cursor = Some(idx)` vs `let mut cur = node.parent`. That is
    /// invisible at the call site, which is how `accumulated_scroll_for_node`
    /// (self-inclusive) and [`node_rect_to_screen`] (ancestors-only) came to
    /// look like the same helper under two names, and how the auto-scroll
    /// timer ended up unable to target the caret's own scroll box. Taking
    /// [`Inclusivity`] as an argument forces every call site to say which it
    /// means.
    ///
    /// [`node_rect_to_screen`]: crate::headless::node_rect_to_screen
    ///
    /// The walk is bounded by `nodes.len()`: no acyclic path can be longer, so
    /// a malformed (cyclic) `parent` chain terminates instead of spinning,
    /// while a legitimately deep tree is never truncated.
    #[inline]
    #[must_use]
7271
    pub fn ancestor_chain(
7271
        &self,
7271
        index: LayoutNodeId,
7271
        inclusivity: Inclusivity,
7271
    ) -> AncestorChain<'_> {
7271
        let start = if inclusivity.includes_self() {
4167
            Some(index.index())
        } else {
3104
            self.nodes.get(index.index()).and_then(|n| n.parent)
        };
7271
        AncestorChain {
7271
            nodes: &self.nodes,
7271
            cursor: start,
7271
            budget: self.nodes.len(),
7271
        }
7271
    }
    /// Get mutable hot layout data for a node.
    #[inline]
2143505
    pub fn get_mut(&mut self, index: LayoutNodeId) -> Option<&mut LayoutNodeHot> {
2143505
        self.nodes.get_mut(index.index())
2143505
    }
    /// Get warm layout data for a node (`intrinsic_sizes`, baseline, `inline_layout`, etc.)
    #[inline]
    #[must_use]
14599523
    pub fn warm(&self, index: LayoutNodeId) -> Option<&LayoutNodeWarm> {
14599523
        self.warm.get(index.index())
14599523
    }
    /// Get mutable warm layout data for a node.
    #[inline]
2384472
    pub fn warm_mut(&mut self, index: LayoutNodeId) -> Option<&mut LayoutNodeWarm> {
2384472
        self.warm.get_mut(index.index())
2384472
    }
    /// Get cold layout data for a node (`dirty_flag`, `subtree_hash`, fingerprint, etc.)
    #[inline]
    #[must_use]
999037
    pub fn cold(&self, index: LayoutNodeId) -> Option<&LayoutNodeCold> {
999037
        self.cold.get(index.index())
999037
    }
    /// Get mutable cold layout data for a node.
    #[inline]
75806
    pub fn cold_mut(&mut self, index: LayoutNodeId) -> Option<&mut LayoutNodeCold> {
75806
        self.cold.get_mut(index.index())
75806
    }
1
    fn root_node(&self) -> &LayoutNodeHot {
1
        &self.nodes[self.root]
1
    }
    /// Reconstruct a full `LayoutNode` from the split hot/warm/cold arrays.
    ///
    /// Used when passing node data to `LayoutTreeBuilder::clone_node_from_old()`.
    #[must_use]
50633
    pub fn get_full_node(&self, index: usize) -> Option<LayoutNode> {
50633
        let hot = self.nodes.get(index)?;
50631
        let warm = self.warm.get(index).cloned().unwrap_or_default();
50631
        let cold = self.cold.get(index).cloned().unwrap_or_default();
50631
        let children = self.children(index).to_vec();
50631
        Some(LayoutNode {
50631
            box_props: hot.box_props.unpack(),
50631
            dom_node_id: hot.dom_node_id,
50631
            children,
50631
            used_size: hot.used_size,
50631
            formatting_context: hot.formatting_context,
50631
            parent: hot.parent,
50631
            intrinsic_sizes: warm.intrinsic_sizes,
50631
            baseline: warm.baseline,
50631
            inline_layout_result: warm.inline_layout_result,
50631
            inline_content_cache: warm.inline_content_cache,
50631
            scrollbar_info: warm.scrollbar_info,
50631
            relative_position: warm.relative_position,
50631
            overflow_content_size: warm.overflow_content_size,
50631
            taffy_cache: warm.taffy_cache,
50631
            measured_content_sizes: warm.measured_content_sizes,
50631
            computed_style: warm.computed_style,
50631
            pseudo_element: warm.pseudo_element,
50631
            escaped_top_margin: warm.escaped_top_margin,
50631
            escaped_bottom_margin: warm.escaped_bottom_margin,
50631
            parent_formatting_context: warm.parent_formatting_context,
50631
            ifc_membership: warm.ifc_membership,
50631
            containing_block_index: warm.containing_block_index,
50631
            anonymous_type: cold.anonymous_type,
50631
            preview_byte_range: cold.preview_byte_range,
50631
            node_data_fingerprint: cold.node_data_fingerprint,
50631
            subtree_hash: cold.subtree_hash,
50631
            dirty_flag: cold.dirty_flag,
50631
            unresolved_box_props: cold.unresolved_box_props,
50631
            ifc_id: cold.ifc_id,
50631
        })
50633
    }
    /// Re-resolve box properties for a node with the actual containing block size.
50578
    pub(crate) fn resolve_box_props(
50578
        &mut self,
50578
        node_index: usize,
50578
        containing_block: LogicalSize,
50578
        viewport_size: LogicalSize,
50578
        element_font_size: f32,
50578
        root_font_size: f32,
50578
    ) {
50578
        let params = crate::solver3::geometry::ResolutionParams {
50578
            containing_block,
50578
            viewport_size,
50578
            element_font_size,
50578
            root_font_size,
50578
        };
50578
        if let (Some(hot), Some(cold)) = (self.nodes.get_mut(node_index), self.cold.get(node_index))
50576
        {
50576
            hot.box_props = crate::solver3::geometry::PackedBoxProps::pack(
50576
                &cold.unresolved_box_props.resolve(&params),
50576
            );
50576
        }
50578
    }
    /// Marks a node and its ancestors as dirty with the given flag.
12
    pub fn mark_dirty(&mut self, start_index: usize, flag: DirtyFlag) {
12
        if flag == DirtyFlag::None {
1
            return;
11
        }
11
        let mut current_index = Some(start_index);
30
        while let Some(index) = current_index {
25
            let Some(cold) = self.cold.get_mut(index) else {
2
                break;
            };
23
            if cold.dirty_flag >= flag {
4
                break;
19
            }
19
            cold.dirty_flag = flag;
19
            current_index = self.nodes.get(index).and_then(|n| n.parent);
        }
12
    }
    /// Marks a node and its entire subtree of descendants with the given dirty flag.
6
    fn mark_subtree_dirty(&mut self, start_index: usize, flag: DirtyFlag) {
6
        if flag == DirtyFlag::None {
1
            return;
5
        }
5
        let mut stack = vec![start_index];
21
        while let Some(index) = stack.pop() {
16
            let children = self.children(index).to_vec();
16
            if let Some(cold) = self.cold.get_mut(index) {
15
                if cold.dirty_flag < flag {
11
                    cold.dirty_flag = flag;
11
                }
15
                stack.extend_from_slice(&children);
1
            }
        }
6
    }
    /// Resets the dirty flags of all nodes in the tree to `None` after layout is complete.
2
    fn clear_all_dirty_flags(&mut self) {
6
        for cold in &mut self.cold {
4
            cold.dirty_flag = DirtyFlag::None;
4
        }
2
    }
    /// Get inline layout for a node, navigating through IFC membership if needed.
    /// (d4) The dense view for a node, resolved through the SAME IFC
    /// membership walk as [`Self::get_inline_layout_for_node`]. `None`
    /// when no dense view is retained (flag off) or the node has no IFC.
    #[must_use]
1084
    pub fn get_dense_for_node(
1084
        &self,
1084
        layout_index: usize,
1084
    ) -> Option<&Arc<crate::text3::dense::DenseText>> {
1084
        let warm = self.warm.get(layout_index)?;
1084
        if let Some(cached) = &warm.inline_layout_result {
931
            return cached.dense.as_ref();
153
        }
153
        if let Some(ifc_membership) = &warm.ifc_membership {
153
            let ifc_root_warm = self.warm.get(ifc_membership.ifc_root_layout_index)?;
153
            if let Some(cached) = &ifc_root_warm.inline_layout_result {
153
                return cached.dense.as_ref();
            }
        }
        None
1084
    }
    /// (d6h) The stored inline layout for a node, MATERIALIZED when it
    /// is the retirement sentinel: dense expands (exact by the d6h
    /// expansion gate) into a transient copy for geometry readers —
    /// the caret and selection painters. Flag-off / verify / non-pure
    /// layouts return the stored Arc untouched.
    #[must_use]
811420
    pub fn materialized_inline_layout_for_node(
811420
        &self,
811420
        layout_index: usize,
811420
    ) -> Option<Arc<UnifiedLayout>> {
811420
        let warm = self.warm(LayoutNodeId::new(layout_index))?;
811420
        let cached = warm.inline_layout_result.as_ref()?;
341397
        if cached.layout.items.is_empty() {
339795
            if let Some(d) = cached.dense.as_deref() {
339795
                if !d.clusters.is_empty() {
339401
                    return Some(Arc::new(UnifiedLayout {
339401
                        items: d.to_unified_items(),
339401
                        overflow: cached.overflow.clone(),
339401
                    }));
394
                }
            }
1602
        }
1996
        Some(cached.layout.clone())
811420
    }
    #[must_use]
538
    pub fn get_inline_layout_for_node(&self, layout_index: usize) -> Option<&Arc<UnifiedLayout>> {
538
        let warm = self.warm.get(layout_index)?;
        // First, check if this node has its own inline_layout_result (it's an IFC root)
533
        if let Some(cached) = &warm.inline_layout_result {
232
            return Some(cached.get_layout());
301
        }
        // For text nodes, check if they have ifc_membership pointing to the IFC root
301
        if let Some(ifc_membership) = &warm.ifc_membership {
289
            let ifc_root_warm = self.warm.get(ifc_membership.ifc_root_layout_index)?;
288
            if let Some(cached) = &ifc_root_warm.inline_layout_result {
287
                return Some(cached.get_layout());
1
            }
12
        }
13
        None
538
    }
    /// Return the layout index of the IFC root that owns `layout_index`'s inline content.
    /// If the node IS an IFC root (has its own `inline_layout_result`) or has no
    /// `ifc_membership`, returns `layout_index` unchanged. Inline text nodes never get
    /// their own box position (it stays the `f32::MIN` sentinel) — their geometry lives
    /// in the IFC root's content box, so selection/inline painting must anchor to the
    /// IFC root's position, not the text node's. See `get_inline_layout_for_node`.
    #[must_use]
350137
    pub fn get_ifc_root_layout_index(&self, layout_index: usize) -> usize {
350137
        if let Some(warm) = self.warm.get(layout_index) {
350135
            if warm.inline_layout_result.is_none() {
11298
                if let Some(ifc_membership) = &warm.ifc_membership {
11217
                    return ifc_membership.ifc_root_layout_index;
81
                }
                // No membership recorded. `ifc_membership` is only ever
                // assigned to text nodes the IFC root's own walk collected
                // directly; `collect_inline_span_recursive` assigns none, so
                // anything under a `<span>` carries nothing and ownership used
                // to resolve to the text node ITSELF. That is why the caret in
                // `p > span > text` was never painted, and why keyboard focus
                // into any editable containing a span produced a session whose
                // caret never appeared.
                //
                // The nearest ancestor that OWNS inline layout is the IFC root
                // by definition, so walk up to it. Nodes outside any IFC have
                // no such ancestor and fall through to the identity below.
81
                let mut cursor = layout_index;
161
                for _ in 0..IFC_ANCESTOR_WALK_LIMIT {
161
                    let Some(parent) = self.nodes.get(cursor).and_then(|n| n.parent) else {
61
                        break;
                    };
100
                    match self.warm.get(parent) {
100
                        Some(w) if w.inline_layout_result.is_some() => return parent,
80
                        Some(_) => cursor = parent,
                        None => break,
                    }
                }
338837
            }
2
        }
338900
        layout_index
350137
    }
    /// Get the content size of a node (for scrollbar calculations).
    #[must_use]
1313689
    pub fn get_content_size(&self, index: LayoutNodeId) -> LogicalSize {
1313689
        let Some(warm) = self.warm.get(index.index()) else {
3
            return LogicalSize::default();
        };
1313686
        if let Some(content_size) = warm.overflow_content_size {
967409
            return content_size;
346277
        }
346277
        let Some(hot) = self.nodes.get(index.index()) else {
            return LogicalSize::default();
        };
346277
        let mut content_size = hot.used_size.unwrap_or_default();
346277
        if let Some(ref cached_layout) = warm.inline_layout_result {
35
            let text_layout = &cached_layout.layout;
35
            let mut max_x: f32 = 0.0;
35
            let mut max_y: f32 = 0.0;
35
            for positioned_item in &text_layout.items {
35
                let item_bounds = positioned_item.item.bounds();
35
                max_x = max_x.max(positioned_item.position.x + item_bounds.width);
35
                max_y = max_y.max(positioned_item.position.y + item_bounds.height);
35
            }
35
            content_size.width = content_size.width.max(max_x);
35
            content_size.height = content_size.height.max(max_y);
346242
        }
346277
        content_size
1313689
    }
}
/// Generate layout tree from styled DOM with proper anonymous box generation
/// # Errors
///
/// Returns a `LayoutError` if the layout tree cannot be built.
214
pub fn generate_layout_tree<T: ParsedFontTrait>(
214
    ctx: &mut LayoutContext<'_, T>,
214
) -> Result<LayoutTree> {
214
    let mut builder = LayoutTreeBuilder::new(ctx.viewport_size);
214
    let root_id = ctx
214
        .styled_dom
214
        .root
214
        .into_crate_internal()
214
        .unwrap_or(NodeId::ZERO);
214
    let root_index = builder.process_node(ctx.styled_dom, root_id, None, ctx.debug_messages)?;
214
    builder.apply_split_previews(ctx.content_overlay, ctx.styled_dom);
214
    let mut layout_tree = builder.build(root_index);
    // Pre-compute the STF (shrink-to-fit) subtree bitmap. This is static-DOM
    // information: whether a subtree establishes any shrink-to-fit context
    // depends only on the DOM structure + formatting context, both of which
    // are frozen from here until the next layout-tree rebuild. The intrinsic
    // sizing pass reads this to skip subtrees whose intrinsics are never
    // consumed (§58 Win #3).
214
    layout_tree.subtree_needs_intrinsic =
214
        compute_subtree_needs_intrinsic(ctx.styled_dom, &layout_tree);
214
    debug_log!(
136
        ctx,
136
        "Generated layout tree with {} nodes (incl. anonymous)",
136
        layout_tree.nodes.len()
    );
214
    Ok(layout_tree)
214
}
/// Returns true if `(dom_node_id, fc)` establishes a formatting context whose
/// sizing algorithm reads children's intrinsic sizes. Covers:
/// - flex containers (flex item sizing uses child min/max-content),
/// - grid containers (grid-track sizing likewise),
/// - tables and table cells,
/// - inline-block (its own width may be shrink-to-fit),
/// - floats and abspos elements (their `auto` width resolves to shrink-to-fit).
///
/// A `FormattingContext::Block` with a definite CSS width is NOT shrink-to-fit —
/// its inner layout gets the width top-down, so descendant intrinsics don't
/// feed back up. That's the path Fix C short-circuits.
241134
pub(crate) fn is_shrink_to_fit_context(
241134
    styled_dom: &StyledDom,
241134
    dom_node_id: Option<NodeId>,
241134
    fc: FormattingContext,
241134
) -> bool {
    use azul_css::props::layout::{LayoutFloat, LayoutPosition};
    use crate::solver3::{
        getters::{get_float, MultiValue},
        positioning::get_position_type,
    };
241134
    match fc {
        FormattingContext::Flex
        | FormattingContext::Grid
        | FormattingContext::Table
64678
        | FormattingContext::InlineBlock => return true,
176456
        _ => {}
    }
176456
    let Some(dom_id) = dom_node_id else {
308
        return false;
    };
176148
    let node_state = &styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
176148
    let float_val = match get_float(styled_dom, dom_id, node_state) {
176138
        MultiValue::Exact(v) => v,
10
        _ => LayoutFloat::None,
    };
176148
    if float_val != LayoutFloat::None {
601
        return true;
175547
    }
175547
    let pos = get_position_type(styled_dom, Some(dom_id));
175547
    if pos == LayoutPosition::Absolute || pos == LayoutPosition::Fixed {
        // Abspos only becomes shrink-to-fit when width is `auto`.
        // Being conservative: treat as STF whenever abspos so we still
        // compute intrinsics for the auto-width case. Misses no work.
2448
        return true;
173099
    }
173099
    false
241134
}
/// Per-node bitmap of "this node or any descendant establishes a shrink-to-fit
/// context." Post-order walk: `out[i] = self_stf(i) || any(out[child_of_i])`.
/// Layout tree nodes are built top-down (pre-order), so iterating from the end
/// visits children before parents.
1689
fn compute_subtree_needs_intrinsic(styled_dom: &StyledDom, tree: &LayoutTree) -> Vec<bool> {
1689
    let n = tree.nodes.len();
1689
    let mut out = vec![false; n];
20849
    for idx in (0..n).rev() {
20849
        let hot = &tree.nodes[idx];
20849
        let self_stf =
20849
            is_shrink_to_fit_context(styled_dom, hot.dom_node_id, hot.formatting_context);
20849
        let mut any = self_stf;
20849
        if !any {
20065
            for &child in tree.children(idx) {
18096
                if out.get(child).copied().unwrap_or(false) {
1328
                    any = true;
1328
                    break;
16768
                }
            }
784
        }
20849
        out[idx] = any;
    }
1689
    out
1689
}
/// Incrementally builds a [`LayoutTree`] from a [`StyledDom`].
///
/// Usage: create via [`LayoutTreeBuilder::new`], call [`process_node`](Self::process_node)
/// on the root DOM node, then call [`build`](Self::build) to produce the final
/// SoA-split `LayoutTree`. During `process_node`, anonymous boxes are generated
/// as required by CSS 2.2 §9.2.1.1 (inline wrappers) and §17.2.1 (table fixup).
#[derive(Debug)]
pub struct LayoutTreeBuilder {
    nodes: Vec<LayoutNode>,
    dom_to_layout: BTreeMap<NodeId, Vec<usize>>,
    viewport_size: LogicalSize,
}
impl LayoutTreeBuilder {
    #[must_use]
10789
    pub const fn new(viewport_size: LogicalSize) -> Self {
10789
        Self {
10789
            nodes: Vec::new(),
10789
            dom_to_layout: BTreeMap::new(),
10789
            viewport_size,
10789
        }
10789
    }
    #[must_use]
2729879
    pub fn get(&self, index: usize) -> Option<&LayoutNode> {
2729879
        self.nodes.get(index)
2729879
    }
260783
    pub fn get_mut(&mut self, index: usize) -> Option<&mut LayoutNode> {
260783
        self.nodes.get_mut(index)
260783
    }
    // +spec:display-property:2188b7 - builds box tree: each element's principal box is child of
    // nearest ancestor's principal box, with anonymous boxes for tables/inline wrapping
    /// Main entry point for recursively building the layout tree.
    /// This function dispatches to specialized handlers based on the node's
    /// `display` property to correctly generate anonymous boxes.
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive:
                                                                   // single-purpose
                                                                   // layout/render/parse routine
                                                                   // (one branch per case)
20450
    fn process_node(
20450
        &mut self,
20450
        styled_dom: &StyledDom,
20450
        dom_id: NodeId,
20450
        parent_idx: Option<usize>,
20450
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
20450
    ) -> Result<usize> {
20450
        let node_data = &styled_dom.node_data.as_container()[dom_id];
20450
        let node_idx = self.create_node_from_dom(styled_dom, dom_id, parent_idx, debug_messages);
20450
        let raw_display = get_display_type(styled_dom, dom_id);
        // +spec:display-property:042f56 - replaced elements with layout-internal display use inline
        // CSS Display 3 §2.4: "When the display property of a replaced element computes to
        // one of the layout-internal values, it is handled as having a used value of inline."
20450
        let raw_display = if raw_display.is_layout_internal() && is_replaced_element(node_data) {
            LayoutDisplay::Inline
        } else {
20450
            raw_display
        };
        // +spec:display-property:0b40af - display/position/float interaction per CSS 2.2 §9.7
        // +spec:display-property:ba53ba - float!=none or position!=static causes display to
        // blockify +spec:positioning:69468c - absolute/fixed blockifies the box, float
        // computes to none +spec:table-layout:cfc60a - CSS 2.2 §9.7: display/position/float
        // interaction Blockification rules (CSS Display 3 §2.7 / §2.8):
        // 1. Root element → blockify
        // 2. position:absolute or position:fixed → float computes to 'none', blockify
        // 3. float is not 'none' → blockify
        // 4. Flex/Grid children → blockify
20450
        let node_position = self
20450
            .nodes
20450
            .get(node_idx)
20450
            .map(|n| n.computed_style.position)
20450
            .unwrap_or_default();
20450
        let node_float = self
20450
            .nodes
20450
            .get(node_idx)
20450
            .map(|n| n.computed_style.float)
20450
            .unwrap_or_default();
20450
        let is_absolute_or_fixed = matches!(
20450
            node_position,
            LayoutPosition::Absolute | LayoutPosition::Fixed
        );
20450
        let is_floated = node_float != LayoutFloat::None;
20450
        let is_root = parent_idx.is_none();
        // Per CSS 2.2 §9.7: if position is absolute or fixed, float computes to 'none'
20450
        if is_absolute_or_fixed && is_floated {
            if let Some(node) = self.nodes.get_mut(node_idx) {
                node.computed_style.float = LayoutFloat::None;
            }
20450
        }
20450
        let is_flex_grid_child = parent_idx
20450
            .and_then(|p| {
18764
                self.nodes.get(p).map(|n| {
18456
                    matches!(
18764
                        n.formatting_context,
                        FormattingContext::Flex | FormattingContext::Grid
                    )
18764
                })
18764
            })
20450
            .unwrap_or(false);
20450
        let display_type = crate::solver3::getters::get_computed_display(
20450
            raw_display,
20450
            is_absolute_or_fixed,
20450
            is_floated,
20450
            is_root,
20450
            is_flex_grid_child,
        );
        // If blockification changed the display type, update the node's formatting context
20450
        if display_type != raw_display {
33
            if let Some(node) = self.nodes.get_mut(node_idx) {
33
                node.computed_style.display = display_type;
33
                node.formatting_context =
33
                    determine_formatting_context_for_display(styled_dom, dom_id, display_type);
33
            }
20417
        }
        // Compute containing block index for abs-pos clip exemption
20450
        if is_absolute_or_fixed {
20
            let cb_index = if matches!(node_position, LayoutPosition::Fixed) {
                // Fixed elements: containing block is the root (viewport)
                None
            } else {
                // Absolute elements: containing block is nearest positioned ancestor
20
                let mut ancestor = parent_idx;
                loop {
20
                    match ancestor {
20
                        Some(idx) => {
20
                            let pos = self
20
                                .nodes
20
                                .get(idx)
20
                                .map(|n| n.computed_style.position)
20
                                .unwrap_or_default();
20
                            if pos.is_positioned() {
20
                                break Some(idx);
                            }
                            ancestor = self.nodes.get(idx).and_then(|n| n.parent);
                        }
                        None => break None, // root
                    }
                }
            };
20
            if let Some(node) = self.nodes.get_mut(node_idx) {
20
                node.containing_block_index = cb_index;
20
            }
20430
        }
20450
        if parent_idx.is_none() {
1686
            if let Some(node) = self.nodes.get_mut(node_idx) {
                if let FormattingContext::Block {
1656
                    ref mut establishes_new_context,
1686
                } = node.formatting_context
1656
                {
1656
                    *establishes_new_context = true;
1656
                }
            }
18764
        }
        // +spec:display-property:1f4039 - list-item generates ::marker pseudo-element + principal
        // box +spec:display-property:2bb592 - list-item generates ::marker pseudo-element
        // with list-style content +spec:display-property:3b507e - list-item generates
        // ::marker pseudo-element +spec:display-property:a48f00 - additional boxes (marker,
        // table wrapper) placed w.r.t. principal box +spec:display-property:998063 -
        // list-item generates principal block box + marker box If this is a list-item,
        // inject a ::marker pseudo-element as its first child +spec:display-property:a42905
        // - list-item generates ::marker pseudo-element with list-style content, principal box
        // outer=block inner=flow
20450
        if display_type == LayoutDisplay::ListItem {
292
            self.create_marker_pseudo_element(styled_dom, dom_id, node_idx);
20158
        }
        // +spec:display-contents:376f2e - display:contents removes principal box, children render
        // normally +spec:display-contents:3c7066 - display:contents strips element from
        // formatting tree, hoists children +spec:display-contents:3f4884 - replaced
        // elements / form controls not specially handled yet (spec note: use display:none instead)
        // +spec:display-contents:4f9129 - semantic container role preserved: children promoted but
        // DOM structure unchanged +spec:display-contents:7558e8 - display:contents is
        // rendering-time only; DOM relationships unaffected +spec:display-contents:a079e3 -
        // display:contents generates no box; children promoted to nearest non-contents ancestor
        // (writing-mode parent lookup skips these) +spec:display-contents:e202d5 -
        // display:contents removes principal box, children render as normal
        // +spec:display-contents:6bbdf4 - display:contents preserves semantic container role
        // (visibility context) +spec:display-property:d7a8de - display:none/contents
        // elements generate no box; anonymous box generation ignores them
        // +spec:display-property:dc2132 - display:none and display:contents control box generation
        // display:contents - element generates no box; promote children to parent
        // +spec:display-contents:61992e - element itself generates no boxes, children promoted to
        // parent +spec:display-contents:af8feb - treated as if replaced in element tree by
        // its contents +spec:display-contents:353e71 - display:contents box generation
        // behavior +spec:display-contents:b0a76b - display:contents generates no box;
        // children promoted to parent +spec:display-property:e370af - display:contents
        // generates no box; children promoted to parent
        //
        // +spec:display-contents:852a59 - display:contents computes to display:none for replaced
        // elements +spec:display-contents:4a524e - display:contents computes to
        // display:none on replaced elements +spec:replaced-elements:af1e68 -
        // display:contents on replaced elements has no effect (element renders normally)
        // Per CSS Display 3 §2.5 / Appendix B: replaced elements (img, canvas, embed, object,
        // audio, iframe, video, input, textarea, select, br, wbr, meter, progress)
        // and similar cannot be "un-boxed" — display:contents becomes display:none.
20450
        if display_type == LayoutDisplay::Contents && is_replaced_element(node_data) {
            // Treat as display:none — remove node from parent and skip children
1
            if let Some(parent) = parent_idx {
1
                if let Some(p) = self.nodes.get_mut(parent) {
1
                    p.children.retain(|&c| c != node_idx);
                }
            }
1
            if let Some(node) = self.nodes.get_mut(node_idx) {
1
                node.computed_style.display = LayoutDisplay::None;
1
                node.formatting_context = FormattingContext::None;
1
            }
1
            return Ok(node_idx);
20449
        }
20449
        if display_type == LayoutDisplay::Contents {
            // Remove the node we just created — it shouldn't generate a box
1
            if let Some(parent) = parent_idx {
1
                if let Some(p) = self.nodes.get_mut(parent) {
1
                    p.children.retain(|&c| c != node_idx);
                }
            }
            // Process children as if they belong to the parent (or root if no parent)
1
            let effective_parent = parent_idx.unwrap_or(node_idx);
1
            for child_dom_id in layout_children(styled_dom, dom_id) {
1
                self.process_node(
1
                    styled_dom,
1
                    child_dom_id,
1
                    Some(effective_parent),
1
                    debug_messages,
                )?;
            }
1
            return Ok(node_idx);
20448
        }
20448
        match display_type {
            LayoutDisplay::Block
            | LayoutDisplay::InlineBlock
            | LayoutDisplay::FlowRoot
            | LayoutDisplay::ListItem => {
12353
                self.process_block_children(styled_dom, dom_id, node_idx, debug_messages)?;
            }
            // +spec:table-layout:d52e09 - display:table/inline-table cause element to behave like a
            // table element +spec:table-layout:360da0 - table display values cause
            // table formatting behavior
            LayoutDisplay::Table | LayoutDisplay::InlineTable => {
3
                self.process_table_children(styled_dom, dom_id, node_idx, debug_messages)?;
            }
            LayoutDisplay::TableRowGroup
            | LayoutDisplay::TableHeaderGroup
            | LayoutDisplay::TableFooterGroup => {
                self.process_table_row_group_children(
                    styled_dom,
                    dom_id,
                    node_idx,
                    debug_messages,
                )?;
            }
            LayoutDisplay::TableRow => {
1
                self.process_table_row_children(styled_dom, dom_id, node_idx, debug_messages)?;
            }
1
            LayoutDisplay::TableColumn => {
1
                // +spec:table-layout:77974f - Stage 1: all children of table-column treated as
1
                // display:none +spec:table-layout:c8dc69 - Stage 1: remove
1
                // irrelevant boxes from table-column CSS 2.2 §17.2.1: "All child
1
                // boxes of a 'table-column' parent are treated as if they had
1
                // 'display: none'." - skip all children.
1
            }
            LayoutDisplay::TableColumnGroup => {
                // CSS 2.2 §17.2.1: "If a child C of a 'table-column-group' parent is not
                // a 'table-column' box, then it is treated as if it had 'display: none'."
                for child_dom_id in layout_children(styled_dom, dom_id) {
                    let child_display = get_display_type(styled_dom, child_dom_id);
                    if child_display == LayoutDisplay::TableColumn {
                        self.process_node(
                            styled_dom,
                            child_dom_id,
                            Some(node_idx),
                            debug_messages,
                        )?;
                    }
                    // Non-table-column children are suppressed (treated as display:none)
                }
            }
            // Inline, TableCell, etc., have their children processed as part of their
            // formatting context layout and don't require anonymous box generation at this stage.
            // of table-internal display values is handled via blockify_flex_item_if_table_internal
            _ => {
                // +spec:display-contents:34008d - display:none elements generate no boxes; excluded
                // from formatting structure +spec:display-property:1f38b2 -
                // display:none creates no box at all, filter from layout tree
                // +spec:display-property:eb53f7 - display:none suppresses box generation;
                // visibility:hidden boxes still affect layout Filter out display:
                // none children - they don't participate in layout
                // +spec:display-property:d1600a - display:none suppresses box generation;
                // visibility:hidden boxes still affect layout ALSO filter out
                // whitespace-only text nodes for Flex/Grid/etc containers
                // to prevent them from becoming unwanted anonymous items.
8090
                let children: Vec<NodeId> = layout_children(styled_dom, dom_id)
8090
                    .into_iter()
                    // +spec:display-property:9f02c6 - display:none elements generate no boxes
8090
                    .filter(|&child_id| {
                        // +spec:display-property:3b507e - display:none excludes subtree from box tree
636
                        if get_display_type(styled_dom, child_id) == LayoutDisplay::None {
                            return false;
636
                        }
                        // Check for whitespace-only text
636
                        let node_data = &styled_dom.node_data.as_container()[child_id];
636
                        if let NodeType::Text(text) = node_data.get_node_type() {
                            // Skip if text is empty or just whitespace
358
                            return !text.as_str().trim().is_empty();
278
                        }
278
                        true
636
                    })
8090
                    .collect();
8090
                let is_flex_or_grid = matches!(
8090
                    display_type,
                    LayoutDisplay::Flex
                        | LayoutDisplay::InlineFlex
                        | LayoutDisplay::Grid
                        | LayoutDisplay::InlineGrid
                );
8576
                for child_dom_id in children {
                    // +spec:display-property:934c84 - table wrapper box generation:
                    // display:table/inline-table generates a principal block container (table
                    // wrapper box) that establishes BFC and contains the table box + caption boxes
                    // +spec:width-calculation:59d456 - table wrapper box is block-level,
                    // establishes BFC (CSS 2.2 §17.4) the table wrapper box
                    // becomes the flex item; align-self applies to the wrapper,
                    // flex longhands apply to the inner table box, caption contents
                    // contribute to wrapper min/max-content sizes
486
                    let child_display = get_display_type(styled_dom, child_dom_id);
486
                    if is_flex_or_grid && child_display.creates_table_context() {
                        let wrapper_idx = self.create_anonymous_node(
                            node_idx,
                            AnonymousBoxType::TableWrapper,
                            FormattingContext::Block {
                                establishes_new_context: true,
                            },
                        );
                        self.process_node(
                            styled_dom,
                            child_dom_id,
                            Some(wrapper_idx),
                            debug_messages,
                        )?;
                    } else {
486
                        let child_idx = self.process_node(
486
                            styled_dom,
486
                            child_dom_id,
486
                            Some(node_idx),
486
                            debug_messages,
                        )?;
                        // table-internal flex items are blockified, preventing anonymous table
                        // box generation (e.g. two display:table-cell flex items become two
                        // separate display:block flex items)
486
                        if is_flex_or_grid {
308
                            blockify_flex_item_if_table_internal(&mut self.nodes, child_idx);
328
                        }
                    }
                }
            }
        }
20448
        Ok(node_idx)
20450
    }
    // +spec:display-property:5572e7 - Anonymous block boxes: wrap inline runs when block container
    // has mixed block/inline children +spec:display-property:090043 - Anonymous block box
    // properties inherited from enclosing non-anonymous box; non-inherited props get initial values
    // +spec:display-property:7b9f7a - Block-level vs inline-level classification and anonymous
    // block box creation +spec:display-property:078fe5 - Anonymous block boxes wrapping inline
    // content in mixed block/inline contexts +spec:display-property:8d8ef3 - block container
    // anonymous box generation: wraps inline runs in anonymous block boxes to ensure block
    // containers contain only block-level or only inline-level boxes +spec:display-property:
    // 1fe2be - inline box construction with anonymous text interspersed with inline elements
    // +spec:display-property:be80e3 - Anonymous inline boxes: text in block containers treated as
    // anonymous inlines, whitespace-only runs collapsed
    /// Handles children of a block-level element, creating anonymous block
    /// wrappers for consecutive runs of inline-level children if necessary.
    // +spec:display-property:b73c50 - blockify inline content by wrapping in anonymous block
    // containers
12353
    fn process_block_children(
12353
        &mut self,
12353
        styled_dom: &StyledDom,
12353
        parent_dom_id: NodeId,
12353
        parent_idx: usize,
12353
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
12353
    ) -> Result<()> {
        // Filter out display: none children - they don't participate in layout
12353
        let children: Vec<NodeId> = layout_children(styled_dom, parent_dom_id)
12353
            .into_iter()
23693
            .filter(|&child_id| get_display_type(styled_dom, child_id) != LayoutDisplay::None)
12353
            .collect();
        // Debug: log which children we found
12353
        if let Some(msgs) = debug_messages.as_mut() {
7790
            msgs.push(LayoutDebugMessage::info(format!(
7790
                "[process_block_children] DOM node {} has {} children: {:?}",
7790
                parent_dom_id.index(),
7790
                children.len(),
7790
                children.iter().map(NodeId::index).collect::<Vec<_>>()
7790
            )));
8403
        }
13143
        let has_block_child = children.iter().any(|&id| is_block_level(styled_dom, id));
12353
        if let Some(msgs) = debug_messages.as_mut() {
7790
            msgs.push(LayoutDebugMessage::info(format!(
7790
                "[process_block_children] has_block_child={}, children display types: {:?}",
                has_block_child,
7790
                children
7790
                    .iter()
12620
                    .map(|c| {
12620
                        let dt = get_display_type(styled_dom, *c);
12620
                        let is_block = is_block_level(styled_dom, *c);
12620
                        format!("{}:{:?}(block={})", c.index(), dt, is_block)
12620
                    })
7790
                    .collect::<Vec<_>>()
            )));
4563
        }
12353
        if !has_block_child {
            // All children are inline, no anonymous boxes needed.
8262
            if let Some(msgs) = debug_messages.as_mut() {
4570
                msgs.push(LayoutDebugMessage::info(format!(
4570
                    "[process_block_children] All inline, processing {} children directly",
4570
                    children.len()
4570
                )));
4852
            }
16058
            for child_id in children {
7796
                self.process_node(styled_dom, child_id, Some(parent_idx), debug_messages)?;
            }
8262
            return Ok(());
4091
        }
        // Mixed block and inline content requires anonymous wrappers.
4091
        let mut inline_run = Vec::new();
19987
        for child_id in children {
15896
            if is_block_level(styled_dom, child_id) {
                // +spec:display-contents:02a534 - contiguous text sequences with no text don't
                // generate boxes End the current inline run — but skip if all nodes
                // are whitespace-only text. +spec:display-property:7d1570 -
                // whitespace-only text that would be collapsed does not generate anonymous inline
                // boxes +spec:white-space-processing:b32f69 - whitespace-only
                // inline runs between blocks don't generate anonymous inline boxes
                // CSS 2.1 §9.2.2.1: "White space content that would subsequently be collapsed
                // away according to the 'white-space' property does not generate any anonymous
                // inline boxes."
10300
                if !inline_run.is_empty() {
4438
                    self.flush_inline_run(styled_dom, parent_idx, &mut inline_run, debug_messages)?;
5862
                }
                // Process the block-level child directly
10300
                if let Some(msgs) = debug_messages.as_mut() {
6060
                    msgs.push(LayoutDebugMessage::info(format!(
6060
                        "[process_block_children] Processing block child DOM {}",
6060
                        child_id.index()
6060
                    )));
6570
                }
10300
                self.process_node(styled_dom, child_id, Some(parent_idx), debug_messages)?;
5596
            } else {
5596
                inline_run.push(child_id);
5596
            }
        }
        // Process any remaining inline children at the end — skip if all whitespace
4091
        if !inline_run.is_empty() {
1078
            self.flush_inline_run(styled_dom, parent_idx, &mut inline_run, debug_messages)?;
3013
        }
4091
        Ok(())
12353
    }
    // +spec:table-layout:6bb84e - Anonymous table object generation (stages 1-3: remove irrelevant
    // boxes, generate missing child wrappers, generate missing parents) +spec:table-layout:
    // 77974f - Stage 2: generate missing child wrappers for table/inline-table
    // +spec:table-layout:c8dc69 - Stage 2: wrap non-proper children in anonymous table-row
    // +spec:display-property:6f8f13 - anonymous table object generation (§17.2.1): suppress
    // table-column/table-column-group children, wrap non-proper children in anonymous rows/cells
4
    fn process_table_level_children(
4
        &mut self,
4
        styled_dom: &StyledDom,
4
        parent_dom_id: NodeId,
4
        parent_idx: usize,
4
        is_expected_child: fn(LayoutDisplay) -> bool,
4
        anon_type: AnonymousBoxType,
4
        anon_fc: FormattingContext,
4
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
4
    ) -> Result<()> {
4
        let parent_display = get_display_type(styled_dom, parent_dom_id);
4
        let mut non_matching_children = Vec::new();
4
        for child_id in layout_children(styled_dom, parent_dom_id) {
4
            if should_skip_for_table_structure(styled_dom, child_id, parent_display) {
1
                continue;
3
            }
3
            let child_display = get_display_type(styled_dom, child_id);
3
            if is_expected_child(child_display) {
1
                if !non_matching_children.is_empty() {
                    let anon_idx = self.create_anonymous_node(parent_idx, anon_type, anon_fc);
                    #[allow(clippy::iter_with_drain)]
                    // accumulator Vec reused across runs; drain(..) empties it while retaining the
                    // allocation
                    for np_id in non_matching_children.drain(..) {
                        self.process_node(styled_dom, np_id, Some(anon_idx), debug_messages)?;
                    }
1
                }
1
                self.process_node(styled_dom, child_id, Some(parent_idx), debug_messages)?;
2
            } else {
2
                non_matching_children.push(child_id);
2
            }
        }
4
        if !non_matching_children.is_empty() {
2
            let anon_idx = self.create_anonymous_node(parent_idx, anon_type, anon_fc);
4
            for np_id in non_matching_children {
2
                self.process_node(styled_dom, np_id, Some(anon_idx), debug_messages)?;
            }
2
        }
4
        Ok(())
4
    }
3
    fn process_table_children(
3
        &mut self,
3
        styled_dom: &StyledDom,
3
        parent_dom_id: NodeId,
3
        parent_idx: usize,
3
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
3
    ) -> Result<()> {
3
        self.process_table_level_children(
3
            styled_dom,
3
            parent_dom_id,
3
            parent_idx,
3
            is_proper_table_child,
3
            AnonymousBoxType::TableRow,
3
            FormattingContext::TableRow,
3
            debug_messages,
        )
3
    }
    fn process_table_row_group_children(
        &mut self,
        styled_dom: &StyledDom,
        parent_dom_id: NodeId,
        parent_idx: usize,
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
    ) -> Result<()> {
        self.process_table_level_children(
            styled_dom,
            parent_dom_id,
            parent_idx,
            |d| d == LayoutDisplay::TableRow,
            AnonymousBoxType::TableRow,
            FormattingContext::TableRow,
            debug_messages,
        )
    }
1
    fn process_table_row_children(
1
        &mut self,
1
        styled_dom: &StyledDom,
1
        parent_dom_id: NodeId,
1
        parent_idx: usize,
1
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
1
    ) -> Result<()> {
1
        self.process_table_level_children(
1
            styled_dom,
1
            parent_dom_id,
1
            parent_idx,
            |d| d == LayoutDisplay::TableCell,
1
            AnonymousBoxType::TableCell,
1
            FormattingContext::Block {
1
                establishes_new_context: true,
1
            },
1
            debug_messages,
        )
1
    }
    // +spec:display-property:7d1570 - whitespace-only text that would be collapsed does not
    // generate anonymous inline boxes +spec:white-space-processing:b32f69 - whitespace-only
    // inline runs between blocks don't generate anonymous inline boxes
5516
    fn flush_inline_run(
5516
        &mut self,
5516
        styled_dom: &StyledDom,
5516
        parent_idx: usize,
5516
        inline_run: &mut Vec<NodeId>,
5516
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
5516
    ) -> Result<()> {
5516
        let all_whitespace = inline_run
5516
            .iter()
5556
            .all(|id| is_whitespace_only_text(styled_dom, *id));
5516
        if all_whitespace {
5418
            if let Some(msgs) = debug_messages.as_mut() {
2180
                msgs.push(LayoutDebugMessage::info(format!(
2180
                    "[process_block_children] Skipping whitespace-only inline run: {:?}",
2180
                    inline_run
2180
                        .iter()
2180
                        .map(|c: &NodeId| c.index())
2180
                        .collect::<Vec<_>>()
                )));
3238
            }
5418
            inline_run.clear();
        } else {
98
            if let Some(msgs) = debug_messages.as_mut() {
60
                msgs.push(LayoutDebugMessage::info(format!(
60
                    "[process_block_children] Creating anon wrapper for inline run: {:?}",
60
                    inline_run
60
                        .iter()
140
                        .map(|c: &NodeId| c.index())
60
                        .collect::<Vec<_>>()
                )));
38
            }
            // CSS 2.2 s 9.2.2.1 / s 9.4.2: this anonymous block box contains
            // nothing but inline-level boxes, so it establishes an INLINE
            // formatting context. `reconcile_recursive` (cache.rs) has always
            // built the same box as `FormattingContext::Inline`; this one said
            // `Block { establishes_new_context: true }`, so the same markup laid
            // out one way on a fresh tree and another on a reconciled one — an
            // atomic inline under it was placed as a block child by one and on a
            // line box by the other, and the two disagreed about its height.
98
            let anon_idx = self.create_anonymous_node(
98
                parent_idx,
98
                AnonymousBoxType::InlineWrapper,
98
                FormattingContext::Inline,
            );
178
            for inline_child_id in inline_run.drain(..) {
178
                self.process_node(styled_dom, inline_child_id, Some(anon_idx), debug_messages)?;
            }
        }
5516
        Ok(())
5516
    }
    // +spec:display-property:52f497 - anonymous inline boxes inherit inheritable properties from
    // block parent; non-inherited properties use initial values (dom_node_id: None +
    // BoxProps::default())
    /// CSS 2.2 Section 17.2.1 - Anonymous box generation:
    /// "In this process, inline-level boxes are wrapped in anonymous boxes as needed
    /// to satisfy the constraints of the table model."
    // +spec:display-property:ee83bf - Anonymous box generation: boxes not associated with elements,
    // inheriting through box tree parentage
    /// Helper to create an anonymous node in the tree.
    /// Anonymous boxes don't have a corresponding DOM node and are used to enforce
    /// the CSS box model structure (e.g., wrapping inline content in blocks,
    /// or creating missing table structural elements).
    // +spec:display-property:6ff51a - anonymous block boxes have no styles (box_props default), so
    // parent element properties still apply to its content
265
    pub fn create_anonymous_node(
265
        &mut self,
265
        parent: usize,
265
        anon_type: AnonymousBoxType,
265
        fc: FormattingContext,
265
    ) -> usize {
265
        let index = self.nodes.len();
        // +spec:display-property:e67146 - Anonymous boxes inherit from enclosing non-anonymous box;
        // non-inherited props use initial values
265
        let parent_fc = self.nodes.get(parent).map(|n| n.formatting_context);
265
        self.nodes.push(LayoutNode {
265
            // ── HOT ──
265
            box_props: BoxProps::default(),
265
            dom_node_id: None,
265
            children: Vec::new(),
265
            used_size: None,
265
            formatting_context: fc,
265
            parent: Some(parent),
265
            // ── WARM ──
265
            intrinsic_sizes: None,
265
            baseline: None,
265
            inline_layout_result: None,
265
            inline_content_cache: None,
265
            scrollbar_info: None,
265
            relative_position: None,
265
            overflow_content_size: None,
265
            taffy_cache: TaffyCache::new(),
265
            measured_content_sizes: (None, None),
265
            computed_style: ComputedLayoutStyle::default(),
265
            pseudo_element: None,
265
            escaped_top_margin: None,
265
            escaped_bottom_margin: None,
265
            parent_formatting_context: parent_fc,
265
            ifc_membership: None,
265
            containing_block_index: None,
265
            // ── COLD ──
265
            anonymous_type: Some(anon_type),
265
            preview_byte_range: None,
265
            node_data_fingerprint: NodeDataFingerprint::default(),
265
            subtree_hash: SubtreeHash(0),
265
            dirty_flag: DirtyFlag::Layout,
265
            unresolved_box_props: crate::solver3::geometry::UnresolvedBoxProps::default(),
265
            ifc_id: None,
265
        });
265
        self.nodes[parent].children.push(index);
265
        index
265
    }
    /// Creates a `::marker` pseudo-element as the first child of a list-item.
    ///
    /// Per CSS Lists Module Level 3, Section 3.1:
    /// "For elements with display: list-item, user agents must generate a
    /// `::marker` pseudo-element as the first child of the principal box."
    ///
    /// The `::marker` references the same DOM node as its parent list-item,
    /// but is marked as a pseudo-element for proper counter resolution and styling.
1872
    pub fn create_marker_pseudo_element(
1872
        &mut self,
1872
        styled_dom: &StyledDom,
1872
        list_item_dom_id: NodeId,
1872
        list_item_idx: usize,
1872
    ) -> usize {
1872
        let index = self.nodes.len();
        // The marker references the same DOM node as the list-item
        // This is important for style resolution (the marker inherits from the list-item)
1872
        let parent_fc = self.nodes.get(list_item_idx).map(|n| n.formatting_context);
1872
        self.nodes.push(LayoutNode {
1872
            // ── HOT ──
1872
            box_props: BoxProps::default(),
1872
            dom_node_id: Some(list_item_dom_id),
1872
            children: Vec::new(),
1872
            used_size: None,
1872
            formatting_context: FormattingContext::Inline,
1872
            parent: Some(list_item_idx),
1872
            // ── WARM ──
1872
            intrinsic_sizes: None,
1872
            baseline: None,
1872
            inline_layout_result: None,
1872
            inline_content_cache: None,
1872
            scrollbar_info: None,
1872
            relative_position: None,
1872
            overflow_content_size: None,
1872
            taffy_cache: TaffyCache::new(),
1872
            measured_content_sizes: (None, None),
1872
            computed_style: ComputedLayoutStyle::default(),
1872
            pseudo_element: Some(PseudoElement::Marker),
1872
            escaped_top_margin: None,
1872
            escaped_bottom_margin: None,
1872
            parent_formatting_context: parent_fc,
1872
            ifc_membership: None,
1872
            containing_block_index: None,
1872
            // ── COLD ──
1872
            anonymous_type: None,
1872
            preview_byte_range: None,
1872
            node_data_fingerprint: NodeDataFingerprint::default(),
1872
            subtree_hash: SubtreeHash(0),
1872
            dirty_flag: DirtyFlag::Layout,
1872
            unresolved_box_props: crate::solver3::geometry::UnresolvedBoxProps::default(),
1872
            ifc_id: None,
1872
        });
        // Insert as FIRST child (per spec)
1872
        self.nodes[list_item_idx].children.insert(0, index);
        // Register with DOM mapping for counter resolution
1872
        self.dom_to_layout
1872
            .entry(list_item_dom_id)
1872
            .or_default()
1872
            .push(index);
1872
        index
1872
    }
    // M12.7: returns `usize`, NOT `Result<usize>` — this fn has no error path
    // (always `Ok(index)`). The `Result` forced callers to use `?`, whose lifted
    // discriminant decode mis-reads the Ok as Err (the rc=5 root cause: reconcile
    // reaches this fn but returns Err before its own Ok). Dropping the Result
    // removes that mis-lifting `?`.
    /// Apply CSS Display 3 §2.7/§2.8 blockification to a freshly-created node:
    /// a flex/grid item (or root / abs-pos / floated box) whose specified display
    /// is inline-level computes to its block-level equivalent.
    ///
    /// `process_node` (the full tree build) does this inline, but the INCREMENTAL
    /// tree builder (`cache.rs` reconcile → `create_node_from_dom`) bypassed it.
    /// Without it, a replaced inline flex item — e.g. an `<img>` canvas with
    /// `flex-grow: 1` (`AzulPaint`) — stayed inline, so its flex-grow was ignored
    /// and it was laid out 300×0 (the replaced-element default width, 0 height).
    /// Must be called AFTER the node is created and AFTER its parent's
    /// formatting context is known (the build is top-down, so the parent exists).
210124
    pub fn blockify_node_display(
210124
        &mut self,
210124
        styled_dom: &StyledDom,
210124
        dom_id: NodeId,
210124
        node_idx: usize,
210124
        parent_idx: Option<usize>,
210124
    ) {
210124
        let node_data = &styled_dom.node_data.as_container()[dom_id];
        // CSS Display 3 §2.4: a replaced element with a layout-internal display
        // value uses 'inline' — so it's inline-level and thus blockifiable.
210124
        let raw_display = {
210124
            let d = get_display_type(styled_dom, dom_id);
210124
            if d.is_layout_internal() && is_replaced_element(node_data) {
                LayoutDisplay::Inline
            } else {
210124
                d
            }
        };
210124
        let (position, float) = self
210124
            .nodes
210124
            .get(node_idx)
210124
            .map(|n| (n.computed_style.position, n.computed_style.float))
210124
            .unwrap_or_default();
210124
        let is_absolute_or_fixed =
210124
            matches!(position, LayoutPosition::Absolute | LayoutPosition::Fixed);
210124
        let is_floated = float != LayoutFloat::None;
210124
        let is_root = parent_idx.is_none();
210124
        let is_flex_grid_child = parent_idx.and_then(|p| self.nodes.get(p)).is_some_and(|n| {
84351
            matches!(
202916
                n.formatting_context,
                FormattingContext::Flex | FormattingContext::Grid
            )
202916
        });
210124
        let display_type = crate::solver3::getters::get_computed_display(
210124
            raw_display,
210124
            is_absolute_or_fixed,
210124
            is_floated,
210124
            is_root,
210124
            is_flex_grid_child,
        );
210124
        if display_type != raw_display {
21333
            if let Some(node) = self.nodes.get_mut(node_idx) {
21333
                node.computed_style.display = display_type;
21333
                node.formatting_context =
21333
                    determine_formatting_context_for_display(styled_dom, dom_id, display_type);
21333
            }
188791
        }
210124
    }
    #[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
230584
    pub fn create_node_from_dom(
230584
        &mut self,
230584
        styled_dom: &StyledDom,
230584
        dom_id: NodeId,
230584
        parent: Option<usize>,
230584
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
230584
    ) -> usize {
230584
        let index = self.nodes.len();
        // as IT sees it). If this is 0 but build() sees 0 nodes, the push is lost
        // between here and build (builder &mut threading); if garbage, len mis-reads.
230584
        {
230584
            let _ = (0xCE00_0000u32 | (index as u32 & 0xffff));
230584
        }
230584
        let parent_fc = parent.and_then(|p| self.nodes.get(p).map(|n| n.formatting_context));
        // this is reached but step A is NOT, collect_box_props diverges; if this is
        // NOT reached, the parent Option discriminant mis-lifts (None→Some garbage).
230584
        {
230584
            let _ = (0xCD00_0001u32 | (u32::from(parent_fc.is_some()) << 8));
230584
        }
230584
        let collected = collect_box_props(styled_dom, dom_id, debug_messages, self.viewport_size);
230584
        {
230584
            let _ = (0xCA00_0001u32);
230584
        }
230584
        self.nodes.push(LayoutNode {
            // ── HOT ──
230584
            box_props: collected.resolved,
230584
            dom_node_id: Some(dom_id),
230584
            children: Vec::new(),
230584
            used_size: None,
230584
            formatting_context: determine_formatting_context(styled_dom, dom_id),
230584
            parent,
            // ── WARM ──
230584
            intrinsic_sizes: None,
230584
            baseline: None,
230584
            inline_layout_result: None,
230584
            inline_content_cache: None,
230584
            scrollbar_info: None,
230584
            relative_position: None,
230584
            overflow_content_size: None,
230584
            taffy_cache: TaffyCache::new(),
230584
            measured_content_sizes: (None, None),
            // +spec:overflow:8f9f7e - viewport overflow propagation: visible→auto, clip→hidden
            computed_style: {
230584
                let mut style = compute_layout_style(styled_dom, dom_id);
230584
                if parent.is_none() {
                    // CSS Overflow 3 §3.3: If visible is applied to the viewport,
                    // it must be interpreted as auto. If clip is applied to the
                    // viewport, it must be interpreted as hidden.
                    use azul_css::props::layout::LayoutOverflow;
8900
                    if style.overflow_x == LayoutOverflow::Visible {
8680
                        style.overflow_x = LayoutOverflow::Auto;
8680
                    } else if style.overflow_x == LayoutOverflow::Clip {
                        style.overflow_x = LayoutOverflow::Hidden;
220
                    }
8900
                    if style.overflow_y == LayoutOverflow::Visible {
8660
                        style.overflow_y = LayoutOverflow::Auto;
8660
                    } else if style.overflow_y == LayoutOverflow::Clip {
                        style.overflow_y = LayoutOverflow::Hidden;
240
                    }
221684
                }
230584
                style
            },
230584
            pseudo_element: None,
230584
            escaped_top_margin: None,
230584
            escaped_bottom_margin: None,
230584
            parent_formatting_context: parent_fc,
230584
            ifc_membership: None,
230584
            containing_block_index: None,
            // ── COLD ──
230584
            anonymous_type: None,
230584
            preview_byte_range: None,
230584
            node_data_fingerprint: NodeDataFingerprint::compute(
230584
                &styled_dom.node_data.as_container()[dom_id],
230584
                styled_dom
230584
                    .styled_nodes
230584
                    .as_container()
230584
                    .get(dom_id)
230584
                    .map(|n| &n.styled_node_state),
            ),
230584
            subtree_hash: SubtreeHash(0),
230584
            dirty_flag: DirtyFlag::Layout,
230584
            unresolved_box_props: collected.unresolved,
230584
            ifc_id: None,
        });
230584
        {
230584
            let _ = (0xCB00_0001u32 | ((self.nodes.len() as u32 & 0xff) << 8));
230584
        }
230584
        if let Some(p) = parent {
221684
            self.nodes[p].children.push(index);
221684
        }
230584
        self.dom_to_layout.entry(dom_id).or_default().push(index);
        // DEBUG (2026-06-02 children-None tree-build): count create_node_from_dom
        // calls @0x40500 + record each dom_id into a 14-slot ring @0x40504. REVERT
        // before commit. Runs only in lifted wasm (server lifts, never runs natively).
        unsafe {
230584
            let c = crate::az_mark_read(0x40500);
230584
            crate::az_mark(0x60500_u32, (c.wrapping_add(1)));
230584
            if (c as usize) < 14 {
230584
                crate::az_mark(
230584
                    (0x40504 + (c as usize) * 4) as u32,
230584
                    (0xDD00_0000 | (dom_id.index() as u32 & 0xffff)),
230584
                );
230584
            }
        }
230584
        index
230584
    }
    /// O3-render: materialize pending SPLIT previews as layout nodes — the
    /// "fake structural edit" becomes VISIBLE. For each recorded split whose
    /// node is an IFC leaf (no layout children; the `<p>text…</p>` shape),
    /// the node becomes part 1 (content byte range `[0, at)`), and a SECOND
    /// node with the SAME `dom_node_id` (the `dom_to_layout` multimap seat)
    /// and `AnonymousBoxType::SplitPreviewPart` shows `[at, ∞)` — a real
    /// layout identity like any anonymous box, NO DOM mutation, no stale
    /// `NodeIds`. Runs as a post-pass just before `build()` on BOTH tree-build
    /// paths (full + reconcile).
    ///
    /// v1 renders text-byte splits; element-children splits stay
    /// recorded-only (the child-routing per part is the staged follow-up).
10722
    pub fn apply_split_previews(
10722
        &mut self,
10722
        overlay: Option<&crate::overlay::ContentOverlay>,
10722
        styled_dom: &StyledDom,
10722
    ) {
10722
        let Some(overlay) = overlay else { return };
8471
        let pending = overlay.pending_structure(styled_dom.dom_id);
8471
        if pending.is_empty() {
8381
            return;
90
        }
90
        let node_data = styled_dom.node_data.as_container();
90
        let hierarchy = styled_dom.node_hierarchy.as_container();
180
        for entry in pending {
90
            let (node, at) = match &entry.preview {
40
                crate::overlay::StructuralPreview::Split { node, at, .. } => (node, at),
10
                crate::overlay::StructuralPreview::Remove { parent, start, end }
                | crate::overlay::StructuralPreview::Replace {
30
                    parent, start, end, ..
                } => {
                    // Removal side renders NOW: the range's layout children
                    // detach from the tree (unreachable from the root, so
                    // never positioned nor painted). Replace's PENDING
                    // content is the staged follow-up — it needs the styled
                    // materialization of a raw `Dom` fragment; until then a
                    // Replace previews as its removal half.
40
                    self.apply_range_suppression_preview(
40
                        *parent,
40
                        *start,
40
                        *end,
40
                        &ordinal_map(&hierarchy, *parent),
                    );
40
                    continue;
                }
10
                crate::overlay::StructuralPreview::Merge { first, second } => {
                    // Backspace-at-start UX: `second` disappears from its
                    // parent, its layout children move (subtrees wholesale)
                    // onto the END of `first` — the inverse mechanics of the
                    // element split above.
10
                    self.apply_merge_preview(*first, *second);
10
                    continue;
                }
                crate::overlay::StructuralPreview::Insert { .. } => {
                    // Staged: rendering a pending `Dom` needs a styled
                    // sub-mount (fragment styling against the retained author
                    // css). Resolvers already expose it (children_for_node);
                    // the box tree does not materialize it yet.
                    continue;
                }
            };
40
            let Some(indices) = self.dom_to_layout.get(node) else {
                continue;
            };
40
            if indices.len() != 1 {
                continue; // already split (or exotic mapping)
40
            }
40
            let idx = indices[0];
            // Child-boundary split (no text byte): a container splits BETWEEN
            // its children — a `<ul>` between `<li>`s, a section between
            // paragraphs. Children before `at.child_index` stay in part 1;
            // the rest MOVE (wholesale, subtrees intact) to the preview part.
40
            let Some(byte) = at.text_byte.into_option() else {
                // Child-boundary split: layout children route to a part by
                // their DOM position.
30
                self.apply_element_split_preview(
30
                    idx,
30
                    *node,
30
                    at.child_index,
30
                    &ordinal_map(&hierarchy, *node),
                );
30
                continue;
            };
            // v1 gate: plain-text IFC roots — every layout child must be
            // text-backed (or anonymous inline machinery). Element children
            // need per-part routing (the staged follow-up).
10
            let all_text_children = self.nodes[idx].children.iter().all(|&c| {
10
                self.nodes.get(c).is_none_or(|n| {
10
                    n.dom_node_id.is_none_or(|d| {
10
                        node_data
10
                            .get(d)
10
                            .is_some_and(|nd| matches!(nd.get_node_type(), NodeType::Text(_)))
10
                    })
10
                })
10
            });
10
            if !all_text_children {
                continue;
10
            }
            // Flat byte offset of the split within the node's concatenated
            // direct-text content (the same flattening fc collects).
10
            let mut flat_at: u32 = 0;
10
            let mut child = hierarchy.get(*node).and_then(|h| h.first_child_id(*node));
10
            let mut i: u32 = 0;
10
            while let Some(c) = child {
10
                if i == at.child_index {
10
                    break;
                }
                if let Some(nd) = node_data.get(c) {
                    if let NodeType::Text(t) = nd.get_node_type() {
                        flat_at += u32::try_from(t.as_str().len()).unwrap_or(u32::MAX);
                    }
                }
                i += 1;
                child = hierarchy
                    .get(c)
                    .and_then(azul_core::styled_dom::NodeHierarchyItem::next_sibling_id);
            }
10
            flat_at += byte;
10
            self.nodes[idx].preview_byte_range = Some((0, flat_at));
10
            self.nodes[idx].inline_layout_result = None;
10
            self.nodes[idx].dirty_flag = DirtyFlag::Layout;
10
            let part2_idx = self.nodes.len();
10
            let mut part2 = self.nodes[idx].clone();
10
            part2.children = Vec::new();
10
            part2.preview_byte_range = Some((flat_at, u32::MAX));
10
            part2.anonymous_type = Some(AnonymousBoxType::SplitPreviewPart);
10
            part2.inline_layout_result = None;
10
            part2.taffy_cache = TaffyCache::new();
10
            part2.measured_content_sizes = (None, None);
10
            part2.dirty_flag = DirtyFlag::Layout;
10
            let parent = part2.parent;
10
            self.nodes.push(part2);
10
            if let Some(p) = parent {
10
                let pos = self.nodes[p]
10
                    .children
10
                    .iter()
10
                    .position(|&c| c == idx)
10
                    .map_or(self.nodes[p].children.len(), |i| i + 1);
10
                self.nodes[p].children.insert(pos, part2_idx);
10
                self.nodes[p].dirty_flag = DirtyFlag::Layout;
            }
10
            self.dom_to_layout.entry(*node).or_default().push(part2_idx);
        }
10722
    }
    /// Child-boundary split preview: partition `idx`'s layout children by DOM
    /// ordinal — `< split_index` stays, the rest MOVE to a fresh
    /// `SplitPreviewPart` sibling that shares `dom_node`'s id (the anon-box
    /// model: rendering knows, callbacks stay blind). Subtrees move
    /// wholesale; nothing is byte-sliced.
    ///
    /// Anonymous wrappers (mixed inline/block content puts inline runs inside
    /// anonymous blocks, so layout children are NOT 1:1 with DOM children)
    /// route through their wrapped runs' ordinals: a wrapper wholly on one
    /// side moves wholesale; a wrapper STRADDLING the split point splits
    /// itself — its second half becomes a fresh anonymous wrapper inside the
    /// preview part, mirroring how the builder would have wrapped the
    /// post-apply trees.
30
    fn apply_element_split_preview(
30
        &mut self,
30
        idx: usize,
30
        dom_node: NodeId,
30
        split_index: u32,
30
        ordinal_of: &BTreeMap<NodeId, u32>,
30
    ) {
30
        let children = self.nodes[idx].children.clone();
30
        let mut keep: Vec<usize> = Vec::new();
30
        let mut moved: Vec<usize> = Vec::new();
110
        for c in children {
80
            if let Some(d) = self.nodes[c].dom_node_id {
                // A layout child mapping to something that is NOT a direct
                // DOM child (unexpected) degrades to "stays" — part 1 keeps
                // rendering it rather than dropping content from a preview.
50
                match ordinal_of.get(&d) {
50
                    Some(&o) if o >= split_index => moved.push(c),
20
                    _ => keep.push(c),
                }
50
                continue;
30
            }
            // Anonymous wrapper: side = the ordinal span of its wrapped runs.
30
            match self.wrapper_ordinal_span(c, ordinal_of) {
30
                Some((_, hi)) if hi < split_index => keep.push(c),
20
                Some((lo, _)) if lo >= split_index => moved.push(c),
                Some(_) => {
                    // Straddling: the wrapper itself splits at the boundary.
10
                    keep.push(c);
10
                    if let Some(second) = self.split_anonymous_wrapper(c, split_index, ordinal_of) {
10
                        moved.push(second);
10
                    }
                }
                // Empty / opaque wrapper (no mapped runs): keep in part 1.
                None => keep.push(c),
            }
        }
30
        if moved.is_empty() {
            return; // split at/after the end: nothing to preview
30
        }
30
        self.nodes[idx].children = keep;
30
        self.nodes[idx].inline_layout_result = None;
30
        self.nodes[idx].dirty_flag = DirtyFlag::Layout;
30
        let part2_idx = self.nodes.len();
30
        let mut part2 = self.nodes[idx].clone();
30
        part2.children.clone_from(&moved);
30
        part2.anonymous_type = Some(AnonymousBoxType::SplitPreviewPart);
30
        part2.inline_layout_result = None;
30
        part2.taffy_cache = TaffyCache::new();
30
        part2.measured_content_sizes = (None, None);
30
        part2.dirty_flag = DirtyFlag::Layout;
30
        let parent = part2.parent;
30
        self.nodes.push(part2);
80
        for &m in &moved {
50
            self.nodes[m].parent = Some(part2_idx);
50
            self.nodes[m].dirty_flag = DirtyFlag::Layout;
50
        }
30
        if let Some(p) = parent {
30
            let pos = self.nodes[p]
30
                .children
30
                .iter()
30
                .position(|&c| c == idx)
30
                .map_or(self.nodes[p].children.len(), |i| i + 1);
30
            self.nodes[p].children.insert(pos, part2_idx);
30
            self.nodes[p].dirty_flag = DirtyFlag::Layout;
        }
30
        self.dom_to_layout
30
            .entry(dom_node)
30
            .or_default()
30
            .push(part2_idx);
30
    }
    /// The min/max DOM ordinal among an anonymous wrapper's DIRECT layout
    /// children that map to real DOM children of the node being edited.
    /// `None` = the wrapper wraps nothing addressable (empty, or generated
    /// content only).
30
    fn wrapper_ordinal_span(
30
        &self,
30
        wrapper: usize,
30
        ordinal_of: &BTreeMap<NodeId, u32>,
30
    ) -> Option<(u32, u32)> {
30
        let mut span: Option<(u32, u32)> = None;
40
        for &c in &self.nodes[wrapper].children {
40
            let Some(o) = self.nodes[c]
40
                .dom_node_id
40
                .and_then(|d| ordinal_of.get(&d).copied())
            else {
                continue;
            };
40
            span = Some(match span {
30
                None => (o, o),
10
                Some((lo, hi)) => (lo.min(o), hi.max(o)),
            });
        }
30
        span
30
    }
    /// Split a straddling anonymous wrapper at `split_index`: runs with
    /// ordinal `>= split_index` move into a NEW wrapper of the same shape
    /// (returned; the caller seats it in the preview part). Runs that map to
    /// nothing stay in the first half. Returns `None` when nothing moves.
10
    fn split_anonymous_wrapper(
10
        &mut self,
10
        wrapper: usize,
10
        split_index: u32,
10
        ordinal_of: &BTreeMap<NodeId, u32>,
10
    ) -> Option<usize> {
10
        let children = core::mem::take(&mut self.nodes[wrapper].children);
20
        let (keep, moved): (Vec<usize>, Vec<usize>) = children.into_iter().partition(|&c| {
20
            self.nodes[c]
20
                .dom_node_id
20
                .and_then(|d| ordinal_of.get(&d).copied())
20
                .is_none_or(|o| o < split_index)
20
        });
10
        self.nodes[wrapper].children = keep;
10
        self.nodes[wrapper].inline_layout_result = None;
10
        self.nodes[wrapper].taffy_cache = TaffyCache::new();
10
        self.nodes[wrapper].measured_content_sizes = (None, None);
10
        self.nodes[wrapper].dirty_flag = DirtyFlag::Layout;
10
        if moved.is_empty() {
            return None;
10
        }
10
        let second_idx = self.nodes.len();
10
        let mut second = self.nodes[wrapper].clone();
10
        second.children = moved;
10
        second.inline_layout_result = None;
10
        second.taffy_cache = TaffyCache::new();
10
        second.measured_content_sizes = (None, None);
10
        second.dirty_flag = DirtyFlag::Layout;
10
        self.nodes.push(second);
10
        let moved_children = self.nodes[second_idx].children.clone();
20
        for m in moved_children {
10
            self.nodes[m].parent = Some(second_idx);
10
            self.nodes[m].dirty_flag = DirtyFlag::Layout;
10
        }
        // The caller re-parents `second_idx` into the preview part; anonymous
        // wrappers have no dom_node_id, so dom_to_layout needs no entry.
10
        Some(second_idx)
10
    }
    /// Remove/Replace preview: detach the layout children of `parent_dom`
    /// whose DOM ordinal falls in `[start, end)`. Detached subtrees stay in
    /// the node arena but are unreachable from the root — never positioned,
    /// never painted (the same fate as any orphaned builder node).
    ///
    /// Anonymous wrappers route through their wrapped runs: wholly inside the
    /// range → the wrapper detaches; straddling → only the wrapper's in-range
    /// runs detach (the wrapper stays for the survivors).
40
    fn apply_range_suppression_preview(
40
        &mut self,
40
        parent_dom: NodeId,
40
        start: u32,
40
        end: u32,
40
        ordinal_of: &BTreeMap<NodeId, u32>,
40
    ) {
40
        let Some(indices) = self.dom_to_layout.get(&parent_dom) else {
            return;
        };
40
        if indices.len() != 1 {
            return; // exotic mapping (already part-split); one preview at a time
40
        }
40
        let idx = indices[0];
40
        let children = self.nodes[idx].children.clone();
40
        let mut kept: Vec<usize> = Vec::new();
40
        let mut changed = false;
160
        for c in children {
120
            if let Some(d) = self.nodes[c].dom_node_id {
120
                let in_range = ordinal_of.get(&d).is_some_and(|&o| o >= start && o < end);
120
                if in_range {
70
                    changed = true;
70
                } else {
50
                    kept.push(c);
50
                }
120
                continue;
            }
            match self.wrapper_ordinal_span(c, ordinal_of) {
                Some((lo, hi)) if lo >= start && hi < end => changed = true, // wholly removed
                Some((lo, hi)) if hi >= start && lo < end => {
                    // Straddling: filter the wrapper's own runs in place.
                    let before = self.nodes[c].children.len();
                    let nodes = &self.nodes;
                    let survivors: Vec<usize> = self.nodes[c]
                        .children
                        .iter()
                        .copied()
                        .filter(|&r| {
                            nodes[r]
                                .dom_node_id
                                .and_then(|d| ordinal_of.get(&d).copied())
                                .is_none_or(|o| o < start || o >= end)
                        })
                        .collect();
                    if survivors.len() != before {
                        self.nodes[c].children = survivors;
                        self.nodes[c].inline_layout_result = None;
                        self.nodes[c].taffy_cache = TaffyCache::new();
                        self.nodes[c].measured_content_sizes = (None, None);
                        self.nodes[c].dirty_flag = DirtyFlag::Layout;
                        changed = true;
                    }
                    kept.push(c);
                }
                _ => kept.push(c), // wholly outside, or opaque: keep
            }
        }
40
        if changed {
40
            self.nodes[idx].children = kept;
40
            self.nodes[idx].inline_layout_result = None;
40
            self.nodes[idx].dirty_flag = DirtyFlag::Layout;
40
        }
40
    }
    /// Merge preview: `second_dom` disappears from its parent; its layout
    /// children move (subtrees wholesale) onto the END of `first_dom`.
10
    fn apply_merge_preview(&mut self, first_dom: NodeId, second_dom: NodeId) {
        // Unmapped or exotic multi-part mappings are staged.
10
        let ((Some(&[first_idx]), Some(&[second_idx]))) = (
10
            self.dom_to_layout.get(&first_dom).map(Vec::as_slice),
10
            self.dom_to_layout.get(&second_dom).map(Vec::as_slice),
        ) else {
            return;
        };
10
        let moved = core::mem::take(&mut self.nodes[second_idx].children);
20
        for &m in &moved {
10
            self.nodes[m].parent = Some(first_idx);
10
            self.nodes[m].dirty_flag = DirtyFlag::Layout;
10
        }
10
        self.nodes[first_idx].children.extend(moved);
10
        self.nodes[first_idx].inline_layout_result = None;
10
        self.nodes[first_idx].dirty_flag = DirtyFlag::Layout;
        // Detach `second` itself from its parent (unreachable = unpainted).
10
        if let Some(p) = self.nodes[second_idx].parent {
20
            self.nodes[p].children.retain(|&c| c != second_idx);
10
            self.nodes[p].dirty_flag = DirtyFlag::Layout;
        }
10
    }
    /// Reuse an old node's cached layout under a NEW DOM identity.
    ///
    /// `new_dom_id` is what the node IS; the clone only carries what it
    /// COSTS (used size, taffy cache, inline layout result). Reconciliation
    /// matches an old child to a new one by DOM id where it can, but falls
    /// back to POSITION when the id is absent from the old child list — and
    /// a positional match pairs nodes with different ids. Copying the old
    /// id through then produced a layout node claiming to be a DOM node
    /// that has moved, or (when the DOM shrank) one that no longer exists:
    /// `compute_counters` panicked indexing `node_data[52]` on a 37-node
    /// `StyledDom`, and every quieter consumer — style lookups, node rects,
    /// damage attribution — silently read a DIFFERENT node's data.
    ///
    /// Passing `None` keeps the node anonymous (no DOM identity), which is
    /// correct for pure layout wrappers.
50609
    pub fn clone_node_from_old(
50609
        &mut self,
50609
        old_node: &LayoutNode,
50609
        parent: Option<usize>,
50609
        new_dom_id: Option<NodeId>,
50609
    ) -> usize {
50609
        let index = self.nodes.len();
50609
        let mut new_node = old_node.clone();
50609
        new_node.parent = parent;
        new_node.parent_formatting_context =
50609
            parent.and_then(|p| self.nodes.get(p).map(|n| n.formatting_context));
50609
        new_node.children = Vec::new();
50609
        new_node.dirty_flag = DirtyFlag::None;
        // The measurement cache does NOT survive the clone.
        //
        // A clone is taken because the node's own data is unchanged — but
        // "unchanged" says nothing about its SURROUNDINGS. Its cached
        // (available space -> computed size) entries were measured against
        // the previous frame's siblings, and a clone is taken precisely when
        // a sibling changed enough to re-lay the parent out. `layout_document`
        // clears this cache for `intrinsic_dirty` nodes; the clean clones
        // beside them kept theirs.
        //
        // Symptom: clicking ribbon tab 1 left tab 2 — the tab that never
        // changed state — drawing its label 1.5px lower than a fresh render
        // of the same state, with an IDENTICAL header box. The cached entry
        // was answering with a measurement taken while tab 0 was active.
        //
        // What the clone is FOR is still preserved: the tree structure, the
        // fingerprint, and `inline_layout_result` — so the text is not
        // re-shaped, only re-measured. Measured flat on
        // layout/tests/frame_perf.rs (idle 19.21 vs 19.70 ms, cold 75.96 vs
        // 74.57 ms, edit 22.72 vs 25.39 ms — all inside run-to-run noise).
50609
        new_node.taffy_cache.clear();
50609
        new_node.measured_content_sizes = (None, None);
50609
        new_node.dom_node_id = new_dom_id;
50609
        self.nodes.push(new_node);
50609
        if let Some(p) = parent {
48726
            self.nodes[p].children.push(index);
48726
        }
50609
        if let Some(dom_id) = new_dom_id {
50608
            self.dom_to_layout.entry(dom_id).or_default().push(index);
50608
        }
50609
        index
50609
    }
    #[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
    #[must_use]
10773
    pub fn build(self, root_idx: usize) -> LayoutTree {
10773
        let nodes = self.nodes;
10773
        let node_count = nodes.len();
        // Flatten per-node children Vecs into a single contiguous arena.
283359
        let total_children: usize = nodes.iter().map(|n| n.children.len()).sum();
10773
        let mut arena = Vec::with_capacity(total_children);
10773
        let mut offsets = Vec::with_capacity(node_count);
        // Split monolithic LayoutNodes into hot/warm/cold SoA arrays
10773
        let mut hot_nodes = Vec::with_capacity(node_count);
10773
        let mut warm_nodes = Vec::with_capacity(node_count);
10773
        let mut cold_nodes = Vec::with_capacity(node_count);
294132
        for node in nodes {
283359
            // Flatten children into arena first
283359
            let start = arena.len() as u32;
283359
            let len = node.children.len() as u32;
283359
            arena.extend_from_slice(&node.children);
283359
            offsets.push((start, len));
283359

            
283359
            // Split into hot/warm/cold
283359
            let (hot, warm, cold) = node.split();
283359
            hot_nodes.push(hot);
283359
            warm_nodes.push(warm);
283359
            cold_nodes.push(cold);
283359
        }
        // discriminant). If len>0 but calculate_intrinsic_recursive's
        // `tree.get(root).ok_or(InvalidTree)?` still errors, that `?`/null-check
        // mis-discriminates Some→None. If len==0, build's input was empty.
        // if build>0 but get_node_size sees 0, the tree.clone() (hashbrown) drops the map.
        LayoutTree {
10773
            nodes: hot_nodes,
10773
            warm: warm_nodes,
10773
            cold: cold_nodes,
10773
            root: root_idx,
10773
            dom_to_layout: self
10773
                .dom_to_layout
10773
                .into_iter()
281175
                .map(|(k, v)| (k, v.into_iter().map(LayoutNodeId::new).collect()))
10773
                .collect(),
10773
            children_arena: arena,
10773
            children_offsets: offsets,
            // Populated by `generate_layout_tree` after the tree is built,
            // since the computation needs styled_dom for float/position lookup.
10773
            subtree_needs_intrinsic: Vec::new(),
        }
10773
    }
}
/// DOM ordinal per direct child of `parent` — the coordinate structural
/// previews use to route layout children (`NodePosition.child_index` space).
70
fn ordinal_map(
70
    hierarchy: &azul_core::id::NodeDataContainerRef<'_, azul_core::styled_dom::NodeHierarchyItem>,
70
    parent: NodeId,
70
) -> BTreeMap<NodeId, u32> {
70
    let mut ordinal_of = BTreeMap::new();
70
    let mut c = hierarchy.get(parent).and_then(|h| h.first_child_id(parent));
70
    let mut ord: u32 = 0;
280
    while let Some(cc) = c {
210
        ordinal_of.insert(cc, ord);
210
        ord += 1;
210
        c = hierarchy
210
            .get(cc)
210
            .and_then(azul_core::styled_dom::NodeHierarchyItem::next_sibling_id);
210
    }
70
    ordinal_of
70
}
// +spec:display-property:697082 - outer display type determines principal box's role in flow layout
// (block vs inline) +spec:display-property:0d251b - Block-level elements: display 'block',
// 'list-item', 'table' generate block-level boxes +spec:display-property:9464be - block-level vs
// block container distinction: not all block-level boxes are block containers (e.g. replaced
// elements, flex containers)
#[must_use]
649882
pub fn is_block_level(styled_dom: &StyledDom, node_id: NodeId) -> bool {
292083
    matches!(
649882
        get_display_type(styled_dom, node_id),
        LayoutDisplay::Block
            | LayoutDisplay::FlowRoot
            | LayoutDisplay::Flex
            | LayoutDisplay::Grid
            | LayoutDisplay::Table
            | LayoutDisplay::TableCaption
            | LayoutDisplay::TableRow
            | LayoutDisplay::TableRowGroup
            | LayoutDisplay::TableHeaderGroup
            | LayoutDisplay::TableFooterGroup
            | LayoutDisplay::TableCell
            | LayoutDisplay::ListItem
    )
649882
}
// +spec:display-property:23f111 - Inline-level elements: inline, inline-block, inline-table,
// inline-flex, inline-grid
/// Checks if a node is inline-level (including text nodes).
/// According to CSS spec, inline-level content includes:
///
/// - Elements with display: inline, inline-block, inline-table, inline-flex, inline-grid
/// - Text nodes
/// - Generated content
84696
fn is_inline_level(styled_dom: &StyledDom, node_id: NodeId) -> bool {
    // Text nodes are always inline-level
84696
    let node_data = &styled_dom.node_data.as_container()[node_id];
84696
    if matches!(node_data.get_node_type(), NodeType::Text(_)) {
68977
        return true;
15719
    }
    // Check the display property
14450
    matches!(
15719
        get_display_type(styled_dom, node_id),
        LayoutDisplay::Inline
            | LayoutDisplay::InlineBlock
            | LayoutDisplay::InlineTable
            | LayoutDisplay::InlineFlex
            | LayoutDisplay::InlineGrid
    )
84696
}
// +spec:display-property:c2520b - Block containers with only inline-level children establish IFC;
// mixed content gets anonymous block wrappers
/// Checks if a block container has only inline-level children.
/// According to CSS 2.2 Section 9.4.2: "An inline formatting context is established
/// by a block container box that contains no block-level boxes."
// +spec:display-property:75d642 - block container with only inline-level content establishes IFC
// +spec:display-property:c188d6 - IFC: all inline content within a containing block flows together
// as continuous text
87721
pub(crate) fn has_only_inline_children(styled_dom: &StyledDom, node_id: NodeId) -> bool {
87721
    let hierarchy = styled_dom.node_hierarchy.as_container();
87721
    let Some(node_hier) = hierarchy.get(node_id) else {
2
        return false;
    };
    // Get the first child
87719
    let mut current_child = node_hier.first_child_id(node_id);
    // If there are no children, it's not an IFC (it's empty)
87719
    if current_child.is_none() {
5772
        return false;
81947
    }
    // Check all children
152187
    while let Some(child_id) = current_child {
84680
        let is_inline = is_inline_level(styled_dom, child_id);
84680
        if !is_inline {
            // Found a block-level child
14440
            return false;
70240
        }
        // Move to next sibling
70240
        if let Some(child_hier) = hierarchy.get(child_id) {
70240
            current_child = child_hier.next_sibling_id();
70240
        } else {
            break;
        }
    }
    // All children are inline-level
67507
    true
87721
}
/// Pre-computes all CSS properties needed during layout for a single node.
///
/// This is called once per node during layout tree construction, avoiding
/// repeated style lookups during the actual layout pass (O(n) vs O(n²)).
230597
fn compute_layout_style(styled_dom: &StyledDom, dom_id: NodeId) -> ComputedLayoutStyle {
230597
    let styled_node_state = styled_dom
230597
        .styled_nodes
230597
        .as_container()
230597
        .get(dom_id)
230597
        .map(|n| n.styled_node_state)
230597
        .unwrap_or_default();
    // Get display property
230597
    let display = match get_display_property(styled_dom, Some(dom_id)) {
230597
        MultiValue::Exact(d) => d,
        MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => LayoutDisplay::Block,
    };
    // Get position property
230597
    let position = get_position(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
    // Get float property
230597
    let float = get_float(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
    // Get overflow properties
    // +spec:overflow:48890c - overflow:hidden treated as overflow:clip on replaced elements
230597
    let is_replaced = matches!(
230597
        styled_dom.node_data.as_container()[dom_id].get_node_type(),
        NodeType::Image(_) | NodeType::VirtualView
    );
230597
    let overflow_x = {
230597
        let v = get_overflow_x(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
230597
        if is_replaced && v == LayoutOverflow::Hidden {
320
            LayoutOverflow::Clip
        } else {
230277
            v
        }
    };
230597
    let overflow_y = {
230597
        let v = get_overflow_y(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
230597
        if is_replaced && v == LayoutOverflow::Hidden {
320
            LayoutOverflow::Clip
        } else {
230277
            v
        }
    };
    // Get writing mode, direction, and text-orientation
    // +spec:writing-modes:2af307 - Propagate used writing-mode from <body> to <html> root
230597
    let writing_mode = {
230597
        let own_wm = get_writing_mode(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
230597
        let nd = &styled_dom.node_data.as_container()[dom_id];
230597
        if matches!(nd.node_type, NodeType::Html) {
            // If root <html>, propagate writing-mode from first <body> child
1840
            styled_dom
1840
                .node_hierarchy
1840
                .as_container()
1840
                .get(dom_id)
1840
                .and_then(|node| node.first_child_id(dom_id))
1840
                .and_then(|child_id| {
1840
                    let child_data = &styled_dom.node_data.as_container()[child_id];
1840
                    if matches!(child_data.node_type, NodeType::Body) {
1820
                        let child_state =
1820
                            &styled_dom.styled_nodes.as_container()[child_id].styled_node_state;
1820
                        Some(
1820
                            get_writing_mode(styled_dom, child_id, child_state).unwrap_or_default(),
1820
                        )
                    } else {
20
                        None
                    }
1840
                })
1840
                .unwrap_or(own_wm)
        } else {
228757
            own_wm
        }
    };
230597
    let direction = get_direction(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
230597
    let text_orientation =
230597
        get_text_orientation(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
    // Get text-align
230597
    let text_align = get_text_align(styled_dom, dom_id, &styled_node_state).unwrap_or_default();
    // Get explicit width/height (None = auto)
230597
    let width = match get_css_width(styled_dom, dom_id, &styled_node_state) {
20382
        MultiValue::Exact(w) => Some(w),
210215
        _ => None,
    };
230597
    let height = match get_css_height(styled_dom, dom_id, &styled_node_state) {
39308
        MultiValue::Exact(h) => Some(h),
191289
        _ => None,
    };
    // Get min/max constraints
230597
    let min_width = match get_css_min_width(styled_dom, dom_id, &styled_node_state) {
4676
        MultiValue::Exact(v) => Some(v),
225921
        _ => None,
    };
230597
    let min_height = match get_css_min_height(styled_dom, dom_id, &styled_node_state) {
706
        MultiValue::Exact(v) => Some(v),
229891
        _ => None,
    };
230597
    let max_width = match get_css_max_width(styled_dom, dom_id, &styled_node_state) {
21
        MultiValue::Exact(v) => Some(v),
230576
        _ => None,
    };
230597
    let max_height = match get_css_max_height(styled_dom, dom_id, &styled_node_state) {
1
        MultiValue::Exact(v) => Some(v),
230596
        _ => None,
    };
230597
    ComputedLayoutStyle {
230597
        display,
230597
        position,
230597
        float,
230597
        overflow_x,
230597
        overflow_y,
230597
        writing_mode,
230597
        direction,
230597
        text_orientation,
230597
        width,
230597
        height,
230597
        min_width,
230597
        min_height,
230597
        max_width,
230597
        max_height,
230597
        text_align,
230597
    }
230597
}
// hash_node_data() removed — replaced by NodeDataFingerprint::compute()
/// Helper function to get element's computed font-size
777567
pub(crate) fn get_element_font_size(styled_dom: &StyledDom, dom_id: NodeId) -> f32 {
777567
    {
777567
        let _ = (0xC3_000001u32);
777567
    } // 2-arg wrapper entered
777567
    let node_state = styled_dom
777567
        .styled_nodes
777567
        .as_container()
777567
        .get(dom_id)
777567
        .map(|n| &n.styled_node_state)
777567
        .copied()
777567
        .unwrap_or_default();
777567
    {
777567
        let _ = (0xC3_000002u32);
777567
    } // after node_state (clone); next = 3-arg call
777567
    crate::solver3::getters::get_element_font_size(styled_dom, dom_id, &node_state)
777567
}
/// Helper function to get parent's computed font-size
230626
fn get_parent_font_size(styled_dom: &StyledDom, dom_id: NodeId) -> f32 {
230626
    styled_dom
230626
        .node_hierarchy
230626
        .as_container()
230626
        .get(dom_id)
230626
        .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
230626
        .map_or(DEFAULT_FONT_SIZE, |parent_id| {
221724
            get_element_font_size(styled_dom, parent_id)
221724
        })
230626
}
/// Helper function to get root element's font-size
274645
pub(crate) fn get_root_font_size(styled_dom: &StyledDom) -> f32 {
    // Root is always NodeId(0) in Azul
274645
    get_element_font_size(styled_dom, NodeId::new(0))
274645
}
/// Create a `ResolutionContext` for a given node
230615
fn create_resolution_context(
230615
    styled_dom: &StyledDom,
230615
    dom_id: NodeId,
230615
    containing_block_size: Option<PhysicalSize>,
230615
    viewport_size: LogicalSize,
230615
) -> ResolutionContext {
230615
    {
230615
        let _ = (0xC1_000001u32);
230615
    } // create_resolution_context entered
230615
    let element_font_size = get_element_font_size(styled_dom, dom_id);
230615
    {
230615
        let _ = (0xC1_000002u32);
230615
    } // after get_element_font_size
230615
    let parent_font_size = get_parent_font_size(styled_dom, dom_id);
230615
    {
230615
        let _ = (0xC1_000003u32);
230615
    } // after get_parent_font_size
230615
    let root_font_size = get_root_font_size(styled_dom);
230615
    {
230615
        let _ = (0xC1_000004u32);
230615
    } // after get_root_font_size
230615
    ResolutionContext {
230615
        vertical_writing_mode: false,
230615
        element_font_size,
230615
        parent_font_size,
230615
        root_font_size,
230615
        // +spec:box-model:ec6466 - percentage margins/padding resolve to 0 when containing block is
230615
        // unknown (intrinsic sizing), breaking cyclic dependencies per css-sizing-3 §5.2.1
230615
        containing_block_size: containing_block_size.unwrap_or(PhysicalSize::new(0.0, 0.0)),
230615
        element_size: None, // Not yet laid out
230615
        viewport_size: PhysicalSize::new(viewport_size.width, viewport_size.height),
230615
    }
230615
}
/// Result of collecting box properties from the styled DOM.
struct CollectedBoxProps {
    unresolved: crate::solver3::geometry::UnresolvedBoxProps,
    resolved: BoxProps,
}
/// Collects box properties from the styled DOM and returns both unresolved and resolved forms.
///
/// The unresolved form stores the raw CSS values for later re-resolution when
/// the containing block size is known. The resolved form is an initial resolution
/// using `viewport_size` for viewport-relative units.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
230604
fn collect_box_props(
230604
    styled_dom: &StyledDom,
230604
    dom_id: NodeId,
230604
    debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
230604
    viewport_size: LogicalSize,
230604
) -> CollectedBoxProps {
    use azul_css::props::style::border::BorderStyle;
    use crate::solver3::geometry::{UnresolvedBoxProps, UnresolvedEdge, UnresolvedMargin};
    #[allow(clippy::wildcard_imports)]
    // widget/render module pulls in the css property/value types it builds with
    use crate::solver3::getters::*;
    // before create_node step A is the diverging call.
230604
    {
230604
        let _ = (0xC0_000001u32);
230604
    } // entered
230604
    let node_data = &styled_dom.node_data.as_container()[dom_id];
    // Get styled node state
230604
    let node_state = styled_dom
230604
        .styled_nodes
230604
        .as_container()
230604
        .get(dom_id)
230604
        .map(|n| &n.styled_node_state)
230604
        .copied()
230604
        .unwrap_or_default();
230604
    {
230604
        let _ = (0xC0_000002u32);
230604
    } // after node_state (clone)
    // Create resolution context for this element
    // Note: containing_block_size is None here because we don't have it yet
    // This is fine for initial resolution - will be re-resolved during layout
230604
    let context = create_resolution_context(styled_dom, dom_id, None, viewport_size);
230604
    {
230604
        let _ = (0xC0_000003u32);
230604
    } // after create_resolution_context
    // Read margin values from styled_dom
230604
    let margin_top_mv = get_css_margin_top(styled_dom, dom_id, &node_state);
230604
    {
230604
        let _ = (0xC0_000004u32);
230604
    } // after get_css_margin_top
230604
    let margin_right_mv = get_css_margin_right(styled_dom, dom_id, &node_state);
230604
    let margin_bottom_mv = get_css_margin_bottom(styled_dom, dom_id, &node_state);
230604
    let margin_left_mv = get_css_margin_left(styled_dom, dom_id, &node_state);
    // Convert MultiValue to UnresolvedMargin
922416
    let to_unresolved_margin = |mv: &MultiValue<PixelValue>| -> UnresolvedMargin {
922416
        match mv {
60
            MultiValue::Auto => UnresolvedMargin::Auto,
922352
            MultiValue::Exact(pv) => UnresolvedMargin::Length(*pv),
4
            _ => UnresolvedMargin::Zero,
        }
922416
    };
    // Build unresolved margins
230604
    let unresolved_margin = UnresolvedEdge {
230604
        top: to_unresolved_margin(&margin_top_mv),
230604
        right: to_unresolved_margin(&margin_right_mv),
230604
        bottom: to_unresolved_margin(&margin_bottom_mv),
230604
        left: to_unresolved_margin(&margin_left_mv),
230604
    };
230604
    {
230604
        let _ = (0xC0_000005u32);
230604
    } // after margin block
    // Read padding values
230604
    let padding_top_mv = get_css_padding_top(styled_dom, dom_id, &node_state);
230604
    let padding_right_mv = get_css_padding_right(styled_dom, dom_id, &node_state);
230604
    let padding_bottom_mv = get_css_padding_bottom(styled_dom, dom_id, &node_state);
230604
    let padding_left_mv = get_css_padding_left(styled_dom, dom_id, &node_state);
    // Convert MultiValue to PixelValue (default to 0px)
1044190
    let to_pixel_value = |mv: MultiValue<PixelValue>| -> PixelValue {
1044190
        match mv {
1044178
            MultiValue::Exact(pv) => pv,
12
            _ => PixelValue::const_px(0),
        }
1044190
    };
    // Build unresolved padding
230604
    let unresolved_padding = UnresolvedEdge {
230604
        top: to_pixel_value(padding_top_mv),
230604
        right: to_pixel_value(padding_right_mv),
230604
        bottom: to_pixel_value(padding_bottom_mv),
230604
        left: to_pixel_value(padding_left_mv),
230604
    };
230604
    {
230604
        let _ = (0xC0_000056u32);
230604
    } // after padding getters+values, before get_display_type
    // +spec:table-layout:038f9d - padding does not apply to table-row-group, table-header-group,
    // table-footer-group, table-row, table-column-group, table-column Non-cell internal table
    // elements (rows, row groups, columns, column groups) do not have padding. 0xC0_57<dt> the
    // CALL returned (dt = LayoutDisplay discriminant) and the MATCH below diverges; if it stays
    // 0x56, get_display_type (the enum extraction) itself diverges. M12.7 NOTE:
    // get_display_type RETURNS a valid dt here (captured =2), but the code immediately after
    // diverges — and replacing the `match` below with a branchless bitmask test did NOT help
    // (so it's NOT the multi-way-branch codegen). So the get_display_type CALL corrupts the
    // caller frame / control flow (same class as create_node's return 0→48704), specific to
    // ENUM-returning getters (pixel getters like get_css_margin_* lift fine). Remill-level. The
    // match is kept (original).
230604
    let unresolved_padding = match get_display_type(styled_dom, dom_id) {
        LayoutDisplay::TableRow
        | LayoutDisplay::TableRowGroup
        | LayoutDisplay::TableHeaderGroup
        | LayoutDisplay::TableFooterGroup
        | LayoutDisplay::TableColumn
428
        | LayoutDisplay::TableColumnGroup => UnresolvedEdge {
428
            top: PixelValue::const_px(0),
428
            right: PixelValue::const_px(0),
428
            bottom: PixelValue::const_px(0),
428
            left: PixelValue::const_px(0),
428
        },
230176
        _ => unresolved_padding,
    };
230604
    {
230604
        let _ = (0xC0_000006u32);
230604
    } // after padding block
    // Read border values
230604
    let border_top_mv = get_css_border_top_width(styled_dom, dom_id, &node_state);
230604
    let border_right_mv = get_css_border_right_width(styled_dom, dom_id, &node_state);
230604
    let border_bottom_mv = get_css_border_bottom_width(styled_dom, dom_id, &node_state);
230604
    let border_left_mv = get_css_border_left_width(styled_dom, dom_id, &node_state);
    // +spec:box-model:17c0e0 - computed border-width is 0 if border-style is none or hidden
    // +spec:box-model:5d2b66 - border-style none/hidden means no border
    // CSS 2.2 §8.5.1: "Computed value: absolute length; '0' if the border style is 'none' or
    // 'hidden'"
922416
    let style_zeroes_width = |s: BorderStyle| matches!(s, BorderStyle::None | BorderStyle::Hidden);
    // Read border styles to check if widths should be zeroed.
    // FAST PATH: compact cache returns styles directly for normal state — no
    // cascade walks. Prior code here did 4 cascade walks × 586 nodes.
230604
    let (bs_top, bs_right, bs_bottom, bs_left) = {
230604
        let cache_ptr = &styled_dom.css_property_cache.ptr;
230604
        if node_state.is_normal() {
230600
            cache_ptr.compact_cache.as_ref().map_or_else(
1
                || {
                    (
1
                        cache_ptr
1
                            .get_border_top_style(node_data, &dom_id, &node_state)
1
                            .and_then(|v| v.get_property())
1
                            .map_or(BorderStyle::None, |s| s.inner),
1
                        cache_ptr
1
                            .get_border_right_style(node_data, &dom_id, &node_state)
1
                            .and_then(|v| v.get_property())
1
                            .map_or(BorderStyle::None, |s| s.inner),
1
                        cache_ptr
1
                            .get_border_bottom_style(node_data, &dom_id, &node_state)
1
                            .and_then(|v| v.get_property())
1
                            .map_or(BorderStyle::None, |s| s.inner),
1
                        cache_ptr
1
                            .get_border_left_style(node_data, &dom_id, &node_state)
1
                            .and_then(|v| v.get_property())
1
                            .map_or(BorderStyle::None, |s| s.inner),
                    )
1
                },
230599
                |cc| {
230599
                    let idx = dom_id.index();
230599
                    (
230599
                        cc.get_border_top_style(idx),
230599
                        cc.get_border_right_style(idx),
230599
                        cc.get_border_bottom_style(idx),
230599
                        cc.get_border_left_style(idx),
230599
                    )
230599
                },
            )
        } else {
            (
4
                cache_ptr
4
                    .get_border_top_style(node_data, &dom_id, &node_state)
4
                    .and_then(|v| v.get_property())
4
                    .map_or(BorderStyle::None, |s| s.inner),
4
                cache_ptr
4
                    .get_border_right_style(node_data, &dom_id, &node_state)
4
                    .and_then(|v| v.get_property())
4
                    .map_or(BorderStyle::None, |s| s.inner),
4
                cache_ptr
4
                    .get_border_bottom_style(node_data, &dom_id, &node_state)
4
                    .and_then(|v| v.get_property())
4
                    .map_or(BorderStyle::None, |s| s.inner),
4
                cache_ptr
4
                    .get_border_left_style(node_data, &dom_id, &node_state)
4
                    .and_then(|v| v.get_property())
4
                    .map_or(BorderStyle::None, |s| s.inner),
            )
        }
    };
    // Build unresolved border, zeroing width when style is none or hidden
230604
    let unresolved_border = UnresolvedEdge {
230604
        top: if style_zeroes_width(bs_top) {
204523
            PixelValue::const_px(0)
        } else {
26081
            to_pixel_value(border_top_mv)
        },
230604
        right: if style_zeroes_width(bs_right) {
199413
            PixelValue::const_px(0)
        } else {
31191
            to_pixel_value(border_right_mv)
        },
230604
        bottom: if style_zeroes_width(bs_bottom) {
193523
            PixelValue::const_px(0)
        } else {
37081
            to_pixel_value(border_bottom_mv)
        },
230604
        left: if style_zeroes_width(bs_left) {
203183
            PixelValue::const_px(0)
        } else {
27421
            to_pixel_value(border_left_mv)
        },
    };
230604
    {
230604
        let _ = (0xC0_000007u32);
230604
    } // after border block (incl is_normal/compact_cache fast-path)
    // +spec:box-model:8538a9 - Internal table elements do not have margins (CSS 2.2 §17.5)
    // "These boxes have content and borders and cells have padding as well.
    //  Internal table elements do not have margins."
    // +spec:box-model:b4923a - Internal table elements do not have margins (CSS 2.2 § 17.5)
    // +spec:box-model:0a9f8e - Internal table elements do not have margins (CSS 2.2 § 17.5)
230604
    let display_type = get_display_type(styled_dom, dom_id);
230604
    let unresolved_margin = match display_type {
        LayoutDisplay::TableRow
        | LayoutDisplay::TableRowGroup
        | LayoutDisplay::TableHeaderGroup
        | LayoutDisplay::TableFooterGroup
        | LayoutDisplay::TableCell
        | LayoutDisplay::TableColumn
1374
        | LayoutDisplay::TableColumnGroup => UnresolvedEdge {
1374
            top: UnresolvedMargin::Zero,
1374
            right: UnresolvedMargin::Zero,
1374
            bottom: UnresolvedMargin::Zero,
1374
            left: UnresolvedMargin::Zero,
1374
        },
        // +spec:box-model:1197a5 - height property does not apply to non-replaced inline elements;
        // vertical margins zeroed +spec:replaced-elements:f07118 - non-replaced elements
        // have rendering dictated by CSS model "These properties apply to all elements, but
        // vertical margins will not have  any effect on non-replaced inline elements."
        LayoutDisplay::Inline => {
77735
            let is_replaced = matches!(
77735
                node_data.get_node_type(),
                NodeType::Image(_) | NodeType::VirtualView
            );
77735
            if is_replaced {
                unresolved_margin
            } else {
77735
                UnresolvedEdge {
77735
                    top: UnresolvedMargin::Zero,
77735
                    bottom: UnresolvedMargin::Zero,
77735
                    ..unresolved_margin
77735
                }
            }
        }
151495
        _ => unresolved_margin,
    };
    // Build the UnresolvedBoxProps
230604
    let unresolved = UnresolvedBoxProps {
230604
        margin: unresolved_margin,
230604
        padding: unresolved_padding,
230604
        border: unresolved_border,
        // Percentage basis axis for margin/padding (writing-modes-4 §7.2).
230534
        vertical_writing_mode: matches!(
230604
            get_writing_mode(styled_dom, dom_id, &node_state),
            MultiValue::Exact(
                azul_css::props::layout::wrapping::LayoutWritingMode::VerticalRl
                    | azul_css::props::layout::wrapping::LayoutWritingMode::VerticalLr
            )
        ),
    };
    // Create initial resolution params (with viewport as containing block for now)
230604
    let params = crate::solver3::geometry::ResolutionParams {
230604
        containing_block: viewport_size,
230604
        viewport_size,
230604
        element_font_size: context.parent_font_size,
230604
        root_font_size: context.root_font_size,
230604
    };
    // Resolve to get initial box_props
230604
    let resolved = unresolved.resolve(&params);
230604
    if let Some(msgs) = debug_messages.as_mut() {
214723
        msgs.push(LayoutDebugMessage::box_props(format!(
214723
            "[BOX] node[{}] {:?} pad=[{:.1} {:.1} {:.1} {:.1}] mar=[{:.1} {:.1} {:.1} {:.1}] \
214723
             bor=[{:.1} {:.1} {:.1} {:.1}]",
214723
            dom_id.index(),
            node_data.node_type,
            resolved.padding.top,
            resolved.padding.right,
            resolved.padding.bottom,
            resolved.padding.left,
            resolved.margin.top,
            resolved.margin.right,
            resolved.margin.bottom,
            resolved.margin.left,
            resolved.border.top,
            resolved.border.right,
            resolved.border.bottom,
            resolved.border.left,
        )));
214723
        let has_vh = match &unresolved_margin.top {
142347
            UnresolvedMargin::Length(pv) => pv.metric == azul_css::props::basic::SizeMetric::Vh,
72376
            _ => false,
        };
214723
        if has_vh || resolved.margin.top > 0.0 || resolved.margin.left > 0.0 {
22465
            msgs.push(LayoutDebugMessage::box_props(format!(
22465
                "NodeId {:?} ({:?}): unresolved_margin_top={:?}, resolved_margin_top={:.2}, \
22465
                 viewport_size={:?}",
22465
                dom_id,
22465
                node_data.node_type,
22465
                unresolved_margin.top,
22465
                resolved.margin.top,
22465
                viewport_size
22465
            )));
192258
        }
214723
        msgs.push(LayoutDebugMessage::box_props(format!(
214723
            "NodeId {:?} ({:?}): margin_auto: left={}, right={}, top={}, bottom={} | \
214723
             margin_left={:?}",
            dom_id,
            node_data.node_type,
            resolved.margin_auto.left,
            resolved.margin_auto.right,
            resolved.margin_auto.top,
            resolved.margin_auto.bottom,
            unresolved_margin.left
        )));
214723
        if matches!(node_data.node_type, NodeType::Body) {
6022
            msgs.push(LayoutDebugMessage::box_props(format!(
6022
                "Body margin resolved: top={:.2}, right={:.2}, bottom={:.2}, left={:.2}",
6022
                resolved.margin.top,
6022
                resolved.margin.right,
6022
                resolved.margin.bottom,
6022
                resolved.margin.left
6022
            )));
208701
        }
15881
    }
230604
    CollectedBoxProps {
230604
        unresolved,
230604
        resolved,
230604
    }
230604
}
/// CSS 2.2 Section 17.2.1 - Anonymous box generation, Stage 1:
///
/// "Remove all irrelevant boxes. These are boxes that do not contain table-related boxes
/// and do not themselves have 'display' set to a table-related value. In this context,
/// 'irrelevant boxes' means anonymous inline boxes that contain only white space."
///
/// Checks if a DOM node is whitespace-only text (for table anonymous box generation).
/// Returns true if the node is a text node containing only whitespace characters
/// that would be collapsed away by the white-space property.
// according to the 'white-space' property does not generate any anonymous inline boxes
// (CSS2§9.2.2.1)
#[must_use]
296196
pub fn is_whitespace_only_text(styled_dom: &StyledDom, node_id: NodeId) -> bool {
296196
    let binding = styled_dom.node_data.as_container();
296196
    let node_data = binding.get(node_id);
296196
    if let Some(data) = node_data {
296194
        if let NodeType::Text(text) = data.get_node_type() {
            // Check if the text contains only CSS document white space characters
            // Per CSS Text 3 §4.1: document white space = U+0020, U+0009, segment breaks
40875
            if !text
40875
                .chars()
73621
                .all(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0C'))
            {
17914
                return false;
22961
            }
            // Per CSS2§9.2.2.1: "White space content that would subsequently be
            // collapsed away according to the 'white-space' property does not
            // generate any anonymous inline boxes."
            // For white-space: pre / pre-wrap / break-spaces, whitespace is preserved
            // and should NOT be treated as collapsible.
22961
            let white_space = styled_dom.styled_nodes.as_container().get(node_id).map_or(
22961
                StyleWhiteSpace::Normal,
22961
                |n| match get_white_space_property(styled_dom, node_id, &n.styled_node_state) {
22961
                    MultiValue::Exact(ws) => ws,
                    _ => StyleWhiteSpace::Normal,
22961
                },
            );
22961
            return match white_space {
                // These values collapse whitespace — whitespace-only text is collapsible
                StyleWhiteSpace::Normal | StyleWhiteSpace::Nowrap | StyleWhiteSpace::PreLine => {
22938
                    true
                }
                // These values preserve whitespace — whitespace-only text is NOT collapsible
                StyleWhiteSpace::Pre | StyleWhiteSpace::PreWrap | StyleWhiteSpace::BreakSpaces => {
23
                    false
                }
            };
255319
        }
2
    }
255321
    false
296196
}
/// Anonymous box generation: is this node a whitespace-only text child that
/// must NOT generate a box for this kind of parent?
///
/// - CSS 2.2 section 17.2.1 (tables): whitespace between table structural elements is "irrelevant"
///   and generates nothing.
/// - css-flexbox-1 section 4: "an anonymous flex item that contains only white space is not
///   rendered".
/// - css-grid-1 section 6: same rule for grid items.
///
/// Without the flex/grid arms, every newline between `<div>` children of a
/// grid container became an anonymous grid ITEM, occupying auto-placement
/// cells: grid-minmax-fr-001 rendered its 9 items in a checkerboard with
/// phantom gaps and overflow rows.
42
fn should_skip_for_table_structure(
42
    styled_dom: &StyledDom,
42
    node_id: NodeId,
42
    parent_display: LayoutDisplay,
42
) -> bool {
18
    matches!(
42
        parent_display,
        LayoutDisplay::Table
            | LayoutDisplay::InlineTable
            | LayoutDisplay::TableRowGroup
            | LayoutDisplay::TableHeaderGroup
            | LayoutDisplay::TableFooterGroup
            | LayoutDisplay::TableRow
            | LayoutDisplay::Grid
            | LayoutDisplay::InlineGrid
            | LayoutDisplay::Flex
            | LayoutDisplay::InlineFlex
24
    ) && is_whitespace_only_text(styled_dom, node_id)
42
}
/// Returns true if the given display type is a "proper table child" of a table/inline-table box.
/// Per CSS 2.2 §17.2.1, proper table children are: table-row-group, table-header-group,
/// table-footer-group, table-row, table-column-group, table-column, table-caption.
27
const fn is_proper_table_child(display: LayoutDisplay) -> bool {
19
    matches!(
27
        display,
        LayoutDisplay::TableRowGroup
            | LayoutDisplay::TableHeaderGroup
            | LayoutDisplay::TableFooterGroup
            | LayoutDisplay::TableRow
            | LayoutDisplay::TableColumnGroup
            | LayoutDisplay::TableColumn
            | LayoutDisplay::TableCaption
    )
27
}
// Determines the display type of a node based on its tag and CSS properties.
// Delegates to getters::get_display_property which uses the compact cache fast path.
// M12.7 ROOT: get_display_type (and every layout enum getter) mis-lifts to wasm via the
// remill enum-return/decode path — the geometry-chain blocker. FOUR Rust workarounds all
// FAILED to advance (none reached collect_box_props past get_display_type):
//   1. skip the get_css_property! enum compact-cache fast path  → no change
//   2. replace the LayoutDisplay `match` with a branchless bitmask → no change
//   3. #[inline(never)] (wrap the call w/ enforce_sp_preservation) → made it diverge earlier
//   4. bypass MultiValue<LayoutDisplay> by reading cc.get_display() directly → diverges earlier
// So it is NOT the match codegen, NOT the MultiValue wrapper, NOT a frame/SP issue — it is
// the lift of a fn RETURNING a small fieldless enum (LayoutDisplay) corrupting control flow
// (pixel/i16-returning getters lift fine). Needs the remill m12-q-reg-x8-sret fork's
// enum-return handling — not fixable in Rust. (Original kept.)
#[must_use]
2273526
pub fn get_display_type(styled_dom: &StyledDom, node_id: NodeId) -> LayoutDisplay {
    use crate::solver3::getters::get_display_property;
    // A `<transient-window>` takes part in its PARENT's layout only while it
    // is docked INLINE (`dock="inline"`, not torn off - see
    // `transient::TransientDocks`). Otherwise it is nothing here: closed, it
    // is nothing at all; open as a popup or torn off, its subtree is laid out
    // as the root of its OWN window, and laying it out here as well would
    // render the content twice. `display: none` is the one choke point every
    // child-collection honours, which is why it is decided here and not in
    // each of them.
2273526
    if let Some(NodeType::TransientWindow(cfg)) = styled_dom
2273526
        .node_data
2273526
        .as_container()
2273526
        .get(node_id)
2273526
        .map(NodeData::get_node_type)
    {
        if !transient_node_is_inline(node_id, cfg) {
            return LayoutDisplay::None;
        }
2273526
    }
2273526
    get_display_property(styled_dom, Some(node_id)).unwrap_or(LayoutDisplay::Inline)
2273526
}
// ---------------------------------------------------------------------------
// Inline-docked transient windows: the per-pass dock set
// ---------------------------------------------------------------------------
thread_local! {
    /// The docking state of the layout pass running on this thread (set by
    /// [`with_transient_docks`] for exactly the duration of a solver call).
    /// `None` outside a pass: nodes are then judged by their config alone.
    static TRANSIENT_DOCKS: core::cell::RefCell<Option<crate::transient::TransientDocks>> =
        const { core::cell::RefCell::new(None) };
}
/// Run `f` with `docks` as the current pass's docking state. Every solver
/// entry (`LayoutWindow`'s `layout_document` call) wraps itself in this so
/// the 25 `get_display_type` call sites and the five child-collection sites
/// agree on which `<transient-window>` is inline and where it is grafted.
/// Nests safely (the previous value is restored) and is per thread, so
/// parallel headless layouts do not see each other's docks.
8460
pub fn with_transient_docks<R>(
8460
    docks: crate::transient::TransientDocks,
8460
    f: impl FnOnce() -> R,
8460
) -> R {
8460
    let previous = TRANSIENT_DOCKS.with(|d| d.replace(Some(docks)));
    struct Restore(Option<crate::transient::TransientDocks>);
    impl Drop for Restore {
8460
        fn drop(&mut self) {
8460
            let prev = self.0.take();
8460
            TRANSIENT_DOCKS.with(|d| *d.borrow_mut() = prev);
8460
        }
    }
8460
    let _restore = Restore(previous);
8460
    f()
8460
}
/// Is the `<transient-window>` `node` laid out inline this pass?
fn transient_node_is_inline(
    node: NodeId,
    cfg: &azul_core::transient::TransientWindowConfig,
) -> bool {
    TRANSIENT_DOCKS.with(|d| match d.borrow().as_ref() {
        Some(docks) => docks.is_inline(node, cfg),
        None => cfg.dock == azul_core::transient::TransientDock::Inline && cfg.open && !cfg.torn,
    })
}
/// The children `parent` lays out, in order: its DOM children, minus any
/// inline transient window that was dropped onto another zone, plus the
/// inline transient windows dropped onto `parent` itself (appended last).
/// THE child-collection helper: every site that used to iterate
/// `az_children` directly goes through here, so a grafted panel is a child
/// of its zone for block, flex, grid, table and `display: contents`
/// processing alike.
#[must_use]
281177
pub fn layout_children(styled_dom: &StyledDom, parent: NodeId) -> Vec<NodeId> {
281177
    let hierarchy = styled_dom.node_hierarchy.as_container();
281177
    if hierarchy.get(parent).is_none() {
2
        return Vec::new(); // an id past the arena: no children, no panic
281175
    }
281175
    TRANSIENT_DOCKS.with(|d| {
281175
        let borrow = d.borrow();
281175
        match borrow.as_ref() {
251323
            Some(docks) if !docks.inline.is_empty() => {
                let mut out: Vec<NodeId> = parent
                    .az_children(&hierarchy)
                    .filter(|c| !docks.moved_away_from(*c, parent))
                    .collect();
                out.extend(docks.grafted_onto(parent, styled_dom));
                out
            }
281175
            _ => parent.az_children(&hierarchy).collect(),
        }
281175
    })
281177
}
// +spec:display-contents:95faa5 - blockification has no effect on none/contents (other => other)
// +spec:display-property:f68848 - Automatic box type transformations: blockification of computed
// display values
/// Blockify a display type per CSS Display 3 §2.7.
// +spec:display-property:760c5f - blockification sets computed outer display type to block
/// +spec:display-property:d50f70 - blockification affects computed values, determining principal
/// box type only // +spec:inline-block:692e44 - blockification of inline-block per CSS2
/// compatibility
// +spec:display-property:c3aca2 - inline-block blockifies to block, not flow-root
// +spec:display-property:ee2d65 - blockification of inline-level display types (CSS Display 3 §2.7)
// +spec:display-property:e4a8b7 - layout-internal boxes blockified to flow (block container)
/// CSS Flexbox §3: flex items with table-internal display values
/// (table-cell, table-row, table-row-group, table-header-group, table-footer-group,
/// table-column, table-column-group, table-caption) are blockified to display:block
/// before anonymous table box generation can occur. E.g. two consecutive
/// display:table-cell flex items become two separate display:block flex items.
325
fn blockify_flex_item_if_table_internal(nodes: &mut [LayoutNode], node_idx: usize) {
325
    if let Some(node) = nodes.get_mut(node_idx) {
321
        let is_table_internal = matches!(
321
            node.formatting_context,
            FormattingContext::TableCell
                | FormattingContext::TableRow
                | FormattingContext::TableRowGroup
                | FormattingContext::TableColumnGroup
                | FormattingContext::TableCaption
                | FormattingContext::Table
        );
321
        if is_table_internal {
6
            node.formatting_context = FormattingContext::Block {
6
                establishes_new_context: true,
6
            };
315
        }
4
    }
325
}
/// Returns true if the node is a replaced element per CSS Display 3 Appendix B.
/// Replaced elements (img, canvas, embed, object, audio, video, input, textarea,
/// select, br, wbr, meter, progress, virtual views) cannot be un-boxed by
/// `display: contents` and always establish an independent formatting context.
748671
pub(crate) const fn is_replaced_element(node_data: &NodeData) -> bool {
748020
    matches!(
748671
        node_data.get_node_type(),
        NodeType::Image(_)
            | NodeType::VirtualView
            | NodeType::Br
            | NodeType::Wbr
            | NodeType::Meter
            | NodeType::Progress
            | NodeType::Canvas
            | NodeType::Embed
            | NodeType::Object
            | NodeType::Audio
            | NodeType::Video
            | NodeType::Input
            | NodeType::TextArea
            | NodeType::Select
    )
748671
}
// +spec:display-property:285fe7 - block box establishing a BFC (block-level block container with
// new BFC)
/// **Corrected:** Checks for all conditions that create a new Block Formatting Context.
/// A BFC contains floats and prevents margin collapse.
20618
fn establishes_new_block_formatting_context(styled_dom: &StyledDom, node_id: NodeId) -> bool {
20618
    let display = get_display_type(styled_dom, node_id);
20409
    if matches!(
20618
        display,
        LayoutDisplay::InlineBlock
            | LayoutDisplay::TableCell
            | LayoutDisplay::TableCaption
            | LayoutDisplay::FlowRoot
    ) {
209
        return true;
20409
    }
20409
    if let Some(styled_node) = styled_dom.styled_nodes.as_container().get(node_id) {
        // Only an EXPLICIT overflow of hidden/scroll/auto establishes a BFC. The
        // initial value is `visible` (no BFC), so an unset overflow — which the
        // slow cascade path returns as the `MultiValue::Auto` "not set" sentinel —
        // must NOT trigger one (`!is_visible_or_clip()` wrongly did, since the
        // sentinel is neither visible nor clip).
20409
        let overflow_x = get_overflow_x(styled_dom, node_id, &styled_node.styled_node_state);
20409
        let overflow_y = get_overflow_y(styled_dom, node_id, &styled_node.styled_node_state);
20409
        if overflow_x.establishes_bfc() || overflow_y.establishes_bfc() {
2068
            return true;
18341
        }
18341
        let position = get_position(styled_dom, node_id, &styled_node.styled_node_state);
18341
        if position.is_absolute_or_fixed() {
1233
            return true;
17108
        }
17108
        let float = get_float(styled_dom, node_id, &styled_node.styled_node_state);
17108
        if !float.is_none() {
252
            return true;
16856
        }
    }
    // CSS Writing Modes 4 § 3.2: block container with different writing-mode than parent
    // establishes BFC
16856
    if let Some(styled_node) = styled_dom.styled_nodes.as_container().get(node_id) {
16856
        let hierarchy = styled_dom.node_hierarchy.as_container();
16856
        if let Some(parent_dom_id) = hierarchy[node_id].parent_id() {
10137
            let parent_state =
10137
                &styled_dom.styled_nodes.as_container()[parent_dom_id].styled_node_state;
10137
            let child_wm = get_writing_mode(styled_dom, node_id, &styled_node.styled_node_state)
10137
                .unwrap_or_default();
10137
            let parent_wm =
10137
                get_writing_mode(styled_dom, parent_dom_id, parent_state).unwrap_or_default();
10137
            if child_wm != parent_wm {
10
                return true;
10127
            }
6719
        }
    }
    // +spec:replaced-elements:4f494d - replaced elements always establish an independent formatting
    // context
16846
    let node_data = &styled_dom.node_data.as_container()[node_id];
16846
    if is_replaced_element(node_data) {
1
        return true;
16845
    }
    // The root element (<html>) also establishes a BFC.
16845
    if styled_dom.root.into_crate_internal() == Some(node_id) {
6719
        return true;
10126
    }
10126
    false
20618
}
// +spec:display-property:0d93f1 - maps display value to box generation (principal box, none, or
// contents)
/// Like `determine_formatting_context`, but uses an explicit (possibly blockified) display type
/// instead of reading it from the DOM. Used when blockification changes the display.
// +spec:display-property:80f43f - inner display type defines formatting context for non-replaced
// elements +spec:display-property:46e71c - Maps outer display (block/inline) and inner display
// (flow/flow-root/table/flex/grid) to FormattingContext +spec:display-property:aa582d - maps
// display types to formatting contexts (inline-level, block-level, atomic inline, block container)
#[allow(clippy::match_same_arms)]
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
// merge)
/// A CHILDLESS block that is (or sits inside) a `contenteditable` editing host
/// still establishes an inline formatting context.
///
/// `layout_ifc` keeps ONE line box — the editing-host strut — for an IFC root
/// with no inline content that is editable: the line the caret stands on, the
/// height `display_list::empty_editable_caret_rect` paints into, and the box a
/// click has to land in. A block with NO CHILDREN AT ALL never reached that
/// code, because `has_only_inline_children` answers false for "no children"
/// (an empty box is neither inline nor block content), so the box became a
/// Block FC and collapsed to zero height.
///
/// A brand-new document is exactly one such box: an empty `<p>` inside the
/// editable content root. With no line box there was nothing to click, nothing
/// to paint a caret on, and no way to start typing — you could only get a
/// caret into a document that already had text in it.
///
/// Non-editable empty blocks are untouched: they keep collapsing to nothing.
20210
fn is_empty_editing_host_line(styled_dom: &StyledDom, node_id: NodeId) -> bool {
20210
    let hierarchy = styled_dom.node_hierarchy.as_container();
20210
    let has_children = hierarchy
20210
        .get(node_id)
20210
        .and_then(|h| h.first_child_id(node_id))
20210
        .is_some();
20210
    !has_children && crate::solver3::getters::is_node_contenteditable_inherited(styled_dom, node_id)
20210
}
176106
fn determine_formatting_context_for_display(
176106
    styled_dom: &StyledDom,
176106
    node_id: NodeId,
176106
    display_type: LayoutDisplay,
176106
) -> FormattingContext {
176106
    let node_data = &styled_dom.node_data.as_container()[node_id];
176106
    if matches!(node_data.get_node_type(), NodeType::Text(_)) {
        // [g147h az-web-lift DIAG] CONSTANT marker of the COMPUTED FC per DOM node_id
        // (0x60B60+slot), written WITHOUT reading the stored field. 1=text→Inline,
        // 2=block-with-inline→Inline, 4=Block. For the divs (node_id 1,3): 2 ⇒ computed
        // Inline correctly (bug is store/clone/read); 4 ⇒ has_only_inline_children
        // mis-lifted to false (computed Block).
        #[cfg(feature = "web_lift")]
        unsafe {
            crate::az_mark(
                (0x60B60 + (node_id.index() & 7) * 4) as u32,
                (0xC0DE0001) as u32,
            );
        }
5623
        return FormattingContext::Inline;
170483
    }
    // +spec:display-property:2a8d62 - block containers with inline-level content establish an IFC
170483
    match display_type {
        // +spec:display-property:37bcf3 - inline outer display type generates an inline box
        // +spec:display-property:30a935 - outer display without inner defaults to flow
        // (block/inline both use flow context)
1812
        LayoutDisplay::Inline => FormattingContext::Inline,
        // +spec:block-formatting-context:97b03b - flow-root always establishes a new BFC;
        // block/list-item may establish one based on other conditions
        // +spec:display-property:0bac26 - list-item limited to flow layout inner types
        // (block/flow-root) +spec:display-property:0beffc - block container with only
        // inline children establishes IFC +spec:display-property:7c49c1 - block container
        // with only inline children establishes an IFC +spec:display-property:90ba2a -
        // flow-root always establishes a new BFC
4
        LayoutDisplay::FlowRoot => FormattingContext::Block {
4
            establishes_new_context: true,
4
        },
        LayoutDisplay::Block | LayoutDisplay::ListItem => {
            // A REPLACED element is never a block *container*: its content is the
            // replaced object (an image, a video, a canvas), not a flow of boxes,
            // so it cannot establish an IFC no matter what its children look like.
            // azul lets a replaced element carry overlay children — the frontpage
            // `opengl` example composits a `Button` over its canvas — and they are
            // laid out by an interior run, not by an inline formatting context.
            //
            // Without this guard the classification depended on something entirely
            // unrelated: an `<img>` keeps `display: inline-block` (and so an
            // independent FC) in normal flow, but as a FLEX ITEM it is blockified
            // to `Block`, fell into the branch below, and became `Inline`. Its
            // overlay child was then painted twice — once as an inline shape of
            // that bogus IFC and once by the ordinary node walk — and the interior
            // run dropped the child's margin, so the two copies disagreed about
            // where the child was.
88250
            if !is_replaced_element(node_data)
87716
                && (has_only_inline_children(styled_dom, node_id)
20210
                    || is_empty_editing_host_line(styled_dom, node_id))
            {
                #[cfg(feature = "web_lift")]
                unsafe {
                    crate::az_mark(
                        (0x60B60 + (node_id.index() & 7) * 4) as u32,
                        (0xC0DE0002) as u32,
                    );
                }
67646
                FormattingContext::Inline
            } else {
                #[cfg(feature = "web_lift")]
                unsafe {
                    crate::az_mark(
                        (0x60B60 + (node_id.index() & 7) * 4) as u32,
                        (0xC0DE0004) as u32,
                    );
                }
20604
                FormattingContext::Block {
20604
                    establishes_new_context: establishes_new_block_formatting_context(
20604
                        styled_dom, node_id,
20604
                    ),
20604
                }
            }
        }
16316
        LayoutDisplay::InlineBlock => FormattingContext::InlineBlock,
        // +spec:display-property:723fe8 - CSS 2.2 §17.2 table model: display types map to
        // formatting contexts, table-column/column-group not rendered, anonymous table objects
        // generated +spec:table-layout:023714 - map display values to table formatting
        // contexts per CSS 2.2 §17.2 +spec:table-layout:6c5039 - row-primary table model:
        // rows/cells/captions/columns mapped here +spec:table-layout:75eea9 - display
        // property values for table elements (table, tr, td, etc.) +spec:table-layout:
        // 3ee121 - layout-internal display types map to table formatting context
        // +spec:display-property:b02b7f - table display types map to table formatting contexts;
        // table-column/table-column-group not rendered (treated as display:none for box generation)
399
        LayoutDisplay::Table | LayoutDisplay::InlineTable => FormattingContext::Table,
        LayoutDisplay::TableRowGroup
        | LayoutDisplay::TableHeaderGroup
39
        | LayoutDisplay::TableFooterGroup => FormattingContext::TableRowGroup,
394
        LayoutDisplay::TableRow => FormattingContext::TableRow,
948
        LayoutDisplay::TableCell => FormattingContext::TableCell,
        // +spec:display-property:da3fc7 - display:none/contents generate no boxes (no inner/outer
        // display types) +spec:display-property:e370af - display:none generates no boxes or
        // text sequences
3
        LayoutDisplay::None => FormattingContext::None,
62241
        LayoutDisplay::Flex | LayoutDisplay::InlineFlex => FormattingContext::Flex,
3
        LayoutDisplay::TableColumnGroup => FormattingContext::TableColumnGroup,
3
        LayoutDisplay::TableCaption => FormattingContext::TableCaption,
56
        LayoutDisplay::Grid | LayoutDisplay::InlineGrid => FormattingContext::Grid,
        // table-column elements are used only for column styling, not for generating boxes
4
        LayoutDisplay::TableColumn => FormattingContext::None,
        // +spec:display-contents:584072 - no special behavior for legend/HTML elements; contents
        // handled normally display:contents - element generates no box, children are
        // promoted to parent
5
        LayoutDisplay::Contents => FormattingContext::Contents,
        // +spec:display-property:b89b80 - run-in box falls back to block (merging into next block
        // not implemented) +spec:display-property:ccd4e6 - run-in falls back to block;
        // reparenting not implemented These less common display types default to block
        // behavior +spec:display-property:7d77f5 - run-in treated as block (run-in
        // sequencing fixup not yet implemented) +spec:display-property:0c30c4 - run-in
        // boxes fall back to block (run-in reparenting not implemented, matches browser behavior)
        // +spec:display-property:2f5c52 - run-in treated as block (full run-in merging not
        // implemented)
6
        LayoutDisplay::RunIn | LayoutDisplay::Marker => FormattingContext::Block {
6
            establishes_new_context: true,
6
        },
    }
176106
}
/// The logic now correctly identifies all BFC roots.
230590
fn determine_formatting_context(styled_dom: &StyledDom, node_id: NodeId) -> FormattingContext {
230590
    let node_data = &styled_dom.node_data.as_container()[node_id];
    // [g147j az-web-lift DIAG] OUTER determine_ entry (0x60BB0+slot): 1=Text early-exit,
    // 0x10|disc = went through for_display and returned that repr(C,u8) discriminant.
    // Discriminates "never called during the lifted build" (slot stays 0) vs "called but
    // the for_display match mis-routes" (here=0x10|x while the g147h inner markers stay 0)
    // vs "value correct at build, corrupted later" (here says Inline, dispatch reads garbage).
230590
    if matches!(node_data.get_node_type(), NodeType::Text(_)) {
        #[cfg(feature = "web_lift")]
        unsafe {
            crate::az_mark(0x60BB0 + (node_id.index() & 7) as u32 * 4, 0xC0DE0001);
        }
75940
        return FormattingContext::Inline;
154650
    }
154650
    let display_type = get_display_type(styled_dom, node_id);
154650
    let fc = determine_formatting_context_for_display(styled_dom, node_id, display_type);
    #[cfg(feature = "web_lift")]
    unsafe {
        let disc: u8 = core::ptr::read_volatile((&fc) as *const FormattingContext as *const u8);
        crate::az_mark(
            0x60BB0 + (node_id.index() & 7) as u32 * 4,
            0xC0DE0010 | disc as u32,
        );
    }
154650
    fc
230590
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use azul_core::{
        dom::{Dom, IdOrClass},
        resources::{ImageRef, RawImageFormat},
        selection::ContentIndex,
    };
    use super::*;
    use crate::{
        solver3::geometry::{EdgeSizes, PackedBoxProps},
        text3::{
            cache::{
                BidiDirection, BreakType, ClearType, ClusterFlags, GlyphKind, GraphemeClusterId,
                InlineBreak, LayoutFontMetrics, OverflowInfo, Point, PositionedItem, Rect,
                ShapedCluster, ShapedGlyph, ShapedItem, StyleProperties,
            },
            script::Script,
        },
    };
    // ==================================================================
    // Fixtures
    // ==================================================================
    const VIEWPORT: LogicalSize = LogicalSize {
        width: 800.0,
        height: 600.0,
    };
    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)
    }
    fn div_class(class: &str) -> Dom {
        Dom::create_div().with_ids_and_classes(vec![IdOrClass::Class(class.into())].into())
    }
    /// Runs the real build pipeline (`process_node` → `build` → STF bitmap) —
    /// i.e. everything `generate_layout_tree` does minus the `LayoutContext`
    /// (which would need a system-font `FontManager`).
    fn build_tree(styled_dom: &StyledDom) -> LayoutTree {
        let mut builder = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs: Option<Vec<LayoutDebugMessage>> = None;
        let root_id = styled_dom
            .root
            .into_crate_internal()
            .unwrap_or(NodeId::ZERO);
        let root_index = builder
            .process_node(styled_dom, root_id, None, &mut msgs)
            .expect("process_node on a well-formed DOM");
        let mut tree = builder.build(root_index);
        tree.subtree_needs_intrinsic = compute_subtree_needs_intrinsic(styled_dom, &tree);
        tree
    }
    /// `body(0) > [ .block(1) > [ text "hello"(2), .inline(3) > text "world"(4) ],
    ///              .mixed(5) > [ text " \n\t"(6), .block2(7), text "tail"(8) ] ]`
    ///
    /// The `.mixed` subtree is the interesting one: a whitespace-only inline run
    /// followed by a block sibling and a real inline run — exactly the CSS 2.1
    /// §9.2.2.1 anonymous-box case.
    fn mixed_dom() -> StyledDom {
        styled(
            Dom::create_body()
                .with_child(
                    div_class("block")
                        .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                            "hello",
                        ))
                        .with_child(div_class("inline").with_child(
                            Dom::create_text_do_not_use_without_block_level_wrapper("world"),
                        )),
                )
                .with_child(
                    div_class("mixed")
                        .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                            " \n\t",
                        ))
                        .with_child(div_class("block2"))
                        .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                            "tail",
                        )),
                ),
            ".block { display: block; } .inline { display: inline; } .mixed { display: block; } \
             .block2 { display: block; }",
        )
    }
    /// Locates a DOM node by its exact text content. Keeps the tests structural
    /// instead of hard-coding `CompactDom` pre-order indices.
    fn text_node(styled_dom: &StyledDom, needle: &str) -> NodeId {
        let container = styled_dom.node_data.as_container();
        for i in 0..styled_dom.node_data.len() {
            let id = NodeId::new(i);
            if let NodeType::Text(text) = container[id].get_node_type() {
                if text.as_str() == needle {
                    return id;
                }
            }
        }
        panic!("no text node with content {needle:?}");
    }
    fn empty_layout() -> Arc<UnifiedLayout> {
        Arc::new(UnifiedLayout {
            items: Vec::new(),
            overflow: OverflowInfo::default(),
        })
    }
    fn layout_of(items: Vec<PositionedItem>) -> Arc<UnifiedLayout> {
        Arc::new(UnifiedLayout {
            items,
            overflow: OverflowInfo::default(),
        })
    }
    fn tab_item(width: f32, height: f32, x: f32, line_index: usize) -> PositionedItem {
        PositionedItem {
            item: ShapedItem::Tab {
                source: ContentIndex {
                    run_index: 0,
                    item_index: 0,
                },
                bounds: Rect {
                    x: 0.0,
                    y: 0.0,
                    width,
                    height,
                },
            },
            position: Point { x, y: 0.0 },
            line_index,
        }
    }
    /// A positioned text cluster with `n_glyphs` degenerate glyphs, all on
    /// one shared default style/font — so same-line clusters MERGE into one
    /// paint run (the report fixtures need runs that actually hold glyphs;
    /// `tab_item` yields none).
    fn glyph_cluster_item(
        text: &str,
        n_glyphs: usize,
        x: f32,
        line_index: usize,
    ) -> PositionedItem {
        let glyphs: Vec<ShapedGlyph> = (0..n_glyphs)
            .map(|i| ShapedGlyph {
                kind: GlyphKind::Character,
                glyph_id: u16::try_from(i + 1).unwrap(),
                cluster_offset: 0,
                advance: 6.0,
                kerning: 0.0,
                offset: Point { x: 0.0, y: 0.0 },
                vertical_advance: 0.0,
                vertical_offset: Point { x: 0.0, y: 0.0 },
                script: Script::Latin,
                font_hash: 0xF0F0,
                font_metrics: LayoutFontMetrics {
                    ascent: 0.0,
                    descent: 0.0,
                    line_gap: 0.0,
                    units_per_em: 0,
                    x_height: None,
                    cap_height: None,
                },
            })
            .collect();
        PositionedItem {
            item: ShapedItem::Cluster(ShapedCluster {
                flags: ClusterFlags::classify(text),
                source_text: Arc::from(text),
                source_byte_len: u16::try_from(text.len()).unwrap(),
                source_cluster_id: GraphemeClusterId {
                    source_run: 0,
                    start_byte_in_run: 0,
                },
                source_content_index: ContentIndex {
                    run_index: 0,
                    item_index: 0,
                },
                source_node_id: None,
                glyphs: glyphs.into_iter().collect(),
                advance: 6.0,
                direction: BidiDirection::Ltr,
                style: Arc::new(StyleProperties::default()),
                marker_position_outside: None,
                is_first_fragment: true,
                is_last_fragment: true,
            }),
            position: Point { x, y: 0.0 },
            line_index,
        }
    }
    fn break_item(line_index: usize) -> PositionedItem {
        PositionedItem {
            item: ShapedItem::Break {
                source: ContentIndex {
                    run_index: 0,
                    item_index: 0,
                },
                break_info: InlineBreak {
                    break_type: BreakType::Hard,
                    clear: ClearType::None,
                    content_index: 0,
                },
            },
            position: Point { x: 0.0, y: 0.0 },
            line_index,
        }
    }
    fn hot(parent: Option<usize>) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: PackedBoxProps::default(),
            dom_node_id: None,
            used_size: None,
            formatting_context: FormattingContext::Block {
                establishes_new_context: false,
            },
            parent,
        }
    }
    /// Hand-assembles a `LayoutTree` from raw hot nodes + child lists so the
    /// index/cycle edge cases the builder can never produce are still reachable.
    fn raw_tree(nodes: Vec<LayoutNodeHot>, 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: vec![LayoutNodeWarm::default(); n],
            cold: vec![LayoutNodeCold::default(); n],
            root: 0,
            dom_to_layout: BTreeMap::new(),
            children_arena,
            children_offsets,
            subtree_needs_intrinsic: Vec::new(),
        }
    }
    const ALL_DISPLAYS: [LayoutDisplay; 23] = [
        LayoutDisplay::None,
        LayoutDisplay::Block,
        LayoutDisplay::Inline,
        LayoutDisplay::InlineBlock,
        LayoutDisplay::Flex,
        LayoutDisplay::InlineFlex,
        LayoutDisplay::Table,
        LayoutDisplay::InlineTable,
        LayoutDisplay::TableRowGroup,
        LayoutDisplay::TableHeaderGroup,
        LayoutDisplay::TableFooterGroup,
        LayoutDisplay::TableRow,
        LayoutDisplay::TableColumnGroup,
        LayoutDisplay::TableColumn,
        LayoutDisplay::TableCell,
        LayoutDisplay::TableCaption,
        LayoutDisplay::FlowRoot,
        LayoutDisplay::ListItem,
        LayoutDisplay::RunIn,
        LayoutDisplay::Marker,
        LayoutDisplay::Grid,
        LayoutDisplay::InlineGrid,
        LayoutDisplay::Contents,
    ];
    // ==================================================================
    // IfcId — thread-local counter (numeric / overflow)
    // ==================================================================
    #[test]
    fn ifcid_unique_hands_out_a_fresh_id_per_call_after_reset() {
        IfcId::reset_counter();
        assert_eq!(IfcId::unique(), IfcId(0));
        assert_eq!(IfcId::unique(), IfcId(1));
        assert_eq!(IfcId::unique(), IfcId(2));
        IfcId::reset_counter();
        assert_eq!(
            IfcId::unique(),
            IfcId(0),
            "reset_counter must restart the sequence, not continue it"
        );
        IfcId::reset_counter();
    }
    #[test]
    fn ifcid_reset_counter_is_idempotent() {
        IfcId::reset_counter();
        IfcId::reset_counter();
        IfcId::reset_counter();
        assert_eq!(IfcId::unique(), IfcId(0));
        IfcId::reset_counter();
    }
    #[test]
    fn ifcid_unique_wraps_at_u32_max_instead_of_panicking() {
        // `wrapping_add` is deliberate: a layout pass with 2^32 IFCs is not a
        // thing, but a debug-mode overflow panic in the middle of layout is.
        IFC_ID_COUNTER.with(|c| c.set(u32::MAX));
        assert_eq!(IfcId::unique(), IfcId(u32::MAX));
        assert_eq!(
            IfcId::unique(),
            IfcId(0),
            "wraps rather than overflow-panics"
        );
        assert_eq!(IfcId::unique(), IfcId(1));
        IfcId::reset_counter();
    }
    // ==================================================================
    // CachedInlineLayout — constructors + metrics extraction
    // ==================================================================
    #[test]
    fn cached_inline_layout_new_keeps_the_args_it_was_given() {
        let arc = empty_layout();
        let c = CachedInlineLayout::new(Arc::clone(&arc), AvailableSpace::Definite(123.5), true);
        assert!(Arc::ptr_eq(&c.layout, &arc));
        assert_eq!(c.available_width, AvailableSpace::Definite(123.5));
        assert!(c.has_floats);
        assert!(c.constraints.is_none(), "new() carries no constraints");
        assert!(c.line_breaks.is_none(), "new() computes no line breaks");
        assert_eq!(
            c.inline_content_hash, 0,
            "0 = unknown ⇒ never fast-path-reuse"
        );
        assert!(
            c.item_metrics.is_empty(),
            "an empty layout has no item metrics"
        );
    }
    #[test]
    fn cached_inline_layout_new_survives_extreme_widths() {
        for w in [
            AvailableSpace::Definite(0.0),
            AvailableSpace::Definite(-1.0),
            AvailableSpace::Definite(f32::MAX),
            AvailableSpace::Definite(f32::MIN),
            AvailableSpace::Definite(f32::INFINITY),
            AvailableSpace::Definite(f32::NEG_INFINITY),
            AvailableSpace::Definite(f32::NAN),
            AvailableSpace::MinContent,
            AvailableSpace::MaxContent,
        ] {
            let c = CachedInlineLayout::new(empty_layout(), w, false);
            assert!(c.item_metrics.is_empty());
            assert!(c.layout.items.is_empty());
        }
    }
    #[test]
    fn extract_item_metrics_mirrors_every_positioned_item() {
        let layout = layout_of(vec![
            tab_item(12.0, 20.0, 5.0, 3),
            tab_item(0.0, 0.0, 0.0, 0),
        ]);
        let m = CachedInlineLayout::extract_item_metrics(&layout);
        assert_eq!(m.len(), 2, "one metric entry per PositionedItem, in order");
        assert_eq!(m[0].advance_width, 12.0);
        assert_eq!(m[0].x_offset, 5.0);
        assert_eq!(m[0].line_index, 3);
        assert!(m[0].can_break, "a Tab is breakable");
        assert!(
            m[0].source_node_id.is_none(),
            "non-Cluster items expose no source_node_id"
        );
        // Tab metrics are the fallback ascent/descent split of the item height.
        assert!(
            (m[0].line_height_contribution - 20.0).abs() < 1e-3,
            "ascent+descent should reconstruct the height, got {}",
            m[0].line_height_contribution
        );
        assert_eq!(m[1].advance_width, 0.0);
        assert_eq!(m[1].line_index, 0);
    }
    #[test]
    fn extract_item_metrics_marks_break_items_as_unbreakable_and_zero_sized() {
        let layout = layout_of(vec![break_item(7)]);
        let m = CachedInlineLayout::extract_item_metrics(&layout);
        assert_eq!(m.len(), 1);
        assert!(
            !m[0].can_break,
            "ShapedItem::Break is the one non-breakable item"
        );
        assert_eq!(m[0].advance_width, 0.0, "a break has no visual geometry");
        assert_eq!(m[0].line_height_contribution, 0.0);
        assert_eq!(m[0].line_index, 7);
    }
    #[test]
    fn extract_item_metrics_on_an_empty_layout_is_empty_not_a_panic() {
        assert!(CachedInlineLayout::extract_item_metrics(&empty_layout()).is_empty());
    }
    #[test]
    fn extract_item_metrics_does_not_choke_on_non_finite_item_bounds() {
        let layout = layout_of(vec![
            tab_item(
                f32::INFINITY,
                f32::NAN,
                f32::NEG_INFINITY,
                u32::MAX as usize,
            ),
            tab_item(f32::MAX, f32::MAX, f32::MIN, 0),
        ]);
        let m = CachedInlineLayout::extract_item_metrics(&layout);
        assert_eq!(m.len(), 2);
        assert!(m[0].advance_width.is_infinite());
        assert!(
            m[0].line_height_contribution.is_nan(),
            "NaN in, NaN out — but no panic"
        );
        assert_eq!(m[1].advance_width, f32::MAX);
    }
    #[test]
    fn extract_item_metrics_truncates_a_huge_line_index_into_u32() {
        // `line_index` is a usize on PositionedItem but a u32 in the metrics —
        // the cast is `as`, so it wraps rather than panicking.
        let huge = (u32::MAX as usize) + 5;
        let m = CachedInlineLayout::extract_item_metrics(&layout_of(vec![tab_item(
            1.0, 1.0, 0.0, huge,
        )]));
        assert_eq!(
            m[0].line_index, 4,
            "wrapping `as u32` truncation, not a panic"
        );
    }
    #[test]
    fn cached_inline_layout_new_with_constraints_records_constraints_and_line_breaks() {
        let arc = layout_of(vec![tab_item(10.0, 20.0, 0.0, 0)]);
        let c = CachedInlineLayout::new_with_constraints(
            Arc::clone(&arc),
            AvailableSpace::Definite(200.0),
            false,
            UnifiedConstraints::default(),
        );
        assert!(c.constraints.is_some());
        let lb = c
            .line_breaks
            .expect("new_with_constraints computes line breaks");
        assert_eq!(lb.available_width, 200.0);
        assert_eq!(c.item_metrics.len(), 1);
    }
    #[test]
    fn new_with_constraints_treats_indefinite_widths_as_f32_max() {
        for w in [AvailableSpace::MinContent, AvailableSpace::MaxContent] {
            let c = CachedInlineLayout::new_with_constraints(
                empty_layout(),
                w,
                false,
                UnifiedConstraints::default(),
            );
            let lb = c.line_breaks.expect("line breaks");
            assert_eq!(
                lb.available_width,
                f32::MAX,
                "indefinite width collapses to f32::MAX for break extraction"
            );
            assert_eq!(
                c.available_width, w,
                "but the cache key keeps the real variant"
            );
        }
    }
    // ==================================================================
    // CachedInlineLayout — width matching / validity (predicates)
    // ==================================================================
    fn cached(width: AvailableSpace, has_floats: bool) -> CachedInlineLayout {
        CachedInlineLayout::new(empty_layout(), width, has_floats)
    }
    /// d1 retention wiring: mode 0 stores NO dense view; mode 1 (and 2)
    /// store one, and the runs it derives equal the reference's. The
    /// SEMANTIC equality over real shaped content is pinned by
    /// text3_dense_equivalence + the e2e corpus under AZ_DENSE_TEXT=verify;
    /// this pins the CACHE wiring (someone dropping the retention or the
    /// tuple plumbing goes red here).
    #[test]
    fn dense_view_is_retained_exactly_when_the_flag_asks() {
        let l = empty_layout();
        let (runs0, d0) = compute_glyph_runs_with_mode(&l, 0);
        assert!(d0.is_none(), "mode 0 must not retain a dense view");
        let (runs1, d1) = compute_glyph_runs_with_mode(&l, 1);
        assert!(d1.is_some(), "mode 1 must retain the dense view");
        let (runs2, d2) = compute_glyph_runs_with_mode(&l, 2);
        assert!(d2.is_some(), "verify mode must retain the dense view");
        assert_eq!(runs0.len(), runs1.len());
        assert_eq!(runs0.len(), runs2.len());
    }
    #[test]
    fn width_constraint_matches_definite_widths_within_the_epsilon() {
        let c = cached(AvailableSpace::Definite(100.0), false);
        assert!(c.width_constraint_matches(AvailableSpace::Definite(100.0)));
        assert!(
            c.width_constraint_matches(AvailableSpace::Definite(100.09)),
            "sub-0.1px drift must not force a relayout"
        );
        // 100.1 is NOT exactly 0.1 away: the f32 literal is 100.0999984741211, so the
        // real diff is ~0.09999847, which genuinely IS < 0.1. Binary floats, not
        // decimal. (Pick a literal that clears the epsilon after rounding to test the
        // miss branch -- see below.)
        assert!(c.width_constraint_matches(AvailableSpace::Definite(100.1)));
        assert!(
            !c.width_constraint_matches(AvailableSpace::Definite(100.2)),
            "the epsilon is strict (`< 0.1`), so a 0.2 drift must miss"
        );
        assert!(!c.width_constraint_matches(AvailableSpace::Definite(0.0)));
    }
    #[test]
    fn width_constraint_matches_only_pairs_like_with_like() {
        let min = cached(AvailableSpace::MinContent, false);
        let max = cached(AvailableSpace::MaxContent, false);
        let def = cached(AvailableSpace::Definite(50.0), false);
        assert!(min.width_constraint_matches(AvailableSpace::MinContent));
        assert!(max.width_constraint_matches(AvailableSpace::MaxContent));
        assert!(!min.width_constraint_matches(AvailableSpace::MaxContent));
        assert!(!max.width_constraint_matches(AvailableSpace::MinContent));
        assert!(!min.width_constraint_matches(AvailableSpace::Definite(50.0)));
        assert!(!def.width_constraint_matches(AvailableSpace::MinContent));
        assert!(!def.width_constraint_matches(AvailableSpace::MaxContent));
    }
    #[test]
    fn width_constraint_matches_is_false_for_nan_widths_rather_than_panicking() {
        // (NaN - NaN).abs() is NaN, and `NaN < eps` is false — so a NaN-width
        // cache entry never validates. Deterministic (always relayout), not a panic.
        let c = cached(AvailableSpace::Definite(f32::NAN), false);
        assert!(!c.width_constraint_matches(AvailableSpace::Definite(f32::NAN)));
        assert!(!c.width_constraint_matches(AvailableSpace::Definite(0.0)));
        let good = cached(AvailableSpace::Definite(10.0), false);
        assert!(!good.width_constraint_matches(AvailableSpace::Definite(f32::NAN)));
    }
    #[test]
    fn width_constraint_matches_is_false_for_an_infinite_width_against_itself() {
        // inf - inf == NaN, so an infinite cached width never matches — the cache
        // simply always misses. Surprising, but safe and deterministic.
        let c = cached(AvailableSpace::Definite(f32::INFINITY), false);
        assert!(!c.width_constraint_matches(AvailableSpace::Definite(f32::INFINITY)));
        assert!(!c.is_valid_for(AvailableSpace::Definite(f32::INFINITY), false));
        assert!(c.should_replace_with(AvailableSpace::Definite(f32::INFINITY), false));
    }
    #[test]
    fn width_constraint_matches_handles_huge_finite_widths() {
        let c = cached(AvailableSpace::Definite(f32::MAX), false);
        assert!(c.width_constraint_matches(AvailableSpace::Definite(f32::MAX)));
        assert!(!c.width_constraint_matches(AvailableSpace::Definite(f32::MIN)));
    }
    #[test]
    fn is_valid_for_rejects_a_no_float_cache_when_the_request_gains_floats() {
        // A cached layout with no floats must be invalidated once the new request
        // carries floats, so the text re-wraps around them (#19); every other float
        // combination reduces to width_constraint_matches. This mirrors
        // should_replace_with()'s gain-float branch (they must stay consistent).
        let widths = [
            AvailableSpace::Definite(0.0),
            AvailableSpace::Definite(100.0),
            AvailableSpace::MinContent,
            AvailableSpace::MaxContent,
        ];
        for cached_floats in [false, true] {
            for cached_w in widths {
                let c = cached(cached_w, cached_floats);
                for new_w in widths {
                    let width_ok = c.width_constraint_matches(new_w);
                    // No-float request: pure width match (a float-aware cache is
                    // still kept for a no-float request, gated on width).
                    assert_eq!(c.is_valid_for(new_w, false), width_ok);
                    // Float request: a no-float cache is always rejected so the text
                    // re-wraps; a float-aware cache stays gated on width.
                    let expected_with_floats = if cached_floats { width_ok } else { false };
                    assert_eq!(c.is_valid_for(new_w, true), expected_with_floats);
                    // is_valid_for and should_replace_with must stay opposites on the
                    // gain-float axis.
                    if !cached_floats {
                        assert!(c.should_replace_with(new_w, true));
                    }
                }
            }
        }
    }
    #[test]
    fn is_valid_for_returns_the_expected_true_and_false() {
        let c = cached(AvailableSpace::Definite(300.0), false);
        assert!(c.is_valid_for(AvailableSpace::Definite(300.0), false));
        assert!(!c.is_valid_for(AvailableSpace::Definite(299.0), false));
    }
    #[test]
    fn should_replace_with_always_replaces_when_float_info_is_gained() {
        // Even at an identical width: a float-aware layout strictly dominates.
        let c = cached(AvailableSpace::Definite(300.0), false);
        assert!(c.should_replace_with(AvailableSpace::Definite(300.0), true));
        assert!(c.should_replace_with(AvailableSpace::MinContent, true));
    }
    #[test]
    fn should_replace_with_keeps_a_float_aware_layout_at_a_matching_width() {
        let c = cached(AvailableSpace::Definite(300.0), true);
        assert!(
            !c.should_replace_with(AvailableSpace::Definite(300.0), false),
            "a non-float layout must not overwrite a float-aware one at the same width"
        );
        assert!(
            c.should_replace_with(AvailableSpace::Definite(100.0), false),
            "…but a width change still forces a replace"
        );
    }
    #[test]
    fn should_replace_with_is_the_negation_of_is_valid_for_when_floats_are_unchanged() {
        let widths = [
            AvailableSpace::Definite(0.0),
            AvailableSpace::Definite(42.0),
            AvailableSpace::MinContent,
            AvailableSpace::MaxContent,
        ];
        for floats in [false, true] {
            for cached_w in widths {
                let c = cached(cached_w, floats);
                for new_w in widths {
                    assert_eq!(
                        c.should_replace_with(new_w, floats),
                        !c.is_valid_for(new_w, floats),
                        "cached={cached_w:?} new={new_w:?} floats={floats}"
                    );
                }
            }
        }
    }
    // ==================================================================
    // CachedInlineLayout — getters
    // ==================================================================
    #[test]
    fn get_layout_and_clone_layout_hand_back_the_very_same_arc() {
        let arc = layout_of(vec![tab_item(1.0, 2.0, 0.0, 0)]);
        let c = CachedInlineLayout::new(Arc::clone(&arc), AvailableSpace::MaxContent, false);
        assert!(Arc::ptr_eq(c.get_layout(), &arc));
        let cloned = c.clone_layout();
        assert!(
            Arc::ptr_eq(&cloned, &arc),
            "clone_layout must not deep-copy"
        );
        assert_eq!(
            Arc::strong_count(&arc),
            4,
            "the original + the cache's + the clone + the DL payload (d5: the payload is built \
             ONCE at store time and holds the layout Arc so TextLayout damage ptr_eq stays \
             stable; 3 -> 4 on 2026-08-11)"
        );
        assert_eq!(c.get_layout().items.len(), 1);
    }
    #[test]
    fn get_layout_works_on_an_empty_extreme_instance() {
        let c = cached(AvailableSpace::Definite(f32::NAN), true);
        assert!(c.get_layout().items.is_empty());
        assert!(c.clone_layout().items.is_empty());
    }
    // ==================================================================
    // LayoutNode::split / LayoutTree::get_full_node — round-trip
    // ==================================================================
    #[test]
    fn get_full_node_then_split_round_trips_through_the_soa_arrays() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        assert!(tree.nodes.len() >= 2);
        for i in 0..tree.nodes.len() {
            let full = tree.get_full_node(i).expect("in-range node");
            let (h, w, c) = full.split();
            let hot = tree.get(LayoutNodeId::new(i)).unwrap();
            assert_eq!(h.dom_node_id, hot.dom_node_id, "node {i}");
            assert_eq!(h.parent, hot.parent, "node {i}");
            assert_eq!(h.used_size, hot.used_size, "node {i}");
            assert_eq!(h.formatting_context, hot.formatting_context, "node {i}");
            // box_props survive a pack → unpack → pack round-trip bit-for-bit.
            assert_eq!(h.box_props.margin, hot.box_props.margin, "node {i}");
            assert_eq!(h.box_props.padding, hot.box_props.padding, "node {i}");
            assert_eq!(h.box_props.border, hot.box_props.border, "node {i}");
            let warm = tree.warm(LayoutNodeId::new(i)).unwrap();
            assert_eq!(w.pseudo_element, warm.pseudo_element, "node {i}");
            assert_eq!(w.baseline, warm.baseline, "node {i}");
            assert_eq!(
                w.computed_style.display, warm.computed_style.display,
                "node {i}"
            );
            let cold = tree.cold(LayoutNodeId::new(i)).unwrap();
            assert_eq!(c.anonymous_type, cold.anonymous_type, "node {i}");
            assert_eq!(c.dirty_flag, cold.dirty_flag, "node {i}");
            assert_eq!(c.subtree_hash, cold.subtree_hash, "node {i}");
            assert_eq!(c.ifc_id, cold.ifc_id, "node {i}");
        }
    }
    #[test]
    fn get_full_node_restores_the_children_from_the_arena() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        for i in 0..tree.nodes.len() {
            let full = tree.get_full_node(i).unwrap();
            assert_eq!(full.children, tree.children(i).to_vec(), "node {i}");
        }
    }
    #[test]
    fn get_full_node_is_none_out_of_range() {
        let tree = build_tree(&mixed_dom());
        assert!(tree.get_full_node(tree.nodes.len()).is_none());
        assert!(tree.get_full_node(usize::MAX).is_none());
    }
    // ==================================================================
    // LayoutTree — index-taking accessors (numeric / min-max / overflow)
    // ==================================================================
    #[test]
    fn tree_accessors_return_none_for_every_out_of_range_index() {
        let mut tree = build_tree(&mixed_dom());
        let n = tree.nodes.len();
        for idx in [n, n + 1, usize::MAX, usize::MAX - 1, usize::MAX / 2] {
            assert!(tree.get(LayoutNodeId::new(idx)).is_none(), "get({idx})");
            assert!(tree.warm(LayoutNodeId::new(idx)).is_none(), "warm({idx})");
            assert!(tree.cold(LayoutNodeId::new(idx)).is_none(), "cold({idx})");
            assert!(
                tree.get_mut(LayoutNodeId::new(idx)).is_none(),
                "get_mut({idx})"
            );
            assert!(
                tree.warm_mut(LayoutNodeId::new(idx)).is_none(),
                "warm_mut({idx})"
            );
            assert!(
                tree.cold_mut(LayoutNodeId::new(idx)).is_none(),
                "cold_mut({idx})"
            );
            assert!(tree.get_inline_layout_for_node(idx).is_none());
        }
    }
    #[test]
    fn tree_accessors_all_resolve_at_index_zero() {
        let mut tree = build_tree(&mixed_dom());
        assert!(tree.get(LayoutNodeId::new(0)).is_some());
        assert!(tree.warm(LayoutNodeId::new(0)).is_some());
        assert!(tree.cold(LayoutNodeId::new(0)).is_some());
        assert!(tree.get_mut(LayoutNodeId::new(0)).is_some());
        assert!(tree.warm_mut(LayoutNodeId::new(0)).is_some());
        assert!(tree.cold_mut(LayoutNodeId::new(0)).is_some());
        assert_eq!(
            tree.get(LayoutNodeId::new(0)).unwrap().parent,
            None,
            "index 0 is the root"
        );
    }
    #[test]
    fn children_of_an_out_of_range_index_is_an_empty_slice() {
        let tree = build_tree(&mixed_dom());
        assert!(tree.children(tree.nodes.len()).is_empty());
        assert!(tree.children(usize::MAX).is_empty());
        assert!(tree.children(usize::MAX - 1).is_empty());
    }
    #[test]
    fn children_arena_slices_agree_with_the_parent_pointers() {
        let tree = build_tree(&mixed_dom());
        let n = tree.nodes.len();
        let mut seen: Vec<usize> = Vec::new();
        for i in 0..n {
            for &child in tree.children(i) {
                assert!(child < n, "child {child} of {i} is out of range");
                assert_eq!(
                    tree.get(LayoutNodeId::new(child)).unwrap().parent,
                    Some(i),
                    "child {child} does not point back at parent {i}"
                );
                seen.push(child);
            }
        }
        seen.sort_unstable();
        seen.dedup();
        assert_eq!(
            seen.len(),
            n - 1,
            "every node but the root is someone's child"
        );
        assert!(!seen.contains(&tree.root), "the root is nobody's child");
    }
    #[test]
    fn children_offsets_stay_inside_the_arena() {
        let tree = build_tree(&mixed_dom());
        assert_eq!(tree.children_offsets.len(), tree.nodes.len());
        let total: usize = tree
            .children_offsets
            .iter()
            .map(|&(_, len)| len as usize)
            .sum();
        assert_eq!(total, tree.children_arena.len());
        for &(start, len) in &tree.children_offsets {
            assert!((start as usize) + (len as usize) <= tree.children_arena.len());
        }
    }
    #[test]
    fn get_content_size_is_default_for_an_out_of_range_index() {
        let tree = build_tree(&mixed_dom());
        assert_eq!(
            tree.get_content_size(LayoutNodeId::new(usize::MAX)),
            LogicalSize::default()
        );
        assert_eq!(
            tree.get_content_size(LayoutNodeId::new(tree.nodes.len())),
            LogicalSize::default()
        );
    }
    #[test]
    fn get_content_size_prefers_the_explicit_overflow_content_size() {
        let mut tree = raw_tree(vec![hot(None)], &[vec![]]);
        tree.nodes[0].used_size = Some(LogicalSize::new(10.0, 10.0));
        tree.warm[0].overflow_content_size = Some(LogicalSize::new(999.0, 888.0));
        assert_eq!(
            tree.get_content_size(LayoutNodeId::new(0)),
            LogicalSize::new(999.0, 888.0)
        );
    }
    #[test]
    fn get_content_size_grows_the_used_size_to_cover_the_inline_items() {
        let mut tree = raw_tree(vec![hot(None)], &[vec![]]);
        tree.nodes[0].used_size = Some(LogicalSize::new(10.0, 10.0));
        tree.warm[0].inline_layout_result = Some(Box::new(CachedInlineLayout::new(
            layout_of(vec![tab_item(30.0, 40.0, 25.0, 0)]),
            AvailableSpace::MaxContent,
            false,
        )));
        // item spans x ∈ [25, 55], y ∈ [0, 40]  →  content must cover 55 × 40.
        let cs = tree.get_content_size(LayoutNodeId::new(0));
        assert_eq!(cs.width, 55.0);
        assert_eq!(cs.height, 40.0);
    }
    #[test]
    fn get_content_size_never_shrinks_below_the_used_size() {
        let mut tree = raw_tree(vec![hot(None)], &[vec![]]);
        tree.nodes[0].used_size = Some(LogicalSize::new(500.0, 500.0));
        tree.warm[0].inline_layout_result = Some(Box::new(CachedInlineLayout::new(
            layout_of(vec![tab_item(1.0, 1.0, 0.0, 0)]),
            AvailableSpace::MaxContent,
            false,
        )));
        assert_eq!(
            tree.get_content_size(LayoutNodeId::new(0)),
            LogicalSize::new(500.0, 500.0)
        );
    }
    #[test]
    fn get_content_size_of_a_node_with_no_used_size_is_zero() {
        let tree = raw_tree(vec![hot(None)], &[vec![]]);
        assert_eq!(
            tree.get_content_size(LayoutNodeId::new(0)),
            LogicalSize::default()
        );
    }
    // ==================================================================
    // LayoutTree — IFC navigation
    // ==================================================================
    #[test]
    fn get_ifc_root_layout_index_returns_the_input_unchanged_when_out_of_range() {
        let tree = build_tree(&mixed_dom());
        // Documented contract: no membership ⇒ identity. That must hold for
        // garbage indices too, and it must not panic.
        assert_eq!(tree.get_ifc_root_layout_index(usize::MAX), usize::MAX);
        assert_eq!(tree.get_ifc_root_layout_index(0), 0);
    }
    #[test]
    fn get_ifc_root_layout_index_follows_membership_only_for_non_ifc_roots() {
        let mut tree = raw_tree(vec![hot(None), hot(Some(0))], &[vec![1], vec![]]);
        tree.warm[0].inline_layout_result = Some(Box::new(CachedInlineLayout::new(
            empty_layout(),
            AvailableSpace::MaxContent,
            false,
        )));
        tree.warm[1].ifc_membership = Some(IfcMembership {
            ifc_id: IfcId(0),
            ifc_root_layout_index: 0,
            run_index: 0,
        });
        assert_eq!(
            tree.get_ifc_root_layout_index(1),
            0,
            "a text node anchors to its IFC root"
        );
        assert_eq!(
            tree.get_ifc_root_layout_index(0),
            0,
            "the IFC root itself is its own anchor"
        );
        // A node that owns an inline_layout_result must NOT be redirected, even
        // if it also carries a (stale) membership.
        tree.warm[0].ifc_membership = Some(IfcMembership {
            ifc_id: IfcId(9),
            ifc_root_layout_index: 1,
            run_index: 0,
        });
        assert_eq!(tree.get_ifc_root_layout_index(0), 0);
    }
    #[test]
    fn get_inline_layout_for_node_walks_membership_then_gives_up_cleanly() {
        let mut tree = raw_tree(vec![hot(None), hot(Some(0)), hot(Some(0))], &[vec![1, 2]]);
        let arc = empty_layout();
        tree.warm[0].inline_layout_result = Some(Box::new(CachedInlineLayout::new(
            Arc::clone(&arc),
            AvailableSpace::MaxContent,
            false,
        )));
        tree.warm[1].ifc_membership = Some(IfcMembership {
            ifc_id: IfcId(0),
            ifc_root_layout_index: 0,
            run_index: 0,
        });
        // Node 2 has neither its own layout nor a membership.
        assert!(Arc::ptr_eq(
            tree.get_inline_layout_for_node(0).unwrap(),
            &arc
        ));
        assert!(Arc::ptr_eq(
            tree.get_inline_layout_for_node(1).unwrap(),
            &arc
        ));
        assert!(tree.get_inline_layout_for_node(2).is_none());
    }
    #[test]
    fn get_inline_layout_for_node_is_none_when_membership_dangles() {
        // A membership pointing at a bogus root index must return None, not panic.
        let mut tree = raw_tree(vec![hot(None)], &[vec![]]);
        tree.warm[0].ifc_membership = Some(IfcMembership {
            ifc_id: IfcId(3),
            ifc_root_layout_index: usize::MAX,
            run_index: 0,
        });
        assert!(tree.get_inline_layout_for_node(0).is_none());
        // …and when the referenced root exists but has no cached layout.
        let mut tree = raw_tree(vec![hot(None), hot(Some(0))], &[vec![1], vec![]]);
        tree.warm[1].ifc_membership = Some(IfcMembership {
            ifc_id: IfcId(3),
            ifc_root_layout_index: 0,
            run_index: 0,
        });
        assert!(tree.get_inline_layout_for_node(1).is_none());
    }
    // ==================================================================
    // LayoutTree — dirty flags
    // ==================================================================
    /// `0 → 1 → 2` chain plus a sibling `3` under `1`.
    fn dirty_tree() -> LayoutTree {
        raw_tree(
            vec![hot(None), hot(Some(0)), hot(Some(1)), hot(Some(1))],
            &[vec![1], vec![2, 3], vec![], vec![]],
        )
    }
    #[test]
    fn mark_dirty_walks_up_to_the_root() {
        let mut tree = dirty_tree();
        tree.mark_dirty(2, DirtyFlag::Layout);
        assert_eq!(
            tree.cold(LayoutNodeId::new(2)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(1)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(0)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(3)).unwrap().dirty_flag,
            DirtyFlag::None,
            "the sibling is untouched"
        );
    }
    #[test]
    fn mark_dirty_with_flag_none_is_a_no_op() {
        let mut tree = dirty_tree();
        tree.mark_dirty(2, DirtyFlag::None);
        assert!(tree.cold.iter().all(|c| c.dirty_flag == DirtyFlag::None));
    }
    #[test]
    fn mark_dirty_never_downgrades_an_existing_flag() {
        let mut tree = dirty_tree();
        tree.mark_dirty(2, DirtyFlag::Layout);
        tree.mark_dirty(2, DirtyFlag::Paint);
        assert_eq!(
            tree.cold(LayoutNodeId::new(2)).unwrap().dirty_flag,
            DirtyFlag::Layout,
            "Layout > Paint — a Paint request must not weaken it"
        );
    }
    #[test]
    fn mark_dirty_upgrades_paint_to_layout_and_keeps_propagating() {
        let mut tree = dirty_tree();
        tree.mark_dirty(2, DirtyFlag::Paint);
        assert_eq!(
            tree.cold(LayoutNodeId::new(0)).unwrap().dirty_flag,
            DirtyFlag::Paint
        );
        tree.mark_dirty(2, DirtyFlag::Layout);
        assert_eq!(
            tree.cold(LayoutNodeId::new(2)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(0)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
    }
    #[test]
    fn mark_dirty_stops_early_when_an_ancestor_is_already_at_least_as_dirty() {
        let mut tree = dirty_tree();
        tree.mark_dirty(3, DirtyFlag::Layout); // marks 3, 1, 0
        tree.mark_dirty(2, DirtyFlag::Layout); // marks 2, then stops at 1
        assert_eq!(
            tree.cold(LayoutNodeId::new(2)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(1)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
    }
    #[test]
    fn mark_dirty_out_of_range_is_a_silent_no_op() {
        let mut tree = dirty_tree();
        tree.mark_dirty(usize::MAX, DirtyFlag::Layout);
        tree.mark_dirty(tree.nodes.len(), DirtyFlag::Layout);
        assert!(tree.cold.iter().all(|c| c.dirty_flag == DirtyFlag::None));
    }
    #[test]
    fn mark_dirty_terminates_on_a_cyclic_parent_chain() {
        // Not reachable through the builder, but the `>= flag` early-out is the
        // only thing standing between a corrupted parent pointer and a hang.
        let mut tree = raw_tree(vec![hot(Some(1)), hot(Some(0))], &[vec![], vec![]]);
        tree.mark_dirty(0, DirtyFlag::Layout);
        assert_eq!(
            tree.cold(LayoutNodeId::new(0)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(1)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
    }
    #[test]
    fn mark_dirty_terminates_when_a_node_is_its_own_parent() {
        let mut tree = raw_tree(vec![hot(Some(0))], &[vec![]]);
        tree.mark_dirty(0, DirtyFlag::Layout);
        assert_eq!(
            tree.cold(LayoutNodeId::new(0)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
    }
    #[test]
    fn mark_subtree_dirty_marks_descendants_but_not_ancestors_or_siblings() {
        let mut tree = dirty_tree();
        tree.mark_subtree_dirty(1, DirtyFlag::Layout);
        assert_eq!(
            tree.cold(LayoutNodeId::new(1)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(2)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(3)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(0)).unwrap().dirty_flag,
            DirtyFlag::None,
            "mark_subtree_dirty walks DOWN only"
        );
    }
    #[test]
    fn mark_subtree_dirty_with_none_or_a_bad_index_is_a_no_op() {
        let mut tree = dirty_tree();
        tree.mark_subtree_dirty(0, DirtyFlag::None);
        tree.mark_subtree_dirty(usize::MAX, DirtyFlag::Layout);
        assert!(tree.cold.iter().all(|c| c.dirty_flag == DirtyFlag::None));
    }
    #[test]
    fn mark_subtree_dirty_does_not_downgrade() {
        let mut tree = dirty_tree();
        tree.mark_subtree_dirty(0, DirtyFlag::Layout);
        tree.mark_subtree_dirty(0, DirtyFlag::Paint);
        assert!(tree.cold.iter().all(|c| c.dirty_flag == DirtyFlag::Layout));
    }
    #[test]
    fn clear_all_dirty_flags_resets_every_node() {
        let mut tree = dirty_tree();
        tree.mark_subtree_dirty(0, DirtyFlag::Layout);
        assert!(tree.cold.iter().any(|c| c.dirty_flag != DirtyFlag::None));
        tree.clear_all_dirty_flags();
        assert!(tree.cold.iter().all(|c| c.dirty_flag == DirtyFlag::None));
    }
    #[test]
    fn clear_all_dirty_flags_on_an_empty_tree_does_not_panic() {
        let mut tree = raw_tree(Vec::new(), &[]);
        tree.clear_all_dirty_flags();
        assert!(tree.cold.is_empty());
    }
    // ==================================================================
    // LayoutTree — memory report (getters / numeric)
    // ==================================================================
    #[test]
    fn memory_report_total_is_the_sum_of_its_parts() {
        let tree = build_tree(&mixed_dom());
        let r = tree.memory_report();
        assert_eq!(r.node_count, tree.nodes.len());
        assert_eq!(
            r.total_bytes(),
            r.hot_bytes
                + r.warm_bytes
                + r.warm_inline_layout_bytes
                + r.warm_taffy_cache_bytes
                + r.cold_bytes
                + r.dom_to_layout_bytes
                + r.children_arena_bytes
                + r.children_offsets_bytes
        );
        assert!(r.hot_bytes >= r.node_count * size_of::<LayoutNodeHot>());
        assert!(r.total_bytes() > 0, "a non-empty tree retains something");
    }
    #[test]
    fn memory_report_of_an_empty_tree_is_all_zero() {
        let tree = raw_tree(Vec::new(), &[]);
        let r = tree.memory_report();
        assert_eq!(r.node_count, 0);
        assert_eq!(r.total_bytes(), 0);
    }
    #[test]
    fn memory_report_total_bytes_default_is_zero() {
        assert_eq!(LayoutTreeMemoryReport::default().total_bytes(), 0);
    }
    #[test]
    fn memory_report_total_bytes_at_the_usize_boundary_does_not_overflow() {
        // Nine byte-fields, each usize::MAX / 9 → usize::MAX - 6 (MAX ≡ 6 mod 9).
        // One notch further and `total_bytes`'s plain `+` chain would
        // overflow-panic in debug.
        let ninth = usize::MAX / 9;
        let r = LayoutTreeMemoryReport {
            node_count: 0,
            hot_bytes: ninth,
            warm_bytes: ninth,
            warm_inline_layout_bytes: ninth,
            glyph_run_bytes: ninth,
            warm_taffy_cache_bytes: ninth,
            cold_bytes: ninth,
            dom_to_layout_bytes: ninth,
            children_arena_bytes: ninth,
            children_offsets_bytes: ninth,
            // Counters, not byte totals — `total_bytes` must not add them.
            shaped_cluster_count: 0,
            shaped_glyph_count: 0,
            shaped_cluster_text_bytes: 0,
            distinct_glyph_style_arcs: 0,
            glyph_run_count: 0,
            glyph_instance_count: 0,
        };
        assert_eq!(r.total_bytes(), ninth * 9);
        assert_eq!(r.total_bytes(), usize::MAX - 6);
    }
    #[test]
    fn memory_report_counts_a_cached_inline_layout() {
        let mut tree = raw_tree(vec![hot(None)], &[vec![]]);
        let bare = tree.memory_report().warm_inline_layout_bytes;
        assert_eq!(bare, 0);
        tree.warm[0].inline_layout_result = Some(Box::new(CachedInlineLayout::new(
            layout_of(vec![tab_item(1.0, 1.0, 0.0, 0)]),
            AvailableSpace::MaxContent,
            false,
        )));
        assert!(
            tree.memory_report().warm_inline_layout_bytes >= size_of::<UnifiedLayout>(),
            "the UnifiedLayout header must at least be counted"
        );
        // The Box allocation itself is retained heap the `warm` line can't
        // see (CachedInlineLayout is boxed off LayoutNodeWarm).
        assert!(
            tree.memory_report().warm_inline_layout_bytes >= size_of::<CachedInlineLayout>(),
            "the boxed CachedInlineLayout struct must be counted"
        );
    }
    #[test]
    fn memory_report_itemizes_the_glyph_run_cache() {
        use crate::text3::glyphs::CompactGlyphRun;
        let mut tree = raw_tree(vec![hot(None), hot(Some(0))], &[vec![1], vec![]]);
        let r0 = tree.memory_report();
        assert_eq!(
            (
                r0.glyph_run_bytes,
                r0.glyph_run_count,
                r0.glyph_instance_count
            ),
            (0, 0, 0)
        );
        // Two same-style same-baseline clusters (2 + 1 glyphs) merge into ONE
        // paint run of 3 instances — the run-merging law, pinned through the
        // report counters.
        tree.warm[0].inline_layout_result = Some(Box::new(CachedInlineLayout::new(
            layout_of(vec![
                glyph_cluster_item("a", 2, 0.0, 0),
                glyph_cluster_item("b", 1, 12.0, 0),
            ]),
            AvailableSpace::MaxContent,
            false,
        )));
        let r1 = tree.memory_report();
        assert_eq!(r1.glyph_run_count, 1, "same style+font+baseline must merge");
        assert_eq!(r1.glyph_instance_count, 3);
        assert!(
            r1.glyph_run_bytes >= size_of::<CompactGlyphRun>() + 3 * size_of::<(u32, f32)>(),
            "bytes must cover the run header and all three compact entries (got {}, header {})",
            r1.glyph_run_bytes,
            size_of::<CompactGlyphRun>(),
        );
        // Arc-dedup law: a second node SHARING the same run list (GlyphSwap
        // reuse clones the Arc) must add ZERO bytes and ZERO counts.
        let shared = tree.warm[0]
            .inline_layout_result
            .as_ref()
            .unwrap()
            .glyph_runs
            .clone();
        let mut second = CachedInlineLayout::new(
            layout_of(vec![glyph_cluster_item("c", 1, 0.0, 0)]),
            AvailableSpace::MaxContent,
            false,
        );
        second.glyph_runs = shared;
        tree.warm[1].inline_layout_result = Some(Box::new(second));
        let r2 = tree.memory_report();
        assert_eq!(
            (
                r2.glyph_run_bytes,
                r2.glyph_run_count,
                r2.glyph_instance_count
            ),
            (
                r1.glyph_run_bytes,
                r1.glyph_run_count,
                r1.glyph_instance_count
            ),
            "a shared Arc must not be double-counted"
        );
        // A DISTINCT run list does count.
        let third = CachedInlineLayout::new(
            layout_of(vec![glyph_cluster_item("d", 1, 0.0, 0)]),
            AvailableSpace::MaxContent,
            false,
        );
        tree.warm[1].inline_layout_result = Some(Box::new(third));
        let r3 = tree.memory_report();
        assert_eq!(r3.glyph_run_count, 2);
        assert_eq!(r3.glyph_instance_count, 4);
        assert!(r3.glyph_run_bytes > r1.glyph_run_bytes);
    }
    #[test]
    fn root_node_returns_the_hot_node_at_the_root_index() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        let root = tree.root_node();
        assert_eq!(root.parent, None);
        assert_eq!(root.dom_node_id, sd.root.into_crate_internal());
    }
    // ==================================================================
    // LayoutTree::resolve_box_props (numeric / NaN-inf)
    // ==================================================================
    #[test]
    fn resolve_box_props_out_of_range_is_a_no_op() {
        let mut tree = build_tree(&mixed_dom());
        tree.resolve_box_props(usize::MAX, VIEWPORT, VIEWPORT, 16.0, 16.0);
        tree.resolve_box_props(tree.nodes.len(), VIEWPORT, VIEWPORT, 16.0, 16.0);
    }
    #[test]
    fn resolve_box_props_keeps_the_stored_props_finite_for_nan_and_inf_inputs() {
        let sd = styled(
            Dom::create_body().with_child(div_class("m")),
            ".m { margin: 50%; padding: 10em; border: 1px solid black; }",
        );
        let mut tree = build_tree(&sd);
        for (cb, vp, efs, rfs) in [
            (
                LogicalSize::new(f32::NAN, f32::NAN),
                LogicalSize::new(f32::NAN, f32::NAN),
                f32::NAN,
                f32::NAN,
            ),
            (
                LogicalSize::new(f32::INFINITY, f32::INFINITY),
                LogicalSize::new(f32::INFINITY, f32::INFINITY),
                f32::INFINITY,
                f32::INFINITY,
            ),
            (
                LogicalSize::new(f32::NEG_INFINITY, 0.0),
                LogicalSize::new(0.0, f32::NEG_INFINITY),
                f32::NEG_INFINITY,
                0.0,
            ),
            (
                LogicalSize::new(f32::MAX, f32::MAX),
                LogicalSize::new(f32::MAX, f32::MAX),
                f32::MAX,
                f32::MAX,
            ),
            (
                LogicalSize::new(0.0, 0.0),
                LogicalSize::new(0.0, 0.0),
                0.0,
                0.0,
            ),
        ] {
            tree.resolve_box_props(1, cb, vp, efs, rfs);
            let bp = tree.get(LayoutNodeId::new(1)).unwrap().box_props.unpack();
            for v in [
                bp.margin.top,
                bp.margin.right,
                bp.margin.bottom,
                bp.margin.left,
                bp.padding.top,
                bp.padding.left,
                bp.border.top,
                bp.border.left,
            ] {
                assert!(
                    v.is_finite(),
                    "the i16×10 packing must launder NaN/inf into a finite value, got {v}"
                );
                assert!(
                    (-3277.0..=3277.0).contains(&v),
                    "packed edges are clamped to ±3276.8px, got {v}"
                );
            }
        }
    }
    #[test]
    fn resolve_box_props_resolves_percentages_against_the_containing_block() {
        let sd = styled(
            Dom::create_body().with_child(div_class("m")),
            ".m { margin-left: 50%; }",
        );
        let mut tree = build_tree(&sd);
        tree.resolve_box_props(1, LogicalSize::new(200.0, 100.0), VIEWPORT, 16.0, 16.0);
        let bp = tree.get(LayoutNodeId::new(1)).unwrap().box_props.unpack();
        assert!(
            (bp.margin.left - 100.0).abs() < 0.2,
            "50% of a 200px containing block ≈ 100px, got {}",
            bp.margin.left
        );
    }
    // ==================================================================
    // Anonymous box generation via the real builder
    // ==================================================================
    #[test]
    fn a_whitespace_only_inline_run_generates_no_anonymous_box() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        let ws = text_node(&sd, " \n\t");
        assert!(
            !tree.dom_to_layout.contains_key(&ws),
            "CSS 2.1 §9.2.2.1: collapsible whitespace generates no box"
        );
        assert!(
            tree.nodes.iter().all(|n| n.dom_node_id != Some(ws)),
            "…and no layout node references it"
        );
    }
    #[test]
    fn a_real_inline_run_next_to_a_block_sibling_gets_exactly_one_anonymous_wrapper() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        let wrappers: Vec<usize> = (0..tree.nodes.len())
            .filter(|&i| {
                tree.cold(LayoutNodeId::new(i)).unwrap().anonymous_type
                    == Some(AnonymousBoxType::InlineWrapper)
            })
            .collect();
        assert_eq!(
            wrappers.len(),
            1,
            "only the trailing `tail` run needs wrapping"
        );
        let w = wrappers[0];
        assert_eq!(
            tree.get(LayoutNodeId::new(w)).unwrap().dom_node_id,
            None,
            "anon boxes have no DOM node"
        );
        assert_eq!(
            tree.cold(LayoutNodeId::new(w)).unwrap().dirty_flag,
            DirtyFlag::Layout
        );
        let tail = text_node(&sd, "tail");
        let kids = tree.children(w);
        assert_eq!(kids.len(), 1);
        assert_eq!(
            tree.get(LayoutNodeId::new(kids[0])).unwrap().dom_node_id,
            Some(tail)
        );
    }
    #[test]
    fn an_all_inline_block_container_gets_no_anonymous_wrapper() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        // `.block` (DOM 1) holds only inline children — the all-inline fast path
        // must hand them straight to the parent, with no wrapper in between.
        let block_idx = (0..tree.nodes.len())
            .find(|&i| tree.get(LayoutNodeId::new(i)).unwrap().dom_node_id == Some(NodeId::new(1)))
            .expect("the .block layout node");
        let kids = tree.children(block_idx);
        assert_eq!(kids.len(), 2, "the text run and the inline div, unwrapped");
        assert!(
            kids.iter().all(|&c| tree
                .cold(LayoutNodeId::new(c))
                .unwrap()
                .anonymous_type
                .is_none()),
            "an all-inline block container needs no anonymous wrapper"
        );
        assert_eq!(
            tree.get(LayoutNodeId::new(block_idx))
                .unwrap()
                .formatting_context,
            FormattingContext::Inline,
            "it establishes an IFC instead"
        );
    }
    #[test]
    fn the_marker_pseudo_element_is_inserted_as_the_first_child_of_a_list_item() {
        let sd = styled(
            Dom::create_body().with_child(div_class("li").with_child(
                Dom::create_text_do_not_use_without_block_level_wrapper("item"),
            )),
            ".li { display: list-item; }",
        );
        let tree = build_tree(&sd);
        let marker = (0..tree.nodes.len())
            .find(|&i| {
                tree.warm(LayoutNodeId::new(i)).unwrap().pseudo_element
                    == Some(PseudoElement::Marker)
            })
            .expect("display:list-item must generate a ::marker");
        let li = tree
            .get(LayoutNodeId::new(marker))
            .unwrap()
            .parent
            .expect("marker has a parent");
        assert_eq!(
            tree.children(li)[0],
            marker,
            "CSS Lists 3 §3.1: ::marker is the FIRST child"
        );
        assert_eq!(
            tree.get(LayoutNodeId::new(marker)).unwrap().dom_node_id,
            tree.get(LayoutNodeId::new(li)).unwrap().dom_node_id,
            "the marker shares the list-item's DOM node for counter/style resolution"
        );
        assert_eq!(
            tree.get(LayoutNodeId::new(marker))
                .unwrap()
                .formatting_context,
            FormattingContext::Inline
        );
        assert!(
            tree.dom_to_layout[&tree
                .get(LayoutNodeId::new(li))
                .unwrap()
                .dom_node_id
                .unwrap()]
                .contains(&LayoutNodeId::new(marker)),
            "the marker is registered in dom_to_layout for counter resolution"
        );
    }
    #[test]
    fn display_none_children_never_reach_the_layout_tree() {
        let sd = styled(
            Dom::create_body()
                .with_child(div_class("gone"))
                .with_child(div_class("here")),
            ".gone { display: none; } .here { display: block; }",
        );
        let tree = build_tree(&sd);
        assert_eq!(
            tree.children(tree.root).len(),
            1,
            "display:none generates no box"
        );
    }
    #[test]
    fn display_contents_promotes_its_children_to_the_grandparent() {
        let sd = styled(
            Dom::create_body().with_child(div_class("c").with_child(div_class("kid"))),
            ".c { display: contents; } .kid { display: block; }",
        );
        let tree = build_tree(&sd);
        // The `.c` box is removed from its parent's child list; `.kid` is hoisted.
        let root_kids = tree.children(tree.root);
        assert!(
            root_kids.iter().any(|&i| tree
                .warm(LayoutNodeId::new(i))
                .unwrap()
                .computed_style
                .display
                == LayoutDisplay::Block),
            "the promoted child must be a direct child of the root"
        );
    }
    #[test]
    fn a_table_with_a_bare_cell_gets_an_anonymous_row() {
        let sd = styled(
            Dom::create_body().with_child(div_class("t").with_child(div_class("cell"))),
            ".t { display: table; } .cell { display: table-cell; }",
        );
        let tree = build_tree(&sd);
        assert!(
            (0..tree.nodes.len()).any(|i| {
                tree.cold(LayoutNodeId::new(i)).unwrap().anonymous_type
                    == Some(AnonymousBoxType::TableRow)
            }),
            "CSS 2.2 §17.2.1 stage 2: a non-proper table child is wrapped in an anonymous row"
        );
    }
    #[test]
    fn whitespace_between_table_rows_is_dropped_not_wrapped() {
        let sd = styled(
            Dom::create_body().with_child(
                div_class("t")
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                        "   ",
                    ))
                    .with_child(div_class("row")),
            ),
            ".t { display: table; } .row { display: table-row; }",
        );
        let tree = build_tree(&sd);
        let ws = text_node(&sd, "   ");
        assert!(
            !tree.dom_to_layout.contains_key(&ws),
            "stage 1: irrelevant (whitespace) boxes are removed"
        );
        assert!(
            !(0..tree.nodes.len()).any(|i| tree.cold(LayoutNodeId::new(i)).unwrap().anonymous_type
                == Some(AnonymousBoxType::TableRow)),
            "and no anonymous row is generated for it"
        );
    }
    #[test]
    fn table_column_children_are_suppressed_entirely() {
        let sd = styled(
            Dom::create_body().with_child(div_class("col").with_child(div_class("kid"))),
            ".col { display: table-column; } .kid { display: block; }",
        );
        let tree = build_tree(&sd);
        // CSS 2.2 §17.2.1: all children of a table-column are display:none.
        let col = tree.children(tree.root)[0];
        assert!(tree.children(col).is_empty());
    }
    // ==================================================================
    // LayoutTreeBuilder (constructor / numeric / boundary)
    // ==================================================================
    #[test]
    fn builder_new_starts_completely_empty() {
        let b = LayoutTreeBuilder::new(VIEWPORT);
        assert!(b.get(0).is_none());
        assert!(b.get(usize::MAX).is_none());
        assert!(b.nodes.is_empty());
        assert!(b.dom_to_layout.is_empty());
        assert_eq!(b.viewport_size, VIEWPORT);
    }
    #[test]
    fn builder_new_accepts_degenerate_viewports() {
        for vp in [
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(-1.0, -1.0),
            LogicalSize::new(f32::MAX, f32::MAX),
            LogicalSize::new(f32::NAN, f32::INFINITY),
        ] {
            let b = LayoutTreeBuilder::new(vp);
            assert!(b.nodes.is_empty());
        }
    }
    #[test]
    fn builder_get_and_get_mut_are_none_out_of_range() {
        let sd = mixed_dom();
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        assert_eq!(root, 0);
        assert!(b.get(0).is_some());
        assert!(b.get_mut(0).is_some());
        for idx in [1, usize::MAX, usize::MAX - 1] {
            assert!(b.get(idx).is_none(), "get({idx})");
            assert!(b.get_mut(idx).is_none(), "get_mut({idx})");
        }
    }
    #[test]
    fn create_anonymous_node_wires_up_parent_children_and_cold_defaults() {
        let sd = mixed_dom();
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        let root_fc = b.get(root).unwrap().formatting_context;
        let anon = b.create_anonymous_node(
            root,
            AnonymousBoxType::TableCell,
            FormattingContext::TableCell,
        );
        assert_eq!(anon, 1, "anon nodes are appended");
        let n = b.get(anon).unwrap();
        assert_eq!(n.dom_node_id, None, "anonymous ⇒ no DOM node");
        assert_eq!(n.anonymous_type, Some(AnonymousBoxType::TableCell));
        assert_eq!(n.formatting_context, FormattingContext::TableCell);
        assert_eq!(n.parent, Some(root));
        assert_eq!(n.parent_formatting_context, Some(root_fc));
        assert_eq!(n.dirty_flag, DirtyFlag::Layout, "a fresh box needs layout");
        assert!(n.children.is_empty());
        assert_eq!(n.subtree_hash, SubtreeHash(0));
        assert!(n.ifc_id.is_none());
        assert_eq!(b.get(root).unwrap().children, vec![anon]);
        assert!(
            b.dom_to_layout.values().all(|v| !v.contains(&anon)),
            "anon boxes are never registered in dom_to_layout"
        );
    }
    #[test]
    fn create_anonymous_node_appends_in_call_order() {
        let sd = mixed_dom();
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        let a = b.create_anonymous_node(
            root,
            AnonymousBoxType::TableRow,
            FormattingContext::TableRow,
        );
        let c = b.create_anonymous_node(
            root,
            AnonymousBoxType::TableCell,
            FormattingContext::TableCell,
        );
        assert_eq!((a, c), (1, 2));
        assert_eq!(b.get(root).unwrap().children, vec![a, c]);
    }
    #[test]
    fn create_node_from_dom_registers_the_dom_mapping_and_the_parent_link() {
        let sd = mixed_dom();
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        let child = b.create_node_from_dom(&sd, NodeId::new(1), Some(root), &mut msgs);
        assert_eq!(b.get(child).unwrap().dom_node_id, Some(NodeId::new(1)));
        assert_eq!(b.get(child).unwrap().parent, Some(root));
        assert_eq!(b.get(root).unwrap().children, vec![child]);
        assert_eq!(b.dom_to_layout[&NodeId::new(1)], vec![child]);
        assert_eq!(b.get(child).unwrap().dirty_flag, DirtyFlag::Layout);
    }
    #[test]
    fn create_node_from_dom_turns_the_roots_visible_overflow_into_auto() {
        // CSS Overflow 3 §3.3 — only for the root (parent == None).
        let sd = styled(
            Dom::create_body().with_child(div_class("d")),
            ".d { display: block; }",
        );
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        let child = b.create_node_from_dom(&sd, NodeId::new(1), Some(root), &mut msgs);
        let root_style = &b.get(root).unwrap().computed_style;
        assert_ne!(root_style.overflow_x, LayoutOverflow::Visible);
        assert_ne!(root_style.overflow_y, LayoutOverflow::Visible);
        let child_style = &b.get(child).unwrap().computed_style;
        assert_eq!(
            child_style.overflow_x,
            LayoutOverflow::Visible,
            "the rule applies to the viewport only, not to every node"
        );
    }
    #[test]
    fn clone_node_from_old_resets_children_and_dirty_state() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        let old_root = tree.get_full_node(0).unwrap();
        let old_child = tree.get_full_node(1).unwrap();
        assert!(
            !old_root.children.is_empty(),
            "the source root has children"
        );
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let root = b.clone_node_from_old(&old_root, None, old_root.dom_node_id);
        let child = b.clone_node_from_old(&old_child, Some(root), old_child.dom_node_id);
        assert_eq!((root, child), (0, 1));
        assert!(
            b.get(root).unwrap().children == vec![child],
            "the clone's children come only from later clone calls"
        );
        assert!(b.get(child).unwrap().children.is_empty());
        assert_eq!(b.get(child).unwrap().parent, Some(root));
        assert_eq!(b.get(child).unwrap().dirty_flag, DirtyFlag::None);
        let root_fc = b.get(root).unwrap().formatting_context;
        assert_eq!(
            b.get(child).unwrap().parent_formatting_context,
            Some(root_fc)
        );
    }
    #[test]
    fn clone_node_from_old_skips_dom_registration_for_anonymous_nodes() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        let anon = (0..tree.nodes.len())
            .find(|&i| {
                tree.cold(LayoutNodeId::new(i))
                    .unwrap()
                    .anonymous_type
                    .is_some()
            })
            .expect("mixed_dom generates one anonymous wrapper");
        let old = tree.get_full_node(anon).unwrap();
        assert_eq!(old.dom_node_id, None);
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let idx = b.clone_node_from_old(&old, None, old.dom_node_id);
        assert_eq!(idx, 0);
        assert!(
            b.dom_to_layout.is_empty(),
            "a node with no dom_node_id must not create a mapping entry"
        );
    }
    /// A clone takes the identity it is given, not the identity it was
    /// copied from.
    ///
    /// Reconciliation falls back to POSITIONAL matching when a new child's
    /// DOM id is absent from the old child list (`cache.rs`, the
    /// `.or_else(|| old_children_indices.get(i))` arm). That pairs an old
    /// node with a new node of a DIFFERENT id, and the clone is taken to
    /// reuse the old node's measurements. Carrying the old id through made
    /// the new tree describe a DOM that no longer exists: after a ribbon
    /// tab switch shrank the tree, `compute_counters` panicked indexing
    /// `node_data[52]` on a 37-node StyledDom, and everything quieter —
    /// style lookups, node rects, damage attribution — read the wrong node.
    ///
    /// NEGATIVE CONTROL: restoring `new_node.dom_node_id` to the old value
    /// (i.e. dropping the `new_node.dom_node_id = new_dom_id` assignment)
    /// makes both assertions below fail — verified.
    #[test]
    fn a_clone_takes_the_new_dom_identity_not_the_one_it_was_copied_from() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        // Any node that HAS a DOM id; its id is the "old" one.
        let old_idx = (0..tree.nodes.len())
            .find(|&i| tree.get_full_node(i).and_then(|n| n.dom_node_id).is_some())
            .expect("mixed_dom has DOM-backed nodes");
        let old = tree.get_full_node(old_idx).unwrap();
        let old_id = old.dom_node_id.unwrap();
        // Reconcile it against a DIFFERENT DOM node, as the positional
        // fallback does.
        let new_id = NodeId::new(old_id.index() + 7);
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let idx = b.clone_node_from_old(&old, None, Some(new_id));
        assert_eq!(
            b.get(idx).unwrap().dom_node_id,
            Some(new_id),
            "the clone must describe the node it was reconciled AGAINST"
        );
        assert_eq!(
            b.dom_to_layout.get(&new_id).map(Vec::as_slice),
            Some(&[idx][..]),
            "dom_to_layout must index the clone under its NEW id"
        );
        assert!(
            !b.dom_to_layout.contains_key(&old_id),
            "the identity it was copied from must leave no mapping behind - a stale entry here is \
             what hands a later lookup a different node's rect"
        );
    }
    #[test]
    fn build_flattens_children_into_the_arena_losslessly() {
        let sd = mixed_dom();
        let mut builder = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root_id = sd.root.into_crate_internal().unwrap_or(NodeId::ZERO);
        let root = builder.process_node(&sd, root_id, None, &mut msgs).unwrap();
        let expected: Vec<Vec<usize>> = builder.nodes.iter().map(|n| n.children.clone()).collect();
        let tree = builder.build(root);
        assert_eq!(tree.nodes.len(), expected.len());
        assert_eq!(tree.warm.len(), expected.len());
        assert_eq!(tree.cold.len(), expected.len());
        for (i, want) in expected.iter().enumerate() {
            assert_eq!(tree.children(i), want.as_slice(), "node {i}");
        }
    }
    #[test]
    fn build_on_an_empty_builder_yields_an_empty_tree() {
        let tree = LayoutTreeBuilder::new(VIEWPORT).build(0);
        assert!(tree.nodes.is_empty());
        assert!(tree.children_arena.is_empty());
        assert!(tree.children_offsets.is_empty());
        assert!(tree.subtree_needs_intrinsic.is_empty());
        assert!(tree.get(LayoutNodeId::new(0)).is_none());
        assert!(tree.children(0).is_empty());
        assert_eq!(
            tree.get_content_size(LayoutNodeId::new(0)),
            LogicalSize::default()
        );
        assert_eq!(tree.memory_report().node_count, 0);
    }
    #[test]
    fn build_with_an_out_of_range_root_index_does_not_panic() {
        let sd = mixed_dom();
        let mut builder = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        builder
            .process_node(&sd, NodeId::ZERO, None, &mut msgs)
            .unwrap();
        let tree = builder.build(usize::MAX);
        assert_eq!(tree.root, usize::MAX, "build() stores the index verbatim");
        assert!(tree.get(LayoutNodeId::new(tree.root)).is_none());
        assert!(tree.children(tree.root).is_empty());
        assert_eq!(tree.get_ifc_root_layout_index(tree.root), usize::MAX);
    }
    #[test]
    fn blockify_node_display_blockifies_an_inline_flex_item() {
        let sd = styled(
            Dom::create_body().with_child(div_class("f").with_child(div_class("i"))),
            ".f { display: flex; } .i { display: inline; }",
        );
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        let flex = b.create_node_from_dom(&sd, NodeId::new(1), Some(root), &mut msgs);
        let item = b.create_node_from_dom(&sd, NodeId::new(2), Some(flex), &mut msgs);
        assert_eq!(
            b.get(flex).unwrap().formatting_context,
            FormattingContext::Flex
        );
        assert_eq!(
            b.get(item).unwrap().computed_style.display,
            LayoutDisplay::Inline
        );
        b.blockify_node_display(&sd, NodeId::new(2), item, Some(flex));
        assert_eq!(
            b.get(item).unwrap().computed_style.display,
            LayoutDisplay::Block,
            "CSS Display 3 §2.7: a flex item's inline display blockifies"
        );
        assert!(matches!(
            b.get(item).unwrap().formatting_context,
            FormattingContext::Block { .. }
        ));
    }
    #[test]
    fn blockify_node_display_leaves_a_plain_block_child_alone() {
        let sd = styled(
            Dom::create_body().with_child(div_class("p").with_child(div_class("b"))),
            ".p { display: block; } .b { display: block; }",
        );
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        let p = b.create_node_from_dom(&sd, NodeId::new(1), Some(root), &mut msgs);
        let child = b.create_node_from_dom(&sd, NodeId::new(2), Some(p), &mut msgs);
        let before = b.get(child).unwrap().formatting_context;
        b.blockify_node_display(&sd, NodeId::new(2), child, Some(p));
        assert_eq!(
            b.get(child).unwrap().computed_style.display,
            LayoutDisplay::Block
        );
        assert_eq!(b.get(child).unwrap().formatting_context, before);
    }
    #[test]
    fn blockify_node_display_with_a_bogus_node_index_is_a_no_op() {
        let sd = mixed_dom();
        let mut b = LayoutTreeBuilder::new(VIEWPORT);
        let mut msgs = None;
        let root = b.create_node_from_dom(&sd, NodeId::ZERO, None, &mut msgs);
        // A valid DOM id with a garbage layout index must not panic: both the
        // read and the write go through `get`/`get_mut`.
        b.blockify_node_display(&sd, NodeId::ZERO, usize::MAX, None);
        b.blockify_node_display(&sd, NodeId::ZERO, 999, Some(usize::MAX));
        assert_eq!(b.nodes.len(), 1);
        assert!(b.get(root).is_some());
    }
    // ==================================================================
    // blockify_flex_item_if_table_internal (numeric / slice bounds)
    // ==================================================================
    #[test]
    fn blockify_flex_item_rewrites_every_table_internal_context() {
        let tree = build_tree(&mixed_dom());
        let mut nodes = vec![tree.get_full_node(0).unwrap()];
        for fc in [
            FormattingContext::TableCell,
            FormattingContext::TableRow,
            FormattingContext::TableRowGroup,
            FormattingContext::TableColumnGroup,
            FormattingContext::TableCaption,
            FormattingContext::Table,
        ] {
            nodes[0].formatting_context = fc;
            blockify_flex_item_if_table_internal(&mut nodes, 0);
            assert_eq!(
                nodes[0].formatting_context,
                FormattingContext::Block {
                    establishes_new_context: true
                },
                "{fc:?} is table-internal and must blockify"
            );
        }
    }
    #[test]
    fn blockify_flex_item_leaves_non_table_contexts_untouched() {
        let tree = build_tree(&mixed_dom());
        let mut nodes = vec![tree.get_full_node(0).unwrap()];
        for fc in [
            FormattingContext::Inline,
            FormattingContext::InlineBlock,
            FormattingContext::Flex,
            FormattingContext::Grid,
            FormattingContext::None,
            FormattingContext::Contents,
            FormattingContext::Block {
                establishes_new_context: false,
            },
        ] {
            nodes[0].formatting_context = fc;
            blockify_flex_item_if_table_internal(&mut nodes, 0);
            assert_eq!(nodes[0].formatting_context, fc, "{fc:?} must be left alone");
        }
    }
    #[test]
    fn blockify_flex_item_out_of_range_or_empty_is_a_no_op() {
        let tree = build_tree(&mixed_dom());
        let mut nodes = vec![tree.get_full_node(0).unwrap()];
        nodes[0].formatting_context = FormattingContext::TableCell;
        blockify_flex_item_if_table_internal(&mut nodes, 1);
        blockify_flex_item_if_table_internal(&mut nodes, usize::MAX);
        blockify_flex_item_if_table_internal(&mut [], 0);
        blockify_flex_item_if_table_internal(&mut [], usize::MAX);
        assert_eq!(nodes[0].formatting_context, FormattingContext::TableCell);
    }
    #[test]
    fn table_cell_flex_items_do_not_produce_anonymous_table_boxes() {
        // CSS Flexbox §3: two `display:table-cell` flex items become two
        // independent block flex items, NOT one anonymous table row.
        let sd = styled(
            Dom::create_body().with_child(
                div_class("f")
                    .with_child(div_class("c"))
                    .with_child(div_class("c")),
            ),
            ".f { display: flex; } .c { display: table-cell; }",
        );
        let tree = build_tree(&sd);
        assert!(
            (0..tree.nodes.len()).all(|i| tree
                .cold(LayoutNodeId::new(i))
                .unwrap()
                .anonymous_type
                .is_none()),
            "no anonymous table boxes for blockified flex items"
        );
        let flex = tree.children(tree.root)[0];
        for &c in tree.children(flex) {
            assert!(matches!(
                tree.get(LayoutNodeId::new(c)).unwrap().formatting_context,
                FormattingContext::Block { .. }
            ));
        }
    }
    // ==================================================================
    // Shrink-to-fit bitmap
    // ==================================================================
    #[test]
    fn is_shrink_to_fit_context_is_true_for_the_intrinsic_reading_contexts() {
        let sd = mixed_dom();
        for fc in [
            FormattingContext::Flex,
            FormattingContext::Grid,
            FormattingContext::Table,
            FormattingContext::InlineBlock,
        ] {
            assert!(
                is_shrink_to_fit_context(&sd, None, fc),
                "{fc:?} sizes from children's intrinsics"
            );
        }
    }
    #[test]
    fn is_shrink_to_fit_context_is_false_for_a_plain_block_with_no_dom_node() {
        let sd = mixed_dom();
        for fc in [
            FormattingContext::Block {
                establishes_new_context: false,
            },
            FormattingContext::Block {
                establishes_new_context: true,
            },
            FormattingContext::Inline,
            FormattingContext::None,
            FormattingContext::TableRow,
        ] {
            assert!(
                !is_shrink_to_fit_context(&sd, None, fc),
                "{fc:?} with no DOM node cannot be float/abspos ⇒ not STF"
            );
        }
    }
    #[test]
    fn is_shrink_to_fit_context_catches_floats_and_abspos() {
        let sd = styled(
            Dom::create_body()
                .with_child(div_class("fl"))
                .with_child(div_class("ab"))
                .with_child(div_class("fx"))
                .with_child(div_class("plain")),
            ".fl { float: left; } .ab { position: absolute; } .fx { position: fixed; } .plain { \
             display: block; }",
        );
        let block = FormattingContext::Block {
            establishes_new_context: false,
        };
        assert!(
            is_shrink_to_fit_context(&sd, Some(NodeId::new(1)), block),
            "float:left"
        );
        assert!(
            is_shrink_to_fit_context(&sd, Some(NodeId::new(2)), block),
            "position:absolute"
        );
        assert!(
            is_shrink_to_fit_context(&sd, Some(NodeId::new(3)), block),
            "position:fixed"
        );
        assert!(
            !is_shrink_to_fit_context(&sd, Some(NodeId::new(4)), block),
            "an in-flow static block is sized top-down ⇒ not STF"
        );
    }
    #[test]
    fn compute_subtree_needs_intrinsic_is_one_bit_per_node() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        let bits = compute_subtree_needs_intrinsic(&sd, &tree);
        assert_eq!(bits.len(), tree.nodes.len());
        assert_eq!(tree.subtree_needs_intrinsic.len(), tree.nodes.len());
    }
    #[test]
    fn compute_subtree_needs_intrinsic_is_all_false_for_a_pure_block_tree() {
        let sd = mixed_dom();
        let tree = build_tree(&sd);
        assert!(
            compute_subtree_needs_intrinsic(&sd, &tree)
                .iter()
                .all(|b| !b),
            "nothing in mixed_dom() is flex/grid/table/float/abspos"
        );
    }
    #[test]
    fn compute_subtree_needs_intrinsic_propagates_a_deep_flex_up_to_the_root() {
        let sd = styled(
            Dom::create_body()
                .with_child(div_class("a").with_child(div_class("b").with_child(div_class("f")))),
            ".a { display: block; } .b { display: block; } .f { display: flex; }",
        );
        let tree = build_tree(&sd);
        let bits = compute_subtree_needs_intrinsic(&sd, &tree);
        assert!(
            bits[tree.root],
            "out[i] = self || any(children) — must reach the root"
        );
        assert!(
            bits.iter().all(|b| *b),
            "every node on the chain is on the flex path"
        );
    }
    #[test]
    fn compute_subtree_needs_intrinsic_leaves_a_flex_free_sibling_branch_false() {
        let sd = styled(
            Dom::create_body()
                .with_child(div_class("f"))
                .with_child(div_class("plain")),
            ".f { display: flex; } .plain { display: block; }",
        );
        let tree = build_tree(&sd);
        let bits = compute_subtree_needs_intrinsic(&sd, &tree);
        let kids = tree.children(tree.root);
        let flex = kids
            .iter()
            .copied()
            .find(|&i| {
                tree.get(LayoutNodeId::new(i)).unwrap().formatting_context
                    == FormattingContext::Flex
            })
            .expect("the flex child");
        let plain = kids
            .iter()
            .copied()
            .find(|&i| i != flex)
            .expect("the plain child");
        assert!(bits[flex]);
        assert!(
            !bits[plain],
            "a sibling that reads no intrinsics stays false"
        );
        assert!(bits[tree.root], "…but the root still sees the flex branch");
    }
    #[test]
    fn compute_subtree_needs_intrinsic_on_an_empty_tree_is_empty() {
        let sd = mixed_dom();
        let tree = raw_tree(Vec::new(), &[]);
        assert!(compute_subtree_needs_intrinsic(&sd, &tree).is_empty());
    }
    // ==================================================================
    // Level / display predicates
    // ==================================================================
    #[test]
    fn is_block_level_matches_the_block_level_display_values() {
        let sd = styled(
            Dom::create_body()
                .with_child(div_class("b"))
                .with_child(div_class("i")),
            ".b { display: block; } .i { display: inline; }",
        );
        assert!(is_block_level(&sd, NodeId::new(1)));
        assert!(!is_block_level(&sd, NodeId::new(2)));
    }
    #[test]
    fn is_block_level_covers_the_table_and_list_item_families() {
        for (css_display, want) in [
            ("block", true),
            ("flow-root", true),
            ("flex", true),
            ("grid", true),
            ("table", true),
            ("table-row", true),
            ("table-cell", true),
            ("table-caption", true),
            ("list-item", true),
            ("inline", false),
            ("inline-block", false),
            ("inline-flex", false),
            ("inline-grid", false),
            ("inline-table", false),
            ("none", false),
        ] {
            let sd = styled(
                Dom::create_body().with_child(div_class("x")),
                &format!(".x {{ display: {css_display}; }}"),
            );
            assert_eq!(
                is_block_level(&sd, NodeId::new(1)),
                want,
                "display:{css_display}"
            );
        }
    }
    #[test]
    fn is_inline_level_is_always_true_for_text_regardless_of_display() {
        let sd = styled(
            Dom::create_body().with_child(
                div_class("b")
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("t")),
            ),
            ".b { display: block; }",
        );
        let t = text_node(&sd, "t");
        assert!(
            is_inline_level(&sd, t),
            "text nodes are inline-level by definition"
        );
        assert!(
            !is_inline_level(&sd, NodeId::new(1)),
            "the block div is not"
        );
    }
    #[test]
    fn is_inline_level_matches_the_inline_display_family() {
        for (css_display, want) in [
            ("inline", true),
            ("inline-block", true),
            ("inline-table", true),
            ("inline-flex", true),
            ("inline-grid", true),
            ("block", false),
            ("flex", false),
            ("table", false),
            ("list-item", false),
        ] {
            let sd = styled(
                Dom::create_body().with_child(div_class("x")),
                &format!(".x {{ display: {css_display}; }}"),
            );
            assert_eq!(
                is_inline_level(&sd, NodeId::new(1)),
                want,
                "display:{css_display}"
            );
        }
    }
    #[test]
    fn block_and_inline_level_are_mutually_exclusive_for_element_nodes() {
        for css_display in [
            "block",
            "inline",
            "inline-block",
            "flex",
            "inline-flex",
            "grid",
            "table",
            "list-item",
        ] {
            let sd = styled(
                Dom::create_body().with_child(div_class("x")),
                &format!(".x {{ display: {css_display}; }}"),
            );
            let id = NodeId::new(1);
            assert!(
                !(is_block_level(&sd, id) && is_inline_level(&sd, id)),
                "display:{css_display} cannot be both block- and inline-level"
            );
        }
    }
    #[test]
    fn has_only_inline_children_is_false_for_a_childless_node() {
        let sd = styled(
            Dom::create_body().with_child(div_class("e")),
            ".e { display: block; }",
        );
        assert!(
            !has_only_inline_children(&sd, NodeId::new(1)),
            "no children ⇒ no IFC (it's empty, not inline)"
        );
    }
    #[test]
    fn has_only_inline_children_is_true_for_an_all_inline_run() {
        let sd = mixed_dom();
        // `.block` (DOM 1) holds a text node and an inline div.
        assert!(has_only_inline_children(&sd, NodeId::new(1)));
    }
    #[test]
    fn has_only_inline_children_is_false_as_soon_as_one_block_child_appears() {
        let sd = mixed_dom();
        // `.mixed` (DOM 5) holds text + a block div + text.
        assert!(!has_only_inline_children(&sd, NodeId::new(5)));
    }
    #[test]
    fn has_only_inline_children_is_false_for_an_out_of_range_node_id() {
        let sd = mixed_dom();
        let past_end = NodeId::new(sd.node_data.len() + 10);
        assert!(
            !has_only_inline_children(&sd, past_end),
            "the hierarchy lookup is a `.get`, so a bogus id must be false, not a panic"
        );
        assert!(!has_only_inline_children(&sd, NodeId::new(usize::MAX / 2)));
    }
    // ==================================================================
    // is_whitespace_only_text (predicate / unicode / boundary)
    // ==================================================================
    fn ws_dom(text: &str, css: &str) -> StyledDom {
        styled(
            Dom::create_body().with_child(div_class("p").with_child(
                Dom::create_text_do_not_use_without_block_level_wrapper(text),
            )),
            css,
        )
    }
    #[test]
    fn is_whitespace_only_text_recognises_the_css_document_whitespace_set() {
        // CSS Text 3 §4.1: space, tab, CR, LF, FF.
        for text in [" ", "\t", "\n", "\r", "\u{000C}", " \t\r\n\u{000C} "] {
            let sd = ws_dom(text, "");
            let id = NodeId::new(2);
            assert!(
                is_whitespace_only_text(&sd, id),
                "{text:?} is collapsible document whitespace"
            );
        }
    }
    #[test]
    fn is_whitespace_only_text_rejects_unicode_spaces_that_css_does_not_collapse() {
        // NBSP, ideographic space, en/em space, zero-width space, line separator:
        // none of these are in the CSS document-whitespace set.
        for text in [
            "\u{00A0}",
            "\u{3000}",
            "\u{2002}",
            "\u{2003}",
            "\u{200B}",
            "\u{2028}",
            " \u{00A0} ",
        ] {
            let sd = ws_dom(text, "");
            assert!(
                !is_whitespace_only_text(&sd, NodeId::new(2)),
                "{text:?} must NOT be treated as collapsible whitespace"
            );
        }
    }
    #[test]
    fn is_whitespace_only_text_is_false_for_real_text() {
        for text in ["hi", " hi ", "\u{1F600}", "a\nb"] {
            let sd = ws_dom(text, "");
            assert!(!is_whitespace_only_text(&sd, NodeId::new(2)), "{text:?}");
        }
    }
    #[test]
    fn is_whitespace_only_text_treats_the_empty_string_as_whitespace() {
        // `"".chars().all(..)` is vacuously true — an empty text node is
        // collapsible and generates no anonymous inline box.
        let sd = ws_dom("", "");
        assert!(is_whitespace_only_text(&sd, NodeId::new(2)));
    }
    #[test]
    fn is_whitespace_only_text_respects_whitespace_preserving_modes() {
        for (ws, collapses) in [
            ("normal", true),
            ("nowrap", true),
            ("pre-line", true),
            ("pre", false),
            ("pre-wrap", false),
            ("break-spaces", false),
        ] {
            let sd = ws_dom(" \n ", &format!(".p {{ white-space: {ws}; }}"));
            assert_eq!(
                is_whitespace_only_text(&sd, NodeId::new(2)),
                collapses,
                "white-space:{ws} — preserved whitespace still generates a box"
            );
        }
    }
    #[test]
    fn is_whitespace_only_text_is_false_for_non_text_and_bogus_nodes() {
        let sd = mixed_dom();
        assert!(
            !is_whitespace_only_text(&sd, NodeId::new(1)),
            "a div is not text"
        );
        assert!(
            !is_whitespace_only_text(&sd, NodeId::ZERO),
            "the body is not text"
        );
        let past_end = NodeId::new(sd.node_data.len() + 1);
        assert!(
            !is_whitespace_only_text(&sd, past_end),
            "an out-of-range id must return false, not panic"
        );
        assert!(!is_whitespace_only_text(&sd, NodeId::new(usize::MAX / 2)));
    }
    // ==================================================================
    // Table-structure predicates
    // ==================================================================
    #[test]
    fn should_skip_for_table_structure_only_fires_inside_table_parents() {
        let sd = ws_dom(" ", "");
        let ws = NodeId::new(2);
        for parent in [
            LayoutDisplay::Table,
            LayoutDisplay::InlineTable,
            LayoutDisplay::TableRowGroup,
            LayoutDisplay::TableHeaderGroup,
            LayoutDisplay::TableFooterGroup,
            LayoutDisplay::TableRow,
            // css-flexbox-1 section 4 / css-grid-1 section 6: whitespace-only
            // anonymous items are not rendered in flex/grid containers.
            LayoutDisplay::Flex,
            LayoutDisplay::InlineFlex,
            LayoutDisplay::Grid,
            LayoutDisplay::InlineGrid,
        ] {
            assert!(
                should_skip_for_table_structure(&sd, ws, parent),
                "whitespace under {parent:?} is an irrelevant box"
            );
        }
        for parent in [
            LayoutDisplay::Block,
            LayoutDisplay::Inline,
            LayoutDisplay::TableCell,
            LayoutDisplay::TableCaption,
            LayoutDisplay::TableColumn,
        ] {
            assert!(
                !should_skip_for_table_structure(&sd, ws, parent),
                "whitespace under {parent:?} is NOT an irrelevant box"
            );
        }
    }
    #[test]
    fn should_skip_for_table_structure_never_skips_real_content() {
        let sd = ws_dom("cell text", "");
        for parent in ALL_DISPLAYS {
            assert!(
                !should_skip_for_table_structure(&sd, NodeId::new(2), parent),
                "non-whitespace text must never be dropped (parent {parent:?})"
            );
        }
    }
    #[test]
    fn is_proper_table_child_matches_exactly_the_seven_spec_values() {
        let proper = [
            LayoutDisplay::TableRowGroup,
            LayoutDisplay::TableHeaderGroup,
            LayoutDisplay::TableFooterGroup,
            LayoutDisplay::TableRow,
            LayoutDisplay::TableColumnGroup,
            LayoutDisplay::TableColumn,
            LayoutDisplay::TableCaption,
        ];
        for d in ALL_DISPLAYS {
            assert_eq!(
                is_proper_table_child(d),
                proper.contains(&d),
                "CSS 2.2 §17.2.1 proper-table-child set: {d:?}"
            );
        }
        assert!(
            !is_proper_table_child(LayoutDisplay::TableCell),
            "a cell is a proper child of a ROW, not of a table"
        );
    }
    // ==================================================================
    // is_replaced_element
    // ==================================================================
    #[test]
    fn is_replaced_element_covers_the_css_display_3_appendix_b_set() {
        for nt in [
            NodeType::Br,
            NodeType::Wbr,
            NodeType::Meter,
            NodeType::Progress,
            NodeType::Canvas,
            NodeType::Embed,
            NodeType::Object,
            NodeType::Audio,
            NodeType::Video,
            NodeType::Input,
            NodeType::TextArea,
            NodeType::Select,
            NodeType::VirtualView,
        ] {
            let nd = NodeData::create_node(nt.clone());
            assert!(is_replaced_element(&nd), "{nt:?} is a replaced element");
        }
        let img =
            NodeData::create_image(ImageRef::null_image(1, 1, RawImageFormat::R8, Vec::new()));
        assert!(
            is_replaced_element(&img),
            "an <img> is the canonical replaced element"
        );
    }
    #[test]
    fn is_replaced_element_is_false_for_ordinary_containers_and_text() {
        for nt in [
            NodeType::Div,
            NodeType::Body,
            NodeType::Html,
            NodeType::P,
            NodeType::Span,
            NodeType::Table,
            NodeType::Button,
            NodeType::Label,
            NodeType::Hr,
        ] {
            let nd = NodeData::create_node(nt.clone());
            assert!(!is_replaced_element(&nd), "{nt:?} is not replaced");
        }
        assert!(!is_replaced_element(
            &NodeData::create_text_do_not_use_without_block_level_wrapper("hello")
        ));
    }
    #[test]
    fn display_contents_on_a_replaced_element_degrades_to_display_none() {
        // CSS Display 3 §2.5: a replaced element cannot be un-boxed.
        let sd = styled(
            Dom::create_body().with_child(
                Dom::create_from_data(NodeData::create_node(NodeType::Br))
                    .with_ids_and_classes(vec![IdOrClass::Class("c".into())].into()),
            ),
            ".c { display: contents; }",
        );
        let tree = build_tree(&sd);
        assert!(
            tree.children(tree.root).is_empty(),
            "the <br> must be dropped from its parent's child list"
        );
        let br = (0..tree.nodes.len())
            .find(|&i| tree.get(LayoutNodeId::new(i)).unwrap().dom_node_id == Some(NodeId::new(1)))
            .expect("the node object still exists, just unparented");
        assert_eq!(
            tree.warm(LayoutNodeId::new(br))
                .unwrap()
                .computed_style
                .display,
            LayoutDisplay::None
        );
        assert_eq!(
            tree.get(LayoutNodeId::new(br)).unwrap().formatting_context,
            FormattingContext::None
        );
    }
    // ==================================================================
    // get_display_type
    // ==================================================================
    #[test]
    fn get_display_type_reads_the_computed_display() {
        for (css_display, want) in [
            ("none", LayoutDisplay::None),
            ("block", LayoutDisplay::Block),
            ("inline", LayoutDisplay::Inline),
            ("inline-block", LayoutDisplay::InlineBlock),
            ("flex", LayoutDisplay::Flex),
            ("grid", LayoutDisplay::Grid),
            ("table", LayoutDisplay::Table),
            ("table-row", LayoutDisplay::TableRow),
            ("table-cell", LayoutDisplay::TableCell),
            ("flow-root", LayoutDisplay::FlowRoot),
            ("list-item", LayoutDisplay::ListItem),
            ("contents", LayoutDisplay::Contents),
        ] {
            let sd = styled(
                Dom::create_body().with_child(div_class("x")),
                &format!(".x {{ display: {css_display}; }}"),
            );
            assert_eq!(
                get_display_type(&sd, NodeId::new(1)),
                want,
                "display:{css_display}"
            );
        }
    }
    #[test]
    fn get_display_type_is_stable_across_repeated_calls() {
        let sd = mixed_dom();
        for i in 0..sd.node_data.len() {
            let id = NodeId::new(i);
            let a = get_display_type(&sd, id);
            let b = get_display_type(&sd, id);
            assert_eq!(a, b, "node {i} must be deterministic");
        }
    }
    // ==================================================================
    // Formatting-context determination
    // ==================================================================
    #[test]
    fn determine_formatting_context_is_inline_for_every_text_node() {
        let sd = mixed_dom();
        for needle in ["hello", "world", "tail", " \n\t"] {
            let id = text_node(&sd, needle);
            assert_eq!(
                determine_formatting_context(&sd, id),
                FormattingContext::Inline,
                "text node {needle:?}"
            );
        }
    }
    #[test]
    fn determine_formatting_context_for_display_ignores_display_on_text_nodes() {
        // The text early-out fires before the display match — a text node is
        // Inline even if you hand it `display: grid`.
        let sd = mixed_dom();
        let t = text_node(&sd, "hello");
        for d in ALL_DISPLAYS {
            assert_eq!(
                determine_formatting_context_for_display(&sd, t, d),
                FormattingContext::Inline,
                "text + display:{d:?}"
            );
        }
    }
    #[test]
    fn determine_formatting_context_for_display_maps_each_display_value() {
        let sd = styled(
            Dom::create_body().with_child(div_class("x")),
            ".x { display: block; }",
        );
        let id = NodeId::new(1);
        for (d, want) in [
            (LayoutDisplay::Inline, FormattingContext::Inline),
            (
                LayoutDisplay::FlowRoot,
                FormattingContext::Block {
                    establishes_new_context: true,
                },
            ),
            (LayoutDisplay::InlineBlock, FormattingContext::InlineBlock),
            (LayoutDisplay::Table, FormattingContext::Table),
            (LayoutDisplay::InlineTable, FormattingContext::Table),
            (
                LayoutDisplay::TableRowGroup,
                FormattingContext::TableRowGroup,
            ),
            (
                LayoutDisplay::TableHeaderGroup,
                FormattingContext::TableRowGroup,
            ),
            (
                LayoutDisplay::TableFooterGroup,
                FormattingContext::TableRowGroup,
            ),
            (LayoutDisplay::TableRow, FormattingContext::TableRow),
            (LayoutDisplay::TableCell, FormattingContext::TableCell),
            (
                LayoutDisplay::TableColumnGroup,
                FormattingContext::TableColumnGroup,
            ),
            (LayoutDisplay::TableCaption, FormattingContext::TableCaption),
            (LayoutDisplay::TableColumn, FormattingContext::None),
            (LayoutDisplay::None, FormattingContext::None),
            (LayoutDisplay::Flex, FormattingContext::Flex),
            (LayoutDisplay::InlineFlex, FormattingContext::Flex),
            (LayoutDisplay::Grid, FormattingContext::Grid),
            (LayoutDisplay::InlineGrid, FormattingContext::Grid),
            (LayoutDisplay::Contents, FormattingContext::Contents),
            (
                LayoutDisplay::RunIn,
                FormattingContext::Block {
                    establishes_new_context: true,
                },
            ),
            (
                LayoutDisplay::Marker,
                FormattingContext::Block {
                    establishes_new_context: true,
                },
            ),
        ] {
            assert_eq!(
                determine_formatting_context_for_display(&sd, id, d),
                want,
                "display:{d:?}"
            );
        }
    }
    #[test]
    fn determine_formatting_context_for_display_never_panics_on_any_display_value() {
        let sd = styled(
            Dom::create_body().with_child(div_class("x")),
            ".x { display: block; }",
        );
        for d in ALL_DISPLAYS {
            let _ = determine_formatting_context_for_display(&sd, NodeId::new(1), d);
            let _ = determine_formatting_context_for_display(&sd, NodeId::ZERO, d);
        }
    }
    #[test]
    fn a_block_with_only_inline_children_establishes_an_ifc() {
        let sd = mixed_dom();
        assert_eq!(
            determine_formatting_context(&sd, NodeId::new(1)),
            FormattingContext::Inline,
            "CSS 2.2 §9.4.2: a block container with no block-level boxes establishes an IFC"
        );
    }
    #[test]
    fn a_block_with_a_block_child_stays_a_bfc() {
        let sd = mixed_dom();
        assert!(matches!(
            determine_formatting_context(&sd, NodeId::new(5)),
            FormattingContext::Block { .. }
        ));
    }
    #[test]
    fn establishes_new_bfc_for_the_unconditional_display_values() {
        for css_display in ["inline-block", "table-cell", "table-caption", "flow-root"] {
            let sd = styled(
                Dom::create_body().with_child(div_class("x")),
                &format!(".x {{ display: {css_display}; }}"),
            );
            assert!(
                establishes_new_block_formatting_context(&sd, NodeId::new(1)),
                "display:{css_display} always establishes a BFC"
            );
        }
    }
    #[test]
    fn establishes_new_bfc_for_non_visible_overflow_floats_and_abspos() {
        for css in [
            ".x { display: block; overflow-x: hidden; }",
            ".x { display: block; overflow-y: scroll; }",
            ".x { display: block; overflow: auto; }",
            ".x { display: block; float: left; }",
            ".x { display: block; float: right; }",
            ".x { display: block; position: absolute; }",
            ".x { display: block; position: fixed; }",
        ] {
            let sd = styled(Dom::create_body().with_child(div_class("x")), css);
            assert!(
                establishes_new_block_formatting_context(&sd, NodeId::new(1)),
                "{css} must establish a BFC"
            );
        }
    }
    #[test]
    fn establishes_new_bfc_is_false_for_a_plain_in_flow_block() {
        let sd = styled(
            Dom::create_body().with_child(div_class("x")),
            ".x { display: block; }",
        );
        assert!(
            !establishes_new_block_formatting_context(&sd, NodeId::new(1)),
            "a static, visible-overflow, unfloated block does not open a BFC"
        );
    }
    #[test]
    fn establishes_new_bfc_for_the_root_and_for_replaced_elements() {
        let sd = styled(
            Dom::create_body()
                .with_child(Dom::create_from_data(NodeData::create_node(NodeType::Br))),
            "",
        );
        assert!(
            establishes_new_block_formatting_context(&sd, NodeId::ZERO),
            "the root element always establishes a BFC"
        );
        assert!(
            establishes_new_block_formatting_context(&sd, NodeId::new(1)),
            "replaced elements always establish an independent formatting context"
        );
    }
    // ==================================================================
    // compute_layout_style
    // ==================================================================
    #[test]
    fn compute_layout_style_captures_every_property_it_advertises() {
        let sd = styled(
            Dom::create_body().with_child(div_class("x")),
            ".x { display: flex; position: absolute; overflow-x: hidden; overflow-y: scroll; \
             width: 50px; height: 60px; min-width: 10px; min-height: 11px; max-width: 99px; \
             max-height: 98px; text-align: center; }",
        );
        let s = compute_layout_style(&sd, NodeId::new(1));
        assert_eq!(s.display, LayoutDisplay::Flex);
        assert_eq!(s.position, LayoutPosition::Absolute);
        assert_eq!(s.overflow_x, LayoutOverflow::Hidden);
        assert_eq!(s.overflow_y, LayoutOverflow::Scroll);
        assert_eq!(s.text_align, StyleTextAlign::Center);
        assert!(s.width.is_some());
        assert!(s.height.is_some());
        assert!(s.min_width.is_some());
        assert!(s.min_height.is_some());
        assert!(s.max_width.is_some());
        assert!(s.max_height.is_some());
    }
    #[test]
    fn compute_layout_style_leaves_auto_sizes_as_none() {
        let sd = styled(
            Dom::create_body().with_child(div_class("x")),
            ".x { display: block; }",
        );
        let s = compute_layout_style(&sd, NodeId::new(1));
        assert!(s.width.is_none(), "auto width must be None, not 0px");
        assert!(s.height.is_none());
        assert!(s.max_width.is_none());
        assert!(s.max_height.is_none());
        assert_eq!(s.float, LayoutFloat::None);
        assert_eq!(s.position, LayoutPosition::Static);
    }
    #[test]
    fn compute_layout_style_reads_float_left_and_right() {
        for (css, want) in [("left", LayoutFloat::Left), ("right", LayoutFloat::Right)] {
            let sd = styled(
                Dom::create_body().with_child(div_class("x")),
                &format!(".x {{ float: {css}; }}"),
            );
            assert_eq!(compute_layout_style(&sd, NodeId::new(1)).float, want);
        }
    }
    #[test]
    fn compute_layout_style_never_panics_on_any_node_of_a_real_dom() {
        let sd = mixed_dom();
        for i in 0..sd.node_data.len() {
            let _ = compute_layout_style(&sd, NodeId::new(i));
        }
    }
    // ==================================================================
    // Font-size helpers
    // ==================================================================
    #[test]
    fn font_size_helpers_fall_back_to_the_default_when_nothing_is_specified() {
        let sd = styled(Dom::create_body().with_child(div_class("x")), "");
        assert_eq!(get_root_font_size(&sd), DEFAULT_FONT_SIZE);
        assert_eq!(
            get_parent_font_size(&sd, NodeId::ZERO),
            DEFAULT_FONT_SIZE,
            "the root has no parent ⇒ documented DEFAULT_FONT_SIZE fallback"
        );
        assert_eq!(
            get_element_font_size(&sd, NodeId::new(1)),
            DEFAULT_FONT_SIZE
        );
    }
    #[test]
    fn get_element_and_parent_font_size_track_the_cascade() {
        let sd = styled(
            Dom::create_body().with_child(div_class("big").with_child(div_class("small"))),
            ".big { font-size: 32px; } .small { font-size: 8px; }",
        );
        assert_eq!(get_element_font_size(&sd, NodeId::new(1)), 32.0);
        assert_eq!(get_element_font_size(&sd, NodeId::new(2)), 8.0);
        assert_eq!(
            get_parent_font_size(&sd, NodeId::new(2)),
            32.0,
            "the parent's size, not the element's own"
        );
    }
    #[test]
    fn get_root_font_size_reads_node_zero() {
        let root = Dom::create_body()
            .with_ids_and_classes(vec![IdOrClass::Class("root".into())].into())
            .with_child(div_class("x"));
        let sd = styled(root, ".root { font-size: 20px; }");
        assert_eq!(
            get_root_font_size(&sd),
            20.0,
            "get_root_font_size hard-codes NodeId(0)"
        );
        assert_eq!(
            get_root_font_size(&sd),
            get_element_font_size(&sd, NodeId::ZERO)
        );
    }
    #[test]
    fn font_size_helpers_return_a_finite_positive_size_for_every_node() {
        let sd = mixed_dom();
        for i in 0..sd.node_data.len() {
            let id = NodeId::new(i);
            for size in [
                get_element_font_size(&sd, id),
                get_parent_font_size(&sd, id),
            ] {
                assert!(size.is_finite(), "node {i}: {size}");
                assert!(
                    size > 0.0,
                    "node {i}: a zero/negative font-size breaks em math"
                );
            }
        }
    }
    // ==================================================================
    // create_resolution_context (numeric / NaN-inf passthrough)
    // ==================================================================
    #[test]
    fn create_resolution_context_zeroes_an_unknown_containing_block() {
        // css-sizing-3 §5.2.1: % margins/padding resolve against 0 when the
        // containing block isn't known yet (cycle breaking).
        let sd = mixed_dom();
        let ctx = create_resolution_context(&sd, NodeId::new(1), None, VIEWPORT);
        assert_eq!(ctx.containing_block_size.width, 0.0);
        assert_eq!(ctx.containing_block_size.height, 0.0);
        assert!(ctx.element_size.is_none(), "not laid out yet");
        assert_eq!(ctx.viewport_size.width, VIEWPORT.width);
        assert_eq!(ctx.viewport_size.height, VIEWPORT.height);
    }
    #[test]
    fn create_resolution_context_passes_a_known_containing_block_through() {
        let sd = mixed_dom();
        let cb = PhysicalSize::new(321.0, 123.0);
        let ctx = create_resolution_context(&sd, NodeId::new(1), Some(cb), VIEWPORT);
        assert_eq!(ctx.containing_block_size.width, 321.0);
        assert_eq!(ctx.containing_block_size.height, 123.0);
    }
    #[test]
    fn create_resolution_context_survives_a_degenerate_viewport() {
        let sd = mixed_dom();
        for vp in [
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(-100.0, -100.0),
            LogicalSize::new(f32::MAX, f32::MAX),
            LogicalSize::new(f32::INFINITY, f32::NEG_INFINITY),
            LogicalSize::new(f32::NAN, f32::NAN),
        ] {
            let ctx = create_resolution_context(&sd, NodeId::new(1), None, vp);
            // Viewport is passed through verbatim; the font sizes must stay sane.
            assert!(ctx.element_font_size.is_finite());
            assert!(ctx.parent_font_size.is_finite());
            assert!(ctx.root_font_size.is_finite());
        }
    }
    #[test]
    fn create_resolution_context_survives_a_degenerate_containing_block() {
        let sd = mixed_dom();
        for cb in [
            PhysicalSize::new(0.0, 0.0),
            PhysicalSize::new(-1.0, -1.0),
            PhysicalSize::new(f32::NAN, f32::INFINITY),
            PhysicalSize::new(f32::MAX, f32::MIN),
        ] {
            let ctx = create_resolution_context(&sd, NodeId::new(1), Some(cb), VIEWPORT);
            assert!(ctx.root_font_size.is_finite());
        }
    }
    // ==================================================================
    // collect_box_props (numeric / saturation / spec zeroing)
    // ==================================================================
    fn collect_for(css: &str, node: usize, viewport: LogicalSize) -> CollectedBoxProps {
        let sd = styled(Dom::create_body().with_child(div_class("x")), css);
        let mut msgs = None;
        collect_box_props(&sd, NodeId::new(node), &mut msgs, viewport)
    }
    #[test]
    fn collect_box_props_resolves_plain_pixel_edges() {
        let c = collect_for(
            ".x { margin: 10px; padding: 5px; border: 2px solid black; }",
            1,
            VIEWPORT,
        );
        assert_eq!(c.resolved.margin.top, 10.0);
        assert_eq!(c.resolved.margin.left, 10.0);
        assert_eq!(c.resolved.padding.right, 5.0);
        assert_eq!(c.resolved.border.bottom, 2.0);
    }
    #[test]
    fn collect_box_props_zeroes_a_border_whose_style_is_none() {
        // CSS 2.2 §8.5.1: computed border-width is 0 when border-style is none/hidden.
        let c = collect_for(".x { border-width: 9px; border-style: none; }", 1, VIEWPORT);
        assert_eq!(c.resolved.border.top, 0.0);
        assert_eq!(c.resolved.border.left, 0.0);
        let c = collect_for(
            ".x { border-width: 9px; border-style: hidden; }",
            1,
            VIEWPORT,
        );
        assert_eq!(c.resolved.border.right, 0.0);
    }
    #[test]
    fn collect_box_props_strips_margins_and_padding_from_internal_table_boxes() {
        // CSS 2.2 §17.5: internal table elements have no margins; rows/groups/
        // columns additionally have no padding.
        for display in [
            "table-row",
            "table-row-group",
            "table-header-group",
            "table-footer-group",
            "table-column",
            "table-column-group",
        ] {
            let c = collect_for(
                &format!(".x {{ display: {display}; margin: 10px; padding: 7px; }}"),
                1,
                VIEWPORT,
            );
            assert_eq!(c.resolved.margin.top, 0.0, "display:{display} margin");
            assert_eq!(c.resolved.padding.top, 0.0, "display:{display} padding");
        }
        // A cell keeps its padding but loses its margin.
        let c = collect_for(
            ".x { display: table-cell; margin: 10px; padding: 7px; }",
            1,
            VIEWPORT,
        );
        assert_eq!(c.resolved.margin.left, 0.0, "cells have no margins");
        assert_eq!(c.resolved.padding.left, 7.0, "…but they do have padding");
    }
    #[test]
    fn collect_box_props_zeroes_vertical_margins_on_a_non_replaced_inline() {
        let c = collect_for(".x { display: inline; margin: 10px; }", 1, VIEWPORT);
        assert_eq!(c.resolved.margin.top, 0.0);
        assert_eq!(c.resolved.margin.bottom, 0.0);
        assert_eq!(
            c.resolved.margin.left, 10.0,
            "horizontal margins still apply to inline boxes"
        );
        assert_eq!(c.resolved.margin.right, 10.0);
    }
    #[test]
    fn collect_box_props_does_not_clamp_huge_lengths_before_packing() {
        // collect_box_props returns f32; the ±3276.8px saturation happens later,
        // in PackedBoxProps. Assert the split so a regression in either is visible.
        let c = collect_for(".x { margin: 99999px; }", 1, VIEWPORT);
        assert_eq!(c.resolved.margin.top, 99_999.0);
        let packed = PackedBoxProps::pack(&c.resolved);
        assert_eq!(
            packed.margin[0],
            i16::MAX,
            "the packing saturates, it does not wrap"
        );
    }
    #[test]
    fn collect_box_props_survives_a_degenerate_viewport() {
        for vp in [
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(-800.0, -600.0),
            LogicalSize::new(f32::MAX, f32::MAX),
            LogicalSize::new(f32::INFINITY, f32::INFINITY),
            LogicalSize::new(f32::NAN, f32::NAN),
        ] {
            // vh/vw units make the viewport actually load-bearing here.
            let c = collect_for(".x { margin: 10vh; padding: 5vw; }", 1, vp);
            let packed = PackedBoxProps::pack(&c.resolved);
            for v in packed.margin.iter().chain(packed.padding.iter()) {
                assert!(
                    (i16::MIN..=i16::MAX).contains(v),
                    "packing must stay in range for viewport {vp:?}"
                );
            }
        }
    }
    #[test]
    fn collect_box_props_fills_debug_messages_when_asked() {
        let sd = styled(
            Dom::create_body().with_child(div_class("x")),
            ".x { margin: 3px; }",
        );
        let mut msgs: Option<Vec<LayoutDebugMessage>> = Some(Vec::new());
        let _ = collect_box_props(&sd, NodeId::new(1), &mut msgs, VIEWPORT);
        assert!(
            !msgs.expect("still Some").is_empty(),
            "a Some(vec) sink must actually receive the [BOX] trace"
        );
        // …and a None sink must be left alone (no allocation, no panic).
        let mut none_sink: Option<Vec<LayoutDebugMessage>> = None;
        let _ = collect_box_props(&sd, NodeId::new(1), &mut none_sink, VIEWPORT);
        assert!(none_sink.is_none());
    }
    #[test]
    fn collect_box_props_unresolved_and_resolved_agree_after_a_re_resolve() {
        let c = collect_for(".x { margin: 4px; padding: 6px; }", 1, VIEWPORT);
        let params = crate::solver3::geometry::ResolutionParams {
            containing_block: VIEWPORT,
            viewport_size: VIEWPORT,
            element_font_size: DEFAULT_FONT_SIZE,
            root_font_size: DEFAULT_FONT_SIZE,
        };
        let again = c.unresolved.resolve(&params);
        assert_eq!(again.margin.top, c.resolved.margin.top);
        assert_eq!(again.padding.left, c.resolved.padding.left);
        assert_eq!(again.border.top, c.resolved.border.top);
    }
    #[test]
    fn edge_sizes_default_is_all_zero() {
        let e = EdgeSizes::default();
        assert_eq!((e.top, e.right, e.bottom, e.left), (0.0, 0.0, 0.0, 0.0));
    }
    // ==================================================================
    // Whole-pipeline invariants
    // ==================================================================
    #[test]
    fn a_freshly_built_tree_satisfies_every_structural_invariant() {
        for sd in [
            mixed_dom(),
            styled(Dom::create_body(), ""),
            styled(
                Dom::create_body().with_child(div_class("f").with_child(div_class("c"))),
                ".f { display: flex; } .c { display: table-cell; }",
            ),
            styled(
                Dom::create_body().with_child(div_class("t").with_child(div_class("c"))),
                ".t { display: table; } .c { display: table-cell; }",
            ),
            styled(
                Dom::create_body().with_child(
                    div_class("li")
                        .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("x")),
                ),
                ".li { display: list-item; }",
            ),
        ] {
            let tree = build_tree(&sd);
            let n = tree.nodes.len();
            assert!(n >= 1);
            assert_eq!(tree.warm.len(), n);
            assert_eq!(tree.cold.len(), n);
            assert_eq!(tree.children_offsets.len(), n);
            assert_eq!(tree.subtree_needs_intrinsic.len(), n);
            assert!(tree.root < n);
            assert_eq!(tree.get(LayoutNodeId::new(tree.root)).unwrap().parent, None);
            for i in 0..n {
                if let Some(p) = tree.get(LayoutNodeId::new(i)).unwrap().parent {
                    assert!(p < n, "node {i}'s parent {p} is out of range");
                }
                for &c in tree.children(i) {
                    assert!(c < n, "node {i}'s child {c} is out of range");
                    assert_ne!(c, i, "no node may be its own child");
                }
            }
            for (dom_id, indices) in &tree.dom_to_layout {
                for &i in indices {
                    assert!(
                        i < LayoutNodeId::new(n),
                        "dom_to_layout[{dom_id:?}] points at {i}, out of range"
                    );
                    assert_eq!(tree.get(i).unwrap().dom_node_id, Some(*dom_id));
                }
            }
        }
    }
    #[test]
    fn building_a_body_only_dom_yields_exactly_one_node() {
        let sd = styled(Dom::create_body(), "");
        let tree = build_tree(&sd);
        assert_eq!(tree.nodes.len(), 1);
        assert_eq!(tree.root, 0);
        assert!(tree.children(0).is_empty());
        assert!(tree.children_arena.is_empty());
        assert_eq!(tree.children_offsets, vec![(0, 0)]);
        assert_eq!(tree.memory_report().node_count, 1);
    }
    #[test]
    fn the_root_box_always_establishes_a_new_block_formatting_context() {
        let tree = build_tree(&mixed_dom());
        match tree
            .get(LayoutNodeId::new(tree.root))
            .unwrap()
            .formatting_context
        {
            FormattingContext::Block {
                establishes_new_context,
            } => assert!(
                establishes_new_context,
                "process_node forces this for the root"
            ),
            other => panic!("the root should be a Block FC, got {other:?}"),
        }
    }
    #[test]
    fn a_deeply_nested_dom_builds_without_blowing_the_stack() {
        // process_node recurses once per level; 200 is well inside a test thread's
        // stack but deep enough to catch an accidental per-level allocation blowup.
        let mut dom = div_class("d");
        for _ in 0..200 {
            dom = div_class("d").with_child(dom);
        }
        let sd = styled(Dom::create_body().with_child(dom), ".d { display: block; }");
        let tree = build_tree(&sd);
        assert_eq!(tree.nodes.len(), 202, "body + 201 divs");
        // The chain must be a straight line: every node but the last has 1 child.
        let mut i = tree.root;
        let mut depth = 0;
        while let Some(&next) = tree.children(i).first() {
            i = next;
            depth += 1;
            assert!(depth <= 202, "the parent/child links formed a cycle");
        }
        assert_eq!(depth, 201);
    }
    // ==================================================================
    // ancestor_chain — THE ancestor walk, with explicit inclusivity
    // ==================================================================
    /// body > a > b, a straight chain, so the ancestor order is unambiguous.
    fn chain_tree() -> LayoutTree {
        let sd = styled(
            Dom::create_body().with_child(div_class("a").with_child(div_class("b"))),
            ".a, .b { display: block; }",
        );
        build_tree(&sd)
    }
    fn chain_from(tree: &LayoutTree, start: usize, incl: Inclusivity) -> Vec<usize> {
        tree.ancestor_chain(LayoutNodeId::new(start), incl)
            .map(LayoutNodeId::index)
            .collect()
    }
    #[test]
    fn ancestor_chain_inclusivity_decides_only_the_first_element() {
        let tree = chain_tree();
        // The deepest node is the last one the straight chain reaches.
        let mut deepest = tree.root;
        while let Some(&next) = tree.children(deepest).first() {
            deepest = next;
        }
        let with_self = chain_from(&tree, deepest, Inclusivity::SelfAndAncestors);
        let without = chain_from(&tree, deepest, Inclusivity::AncestorsOnly);
        assert_eq!(with_self.first(), Some(&deepest));
        assert_eq!(&with_self[1..], &without[..]);
        assert_eq!(
            with_self.last(),
            Some(&tree.root),
            "the walk must reach the root"
        );
        assert_eq!(with_self.len(), without.len() + 1);
    }
    #[test]
    fn ancestor_chain_at_the_root_is_the_root_or_nothing() {
        let tree = chain_tree();
        assert_eq!(
            chain_from(&tree, tree.root, Inclusivity::SelfAndAncestors),
            vec![tree.root]
        );
        assert!(chain_from(&tree, tree.root, Inclusivity::AncestorsOnly).is_empty());
    }
    #[test]
    fn ancestor_chain_on_an_out_of_range_index_yields_at_most_that_index() {
        let tree = chain_tree();
        assert!(chain_from(&tree, 9_999, Inclusivity::AncestorsOnly).is_empty());
        // Self-inclusive still reports the requested index once (callers
        // filter on `tree.get()`), then stops: no panic, no spin.
        assert_eq!(
            chain_from(&tree, 9_999, Inclusivity::SelfAndAncestors),
            vec![9_999]
        );
    }
    #[test]
    fn ancestor_chain_terminates_on_a_cyclic_parent_link() {
        let mut tree = chain_tree();
        // Forge a cycle: root's parent points at its own child.
        let child = tree
            .children(tree.root)
            .first()
            .copied()
            .expect("body has a child");
        tree.nodes[tree.root].parent = Some(child);
        let walked = chain_from(&tree, child, Inclusivity::SelfAndAncestors);
        assert!(
            walked.len() <= tree.nodes.len(),
            "the budget must stop a cyclic chain, walked {} of {} nodes",
            walked.len(),
            tree.nodes.len()
        );
    }
}