1
//! Intrinsic and used size calculations for layout nodes
2

            
3
use std::{collections::BTreeSet, sync::Arc};
4

            
5
use azul_core::{
6
    dom::{FormattingContext, NodeId, NodeType},
7
    geom::LogicalSize,
8
    resources::RendererResources,
9
    styled_dom::{StyledDom, StyledNodeState},
10
};
11
use azul_css::{
12
    css::CssPropertyValue,
13
    props::{
14
        basic::PixelValue,
15
        layout::{
16
            LayoutDisplay, LayoutFlexDirection, LayoutFlexWrap, LayoutFloat, LayoutHeight,
17
            LayoutPosition, LayoutWidth, LayoutWritingMode,
18
        },
19
        property::{CssProperty, CssPropertyType},
20
    },
21
    LayoutDebugMessage,
22
};
23
use rust_fontconfig::FcFontCache;
24

            
25
#[cfg(feature = "text_layout")]
26
use crate::text3;
27
use crate::{
28
    debug_log,
29
    font::parsed::ParsedFont,
30
    font_traits::{
31
        AvailableSpace, FontLoaderTrait, FontManager, ImageSource, InlineContent, InlineImage,
32
        InlineShape, LayoutCache, LayoutFragment, ObjectFit, ParsedFontTrait, ShapeDefinition,
33
        StyleProperties, UnifiedConstraints,
34
    },
35
    solver3::{
36
        fc::split_text_for_whitespace,
37
        geometry::{BoxProps, IntrinsicSizes, WritingModeContext},
38
        getters::{
39
            get_css_box_sizing, get_css_height, get_css_width, get_direction_property,
40
            get_display_property, get_element_font_size, get_flex_direction, get_float,
41
            get_style_properties, get_text_orientation_property, get_writing_mode, MultiValue,
42
        },
43
        layout_tree::{get_display_type, LayoutNodeHot, LayoutNodeId, LayoutTree},
44
        positioning::get_position_type,
45
        LayoutContext, LayoutError, Result,
46
    },
47
    text3::cache::AvailableSpace as Text3AvailableSpace,
48
};
49

            
50
const FALLBACK_MIN_CONTENT_WIDTH: f32 = 100.0;
51
const FALLBACK_MAX_CONTENT_WIDTH: f32 = 300.0;
52
const FALLBACK_MIN_CONTENT_HEIGHT: f32 = 20.0;
53
const FALLBACK_MAX_CONTENT_HEIGHT: f32 = 20.0;
54

            
55
/// Resolves a min/max sizing `PixelValue`, falling back to percentage-against-
56
/// containing-block resolution (with box-model adjustment) when the value is a
57
/// percentage rather than an absolute length.
58
///
59
/// `is_horizontal` selects which axis of `box_props` (left/right vs top/bottom)
60
/// is subtracted during percentage resolution.
61
1076
fn resolve_px_with_box_model(
62
1076
    px: &PixelValue,
63
1076
    containing: f32,
64
1076
    box_props: &BoxProps,
65
1076
    is_horizontal: bool,
66
1076
    em: f32,
67
1076
    rem: f32,
68
1076
) -> Option<f32> {
69
1076
    if let Some(v) = super::calc::resolve_pixel_value_no_percent(px, em, rem) {
70
1058
        return Some(v);
71
18
    }
72

            
73
18
    let percent = px.to_percent()?;
74
    // css-sizing-3 §5.2.1 (febf0c): a percentage that would resolve against an
75
    // INDEFINITE size cannot resolve at all. Returning None routes every caller
76
    // to its own "no constraint" answer — min-* becomes 0, max-* becomes
77
    // unbounded — instead of manufacturing an infinite length that a later
78
    // clamp would then FORCE onto the box (a percent min-width was enough to
79
    // re-infect a width the main resolution had already fixed up).
80
11
    if !containing.is_finite() {
81
6
        return None;
82
5
    }
83
5
    let (margin, border, padding) = if is_horizontal {
84
4
        (
85
4
            (box_props.margin.left, box_props.margin.right),
86
4
            (box_props.border.left, box_props.border.right),
87
4
            (box_props.padding.left, box_props.padding.right),
88
4
        )
89
    } else {
90
1
        (
91
1
            (box_props.margin.top, box_props.margin.bottom),
92
1
            (box_props.border.top, box_props.border.bottom),
93
1
            (box_props.padding.top, box_props.padding.bottom),
94
1
        )
95
    };
96
5
    Some(resolve_percentage_with_box_model(
97
5
        containing,
98
5
        percent.get(),
99
5
        margin,
100
5
        border,
101
5
        padding,
102
5
    ))
103
1076
}
104

            
105
/// Resolves a percentage value against the containing block dimension.
106
///
107
/// Per CSS 2.1 Section 10.2, percentages resolve directly against the containing
108
/// block's width or height. The margin/border/padding parameters are accepted for
109
/// call-site convenience but are intentionally unused — percentage resolution does
110
/// not subtract box-model extras in content-box sizing.
111
///
112
/// Returns `(containing_block_dimension * percentage).max(0.0)`.
113
// +spec:containing-block:43c719 - percentages resolved against containing block width/height
114
// +spec:containing-block:723eee - Percentages specify sizing with respect to the containing block
115
// +spec:containing-block:8ad6f4 - Percentage resolution against containing block (editorial note:
116
// transferred percentages) +spec:containing-block:257f3b - Block-axis percentages resolve against
117
// containing block size +spec:containing-block:f1344e - percentage min/max-width resolved against
118
// containing block width; negative CB width yields zero
119
#[must_use]
120
3179
pub fn resolve_percentage_with_box_model(
121
3179
    containing_block_dimension: f32,
122
3179
    percentage: f32,
123
3179
    _margins: (f32, f32),
124
3179
    _borders: (f32, f32),
125
3179
    _paddings: (f32, f32),
126
3179
) -> f32 {
127
    // +spec:containing-block:b3388b - percentage resolved against containing block size without
128
    // re-resolution (css-sizing-3 §5.2.1) CSS 2.1 Section 10.2: percentages resolve against
129
    // containing block, not available space after margins/borders/padding
130
3179
    (containing_block_dimension * percentage).max(0.0)
131
3179
}
132

            
133
/// Returns true if the DOM subtree rooted at `dom_id` contains any `NodeType::Text`.
134
///
135
/// Used when deciding whether a `FormattingContext::Inline` node should measure
136
/// its inline content (it acts as an IFC root when nested inlines eventually
137
/// hold text) versus returning zero (pure inline wrapper with no text reaches).
138
201139
fn subtree_contains_text(styled_dom: &StyledDom, dom_id: NodeId) -> bool {
139
201139
    let node_hierarchy = styled_dom.node_hierarchy.as_container();
140
201139
    let node_data = styled_dom.node_data.as_container();
141
201139
    if matches!(node_data[dom_id].get_node_type(), NodeType::Text(_)) {
142
134695
        return true;
143
66444
    }
144
66444
    dom_id
145
66444
        .az_children(&node_hierarchy)
146
66444
        .any(|child| subtree_contains_text(styled_dom, child))
147
201139
}
148

            
149
/// Phase 2a: Calculate intrinsic sizes (bottom-up pass)
150
/// // +spec:display-contents:f12d4e - intrinsic sizing: size determined by contents, not context
151
// [g71 TEST] #[inline(never)] — RELIABLE bisection (g70, markers in free band) showed new_tree
152
// drops 2→0 RIGHT BEFORE this call. It's currently INLINED into layout_document (absent from the
153
// lift log), so its frame/entry isn't a separate SP-wrapped @sub_ call. Forcing it OUT makes the
154
// call a wrapped @sub_ → enforce_sp_preservation save/restores SP around it. If new_tree survives
155
// (sizingEntry=2), the inlined entry/frame-setup was mis-lifting SP. (g60's inline(always) was a
156
// no-op — already inlined.)
157
#[inline(never)]
158
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
159
/// # Errors
160
///
161
/// Returns a `LayoutError` if intrinsic sizing fails.
162
10458
pub fn calculate_intrinsic_sizes<T: ParsedFontTrait>(
163
10458
    ctx: &mut LayoutContext<'_, T>,
164
10458
    tree: &mut LayoutTree,
165
10458
    text_cache: &mut LayoutCache,
166
10458
    dirty_nodes: &BTreeSet<usize>,
167
10458
) -> Result<()> {
168
    // [az-diag g59 REVERT] RELIABLE field-access bracket (pointer CASTS mis-lift to 0 — g58 proved
169
    // it; use tree.nodes.len() which is reliable). 0x407B0 = nodes.len at ENTRY. If 2 here but
170
    // 0x40734 (line ~142, after compute_dirty_ancestor_closure + calculator) reads 0, the
171
    // corruption is in 121-142. compute_dirty_ancestor_closure RETURNS a HashSet by sret —
172
    // prime suspect: sret-slot overlapping new_tree, or the hashbrown empty-map bug. 0x407B4
173
    // (post-compute_dirty) isolates compute_dirty vs calculator-creation.
174
10458
    unsafe {
175
10458
        crate::az_mark(0x607B0_u32, (tree.nodes.len() as u32));
176
10458
    }
177
10458
    if dirty_nodes.is_empty() {
178
387
        return Ok(());
179
10071
    }
180

            
181
10071
    debug_log!(ctx, "Starting intrinsic size calculation");
182
    // Pre-compute the "ancestor closure" of dirty_nodes: every dirty
183
    // node AND each of its ancestors up to root. A node not in this
184
    // set (and whose `intrinsic_sizes` is already populated) can
185
    // reuse its cached intrinsic — we skip its entire subtree walk.
186
    // Before this, `calculate_intrinsic_recursive` walked the full
187
    // tree from root regardless, costing ~2 ms per warm render on
188
    // excel.html even when only 3 nodes were actually dirty.
189
10071
    let dirty_closure = compute_dirty_ancestor_closure(tree, dirty_nodes);
190
    // [az-diag g59 REVERT] 0x407B4 = nodes.len AFTER compute_dirty_ancestor_closure (its HashSet
191
    // sret).
192
10071
    unsafe {
193
10071
        crate::az_mark(0x607B4_u32, (tree.nodes.len() as u32));
194
10071
    }
195

            
196
10071
    let mut calculator = IntrinsicSizeCalculator::new(ctx, text_cache);
197
10071
    calculator.dirty_closure = Some(dirty_closure);
198
    // Fix C (re-enabled §58 Win #3): skip intrinsic computation for subtrees
199
    // whose values will never be consumed. `tree.subtree_needs_intrinsic` is a
200
    // static-DOM bitmap precomputed at tree-build time — true if this node or
201
    // any descendant establishes a shrink-to-fit context. When both the
202
    // caller and the subtree are non-STF, no one reads the intrinsic, so the
203
    // whole descent is pure waste.
204
    //
205
    // The previous attempt (7667d13e, reverted in bd9ad36d) wrote default
206
    // (zero) intrinsics and broke auto-height rendering because
207
    // calculate_used_size_for_node read intrinsic.max_content_height as the
208
    // height:auto fallback. 97c3d3db refactored that dependency away: for
209
    // block-level auto-height, used_size.height is 0 pre-layout and
210
    // apply_content_based_height fills it from the laid-out content size.
211
    // With that gone, skipping intrinsic is safe.
212
    // [az-diag g53 REVERT] DECISIVE: is the lifted LayoutTree itself empty/broken? If
213
    // tree.get(root)=None (0x40738=0) or nodes.len()=0 (0x40734), the InvalidTree@229 is
214
    // because RECONCILE produced a broken tree — root cause is reconcile, not sizing.
215
10071
    unsafe {
216
10071
        crate::az_mark(0x60730_u32, (tree.root as u32));
217
10071
        crate::az_mark(0x60734_u32, (tree.nodes.len() as u32));
218
10071
        crate::az_mark(
219
10071
            0x60738_u32,
220
10071
            u32::from(tree.get(LayoutNodeId::new(tree.root)).is_some()),
221
10071
        );
222
10071
        // [az-diag g55] 0x4075C = the `tree` ptr the CALLEE sees. Compare with 0x40748
223
10071
        // (caller's &new_tree). Same → nodes-field-offset mis-lift; differ → &mut arg mis-passed.
224
10071
        crate::az_mark(
225
10071
            0x6075C_u32,
226
10071
            ((std::ptr::from_ref::<LayoutTree>(tree) as usize) as u32),
227
10071
        );
228
10071
    }
229
10071
    calculator.calculate_intrinsic_recursive(tree, tree.root, false)?;
230
10071
    debug_log!(ctx, "Finished intrinsic size calculation");
231
10071
    Ok(())
232
10458
}
233

            
234
18750
pub(crate) fn compute_dirty_ancestor_closure(
235
18750
    tree: &LayoutTree,
236
18750
    dirty_nodes: &BTreeSet<usize>,
237
18750
) -> std::collections::HashSet<usize> {
238
18750
    let mut closure: std::collections::HashSet<usize> = std::collections::HashSet::new();
239
465435
    for &dirty in dirty_nodes {
240
446685
        let mut cur = Some(dirty);
241
896149
        while let Some(idx) = cur {
242
877851
            if !closure.insert(idx) {
243
428387
                break;
244
449464
            }
245
449464
            cur = tree.get(LayoutNodeId::new(idx)).and_then(|n| n.parent);
246
        }
247
    }
248
18750
    closure
249
18750
}
250

            
251
struct IntrinsicSizeCalculator<'a, 'b, 'c, T: ParsedFontTrait> {
252
    ctx: &'a mut LayoutContext<'b, T>,
253
    /// Shared text shaping cache, threaded through from the caller so
254
    /// stages 1–3 of the inline layout pipeline (logical / `BiDi` / shaping)
255
    /// are cache-hits across the sizing pass's min/max-content measurements
256
    /// AND the subsequent real layout pass. Previously each pass held its
257
    /// own `LayoutCache`, so identical text was shaped three times per
258
    /// `root_layout_pass` — once per min-content measurement, once per
259
    /// max-content measurement, once at final layout.
260
    text_cache: &'c mut LayoutCache,
261
    /// If `Some`, only nodes in this set (the ancestor-closure of
262
    /// dirty nodes) need recomputation. A clean node whose
263
    /// `warm.intrinsic_sizes` is already populated reuses the
264
    /// cached value and skips its entire subtree descent.
265
    dirty_closure: Option<std::collections::HashSet<usize>>,
266
}
267

            
268
impl<'a, 'b, 'c, T: ParsedFontTrait> IntrinsicSizeCalculator<'a, 'b, 'c, T> {
269
10090
    const fn new(ctx: &'a mut LayoutContext<'b, T>, text_cache: &'c mut LayoutCache) -> Self {
270
10090
        Self {
271
10090
            ctx,
272
10090
            text_cache,
273
10090
            dirty_closure: None,
274
10090
        }
275
10090
    }
276

            
277
    #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/
278
                                               // debug-marker cast
279
228769
    fn calculate_intrinsic_recursive(
280
228769
        &mut self,
281
228769
        tree: &mut LayoutTree,
282
228769
        node_index: usize,
283
228769
        ancestor_is_stf: bool,
284
228769
    ) -> Result<IntrinsicSizes> {
285
        // [az-diag g52 REVERT] 0x40720 = node_index entering calculate_intrinsic_recursive
286
        // (last value after the run = the node that InvalidTree'd or the stray child).
287
228769
        unsafe {
288
228769
            crate::az_mark(0x60720_u32, (node_index as u32));
289
228769
        }
290
        // Fast path: if this subtree has no dirty nodes AND we
291
        // already have a cached intrinsic, return the cached value
292
        // and skip the whole descent. Caller is the ancestor-closure
293
        // computation in `calculate_intrinsic_sizes` — anything not
294
        // in that set is guaranteed clean through every descendant.
295
228769
        if let Some(closure) = self.dirty_closure.as_ref() {
296
228764
            if !closure.contains(&node_index) {
297
8573
                if let Some(cached) = tree
298
8573
                    .warm(LayoutNodeId::new(node_index))
299
8573
                    .and_then(|w| w.intrinsic_sizes)
300
                {
301
6851
                    drop(crate::probe::Probe::span("intrinsic_cache_hit"));
302
6851
                    return Ok(cached);
303
1722
                }
304
                // A node the reconcile pass called CLEAN whose intrinsic
305
                // was not carried over: it recomputes (text measurement,
306
                // ~3 ms for an IFC root) even though nothing about it
307
                // changed. Counted so the warm profile shows how much of
308
                // the sizing pass is this hole rather than real work.
309
1722
                drop(crate::probe::Probe::span("intrinsic_clean_but_uncached"));
310
220191
            }
311
5
        }
312

            
313
        // Fix C static-DOM short-circuit: if no ancestor needs this intrinsic
314
        // (none are STF) AND no descendant in this subtree is STF, nobody
315
        // will ever read the value. Write a default and skip the recursion.
316
        // `subtree_needs_intrinsic` is precomputed at tree-build time from
317
        // the DOM's display/position/float properties, so this is a constant
318
        // lookup with no per-pass work.
319
221918
        if !ancestor_is_stf
320
42167
            && tree
321
42167
                .subtree_needs_intrinsic
322
42167
                .get(node_index)
323
42167
                .copied()
324
42167
                .is_some_and(|v| !v)
325
        {
326
1643
            let default = IntrinsicSizes::default();
327
1643
            if let Some(n) = tree.warm_mut(LayoutNodeId::new(node_index)) {
328
1643
                n.intrinsic_sizes = Some(default);
329
1643
            }
330
1643
            return Ok(default);
331
220275
        }
332

            
333
        // Previously cloned the full LayoutNode to sidestep borrow conflicts
334
        // with the `&mut tree` recursive calls below, but we only need the
335
        // DOM id here — a `Copy` scalar. The clone was allocating a
336
        // Vec<usize> for children and a TaffyCache on every recursion
337
        // (~300x on excel.html).
338
220275
        let dom_node_id = tree
339
220275
            .get(LayoutNodeId::new(node_index))
340
220275
            .ok_or(LayoutError::InvalidTree)?
341
            .dom_node_id;
342

            
343
        // Out-of-flow (absolute/fixed) elements must NOT contribute to their
344
        // parent's intrinsic size — but they still need their OWN intrinsic size
345
        // computed, because an abs-pos box with `width:auto` is sized shrink-to-fit
346
        // (§10.3.7), which reads this node's max-content width. So we compute and
347
        // store the real intrinsic size below, then return zero to the caller so
348
        // the parent ignores it. (Previously this early-returned zero AND stored
349
        // zero on the node, collapsing every auto-width abs-pos box to width 0.)
350
220272
        let is_out_of_flow = matches!(
351
220272
            get_position_type(self.ctx.styled_dom, dom_node_id),
352
            LayoutPosition::Absolute | LayoutPosition::Fixed
353
        );
354

            
355
        // Copy child indices before recursive calls (which need &mut tree).
356
        // Stack buffer for the common case (≤32 children); heap only for huge nodes.
357
220272
        let children_slice = tree.children(node_index);
358
220272
        let n = children_slice.len();
359
220272
        let mut stack_buf = [0usize; 32];
360
        let heap_buf: Vec<usize>;
361
220272
        let children: &[usize] = if n <= 32 {
362
220222
            stack_buf[..n].copy_from_slice(children_slice);
363
220222
            &stack_buf[..n]
364
        } else {
365
50
            heap_buf = children_slice.to_vec();
366
50
            &heap_buf
367
        };
368
        // Propagate STF flag: children inherit `ancestor_is_stf=true` if any
369
        // ancestor up to and including self is STF.
370
220272
        let self_is_stf = tree.get(LayoutNodeId::new(node_index)).is_some_and(|n| {
371
220272
            crate::solver3::layout_tree::is_shrink_to_fit_context(
372
220272
                self.ctx.styled_dom,
373
220272
                n.dom_node_id,
374
220272
                n.formatting_context,
375
            )
376
220272
        });
377
220272
        let child_ancestor_is_stf = ancestor_is_stf || self_is_stf;
378

            
379
220272
        let mut child_intrinsics = Vec::with_capacity(n);
380
438966
        for &child_index in children {
381
            // [az-diag g52 REVERT] 0x40728 = child_index about to recurse (last = the stray).
382
218694
            unsafe {
383
218694
                crate::az_mark(0x60728_u32, (child_index as u32));
384
218694
            }
385
            // [g52 FIX] Defensive: reconcile can mis-list a stray/out-of-range child_index
386
            // (a Text node mis-listed as a layout child, or a lift artifact in the children
387
            // array). The unguarded recursion would hit `tree.get(child_index).ok_or(InvalidTree)`
388
            // at line ~226 and abort the WHOLE intrinsic-sizing pass. Skip gracefully so
389
            // measurement continues — mirrors process_layout_children's guard (line ~1079).
390
            // REAL fix = reconcile not listing the stray child.
391
218694
            if tree.get(LayoutNodeId::new(child_index)).is_none() {
392
1
                continue;
393
218693
            }
394
218693
            let child_intrinsic =
395
218693
                self.calculate_intrinsic_recursive(tree, child_index, child_ancestor_is_stf)?;
396
218693
            child_intrinsics.push((child_index, child_intrinsic));
397
        }
398

            
399
        // Then calculate this node's intrinsic size based on its children
400
220272
        let _p_self = crate::probe::Probe::span("intrinsic_node_compute");
401
220272
        let mut intrinsic =
402
220272
            self.calculate_node_intrinsic_sizes(tree, node_index, &child_intrinsics)?;
403

            
404
        // +spec:min-max-sizing:970fef - if min-width/min-height is a <length>, use as floor for
405
        // intrinsic sizes
406
220272
        if let Some(dom_id) = tree
407
220272
            .get(LayoutNodeId::new(node_index))
408
220272
            .and_then(|n| n.dom_node_id)
409
        {
410
            use crate::solver3::getters::{get_css_min_height, get_css_min_width, MultiValue};
411

            
412
220069
            let node_state =
413
220069
                &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
414

            
415
            // Resolve em against the element's OWN font-size and rem against the root.
416
220069
            let em = get_element_font_size(self.ctx.styled_dom, dom_id, node_state);
417
220069
            let rem = super::getters::get_root_font_size(self.ctx.styled_dom, node_state);
418

            
419
            // css-sizing-3 §5.2.1: a box with a DEFINITE preferred size
420
            // contributes exactly that size — its min- and max-content are
421
            // the used width/height, not the (possibly empty) content's.
422
            // Without this, an empty `width: 794px` block contributed 0, so
423
            // every shrink-to-fit ancestor (auto-width abspos §10.3.7,
424
            // floats §10.3.5) collapsed to 0x0 and its children vanished
425
            // (miniword ENGINE-ISSUE 5c). Intrinsics here are CONTENT sizes,
426
            // so border-box declarations shed their border+padding first.
427
            // Applied BEFORE the min floors so an explicit min still wins.
428
            {
429
                use azul_css::props::layout::{
430
                    dimensions::{LayoutHeight, LayoutWidth},
431
                    LayoutBoxSizing,
432
                };
433
220069
                let box_sizing = match get_css_box_sizing(self.ctx.styled_dom, dom_id, node_state) {
434
220060
                    MultiValue::Exact(v) => v,
435
9
                    _ => LayoutBoxSizing::ContentBox,
436
                };
437
220069
                let bp = tree
438
220069
                    .get(LayoutNodeId::new(node_index))
439
220069
                    .map(|n| n.box_props.unpack())
440
220069
                    .unwrap_or_default();
441
21319
                if let MultiValue::Exact(LayoutWidth::Px(px)) =
442
220069
                    get_css_width(self.ctx.styled_dom, dom_id, node_state)
443
                {
444
21319
                    if let Some(mut w) = super::calc::resolve_pixel_value_no_percent(&px, em, rem) {
445
20051
                        if box_sizing == LayoutBoxSizing::BorderBox {
446
10480
                            w = (w
447
10480
                                - bp.border.left
448
10480
                                - bp.border.right
449
10480
                                - bp.padding.left
450
10480
                                - bp.padding.right)
451
10480
                                .max(0.0);
452
10651
                        }
453
20051
                        intrinsic.min_content_width = w;
454
20051
                        intrinsic.max_content_width = w;
455
1268
                    }
456
198750
                }
457
38805
                if let MultiValue::Exact(LayoutHeight::Px(px)) =
458
220069
                    get_css_height(self.ctx.styled_dom, dom_id, node_state)
459
                {
460
38805
                    if let Some(mut h) = super::calc::resolve_pixel_value_no_percent(&px, em, rem) {
461
37776
                        if box_sizing == LayoutBoxSizing::BorderBox {
462
27430
                            h = (h
463
27430
                                - bp.border.top
464
27430
                                - bp.border.bottom
465
27430
                                - bp.padding.top
466
27430
                                - bp.padding.bottom)
467
27430
                                .max(0.0);
468
27686
                        }
469
37776
                        intrinsic.min_content_height = h;
470
37776
                        intrinsic.max_content_height = h;
471
1029
                    }
472
181264
                }
473
            }
474

            
475
4674
            if let MultiValue::Exact(mw) =
476
220069
                get_css_min_width(self.ctx.styled_dom, dom_id, node_state)
477
            {
478
4674
                if let Some(min_w) = super::calc::resolve_pixel_value_no_percent(&mw.inner, em, rem)
479
4674
                {
480
4674
                    intrinsic.min_content_width = intrinsic.min_content_width.max(min_w);
481
4674
                    intrinsic.max_content_width = intrinsic.max_content_width.max(min_w);
482
4674
                }
483
215395
            }
484

            
485
704
            if let MultiValue::Exact(mh) =
486
220069
                get_css_min_height(self.ctx.styled_dom, dom_id, node_state)
487
            {
488
704
                if let Some(min_h) = super::calc::resolve_pixel_value_no_percent(&mh.inner, em, rem)
489
704
                {
490
704
                    intrinsic.min_content_height = intrinsic.min_content_height.max(min_h);
491
704
                    intrinsic.max_content_height = intrinsic.max_content_height.max(min_h);
492
704
                }
493
219365
            }
494
203
        }
495

            
496
220272
        if let Some(n) = tree.warm_mut(LayoutNodeId::new(node_index)) {
497
220272
            n.intrinsic_sizes = Some(intrinsic);
498
220272
        }
499

            
500
        // An out-of-flow box's own intrinsic size is stored above (for its
501
        // shrink-to-fit auto width), but it does not contribute to its parent's
502
        // intrinsic size — return zero to the caller.
503
220272
        if is_out_of_flow {
504
2436
            Ok(IntrinsicSizes::default())
505
        } else {
506
217836
            Ok(intrinsic)
507
        }
508
228769
    }
509

            
510
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse
511
                                     // routine (one branch per case)
512
220273
    fn calculate_node_intrinsic_sizes(
513
220273
        &mut self,
514
220273
        tree: &LayoutTree,
515
220273
        node_index: usize,
516
220273
        child_intrinsics: &[(usize, IntrinsicSizes)],
517
220273
    ) -> Result<IntrinsicSizes> {
518
220273
        let node = tree
519
220273
            .get(LayoutNodeId::new(node_index))
520
220273
            .ok_or(LayoutError::InvalidTree)?;
521

            
522
        // +spec:block-formatting-context:30def2 - replaced elements use physical 300x150 default,
523
        // not re-oriented by writing-mode +spec:display-property:015c41 - replaced elements
524
        // default to 300x150 intrinsic size per css-sizing-3 §5.1 +spec:display-property:
525
        // 2c6af3 - replaced elements with auto width/height use max-content size
526
        // +spec:replaced-elements:6d6030 - Intrinsic sizes for replaced elements (images, virtual
527
        // views) VirtualViews are replaced elements with a default intrinsic size of
528
        // 300x150px (same as virtualized view elements)
529
220272
        if let Some(dom_id) = node.dom_node_id {
530
220069
            let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
531
220069
            if node_data.is_virtual_view_node() {
532
                // SIZED BY WHAT IT RETURNED, once it has returned something.
533
                //
534
                // A VirtualView reports exactly how big its content is
535
                // (`VirtualViewReturn::materialized`), and that report used to
536
                // reach placement and scrollbar geometry only - so the view
537
                // itself was stuck at the 300x150 of a replaced element with
538
                // no natural size, and every caller had to state a size up
539
                // front. `width: auto` on a view now means what it means on an
540
                // `<img>`: as big as the content.
541
                //
542
                // The FIRST pass has nothing materialized yet and still falls
543
                // back to 300x150: a view is sized from the outside first and
544
                // by its content afterwards, which is the only order that
545
                // terminates (the callback is handed the node's bounds).
546
622
                let materialized = self
547
622
                    .ctx
548
622
                    .virtual_view_sizes
549
622
                    .and_then(|sizes| sizes.get(&(self.ctx.styled_dom.dom_id, dom_id)).copied());
550
622
                let (w, h) = materialized.map_or((300.0, 150.0), |s| (s.width, s.height));
551
622
                return Ok(IntrinsicSizes {
552
622
                    min_content_width: w,
553
622
                    max_content_width: w,
554
622
                    preferred_width: None, // Will be determined by CSS or flex-grow
555
622
                    min_content_height: h,
556
622
                    max_content_height: h,
557
622
                    preferred_height: None, // Will be determined by CSS or flex-grow
558
622
                    preferred_aspect_ratio: None,
559
622
                });
560
219447
            }
561

            
562
            // +spec:containing-block:bb5a12 - replaced element intrinsic sizes using initial
563
            // containing block +spec:display-property:7127f9 - intrinsic sizes of
564
            // replaced elements without natural sizes (300x150 fallback, aspect ratio)
565
            // +spec:display-property:f9cede - replaced elements derive intrinsic size from natural
566
            // dimensions +spec:writing-modes:b18121 - stretch fit inline size from
567
            // available space, calculate block size via aspect ratio
568
219447
            if let NodeType::Image(image_ref) = node_data.get_node_type() {
569
                // Overlay→DOM: a runtime-swapped image's intrinsic size must
570
                // drive layout (the DOM is immutable; live content is in the
571
                // overlay). Produced callback frames are deliberately NOT
572
                // consulted — `image_for_layout` keeps the DOM's declared
573
                // (sizeless) callback so a per-frame producer cannot resize
574
                // the box it draws into.
575
153
                let size = self
576
153
                    .ctx
577
153
                    .resolved_content()
578
153
                    .image_for_layout(dom_id)
579
153
                    .map_or_else(|| image_ref.get_size(), |img| img.get_size());
580
                // +spec:containing-block:1da6dc - use initial CB inline size for replaced elements
581
                // with aspect ratio but no intrinsic size Per css-sizing-3 §5.1:
582
                // "use an inline size matching the corresponding dimension
583
                // of the initial containing block and calculate the other dimension using the
584
                // aspect ratio"
585
153
                let has_intrinsic = size.width > 0.0 || size.height > 0.0;
586
153
                let (width, height) = if size.width > 0.0 && size.height > 0.0 {
587
32
                    (size.width, size.height)
588
121
                } else if size.width > 0.0 {
589
                    (size.width, size.width / 2.0)
590
121
                } else if size.height > 0.0 {
591
                    // Has intrinsic height but no width — use initial CB inline dimension
592
                    (self.ctx.viewport_size.width, size.height)
593
                } else {
594
                    // +spec:replaced-elements:43376b - 300px fallback with 2:1 ratio for replaced
595
                    // elements No intrinsic dimensions — cap at 300x150 per CSS
596
                    // 2.2 §10.3.2 +spec:width-calculation:3b0efe - auto width
597
                    // fallback: 300px capped to device width
598
                    // +spec:width-calculation:16c305 - auto height fallback: 2:1 ratio, max 150px
599
121
                    let w = self.ctx.viewport_size.width.min(300.0);
600
121
                    (w, w / 2.0)
601
                };
602
                // A replaced element with NO intrinsic size (e.g. a RenderImageCallback
603
                // <img> like the AzulPaint canvas) must behave like a VirtualView: keep
604
                // the 300×150 fallback as the min/max-content (so it has a sensible
605
                // default) but leave `preferred` as None so `flex-grow` / explicit CSS
606
                // can size it. A `Some(preferred)` here pins the box and defeats
607
                // flex-grow (the canvas was laid out 300×0 — see the VirtualView arm
608
                // above, which already uses None for exactly this reason). Images WITH
609
                // a real intrinsic size keep `preferred = Some` so they display at their
610
                // natural size when unconstrained.
611
153
                let (pref_w, pref_h) = if has_intrinsic {
612
32
                    (Some(width), Some(height))
613
                } else {
614
121
                    (None, None)
615
                };
616
153
                return Ok(IntrinsicSizes {
617
153
                    min_content_width: width,
618
153
                    max_content_width: width,
619
153
                    preferred_width: pref_w,
620
153
                    min_content_height: height,
621
153
                    max_content_height: height,
622
153
                    preferred_height: pref_h,
623
153
                    preferred_aspect_ratio: None,
624
153
                });
625
219294
            }
626
203
        }
627

            
628
219497
        match node.formatting_context {
629
            FormattingContext::Block { .. } => {
630
                // Check if this block establishes an Inline Formatting Context (IFC).
631
                // Per CSS 2.2 §9.2.1.1: A block container with mixed block-level and
632
                // inline-level children creates anonymous block boxes to wrap the inline
633
                // content. So we only treat as IFC root if there are NO block-level children.
634
                //
635
                // We check the actual CSS display property, NOT formatting_context,
636
                // because a display:block element with only inline children gets
637
                // FormattingContext::Inline (meaning "establishes IFC for its children"),
638
                // which is different from being an inline element itself.
639
18976
                let has_block_child = tree.children(node_index).iter().any(|&child_idx| {
640
13131
                    tree.get(LayoutNodeId::new(child_idx))
641
13131
                        .and_then(|c| c.dom_node_id)
642
13131
                        .is_some_and(|dom_id| {
643
13046
                            let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
644
                            // Text nodes are inline-level
645
13046
                            if matches!(node_data.get_node_type(), NodeType::Text(_)) {
646
1
                                return false;
647
13045
                            }
648
13045
                            let display = get_display_type(self.ctx.styled_dom, dom_id);
649
13045
                            display.creates_block_context()
650
13046
                        })
651
13131
                });
652

            
653
29766
                let has_inline_child = tree.children(node_index).iter().any(|&child_idx| {
654
29705
                    tree.get(LayoutNodeId::new(child_idx))
655
29705
                        .and_then(|c| c.dom_node_id)
656
29705
                        .is_some_and(|dom_id| {
657
29502
                            let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
658
29502
                            if matches!(node_data.get_node_type(), NodeType::Text(_)) {
659
1
                                return true;
660
29501
                            }
661
29501
                            let display = get_display_type(self.ctx.styled_dom, dom_id);
662
29500
                            matches!(
663
29501
                                display,
664
                                LayoutDisplay::Inline
665
                                    | LayoutDisplay::InlineBlock
666
                                    | LayoutDisplay::InlineFlex
667
                                    | LayoutDisplay::InlineGrid
668
                                    | LayoutDisplay::InlineTable
669
                            )
670
29502
                        })
671
29705
                });
672

            
673
                // IFC root only if there are inline children and NO block children.
674
                // If there are block children, text nodes get anonymous block wrappers.
675
18976
                let is_ifc_root = has_inline_child && !has_block_child;
676

            
677
                // Also check if this block has direct text content (text nodes in DOM)
678
                // but ONLY if there are no block-level layout children
679
18976
                let has_direct_text = if has_block_child {
680
13044
                    false
681
5932
                } else if let Some(dom_id) = node.dom_node_id {
682
5930
                    let node_hierarchy = &self.ctx.styled_dom.node_hierarchy.as_container();
683
5930
                    dom_id.az_children(node_hierarchy).any(|child_id| {
684
21
                        let child_node_data =
685
21
                            &self.ctx.styled_dom.node_data.as_container()[child_id];
686
21
                        matches!(child_node_data.get_node_type(), NodeType::Text(_))
687
21
                    })
688
                } else {
689
2
                    false
690
                };
691

            
692
18976
                if is_ifc_root || has_direct_text {
693
                    // This block is an IFC root - measure all inline content ONCE
694
21
                    self.calculate_ifc_root_intrinsic_sizes(tree, node_index)
695
                } else {
696
                    // This is a BFC root (only block children) - aggregate child sizes
697
18955
                    self.calculate_block_intrinsic_sizes(tree, node_index, child_intrinsics)
698
                }
699
            }
700
            FormattingContext::Inline => {
701
                // There are THREE cases for FormattingContext::Inline:
702
                // 1. A Text node (NodeType::Text) - this IS the text content itself -> Needs to
703
                //    measure itself as an atomic inline unit
704
                // 2. An IFC root - a block with only inline children (has text child nodes) ->
705
                //    Should measure its inline content
706
                // 3. A true inline element (display: inline, e.g., <span>) with no text -> Returns
707
                //    default(0,0), measured by parent IFC root
708
                //
709
                // We distinguish by:
710
                // - Checking if THIS node is a Text node (case 1)
711
                // - Checking if this subtree contains any text (case 2)
712
                //
713
                // Why descendants, not just direct children: for `<span><a>text</a></span>`,
714
                // the `<span>` is a layout-tree IFC root (layout_ifc is called on it), but
715
                // its direct DOM children are inline elements, not text. Restricting the
716
                // check to direct text children would zero out the span's intrinsic width
717
                // even though the cell content width depends on it.
718
135062
                let is_text_node = if let Some(dom_id) = node.dom_node_id {
719
134861
                    let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
720
134861
                    matches!(node_data.get_node_type(), NodeType::Text(_))
721
                } else {
722
201
                    false
723
                };
724

            
725
135062
                let has_text_in_subtree = if let Some(dom_id) = node.dom_node_id {
726
134861
                    subtree_contains_text(self.ctx.styled_dom, dom_id)
727
                } else {
728
201
                    false
729
                };
730

            
731
135062
                if is_text_node || has_text_in_subtree {
732
                    // Case 1 or 2: Text node or IFC root - measure inline content
733
134691
                    self.calculate_ifc_root_intrinsic_sizes(tree, node_index)
734
                } else {
735
                    // Case 3: True inline element - measured by parent IFC root
736
371
                    Ok(IntrinsicSizes::default())
737
                }
738
            }
739
            FormattingContext::InlineBlock => {
740
                // Inline-block IS an atomic inline - it needs its own intrinsic size.
741
                // Check layout tree children AND direct DOM text children (text nodes
742
                // are not in the layout tree, only in the DOM).
743
500
                let has_inline_children = tree.children(node_index).iter().any(|&child_idx| {
744
500
                    tree.get(LayoutNodeId::new(child_idx))
745
500
                        .is_some_and(|c| matches!(c.formatting_context, FormattingContext::Inline))
746
500
                });
747

            
748
500
                let has_direct_text = if let Some(dom_id) = node.dom_node_id {
749
500
                    let node_hierarchy = &self.ctx.styled_dom.node_hierarchy.as_container();
750
500
                    dom_id.az_children(node_hierarchy).any(|child_id| {
751
500
                        let child_node_data =
752
500
                            &self.ctx.styled_dom.node_data.as_container()[child_id];
753
500
                        matches!(child_node_data.get_node_type(), NodeType::Text(_))
754
500
                    })
755
                } else {
756
                    false
757
                };
758

            
759
500
                if has_inline_children || has_direct_text {
760
                    // InlineBlock with inline children - measure as IFC root.
761
                    // Returns content-level intrinsic sizes (no margin/padding/border).
762
                    // The parent adds box-model extras via calculate_block_intrinsic_sizes,
763
                    // and calculate_used_size_for_node adds padding+border for border-box.
764
500
                    let intrinsic = self.calculate_ifc_root_intrinsic_sizes(tree, node_index)?;
765

            
766
500
                    Ok(intrinsic)
767
                } else {
768
                    // InlineBlock with block children - aggregate like block
769
                    self.calculate_block_intrinsic_sizes(tree, node_index, child_intrinsics)
770
                }
771
            }
772
            FormattingContext::Table => {
773
390
                Ok(self.calculate_table_intrinsic_sizes(tree, node_index, child_intrinsics))
774
            }
775
            FormattingContext::Flex => {
776
63159
                self.calculate_flex_intrinsic_sizes(tree, node_index, child_intrinsics)
777
            }
778
1410
            _ => self.calculate_block_intrinsic_sizes(tree, node_index, child_intrinsics),
779
        }
780
220273
    }
781

            
782
    // +spec:intrinsic-sizing:ea2c2c - §5.1 min-content size = size as float with auto; max-content
783
    // = no wrapping
784
    /// Calculate intrinsic sizes for an IFC root (a block containing inline content).
785
    /// This collects ALL inline descendants' text and measures it ONCE.
786
    // +spec:intrinsic-sizing:8f3c0c - hanging glyphs must be excluded from intrinsic size
787
    // measurement
788
    #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/
789
                                               // debug-marker cast
790
136154
    fn calculate_ifc_root_intrinsic_sizes(
791
136154
        &mut self,
792
136154
        tree: &LayoutTree,
793
136154
        node_index: usize,
794
136154
    ) -> Result<IntrinsicSizes> {
795
        // [g75] 0x60758 = how many times this IFC sizer is entered; 0x6075C = node_index of THIS
796
        // call.
797
136154
        unsafe {
798
136154
            let c = crate::az_mark_read(0x60758).wrapping_add(1);
799
136154
            crate::az_mark(0x60758_u32, (c));
800
136154
            crate::az_mark(0x6075C_u32, (node_index as u32));
801
136154
        }
802
136154
        let _p_ifc = crate::probe::Probe::span("intrinsic_ifc_root");
803
        // Collect all inline content from this IFC root and its inline descendants
804
        // [g76] EXPLICIT match (was `?`): the g75 markers showed collect_inline_content reaching
805
        // its completion marker B8 (Ok at the source level) yet the IFC sizer never
806
        // advancing to 0xA1 — i.e. the lifted `Result<Vec<InlineContent>, LayoutError>`
807
        // return arrives as Err at this call site (a complex by-value Result-return
808
        // mis-lift). 0x60760 = 1 (Ok) / 0xEE (Err-but-B8-ran). RESILIENCE: on Err, degrade
809
        // to empty content (→ default intrinsic) instead of aborting the WHOLE layout with
810
        // InvalidTree, so the page renders and the next real blocker surfaces. g76 PROVED:
811
        // degrading to Vec::new() here (resilience) lets layout proceed past this
812
        // InvalidTree but then HANGS in the downstream actual-layout shaping (the documented g47
813
        // hashbrown empty-map infinite loop). So for a CLEAN (non-hanging) state we PROPAGATE the
814
        // Err (same as the original `?`), keeping the 0x60760 diagnostic. To chase the g47
815
        // hang, flip the Err arm back to `Vec::new()`. 0x60760 = 1 (Ok) / 0xEE
816
        // (Err-despite-B8 = the Result mis-lift). [g78] OUT-PARAM refactor: the by-value
817
        // `Result<Vec<InlineContent>, LayoutError>` return mis-lifted Ok→Err (g76/g77
818
        // PROVED it: 0x60760=0xEE despite the source reaching B8). Filling a `&mut Vec`
819
        // out-param and returning `Result<()>` (register-returned, NO sret-of-Vec) lifts
820
        // cleanly — the established M12.7 "a pointer arg lifts cleanly" pattern. 0x60760 should now
821
        // =1.
822
136154
        let collect_result = {
823
136154
            let _p = crate::probe::Probe::span("intrinsic_collect_inline");
824
136154
            collect_inline_content(self.ctx, tree, node_index)
825
        };
826
        #[cfg(feature = "web_lift")]
827
        unsafe {
828
            crate::az_mark(
829
                (0x60760) as u32,
830
                (if collect_result.is_ok() {
831
                    0x00000001u32
832
                } else {
833
                    0x000000EEu32
834
                }) as u32,
835
            );
836
        }
837
136154
        let inline_content: Vec<InlineContent> = collect_result?;
838

            
839
136154
        if inline_content.is_empty() {
840
31520
            return Ok(IntrinsicSizes::default());
841
104634
        }
842

            
843
        // Get pre-loaded fonts from font manager
844
104634
        let loaded_fonts = self.ctx.font_manager.get_loaded_fonts();
845

            
846
        // +spec:intrinsic-sizing:ae8beb - min-content = zero-width CB, max-content = infinite-width
847
        // CB +spec:intrinsic-sizing:8c94e2 - min-content/max-content intrinsic size
848
        // determination via constrained layout Use `measure_intrinsic_widths` instead of
849
        // two `layout_flow` passes (fix B): it runs stages 1–4 of the pipeline once
850
        // (logical → BiDi → shape → orient) and derives min/max-content by scanning the
851
        // shaped items directly. This avoids the BreakCursor line-breaking loop entirely —
852
        // that loop clones every ShapedCluster it inspects via `peek_next_unit` and
853
        // accounted for 24% of total CPU on the text_2000 stress fixture. Shaping is cached
854
        // at the per-item level (keyed on text+style), so the subsequent real
855
        // layout_flow call for this content gets pure cache hits for stages 1–3.
856
        // Populate the measurement constraints from the IFC root's real white-space
857
        // mode instead of always using defaults. With the default (Normal) the scan
858
        // treats every space as a break opportunity, so a white-space:nowrap / pre
859
        // element reports a min-content SMALLER than its true unbreakable width and
860
        // the flex/shrink-to-fit algorithm clips it.
861
104634
        let mut constraints = UnifiedConstraints::default();
862
104634
        if let Some(dom_id) = tree
863
104634
            .get(LayoutNodeId::new(node_index))
864
104634
            .and_then(|n| n.dom_node_id)
865
        {
866
            use azul_css::props::style::text::StyleWhiteSpace;
867

            
868
            use crate::solver3::getters::{get_white_space_property, MultiValue};
869
104634
            let node_state =
870
104634
                &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
871
104634
            let ws = match get_white_space_property(self.ctx.styled_dom, dom_id, node_state) {
872
104632
                MultiValue::Exact(v) => v,
873
2
                _ => StyleWhiteSpace::Normal,
874
            };
875
104634
            constraints.white_space_mode = match ws {
876
77830
                StyleWhiteSpace::Normal => crate::text3::cache::WhiteSpaceMode::Normal,
877
18860
                StyleWhiteSpace::Nowrap => crate::text3::cache::WhiteSpaceMode::Nowrap,
878
208
                StyleWhiteSpace::Pre => crate::text3::cache::WhiteSpaceMode::Pre,
879
7736
                StyleWhiteSpace::PreWrap => crate::text3::cache::WhiteSpaceMode::PreWrap,
880
                StyleWhiteSpace::PreLine => crate::text3::cache::WhiteSpaceMode::PreLine,
881
                StyleWhiteSpace::BreakSpaces => crate::text3::cache::WhiteSpaceMode::BreakSpaces,
882
            };
883
        }
884
        // [g79 DIAG] Probe the font state at shaping time, then convert the downstream shape_text
885
        // HANG (g47 hashbrown empty-map loop) → trap so the harness RETURNS and these markers are
886
        // readable (can't read markers from a hung wasm call). Tests the #4→#3 coupling: if
887
        // 0x60768(font_chain_cache.len) / 0x6076C(loaded_fonts.len) are 0, the EMPTY FONT CHAIN is
888
        // the ROOT of the hang (no font → allsorts builds empty hashbrown maps → RawIter loops).
889
        // [g82] CONDITIONAL trap: if the font_chain_cache is still EMPTY, shaping would HANG
890
        // (allsorts builds empty hashbrown maps → g47 RawIter loop) → trap instead so the
891
        // markers are readable (non-hang). If the chain is NON-empty (unique_font_keys
892
        // BTreeMap fix worked + populated it), PROCEED into measure → shape → text should
893
        // MEASURE. g81 hung (no conditional) → need to know whether the chain populated.
894
        // 0x60768=chain.len, 0x6076C=loaded_fonts.len, 0x60704=0xA15.
895
        #[cfg(feature = "web_lift")]
896
        {
897
            let cl = self.ctx.font_manager.font_chain_cache.len();
898
            unsafe {
899
                crate::az_mark((0x60768) as u32, (cl as u32) as u32);
900
                crate::az_mark((0x6076C) as u32, (loaded_fonts.len() as u32) as u32);
901
                crate::az_mark((0x60704) as u32, (0xA15u32) as u32);
902
            }
903
            // [g88] g85+g87 PROVED whack-a-mole does NOT converge: BTreeMap'd unique_font_keys
904
            // (chain ✓), supported_features+lookups_index (g85), ReadCache (g87) —
905
            // STILL HANGS. Too many hashbrown empty-map sites across
906
            // allsorts/std/rust-fontconfig. The ONLY convergent fix is the SYSTEMIC
907
            // transpiler empty-static mirror (force the lifted hashbrown ctrl-scan to read
908
            // 0xFF not 0x00). TEMP non-hang trap until that lands. ★ REMOVE to test the systemic
909
            // fix. [g93] PROCEED into shaping to test the AZ_FORCE_MIRROR_VMADDRS
910
            // hashbrown-EMPTY_GROUP fix. If text MEASURES → the forced const pages
911
            // contained EMPTY_GROUP → systemic fix found.
912
            let _ = (cl, loaded_fonts.len());
913
        }
914
104634
        let _p_measure = crate::probe::Probe::span("intrinsic_measure_widths");
915
104634
        let Ok(intrinsic_text) = self.text_cache.measure_intrinsic_widths(
916
104634
            &inline_content,
917
104634
            &[],
918
104634
            &constraints,
919
104634
            &self.ctx.font_manager.font_chain_cache,
920
104634
            &self.ctx.font_manager.fc_cache,
921
104634
            &loaded_fonts,
922
104634
            self.ctx.debug_messages,
923
104634
        ) else {
924
            return Ok(IntrinsicSizes {
925
                min_content_width: FALLBACK_MIN_CONTENT_WIDTH,
926
                max_content_width: FALLBACK_MAX_CONTENT_WIDTH,
927
                preferred_width: None,
928
                min_content_height: FALLBACK_MIN_CONTENT_HEIGHT,
929
                max_content_height: FALLBACK_MAX_CONTENT_HEIGHT,
930
                preferred_height: None,
931
                preferred_aspect_ratio: None,
932
            });
933
        };
934

            
935
104634
        let min_width = intrinsic_text.min_content_width;
936
104634
        let max_width = intrinsic_text.max_content_width;
937

            
938
        // +spec:display-property:c587fd - min-content block size equals max-content block size for
939
        // block containers, tables, inline boxes +spec:intrinsic-sizing:02eedc -
940
        // min-content block size equals max-content block size for block containers
941
        // For a single-line max-content layout the height is one line box;
942
        // `measure_intrinsic_widths` returns exactly that.
943
104634
        let max_content_height = intrinsic_text.max_content_height;
944

            
945
        // NOTE(writing-modes): min_content_width / max_content_width are named for
946
        // the physical axis. In vertical writing modes the "inline" axis is vertical,
947
        // so these are swapped by calculate_block_intrinsic_sizes when computing
948
        // the parent's intrinsic sizes. The physical naming is intentional here.
949
104634
        Ok(IntrinsicSizes {
950
104634
            min_content_width: min_width,
951
104634
            max_content_width: max_width,
952
104634
            preferred_width: None,
953
104634
            min_content_height: max_content_height,
954
104634
            max_content_height,
955
104634
            preferred_height: None,
956
104634
            preferred_aspect_ratio: None,
957
104634
        })
958
136154
    }
959

            
960
    // +spec:containing-block:bb0658 - percentage block-sizes behave as auto during intrinsic
961
    // computation (no CSS height resolution here) +spec:display-contents:84fe7f - cyclic
962
    // percentage contributions: percentage-sized children use auto during intrinsic sizing
963
    // +spec:min-max-sizing:411904 - percentage block-sizes treated as auto during intrinsic sizing
964
    // (content-sized CB) +spec:min-max-sizing:737e62 - percentage heights don't resolve inside
965
    // content-sized containing blocks
966
20370
    fn calculate_block_intrinsic_sizes(
967
20370
        &self,
968
20370
        tree: &LayoutTree,
969
20370
        node_index: usize,
970
20370
        child_intrinsics: &[(usize, IntrinsicSizes)],
971
20370
    ) -> Result<IntrinsicSizes> {
972
20370
        let node = tree
973
20370
            .get(LayoutNodeId::new(node_index))
974
20370
            .ok_or(LayoutError::InvalidTree)?;
975
20369
        let writing_mode = node
976
20369
            .dom_node_id
977
20369
            .map_or_else(LayoutWritingMode::default, |dom_id| {
978
20363
                let node_state =
979
20363
                    &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
980
20363
                get_writing_mode(self.ctx.styled_dom, dom_id, node_state).unwrap_or_default()
981
20363
            });
982

            
983
        // NOTE: Text content detection is now handled in calculate_node_intrinsic_sizes
984
        // which calls calculate_ifc_root_intrinsic_sizes for blocks with inline content.
985
        // This function now only handles pure block containers (BFC roots).
986
        // +spec:height-calculation:d9ca8d - cyclic percentage contributions: percentage
987
        // min-height/max-height on children should behave as auto when computing intrinsic
988
        // contributions (not yet implemented)
989

            
990
20369
        let mut max_child_min_cross = 0.0f32;
991
20369
        let mut max_child_max_cross = 0.0f32;
992
20369
        let mut total_main_size = 0.0;
993
        // Track margins for CSS 2.2 §8.3.1 collapsing in the block direction.
994
        // Block margins collapse between siblings (max instead of sum) and
995
        // parent-child margins can escape (first/last child).
996
20369
        let mut last_margin_main_end = 0.0f32;
997
20369
        let mut is_first_child = true;
998

            
999
31729
        for &child_index in tree.children(node_index) {
31672
            if let Some(child_intrinsic) = child_intrinsics
31672
                .iter()
443353
                .find(|(k, _)| k == &child_index)
31672
                .map(|(_, v)| v)
            {
                // +spec:intrinsic-sizing:ed72bb - intrinsic contributions based on outer size, auto
                // margins as zero
31669
                let child_node = tree.get(LayoutNodeId::new(child_index));
31669
                let (cross_extras, main_border_padding, main_margin_start, main_margin_end) =
31669
                    child_node.map_or((0.0, 0.0, 0.0, 0.0), |cn| {
31669
                        let bp = cn.box_props.unpack();
31669
                        let h = bp.margin.left
31669
                            + bp.margin.right
31669
                            + bp.border.left
31669
                            + bp.border.right
31669
                            + bp.padding.left
31669
                            + bp.padding.right;
31669
                        let v_bp =
31669
                            bp.border.top + bp.border.bottom + bp.padding.top + bp.padding.bottom;
31669
                        match writing_mode {
                            LayoutWritingMode::HorizontalTb => {
31659
                                (h, v_bp, bp.margin.top, bp.margin.bottom)
                            }
10
                            _ => (v_bp, h, bp.margin.left, bp.margin.right),
                        }
31669
                    });
31669
                let (child_min_cross, child_max_cross, child_border_box_main) = match writing_mode {
31659
                    LayoutWritingMode::HorizontalTb => (
31659
                        child_intrinsic.min_content_width + cross_extras,
31659
                        child_intrinsic.max_content_width + cross_extras,
31659
                        child_intrinsic.max_content_height + main_border_padding,
31659
                    ),
10
                    _ => (
10
                        child_intrinsic.min_content_height + cross_extras,
10
                        child_intrinsic.max_content_height + cross_extras,
10
                        child_intrinsic.max_content_width + main_border_padding,
10
                    ),
                };
31669
                max_child_min_cross = max_child_min_cross.max(child_min_cross);
31669
                max_child_max_cross = max_child_max_cross.max(child_max_cross);
                // CSS 2.2 §8.3.1 margin collapsing for intrinsic sizing:
                // - First child's margin-start can escape (don't add to total)
                // - Between siblings: collapsed gap = max(prev_end, curr_start)
                // - Last child's margin-end can escape (don't add to total)
31669
                if is_first_child {
14398
                    is_first_child = false;
14398
                    // First child: top margin may escape, don't add it
17458
                } else {
17271
                    // Sibling gap: collapsed margin between prev bottom and current top
17271
                    let collapsed_gap = crate::solver3::fc::collapse_margins(
17271
                        last_margin_main_end,
17271
                        main_margin_start,
17271
                    );
17271
                    total_main_size += collapsed_gap;
17271
                }
31669
                total_main_size += child_border_box_main;
31669
                last_margin_main_end = main_margin_end;
3
            }
        }
        // Last child's margin-end may escape — don't add it to total_main_size
20369
        let (min_width, max_width, min_height, max_height) = match writing_mode {
20349
            LayoutWritingMode::HorizontalTb => (
20349
                max_child_min_cross,
20349
                max_child_max_cross,
20349
                total_main_size,
20349
                total_main_size,
20349
            ),
20
            _ => (
20
                total_main_size,
20
                total_main_size,
20
                max_child_min_cross,
20
                max_child_max_cross,
20
            ),
        };
20369
        Ok(IntrinsicSizes {
20369
            min_content_width: min_width,
20369
            max_content_width: max_width,
20369
            preferred_width: None,
20369
            min_content_height: min_height,
20369
            max_content_height: max_height,
20369
            preferred_height: None,
20369
            preferred_aspect_ratio: None,
20369
        })
20370
    }
    // The max-content main size is the sum of items' max-content contributions.
    // The min-content main size of a single-line flex container is the sum of items'
    // min-content contributions. For multi-line, it is the largest min-content contribution.
    // Auto margins on flex items are treated as 0 for this computation.
63163
    fn calculate_flex_intrinsic_sizes(
63163
        &self,
63163
        tree: &LayoutTree,
63163
        node_index: usize,
63163
        child_intrinsics: &[(usize, IntrinsicSizes)],
63163
    ) -> Result<IntrinsicSizes> {
63163
        let node = tree
63163
            .get(LayoutNodeId::new(node_index))
63163
            .ok_or(LayoutError::InvalidTree)?;
        // Determine flex-direction to know if main axis is horizontal or vertical
63162
        let is_row = node.dom_node_id.is_none_or(|dom_id| {
63159
            let node_state =
63159
                &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
63159
            match get_flex_direction(self.ctx.styled_dom, dom_id, node_state) {
63159
                MultiValue::Exact(dir) => matches!(
63159
                    dir,
                    LayoutFlexDirection::Row | LayoutFlexDirection::RowReverse
                ),
                _ => true, // default is row
            }
63159
        });
63162
        let mut sum_main_min: f32 = 0.0;
63162
        let mut sum_main_max: f32 = 0.0;
63162
        let mut max_main_min: f32 = 0.0;
63162
        let mut max_cross_min: f32 = 0.0;
63162
        let mut max_cross_max: f32 = 0.0;
119881
        for &child_index in tree.children(node_index) {
119881
            if let Some(child_intrinsic) = child_intrinsics
119881
                .iter()
236519
                .find(|(k, _)| k == &child_index)
119881
                .map(|(_, v)| v)
            {
119878
                let (child_main_min, child_main_max, child_cross_min, child_cross_max) = if is_row {
77351
                    (
77351
                        child_intrinsic.min_content_width,
77351
                        child_intrinsic.max_content_width,
77351
                        child_intrinsic.min_content_height,
77351
                        child_intrinsic.max_content_height,
77351
                    )
                } else {
42527
                    (
42527
                        child_intrinsic.min_content_height,
42527
                        child_intrinsic.max_content_height,
42527
                        child_intrinsic.min_content_width,
42527
                        child_intrinsic.max_content_width,
42527
                    )
                };
119878
                sum_main_max += child_main_max;
119878
                sum_main_min += child_main_min;
                // For multi-line min-content, track the largest single item
119878
                max_main_min = max_main_min.max(child_main_min);
                // Cross axis: largest child determines the container's cross size
119878
                max_cross_min = max_cross_min.max(child_cross_min);
119878
                max_cross_max = max_cross_max.max(child_cross_max);
3
            }
        }
        // For single-line (nowrap), min-content = sum; for multi-line (wrap), min-content = max
        // Default flex-wrap is nowrap (single-line)
63162
        let is_single_line = node.dom_node_id.is_none_or(|dom_id| {
63159
            let node_state =
63159
                &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
63159
            let wrap_prop = crate::solver3::getters::get_flex_wrap_prop(
63159
                self.ctx.styled_dom,
63159
                dom_id,
63159
                node_state,
            );
63159
            wrap_prop.is_none_or(|val| {
10
                matches!(
10
                    val.get_property_or_default().unwrap_or_default(),
                    LayoutFlexWrap::NoWrap
                )
10
            })
63159
        });
63162
        let min_main = if is_single_line {
63152
            sum_main_min
        } else {
10
            max_main_min
        };
63162
        let max_main = sum_main_max;
63162
        if is_row {
44395
            Ok(IntrinsicSizes {
44395
                min_content_width: min_main,
44395
                max_content_width: max_main,
44395
                preferred_width: None,
44395
                min_content_height: max_cross_min,
44395
                max_content_height: max_cross_max,
44395
                preferred_height: None,
44395
                preferred_aspect_ratio: None,
44395
            })
        } else {
18767
            Ok(IntrinsicSizes {
18767
                min_content_width: max_cross_min,
18767
                max_content_width: max_cross_max,
18767
                preferred_width: None,
18767
                min_content_height: min_main,
18767
                max_content_height: max_main,
18767
                preferred_height: None,
18767
                preferred_aspect_ratio: None,
18767
            })
        }
63163
    }
    /// Calculate intrinsic sizes for a table element by aggregating cell content
    /// widths per column and row heights.
    /// +spec:table-layout:93b13c - shrink-to-fit for tables uses intrinsic sizing
395
    fn calculate_table_intrinsic_sizes(
395
        &mut self,
395
        tree: &LayoutTree,
395
        node_index: usize,
395
        child_intrinsics: &[(usize, IntrinsicSizes)],
395
    ) -> IntrinsicSizes {
        // Collect per-column min/max widths and total row heights.
        // Table structure: table > row-group? > row > cell
395
        let mut col_min: Vec<f32> = Vec::new();
395
        let mut col_max: Vec<f32> = Vec::new();
395
        let mut total_height = 0.0f32;
        // Iterate rows — children may be row groups (thead/tbody/tfoot) or direct rows
395
        let mut rows: Vec<usize> = Vec::new();
415
        for &child_idx in tree.children(node_index) {
414
            let Some(child) = tree.get(LayoutNodeId::new(child_idx)) else {
                continue;
            };
414
            match child.formatting_context {
363
                FormattingContext::TableRow => rows.push(child_idx),
                FormattingContext::TableRowGroup => {
                    // Row group contains rows
30
                    for &row_idx in tree.children(child_idx) {
30
                        if let Some(row) = tree.get(LayoutNodeId::new(row_idx)) {
30
                            if matches!(row.formatting_context, FormattingContext::TableRow) {
30
                                rows.push(row_idx);
30
                            }
                        }
                    }
                }
21
                _ => {}
            }
        }
788
        for &row_idx in &rows {
393
            let mut row_height = 0.0f32;
946
            for (col, &cell_idx) in tree.children(row_idx).iter().enumerate() {
946
                let cell_intrinsic = child_intrinsics
946
                    .iter()
1008
                    .find(|(k, _)| k == &cell_idx)
946
                    .map(|(_, v)| *v)
946
                    .unwrap_or_default();
                // Also check if cell has IFC content we can measure
946
                let cell_is = if cell_intrinsic.max_content_width > 0.0 {
4
                    cell_intrinsic
                } else {
                    // Try to measure cell content via IFC
942
                    self.calculate_ifc_root_intrinsic_sizes(tree, cell_idx)
942
                        .unwrap_or_default()
                };
                // Add cell box-model extras
946
                let cell_node = tree.get(LayoutNodeId::new(cell_idx));
946
                let (h_extras, v_extras) = cell_node.map_or((0.0, 0.0), |cn| {
946
                    let bp = cn.box_props.unpack();
946
                    (
946
                        bp.padding.left + bp.padding.right + bp.border.left + bp.border.right,
946
                        bp.padding.top + bp.padding.bottom + bp.border.top + bp.border.bottom,
946
                    )
946
                });
946
                let cell_min = cell_is.min_content_width + h_extras;
946
                let cell_max = cell_is.max_content_width + h_extras;
946
                let cell_h = cell_is.max_content_height + v_extras;
946
                if col >= col_min.len() {
916
                    col_min.push(cell_min);
916
                    col_max.push(cell_max);
916
                } else {
30
                    col_min[col] = col_min[col].max(cell_min);
30
                    col_max[col] = col_max[col].max(cell_max);
30
                }
946
                row_height = row_height.max(cell_h);
            }
393
            total_height += row_height;
        }
395
        let min_width: f32 = col_min.iter().sum();
395
        let max_width: f32 = col_max.iter().sum();
395
        IntrinsicSizes {
395
            min_content_width: min_width,
395
            max_content_width: max_width,
395
            min_content_height: total_height,
395
            max_content_height: total_height,
395
            preferred_width: None,
395
            preferred_height: None,
395
            preferred_aspect_ratio: None,
395
        }
395
    }
}
/// Gathers all inline content for the intrinsic sizing pass.
///
/// This function recursively collects text and inline-level content according to
/// CSS Sizing Level 3, Section 4.1: "Intrinsic Sizes"
/// <https://www.w3.org/TR/css-sizing-3/#intrinsic-sizes>
///
/// For inline formatting contexts, we need to gather:
/// 1. Text nodes (inline content)
/// 2. Inline-level boxes (display: inline, inline-block, etc.)
/// 3. Atomic inline-level elements (replaced elements like images)
///
/// The key difference from `collect_and_measure_inline_content` in fc.rs is that
/// this version is used for intrinsic sizing (calculating min/max-content widths)
/// before the actual layout pass, so it must recursively gather content from
/// inline descendants without laying them out first.
136162
fn collect_inline_content_for_sizing<T: ParsedFontTrait>(
136162
    ctx: &mut LayoutContext<'_, T>,
136162
    tree: &LayoutTree,
136162
    ifc_root_index: usize,
136162
    out: &mut Vec<InlineContent>,
136162
) -> Result<()> {
136162
    debug_log!(
130027
        ctx,
130027
        "Collecting inline content from node {} for intrinsic sizing",
        ifc_root_index
    );
    // [g78] fill the caller's out-param (was a local Vec returned by value → Ok→Err mis-lift).
    // Recursively collect inline content from this node and its inline descendants
136162
    collect_inline_content_recursive(ctx, tree, ifc_root_index, out)?;
    // [g73] B8 = top-level recursion returned Ok (collect_inline_content complete).
136159
    unsafe {
136159
        crate::az_mark(0x6071C_u32, (0xB8u32));
136159
    }
136159
    debug_log!(
130027
        ctx,
130027
        "Collected {} inline content items from node {}",
130027
        out.len(),
        ifc_root_index
    );
136159
    Ok(())
136162
}
/// Recursive helper for collecting inline content.
///
/// According to CSS Sizing Level 3, the intrinsic size of an inline formatting context
/// is based on all inline-level content, including text in nested inline elements.
///
/// This function:
/// - Collects text from the current node if it's a text node
/// - Collects text from DOM children (text nodes may not be in layout tree)
/// - Recursively collects from inline children (display: inline)
/// - Treats non-inline children as atomic inline-level boxes
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker
                                           // cast
204318
fn collect_inline_content_recursive<T: ParsedFontTrait>(
204318
    ctx: &mut LayoutContext<'_, T>,
204318
    tree: &LayoutTree,
204318
    node_index: usize,
204318
    content: &mut Vec<InlineContent>,
204318
) -> Result<()> {
    // [g75] capture node_index of EVERY recursion entry (0x60754) and mark the entry-tree.get
    // FAILURE distinctly (inline-phase=0xBAD) so a node_index that fails HERE (before B1) is
    // visible even though a PRIOR successful call already wrote B8. This is the suspected
    // InvalidTree site (phase stuck at 0xA0 + B8 reached ⇒ a 2nd IFC call fails at this get).
204318
    unsafe {
204318
        crate::az_mark(0x60754_u32, (node_index as u32));
204318
    }
204318
    let Some(node) = tree.get(LayoutNodeId::new(node_index)) else {
3
        unsafe {
3
            crate::az_mark(0x6071C_u32, (0xBADu32));
3
        }
3
        return Err(LayoutError::InvalidTree);
    };
    // CRITICAL FIX: Text nodes may exist in the DOM but not as separate layout nodes!
    // We need to check the DOM children for text content.
204315
    let Some(dom_id) = node.dom_node_id else {
        // No DOM ID means this is a synthetic node, skip text extraction
2
        return process_layout_children(ctx, tree, node_index, content);
    };
    // First check if THIS node is a text node
204313
    if let Some(text) = extract_text_from_node(ctx.styled_dom, dom_id) {
136335
        let style_props = crate::solver3::getters::get_style_properties_cached(
136335
            &mut ctx.style_cache,
136335
            ctx.styled_dom,
136335
            dom_id,
136335
            ctx.system_style.as_ref(),
136335
            azul_css::props::basic::PhysicalSize::new(
136335
                ctx.viewport_size.width,
136335
                ctx.viewport_size.height,
            ),
        );
136335
        debug_log!(ctx, "Found text in node {}: '{}'", node_index, text);
        // Use split_text_for_whitespace to correctly handle white-space: pre with \n
136335
        let text_items = split_text_for_whitespace(ctx.styled_dom, dom_id, &text, &style_props);
136335
        content.extend(text_items);
67978
    }
    // CRITICAL: Also check DOM children for text nodes!
    // Text nodes are often not represented as separate layout nodes.
    // However, we must SKIP children that already have a layout tree entry,
    // because those will be handled by process_layout_children() below.
    // Without this guard, text nodes present in both DOM and layout tree
    // get collected twice, causing inline-block containers to be ~2x too wide.
204313
    let node_hierarchy = &ctx.styled_dom.node_hierarchy.as_container();
204313
    for child_id in dom_id.az_children(node_hierarchy) {
        // Skip DOM children that have layout tree nodes - they will be
        // processed via process_layout_children -> collect_inline_content_recursive
69439
        if tree.dom_to_layout.contains_key(&child_id) {
69139
            continue;
300
        }
        // Check if this DOM child is a text node
300
        let child_dom_node = &ctx.styled_dom.node_data.as_container()[child_id];
300
        if let NodeType::Text(text_data) = child_dom_node.get_node_type() {
280
            let text = text_data.as_str().to_string();
280
            let style_props = crate::solver3::getters::get_style_properties_cached(
280
                &mut ctx.style_cache,
280
                ctx.styled_dom,
280
                child_id,
280
                ctx.system_style.as_ref(),
280
                azul_css::props::basic::PhysicalSize::new(
280
                    ctx.viewport_size.width,
280
                    ctx.viewport_size.height,
                ),
            );
280
            debug_log!(
20
                ctx,
20
                "Found text in DOM child of node {}: '{}'",
                node_index,
                text
            );
            // Use split_text_for_whitespace to correctly handle white-space: pre with \n
280
            let text_items =
280
                split_text_for_whitespace(ctx.styled_dom, child_id, &text, &style_props);
280
            content.extend(text_items);
20
        }
    }
    // [g73] B6 = DOM-children loop done (about to process_layout_children).
204313
    unsafe {
204313
        crate::az_mark(0x6071C_u32, (0xB6u32));
204313
    }
204313
    process_layout_children(ctx, tree, node_index, content)
204318
}
/// Helper to process layout tree children for inline content collection
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
                                  // (or cross-type bindings that can't merge)
204315
fn process_layout_children<T: ParsedFontTrait>(
204315
    ctx: &mut LayoutContext<'_, T>,
204315
    tree: &LayoutTree,
204315
    node_index: usize,
204315
    content: &mut Vec<InlineContent>,
204315
) -> Result<()> {
    use azul_css::props::layout::{LayoutHeight, LayoutWidth};
    // [g73] PLC entry: 0x60708 = 0xC0<<24 | node_index (which node's children we process).
204315
    unsafe {
204315
        crate::az_mark(
204315
            0x60708_u32,
204315
            (0xC000_0000_u32 | (node_index as u32 & 0x00FF_FFFF)),
204315
        );
204315
    }
    // Process layout tree children (these are elements with layout properties)
204315
    for &child_index in tree.children(node_index) {
        // [g73] PLC loop: 0x6070C = current child_index being processed.
69099
        unsafe {
69099
            crate::az_mark(0x6070C_u32, (child_index as u32));
69099
        }
        // 2026-06-02: was `.ok_or(LayoutError::InvalidTree)?` — a stray/invalid child_index in
        // tree.children (likely a Text node mis-listed during reconcile, since Text is INLINE
        // content not a layout-tree node) aborted the WHOLE intrinsic-sizing pass with
        // InvalidTree BEFORE the inline text got measured → label height 0. Skip gracefully so
        // measurement continues (the inline text is collected separately above, at the
        // collect_inline_content_recursive DOM-children loop). REAL fix = reconcile not listing it.
69099
        let Some(child_node) = tree.get(LayoutNodeId::new(child_index)) else {
            continue;
        };
69099
        let Some(child_dom_id) = child_node.dom_node_id else {
20
            continue;
        };
69079
        let display = get_display_property(ctx.styled_dom, Some(child_dom_id));
        // CSS Sizing Level 3: Inline-level boxes participate in the IFC
69079
        if display.unwrap_or_default() == LayoutDisplay::Inline {
            // Recursively collect content from inline children
            // This is CRITICAL for proper intrinsic width calculation!
68156
            debug_log!(ctx, "Recursing into inline child at node {}", child_index);
68156
            collect_inline_content_recursive(ctx, tree, child_index, content)?;
        } else {
            // Non-inline children are treated as atomic inline-level boxes
            // (e.g., inline-block, images, floats)
            // Their intrinsic size must have been calculated in the bottom-up pass
923
            let intrinsic_sizes = tree
923
                .warm(LayoutNodeId::new(child_index))
923
                .and_then(|w| w.intrinsic_sizes)
923
                .unwrap_or_default();
            // CSS 2.2 § 10.3.9: For inline-block elements with explicit CSS width/height,
            // use the CSS-defined values instead of intrinsic sizes.
923
            let node_state =
923
                &ctx.styled_dom.styled_nodes.as_container()[child_dom_id].styled_node_state;
923
            let css_width = get_css_width(ctx.styled_dom, child_dom_id, node_state);
923
            let css_height = get_css_height(ctx.styled_dom, child_dom_id, node_state);
            // Resolve CSS width - use explicit value if set, otherwise fall back to intrinsic
923
            let used_width = match css_width {
361
                MultiValue::Exact(LayoutWidth::Px(px)) => {
                    // +spec:containing-block:495930 - percentages in intrinsic sizing fall back to
                    // intrinsic contribution (css-sizing-3 §5.2.1)
                    // +spec:containing-block:5246c0 - cyclic percentage: when containing block size
                    // depends on this box's intrinsic contribution, percentages fall back to
                    // intrinsic size +spec:containing-block:598124 - cyclic
                    // percentage contributions use intrinsic size
                    // +spec:height-calculation:ca9f19 - percentage-sized boxes use intrinsic size
                    // as contribution during intrinsic sizing
                    // +spec:width-calculation:7a384a - percentage-sized boxes behave as width:auto
                    // for intrinsic contributions (cyclic percentage)
                    // Resolve em/rem against the element's OWN font-size and the root
                    // font-size, NOT a hard-coded 16px — otherwise `width: 5em` on a
                    // font-size:24px inline-block sizes to 80px instead of 120px.
361
                    let em = get_element_font_size(ctx.styled_dom, child_dom_id, node_state);
361
                    let rem = super::getters::get_root_font_size(ctx.styled_dom, node_state);
361
                    super::calc::resolve_pixel_value_no_percent(&px, em, rem)
361
                        .unwrap_or(intrinsic_sizes.max_content_width)
                }
                MultiValue::Exact(LayoutWidth::MinContent) => intrinsic_sizes.min_content_width,
                MultiValue::Exact(LayoutWidth::MaxContent) => intrinsic_sizes.max_content_width,
                MultiValue::Exact(LayoutWidth::FitContent(_)) => {
                    // During intrinsic sizing, fit-content resolves to max-content
                    intrinsic_sizes.max_content_width
                }
                // For Auto or other values, use intrinsic size
562
                _ => intrinsic_sizes.max_content_width,
            };
            // +spec:containing-block:5145c5 - percentage block-size ignored in content-sized
            // containing blocks during intrinsic sizing Resolve CSS height - use
            // explicit value if set, otherwise fall back to intrinsic
923
            let used_height = match css_height {
351
                MultiValue::Exact(LayoutHeight::Px(px)) => {
                    // +spec:containing-block:7d5e79 - percentages behave as auto when containing
                    // block height is auto (cyclic percentage contribution)
                    // +spec:height-calculation:7d807b - css-sizing-3 §5.2.1: percentage heights
                    // behave as auto during intrinsic sizing (cyclic percentage contribution)
                    // Resolve em/rem against the element's own + root font-size (see width above).
351
                    let em = get_element_font_size(ctx.styled_dom, child_dom_id, node_state);
351
                    let rem = super::getters::get_root_font_size(ctx.styled_dom, node_state);
351
                    super::calc::resolve_pixel_value_no_percent(&px, em, rem)
351
                        .unwrap_or(intrinsic_sizes.max_content_height)
                }
                // is equivalent to automatic size
                MultiValue::Exact(LayoutHeight::MinContent) => intrinsic_sizes.max_content_height,
                // is equivalent to automatic size
                MultiValue::Exact(LayoutHeight::MaxContent) => intrinsic_sizes.max_content_height,
                MultiValue::Exact(LayoutHeight::FitContent(_)) => {
                    intrinsic_sizes.max_content_height
                }
572
                _ => intrinsic_sizes.max_content_height,
            };
923
            debug_log!(
620
                ctx,
620
                "Found atomic inline child at node {}: display={:?}, intrinsic_width={}, \
620
                 used_width={}, css_width={:?}",
                child_index,
                display,
                intrinsic_sizes.max_content_width,
                used_width,
                css_width
            );
            // Represent as a rectangular shape with the resolved dimensions
923
            content.push(InlineContent::Shape(InlineShape {
923
                shape_def: ShapeDefinition::Rectangle {
923
                    size: crate::text3::cache::Size {
923
                        width: used_width,
923
                        height: used_height,
923
                    },
923
                    corner_radius: None,
923
                },
923
                fill: None,
923
                stroke: None,
923
                baseline_offset: used_height,
923
                alignment: crate::solver3::getters::get_vertical_align_for_node(
923
                    ctx.styled_dom,
923
                    child_dom_id,
923
                ),
923
                source_node_id: Some(child_dom_id),
923
            }));
        }
    }
204315
    Ok(())
204315
}
// Keep old name as an alias for backward compatibility
/// # Errors
///
/// Returns a `LayoutError` if collecting inline content fails.
136162
pub fn collect_inline_content<T: ParsedFontTrait>(
136162
    ctx: &mut LayoutContext<'_, T>,
136162
    tree: &LayoutTree,
136162
    ifc_root_index: usize,
136162
) -> Result<Vec<InlineContent>> {
136162
    let mut out = Vec::new();
136162
    collect_inline_content_for_sizing(ctx, tree, ifc_root_index, &mut out)?;
136159
    Ok(out)
136162
}
// +spec:height-calculation:1c899b - width and height properties specify the preferred size of the
// box
/// Calculates the used size of a single node based on its CSS properties and
/// the available space provided by its containing block.
///
/// // +spec:display-contents:71ccde - extrinsic sizing: size determined by context (containing
/// block), not contents
///
/// This implementation correctly handles writing modes and percentage-based sizes
/// according to the CSS specification:
/// 1. `width` and `height` CSS properties are resolved to pixel values. Percentages are calculated
///    based on the containing block's PHYSICAL dimensions (`width` for `width`, `height` for
///    `height`), regardless of writing mode.
/// 2. The resolved physical `width` is then mapped to the node's logical CROSS size.
/// 3. The resolved physical `height` is then mapped to the node's logical MAIN size.
/// 4. A final `LogicalSize` is constructed from these logical dimensions.
// +spec:overflow:3c4f25 - auto box sizes: four auto-determined size types resolved here
// +spec:width-calculation:fb0629 - width/margin used values depend on box type, auto replaced by
// suitable value
///    M12.7: out-of-line auto-width-block inline size — `(cb.width - margins - borders -
/// padding).max(0.0)`. Extracted from `calc_used_size`'s auto-width Block arm so the
///    `.max(0.0)` runs in a small fn (proven to lift correctly), with a FRESH pointer
///    deref (the huge `calc_used_size` body hoists/spills cb.width and the remill lift then
///    reads it back 0). Returns by f32 (D0/V0 — the standard scalar return), NOT an out-ptr:
///    the out-ptr version computed 800 correctly but the caller's reload was opt-forwarded
///    to the init 0.0 across the opaque call (the helper's `*out` lowers to a direct
///    linear-mem store not modeled as aliasing the caller's slot). The f32 return is the
///    call's SSA result, which opt cannot replace. (The earlier "f32-return mis-lift" worry
///    was the 2×f32 *struct* HFA — a single scalar f32 return is fine.)
#[inline(never)]
#[allow(clippy::trivially_copy_pass_by_ref)]
// <=8B Copy param kept by-ref intentionally (hot pixel/coord path or to avoid churning call sites
// for a perf-neutral change)
/// The AVAILABLE term of a shrink-to-fit width, per constraint kind.
///
/// shrink-to-fit = `min(max(preferred_minimum, available), preferred)`, so a
/// min-content pass wants `available = 0` (clamps to the preferred minimum)
/// and a max-content pass wants it unbounded (clamps to the preferred width).
/// `f32::MAX` is safe as "unbounded" here — every caller immediately clamps
/// with `.min(preferred)`, so it can never escape into a used size.
///
/// Small and `#[inline(never)]`: M12.7 — the wasm lift mis-reads f32 loads
/// inside the ~6 KB sizing function these are called from.
2678
fn shrink_to_fit_available_width(cb_w: Text3AvailableSpace, bp: &BoxProps) -> f32 {
2678
    match cb_w {
2676
        Text3AvailableSpace::Definite(w) => (w
2676
            - bp.margin.left
2676
            - bp.margin.right
2676
            - bp.border.left
2676
            - bp.border.right
2676
            - bp.padding.left
2676
            - bp.padding.right)
2676
            .max(0.0),
1
        Text3AvailableSpace::MinContent => 0.0,
1
        Text3AvailableSpace::MaxContent => f32::MAX,
    }
2678
}
// `cb` stays by REFERENCE deliberately: see the sibling
// `auto_block_inline_size_definite_or_max_content` - the M12.7 remill lift
// mis-reads f32 loads passed by value out of `calculate_used_size_for_node`.
#[allow(clippy::trivially_copy_pass_by_ref)]
38850
fn auto_block_inline_size(cb: &LogicalSize, bp: &BoxProps) -> f32 {
38850
    let aw = cb.width
38850
        - bp.margin.left
38850
        - bp.margin.right
38850
        - bp.border.left
38850
        - bp.border.right
38850
        - bp.padding.left
38850
        - bp.padding.right;
38850
    aw.max(0.0)
38850
}
/// The used inline size of an `auto` block-level box, per constraint kind.
///
/// CSS Sizing 3 §5.1: stretch-fit is defined against a **definite** available
/// size. Under a measurement constraint there is none, and the box resolves
/// to its CONTRIBUTION of that constraint's kind — min-content under a
/// min-content pass, max-content under a max-content pass. The pre-typed
/// version of this helper only knew "not finite" and always answered
/// max-content, which was subtly wrong for min-content passes; the typed axis
/// makes the distinction expressible at all.
///
/// (History: before any of this, `auto` stretch-fit against the flattened
/// `f32::INFINITY` sentinel persisted an INFINITE used width — which became an
/// infinite clip rect, a `u32::MAX`-wide compositor layer, and a ~900 GB
/// pixmap request.)
///
/// Kept as a separate small `#[inline(never)]` fn taking `&` args and
/// returning `f32` for the same reason [`auto_block_inline_size`] is: the
/// M12.7 remill lift mis-reads f32 loads inside the ~6 KB
/// `calculate_used_size_for_node`.
#[inline(never)]
38864
fn auto_inline_size_for(
38864
    cb_w: Text3AvailableSpace,
38864
    bp: &BoxProps,
38864
    min_content_width: f32,
38864
    max_content_width: f32,
38864
) -> f32 {
38864
    match cb_w {
38839
        Text3AvailableSpace::Definite(w) => auto_block_inline_size(&LogicalSize::new(w, 0.0), bp),
        // `.max(0.0)` also normalises a NaN intrinsic to 0 — an unmeasured box
        // is zero-sized, never a size that poisons everything downstream.
10
        Text3AvailableSpace::MinContent => min_content_width.max(0.0),
15
        Text3AvailableSpace::MaxContent => max_content_width.max(0.0),
    }
38864
}
#[allow(clippy::match_same_arms)]
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
// merge)
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Errors
///
/// Returns a `LayoutError` if computing the used size fails.
58370
pub fn calculate_used_size_for_node(
58370
    styled_dom: &StyledDom,
58370
    dom_id: Option<NodeId>,
58370
    // M12.7: by-reference (GP-register pointer). A by-value LogicalSize is an HFA
58370
    // (2×f32) the remill lift stages as an 8-byte double into a V register, and that
58370
    // f64/d-register copyload mis-tracks to 0 in the wasm lift (single-f32 reads work,
58370
    // the 64-bit one doesn't) — so cb + viewport arrived 0 and every width came out 0.
58370
    // A pointer arg lifts cleanly. The typed `ContainingBlock` keeps that shape.
58370
    //
58370
    // TYPED on purpose: each axis says whether it is a LENGTH or a measurement
58370
    // CONSTRAINT, so no arm below can do arithmetic on an `f32::INFINITY`
58370
    // sentinel — the erasure that produced an infinite used size three
58370
    // different ways (auto stretch-fit, `width: 100%`, percent min-width).
58370
    cb: &super::geometry::ContainingBlock,
58370
    intrinsic: IntrinsicSizes,
58370
    box_props: &BoxProps,
58370
    viewport_size: &LogicalSize,
58370
) -> Result<LogicalSize> {
    // The two axes, consumed all over the body. `Copy` enums — reading them
    // out once keeps every use a plain register value (M12.7).
58370
    let cb_w = cb.width;
58370
    let cb_h = cb.height;
    // For helpers that treat a non-finite base as "cannot resolve" (the min/max
    // constraint resolvers): an indefinite axis travels as NaN, which their
    // `is_finite` guard maps to None. NEVER used in arithmetic here.
58370
    let cbw_unresolvable_nan = cb_w.definite().unwrap_or(f32::NAN);
58370
    let cbh_unresolvable_nan = cb_h.definite().unwrap_or(f32::NAN);
58370
    let Some(id) = dom_id else {
        // Anonymous boxes:
        // CSS 2.2 § 9.2.1.1: Anonymous boxes inherit from their enclosing box.
        // The inline dimension fills the containing block's inline size,
        // and the block dimension is auto (content-based).
        // In horizontal-tb: inline=width, block=height.
        // In vertical modes: inline=height, block=width.
        //
        // Since anonymous boxes don't have a DOM node, we default to horizontal-tb.
        // The parent's writing mode is already reflected in containing_block_size.
210
        return Ok(LogicalSize::new(
            // An anonymous box fills a definite containing block; under a
            // measurement constraint it is exactly its contribution of that
            // kind — never infinitely wide.
210
            match cb_w {
210
                Text3AvailableSpace::Definite(w) => w,
                Text3AvailableSpace::MinContent => intrinsic.min_content_width.max(0.0),
                Text3AvailableSpace::MaxContent => intrinsic.max_content_width.max(0.0),
            },
210
            if intrinsic.max_content_height > 0.0 {
1
                intrinsic.max_content_height
            } else {
                // Auto height - will be resolved from content
209
                0.0
            },
        ));
    };
58160
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
58160
    let css_width = get_css_width(styled_dom, id, node_state);
58160
    let css_height = get_css_height(styled_dom, id, node_state);
58160
    let writing_mode = get_writing_mode(styled_dom, id, node_state);
58160
    let display = get_display_property(styled_dom, Some(id));
58160
    let position = get_position_type(styled_dom, dom_id);
    // Construct the full WritingModeContext from resolved styles.
    // This determines how logical dimensions (inline/block) map to physical (width/height).
58160
    let wm_ctx = WritingModeContext::new(
58160
        writing_mode.unwrap_or_default(),
58160
        get_direction_property(styled_dom, id, node_state).unwrap_or_default(),
58160
        get_text_orientation_property(styled_dom, id, node_state).unwrap_or_default(),
    );
58160
    let is_vertical = !wm_ctx.is_horizontal();
    // +spec:display-property:06e0b1 - form controls (non-image) treated as non-replaced
    // Determine if this element is a replaced element (images, virtual views)
58160
    let node_data = &styled_dom.node_data.as_container()[id];
58160
    let is_replaced =
58160
        matches!(node_data.get_node_type(), NodeType::Image(_)) || node_data.is_virtual_view_node();
    // +spec:width-calculation:79cdf8 - inline non-replaced: width property does not apply
    // +spec:width-calculation:972e86 - §10.3.1: width property does not apply to inline
    // non-replaced elements For inline non-replaced elements, override any explicit width to
    // Auto.
58160
    let css_width = if display.unwrap_or_default() == LayoutDisplay::Inline && !is_replaced {
2040
        MultiValue::Exact(LayoutWidth::Auto)
    } else {
56120
        css_width
    };
    // +spec:box-model:1197a5 - height does not apply to non-replaced inline elements
    // +spec:display-property:9cb33d - height does not apply to inline boxes
    // +spec:height-calculation:c03717 - height does not apply to inline non-replaced elements
    // CSS 2.2 §10.6.1 / CSS Inline 3 §6.4: height property does not apply to
    // inline, non-replaced elements. Override any explicit height to Auto.
58160
    let css_height = if display.unwrap_or_default() == LayoutDisplay::Inline && !is_replaced {
2040
        MultiValue::Exact(LayoutHeight::Auto)
    } else {
56120
        css_height
    };
    // Remember if width/height were auto before consuming them
58160
    let width_is_auto =
58160
        css_width.is_auto() || matches!(&css_width, MultiValue::Exact(LayoutWidth::Auto));
58160
    let height_is_auto =
58160
        css_height.is_auto() || matches!(&css_height, MultiValue::Exact(LayoutHeight::Auto));
    // +spec:intrinsic-sizing:9e1c9d - non-quantitative values (auto, min-content, max-content) are
    // not influenced by box-sizing
58160
    let width_is_quantitative = matches!(
12840
        &css_width,
        MultiValue::Exact(LayoutWidth::Px(_) | LayoutWidth::FitContent(_) | LayoutWidth::Calc(_))
    );
58160
    let height_is_quantitative = matches!(
16930
        &css_height,
        MultiValue::Exact(
            LayoutHeight::Px(_) | LayoutHeight::FitContent(_) | LayoutHeight::Calc(_)
        )
    );
    // +spec:width-calculation:50d67a - automatic sizing concepts (width/height auto resolution)
    // +spec:width-calculation:564315 - §10.3 width calculation dispatch for all box types
    // Step 1: Resolve the CSS `width` property into a concrete pixel value.
    // CSS `width` always refers to the physical horizontal dimension, regardless of writing mode.
    // Percentage values resolve against the containing block's physical width.
    // In horizontal-tb: width = inline size. In vertical modes: width = block size.
    // The physical-to-logical mapping happens in Step 5 below.
    // Percentage values for `width` are resolved against the containing block's width.
    // +spec:width-calculation:febf0c - width/height "behaves as auto" when computed auto or
    // percentage resolves against indefinite
58160
    let resolved_width = match css_width.unwrap_or_default() {
        LayoutWidth::Auto => {
            // +spec:width-calculation:ed6a34 - auto width on replaced element uses intrinsic width
            // CSS 2.2 §10.3.2: If 'width' has a computed value of 'auto', and the element
            // has an intrinsic width, then that intrinsic width is the used value of 'width'.
            // +spec:replaced-elements:992ea5 - block-level replaced elements use inline replaced
            // width rules §10.3.4: "The used value of 'width' is determined as for
            // inline replaced elements." +spec:replaced-elements:36de3e -
            // §10.3.2/§10.3.4: auto width for inline/block replaced elements uses intrinsic width
            // +spec:replaced-elements:b9a780 - §10.3.2: inline replaced auto width = intrinsic
            // width (conditions resolved during intrinsic size calc)
47360
            if is_replaced {
                // +spec:width-calculation:b41dbe - floating/inline replaced: auto width = intrinsic
                // width +spec:width-calculation:c62d35 - §10.3.2: auto width for
                // replaced elements uses intrinsic width +spec:width-calculation:
                // d87ca4 - abs-replaced: auto width+height uses intrinsic width For
                // replaced elements (inline or block-level), auto width = intrinsic width.
                // The intrinsic sizes were already computed with the 300px fallback per §10.3.2.
780
                intrinsic.max_content_width
            }
            // +spec:intrinsic-sizing:560697 - shrink-to-fit = clamp(min-content, stretch-fit,
            // max-content)
46580
            else if get_float(styled_dom, id, node_state).unwrap_or(LayoutFloat::None)
46580
                != LayoutFloat::None
            {
                // +spec:width-calculation:8d7047 - shrink-to-fit width per CSS2.1§10.3.5
                // +spec:width-calculation:0bb038 - shrink-to-fit for floating non-replaced elements
                // (§10.3.5) shrink-to-fit = min(max(preferred minimum width,
                // available width), preferred width) +spec:table-layout:93b13c -
                // shrink-to-fit for floats, inline-blocks, table-cells; orthogonal
                // flows would require child block size as input (not yet implemented)
                // +spec:width-calculation:a6fd29 - shrink-to-fit width for floats:
                // min(max(preferred minimum, available), preferred) CSS 2.2 §10.3.
                // 5: For floats, auto width = shrink-to-fit
20
                let available_width = shrink_to_fit_available_width(cb_w, box_props);
20
                let preferred_minimum = intrinsic.min_content_width;
20
                let preferred = intrinsic.max_content_width;
20
                preferred_minimum
20
                    .max(available_width)
20
                    .min(preferred)
20
                    .max(0.0)
46560
            } else if matches!(position, LayoutPosition::Absolute | LayoutPosition::Fixed) {
                // +spec:intrinsic-sizing:12a531 - abspos auto size = fit-content (shrink-to-fit)
                // +spec:width-calculation:0bb038 - shrink-to-fit width for abs-pos non-replaced
                // elements §10.3.7: abs-pos elements with auto width use
                // shrink-to-fit +spec:intrinsic-sizing:087b57 - abspos automatic
                // size is fit-content (shrink-to-fit) +spec:width-calculation:
                // 1661b4 - abs-pos non-replaced auto width uses shrink-to-fit (§10.3.7)
                // shrink-to-fit = min(max(preferred_minimum, available), preferred)
2404
                let available_width = shrink_to_fit_available_width(cb_w, box_props);
2404
                let preferred_minimum = intrinsic.min_content_width;
2404
                let preferred = intrinsic.max_content_width;
2404
                preferred_minimum
2404
                    .max(available_width)
2404
                    .min(preferred)
2404
                    .max(0.0)
            } else {
                // +spec:width-calculation:472065 - orthogonal flow auto inline size: if this block
                // container establishes an orthogonal flow (child writing mode axis differs from
                // parent), its auto inline size should use the parent's block-axis size as
                // available space, falling back to the initial containing block
                // size. Currently not implemented; auto width always resolves
                // against the containing block's width. 'auto' width resolution
                // depends on the display type.
44156
                match display.unwrap_or_default() {
                    LayoutDisplay::Block
                    | LayoutDisplay::FlowRoot
                    | LayoutDisplay::ListItem
                    | LayoutDisplay::Flex
                    | LayoutDisplay::Grid => {
                        // +spec:box-model:503ea3 - margin + border + padding + width = containing
                        // block width +spec:box-model:5ed651 - stretch fit:
                        // size minus margins (auto=0), border, padding, floored at 0
                        // +spec:box-model:33b951 - stretch-fit inline size: available space minus
                        // margins/border/padding, floored at zero
                        // +spec:box-model:30b4d0 - stretch fit: available size minus margins (auto
                        // as zero), border, padding, floored at zero
                        // +spec:width-calculation:e2c8f6 - auto width for non-replaced blocks in
                        // normal flow per CSS2.1§10.3.3 For block-level
                        // non-replaced elements, 'auto' width fills the
                        // containing block (minus margins, borders, padding).
                        // CSS 2.2 §10.3.3: width = containing_block_width - margin_left -
                        // margin_right - border_left - border_right - padding_left - padding_right
                        // +spec:width-calculation:aef2da - auto width: other auto values become 0,
                        // width follows from constraint equality
                        // M12.7: compute in a small #[inline(never)] helper with by-ref/out-ptr
                        // args. calc_used_size is a ~6KB fn (38 maxnum, heavy SROA); the remill
                        // lift spills + diverges the available_width copyload feeding `.max`
                        // (a marker read sees 800, the maxnum's copyload reads 0 → width 0). A
                        // small fn has clean register allocation; out-ptr avoids the f32-return
                        // mis-lift. cb/bp are already &-refs (GP-pointer args lift cleanly).
                        // M12.7: compute the auto-width in a small f32-RETURNING helper.
                        // Inline-in-calc reads cb.width back 0 (huge-fn lift divergence); the
                        // out-ptr helper's readback was opt-forwarded to init 0. The f32
                        // return comes back in D0 as the call's SSA result (opt can't forward
                        // the init over it), and with D8-D15 preserved across calc's later
                        // calls the value survives to the return.
38845
                        auto_inline_size_for(
38845
                            cb_w,
38845
                            box_props,
38845
                            intrinsic.min_content_width,
38845
                            intrinsic.max_content_width,
                        )
                    }
                    LayoutDisplay::InlineBlock
                    | LayoutDisplay::InlineGrid
                    | LayoutDisplay::InlineFlex => {
                        // +spec:width-calculation:c01de8 - inline-block auto width uses
                        // shrink-to-fit (§10.3.9) shrink-to-fit =
                        // min(max(preferred_minimum, available), preferred)
251
                        let available_width = shrink_to_fit_available_width(cb_w, box_props);
251
                        let preferred_minimum = intrinsic.min_content_width;
251
                        let preferred = intrinsic.max_content_width;
251
                        preferred_minimum
251
                            .max(available_width)
251
                            .min(preferred)
251
                            .max(0.0)
                    }
                    LayoutDisplay::Inline => {
                        // For inline elements, 'auto' width is the intrinsic/max-content width
2040
                        intrinsic.max_content_width
                    }
                    LayoutDisplay::Table | LayoutDisplay::InlineTable => {
680
                        intrinsic.max_content_width
                    }
                    // Table cells: during intrinsic measurement, intrinsic sizes
                    // aren't known yet (0). Use containing block width so content
                    // can expand and be measured. The table layout algorithm sets
                    // the final cell width from computed column widths.
                    LayoutDisplay::TableCell => {
2340
                        if intrinsic.max_content_width > 0.0 {
2340
                            intrinsic.max_content_width
                        } else {
                            // A definite containing block lets an unmeasured
                            // cell expand for measurement. Under a measurement
                            // CONSTRAINT there is nothing to expand into — the
                            // old sentinel arithmetic made this infinite; an
                            // unmeasured cell contributes zero until the table
                            // algorithm assigns real column widths.
                            cb_w.definite().map_or(0.0, |w| {
                                (w - box_props.margin.left
                                    - box_props.margin.right
                                    - box_props.border.left
                                    - box_props.border.right
                                    - box_props.padding.left
                                    - box_props.padding.right)
                                    .max(0.0)
                            })
                        }
                    }
                    // Other display types use intrinsic sizing
                    _ => intrinsic.max_content_width,
                }
            }
        }
10800
        LayoutWidth::Px(px) => {
10800
            let em = get_element_font_size(styled_dom, id, node_state);
10800
            let rem = super::getters::get_root_font_size(styled_dom, node_state);
10800
            let pixels_opt = super::calc::resolve_pixel_value_no_percent_with_viewport(
10800
                &px,
10800
                em,
10800
                rem,
10800
                viewport_size.width,
10800
                viewport_size.height,
            );
10800
            pixels_opt.unwrap_or_else(|| {
2015
                px.to_percent().map_or(intrinsic.max_content_width, |p| {
                    // css-sizing-3 §5.2.1: a percentage against an indefinite
                    // size behaves as auto — the contribution of the pass's
                    // kind, never sentinel arithmetic.
2015
                    match cb_w {
1999
                        Text3AvailableSpace::Definite(w) => resolve_percentage_with_box_model(
1999
                            w,
1999
                            p.get(),
1999
                            (box_props.margin.left, box_props.margin.right),
1999
                            (box_props.border.left, box_props.border.right),
1999
                            (box_props.padding.left, box_props.padding.right),
                        ),
11
                        Text3AvailableSpace::MinContent => intrinsic.min_content_width,
5
                        Text3AvailableSpace::MaxContent => intrinsic.max_content_width,
                    }
2015
                })
2015
            })
        }
        // +spec:intrinsic-sizing:069c75 - min-content, max-content, fit-content() sizing value
        // keywords +spec:intrinsic-sizing:1ce4fa - §3.2
        // min-content/max-content/fit-content() sizing values
        LayoutWidth::MinContent => intrinsic.min_content_width,
        LayoutWidth::MaxContent => intrinsic.max_content_width,
        // +spec:width-calculation:7b2128 - fit-content formula and non-negative inner size flooring
        // (css-sizing-3 §3.2) +spec:width-calculation:bf694a - min-content, max-content,
        // fit-content() sizing values css-sizing-3 §3.2: fit-content(<length-percentage>) =
        // min(max-content, max(min-content, <length-percentage>))
        LayoutWidth::FitContent(px) => {
            let em = get_element_font_size(styled_dom, id, node_state);
            let rem = super::getters::get_root_font_size(styled_dom, node_state);
            // An indefinite basis travels as NaN: a percent argument then
            // resolves to NaN, the fit-content formula propagates it, and the
            // non-finite net below lands on the content contribution — the
            // behaves-as-auto outcome, without sentinel arithmetic.
            let arg = super::calc::resolve_pixel_value_with_viewport(
                &px,
                cbw_unresolvable_nan,
                em,
                rem,
                viewport_size.width,
                viewport_size.height,
            );
            intrinsic
                .max_content_width
                .min(intrinsic.min_content_width.max(arg))
        }
        LayoutWidth::Calc(items) => {
            use azul_css::props::basic::pixel::DEFAULT_FONT_SIZE;
            let em = get_element_font_size(styled_dom, id, node_state);
            let calc_ctx = super::calc::CalcResolveContext {
                items,
                em_size: em,
                rem_size: DEFAULT_FONT_SIZE,
            };
            // A calc() with percent terms against an indefinite basis behaves
            // as auto, like the plain percentage above.
            match cb_w {
                Text3AvailableSpace::Definite(w) => super::calc::evaluate_calc(&calc_ctx, w),
                Text3AvailableSpace::MinContent => intrinsic.min_content_width,
                Text3AvailableSpace::MaxContent => intrinsic.max_content_width,
            }
        }
    };
    // css-sizing-3: "the used value is floored to preserve a non-negative inner size"
    //
    // And a net over EVERY arm above: a width that came out non-finite means
    // some input resolved against the indefinite (measurement-pass) containing
    // block — a percentage, a calc() with percent terms, anything. Spec-wise
    // such a size "behaves as auto" (febf0c), and auto under an indefinite
    // constraint is the max-content contribution (see
    // auto_block_inline_size_definite_or_max_content). Letting the infinity
    // through instead PERSISTS it as the node's used size, and no later stage
    // survives that — it becomes an infinite clip, u32::MAX device pixels, and
    // a ~900 GB pixmap request. Not loud: this is a legitimate, per-frame
    // situation during measurement, not a bug to report.
58160
    let resolved_width = if resolved_width.is_finite() {
58159
        resolved_width.max(0.0)
    } else {
1
        intrinsic.max_content_width.max(0.0)
    };
    // +spec:height-calculation:7880e3 - Distinction between box types for height/margin calculation
    // +spec:height-calculation:753d8d - Height calculation for various box types (§10.6)
    // +spec:positioning:d5184e - percentage height resolved against containing block height
    // +spec:height-calculation:6a6cac - §10.5 content height resolution (auto, length, percentage)
    // +spec:height-calculation:d398e4 - §10.5/10.6 height property resolution for different box
    // types Step 2: Resolve the CSS `height` property into a concrete pixel value.
    // CSS `height` always refers to the physical vertical dimension, regardless of writing mode.
    // Percentage values resolve against the containing block's physical height.
    // In horizontal-tb: height = block size. In vertical modes: height = inline size.
    // The physical-to-logical mapping happens in Step 5 below.
    // Percentage values for `height` are resolved against the containing block's height.
    // +spec:height-calculation:0b5b0a - abs-pos replaced elements use intrinsic height for auto
58160
    let resolved_height = match css_height.unwrap_or_default() {
        LayoutHeight::Auto => {
            // +spec:width-calculation:be5eb1 - auto height means available block space is infinite
            // (unconstrained) +spec:replaced-elements:994ac6 - §10.6.2: auto height for
            // replaced elements uses intrinsic height or (used width)/ratio
            //
            // For block-level non-replaced containers in normal flow, CSS 2.2 §10.6.3
            // says auto height is resolved from children after layout. We return 0.0
            // as a placeholder; `apply_content_based_height` (cache.rs) overwrites it
            // with the laid-out content size. Reading `intrinsic.max_content_height`
            // here is unsafe: when the intrinsic pass short-circuits (e.g. a non-STF
            // subtree whose intrinsics are never consumed), that field is zero anyway
            // — so any caller that "trusts" the pre-layout value is depending on an
            // estimate that isn't guaranteed to exist.
            //
            // Shrink-to-fit contexts (inline-block, float, abspos, table/table-cell)
            // genuinely need intrinsic for width sizing; auto-height for those is
            // still driven by content, but we keep the intrinsic fallback for
            // backwards compatibility with the existing paths.
            // CSS 2.2 §10.6.4: an absolutely/fixed-positioned non-replaced box with
            // `height:auto` and BOTH `top` and `bottom` specified has a STRETCH-FIT
            // height = cb_height − top − bottom − margins. `position_out_of_flow_
            // elements` also derives this, but it runs AFTER the subtree is laid out —
            // so resolving it HERE (a definite, computed height) lets percentage-height
            // CHILDREN resolve against the real box during their own layout instead of
            // collapsing against a 0 placeholder. (Root cause of the slippy-map
            // VirtualView blank-bounds bug: its container fills via abs inset:0.)
43270
            let abs_stretch_fit =
43270
                if matches!(position, LayoutPosition::Absolute | LayoutPosition::Fixed)
2406
                    && !is_replaced
                {
                    // §10.6.4 solves the height from the insets only against
                    // a DEFINITE containing block; under a measurement
                    // constraint there is no block to inset from, so the auto
                    // (content height) fallback below applies.
2406
                    let off = crate::solver3::positioning::resolve_position_offsets(
2406
                        styled_dom,
2406
                        dom_id,
2406
                        cb.flattened(),
2406
                        *viewport_size,
                    );
2406
                    match (off.top, off.bottom, cb_h.definite()) {
262
                        (Some(t), Some(b), Some(cbh)) => Some(
262
                            (cbh - t - b - box_props.margin.top - box_props.margin.bottom).max(0.0),
262
                        ),
2144
                        _ => None,
                    }
                } else {
40864
                    None
                };
43008
            match abs_stretch_fit {
262
                Some(h) => h,
                // §10.6.2: auto height for a replaced element (image / VirtualView)
                // uses its intrinsic height — mirrors the auto-WIDTH replaced branch
                // above. Without this, replaced nodes (no flow content) get 0 height
                // (the blank-image / "300x0" bug).
1470
                None if is_replaced => intrinsic.max_content_height,
41538
                None => match display.unwrap_or_default() {
                    LayoutDisplay::Block
                    | LayoutDisplay::FlowRoot
                    | LayoutDisplay::ListItem
                    | LayoutDisplay::Flex
36157
                    | LayoutDisplay::Grid => 0.0,
                    // Inline: height property does not apply (§10.6.1), handled earlier
                    // via css_height override, but be explicit anyway.
2040
                    LayoutDisplay::Inline => 0.0,
                    // Shrink-to-fit and intrinsically-sized: keep using intrinsic pre-layout.
3341
                    _ => intrinsic.max_content_height,
                },
            }
        }
14890
        LayoutHeight::Px(px) => {
14890
            let em = get_element_font_size(styled_dom, id, node_state);
14890
            let rem = super::getters::get_root_font_size(styled_dom, node_state);
14890
            let pixels_opt = super::calc::resolve_pixel_value_no_percent_with_viewport(
14890
                &px,
14890
                em,
14890
                rem,
14890
                viewport_size.width,
14890
                viewport_size.height,
            );
            // +spec:height-calculation:37bc8c - percentage heights resolve against definite
            // containing block height
14890
            pixels_opt.unwrap_or_else(|| {
1089
                px.to_percent().map_or(intrinsic.max_content_height, |p| {
                    // Percentage against an indefinite block size behaves as
                    // auto = the content height. (Both measurement kinds map
                    // to max-content here: "min-content height" is height at
                    // min-content WIDTH, not a shorter height.)
1089
                    cb_h.definite().map_or(intrinsic.max_content_height, |h| {
1083
                        resolve_percentage_with_box_model(
1083
                            h,
1083
                            p.get(),
1083
                            (box_props.margin.top, box_props.margin.bottom),
1083
                            (box_props.border.top, box_props.border.bottom),
1083
                            (box_props.padding.top, box_props.padding.bottom),
                        )
1083
                    })
1089
                })
1089
            })
        }
        // equivalent to automatic size (not min_content_height which is height at min-content
        // width)
        LayoutHeight::MinContent => intrinsic.max_content_height,
        // equivalent to automatic size
        LayoutHeight::MaxContent => intrinsic.max_content_height,
        // css-sizing-3 §3.2: fit-content(<length-percentage>) = min(max-content, max(min-content,
        // <length-percentage>)) For block axis, both min-content and max-content equal auto
        // height
        LayoutHeight::FitContent(px) => {
            let em = get_element_font_size(styled_dom, id, node_state);
            let rem = super::getters::get_root_font_size(styled_dom, node_state);
            // NaN routing as in the width fit-content arm.
            let arg = super::calc::resolve_pixel_value_with_viewport(
                &px,
                cbh_unresolvable_nan,
                em,
                rem,
                viewport_size.width,
                viewport_size.height,
            );
            let auto_height = intrinsic.max_content_height;
            auto_height.min(auto_height.max(arg))
        }
        LayoutHeight::Calc(items) => {
            use azul_css::props::basic::pixel::DEFAULT_FONT_SIZE;
            let em = get_element_font_size(styled_dom, id, node_state);
            let calc_ctx = super::calc::CalcResolveContext {
                items,
                em_size: em,
                rem_size: DEFAULT_FONT_SIZE,
            };
            // Same indefinite-basis rule as the width calc arm.
            cb_h.definite().map_or(intrinsic.max_content_height, |h| {
                super::calc::evaluate_calc(&calc_ctx, h)
            })
        }
    };
    // css-sizing-3: "the used value is floored to preserve a non-negative inner size"
    // Same indefinite-input net as resolved_width above.
58160
    let resolved_height = if resolved_height.is_finite() {
58159
        resolved_height.max(0.0)
    } else {
1
        intrinsic.max_content_height.max(0.0)
    };
    // +spec:replaced-elements:5a85ce - abs-pos replaced: derive auto width from height × intrinsic
    // ratio +spec:replaced-elements:aedb26 - abs-pos replaced: both auto, ratio but no
    // intrinsic w/h → block constraint CSS Position 3 §6.2 (abs-replaced-width): For absolutely
    // positioned replaced elements, if width is auto and the element has an intrinsic ratio,
    // width may be derived from height.
58160
    let (resolved_width, resolved_height) = if is_replaced
1907
        && width_is_auto
780
        && matches!(position, LayoutPosition::Absolute | LayoutPosition::Fixed)
    {
        let has_intrinsic_width = intrinsic.preferred_width.is_some_and(|w| w > 0.0);
        let has_intrinsic_height = intrinsic.preferred_height.is_some_and(|h| h > 0.0);
        let intrinsic_ratio = match (intrinsic.preferred_width, intrinsic.preferred_height) {
            (Some(iw), Some(ih)) if ih > 0.0 => Some(iw / ih),
            _ => None,
        };
        intrinsic_ratio.map_or((resolved_width, resolved_height), |ratio| {
            if height_is_auto && !has_intrinsic_width && has_intrinsic_height {
                // §6.2 case: both auto, no intrinsic width, has intrinsic height + ratio
                // → width = used height × ratio
                (resolved_height * ratio, resolved_height)
            } else if !height_is_auto {
                // §6.2 case: width auto, height not auto, has intrinsic ratio
                // → width = used height × ratio
                (resolved_height * ratio, resolved_height)
            } else if height_is_auto && !has_intrinsic_width && !has_intrinsic_height {
                // §6.2 case: both auto, has ratio but no intrinsic width or height
                // → use block-level non-replaced constraint equation for width
                // The §6.2 block constraint equation needs a definite inline
                // size; under a measurement constraint fall back to the
                // element's content contribution instead of stretching to a
                // sentinel.
                let block_width = cb_w.definite().map_or(intrinsic.max_content_width, |w| {
                    (w - box_props.margin.left
                        - box_props.margin.right
                        - box_props.border.left
                        - box_props.border.right
                        - box_props.padding.left
                        - box_props.padding.right)
                        .max(0.0)
                });
                (block_width, block_width / ratio)
            } else {
                (resolved_width, resolved_height)
            }
        })
    } else {
58160
        (resolved_width, resolved_height)
    };
    // +spec:aspect-ratio:0 - CSS Sizing 4: a non-replaced box with `aspect-ratio` and
    // exactly one auto axis derives the auto axis from the definite one via the ratio.
    // The ratio is applied to the content box here (box-sizing:border-box, which would
    // fold in padding+border, is not yet handled). Replaced elements use their intrinsic
    // ratio in the block above.
    #[allow(clippy::cast_precision_loss)] // small integer aspect-ratio components (e.g. 2000/1000)
58160
    let (resolved_width, resolved_height) = if is_replaced {
1907
        (resolved_width, resolved_height)
21
    } else if let MultiValue::Exact(azul_css::props::style::effects::StyleAspectRatio::Ratio(ar)) =
56253
        crate::solver3::getters::get_aspect_ratio_property(styled_dom, id, node_state)
    {
21
        let ratio = if ar.height == 0 {
            0.0
        } else {
21
            ar.width as f32 / ar.height as f32
        };
21
        if ratio > 0.0 && height_is_auto && !width_is_auto {
21
            (resolved_width, resolved_width / ratio)
        } else if ratio > 0.0 && width_is_auto && !height_is_auto {
            (resolved_height * ratio, resolved_height)
        } else {
            (resolved_width, resolved_height)
        }
    } else {
56232
        (resolved_width, resolved_height)
    };
    // +spec:min-max-sizing:58869e - sizing properties
    // width/height/min-width/min-height/max-width/max-height applied here +spec:min-max-sizing:
    // 2e2414 - max-width/max-height specify maximum box dimensions, applied here
    // +spec:min-max-sizing:73f51a - tentative width clamped by max-width then min-width per §10.4
    // +spec:min-max-sizing:e98c4e - preferred size clamped by min/max, box-sizing handled
    // Step 3: Apply min/max constraints (CSS 2.2 § 10.4 and § 10.7)
    // "The tentative used width is calculated (without 'min-width' and 'max-width')
    // ...If the tentative used width is greater than 'max-width', the rules above are
    // applied again using the computed value of 'max-width' as the computed value for 'width'.
    // If the resulting width is smaller than 'min-width', the rules above are applied again
    // using the value of 'min-width' as the computed value for 'width'."
    // use the constraint violation table to coordinate width+height together;
    // for non-replaced elements, apply width and height constraints independently
58160
    let has_intrinsic_ratio = intrinsic.preferred_width.is_some()
33
        && intrinsic.preferred_height.is_some()
33
        && intrinsic.preferred_width.unwrap_or(0.0) > 0.0
33
        && intrinsic.preferred_height.unwrap_or(0.0) > 0.0;
    // +spec:margin-collapsing:840eb6 - aspect ratio transfers size constraints across dimensions
58160
    let (constrained_width, constrained_height) = if has_intrinsic_ratio {
        // +spec:width-calculation:ef71c4 - replaced elements with both width/height auto use
        // constraint violation table Replaced element with intrinsic ratio: use §10.4
        // constraint violation table
33
        apply_constraint_violation_table(
33
            styled_dom,
33
            id,
33
            node_state,
33
            resolved_width,
33
            resolved_height,
            // Indefinite axes travel as NaN: percent min/max constraints
            // against them are unresolvable and resolve_px_with_box_model
            // maps a non-finite basis to None (min -> 0, max -> unbounded).
33
            cbw_unresolvable_nan,
33
            cbh_unresolvable_nan,
33
            box_props,
        )
    } else {
        // Non-replaced element: apply width and height constraints independently
58127
        let cw = apply_width_constraints(
58127
            styled_dom,
58127
            id,
58127
            node_state,
58127
            resolved_width,
58127
            cbw_unresolvable_nan,
58127
            box_props,
        );
58127
        let ch = apply_height_constraints(
58127
            styled_dom,
58127
            id,
58127
            node_state,
58127
            resolved_height,
58127
            cbh_unresolvable_nan,
58127
            box_props,
        );
58127
        (cw, ch)
    };
    // +spec:box-model:cc170b - box-sizing: border-box includes padding+border in specified size;
    // content-box adds them outside; content size floored at zero +spec:box-model:d9d797 -
    // box-sizing: content-box vs border-box dimension interpretation +spec:box-model:e2a773 -
    // box-sizing: border-box includes padding+border in width/height; content-box adds them outside
    // +spec:box-sizing:8159a8 - box-sizing property indicates whether content-box or border-box is
    // measured +spec:box-sizing:b0ff05 - border-box sets border-box to specified size,
    // content-box calculated from it +spec:box-sizing:aefeb2 - box-sizing: content-box vs
    // border-box width/height interpretation +spec:box-sizing:e2e28c - width/height refer to
    // content-box size by default (content-box); box-sizing: border-box makes them refer to
    // border-box size Step 4: Convert to border-box dimensions, respecting box-sizing property
    // CSS box-sizing:
    // - content-box (default): width/height set content size, border+padding are added
    // - border-box: width/height set border-box size, border+padding are included
58160
    let box_sizing = match get_css_box_sizing(styled_dom, id, node_state) {
58152
        MultiValue::Exact(bs) => bs,
        MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => {
8
            azul_css::props::layout::LayoutBoxSizing::ContentBox
        }
    };
58160
    let (border_box_width, border_box_height) = match box_sizing {
        azul_css::props::layout::LayoutBoxSizing::BorderBox => {
            // +spec:box-sizing:cdfe09 - box-sizing: border-box makes width/height set the border
            // box +spec:box-sizing:3ba6d3 - content-box floors at 0px, so border-box
            // can't be less than padding+border
2773
            let min_border_box_w = box_props.padding.left
2773
                + box_props.padding.right
2773
                + box_props.border.left
2773
                + box_props.border.right;
2773
            let min_border_box_h = box_props.padding.top
2773
                + box_props.padding.bottom
2773
                + box_props.border.top
2773
                + box_props.border.bottom;
            // +spec:box-model:4f423b - used values refer to the border box when box-sizing:
            // border-box border-box: The width/height values already include border and
            // padding CSS Box Sizing Level 3: "the specified width and height (and
            // respective min/max properties) on this element determine the border box
            // of the element" However, non-quantitative values (auto, min-content,
            // max-content) are not influenced by box-sizing, so they still need
            // border+padding added. Floor: content-box cannot go negative, so
            // border-box >= padding+border
2773
            let bw = if width_is_quantitative {
383
                constrained_width.max(min_border_box_w)
            } else {
2390
                constrained_width
2390
                    + box_props.padding.left
2390
                    + box_props.padding.right
2390
                    + box_props.border.left
2390
                    + box_props.border.right
            };
2773
            let bh = if height_is_quantitative {
423
                constrained_height.max(min_border_box_h)
            } else {
2350
                constrained_height
2350
                    + box_props.padding.top
2350
                    + box_props.padding.bottom
2350
                    + box_props.border.top
2350
                    + box_props.border.bottom
            };
2773
            (bw, bh)
        }
        azul_css::props::layout::LayoutBoxSizing::ContentBox => {
            // +spec:box-sizing:fead70 - content-box: width/height set content size, border+padding
            // added outside
55387
            let border_box_width = constrained_width
55387
                + box_props.padding.left
55387
                + box_props.padding.right
55387
                + box_props.border.left
55387
                + box_props.border.right;
55387
            let border_box_height = constrained_height
55387
                + box_props.padding.top
55387
                + box_props.padding.bottom
55387
                + box_props.border.top
55387
                + box_props.border.bottom;
55387
            (border_box_width, border_box_height)
        }
    };
    // +spec:block-formatting-context:c6fb58 - vertical writing modes swap layout dimensions
    // +spec:min-max-sizing:d97870 - width/height/min/max refer to physical dimensions; layout rules
    // are logical Step 5: Map the resolved physical dimensions to logical dimensions.
    //
    // CSS Writing Modes Level 4:
    // - In horizontal-tb: width = inline (cross) size, height = block (main) size.
    // - In vertical-rl/lr: width = block (main) size, height = inline (cross) size.
    //
    // `from_main_cross` handles this mapping: given (main, cross) and writing mode,
    // it produces the correct LogicalSize with physical (width, height).
58160
    let (main_size, cross_size) = if is_vertical {
        // Vertical writing mode: width is the block (main) dimension,
        // height is the inline (cross) dimension.
30
        (border_box_width, border_box_height)
    } else {
        // Horizontal writing mode (default): width is cross, height is main.
58130
        (border_box_height, border_box_width)
    };
    // Step 6: Construct the final LogicalSize from the logical dimensions.
    // +spec:min-max-sizing:2f66a6 - direction-dependent layout rules abstracted to logical
    // start/end via writing mode
58160
    let result =
58160
        LogicalSize::from_main_cross(main_size, cross_size, writing_mode.unwrap_or_default());
58160
    Ok(result)
58370
}
// +spec:min-max-sizing:b02ebc - sizing properties min-width/max-width/min-height/max-height and
// preferred aspect ratio +spec:replaced-elements:740f3e - constraint violation table for replaced
// elements with intrinsic ratio and both width/height auto +spec:min-max-sizing:939f2c - use
// min-width/min-height <length> with aspect ratio for replaced elements with intrinsic ratios.
// Implements all 10 cases from the spec table, coordinating +spec:min-max-sizing:07620d - CSS 2.2
// §10.4 constraint violation table for replaced elements with intrinsic ratios Implements all 11
// cases from the spec table, coordinating width and height together to preserve the aspect ratio
// while respecting min/max constraints.
48
fn apply_constraint_violation_table(
48
    styled_dom: &StyledDom,
48
    id: NodeId,
48
    node_state: &StyledNodeState,
48
    w: f32, // tentative width (ignoring min/max)
48
    h: f32, // tentative height (ignoring min/max)
48
    containing_block_width: f32,
48
    containing_block_height: f32,
48
    box_props: &BoxProps,
48
) -> (f32, f32) {
    use crate::solver3::getters::{
        get_css_max_height, get_css_max_width, get_css_min_height, get_css_min_width, MultiValue,
    };
    // Resolve em against the element's OWN font-size and rem against the root
    // font-size, NOT a hard-coded 16px.
48
    let em = get_element_font_size(styled_dom, id, node_state);
48
    let rem = super::getters::get_root_font_size(styled_dom, node_state);
    // +spec:min-max-sizing:92ab8d - constraint violation table for replaced elements with intrinsic
    // ratio (cyclic percentage contributions use auto fallback) +spec:min-max-sizing:ad8605 -
    // min-height/max-height interact with percentage heights; percentages behave as auto in
    // intrinsic contribution calc
    // +spec:positioning:c0af55 - automatic minimum size of abspos box is always zero (default 0.0)
    // Resolve min-width (default 0)
48
    let min_w = match get_css_min_width(styled_dom, id, node_state) {
3
        MultiValue::Exact(mw) => {
3
            resolve_px_with_box_model(&mw.inner, containing_block_width, box_props, true, em, rem)
3
                .unwrap_or(0.0)
        }
45
        _ => 0.0,
    };
    // Resolve max-width (default infinity)
48
    let max_w = match get_css_max_width(styled_dom, id, node_state) {
9
        MultiValue::Exact(mw) => {
9
            if mw.inner.number.get() >= core::f32::MAX - 1.0 {
                f32::MAX
            } else {
9
                resolve_px_with_box_model(
9
                    &mw.inner,
9
                    containing_block_width,
9
                    box_props,
                    true,
9
                    em,
9
                    rem,
                )
9
                .unwrap_or(f32::MAX)
            }
        }
39
        _ => f32::MAX,
    };
    // Resolve min-height (default 0)
48
    let min_h = match get_css_min_height(styled_dom, id, node_state) {
        MultiValue::Exact(mh) => resolve_px_with_box_model(
            &mh.inner,
            containing_block_height,
            box_props,
            false,
            em,
            rem,
        )
        .unwrap_or(0.0),
48
        _ => 0.0,
    };
    // Resolve max-height (default infinity)
48
    let max_h = match get_css_max_height(styled_dom, id, node_state) {
3
        MultiValue::Exact(mh) => {
3
            if mh.inner.number.get() >= core::f32::MAX - 1.0 {
                f32::MAX
            } else {
3
                resolve_px_with_box_model(
3
                    &mh.inner,
3
                    containing_block_height,
3
                    box_props,
                    false,
3
                    em,
3
                    rem,
                )
3
                .unwrap_or(f32::MAX)
            }
        }
45
        _ => f32::MAX,
    };
    // max(min, max) so that min ≤ max holds true."
48
    let max_w = max_w.max(min_w);
48
    let max_h = max_h.max(min_h);
    // Guard against zero dimensions (avoid division by zero)
48
    if w <= 0.0 || h <= 0.0 {
4
        return (w.max(min_w).min(max_w), h.max(min_h).min(max_h));
44
    }
44
    let w_over = w > max_w;
44
    let w_under = w < min_w;
44
    let h_over = h > max_h;
44
    let h_under = h < min_h;
    // +spec:min-max-sizing:713560 - constraint violation table for replaced elements with intrinsic
    // ratio
44
    match (w_over, w_under, h_over, h_under) {
        // Row 1: no constraint violation
39
        (false, false, false, false) => (w, h),
        // Row 2: w > max-width only
3
        (true, false, false, false) => (max_w, (max_w * h / w).max(min_h)),
        // Row 3: w < min-width only
        (false, true, false, false) => (min_w, (min_w * h / w).min(max_h)),
        // Row 4: h > max-height only
        (false, false, true, false) => ((max_h * w / h).max(min_w), max_h),
        // Row 5: h < min-height only
        (false, false, false, true) => ((min_h * w / h).min(max_w), min_h),
        // Row 6+7: (w > max-width) and (h > max-height)
        (true, false, true, false) => {
            if max_w / w <= max_h / h {
                (max_w, (max_w * h / w).max(min_h))
            } else {
                ((max_h * w / h).max(min_w), max_h)
            }
        }
        // Row 8+9: (w < min-width) and (h < min-height)
        (false, true, false, true) => {
            if min_w / w <= min_h / h {
                ((min_h * w / h).min(max_w), min_h)
            } else {
                (min_w, (min_w * h / w).min(max_h))
            }
        }
        // Row 10: (w < min-width) and (h > max-height)
2
        (false, true, true, false) => (min_w, max_h),
        // Row 11: (w > max-width) and (h < min-height)
        (true, false, false, true) => (max_w, min_h),
        // Fallback (impossible combinations like w_over && w_under)
        _ => (w.max(min_w).min(max_w), h.max(min_h).min(max_h)),
    }
48
}
// +spec:min-max-sizing:114b53 - min-width/max-width/min-height/max-height property definitions:
// initial values, percentage resolution against containing block, applies to elements accepting
// width/height +spec:min-max-sizing:12667d - width/height/min-width/min-height/max-width/max-height
// properties from CSS Sizing 3
/// +spec:min-max-sizing:205e9e - intrinsic size constraints (min/max-content contributions, min/max
/// sizing properties)
// +spec:min-max-sizing:cac146 - min-width/min-height specify minimum box dimensions; max overridden
// by min +spec:width-calculation:e77d58 - min/max-width clamping algorithm per CSS 2.2 § 10.4
// +spec:width-calculation:1d63f0 - min-width/max-width property resolution and value meanings
/// Apply min-width and max-width constraints to tentative width
/// Per CSS 2.2 § 10.4: min-width overrides max-width if min > max
58145
fn apply_width_constraints(
58145
    styled_dom: &StyledDom,
58145
    id: NodeId,
58145
    node_state: &StyledNodeState,
58145
    tentative_width: f32,
58145
    containing_block_width: f32,
58145
    box_props: &BoxProps,
58145
) -> f32 {
    use crate::solver3::getters::{get_css_max_width, get_css_min_width, MultiValue};
    // Resolve em against the element's OWN font-size and rem against the root.
58145
    let em = get_element_font_size(styled_dom, id, node_state);
58145
    let rem = super::getters::get_root_font_size(styled_dom, node_state);
    // +spec:display-property:0c55e5 - auto min-width resolves to 0 for CSS2 display types
    // Resolve min-width (default is 0)
58145
    let min_width = match get_css_min_width(styled_dom, id, node_state) {
16
        MultiValue::Exact(mw) => {
16
            resolve_px_with_box_model(&mw.inner, containing_block_width, box_props, true, em, rem)
16
                .unwrap_or(0.0)
        }
58129
        _ => 0.0,
    };
    // Resolve max-width (default is infinity/none)
58145
    let max_width = match get_css_max_width(styled_dom, id, node_state) {
21
        MultiValue::Exact(mw) => {
21
            if mw.inner.number.get() >= core::f32::MAX - 1.0 {
                None
            } else {
21
                resolve_px_with_box_model(
21
                    &mw.inner,
21
                    containing_block_width,
21
                    box_props,
                    true,
21
                    em,
21
                    rem,
                )
            }
        }
58124
        _ => None,
    };
    // Apply constraints: max(min_width, min(tentative, max_width))
    // If min > max, min wins per CSS spec
58145
    let mut result = tentative_width;
58145
    if let Some(max) = max_width {
21
        result = result.min(max);
58124
    }
58145
    result.max(min_width)
58145
}
/// Apply min-height and max-height constraints to tentative height
/// Per CSS 2.2 § 10.7: min-height overrides max-height if min > max
// +spec:height-calculation:22a77a - percentage min/max-height resolved against containing block; if
// CB height depends on content and element is not absolutely positioned, percentage treated as 0
// (min-height) or none (max-height) +spec:height-calculation:982aaf - min-height/max-height
// constrain box heights to a range +spec:height-calculation:c6c33a - min-height and max-height
// property resolution and application
58136
fn apply_height_constraints(
58136
    styled_dom: &StyledDom,
58136
    id: NodeId,
58136
    node_state: &StyledNodeState,
58136
    tentative_height: f32,
58136
    containing_block_height: f32,
58136
    box_props: &BoxProps,
58136
) -> f32 {
    use crate::solver3::getters::{get_css_max_height, get_css_min_height, MultiValue};
    // Resolve em against the element's OWN font-size and rem against the root.
58136
    let em = get_element_font_size(styled_dom, id, node_state);
58136
    let rem = super::getters::get_root_font_size(styled_dom, node_state);
    // for backwards-compat with CSS2 display types (block, inline, inline-block, table)
    // Resolve min-height (default is 0)
58136
    let min_height = match get_css_min_height(styled_dom, id, node_state) {
996
        MultiValue::Exact(mh) => resolve_px_with_box_model(
996
            &mh.inner,
996
            containing_block_height,
996
            box_props,
            false,
996
            em,
996
            rem,
        )
996
        .unwrap_or(0.0),
57140
        _ => 0.0,
    };
    // Resolve max-height (default is infinity/none)
58136
    let max_height = match get_css_max_height(styled_dom, id, node_state) {
7
        MultiValue::Exact(mh) => {
7
            if mh.inner.number.get() >= core::f32::MAX - 1.0 {
                None
            } else {
7
                resolve_px_with_box_model(
7
                    &mh.inner,
7
                    containing_block_height,
7
                    box_props,
                    false,
7
                    em,
7
                    rem,
                )
            }
        }
58129
        _ => None,
    };
    // +spec:height-calculation:297001 - min/max height constraint algorithm per CSS 2.2 §10.7
    // Apply constraints: max(min_height, min(tentative, max_height))
    // If min > max, min wins per CSS spec
58136
    let mut result = tentative_height;
58136
    if let Some(max) = max_height {
7
        result = result.min(max);
58129
    }
58136
    result.max(min_height)
58136
}
#[must_use]
204320
pub fn extract_text_from_node(styled_dom: &StyledDom, node_id: NodeId) -> Option<String> {
204320
    match &styled_dom.node_data.as_container()[node_id].get_node_type() {
136340
        NodeType::Text(text_data) => Some(text_data.as_str().to_string()),
67980
        _ => None,
    }
204320
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use std::collections::{BTreeMap, HashMap, HashSet};
    use azul_core::{
        dom::{Dom, DomId, IdOrClass},
        selection::TextSelection,
    };
    use azul_css::props::basic::{FontRef, SizeMetric};
    use super::*;
    use crate::solver3::{
        geometry::{EdgeSizes, MarginAuto, PackedBoxProps},
        layout_tree::{generate_layout_tree, LayoutNodeCold, LayoutNodeWarm},
    };
    // ==================================================================
    // Fixtures
    // ==================================================================
    const VIEWPORT: LogicalSize = LogicalSize {
        width: 800.0,
        height: 600.0,
    };
    const BLOCK: FormattingContext = FormattingContext::Block {
        establishes_new_context: false,
    };
    fn size(w: f32, h: f32) -> LogicalSize {
        LogicalSize::new(w, h)
    }
    fn all_edges(v: f32) -> EdgeSizes {
        EdgeSizes {
            top: v,
            right: v,
            bottom: v,
            left: v,
        }
    }
    /// `BoxProps` with the same value on every edge of each ring.
    fn props(margin: f32, border: f32, padding: f32) -> BoxProps {
        BoxProps {
            margin: all_edges(margin),
            border: all_edges(border),
            padding: all_edges(padding),
            margin_auto: MarginAuto::default(),
        }
    }
    fn zero_props() -> BoxProps {
        props(0.0, 0.0, 0.0)
    }
    fn isz(min_w: f32, max_w: f32, min_h: f32, max_h: f32) -> IntrinsicSizes {
        IntrinsicSizes {
            min_content_width: min_w,
            max_content_width: max_w,
            preferred_width: None,
            min_content_height: min_h,
            max_content_height: max_h,
            preferred_height: None,
            preferred_aspect_ratio: None,
        }
    }
    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())
    }
    /// Owns everything a `LayoutContext` borrows. A font-less `FontManager`
    /// (empty `FcFontCache`) is enough for every function exercised here:
    /// text *shaping* is never reached — the DOM fixtures that go through the
    /// intrinsic-sizing pass carry no text nodes, and the text fixtures only
    /// go through `collect_inline_content`, which gathers but never measures.
    struct Env {
        styled_dom: StyledDom,
        font_manager: FontManager<FontRef>,
        text_selections: BTreeMap<DomId, TextSelection>,
        counters: HashMap<(usize, String), i32>,
        image_cache: azul_core::resources::ImageCache,
        debug_messages: Option<Vec<LayoutDebugMessage>>,
    }
    impl Env {
        fn new(styled_dom: StyledDom) -> Self {
            Self {
                styled_dom,
                font_manager: FontManager::new(FcFontCache::default())
                    .expect("FontManager over an empty font cache"),
                text_selections: BTreeMap::new(),
                counters: HashMap::new(),
                image_cache: azul_core::resources::ImageCache::default(),
                debug_messages: None,
            }
        }
        fn ctx(&mut self) -> LayoutContext<'_, FontRef> {
            LayoutContext {
                owner_colors: Default::default(),
                seat_focus_rings: Vec::new(),
                paint_selection_handles: false,
                reflowed_ifcs: BTreeSet::new(),
                style_cache: Default::default(),
                virtual_view_sizes: None,
                scrollbar_style_cache: core::cell::RefCell::new(HashMap::new()),
                styled_dom: &self.styled_dom,
                font_manager: &self.font_manager,
                text_selections: &self.text_selections,
                debug_messages: &mut self.debug_messages,
                counters: &mut self.counters,
                viewport_size: VIEWPORT,
                fragmentation_context: None,
                cursor_is_visible: true,
                cursor_locations: Vec::new(),
                preedit_text: None,
                cache_map: crate::solver3::cache::LayoutCacheMap::default(),
                image_cache: &self.image_cache,
                content_overlay: None,
                system_style: None,
                get_system_time_fn: azul_core::task::GetSystemTimeCallback {
                    cb: azul_core::task::get_system_time_libstd,
                },
            }
        }
    }
    fn hot(parent: Option<usize>, fc: FormattingContext, bp: &BoxProps) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: PackedBoxProps::pack(bp),
            dom_node_id: None,
            used_size: None,
            formatting_context: fc,
            parent,
        }
    }
    /// Hand-builds a `LayoutTree` (SoA invariants kept consistent) from hot
    /// nodes + per-node child lists. `dom_node_id` is `None` throughout, which
    /// is exactly the "anonymous box" path through the sizing code.
    fn tree_of(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()).expect("arena fits in u32");
            children_arena.extend_from_slice(cl);
            children_offsets.push((start, u32::try_from(cl.len()).expect("len fits in u32")));
        }
        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(),
        }
    }
    /// The single layout index of a DOM node (fixtures never produce splits).
    fn layout_index(tree: &LayoutTree, dom_id: NodeId) -> usize {
        tree.dom_to_layout
            .get(&dom_id)
            .and_then(|v| v.first())
            .expect("DOM node has a layout node")
            .index()
    }
    // ==================================================================
    // resolve_percentage_with_box_model  (numeric)
    // ==================================================================
    #[test]
    fn resolve_percentage_at_zero_is_zero_on_both_operands() {
        assert_eq!(
            resolve_percentage_with_box_model(0.0, 0.5, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)),
            0.0
        );
        assert_eq!(
            resolve_percentage_with_box_model(800.0, 0.0, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)),
            0.0
        );
    }
    #[test]
    fn resolve_percentage_ignores_the_box_model_arguments_entirely() {
        // Documented contract: margins/borders/paddings are accepted for
        // call-site convenience and MUST NOT influence the result (CSS 2.1
        // §10.2 — percentages resolve against the containing block itself).
        let plain =
            resolve_percentage_with_box_model(800.0, 0.5, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0));
        let poisoned = resolve_percentage_with_box_model(
            800.0,
            0.5,
            (f32::NAN, f32::INFINITY),
            (f32::MAX, f32::MIN),
            (-1e30, 1e30),
        );
        assert_eq!(plain, 400.0);
        assert_eq!(
            poisoned, 400.0,
            "box-model args must not leak into the result"
        );
    }
    #[test]
    fn resolve_percentage_floors_negative_products_at_zero() {
        // +spec:containing-block:f1344e — negative CB width yields zero.
        assert_eq!(
            resolve_percentage_with_box_model(-800.0, 0.5, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)),
            0.0
        );
        assert_eq!(
            resolve_percentage_with_box_model(800.0, -0.5, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)),
            0.0
        );
        // Two negatives multiply back to a positive — still deterministic.
        assert_eq!(
            resolve_percentage_with_box_model(-800.0, -0.5, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)),
            400.0
        );
    }
    #[test]
    fn resolve_percentage_never_returns_nan() {
        // f32::max(NaN, 0.0) == 0.0, so every NaN-producing combination
        // (NaN operand, or inf * 0 == NaN) collapses to a defined 0.0.
        for (cb, pct) in [
            (f32::NAN, 0.5),
            (800.0, f32::NAN),
            (f32::NAN, f32::NAN),
            (f32::INFINITY, 0.0),
            (f32::NEG_INFINITY, 0.0),
            (f32::NEG_INFINITY, 0.5),
        ] {
            let r = resolve_percentage_with_box_model(cb, pct, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0));
            assert!(!r.is_nan(), "NaN escaped for cb={cb}, pct={pct}");
            assert_eq!(r, 0.0, "cb={cb}, pct={pct}");
        }
    }
    #[test]
    fn resolve_percentage_saturates_to_infinity_on_overflow() {
        // f32::MAX * 100 overflows to +inf — saturation, not a panic.
        let r =
            resolve_percentage_with_box_model(f32::MAX, 100.0, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0));
        assert!(r.is_infinite() && r.is_sign_positive());
        // An infinite CB with a finite non-zero percentage stays infinite.
        let r = resolve_percentage_with_box_model(
            f32::INFINITY,
            0.5,
            (0.0, 0.0),
            (0.0, 0.0),
            (0.0, 0.0),
        );
        assert!(r.is_infinite() && r.is_sign_positive());
    }
    #[test]
    fn resolve_percentage_is_monotone_in_the_percentage() {
        let at = |p: f32| {
            resolve_percentage_with_box_model(800.0, p, (0.0, 0.0), (0.0, 0.0), (0.0, 0.0))
        };
        assert!(at(0.0) <= at(0.25) && at(0.25) <= at(0.5) && at(0.5) <= at(1.0));
        assert_eq!(at(1.0), 800.0);
    }
    // ==================================================================
    // resolve_px_with_box_model  (numeric)
    // ==================================================================
    #[test]
    fn resolve_px_absolute_length_ignores_the_containing_block() {
        let bp = props(7.0, 3.0, 11.0);
        let px = PixelValue::const_px(50);
        assert_eq!(
            resolve_px_with_box_model(&px, 800.0, &bp, true, 16.0, 16.0),
            Some(50.0)
        );
        // A wildly different containing block cannot move an absolute length.
        assert_eq!(
            resolve_px_with_box_model(&px, -1.0e30, &bp, false, 16.0, 16.0),
            Some(50.0)
        );
    }
    #[test]
    fn resolve_px_percentage_resolves_against_the_containing_block_on_either_axis() {
        let bp = props(10.0, 2.0, 5.0);
        let px = PixelValue::const_percent(50);
        let horizontal = resolve_px_with_box_model(&px, 800.0, &bp, true, 16.0, 16.0);
        let vertical = resolve_px_with_box_model(&px, 800.0, &bp, false, 16.0, 16.0);
        assert_eq!(horizontal, Some(400.0));
        // `is_horizontal` picks which box-model edges are passed down, but the
        // resolver discards them — so both axes agree for the same CB extent.
        assert_eq!(vertical, horizontal);
    }
    #[test]
    fn resolve_px_percentage_against_a_degenerate_containing_block_cannot_resolve() {
        // A non-finite containing dimension is INDEFINITE, and css-sizing-3
        // says a percentage against it cannot resolve — so the answer is None,
        // routing each caller to its own "no constraint" fallback. The old
        // contract answered Some(0.0) instead, which zeroed a percent
        // max-width under a measurement pass and crushed the box.
        let bp = zero_props();
        let px = PixelValue::const_percent(50);
        for cb in [f32::NAN, f32::NEG_INFINITY, f32::INFINITY] {
            assert_eq!(
                resolve_px_with_box_model(&px, cb, &bp, true, 16.0, 16.0),
                None,
                "cb={cb} is indefinite and must not resolve"
            );
        }
        // A negative but FINITE containing block is still definite — it
        // resolves, floored to zero.
        assert_eq!(
            resolve_px_with_box_model(&px, -800.0, &bp, true, 16.0, 16.0),
            Some(0.0)
        );
    }
    #[test]
    fn resolve_px_em_and_rem_resolve_against_the_supplied_font_sizes() {
        let bp = zero_props();
        assert_eq!(
            resolve_px_with_box_model(&PixelValue::const_em(3), 800.0, &bp, true, 20.0, 16.0),
            Some(60.0)
        );
        assert_eq!(
            resolve_px_with_box_model(
                &PixelValue::from_metric(SizeMetric::Rem, 2.0),
                800.0,
                &bp,
                true,
                20.0,
                16.0
            ),
            Some(32.0)
        );
        // A zero font-size collapses em to 0 rather than producing NaN.
        assert_eq!(
            resolve_px_with_box_model(&PixelValue::const_em(3), 800.0, &bp, true, 0.0, 0.0),
            Some(0.0)
        );
    }
    #[test]
    fn resolve_px_returns_none_for_viewport_units() {
        // Viewport units are neither absolute (no viewport is threaded in here)
        // nor percentages, so this resolver reports "cannot resolve". Every
        // caller (`apply_width_constraints`, `apply_height_constraints`,
        // `apply_constraint_violation_table`) turns that into the *default*
        // (0 / none), i.e. a `min-width: 10vw` constraint is silently dropped.
        let bp = zero_props();
        for metric in [
            SizeMetric::Vw,
            SizeMetric::Vh,
            SizeMetric::Vmin,
            SizeMetric::Vmax,
        ] {
            let px = PixelValue::from_metric(metric, 10.0);
            assert_eq!(
                resolve_px_with_box_model(&px, 800.0, &bp, true, 16.0, 16.0),
                None,
                "{metric:?} unexpectedly resolved"
            );
        }
    }
    #[test]
    fn resolve_px_extreme_lengths_stay_finite() {
        // `PixelValue` stores its number as a fixed-point isize, so f32
        // extremes are clamped at construction — nothing infinite or NaN can
        // reach the sizing math through a `PixelValue`.
        let bp = zero_props();
        for raw in [
            f32::MAX,
            f32::MIN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::NAN,
        ] {
            let px = PixelValue::px(raw);
            let r = resolve_px_with_box_model(&px, 800.0, &bp, true, 16.0, 16.0)
                .expect("px metric always resolves to Some");
            assert!(
                r.is_finite(),
                "non-finite length from PixelValue::px({raw})"
            );
        }
        assert_eq!(
            resolve_px_with_box_model(&PixelValue::px(f32::NAN), 800.0, &bp, true, 16.0, 16.0),
            Some(0.0),
            "NaN saturates to 0 in the fixed-point encoding"
        );
    }
    // ==================================================================
    // auto_block_inline_size  (numeric)
    // ==================================================================
    #[test]
    fn auto_block_inline_size_subtracts_the_full_horizontal_box_model() {
        let cb = size(800.0, 600.0);
        // margin 10 + border 2 + padding 5, on both sides = 34 total.
        assert_eq!(auto_block_inline_size(&cb, &props(10.0, 2.0, 5.0)), 766.0);
        assert_eq!(auto_block_inline_size(&cb, &zero_props()), 800.0);
    }
    #[test]
    fn auto_block_inline_size_floors_at_zero_when_the_box_model_exceeds_the_cb() {
        let cb = size(10.0, 600.0);
        assert_eq!(auto_block_inline_size(&cb, &props(100.0, 50.0, 25.0)), 0.0);
        // A zero-width containing block is exactly the boundary case.
        assert_eq!(auto_block_inline_size(&size(0.0, 0.0), &zero_props()), 0.0);
        // A negative containing block never yields a negative inline size.
        assert_eq!(
            auto_block_inline_size(&size(-800.0, 0.0), &zero_props()),
            0.0
        );
    }
    #[test]
    fn auto_block_inline_size_never_returns_nan() {
        let cases = [
            (size(f32::NAN, 0.0), zero_props()),
            (size(f32::INFINITY, 0.0), props(f32::INFINITY, 0.0, 0.0)),
            (size(f32::NEG_INFINITY, 0.0), zero_props()),
            (size(0.0, 0.0), props(f32::NAN, 0.0, 0.0)),
        ];
        for (cb, bp) in cases {
            let r = auto_block_inline_size(&cb, &bp);
            assert!(!r.is_nan(), "NaN escaped for cb.width={}", cb.width);
            assert_eq!(r, 0.0);
        }
    }
    #[test]
    fn an_auto_width_answers_each_constraint_kind_with_its_own_contribution() {
        // Definite stretches; a MIN-content pass gets the min-content
        // contribution and a MAX-content pass the max-content one. The
        // pre-typed helper could only say "not finite" and answered
        // max-content for both — wrong for every min-content measurement.
        let bp = props(10.0, 2.0, 5.0);
        assert_eq!(
            auto_inline_size_for(Text3AvailableSpace::Definite(800.0), &bp, 120.0, 420.0),
            766.0,
            "800 - (10+2+5)*2, exactly as the untyped stretch-fit did"
        );
        assert_eq!(
            auto_inline_size_for(Text3AvailableSpace::MinContent, &bp, 120.0, 420.0),
            120.0,
        );
        assert_eq!(
            auto_inline_size_for(Text3AvailableSpace::MaxContent, &bp, 120.0, 420.0),
            420.0,
        );
    }
    #[test]
    fn auto_inline_size_is_finite_for_every_constraint_and_intrinsic() {
        // Including unmeasured (NaN/negative) intrinsics — a zero-width box is
        // recoverable, a non-finite one poisons the display list, the clip and
        // the scroll clamp.
        let kinds = [
            Text3AvailableSpace::Definite(800.0),
            Text3AvailableSpace::Definite(-800.0),
            Text3AvailableSpace::MinContent,
            Text3AvailableSpace::MaxContent,
        ];
        for cbw in kinds {
            for c in [420.0, 0.0, -1.0, f32::NAN] {
                let r = auto_inline_size_for(cbw, &props(1.0, 1.0, 1.0), c, c);
                assert!(r.is_finite(), "{cbw:?} content={c} produced {r}");
                assert!(r >= 0.0, "{cbw:?} content={c} produced {r}");
            }
        }
    }
    #[test]
    fn shrink_to_fit_available_width_clamps_to_the_right_contribution() {
        // min(max(pref_min, available), preferred): 0 under min-content pins
        // the minimum, MAX under max-content pins the preferred — and the MAX
        // can never escape because every caller clamps with `.min(preferred)`.
        let bp = props(10.0, 2.0, 5.0);
        assert_eq!(
            shrink_to_fit_available_width(Text3AvailableSpace::Definite(800.0), &bp),
            766.0
        );
        assert_eq!(
            shrink_to_fit_available_width(Text3AvailableSpace::MinContent, &bp),
            0.0
        );
        assert_eq!(
            shrink_to_fit_available_width(Text3AvailableSpace::MaxContent, &bp),
            f32::MAX
        );
    }
    #[test]
    fn auto_block_inline_size_saturates_rather_than_overflowing() {
        // f32::MAX minus finite edges stays finite; +inf CB stays +inf.
        let r = auto_block_inline_size(&size(f32::MAX, 0.0), &props(1.0, 1.0, 1.0));
        assert!(r.is_finite() && r > 0.0);
        let r = auto_block_inline_size(&size(f32::INFINITY, 0.0), &props(1.0, 1.0, 1.0));
        assert!(r.is_infinite() && r.is_sign_positive());
    }
    // ==================================================================
    // compute_dirty_ancestor_closure  (other)
    // ==================================================================
    /// 0 → 1 → 2 (2's parent is 1, 1's parent is 0).
    fn chain_tree() -> LayoutTree {
        let bp = zero_props();
        tree_of(
            vec![
                hot(None, BLOCK, &bp),
                hot(Some(0), BLOCK, &bp),
                hot(Some(1), BLOCK, &bp),
            ],
            &[vec![1], vec![2], vec![]],
        )
    }
    #[test]
    fn dirty_closure_of_an_empty_set_is_empty() {
        let tree = chain_tree();
        let closure = compute_dirty_ancestor_closure(&tree, &BTreeSet::new());
        assert!(closure.is_empty());
    }
    #[test]
    fn dirty_closure_of_a_leaf_contains_every_ancestor_up_to_the_root() {
        let tree = chain_tree();
        let dirty: BTreeSet<usize> = [2].into_iter().collect();
        let closure = compute_dirty_ancestor_closure(&tree, &dirty);
        assert_eq!(closure, [0, 1, 2].into_iter().collect::<HashSet<usize>>());
    }
    #[test]
    fn dirty_closure_tolerates_out_of_range_dirty_indices() {
        let tree = chain_tree();
        let dirty: BTreeSet<usize> = [usize::MAX, 999, 2].into_iter().collect();
        let closure = compute_dirty_ancestor_closure(&tree, &dirty);
        // The bogus ids are inserted (they have no parent to walk), the real
        // one still drags in its ancestors. No panic, no index arithmetic.
        assert!(closure.contains(&usize::MAX) && closure.contains(&999));
        assert!(closure.contains(&0) && closure.contains(&1) && closure.contains(&2));
    }
    #[test]
    fn dirty_closure_terminates_on_a_cyclic_parent_chain() {
        // A malformed tree (0's parent is 1, 1's parent is 0) must not spin
        // forever: the `insert` returning false breaks the walk.
        let bp = zero_props();
        let tree = tree_of(
            vec![hot(Some(1), BLOCK, &bp), hot(Some(0), BLOCK, &bp)],
            &[vec![], vec![]],
        );
        let dirty: BTreeSet<usize> = [0].into_iter().collect();
        let closure = compute_dirty_ancestor_closure(&tree, &dirty);
        assert_eq!(closure, [0, 1].into_iter().collect::<HashSet<usize>>());
    }
    #[test]
    fn dirty_closure_terminates_on_a_self_parenting_node() {
        let bp = zero_props();
        let tree = tree_of(vec![hot(Some(0), BLOCK, &bp)], &[vec![]]);
        let dirty: BTreeSet<usize> = [0].into_iter().collect();
        let closure = compute_dirty_ancestor_closure(&tree, &dirty);
        assert_eq!(closure, [0].into_iter().collect::<HashSet<usize>>());
    }
    // ==================================================================
    // IntrinsicSizeCalculator::new  (constructor)
    // ==================================================================
    #[test]
    fn intrinsic_size_calculator_new_starts_without_a_dirty_closure() {
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        assert!(
            calc.dirty_closure.is_none(),
            "a fresh calculator must not skip any node"
        );
        assert_eq!(calc.ctx.viewport_size, VIEWPORT, "ctx is threaded through");
    }
    // ==================================================================
    // calculate_intrinsic_recursive / calculate_node_intrinsic_sizes
    // ==================================================================
    #[test]
    fn calculate_intrinsic_recursive_rejects_an_out_of_range_node_index() {
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let mut tree = chain_tree();
        for bogus in [3, 999, usize::MAX] {
            let r = calc.calculate_intrinsic_recursive(&mut tree, bogus, false);
            assert!(
                matches!(r, Err(LayoutError::InvalidTree)),
                "index {bogus} must be rejected, not panic"
            );
        }
    }
    #[test]
    fn calculate_node_intrinsic_sizes_rejects_an_out_of_range_node_index() {
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let tree = chain_tree();
        let r = calc.calculate_node_intrinsic_sizes(&tree, usize::MAX, &[]);
        assert!(matches!(r, Err(LayoutError::InvalidTree)));
    }
    #[test]
    fn calculate_intrinsic_recursive_skips_stray_child_indices_instead_of_aborting() {
        // Reconcile can mis-list a child index that has no node (the g52 case).
        // The whole pass must survive it, not abort with InvalidTree.
        let bp = zero_props();
        let mut tree = tree_of(
            vec![hot(None, BLOCK, &bp), hot(Some(0), BLOCK, &bp)],
            &[vec![1, 4242], vec![]],
        );
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let r = calc.calculate_intrinsic_recursive(&mut tree, 0, false);
        let sizes = r.expect("a stray child index must be skipped, not fatal");
        assert!(sizes.min_content_width.is_finite());
        assert!(tree
            .warm(LayoutNodeId::new(0))
            .and_then(|w| w.intrinsic_sizes)
            .is_some());
    }
    #[test]
    fn calculate_intrinsic_recursive_reuses_the_cache_for_nodes_outside_the_dirty_closure() {
        let mut tree = chain_tree();
        let cached = isz(11.0, 22.0, 33.0, 44.0);
        tree.warm_mut(LayoutNodeId::new(0))
            .expect("root warm slot")
            .intrinsic_sizes = Some(cached);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        // An empty closure means "nothing is dirty" — the cached value wins
        // and the descent is skipped entirely.
        calc.dirty_closure = Some(HashSet::new());
        let sizes = calc
            .calculate_intrinsic_recursive(&mut tree, 0, false)
            .expect("cached path");
        assert_eq!(sizes.min_content_width, 11.0);
        assert_eq!(sizes.max_content_width, 22.0);
        assert_eq!(sizes.min_content_height, 33.0);
        assert_eq!(sizes.max_content_height, 44.0);
        // Children were never visited, so their warm slots stay empty.
        assert!(tree
            .warm(LayoutNodeId::new(1))
            .and_then(|w| w.intrinsic_sizes)
            .is_none());
    }
    // ==================================================================
    // calculate_block_intrinsic_sizes  (numeric)
    // ==================================================================
    /// root(0) with `n` block children, no box-model extras.
    fn block_parent_with_children(n: usize) -> LayoutTree {
        parent_with_children(BLOCK, n)
    }
    /// root(0) establishing `fc`, with `n` childless block children.
    fn parent_with_children(fc: FormattingContext, n: usize) -> LayoutTree {
        let bp = zero_props();
        let mut nodes = vec![hot(None, fc, &bp)];
        let mut kids = Vec::new();
        for i in 0..n {
            nodes.push(hot(Some(0), BLOCK, &bp));
            kids.push(i + 1);
        }
        let mut child_lists = vec![kids];
        child_lists.resize(n + 1, Vec::new());
        tree_of(nodes, &child_lists)
    }
    #[test]
    fn block_intrinsic_sizes_take_the_max_width_and_the_sum_of_heights() {
        let tree = block_parent_with_children(2);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let children = [
            (1usize, isz(10.0, 20.0, 5.0, 6.0)),
            (2usize, isz(30.0, 40.0, 7.0, 8.0)),
        ];
        let r = calc
            .calculate_block_intrinsic_sizes(&tree, 0, &children)
            .expect("valid tree");
        assert_eq!(r.min_content_width, 30.0, "cross axis = widest child");
        assert_eq!(r.max_content_width, 40.0);
        assert_eq!(r.min_content_height, 14.0, "main axis = stacked heights");
        assert_eq!(r.max_content_height, 14.0);
    }
    #[test]
    fn block_intrinsic_sizes_ignore_children_missing_from_the_intrinsics_slice() {
        let tree = block_parent_with_children(2);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let r = calc
            .calculate_block_intrinsic_sizes(&tree, 0, &[])
            .expect("valid tree");
        assert_eq!(r.min_content_width, 0.0);
        assert_eq!(r.max_content_width, 0.0);
        assert_eq!(r.min_content_height, 0.0);
        assert_eq!(r.max_content_height, 0.0);
    }
    #[test]
    fn block_intrinsic_sizes_saturate_to_infinity_instead_of_overflowing() {
        let tree = block_parent_with_children(2);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let huge = isz(f32::MAX, f32::MAX, f32::MAX, f32::MAX);
        let children = [(1usize, huge), (2usize, huge)];
        let r = calc
            .calculate_block_intrinsic_sizes(&tree, 0, &children)
            .expect("valid tree");
        // MAX + MAX overflows the f32 range: +inf, not a wrap, not a panic.
        assert!(r.min_content_height.is_infinite() && r.min_content_height.is_sign_positive());
        assert_eq!(r.max_content_width, f32::MAX, "cross axis only takes a max");
    }
    #[test]
    fn block_intrinsic_sizes_sanitize_nan_on_the_cross_axis() {
        let tree = block_parent_with_children(1);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let nan = isz(f32::NAN, f32::NAN, f32::NAN, f32::NAN);
        let r = calc
            .calculate_block_intrinsic_sizes(&tree, 0, &[(1usize, nan)])
            .expect("valid tree");
        // The cross axis goes through `f32::max`, which drops NaN — so a NaN
        // child cannot poison the parent's width. The main axis is a plain
        // sum, so it does carry the NaN through (unreachable in practice:
        // every measured/fallback intrinsic is finite).
        assert!(!r.min_content_width.is_nan() && r.min_content_width == 0.0);
        assert!(!r.max_content_width.is_nan() && r.max_content_width == 0.0);
        assert!(r.min_content_height.is_nan());
    }
    #[test]
    fn block_intrinsic_sizes_reject_an_out_of_range_node_index() {
        let tree = block_parent_with_children(1);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let r = calc.calculate_block_intrinsic_sizes(&tree, usize::MAX, &[]);
        assert!(matches!(r, Err(LayoutError::InvalidTree)));
    }
    // ==================================================================
    // calculate_flex_intrinsic_sizes  (numeric)
    // ==================================================================
    fn flex_parent_with_children(n: usize) -> LayoutTree {
        parent_with_children(FormattingContext::Flex, n)
    }
    #[test]
    fn flex_row_intrinsic_sizes_sum_the_main_axis_and_max_the_cross_axis() {
        let tree = flex_parent_with_children(2);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let children = [
            (1usize, isz(10.0, 20.0, 5.0, 6.0)),
            (2usize, isz(30.0, 40.0, 7.0, 8.0)),
        ];
        let r = calc
            .calculate_flex_intrinsic_sizes(&tree, 0, &children)
            .expect("valid tree");
        // No DOM node → default flex-direction: row, default flex-wrap: nowrap
        // → single line → min-content main = SUM of item min-contents.
        assert_eq!(r.min_content_width, 40.0);
        assert_eq!(r.max_content_width, 60.0);
        assert_eq!(r.min_content_height, 7.0);
        assert_eq!(r.max_content_height, 8.0);
    }
    #[test]
    fn flex_intrinsic_sizes_are_zero_when_no_child_intrinsics_are_supplied() {
        let tree = flex_parent_with_children(3);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let r = calc
            .calculate_flex_intrinsic_sizes(&tree, 0, &[])
            .expect("valid tree");
        assert_eq!(r.min_content_width, 0.0);
        assert_eq!(r.max_content_width, 0.0);
        assert_eq!(r.min_content_height, 0.0);
        assert_eq!(r.max_content_height, 0.0);
    }
    #[test]
    fn flex_intrinsic_sizes_saturate_on_a_summing_overflow() {
        let tree = flex_parent_with_children(2);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let huge = isz(f32::MAX, f32::MAX, 1.0, 2.0);
        let children = [(1usize, huge), (2usize, huge)];
        let r = calc
            .calculate_flex_intrinsic_sizes(&tree, 0, &children)
            .expect("valid tree");
        assert!(r.min_content_width.is_infinite() && r.min_content_width.is_sign_positive());
        assert!(r.max_content_width.is_infinite() && r.max_content_width.is_sign_positive());
        // The cross axis only takes maxima, so it stays finite.
        assert_eq!(r.max_content_height, 2.0);
    }
    #[test]
    fn flex_intrinsic_sizes_reject_an_out_of_range_node_index() {
        let tree = flex_parent_with_children(1);
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let r = calc.calculate_flex_intrinsic_sizes(&tree, usize::MAX, &[]);
        assert!(matches!(r, Err(LayoutError::InvalidTree)));
    }
    // ==================================================================
    // calculate_table_intrinsic_sizes  (numeric)
    // ==================================================================
    /// table(0) > row(1) > [cell(2), cell(3)]
    fn table_tree() -> LayoutTree {
        let bp = zero_props();
        tree_of(
            vec![
                hot(None, FormattingContext::Table, &bp),
                hot(Some(0), FormattingContext::TableRow, &bp),
                hot(Some(1), FormattingContext::TableCell, &bp),
                hot(Some(1), FormattingContext::TableCell, &bp),
            ],
            &[vec![1], vec![2, 3], vec![], vec![]],
        )
    }
    #[test]
    fn table_intrinsic_sizes_sum_columns_and_stack_row_heights() {
        let tree = table_tree();
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        // Cell intrinsics keyed by the *cell* indices (the aggregation path).
        let cells = [
            (2usize, isz(30.0, 50.0, 10.0, 20.0)),
            (3usize, isz(40.0, 60.0, 10.0, 15.0)),
        ];
        let r = calc.calculate_table_intrinsic_sizes(&tree, 0, &cells);
        assert_eq!(r.min_content_width, 70.0, "sum of per-column minima");
        assert_eq!(r.max_content_width, 110.0, "sum of per-column maxima");
        assert_eq!(r.min_content_height, 20.0, "row height = tallest cell");
        assert_eq!(r.max_content_height, 20.0);
    }
    #[test]
    fn table_intrinsic_sizes_are_zero_when_cells_carry_no_measurable_content() {
        // The real caller passes the table's *direct* children (rows), so cell
        // lookups miss and each cell is re-measured through the IFC path. With
        // anonymous (DOM-less) cells there is nothing to measure → all zeros.
        let tree = table_tree();
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let rows = [(1usize, isz(1.0, 2.0, 3.0, 4.0))];
        let r = calc.calculate_table_intrinsic_sizes(&tree, 0, &rows);
        assert_eq!(r.min_content_width, 0.0);
        assert_eq!(r.max_content_width, 0.0);
        assert_eq!(r.max_content_height, 0.0);
    }
    #[test]
    fn table_intrinsic_sizes_of_a_table_without_rows_are_zero() {
        // A `FormattingContext::Table` whose children are neither rows nor row
        // groups must not panic — it simply aggregates nothing.
        let bp = zero_props();
        let tree = tree_of(
            vec![
                hot(None, FormattingContext::Table, &bp),
                hot(Some(0), BLOCK, &bp),
            ],
            &[vec![1], vec![]],
        );
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let r =
            calc.calculate_table_intrinsic_sizes(&tree, 0, &[(1usize, isz(9.0, 9.0, 9.0, 9.0))]);
        assert_eq!(r.min_content_width, 0.0);
        assert_eq!(r.max_content_width, 0.0);
        assert_eq!(r.min_content_height, 0.0);
    }
    #[test]
    fn table_intrinsic_sizes_saturate_on_extreme_cell_widths() {
        let tree = table_tree();
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        let huge = isz(f32::MAX, f32::MAX, 1.0, 1.0);
        let cells = [(2usize, huge), (3usize, huge)];
        let r = calc.calculate_table_intrinsic_sizes(&tree, 0, &cells);
        assert!(r.min_content_width.is_infinite() && r.min_content_width.is_sign_positive());
        assert!(r.max_content_width.is_infinite() && r.max_content_width.is_sign_positive());
        assert_eq!(r.max_content_height, 1.0);
    }
    #[test]
    fn table_intrinsic_sizes_with_an_out_of_range_index_are_zero() {
        let tree = table_tree();
        let mut env = Env::new(styled(Dom::create_body(), ""));
        let mut ctx = env.ctx();
        let mut text_cache = LayoutCache::new();
        let mut calc = IntrinsicSizeCalculator::new(&mut ctx, &mut text_cache);
        // `tree.children(usize::MAX)` must yield an empty slice, not panic.
        let r = calc.calculate_table_intrinsic_sizes(&tree, usize::MAX, &[]);
        assert_eq!(r.min_content_width, 0.0);
        assert_eq!(r.max_content_height, 0.0);
    }
    // ==================================================================
    // calculate_intrinsic_sizes (phase 2a entry point)
    // ==================================================================
    /// `body(0) > .flex(1) > .a(2)` — deliberately text-free, so the whole
    /// intrinsic pass runs without ever entering text shaping. `.flex` is a
    /// shrink-to-fit context, so Fix C does not short-circuit the subtree.
    fn flex_dom() -> StyledDom {
        styled(
            Dom::create_body().with_child(div_class("flex").with_child(div_class("a"))),
            ".flex { display: flex; } .a { display: block; min-width: 120px; min-height: 30px; }",
        )
    }
    #[test]
    fn calculate_intrinsic_sizes_is_a_no_op_when_nothing_is_dirty() {
        let mut env = Env::new(flex_dom());
        let mut ctx = env.ctx();
        let mut tree = generate_layout_tree(&mut ctx).expect("layout tree");
        let mut text_cache = LayoutCache::new();
        calculate_intrinsic_sizes(&mut ctx, &mut tree, &mut text_cache, &BTreeSet::new())
            .expect("empty dirty set returns early");
        assert!(
            tree.warm.iter().all(|w| w.intrinsic_sizes.is_none()),
            "an empty dirty set must not compute anything"
        );
    }
    #[test]
    fn calculate_intrinsic_sizes_applies_the_min_width_floor_bottom_up() {
        let mut env = Env::new(flex_dom());
        let mut ctx = env.ctx();
        let mut tree = generate_layout_tree(&mut ctx).expect("layout tree");
        let mut text_cache = LayoutCache::new();
        let dirty: BTreeSet<usize> = (0..tree.nodes.len()).collect();
        calculate_intrinsic_sizes(&mut ctx, &mut tree, &mut text_cache, &dirty).expect("sizing");
        // `.a` is an empty block: its content intrinsic is 0, but `min-width`
        // / `min-height` are <length>s, so they floor both min- and
        // max-content (+spec:min-max-sizing:970fef).
        let a = layout_index(&tree, NodeId::new(2));
        let a_sizes = tree
            .warm(LayoutNodeId::new(a))
            .and_then(|w| w.intrinsic_sizes)
            .expect("`.a` was measured");
        assert_eq!(a_sizes.min_content_width, 120.0);
        assert_eq!(a_sizes.max_content_width, 120.0);
        assert_eq!(a_sizes.min_content_height, 30.0);
        assert_eq!(a_sizes.max_content_height, 30.0);
        // The flex container aggregates its single item on both axes.
        let f = layout_index(&tree, NodeId::new(1));
        let f_sizes = tree
            .warm(LayoutNodeId::new(f))
            .and_then(|w| w.intrinsic_sizes)
            .expect("`.flex` was measured");
        assert_eq!(f_sizes.min_content_width, 120.0);
        assert_eq!(f_sizes.max_content_width, 120.0);
        assert_eq!(f_sizes.max_content_height, 30.0);
    }
    #[test]
    fn calculate_intrinsic_sizes_tolerates_bogus_dirty_node_indices() {
        let mut env = Env::new(flex_dom());
        let mut ctx = env.ctx();
        let mut tree = generate_layout_tree(&mut ctx).expect("layout tree");
        let mut text_cache = LayoutCache::new();
        // Dirty ids that no longer exist (a stale dirty set after a DOM shrink)
        // must not index out of bounds nor abort the pass.
        let dirty: BTreeSet<usize> = [0, 999, usize::MAX].into_iter().collect();
        calculate_intrinsic_sizes(&mut ctx, &mut tree, &mut text_cache, &dirty)
            .expect("stale dirty ids must be ignored, not fatal");
        let root = tree
            .warm(LayoutNodeId::new(tree.root))
            .and_then(|w| w.intrinsic_sizes);
        assert!(root.is_some(), "the root is still measured");
    }
    #[test]
    fn calculate_intrinsic_sizes_is_idempotent_across_repeated_passes() {
        let mut env = Env::new(flex_dom());
        let mut ctx = env.ctx();
        let mut tree = generate_layout_tree(&mut ctx).expect("layout tree");
        let mut text_cache = LayoutCache::new();
        let dirty: BTreeSet<usize> = (0..tree.nodes.len()).collect();
        calculate_intrinsic_sizes(&mut ctx, &mut tree, &mut text_cache, &dirty).expect("pass 1");
        let a = layout_index(&tree, NodeId::new(2));
        let first = tree
            .warm(LayoutNodeId::new(a))
            .and_then(|w| w.intrinsic_sizes)
            .expect("measured");
        calculate_intrinsic_sizes(&mut ctx, &mut tree, &mut text_cache, &dirty).expect("pass 2");
        let second = tree
            .warm(LayoutNodeId::new(a))
            .and_then(|w| w.intrinsic_sizes)
            .expect("measured");
        assert_eq!(first.min_content_width, second.min_content_width);
        assert_eq!(first.max_content_width, second.max_content_width);
        assert_eq!(first.min_content_height, second.min_content_height);
        assert_eq!(first.max_content_height, second.max_content_height);
    }
    // ==================================================================
    // collect_inline_content / collect_inline_content_recursive
    // ==================================================================
    fn text_dom(text: &str) -> StyledDom {
        styled(
            Dom::create_body().with_child(div_class("p").with_child(
                Dom::create_text_do_not_use_without_block_level_wrapper(text),
            )),
            ".p { display: block; }",
        )
    }
    fn collected_text(items: &[InlineContent]) -> String {
        items
            .iter()
            .filter_map(|item| match item {
                InlineContent::Text(run) => Some(String::from(&*run.text)),
                _ => None,
            })
            .collect()
    }
    /// The layout node the IFC sizer measures the text through: the text node's
    /// own layout node when reconcile produced one, otherwise the enclosing
    /// block (whose DOM-children scan then picks the text up). Both routes must
    /// surface the same characters — which is exactly the invariant under test.
    fn text_ifc_index(tree: &LayoutTree, text_dom: NodeId, block_dom: NodeId) -> usize {
        tree.dom_to_layout
            .get(&text_dom)
            .and_then(|v| v.first())
            .copied()
            .unwrap_or_else(|| LayoutNodeId::new(layout_index(tree, block_dom)))
            .index()
    }
    #[test]
    fn collect_inline_content_gathers_the_text_of_an_ifc_root() {
        let mut env = Env::new(text_dom("hello world"));
        let mut ctx = env.ctx();
        let tree = generate_layout_tree(&mut ctx).expect("layout tree");
        let idx = text_ifc_index(&tree, NodeId::new(2), NodeId::new(1));
        let items = collect_inline_content(&mut ctx, &tree, idx).expect("collect");
        assert!(!items.is_empty(), "the IFC root must see its text");
        assert!(collected_text(&items).contains("hello"));
    }
    #[test]
    fn collect_inline_content_preserves_unicode_verbatim() {
        // Combining marks, an RTL run, an emoji ZWJ sequence — none of this may
        // be truncated, re-encoded, or split mid-scalar.
        let needle = "e\u{301}llo مرحبا 👨\u{200d}👩\u{200d}👧";
        let mut env = Env::new(text_dom(needle));
        let mut ctx = env.ctx();
        let tree = generate_layout_tree(&mut ctx).expect("layout tree");
        let idx = text_ifc_index(&tree, NodeId::new(2), NodeId::new(1));
        let items = collect_inline_content(&mut ctx, &tree, idx).expect("collect");
        let text = collected_text(&items);
        assert!(text.contains('\u{301}'), "combining acute survived");
        assert!(text.contains("مرحبا"), "RTL run survived");
        assert!(
            text.contains("👨\u{200d}👩\u{200d}👧"),
            "ZWJ sequence survived"
        );
    }
    #[test]
    fn collect_inline_content_handles_whitespace_only_and_very_long_text() {
        for text in [" \n\t".to_string(), "x".repeat(20_000)] {
            let mut env = Env::new(text_dom(&text));
            let mut ctx = env.ctx();
            let tree = generate_layout_tree(&mut ctx).expect("layout tree");
            let idx = text_ifc_index(&tree, NodeId::new(2), NodeId::new(1));
            let items = collect_inline_content(&mut ctx, &tree, idx)
                .expect("degenerate text must still collect");
            // The DOM-children scan and the layout-children walk must not BOTH
            // pick the run up (that double-count made inline-blocks 2× too wide).
            assert!(
                collected_text(&items).len() <= text.len(),
                "the same text run was collected more than once"
            );
        }
    }
    #[test]
    fn collect_inline_content_rejects_an_out_of_range_root_index() {
        let mut env = Env::new(text_dom("hello"));
        let mut ctx = env.ctx();
        let tree = generate_layout_tree(&mut ctx).expect("layout tree");
        for bogus in [tree.nodes.len(), 999, usize::MAX] {
            let r = collect_inline_content(&mut ctx, &tree, bogus);
            assert!(
                matches!(r, Err(LayoutError::InvalidTree)),
                "index {bogus} must be rejected, not panic"
            );
        }
    }
    #[test]
    fn collect_inline_content_of_a_text_free_subtree_is_empty() {
        let mut env = Env::new(flex_dom());
        let mut ctx = env.ctx();
        let tree = generate_layout_tree(&mut ctx).expect("layout tree");
        let a = layout_index(&tree, NodeId::new(2));
        let items = collect_inline_content(&mut ctx, &tree, a).expect("collect");
        assert!(
            collected_text(&items).is_empty(),
            "a childless block has no inline text"
        );
    }
    // ==================================================================
    // subtree_contains_text  (other)
    // ==================================================================
    #[test]
    fn subtree_contains_text_sees_the_node_itself_and_its_descendants() {
        let dom = text_dom("hi");
        // body(0) > .p(1) > text(2)
        assert!(
            subtree_contains_text(&dom, NodeId::new(2)),
            "the text node itself"
        );
        assert!(subtree_contains_text(&dom, NodeId::new(1)), "its parent");
        assert!(subtree_contains_text(&dom, NodeId::new(0)), "the root");
    }
    #[test]
    fn subtree_contains_text_is_false_for_a_text_free_subtree() {
        let dom = styled(
            Dom::create_body().with_child(div_class("a").with_child(div_class("b"))),
            "",
        );
        assert!(!subtree_contains_text(&dom, NodeId::new(0)));
        assert!(!subtree_contains_text(&dom, NodeId::new(1)));
        assert!(!subtree_contains_text(&dom, NodeId::new(2)));
    }
    #[test]
    fn subtree_contains_text_walks_a_deeply_nested_subtree() {
        // The recursion is unbounded in depth — 200 levels must not blow up.
        const DEPTH: usize = 200;
        let mut inner = Dom::create_div().with_child(
            Dom::create_text_do_not_use_without_block_level_wrapper("deep"),
        );
        for _ in 0..DEPTH {
            inner = Dom::create_div().with_child(inner);
        }
        let dom = styled(Dom::create_body().with_child(inner), "");
        assert!(subtree_contains_text(&dom, NodeId::new(0)));
        let mut empty = Dom::create_div();
        for _ in 0..DEPTH {
            empty = Dom::create_div().with_child(empty);
        }
        let dom = styled(Dom::create_body().with_child(empty), "");
        assert!(!subtree_contains_text(&dom, NodeId::new(0)));
    }
    // ==================================================================
    // extract_text_from_node  (other)
    // ==================================================================
    #[test]
    fn extract_text_from_node_round_trips_the_exact_string() {
        for needle in [
            "hello world",
            " \n\t",
            "e\u{301}llo مرحبا 👨\u{200d}👩\u{200d}👧",
            "line1\nline2\r\n\u{0}nul",
        ] {
            let dom = text_dom(needle);
            assert_eq!(
                extract_text_from_node(&dom, NodeId::new(2)).as_deref(),
                Some(needle),
                "text must survive the DOM round-trip byte for byte"
            );
        }
    }
    #[test]
    fn extract_text_from_node_is_none_for_non_text_nodes() {
        let dom = text_dom("hello");
        assert_eq!(extract_text_from_node(&dom, NodeId::new(0)), None, "body");
        assert_eq!(extract_text_from_node(&dom, NodeId::new(1)), None, "div");
    }
    #[test]
    fn extract_text_from_node_handles_a_very_long_string() {
        let long = "ü".repeat(50_000);
        let dom = text_dom(&long);
        let got = extract_text_from_node(&dom, NodeId::new(2)).expect("text node");
        assert_eq!(got.chars().count(), 50_000);
        assert_eq!(got, long);
    }
    // ==================================================================
    // calculate_used_size_for_node  (numeric)
    // ==================================================================
    /// One classed div per constraint case; DOM ids follow pre-order.
    ///  body(0), .plain(1), .pct(2), .clamped(3), .maxed(4), .pctmin(5),
    ///  .bbox(6), .autoblock(7), .vwmin(8), .em(9), .hclamped(10), .row10(11)
    fn constraints_dom() -> StyledDom {
        styled(
            Dom::create_body()
                .with_child(div_class("plain"))
                .with_child(div_class("pct"))
                .with_child(div_class("clamped"))
                .with_child(div_class("maxed"))
                .with_child(div_class("pctmin"))
                .with_child(div_class("bbox"))
                .with_child(div_class("autoblock"))
                .with_child(div_class("vwmin"))
                .with_child(div_class("em"))
                .with_child(div_class("hclamped"))
                .with_child(div_class("row10")),
            "
            .plain     { display: block; width: 50px; height: 20px; }
            .pct       { display: block; width: 50%; height: 25%; }
            .clamped   { display: block; width: 300px; min-width: 200px; max-width: 100px; }
            .maxed     { display: block; width: 300px; max-width: 100px; }
            .pctmin    { display: block; min-width: 50%; }
            .bbox      { display: block; width: 5px; height: 5px; box-sizing: border-box; }
            .autoblock { display: block; }
            .vwmin     { display: block; width: 300px; min-width: 10vw; }
            .em        { display: block; font-size: 20px; min-width: 3em; }
            .hclamped  { display: block; height: 300px; min-height: 200px; max-height: 100px; }
            .row10     { display: block; min-width: 200px; max-height: 50px; }
            ",
        )
    }
    const PLAIN: NodeId = NodeId::new(1);
    const PCT: NodeId = NodeId::new(2);
    const CLAMPED: NodeId = NodeId::new(3);
    const MAXED: NodeId = NodeId::new(4);
    const PCTMIN: NodeId = NodeId::new(5);
    const BBOX: NodeId = NodeId::new(6);
    const AUTOBLOCK: NodeId = NodeId::new(7);
    const VWMIN: NodeId = NodeId::new(8);
    const EM: NodeId = NodeId::new(9);
    const HCLAMPED: NodeId = NodeId::new(10);
    const ROW10: NodeId = NodeId::new(11);
    fn node_state(dom: &StyledDom, id: NodeId) -> StyledNodeState {
        dom.styled_nodes.as_container()[id].styled_node_state
    }
    fn used_size(dom: &StyledDom, id: NodeId, cb: LogicalSize, bp: &BoxProps) -> LogicalSize {
        // Legacy-shaped entry: adopt the flattened size the way migration call
        // sites do (non-finite axis -> max-content).
        let cb = crate::solver3::geometry::ContainingBlock::from_flattened(cb);
        calculate_used_size_for_node(dom, Some(id), &cb, IntrinsicSizes::default(), bp, &VIEWPORT)
            .expect("used size")
    }
    fn used_size_typed(
        dom: &StyledDom,
        id: NodeId,
        cb: crate::solver3::geometry::ContainingBlock,
        bp: &BoxProps,
    ) -> LogicalSize {
        calculate_used_size_for_node(dom, Some(id), &cb, IntrinsicSizes::default(), bp, &VIEWPORT)
            .expect("used size")
    }
    #[test]
    fn used_size_of_an_anonymous_box_fills_the_cb_inline_and_uses_content_height() {
        let dom = constraints_dom();
        let cb = size(800.0, 600.0);
        let bp = zero_props();
        let tcb = crate::solver3::geometry::ContainingBlock::from_flattened(cb);
        let r = calculate_used_size_for_node(
            &dom,
            None,
            &tcb,
            isz(0.0, 0.0, 0.0, 42.0),
            &bp,
            &VIEWPORT,
        )
        .expect("anonymous box");
        assert_eq!(r.width, 800.0);
        assert_eq!(r.height, 42.0);
        // A non-positive content height means "auto" — resolved later from the
        // laid-out children, so 0.0 (not the negative value) is stored now.
        let r = calculate_used_size_for_node(
            &dom,
            None,
            &tcb,
            isz(0.0, 0.0, 0.0, -5.0),
            &bp,
            &VIEWPORT,
        )
        .expect("anonymous box");
        assert_eq!(r.height, 0.0);
    }
    #[test]
    fn used_size_resolves_absolute_lengths_and_adds_the_content_box_extras() {
        let dom = constraints_dom();
        let cb = size(800.0, 600.0);
        let r = used_size(&dom, PLAIN, cb, &zero_props());
        assert_eq!(r.width, 50.0);
        assert_eq!(r.height, 20.0);
        // content-box (default): padding + border grow the border box.
        let r = used_size(&dom, PLAIN, cb, &props(0.0, 2.0, 10.0));
        assert_eq!(r.width, 50.0 + 2.0 * (2.0 + 10.0));
        assert_eq!(r.height, 20.0 + 2.0 * (2.0 + 10.0));
    }
    #[test]
    fn used_size_resolves_percentages_against_the_physical_containing_block() {
        let dom = constraints_dom();
        let r = used_size(&dom, PCT, size(800.0, 600.0), &zero_props());
        assert_eq!(r.width, 400.0, "50% of the CB width");
        assert_eq!(r.height, 150.0, "25% of the CB height");
    }
    #[test]
    fn used_size_percentages_against_degenerate_containing_blocks_never_produce_nan() {
        let dom = constraints_dom();
        let bp = zero_props();
        for cb in [
            size(f32::NAN, f32::NAN),
            size(-800.0, -600.0),
            size(0.0, 0.0),
            size(f32::NEG_INFINITY, f32::NEG_INFINITY),
        ] {
            let r = used_size(&dom, PCT, cb, &bp);
            assert!(!r.width.is_nan() && !r.height.is_nan(), "NaN for cb={cb:?}");
            assert!(
                r.width >= 0.0 && r.height >= 0.0,
                "negative size for cb={cb:?}"
            );
        }
        // An infinite CB is a MEASUREMENT constraint, not a length: a
        // percentage against it behaves as auto (max-content), never as an
        // infinite used size. The earlier form of this test asserted the
        // saturation instead — a green test encoding the very bug that grew a
        // u32::MAX-wide compositor layer.
        let r = used_size(&dom, PCT, size(f32::INFINITY, f32::INFINITY), &bp);
        assert!(
            r.width.is_finite() && r.height.is_finite(),
            "percent against an indefinite CB must behave as auto, got {r:?}"
        );
    }
    #[test]
    fn an_auto_width_under_a_min_content_pass_is_its_min_content_contribution() {
        // The interim (pre-typed) fix answered max-content for EVERY
        // indefinite containing block, because `f32::INFINITY` cannot say
        // which measurement produced it. The typed axis can — and a
        // min-content pass must get the min-content contribution, or every
        // auto block reports the same number for both passes and shrink-to-fit
        // collapses to a constant.
        use crate::{solver3::geometry::ContainingBlock, text3::cache::AvailableSpace};
        let dom = constraints_dom();
        let bp = zero_props();
        let min_cb = ContainingBlock::from_axes(
            AvailableSpace::MinContent,
            AvailableSpace::MaxContent,
            size(f32::INFINITY, f32::INFINITY),
        );
        let max_cb = ContainingBlock::from_flattened(size(f32::INFINITY, f32::INFINITY));
        let intrinsic = isz(120.0, 420.0, 0.0, 30.0);
        let r_min =
            calculate_used_size_for_node(&dom, Some(AUTOBLOCK), &min_cb, intrinsic, &bp, &VIEWPORT)
                .expect("min pass");
        let r_max =
            calculate_used_size_for_node(&dom, Some(AUTOBLOCK), &max_cb, intrinsic, &bp, &VIEWPORT)
                .expect("max pass");
        assert_eq!(r_min.width, 120.0, "min-content pass -> min-content width");
        assert_eq!(r_max.width, 420.0, "max-content pass -> max-content width");
    }
    #[test]
    fn a_percent_width_under_each_measurement_pass_behaves_as_auto_of_that_kind() {
        // css-sizing-3 §5.2.1 — and with the typed axis, "behaves as auto"
        // can finally distinguish the two passes for percentages too.
        use crate::{solver3::geometry::ContainingBlock, text3::cache::AvailableSpace};
        let dom = constraints_dom();
        let bp = zero_props();
        let intrinsic = isz(120.0, 420.0, 0.0, 30.0);
        let min_cb = ContainingBlock::from_axes(
            AvailableSpace::MinContent,
            AvailableSpace::MaxContent,
            size(f32::INFINITY, f32::INFINITY),
        );
        let r = calculate_used_size_for_node(&dom, Some(PCT), &min_cb, intrinsic, &bp, &VIEWPORT)
            .expect("pct under min pass");
        assert_eq!(r.width, 120.0);
        let max_cb = ContainingBlock::from_flattened(size(f32::INFINITY, f32::INFINITY));
        let r = calculate_used_size_for_node(&dom, Some(PCT), &max_cb, intrinsic, &bp, &VIEWPORT)
            .expect("pct under max pass");
        assert_eq!(r.width, 420.0);
    }
    #[test]
    fn a_percent_min_width_cannot_reinfect_a_width_with_infinity() {
        // The main width resolution already treats an indefinite CB as auto —
        // but min/max constraints are clamped on AFTERWARDS. A percent
        // min-width resolved against the same indefinite CB used to come out
        // infinite, and `.max(min_w)` then forced the finished width back to
        // infinity. Per css-sizing-3 an unresolvable percentage minimum is
        // simply ignored.
        let dom = constraints_dom();
        let bp = zero_props();
        let r = used_size(&dom, PCTMIN, size(f32::INFINITY, f32::INFINITY), &bp);
        assert!(
            r.width.is_finite(),
            "percent min-width against an indefinite CB must be ignored, got {r:?}"
        );
    }
    #[test]
    fn every_node_shape_yields_a_finite_used_size_under_a_measurement_pass() {
        // Taffy's MinContent/MaxContent passes hand the bridge an INFINITE
        // available size on purpose, and whatever this function returns is
        // PERSISTED as the node's real used size. So for every CSS shape in
        // the fixture — plain px, percent, clamped, box-sizing, auto, vw, em —
        // the answer under that constraint must be a finite number. One
        // infinity here became an infinite clip rect, a u32::MAX-wide
        // compositor layer, and a ~900 GB allocation.
        let dom = constraints_dom();
        let bp = zero_props();
        for id in [
            PLAIN, PCT, CLAMPED, MAXED, PCTMIN, BBOX, AUTOBLOCK, VWMIN, EM, HCLAMPED, ROW10,
        ] {
            let r = used_size(&dom, id, size(f32::INFINITY, f32::INFINITY), &bp);
            assert!(
                r.width.is_finite() && r.height.is_finite(),
                "node {id:?} leaked a non-finite used size under max-content: {r:?}"
            );
        }
    }
    #[test]
    fn used_size_min_width_overrides_max_width_when_they_conflict() {
        // CSS 2.2 §10.4: if min-width > max-width, min-width wins.
        let dom = constraints_dom();
        let cb = size(800.0, 600.0);
        assert_eq!(used_size(&dom, CLAMPED, cb, &zero_props()).width, 200.0);
        // Without the conflicting min, max-width clamps normally.
        assert_eq!(used_size(&dom, MAXED, cb, &zero_props()).width, 100.0);
    }
    #[test]
    fn used_size_min_height_overrides_max_height_when_they_conflict() {
        let dom = constraints_dom();
        let cb = size(800.0, 600.0);
        assert_eq!(used_size(&dom, HCLAMPED, cb, &zero_props()).height, 200.0);
    }
    #[test]
    fn used_size_border_box_floors_at_the_padding_plus_border_sum() {
        // box-sizing: border-box with width:5px and 10px padding per side:
        // the content box cannot go negative, so the border box floors at 20.
        let dom = constraints_dom();
        let r = used_size(&dom, BBOX, size(800.0, 600.0), &props(0.0, 0.0, 10.0));
        assert_eq!(r.width, 20.0);
        assert_eq!(r.height, 20.0);
        // With no padding/border the specified size IS the border box.
        let r = used_size(&dom, BBOX, size(800.0, 600.0), &zero_props());
        assert_eq!(r.width, 5.0);
        assert_eq!(r.height, 5.0);
    }
    #[test]
    fn used_size_auto_width_block_fills_the_cb_minus_its_box_model() {
        let dom = constraints_dom();
        let cb = size(800.0, 600.0);
        let r = used_size(&dom, AUTOBLOCK, cb, &props(100.0, 0.0, 0.0));
        assert_eq!(r.width, 600.0, "800 - 2*100 margin");
        assert_eq!(r.height, 0.0, "auto block height is filled in after layout");
        // Box model wider than the CB → floored at 0, never negative.
        let r = used_size(&dom, AUTOBLOCK, size(10.0, 600.0), &props(100.0, 0.0, 0.0));
        assert_eq!(r.width, 0.0);
    }
    // ==================================================================
    // apply_width_constraints / apply_height_constraints  (numeric)
    // ==================================================================
    fn width_constrained(dom: &StyledDom, id: NodeId, tentative: f32, cb_width: f32) -> f32 {
        let state = node_state(dom, id);
        apply_width_constraints(dom, id, &state, tentative, cb_width, &zero_props())
    }
    fn height_constrained(dom: &StyledDom, id: NodeId, tentative: f32, cb_height: f32) -> f32 {
        let state = node_state(dom, id);
        apply_height_constraints(dom, id, &state, tentative, cb_height, &zero_props())
    }
    #[test]
    fn width_constraints_are_the_identity_without_min_or_max() {
        let dom = constraints_dom();
        for tentative in [0.0, 42.0, f32::MAX] {
            assert_eq!(width_constrained(&dom, PLAIN, tentative, 800.0), tentative);
        }
    }
    #[test]
    fn width_constraints_clamp_then_let_min_win_over_max() {
        let dom = constraints_dom();
        assert_eq!(
            width_constrained(&dom, MAXED, 300.0, 800.0),
            100.0,
            "max clamps"
        );
        assert_eq!(
            width_constrained(&dom, MAXED, 50.0, 800.0),
            50.0,
            "below max: untouched"
        );
        assert_eq!(
            width_constrained(&dom, CLAMPED, 300.0, 800.0),
            200.0,
            "min-width overrides max-width per §10.4"
        );
    }
    #[test]
    fn width_constraints_resolve_percentage_minimums_against_the_containing_block() {
        let dom = constraints_dom();
        assert_eq!(width_constrained(&dom, PCTMIN, 10.0, 800.0), 400.0);
        // A negative CB floors the percentage at 0, so the min is inert.
        assert_eq!(width_constrained(&dom, PCTMIN, 10.0, -800.0), 10.0);
        // A NaN CB must not poison the result.
        let r = width_constrained(&dom, PCTMIN, 10.0, f32::NAN);
        assert!(!r.is_nan() && r == 10.0);
    }
    #[test]
    fn width_constraints_resolve_em_minimums_against_the_elements_own_font_size() {
        // .em has font-size: 20px and min-width: 3em → 60px, NOT 3 × 16px.
        let dom = constraints_dom();
        assert_eq!(width_constrained(&dom, EM, 10.0, 800.0), 60.0);
    }
    #[test]
    fn width_constraints_never_return_nan() {
        // A NaN tentative width is sanitized by the final `.max(min_width)`
        // (f32::max drops NaN), so nothing downstream can see a NaN size.
        let dom = constraints_dom();
        assert_eq!(width_constrained(&dom, PLAIN, f32::NAN, 800.0), 0.0);
        // MAXED has a max-width, so the FIRST `.min(max_width)` absorbs the NaN (IEEE
        // 754: f32::min drops NaN) and lands on the max, before `.max(min_width)` ever
        // sees it. NaN doesn't always collapse to min_width -- it collapses to
        // whichever clamp touches it first.
        assert_eq!(width_constrained(&dom, MAXED, f32::NAN, 800.0), 100.0);
        assert_eq!(width_constrained(&dom, CLAMPED, f32::NAN, 800.0), 200.0);
    }
    #[test]
    fn width_constraints_handle_infinite_tentative_widths() {
        let dom = constraints_dom();
        assert_eq!(width_constrained(&dom, MAXED, f32::INFINITY, 800.0), 100.0);
        // No max-width → +inf survives (a definite size is never produced from
        // an infinite one, but the function must not panic or wrap).
        assert!(width_constrained(&dom, PLAIN, f32::INFINITY, 800.0).is_infinite());
        assert_eq!(
            width_constrained(&dom, CLAMPED, f32::NEG_INFINITY, 800.0),
            200.0
        );
    }
    #[test]
    fn width_constraints_ignore_viewport_unit_minimums() {
        // KNOWN GAP: `resolve_px_with_box_model` cannot resolve vw/vh/vmin/vmax
        // (no viewport is threaded into it), so `min-width: 10vw` silently
        // defaults to 0 and never floors the width — even though `width: 10vw`
        // on the very same element DOES resolve (via
        // `resolve_pixel_value_no_percent_with_viewport`).
        let dom = constraints_dom();
        assert_eq!(width_constrained(&dom, VWMIN, 300.0, 800.0), 300.0);
        assert_eq!(
            width_constrained(&dom, VWMIN, 10.0, 800.0),
            10.0,
            "10vw (= 80px on an 800px viewport) does not floor the width"
        );
    }
    #[test]
    fn height_constraints_clamp_then_let_min_win_over_max() {
        let dom = constraints_dom();
        assert_eq!(height_constrained(&dom, HCLAMPED, 300.0, 600.0), 200.0);
        assert_eq!(height_constrained(&dom, PLAIN, 42.0, 600.0), 42.0);
    }
    #[test]
    fn height_constraints_never_return_nan() {
        let dom = constraints_dom();
        assert_eq!(height_constrained(&dom, PLAIN, f32::NAN, 600.0), 0.0);
        assert_eq!(height_constrained(&dom, HCLAMPED, f32::NAN, 600.0), 200.0);
    }
    #[test]
    fn height_constraints_are_stable_at_the_f32_boundaries() {
        let dom = constraints_dom();
        assert_eq!(height_constrained(&dom, HCLAMPED, f32::MAX, 600.0), 200.0);
        assert_eq!(height_constrained(&dom, HCLAMPED, f32::MIN, 600.0), 200.0);
        // The implicit min-height of 0 floors any negative tentative height,
        // so a negative size can never escape into layout.
        assert_eq!(height_constrained(&dom, PLAIN, f32::MIN, 600.0), 0.0);
        assert_eq!(height_constrained(&dom, PLAIN, -1.0, 600.0), 0.0);
        assert!(height_constrained(&dom, PLAIN, f32::MAX, 600.0).is_finite());
    }
    // ==================================================================
    // apply_constraint_violation_table  (numeric)
    // ==================================================================
    fn cvt(dom: &StyledDom, id: NodeId, w: f32, h: f32) -> (f32, f32) {
        let state = node_state(dom, id);
        apply_constraint_violation_table(dom, id, &state, w, h, 800.0, 600.0, &zero_props())
    }
    #[test]
    fn constraint_violation_table_row1_leaves_an_unviolated_box_alone() {
        let dom = constraints_dom();
        assert_eq!(cvt(&dom, PLAIN, 200.0, 100.0), (200.0, 100.0));
    }
    #[test]
    fn constraint_violation_table_row2_preserves_the_aspect_ratio_under_max_width() {
        // w=200 > max-width=100 → w := 100, h scaled by the same factor.
        let dom = constraints_dom();
        assert_eq!(cvt(&dom, MAXED, 200.0, 100.0), (100.0, 50.0));
    }
    #[test]
    fn constraint_violation_table_row10_pins_min_width_and_max_height_together() {
        // .row10: min-width 200, max-height 50. w=100 (< min) and h=100 (> max)
        // → the ratio cannot be preserved; the spec pins both constraints.
        let dom = constraints_dom();
        assert_eq!(cvt(&dom, ROW10, 100.0, 100.0), (200.0, 50.0));
    }
    #[test]
    fn constraint_violation_table_guards_against_division_by_zero() {
        // The w<=0 / h<=0 guard must fire BEFORE any `w / h` division.
        let dom = constraints_dom();
        assert_eq!(cvt(&dom, MAXED, 0.0, 100.0), (0.0, 100.0));
        assert_eq!(cvt(&dom, MAXED, 200.0, 0.0), (100.0, 0.0));
        assert_eq!(cvt(&dom, MAXED, 0.0, 0.0), (0.0, 0.0));
        assert_eq!(
            cvt(&dom, MAXED, -50.0, -50.0),
            (0.0, 0.0),
            "negatives clamp up to 0"
        );
    }
    #[test]
    fn constraint_violation_table_survives_extreme_ratios() {
        // A near-degenerate ratio (MAX / MIN_POSITIVE) must not produce NaN or
        // panic — the scaled dimension underflows to 0 and is then floored.
        let dom = constraints_dom();
        let (w, h) = cvt(&dom, MAXED, f32::MAX, f32::MIN_POSITIVE);
        assert_eq!(w, 100.0, "max-width still clamps");
        assert!(h.is_finite() && h >= 0.0, "scaled height stays finite: {h}");
        let (w, h) = cvt(&dom, MAXED, f32::MIN_POSITIVE, f32::MAX);
        assert!(w.is_finite() && w >= 0.0, "w={w}");
        assert!(h.is_finite() && h >= 0.0, "h={h}");
    }
    #[test]
    fn constraint_violation_table_is_idempotent() {
        // Re-applying the table to its own output must be a fixed point —
        // otherwise a re-layout would keep shrinking the box.
        let dom = constraints_dom();
        for (id, w, h) in [
            (MAXED, 200.0_f32, 100.0_f32),
            (ROW10, 100.0, 100.0),
            (PLAIN, 200.0, 100.0),
        ] {
            let first = cvt(&dom, id, w, h);
            let second = cvt(&dom, id, first.0, first.1);
            assert_eq!(first, second, "not a fixed point for {id:?}");
        }
    }
}