1
//! Bridge between Azul's CSS style system and the Taffy layout engine.
2
//!
3
//! This module translates Azul CSS properties into Taffy's `Style` struct and
4
//! implements Taffy's `TraversePartialTree`, `LayoutPartialTree`, `CacheTree`,
5
//! `LayoutFlexboxContainer`, and `LayoutGridContainer` traits via the
6
//! [`TaffyBridge`] struct. The main entry point is [`layout_taffy_subtree`],
7
//! which is called from `fc.rs` when a flex or grid formatting context is
8
//! encountered during layout.
9

            
10
use azul_core::dom::FormattingContext;
11
use azul_css::{
12
    css::CssPropertyValue,
13
    props::{
14
        basic::{
15
            pixel::{DEFAULT_FONT_SIZE, PT_TO_PX},
16
            PixelValue, SizeMetric,
17
        },
18
        layout::{
19
            dimensions::CalcAstItemVec,
20
            flex::LayoutFlexBasis,
21
            grid::{GridAutoTracks, GridTemplate, GridTrackSizing},
22
            LayoutAlignContent, LayoutAlignItems, LayoutAlignSelf, LayoutDisplay,
23
            LayoutFlexDirection, LayoutFlexWrap, LayoutGridAutoFlow, LayoutJustifyContent,
24
            LayoutPosition, LayoutWritingMode,
25
        },
26
        property::{
27
            LayoutAlignContentValue, LayoutAlignItemsValue, LayoutAlignSelfValue,
28
            LayoutDisplayValue, LayoutFlexDirectionValue, LayoutFlexWrapValue,
29
            LayoutGridAutoColumnsValue, LayoutGridAutoFlowValue, LayoutGridAutoRowsValue,
30
            LayoutGridTemplateColumnsValue, LayoutGridTemplateRowsValue, LayoutJustifyContentValue,
31
            LayoutPositionValue,
32
        },
33
    },
34
};
35
use taffy::style::{MaxTrackSizingFunction, MinTrackSizingFunction, TrackSizingFunction};
36

            
37
use crate::solver3::{
38
    calc::CalcResolveContext,
39
    getters::{get_overflow_x, get_overflow_y},
40
    layout_tree::LayoutNodeId,
41
};
42

            
43
/// CSS reference pixels per inch (96 dpi per CSS Values spec).
44
const CSS_PX_PER_INCH: f32 = 96.0;
45

            
46
/// Convert `PixelValue` to pixels, only for absolute units (no %, and em/rem use fallback)
47
/// Used where proper resolution context is not available (grid tracks, etc.)
48
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
49
                                  // (or cross-type bindings that can't merge)
50
1658789
fn pixel_value_to_pixels_fallback(pv: &PixelValue) -> Option<f32> {
51
1658789
    match pv.metric {
52
1656755
        SizeMetric::Px => Some(pv.number.get()),
53
10
        SizeMetric::Pt => Some(pv.number.get() * PT_TO_PX),
54
7
        SizeMetric::In => Some(pv.number.get() * CSS_PX_PER_INCH),
55
7
        SizeMetric::Cm => Some(pv.number.get() * CSS_PX_PER_INCH / 2.54),
56
7
        SizeMetric::Mm => Some(pv.number.get() * CSS_PX_PER_INCH / 25.4),
57
        // For em/rem, use DEFAULT_FONT_SIZE as fallback (not ideal but needed without context)
58
25
        SizeMetric::Em | SizeMetric::Rem => Some(pv.number.get() * DEFAULT_FONT_SIZE),
59
1951
        SizeMetric::Percent => None, // Cannot resolve without containing block
60
        // Viewport units: Cannot resolve without viewport context
61
27
        SizeMetric::Vw | SizeMetric::Vh | SizeMetric::Vmin | SizeMetric::Vmax => None,
62
    }
63
1658789
}
64

            
65
/// Converts an Azul `grid-template-rows` value into Taffy grid template components.
66
38
fn grid_template_rows_to_taffy(
67
38
    val: LayoutGridTemplateRowsValue,
68
38
) -> Vec<GridTemplateComponent<String>> {
69
38
    let auto_tracks = val.get_property_or_default().unwrap_or_default();
70
38
    auto_tracks
71
38
        .tracks
72
38
        .iter()
73
58
        .map(|track| GridTemplateComponent::Single(translate_track(track)))
74
38
        .collect()
75
38
}
76

            
77
/// Converts an Azul `grid-template-columns` value into Taffy grid template components.
78
38
fn grid_template_columns_to_taffy(
79
38
    val: LayoutGridTemplateColumnsValue,
80
38
) -> Vec<GridTemplateComponent<String>> {
81
38
    let auto_tracks = val.get_property_or_default().unwrap_or_default();
82
38
    auto_tracks
83
38
        .tracks
84
38
        .iter()
85
2141
        .map(|track| GridTemplateComponent::Single(translate_track(track)))
86
38
        .collect()
87
38
}
88

            
89
/// Converts an Azul `grid-auto-rows` value into Taffy min/max track sizing pairs.
90
7
fn grid_auto_rows_to_taffy(
91
7
    val: LayoutGridAutoRowsValue,
92
7
) -> Vec<taffy::MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>> {
93
7
    let auto_tracks = val.get_property_or_default().unwrap_or_default();
94
7
    let tracks = auto_tracks.tracks;
95
7
    tracks
96
7
        .iter()
97
7
        .map(|track| taffy::MinMax {
98
4
            min: translate_track(track).min,
99
4
            max: translate_track(track).max,
100
4
        })
101
7
        .collect()
102
7
}
103

            
104
/// Converts an Azul `grid-auto-columns` value into Taffy track sizing functions.
105
7
fn grid_auto_columns_to_taffy(val: LayoutGridAutoColumnsValue) -> Vec<taffy::TrackSizingFunction> {
106
7
    let auto_tracks = val.get_property_or_default().unwrap_or_default();
107
7
    auto_tracks.tracks.iter().map(translate_track).collect()
108
7
}
109

            
110
#[allow(clippy::cast_precision_loss)] // bounded layout/render numeric cast
111
4584
fn translate_track(track: &GridTrackSizing) -> taffy::TrackSizingFunction {
112
    // Helper to resolve PixelValue to absolute pixels (handles em, rem, but not %)
113
    // Grid track sizing in Taffy doesn't support % - only absolute values
114
4584
    let px_to_float =
115
1169
        |pv: PixelValue| -> f32 { pixel_value_to_pixels_fallback(&pv).unwrap_or(0.0) };
116

            
117
4584
    match track {
118
6
        GridTrackSizing::MinContent => minmax(
119
6
            MinTrackSizingFunction::min_content(),
120
6
            MaxTrackSizingFunction::min_content(),
121
        ),
122
70
        GridTrackSizing::MaxContent => minmax(
123
70
            MinTrackSizingFunction::max_content(),
124
70
            MaxTrackSizingFunction::max_content(),
125
        ),
126
1173
        GridTrackSizing::MinMax(minmax_box) => minmax(
127
1173
            translate_track(&minmax_box.min).min,
128
1173
            translate_track(&minmax_box.max).max,
129
        ),
130
1159
        GridTrackSizing::Fixed(px) => {
131
            // Fixed tracks: resolve em/rem to pixels
132
            // Note: % is not supported in grid track sizing (CSS Grid spec)
133
1159
            let pixels = px_to_float(*px);
134
1159
            minmax(
135
1159
                MinTrackSizingFunction::length(pixels),
136
1159
                MaxTrackSizingFunction::length(pixels),
137
            )
138
        }
139
2163
        GridTrackSizing::Fr(fr) => {
140
            // Fr units: minmax(auto, Xfr) per CSS Grid spec
141
            // The min is auto, max is the fractional value
142
            // fr is stored as i32 * 100 (e.g., 1fr = 100, 2fr = 200)
143
2163
            minmax(
144
2163
                MinTrackSizingFunction::auto(),
145
2163
                MaxTrackSizingFunction::fr(*fr as f32 / 100.0),
146
            )
147
        }
148
3
        GridTrackSizing::Auto => minmax(
149
3
            MinTrackSizingFunction::min_content(),
150
3
            MaxTrackSizingFunction::max_content(),
151
        ),
152
10
        GridTrackSizing::FitContent(px) => {
153
            // fit-content: resolve em/rem to pixels
154
10
            let pixels = px_to_float(*px);
155
10
            minmax(
156
10
                MinTrackSizingFunction::length(pixels),
157
10
                MaxTrackSizingFunction::max_content(),
158
            )
159
        }
160
    }
161
4584
}
162

            
163
4612
const fn minmax(
164
4612
    min: MinTrackSizingFunction,
165
4612
    max: MaxTrackSizingFunction,
166
4612
) -> taffy::TrackSizingFunction {
167
4612
    TrackSizingFunction { min, max }
168
4612
}
169

            
170
129609
fn layout_display_to_taffy(val: LayoutDisplayValue) -> Display {
171
129609
    match val.get_property_or_default().unwrap_or_default() {
172
2
        LayoutDisplay::None => Display::None,
173
66082
        LayoutDisplay::Flex | LayoutDisplay::InlineFlex => Display::Flex,
174
52
        LayoutDisplay::Grid | LayoutDisplay::InlineGrid => Display::Grid,
175
63473
        _ => Display::Block,
176
    }
177
129609
}
178

            
179
// to determine their CB; Taffy's Position::Absolute handles this for both flex and grid
180
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
181
                                  // (or cross-type bindings that can't merge)
182
7
fn layout_position_to_taffy(val: LayoutPositionValue) -> Position {
183
7
    match val.get_property_or_default().unwrap_or_default() {
184
1
        LayoutPosition::Absolute => Position::Absolute,
185
1
        LayoutPosition::Fixed => Position::Absolute, // Taffy has no Fixed variant
186
1
        LayoutPosition::Relative => Position::Relative,
187
3
        LayoutPosition::Static => Position::Relative,
188
1
        LayoutPosition::Sticky => Position::Relative, // Sticky treated as Relative
189
    }
190
7
}
191

            
192
#[allow(clippy::cast_sign_loss)] // bounded layout/render numeric cast
193
10
fn decode_compact_grid_line(v: i16) -> GridPlacement<String> {
194
10
    if v == azul_css::compact_cache::I16_AUTO || v == azul_css::compact_cache::I16_SENTINEL {
195
3
        GridPlacement::Auto
196
7
    } else if v < 0 {
197
4
        GridPlacement::<String>::from_span((-v) as u16)
198
    } else {
199
3
        GridPlacement::<String>::from_line_index(v)
200
    }
201
10
}
202

            
203
40
fn grid_auto_flow_to_taffy(val: LayoutGridAutoFlowValue) -> GridAutoFlow {
204
40
    match val.get_property_or_default().unwrap_or_default() {
205
37
        LayoutGridAutoFlow::Row => GridAutoFlow::Row,
206
1
        LayoutGridAutoFlow::Column => GridAutoFlow::Column,
207
1
        LayoutGridAutoFlow::RowDense => GridAutoFlow::RowDense,
208
1
        LayoutGridAutoFlow::ColumnDense => GridAutoFlow::ColumnDense,
209
    }
210
40
}
211

            
212
/// Convert an azul `GridLine` (single start or end) to a Taffy `GridPlacement`.
213
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded layout/render numeric
214
                                                                   // cast
215
222
fn grid_line_to_taffy(line: &azul_css::props::layout::grid::GridLine) -> GridPlacement<String> {
216
    use azul_css::props::layout::grid::GridLine as AzGridLine;
217
    use taffy::style_helpers::{TaffyGridLine, TaffyGridSpan};
218
222
    match line {
219
3
        AzGridLine::Auto => GridPlacement::Auto,
220
7
        AzGridLine::Line(n) => GridPlacement::<String>::from_line_index(*n as i16),
221
6
        AzGridLine::Span(n) => GridPlacement::<String>::from_span(*n as u16),
222
206
        AzGridLine::Named(named) => {
223
            // Named lines: use the name with optional span
224
206
            let name = named.grid_line_name.as_str().to_string();
225
206
            if named.span_count > 0 {
226
3
                GridPlacement::NamedSpan(name, named.span_count as u16)
227
            } else {
228
203
                GridPlacement::NamedLine(name, 0)
229
            }
230
        }
231
    }
232
222
}
233

            
234
/// Convert an azul `GridPlacement` (grid-column / grid-row) to a Taffy `Line<GridPlacement>`.
235
102
fn grid_placement_to_taffy(
236
102
    placement: &azul_css::props::layout::grid::GridPlacement,
237
102
) -> Line<GridPlacement<String>> {
238
102
    Line {
239
102
        start: grid_line_to_taffy(&placement.grid_start),
240
102
        end: grid_line_to_taffy(&placement.grid_end),
241
102
    }
242
102
}
243

            
244
129593
fn layout_flex_direction_to_taffy(val: LayoutFlexDirectionValue) -> FlexDirection {
245
129593
    match val.get_property_or_default().unwrap_or_default() {
246
109228
        LayoutFlexDirection::Row => FlexDirection::Row,
247
1
        LayoutFlexDirection::RowReverse => FlexDirection::RowReverse,
248
20363
        LayoutFlexDirection::Column => FlexDirection::Column,
249
1
        LayoutFlexDirection::ColumnReverse => FlexDirection::ColumnReverse,
250
    }
251
129593
}
252

            
253
129592
fn layout_flex_wrap_to_taffy(val: LayoutFlexWrapValue) -> FlexWrap {
254
129592
    match val.get_property_or_default().unwrap_or_default() {
255
129580
        LayoutFlexWrap::NoWrap => FlexWrap::NoWrap,
256
11
        LayoutFlexWrap::Wrap => FlexWrap::Wrap,
257
1
        LayoutFlexWrap::WrapReverse => FlexWrap::WrapReverse,
258
    }
259
129592
}
260

            
261
129595
fn layout_align_items_to_taffy(val: LayoutAlignItemsValue) -> AlignItems {
262
129595
    match val.get_property_or_default().unwrap_or_default() {
263
79856
        LayoutAlignItems::Stretch => AlignItems::Stretch,
264
40735
        LayoutAlignItems::Center => AlignItems::Center,
265
9002
        LayoutAlignItems::Start => AlignItems::FlexStart,
266
1
        LayoutAlignItems::End => AlignItems::FlexEnd,
267
1
        LayoutAlignItems::Baseline => AlignItems::Baseline,
268
    }
269
129595
}
270

            
271
8
fn layout_align_self_to_taffy(val: LayoutAlignSelfValue) -> Option<AlignSelf> {
272
8
    match val.get_property_or_default().unwrap_or_default() {
273
3
        LayoutAlignSelf::Auto => None, /* Auto means inherit from parent's align-items (for non-abspos; abspos auto computes to itself per spec) */
274
1
        LayoutAlignSelf::Start => Some(AlignSelf::FlexStart),
275
1
        LayoutAlignSelf::End => Some(AlignSelf::FlexEnd),
276
1
        LayoutAlignSelf::Center => Some(AlignSelf::Center),
277
1
        LayoutAlignSelf::Baseline => Some(AlignSelf::Baseline),
278
1
        LayoutAlignSelf::Stretch => Some(AlignSelf::Stretch),
279
    }
280
8
}
281

            
282
129595
fn layout_align_content_to_taffy(val: LayoutAlignContentValue) -> AlignContent {
283
129595
    match val.get_property_or_default().unwrap_or_default() {
284
1
        LayoutAlignContent::Start => AlignContent::FlexStart,
285
1
        LayoutAlignContent::End => AlignContent::FlexEnd,
286
1
        LayoutAlignContent::Center => AlignContent::Center,
287
129590
        LayoutAlignContent::Stretch => AlignContent::Stretch,
288
1
        LayoutAlignContent::SpaceBetween => AlignContent::SpaceBetween,
289
1
        LayoutAlignContent::SpaceAround => AlignContent::SpaceAround,
290
    }
291
129595
}
292

            
293
9
fn layout_justify_content_to_taffy(val: LayoutJustifyContentValue) -> JustifyContent {
294
9
    match val.get_property_or_default().unwrap_or_default() {
295
1
        LayoutJustifyContent::FlexStart => JustifyContent::FlexStart,
296
1
        LayoutJustifyContent::FlexEnd => JustifyContent::FlexEnd,
297
2
        LayoutJustifyContent::Start => JustifyContent::Start,
298
1
        LayoutJustifyContent::End => JustifyContent::End,
299
1
        LayoutJustifyContent::Center => JustifyContent::Center,
300
1
        LayoutJustifyContent::SpaceBetween => JustifyContent::SpaceBetween,
301
1
        LayoutJustifyContent::SpaceAround => JustifyContent::SpaceAround,
302
1
        LayoutJustifyContent::SpaceEvenly => JustifyContent::SpaceEvenly,
303
    }
304
9
}
305

            
306
6
fn layout_justify_items_to_taffy(
307
6
    val: azul_css::props::property::LayoutJustifyItemsValue,
308
6
) -> AlignItems {
309
    use azul_css::props::layout::grid::LayoutJustifyItems;
310
6
    match val.get_property_or_default().unwrap_or_default() {
311
2
        LayoutJustifyItems::Start => AlignItems::Start,
312
1
        LayoutJustifyItems::End => AlignItems::End,
313
1
        LayoutJustifyItems::Center => AlignItems::Center,
314
2
        LayoutJustifyItems::Stretch => AlignItems::Stretch,
315
    }
316
6
}
317

            
318
// TODO: visibility, z_index still missing
319
// --- CSS <-> Taffy conversion functions ---
320

            
321
use std::{
322
    collections::{BTreeMap, HashMap},
323
    sync::Arc,
324
};
325

            
326
use azul_core::{dom::NodeId, geom::LogicalSize, styled_dom::StyledDom};
327
use azul_css::props::{
328
    layout::{LayoutHeight, LayoutWidth},
329
    property::{CssProperty, CssPropertyType},
330
};
331
use taffy::{
332
    compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout,
333
    prelude::*, CacheTree, LayoutFlexboxContainer, LayoutGridContainer, LayoutInput, LayoutOutput,
334
    RunMode,
335
};
336

            
337
use crate::{
338
    font_traits::{FontLoaderTrait, ParsedFontTrait},
339
    solver3::{
340
        fc::{
341
            translate_taffy_point_back, translate_taffy_size_back, FloatingContext,
342
            LayoutConstraints, TextAlign as FcTextAlign,
343
        },
344
        getters::{
345
            get_align_content, get_align_items, get_css_border_bottom_width,
346
            get_css_border_left_width, get_css_border_right_width, get_css_border_top_width,
347
            get_css_bottom, get_css_box_sizing, get_css_height, get_css_left,
348
            get_css_margin_bottom, get_css_margin_left, get_css_margin_right, get_css_margin_top,
349
            get_css_max_height, get_css_max_width, get_css_min_height, get_css_min_width,
350
            get_css_padding_bottom, get_css_padding_left, get_css_padding_right,
351
            get_css_padding_top, get_css_right, get_css_top, get_css_width, get_flex_direction,
352
            get_position, MultiValue,
353
        },
354
        layout_tree::{get_display_type, LayoutTree},
355
        sizing, LayoutContext,
356
    },
357
};
358

            
359
/// Coordinate space the `taffy_content_*` arguments of
360
/// [`compute_taffy_scrollbar_info`] are measured in.
361
#[derive(Copy, Clone, PartialEq, Eq)]
362
enum ContentSizeOrigin {
363
    /// Taffy's `LayoutOutput::content_size`: child extents measured from the
364
    /// BORDER-BOX origin, so the leading border + padding ride along as an
365
    /// offset and the flex path adds the trailing padding on top.
366
    BorderBox,
367
    /// Our own BFC/IFC `overflow_size`, already relative to the content box.
368
    ContentBox,
369
}
370

            
371
/// Shared scrollbar detection for Taffy-managed flex/grid nodes.
372
///
373
/// When Taffy lays out a flex/grid container, it may expand the container
374
/// beyond the CSS-specified size (Taffy doesn't know about `overflow`).
375
/// This function resolves the CSS-constrained container size, computes
376
/// content vs. container overflow, and returns the resulting `ScrollbarRequirements`
377
/// plus the effective content size (for `overflow_content_size`).
378
///
379
/// Returns `(scrollbar_info, effective_content_width, effective_content_height)`.
380
358455
fn compute_taffy_scrollbar_info<T: ParsedFontTrait>(
381
358455
    ctx: &LayoutContext<'_, T>,
382
358455
    tree: &LayoutTree,
383
358455
    node_idx: usize,
384
358455
    result_width: f32,
385
358455
    result_height: f32,
386
358455
    taffy_content_width: f32,
387
358455
    taffy_content_height: f32,
388
358455
    content_origin: ContentSizeOrigin,
389
358455
) -> (crate::solver3::scrollbar::ScrollbarRequirements, f32, f32) {
390
    use crate::solver3::scrollbar::ScrollbarRequirements;
391

            
392
358455
    let node = tree.get(LayoutNodeId::new(node_idx));
393
358455
    let dom_id = node.and_then(|n| n.dom_node_id);
394

            
395
358455
    let Some(dom_id) = dom_id else {
396
3
        return (ScrollbarRequirements::default(), 0.0, 0.0);
397
    };
398

            
399
358452
    let styled_node_state = ctx
400
358452
        .styled_dom
401
358452
        .styled_nodes
402
358452
        .as_container()
403
358452
        .get(dom_id)
404
358452
        .map(|s| s.styled_node_state)
405
358452
        .unwrap_or_default();
406

            
407
    // Compute padding + border from the node's box_props
408
358452
    let (padding_width, padding_height, border_width, border_height, border_left, border_top) =
409
358452
        tree.get(LayoutNodeId::new(node_idx))
410
358452
            .map_or((0.0, 0.0, 0.0, 0.0, 0.0, 0.0), |node| {
411
358452
                let bp = node.box_props.unpack();
412
358452
                (
413
358452
                    bp.padding.left + bp.padding.right,
414
358452
                    bp.padding.top + bp.padding.bottom,
415
358452
                    bp.border.left + bp.border.right,
416
358452
                    bp.border.top + bp.border.bottom,
417
358452
                    bp.border.left,
418
358452
                    bp.border.top,
419
358452
                )
420
358452
            });
421

            
422
    // Use CSS-specified dimensions as the container constraint.
423
    // Taffy may have expanded the box beyond these, but the CSS spec says
424
    // the container clips at the specified size.
425
358452
    let css_height = get_css_height(ctx.styled_dom, dom_id, &styled_node_state);
426
358452
    let css_width = get_css_width(ctx.styled_dom, dom_id, &styled_node_state);
427

            
428
358452
    let result_content_w = result_width - padding_width - border_width;
429
358452
    let result_content_h = result_height - padding_height - border_height;
430

            
431
358452
    let css_container_w = css_width
432
358452
        .exact()
433
358452
        .and_then(|w| css_width_to_px(&w))
434
358452
        .unwrap_or(result_content_w)
435
358452
        .max(0.0);
436

            
437
358452
    let css_container_h = css_height
438
358452
        .exact()
439
358452
        .and_then(|h| css_height_to_px(&h))
440
358452
        .unwrap_or(result_content_h)
441
358452
        .max(0.0);
442

            
443
    // Content size: use the caller's content_size if non-zero,
444
    // else result size minus padding/border (Taffy expanded to fit).
445
    //
446
    // IMPORTANT: Taffy's content_size is measured from (0,0) of the BORDER box.
447
    // Child positions therefore carry border.left/top AND the leading padding as
448
    // an offset, and the flex path adds the TRAILING padding on top
449
    // (`content_size.height += content_box_inset.bottom - border.bottom`).
450
    // container_size below is a content-box size, so the whole inset has to come
451
    // off to align the coordinate spaces: subtracting only the border left a
452
    // `padding-top: 18px` container reporting content = viewport + 18px, i.e. a
453
    // phantom `overflow: auto` scrollbar whose thumb spans ~98% of the track and
454
    // whose max_scroll is 18px. Subtracting the padding SUM (leading + trailing)
455
    // leaves the pure child extent, so a container whose children fit reports
456
    // content == container (no bar) and a genuinely overflowing one keeps
457
    // max_scroll = children − content box.
458
    //
459
    // Our own BFC/IFC overflow_size is already content-box relative and must not
460
    // be adjusted at all — hence `content_origin`.
461
358452
    let (inset_w, inset_h) = match content_origin {
462
58239
        ContentSizeOrigin::BorderBox => (border_left + padding_width, border_top + padding_height),
463
300213
        ContentSizeOrigin::ContentBox => (0.0, 0.0),
464
    };
465
358452
    let content_w = if taffy_content_width > 0.0 {
466
269491
        (taffy_content_width - inset_w).max(0.0)
467
    } else {
468
88961
        result_content_w.max(0.0)
469
    };
470
358452
    let content_h = if taffy_content_height > 0.0 {
471
271095
        (taffy_content_height - inset_h).max(0.0)
472
    } else {
473
87357
        result_content_h.max(0.0)
474
    };
475

            
476
358452
    let content_size = LogicalSize::new(content_w, content_h);
477
358452
    let container_size = LogicalSize::new(css_container_w, css_container_h);
478

            
479
358452
    let scrollbar_info = crate::solver3::cache::compute_scrollbar_info_core(
480
358452
        ctx,
481
358452
        dom_id,
482
358452
        &styled_node_state,
483
358452
        content_size,
484
358452
        container_size,
485
    );
486

            
487
358452
    (scrollbar_info, content_w, content_h)
488
358455
}
489

            
490
/// Convert `LayoutWidth::Px(…)` to `f32`, returning None for non-px units.
491
13573
fn css_width_to_px(w: &LayoutWidth) -> Option<f32> {
492
13573
    match w {
493
13568
        LayoutWidth::Px(px) => pixel_value_to_pixels_fallback(px),
494
5
        _ => None,
495
    }
496
13573
}
497

            
498
/// Convert `LayoutHeight::Px(…)` to `f32`, returning None for non-px units.
499
34722
fn css_height_to_px(h: &LayoutHeight) -> Option<f32> {
500
34722
    match h {
501
34717
        LayoutHeight::Px(px) => pixel_value_to_pixels_fallback(px),
502
5
        _ => None,
503
    }
504
34722
}
505

            
506
// Helper function to convert MultiValue<PixelValue> to LengthPercentageAuto
507
518376
fn multi_value_to_lpa(mv: MultiValue<PixelValue>) -> LengthPercentageAuto {
508
518376
    match mv {
509
        MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => {
510
518328
            LengthPercentageAuto::auto()
511
        }
512
48
        MultiValue::Exact(pv) => pixel_value_to_pixels_fallback(&pv)
513
48
            .map(LengthPercentageAuto::length)
514
48
            .or_else(|| {
515
5
                pv.to_percent()
516
5
                    .map(|p| LengthPercentageAuto::percent(p.get()))
517
5
            })
518
48
            .unwrap_or_else(LengthPercentageAuto::auto),
519
    }
520
518376
}
521

            
522
// Helper function to convert MultiValue<PixelValue> to LengthPercentageAuto for margins
523
// CSS spec: margin initial value is 0, but `auto` has special centering meaning in flexbox
524
518176
fn multi_value_to_lpa_margin(mv: MultiValue<PixelValue>) -> LengthPercentageAuto {
525
518176
    match mv {
526
        MultiValue::Auto => {
527
42
            LengthPercentageAuto::auto() // Preserve auto for flexbox centering
528
        }
529
        MultiValue::Initial | MultiValue::Inherit => {
530
14
            LengthPercentageAuto::length(0.0) // Margins' initial value is 0
531
        }
532
518120
        MultiValue::Exact(pv) => {
533
518120
            pixel_value_to_pixels_fallback(&pv)
534
518120
                .map(LengthPercentageAuto::length)
535
518120
                .or_else(|| {
536
2
                    pv.to_percent()
537
2
                        .map(|p| LengthPercentageAuto::percent(p.get()))
538
2
                })
539
518120
                .unwrap_or_else(|| LengthPercentageAuto::length(0.0)) // Fallback to 0 for
540
                                                                      // margins
541
        }
542
    }
543
518176
}
544

            
545
/// `em` / `rem` resolved against the NODE's font sizes; every other unit as
546
/// [`pixel_value_to_pixels_fallback`].
547
///
548
/// The fallback's `DEFAULT_FONT_SIZE`
549
/// (16 px) is only right for a 16 px font: a widget label's `margin: 1em`
550
/// at 11 px came out as 16 px top and bottom, which is the bug class "a
551
/// relative unit resolved against a constant" — use this wherever the font
552
/// size is known.
553
201
fn pixel_value_to_pixels_ctx(pv: &PixelValue, em_size: f32, rem_size: f32) -> Option<f32> {
554
201
    match pv.metric {
555
200
        SizeMetric::Em => Some(pv.number.get() * em_size),
556
1
        SizeMetric::Rem => Some(pv.number.get() * rem_size),
557
        _ => pixel_value_to_pixels_fallback(pv),
558
    }
559
201
}
560

            
561
/// [`multi_value_to_lpa_margin`] with the node's font sizes for `em` / `rem`.
562
518368
fn multi_value_to_lpa_margin_ctx(
563
518368
    mv: MultiValue<PixelValue>,
564
518368
    em_size: f32,
565
518368
    rem_size: f32,
566
518368
) -> LengthPercentageAuto {
567
518315
    match mv {
568
518315
        MultiValue::Exact(pv) if matches!(pv.metric, SizeMetric::Em | SizeMetric::Rem) => {
569
200
            pixel_value_to_pixels_ctx(&pv, em_size, rem_size).map_or_else(
570
                || LengthPercentageAuto::length(0.0),
571
                LengthPercentageAuto::length,
572
            )
573
        }
574
518168
        other => multi_value_to_lpa_margin(other),
575
    }
576
518368
}
577

            
578
/// [`multi_value_to_lp`] with the node's font sizes for `em` / `rem`.
579
1036730
fn multi_value_to_lp_ctx(
580
1036730
    mv: MultiValue<PixelValue>,
581
1036730
    em_size: f32,
582
1036730
    rem_size: f32,
583
1036730
) -> LengthPercentage {
584
1036705
    match mv {
585
1036705
        MultiValue::Exact(pv) if matches!(pv.metric, SizeMetric::Em | SizeMetric::Rem) => {
586
1
            pixel_value_to_pixels_ctx(&pv, em_size, rem_size)
587
1
                .map_or(LengthPercentage::ZERO, LengthPercentage::length)
588
        }
589
1036729
        other => multi_value_to_lp(other),
590
    }
591
1036730
}
592

            
593
// Helper function to convert MultiValue<PixelValue> to LengthPercentage
594
1036749
fn multi_value_to_lp(mv: MultiValue<PixelValue>) -> LengthPercentage {
595
1036749
    match mv {
596
28
        MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => LengthPercentage::ZERO,
597
1036721
        MultiValue::Exact(pv) => pixel_value_to_pixels_fallback(&pv)
598
1036721
            .map(LengthPercentage::length)
599
1036721
            .or_else(|| pv.to_percent().map(|p| LengthPercentage::percent(p.get())))
600
1036721
            .unwrap_or(LengthPercentage::ZERO),
601
    }
602
1036749
}
603

            
604
// Helper function to convert plain PixelValue to LengthPercentage
605
/// Converts Azul's CSS overflow value to Taffy's Overflow enum.
606
///
607
/// Taffy only has Visible, Clip, Hidden, Scroll (no Auto).
608
/// CSS `auto` behaves like `scroll` from a layout perspective —
609
/// it constrains the container and enables scrolling.
610
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
611
                                  // (or cross-type bindings that can't merge)
612
259190
const fn azul_overflow_to_taffy(
613
259190
    ov: MultiValue<azul_css::props::layout::LayoutOverflow>,
614
259190
) -> taffy::Overflow {
615
    use azul_css::props::layout::LayoutOverflow;
616
259181
    match ov {
617
249778
        MultiValue::Exact(LayoutOverflow::Visible) => taffy::Overflow::Visible,
618
8631
        MultiValue::Exact(LayoutOverflow::Hidden) => taffy::Overflow::Hidden,
619
99
        MultiValue::Exact(LayoutOverflow::Scroll) => taffy::Overflow::Scroll,
620
672
        MultiValue::Exact(LayoutOverflow::Auto) => taffy::Overflow::Scroll, /* Auto acts like scroll for layout */
621
1
        MultiValue::Exact(LayoutOverflow::Clip) => taffy::Overflow::Clip,
622
9
        _ => taffy::Overflow::Visible, // default
623
    }
624
259190
}
625

            
626
6122
fn pixel_to_lp(pv: PixelValue) -> LengthPercentage {
627
6122
    pixel_value_to_pixels_fallback(&pv)
628
6122
        .map(LengthPercentage::length)
629
6122
        .or_else(|| pv.to_percent().map(|p| LengthPercentage::percent(p.get())))
630
6122
        .unwrap_or(LengthPercentage::ZERO)
631
6122
}
632

            
633
/// Slow path for flex-basis: full property cache lookup + decode.
634
/// Extracted to avoid duplicating the logic in the compact fast-path fallback.
635
#[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
636
                                             // pixel/coord path or to avoid churning call sites for
637
                                             // a perf-neutral change)
638
3
fn flex_basis_slow_path(
639
3
    cache: &azul_core::prop_cache::CssPropertyCache,
640
3
    node_data: &azul_core::dom::NodeData,
641
3
    id: &NodeId,
642
3
    node_state: &azul_core::styled_dom::StyledNodeState,
643
3
    taffy_style: &mut Style,
644
3
) -> Dimension {
645
3
    cache
646
3
        .get_property(node_data, id, node_state, &CssPropertyType::FlexBasis)
647
3
        .and_then(|p| {
648
            if let CssProperty::FlexBasis(v) = p {
649
                let basis = match v.get_property_or_default().unwrap_or_default() {
650
                    LayoutFlexBasis::Auto => Dimension::auto(),
651
                    LayoutFlexBasis::Exact(pv) => pixel_value_to_pixels_fallback(&pv)
652
                        .map(Dimension::length)
653
                        .or_else(|| pv.to_percent().map(|p| Dimension::percent(p.get())))
654
                        .unwrap_or_else(Dimension::auto),
655
                };
656
                // WORKAROUND: If flex-basis is set and not auto, clear width to let flex-basis
657
                // take precedence. Workaround for Taffy not properly prioritizing flex-basis over
658
                // width
659
                if !matches!(basis, auto if auto == Dimension::auto()) {
660
                    taffy_style.size.width = Dimension::auto();
661
                }
662
                Some(basis)
663
            } else {
664
                None
665
            }
666
        })
667
3
        .unwrap_or_else(Dimension::auto)
668
3
}
669

            
670
/// The bridge struct that implements Taffy's traits.
671
/// It holds mutable references to the solver's data structures, allowing Taffy
672
/// to read styles and write layout results back into our `LayoutTree`.
673
struct TaffyBridge<'a, 'b, T: ParsedFontTrait> {
674
    ctx: &'a mut LayoutContext<'b, T>,
675
    tree: &'a mut LayoutTree,
676
    /// Raw pointer to text cache - needed because we can't have multiple &mut references
677
    /// SAFETY: This pointer is only valid for the lifetime of the `TaffyBridge`
678
    /// and must only be used within `compute_child_layout` callbacks
679
    text_cache: *mut crate::font_traits::TextLayoutCache,
680
    /// Heap-pinned `CalcResolveContext`s whose addresses are passed into taffy
681
    /// `Dimension::calc(ptr)`. Kept alive for the duration of the layout pass.
682
    /// Uses `RefCell` because `get_core_container_style` takes `&self`.
683
    // Box gives each CalcResolveContext a stable heap address for the `*const` handed to
684
    // taffy `Dimension::calc()`; a plain Vec<T> would invalidate those pointers on realloc.
685
    #[allow(clippy::vec_box)]
686
    calc_storage: std::cell::RefCell<Vec<Box<CalcResolveContext>>>,
687
    /// Memoised `translate_style_to_taffy` results, keyed by DOM node id
688
    /// (`usize` = `NodeId::index`). Taffy calls
689
    /// `get_core_container_style` and `should_suppress_cross_intrinsic`
690
    /// many times per node during a single layout pass; each call
691
    /// triggers ~13 `cache.get_property` cascade walks for grid/flex
692
    /// props. Caching the built `Style` cuts this to one build per node.
693
    style_memo: std::cell::RefCell<HashMap<usize, Style>>,
694
}
695

            
696
impl<'a, 'b, T: ParsedFontTrait> TaffyBridge<'a, 'b, T> {
697
3714
    fn new(
698
3714
        ctx: &'a mut LayoutContext<'b, T>,
699
3714
        tree: &'a mut LayoutTree,
700
3714
        text_cache: *mut crate::font_traits::TextLayoutCache,
701
3714
    ) -> Self {
702
3714
        Self {
703
3714
            ctx,
704
3714
            tree,
705
3714
            text_cache,
706
3714
            calc_storage: std::cell::RefCell::new(Vec::new()),
707
3714
            style_memo: std::cell::RefCell::new(HashMap::new()),
708
3714
        }
709
3714
    }
710

            
711
    /// Cache-backed wrapper for `translate_style_to_taffy`. Returns a
712
    /// clone of the memoised `Style` on cache hit, builds + inserts on
713
    /// miss. Keyed by DOM node index (not tree index) because the
714
    /// result depends only on the styled DOM, not on the transient
715
    /// layout tree.
716
10922012
    fn translate_style_to_taffy_cached(&self, dom_id: Option<NodeId>) -> Style {
717
10922012
        let Some(id) = dom_id else {
718
            return Style::default();
719
        };
720
10922012
        let key = id.index();
721
10922012
        if let Some(style) = self.style_memo.borrow().get(&key) {
722
10792835
            return style.clone();
723
129177
        }
724
129177
        let style = self.translate_style_to_taffy(dom_id);
725
129177
        self.style_memo.borrow_mut().insert(key, style.clone());
726
129177
        style
727
10922012
    }
728

            
729
    /// Translates CSS properties from the `StyledDom` into a `taffy::Style` struct.
730
    /// This is the core of the integration, mapping one style system to another.
731
    #[allow(clippy::field_reassign_with_default)] // struct built incrementally / test setup; a struct literal is not clearer here
732
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse
733
                                     // routine (one branch per case)
734
129177
    fn translate_style_to_taffy(&self, dom_id: Option<NodeId>) -> Style {
735
129177
        let Some(id) = dom_id else {
736
            return Style::default();
737
        };
738
129177
        let styled_dom = &self.ctx.styled_dom;
739
129177
        let node_data = &styled_dom.node_data.as_ref()[id.index()];
740
129177
        let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
741
129177
        let cache = &styled_dom.css_property_cache.ptr;
742
129177
        let mut taffy_style = Style::default();
743

            
744
        // Box Sizing — CSS default is content-box, but Taffy defaults to border-box
745
        taffy_style.box_sizing =
746
129177
            match get_css_box_sizing(styled_dom, id, node_state).unwrap_or_default() {
747
49420
                azul_css::props::layout::LayoutBoxSizing::BorderBox => BoxSizing::BorderBox,
748
79757
                azul_css::props::layout::LayoutBoxSizing::ContentBox => BoxSizing::ContentBox,
749
            };
750

            
751
        // Display Mode
752
129177
        taffy_style.display =
753
129177
            layout_display_to_taffy(CssPropertyValue::Exact(get_display_type(styled_dom, id)));
754

            
755
        // Position
756
129177
        taffy_style.position =
757
129177
            from_layout_position(get_position(styled_dom, id, node_state).unwrap_or_default());
758

            
759
        // Inset (top, left, bottom, right)
760
129177
        taffy_style.inset = Rect {
761
129177
            left: multi_value_to_lpa(get_css_left(styled_dom, id, node_state)),
762
129177
            right: multi_value_to_lpa(get_css_right(styled_dom, id, node_state)),
763
129177
            top: multi_value_to_lpa(get_css_top(styled_dom, id, node_state)),
764
129177
            bottom: multi_value_to_lpa(get_css_bottom(styled_dom, id, node_state)),
765
129177
        };
766

            
767
        // Size
768
129177
        let width = get_css_width(self.ctx.styled_dom, id, node_state);
769
129177
        let height = get_css_height(self.ctx.styled_dom, id, node_state);
770

            
771
        // Resolve node-local font sizes for calc() em/rem resolution
772
129177
        let em_size = crate::solver3::getters::get_element_font_size(styled_dom, id, node_state);
773
129177
        let rem_size = {
774
129177
            let root_id = NodeId::new(0);
775
129177
            let root_state = &styled_dom.styled_nodes.as_container()[root_id].styled_node_state;
776
129177
            crate::solver3::getters::get_element_font_size(styled_dom, root_id, root_state)
777
        };
778

            
779
129177
        let taffy_width = from_layout_width(
780
129177
            width.unwrap_or_default(),
781
129177
            &self.calc_storage,
782
129177
            em_size,
783
129177
            rem_size,
784
        );
785
129177
        let taffy_height = from_layout_height(
786
129177
            height.unwrap_or_default(),
787
129177
            &self.calc_storage,
788
129177
            em_size,
789
129177
            rem_size,
790
        );
791

            
792
129177
        taffy_style.size = Size {
793
129177
            width: taffy_width,
794
129177
            height: taffy_height,
795
129177
        };
796

            
797
        // Overflow — CRITICAL for scroll containers.
798
        // Without this, Taffy's flexbox algorithm uses content size as automatic
799
        // minimum size, causing flex containers with overflow:auto/scroll to
800
        // expand to fit all content instead of clipping at the explicit size.
801
        // With overflow: Hidden/Scroll, Taffy sets automatic min size to 0 and
802
        // constrains the container.
803
129177
        let overflow_x = get_overflow_x(styled_dom, id, node_state);
804
129177
        let overflow_y = get_overflow_y(styled_dom, id, node_state);
805
129177
        taffy_style.overflow = taffy::Point {
806
129177
            x: azul_overflow_to_taffy(overflow_x),
807
129177
            y: azul_overflow_to_taffy(overflow_y),
808
129177
        };
809

            
810
        // Forward CSS aspect-ratio to taffy so flex/grid items honor it (and taffy's
811
        // transferred min-size suggestion works). AspectRatioValue stores width and
812
        // height ×1000, so the preferred ratio is simply width/height.
813
        #[allow(clippy::cast_precision_loss)]
814
        // small integer aspect-ratio components (e.g. 2000/1000)
815
        {
816
129177
            taffy_style.aspect_ratio = match crate::solver3::getters::get_aspect_ratio_property(
817
129177
                styled_dom, id, node_state,
818
            ) {
819
                MultiValue::Exact(azul_css::props::style::effects::StyleAspectRatio::Ratio(ar))
820
                    if ar.height != 0 =>
821
                {
822
                    Some(ar.width as f32 / ar.height as f32)
823
                }
824
129177
                _ => None,
825
            };
826
        }
827

            
828
        // Min/Max Size
829
        // min-size:auto enables Taffy's auto minimum size algorithm which computes the
830
        // content size suggestion (min-content in main axis) and transferred size suggestion
831
        // (cross size converted through aspect ratio, if any). NOTE: aspect_ratio is not yet
832
        // forwarded to Taffy, so the transferred size suggestion path is incomplete.
833
        // NOTE: In CSS, the default min-width/min-height for flex items is `auto`
834
        // (which resolves to `min-content`), preventing them from shrinking below
835
        // their content size. We must map Auto to Dimension::Auto, NOT to 0px.
836
129177
        let min_width_css = get_css_min_width(styled_dom, id, node_state);
837
129177
        let min_height_css = get_css_min_height(styled_dom, id, node_state);
838

            
839
        taffy_style.min_size = Size {
840
129177
            width: match min_width_css {
841
123607
                MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => Dimension::auto(),
842
5570
                MultiValue::Exact(v) => pixel_to_lp(v.inner).into(),
843
            },
844
129177
            height: match min_height_css {
845
128647
                MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => Dimension::auto(),
846
530
                MultiValue::Exact(v) => pixel_to_lp(v.inner).into(),
847
            },
848
        };
849

            
850
        // For max-size, we need to handle Auto specially - it should translate to Taffy's auto, not
851
        // a concrete value This is CRITICAL for flexbox stretch to work: items with
852
        // max-height: auto CAN be stretched
853
129177
        let max_width_css = get_css_max_width(styled_dom, id, node_state);
854
129177
        let max_height_css = get_css_max_height(styled_dom, id, node_state);
855

            
856
        taffy_style.max_size = Size {
857
129177
            width: match max_width_css {
858
129167
                MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => Dimension::auto(),
859
10
                MultiValue::Exact(v) => pixel_to_lp(v.inner).into(),
860
            },
861
129177
            height: match max_height_css {
862
129177
                MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => Dimension::auto(),
863
                MultiValue::Exact(v) => pixel_to_lp(v.inner).into(),
864
            },
865
        };
866

            
867
        // Box Model (margin, padding, border)
868
129177
        let margin_left_css = get_css_margin_left(styled_dom, id, node_state);
869
129177
        let margin_right_css = get_css_margin_right(styled_dom, id, node_state);
870
129177
        let margin_top_css = get_css_margin_top(styled_dom, id, node_state);
871
129177
        let margin_bottom_css = get_css_margin_bottom(styled_dom, id, node_state);
872

            
873
        // `em`/`rem` against THIS node's font size (the UA `<p>` margin is
874
        // `1em`; resolving it against the 16 px constant gave an 11 px label
875
        // 16 px margins).
876
129177
        taffy_style.margin = Rect {
877
129177
            left: multi_value_to_lpa_margin_ctx(margin_left_css, em_size, rem_size),
878
129177
            right: multi_value_to_lpa_margin_ctx(margin_right_css, em_size, rem_size),
879
129177
            top: multi_value_to_lpa_margin_ctx(margin_top_css, em_size, rem_size),
880
129177
            bottom: multi_value_to_lpa_margin_ctx(margin_bottom_css, em_size, rem_size),
881
129177
        };
882

            
883
129177
        taffy_style.padding = Rect {
884
129177
            left: multi_value_to_lp_ctx(
885
129177
                get_css_padding_left(styled_dom, id, node_state),
886
129177
                em_size,
887
129177
                rem_size,
888
129177
            ),
889
129177
            right: multi_value_to_lp_ctx(
890
129177
                get_css_padding_right(styled_dom, id, node_state),
891
129177
                em_size,
892
129177
                rem_size,
893
129177
            ),
894
129177
            top: multi_value_to_lp_ctx(
895
129177
                get_css_padding_top(styled_dom, id, node_state),
896
129177
                em_size,
897
129177
                rem_size,
898
129177
            ),
899
129177
            bottom: multi_value_to_lp_ctx(
900
129177
                get_css_padding_bottom(styled_dom, id, node_state),
901
129177
                em_size,
902
129177
                rem_size,
903
129177
            ),
904
129177
        };
905

            
906
129177
        taffy_style.border = Rect {
907
129177
            left: multi_value_to_lp_ctx(
908
129177
                get_css_border_left_width(styled_dom, id, node_state),
909
129177
                em_size,
910
129177
                rem_size,
911
129177
            ),
912
129177
            right: multi_value_to_lp_ctx(
913
129177
                get_css_border_right_width(styled_dom, id, node_state),
914
129177
                em_size,
915
129177
                rem_size,
916
129177
            ),
917
129177
            top: multi_value_to_lp_ctx(
918
129177
                get_css_border_top_width(styled_dom, id, node_state),
919
129177
                em_size,
920
129177
                rem_size,
921
129177
            ),
922
129177
            bottom: multi_value_to_lp_ctx(
923
129177
                get_css_border_bottom_width(styled_dom, id, node_state),
924
129177
                em_size,
925
129177
                rem_size,
926
129177
            ),
927
129177
        };
928

            
929
        // Grid & gap properties — COMPACT FAST PATH: row_gap/column_gap are
930
        // i16 px × 10 in tier2_dims. The slow-path lookup would walk the
931
        // cascade for every node even though the answer is already encoded.
932
129177
        taffy_style.gap = cache.compact_cache.as_ref().map_or_else(
933
            || {
934
                cache
935
                    .get_property(node_data, &id, node_state, &CssPropertyType::Gap)
936
                    .and_then(|p| {
937
                        if let CssProperty::Gap(v) = p {
938
                            Some(v)
939
                        } else {
940
                            None
941
                        }
942
                    })
943
                    .map_or_else(Size::zero, |v| {
944
                        let val = v.get_property_or_default().unwrap_or_default().inner;
945
                        let gap_lp = pixel_to_lp(val);
946
                        Size {
947
                            width: gap_lp,
948
                            height: gap_lp,
949
                        }
950
                    })
951
            },
952
129177
            |cc| {
953
129177
                let row = cc.tier2_dims[id.index()].row_gap;
954
129177
                let col = cc.tier2_dims[id.index()].column_gap;
955
258354
                let decode = |raw: i16| -> LengthPercentage {
956
258354
                    if raw >= azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
957
                        LengthPercentage::length(0.0)
958
                    } else {
959
258354
                        LengthPercentage::length(f32::from(raw) / 10.0)
960
                    }
961
258354
                };
962
129177
                Size {
963
129177
                    width: decode(col),
964
129177
                    height: decode(row),
965
129177
                }
966
129177
            },
967
        );
968

            
969
        // Skip grid properties when not in a grid context.
970
        // Grid container props: only if this node has display:grid.
971
        // Grid item props: only if parent has display:grid.
972
129177
        let (self_is_grid, parent_is_grid) =
973
129177
            cache.compact_cache.as_ref().map_or((false, false), |cc| {
974
                #[allow(clippy::wildcard_imports)]
975
                // widget/render module pulls in the css property/value types it builds with
976
                use azul_css::compact_cache::*;
977
129177
                let self_t1 = cc.tier1_enums[id.index()];
978
129177
                let self_display = ((self_t1 >> DISPLAY_SHIFT) & DISPLAY_MASK) as u8;
979
129177
                let grid_val = layout_display_to_u8(LayoutDisplay::Grid);
980
129177
                let self_grid = self_display == grid_val;
981

            
982
129177
                let parent_idx = styled_dom.node_hierarchy.as_ref()[id.index()]
983
129177
                    .parent_id()
984
129177
                    .map_or(0, |p| p.index());
985
129177
                let parent_t1 = cc.tier1_enums[parent_idx];
986
129177
                let parent_display = ((parent_t1 >> DISPLAY_SHIFT) & DISPLAY_MASK) as u8;
987
129177
                let parent_grid = parent_display == grid_val;
988
129177
                (self_grid, parent_grid)
989
129177
            });
990

            
991
129177
        if self_is_grid {
992
30
            taffy_style.grid_template_rows = cache
993
30
                .get_property(
994
30
                    node_data,
995
30
                    &id,
996
30
                    node_state,
997
30
                    &CssPropertyType::GridTemplateRows,
998
30
                )
999
30
                .and_then(|p| {
30
                    if let CssProperty::GridTemplateRows(v) = p {
30
                        Some(v.clone())
                    } else {
                        None
                    }
30
                })
30
                .map(grid_template_rows_to_taffy)
30
                .unwrap_or_default();
            // Grid template columns - convert GridTemplate to Vec<GridTemplateComponent>
30
            taffy_style.grid_template_columns = cache
30
                .get_property(
30
                    node_data,
30
                    &id,
30
                    node_state,
30
                    &CssPropertyType::GridTemplateColumns,
30
                )
30
                .and_then(|p| {
30
                    if let CssProperty::GridTemplateColumns(v) = p {
30
                        Some(v.clone())
                    } else {
                        None
                    }
30
                })
30
                .map(grid_template_columns_to_taffy)
30
                .unwrap_or_default();
            // Grid template areas - convert GridTemplateAreas to
            // Vec<taffy::GridTemplateArea<String>>
30
            taffy_style.grid_template_areas = cache
30
                .get_property(
30
                    node_data,
30
                    &id,
30
                    node_state,
30
                    &CssPropertyType::GridTemplateAreas,
30
                )
30
                .and_then(|p| {
10
                    if let CssProperty::GridTemplateAreas(v) = p {
10
                        v.get_property().cloned()
                    } else {
                        None
                    }
10
                })
30
                .map(|areas| {
10
                    areas
10
                        .areas
10
                        .as_ref()
10
                        .iter()
10
                        .map(|a| taffy::GridTemplateArea {
50
                            name: a.name.as_str().to_string(),
50
                            row_start: a.row_start,
50
                            row_end: a.row_end,
50
                            column_start: a.column_start,
50
                            column_end: a.column_end,
50
                        })
10
                        .collect::<Vec<_>>()
10
                })
30
                .unwrap_or_default();
30
            taffy_style.grid_auto_rows = cache
30
                .get_property(node_data, &id, node_state, &CssPropertyType::GridAutoRows)
30
                .and_then(|p| {
                    if let CssProperty::GridAutoRows(v) = p {
                        Some(v.clone())
                    } else {
                        None
                    }
                })
30
                .map(grid_auto_rows_to_taffy)
30
                .unwrap_or_default();
30
            taffy_style.grid_auto_columns = cache
30
                .get_property(
30
                    node_data,
30
                    &id,
30
                    node_state,
30
                    &CssPropertyType::GridAutoColumns,
30
                )
30
                .and_then(|p| {
                    if let CssProperty::GridAutoColumns(v) = p {
                        Some(v.clone())
                    } else {
                        None
                    }
                })
30
                .map(grid_auto_columns_to_taffy)
30
                .unwrap_or_default();
30
            taffy_style.grid_auto_flow = cache.compact_cache.as_ref().map_or_else(
                || {
                    cache
                        .get_property(node_data, &id, node_state, &CssPropertyType::GridAutoFlow)
                        .and_then(|p| {
                            if let CssProperty::GridAutoFlow(v) = p {
                                Some(*v)
                            } else {
                                None
                            }
                        })
                        .map(grid_auto_flow_to_taffy)
                        .unwrap_or_default()
                },
30
                |cc| {
                    #[allow(clippy::wildcard_imports)]
                    // widget/render module pulls in the css property/value types it builds
                    // with
                    use azul_css::compact_cache::*;
30
                    let bits = ((cc.tier1_enums[id.index()] >> GRID_AUTO_FLOW_SHIFT)
30
                        & GRID_AUTO_FLOW_MASK) as u8;
30
                    let val = layout_grid_auto_flow_from_u8(bits);
30
                    grid_auto_flow_to_taffy(CssPropertyValue::Exact(val))
30
                },
            );
129147
        } // end if self_is_grid
129177
        if parent_is_grid {
            // Grid item placement. The compact cold cache holds Auto/Line/Span as
            // an i16; NAMED lines and areas (`grid-area: header`) cannot be
            // encoded there and are stored as I16_SENTINEL — for those the REAL
            // property must be consulted, per axis. Decoding the sentinel as
            // Auto silently discarded every named placement, which auto-flowed
            // all grid-template-areas layouts (grid-template-areas-001).
110
            let slow_grid_column = || {
50
                cache
50
                    .get_property(node_data, &id, node_state, &CssPropertyType::GridColumn)
50
                    .and_then(|p| {
50
                        if let CssProperty::GridColumn(v) = p {
50
                            v.get_property().cloned()
                        } else {
                            None
                        }
50
                    })
50
            };
110
            let slow_grid_row = || {
50
                cache
50
                    .get_property(node_data, &id, node_state, &CssPropertyType::GridRow)
50
                    .and_then(|p| {
50
                        if let CssProperty::GridRow(v) = p {
50
                            v.get_property().cloned()
                        } else {
                            None
                        }
50
                    })
50
            };
110
            if let Some(cc) = cache.compact_cache.as_ref() {
                use azul_css::compact_cache::{I16_AUTO, I16_SENTINEL};
110
                let cold = &cc.tier2_cold[id.index()];
110
                let (cs, ce) = (cold.grid_col_start, cold.grid_col_end);
110
                if cs == I16_SENTINEL || ce == I16_SENTINEL {
50
                    if let Some(grid_col) = slow_grid_column() {
50
                        taffy_style.grid_column = grid_placement_to_taffy(&grid_col);
50
                    }
60
                } else if cs != I16_AUTO || ce != I16_AUTO {
                    taffy_style.grid_column = Line {
                        start: decode_compact_grid_line(cs),
                        end: decode_compact_grid_line(ce),
                    };
60
                }
110
                let (rs, re) = (cold.grid_row_start, cold.grid_row_end);
110
                if rs == I16_SENTINEL || re == I16_SENTINEL {
50
                    if let Some(grid_row) = slow_grid_row() {
50
                        taffy_style.grid_row = grid_placement_to_taffy(&grid_row);
50
                    }
60
                } else if rs != I16_AUTO || re != I16_AUTO {
                    taffy_style.grid_row = Line {
                        start: decode_compact_grid_line(rs),
                        end: decode_compact_grid_line(re),
                    };
60
                }
            } else {
                if let Some(grid_col) = slow_grid_column() {
                    taffy_style.grid_column = grid_placement_to_taffy(&grid_col);
                }
                if let Some(grid_row) = slow_grid_row() {
                    taffy_style.grid_row = grid_placement_to_taffy(&grid_row);
                }
            }
129067
        } // end if parent_is_grid
        // Flexbox
129177
        taffy_style.flex_direction = match get_flex_direction(styled_dom, id, node_state) {
129174
            MultiValue::Exact(v) => layout_flex_direction_to_taffy(CssPropertyValue::Exact(v)),
3
            _ => FlexDirection::Row,
        };
        // COMPACT FAST PATH: flex_wrap is Tier 1 enum
        taffy_style.flex_wrap = {
129177
            let compact = if node_state.is_normal() {
129174
                cache.compact_cache.as_ref().map(|cc| {
129174
                    layout_flex_wrap_to_taffy(CssPropertyValue::Exact(cc.get_flex_wrap(id.index())))
129174
                })
            } else {
3
                None
            };
129177
            compact.unwrap_or_else(|| {
3
                cache
3
                    .get_property(node_data, &id, node_state, &CssPropertyType::FlexWrap)
3
                    .and_then(|p| {
                        if let CssProperty::FlexWrap(v) = p {
                            Some(*v)
                        } else {
                            None
                        }
                    })
3
                    .map_or(FlexWrap::NoWrap, layout_flex_wrap_to_taffy)
3
            })
        };
129177
        taffy_style.align_items = match get_align_items(styled_dom, id, node_state) {
129174
            MultiValue::Exact(v) => Some(layout_align_items_to_taffy(CssPropertyValue::Exact(v))),
3
            _ => None,
        };
        // CSS spec: default align-items is "normal" which acts like "stretch"
        // for non-replaced grid/flex items. Taffy handles this internally when
        // align_items is None, so we should NOT force a default here.
129177
        taffy_style.justify_items = cache.compact_cache.as_ref().map_or_else(
            || {
                cache
                    .get_property(node_data, &id, node_state, &CssPropertyType::JustifyItems)
                    .and_then(|p| {
                        if let CssProperty::JustifyItems(v) = p {
                            Some(*v)
                        } else {
                            None
                        }
                    })
                    .map(layout_justify_items_to_taffy)
            },
129177
            |cc| {
                #[allow(clippy::wildcard_imports)]
                // widget/render module pulls in the css property/value types it builds with
                use azul_css::compact_cache::*;
                use azul_css::props::layout::grid::LayoutJustifyItems;
129177
                let bits = ((cc.tier1_enums[id.index()] >> JUSTIFY_ITEMS_SHIFT)
129177
                    & JUSTIFY_ITEMS_MASK) as u8;
129177
                let val = layout_justify_items_from_u8(bits);
129177
                Some(match val {
                    LayoutJustifyItems::Start => AlignItems::Start,
                    LayoutJustifyItems::End => AlignItems::End,
                    LayoutJustifyItems::Center => AlignItems::Center,
129177
                    LayoutJustifyItems::Stretch => AlignItems::Stretch,
                })
129177
            },
        );
        // COMPACT FAST PATH: justify-content is in tier1 bits 21-23.
129177
        taffy_style.justify_content = cache.compact_cache.as_ref().map_or_else(
            || {
                cache
                    .get_property(node_data, &id, node_state, &CssPropertyType::JustifyContent)
                    .and_then(|p| {
                        if let CssProperty::JustifyContent(v) = p {
                            Some(v)
                        } else {
                            None
                        }
                    })
                    .map(|v| layout_justify_content_to_taffy(*v))
            },
129177
            |cc| {
                #[allow(clippy::wildcard_imports)]
                // widget/render module pulls in the css property/value types it builds with
                use azul_css::compact_cache::*;
                use azul_css::props::layout::LayoutJustifyContent;
129177
                let bits =
129177
                    ((cc.tier1_enums[id.index()] >> JUSTIFY_CONTENT_SHIFT) & JUSTIFY_MASK) as u8;
129177
                Some(match layout_justify_content_from_u8(bits) {
119023
                    LayoutJustifyContent::FlexStart => JustifyContent::FlexStart,
                    LayoutJustifyContent::FlexEnd => JustifyContent::FlexEnd,
                    LayoutJustifyContent::Start => JustifyContent::Start,
                    LayoutJustifyContent::End => JustifyContent::End,
10094
                    LayoutJustifyContent::Center => JustifyContent::Center,
60
                    LayoutJustifyContent::SpaceBetween => JustifyContent::SpaceBetween,
                    LayoutJustifyContent::SpaceAround => JustifyContent::SpaceAround,
                    LayoutJustifyContent::SpaceEvenly => JustifyContent::SpaceEvenly,
                })
129177
            },
        );
        // CSS spec: default justify-content is "normal". Taffy handles
        // this internally when justify_content is None.
        // COMPACT FAST PATH: flex_grow stored as u16 × 100
        taffy_style.flex_grow = {
129177
            let compact = if node_state.is_normal() {
129174
                cache
129174
                    .compact_cache
129174
                    .as_ref()
129174
                    .and_then(|cc| cc.get_flex_grow(id.index()))
            } else {
3
                None
            };
129177
            compact.unwrap_or_else(|| {
3
                cache
3
                    .get_property(node_data, &id, node_state, &CssPropertyType::FlexGrow)
3
                    .and_then(|p| {
                        if let CssProperty::FlexGrow(v) = p {
                            Some(v.get_property_or_default().unwrap_or_default().inner.get())
                        } else {
                            None
                        }
                    })
3
                    .unwrap_or(0.0)
3
            })
        };
        // COMPACT FAST PATH: flex_shrink stored as u16 × 100
        taffy_style.flex_shrink = {
129177
            let compact = if node_state.is_normal() {
129174
                cache
129174
                    .compact_cache
129174
                    .as_ref()
129174
                    .and_then(|cc| cc.get_flex_shrink(id.index()))
            } else {
3
                None
            };
129177
            compact.unwrap_or_else(|| {
3
                cache
3
                    .get_property(node_data, &id, node_state, &CssPropertyType::FlexShrink)
3
                    .and_then(|p| {
                        if let CssProperty::FlexShrink(v) = p {
                            Some(v.get_property_or_default().unwrap_or_default().inner.get())
                        } else {
                            None
                        }
                    })
3
                    .unwrap_or(1.0)
3
            })
        };
        // COMPACT FAST PATH: flex_basis stored as u32 with PixelValue encoding
        taffy_style.flex_basis = {
129177
            let compact = if node_state.is_normal() {
129174
                cache.compact_cache.as_ref().and_then(|cc| {
129174
                    let raw = cc.get_flex_basis_raw(id.index());
129174
                    match raw {
                        azul_css::compact_cache::U32_AUTO
                        | azul_css::compact_cache::U32_NONE
129141
                        | azul_css::compact_cache::U32_INITIAL => Some(Dimension::auto()),
                        azul_css::compact_cache::U32_SENTINEL
                        | azul_css::compact_cache::U32_INHERIT => None,
                        _ => {
33
                            if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
33
                                let basis = pixel_value_to_pixels_fallback(&pv)
33
                                    .map(Dimension::length)
33
                                    .or_else(|| {
                                        pv.to_percent().map(|p| Dimension::percent(p.get()))
                                    })
33
                                    .unwrap_or_else(Dimension::auto);
33
                                if !matches!(basis, auto if auto == Dimension::auto()) {
33
                                    taffy_style.size.width = Dimension::auto();
33
                                }
33
                                Some(basis)
                            } else {
                                Some(Dimension::auto())
                            }
                        }
                    }
129174
                })
            } else {
3
                None
            };
129177
            compact.unwrap_or_else(|| {
3
                flex_basis_slow_path(cache, node_data, &id, node_state, &mut taffy_style)
3
            })
        };
129177
        taffy_style.align_self = cache.compact_cache.as_ref().map_or_else(
            || {
                cache
                    .get_property(node_data, &id, node_state, &CssPropertyType::AlignSelf)
                    .and_then(|p| {
                        if let CssProperty::AlignSelf(v) = p {
                            layout_align_self_to_taffy(*v)
                        } else {
                            None
                        }
                    })
            },
129177
            |cc| {
                #[allow(clippy::wildcard_imports)]
                // widget/render module pulls in the css property/value types it builds with
                use azul_css::compact_cache::*;
129177
                let bits =
129177
                    ((cc.tier1_enums[id.index()] >> ALIGN_SELF_SHIFT) & ALIGN_SELF_MASK) as u8;
129177
                let val = layout_align_self_from_u8(bits);
129177
                match val {
128567
                    LayoutAlignSelf::Auto => None,
69
                    LayoutAlignSelf::Start => Some(AlignSelf::FlexStart),
10
                    LayoutAlignSelf::End => Some(AlignSelf::FlexEnd),
530
                    LayoutAlignSelf::Center => Some(AlignSelf::Center),
                    LayoutAlignSelf::Baseline => Some(AlignSelf::Baseline),
1
                    LayoutAlignSelf::Stretch => Some(AlignSelf::Stretch),
                }
129177
            },
        );
129177
        taffy_style.justify_self = cache.compact_cache.as_ref().map_or_else(
            || {
                cache
                    .get_property(node_data, &id, node_state, &CssPropertyType::JustifySelf)
                    .and_then(|p| {
                        if let CssProperty::JustifySelf(v) = p {
                            use azul_css::props::layout::grid::LayoutJustifySelf;
                            match v.get_property_or_default().unwrap_or_default() {
                                LayoutJustifySelf::Auto => None,
                                LayoutJustifySelf::Start => Some(AlignSelf::Start),
                                LayoutJustifySelf::End => Some(AlignSelf::End),
                                LayoutJustifySelf::Center => Some(AlignSelf::Center),
                                LayoutJustifySelf::Stretch => Some(AlignSelf::Stretch),
                            }
                        } else {
                            None
                        }
                    })
            },
129177
            |cc| {
                #[allow(clippy::wildcard_imports)]
                // widget/render module pulls in the css property/value types it builds with
                use azul_css::compact_cache::*;
                use azul_css::props::layout::grid::LayoutJustifySelf;
129177
                let bits =
129177
                    ((cc.tier1_enums[id.index()] >> JUSTIFY_SELF_SHIFT) & JUSTIFY_SELF_MASK) as u8;
129177
                let val = layout_justify_self_from_u8(bits);
129177
                match val {
129177
                    LayoutJustifySelf::Auto => None,
                    LayoutJustifySelf::Start => Some(AlignSelf::Start),
                    LayoutJustifySelf::End => Some(AlignSelf::End),
                    LayoutJustifySelf::Center => Some(AlignSelf::Center),
                    LayoutJustifySelf::Stretch => Some(AlignSelf::Stretch),
                }
129177
            },
        );
129177
        taffy_style.align_content = match get_align_content(styled_dom, id, node_state) {
129174
            MultiValue::Exact(v) => Some(layout_align_content_to_taffy(CssPropertyValue::Exact(v))),
3
            _ => None,
        };
        // CSS spec: default align-content is "normal". Taffy handles
        // this internally when align_content is None.
129177
        taffy_style
129177
    }
    /// Gets or computes the Taffy style for a given node index.
5353288
    fn get_taffy_style(&self, node_idx: usize) -> Style {
5353288
        let dom_id = self
5353288
            .tree
5353288
            .get(LayoutNodeId::new(node_idx))
5353288
            .and_then(|n| n.dom_node_id);
5353288
        let mut style = self.translate_style_to_taffy_cached(dom_id);
        // CSS 2.1 § 10.3.3: Root element margin handling for Flex/Grid.
        //
        // The root element's margin is already resolved and subtracted from
        // available_size by calculate_used_size_for_node() (sizing.rs). The
        // resulting margin-adjusted size is passed to Taffy as known_dimensions.
        //
        // Taffy's layout algorithm reads margin from the style and subtracts it
        // from known_dimensions internally. If we also pass the margin through
        // the style, it gets subtracted twice:
        //   1. calculate_used_size_for_node: viewport - margin → available_size
        //   2. Taffy: known_dimensions - style.margin → content_area
        //
        // Zeroing the style margin for root nodes prevents this double-subtraction.
        // This is NOT a hack — it's the correct integration point between Azul's
        // BFC-level sizing and Taffy's Flex/Grid algorithm.
5353288
        let is_root = self
5353288
            .tree
5353288
            .get(LayoutNodeId::new(node_idx))
5353288
            .is_some_and(|n| n.parent.is_none());
5353288
        if is_root {
2556
            style.margin = Rect::zero();
5350732
        }
        // FIX: Apply cross-axis intrinsic size suppression for stretch alignment.
        // This enables align-self: stretch to work correctly by ensuring Taffy
        // sees the cross-axis size as Auto (allowing stretch) rather than a definite value.
5353288
        let (suppress_width, suppress_height) =
5353288
            self.should_suppress_cross_intrinsic(node_idx, &style);
5353288
        if suppress_width {
778169
            // Force width to Auto and set min-width to 0 to allow stretching.
778169
            // Taffy treats Auto size + Stretch alignment as a signal to fill the container.
778169
            style.size.width = Dimension::auto();
778169
            style.min_size.width = Dimension::length(0.0);
4575119
        }
5353288
        if suppress_height {
948376
            style.size.height = Dimension::auto();
948376
            style.min_size.height = Dimension::length(0.0);
4404912
        }
5353288
        style
5353288
    }
    /// The node's explicit PIXEL `min-height` / `max-height` in BORDER-BOX terms
    /// (`None` for auto / percent / calc — those stay taffy's business). Read
    /// from the memoised taffy style, so it is exactly what taffy was told.
226191
    fn own_px_height_bounds(
226191
        &self,
226191
        node_idx: usize,
226191
        padding_border_height: f32,
226191
    ) -> (Option<f32>, Option<f32>) {
226191
        let dom_id = self
226191
            .tree
226191
            .get(LayoutNodeId::new(node_idx))
226191
            .and_then(|n| n.dom_node_id);
226191
        let style = self.translate_style_to_taffy_cached(dom_id);
        // `min-height` on a content-box node bounds the CONTENT box.
226191
        let extra = if style.box_sizing == BoxSizing::ContentBox {
225151
            padding_border_height
        } else {
1040
            0.0
        };
452382
        let px = |d: Dimension| -> Option<f32> {
452382
            let raw = d.into_raw();
452382
            (raw.tag() == CompactLength::LENGTH_TAG && raw.value().is_finite())
452382
                .then(|| raw.value() + extra)
452382
        };
226191
        (px(style.min_size.height), px(style.max_size.height))
226191
    }
    /// Determines if cross-axis intrinsic size should be suppressed for stretching.
    ///
    /// Per CSS Flexbox spec, align-items: stretch makes items fill the cross-axis
    /// ONLY if the item's cross-size is 'auto' AND the item has no intrinsic cross-size.
    ///
    /// Returns (`suppress_width`, `suppress_height`) booleans.
    #[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input
                                      // variant (or cross-type bindings that can't merge)
5353288
    fn should_suppress_cross_intrinsic(&self, node_idx: usize, style: &Style) -> (bool, bool) {
5353288
        let Some(node) = self.tree.get(LayoutNodeId::new(node_idx)) else {
            return (false, false);
        };
        // Check if parent is a flex or grid container
5353288
        let Some(parent_fc) = self
5353288
            .tree
5353288
            .warm(LayoutNodeId::new(node_idx))
5353288
            .and_then(|w| w.parent_formatting_context)
        else {
2556
            return (false, false);
        };
5350732
        match parent_fc {
            FormattingContext::Flex => {
                // Get parent node to check its flex-direction and align-items
5342533
                let Some(parent_idx) = node.parent else {
                    return (false, false);
                };
5342533
                let parent_dom_id = self
5342533
                    .tree
5342533
                    .get(LayoutNodeId::new(parent_idx))
5342533
                    .and_then(|n| n.dom_node_id);
5342533
                let parent_style = self.translate_style_to_taffy_cached(parent_dom_id);
                // Determine if flex container is row or column
5342533
                let is_row = matches!(
5342533
                    parent_style.flex_direction,
                    FlexDirection::Row | FlexDirection::RowReverse
                );
                // Get effective align value for this item
                // align-self overrides parent's align-items
5342533
                let align = style
5342533
                    .align_self
5342533
                    .or(parent_style.align_items)
5342533
                    .unwrap_or(AlignSelf::Stretch);
5342533
                let should_stretch = matches!(align, AlignSelf::Stretch);
5342533
                if !should_stretch {
3434146
                    return (false, false);
1908387
                }
                // Check if cross-axis size is auto
                // For row flex: cross-axis is height
                // For column flex: cross-axis is width
1908387
                let cross_size_is_auto = if is_row {
1030090
                    style.size.height == Dimension::auto()
                } else {
878297
                    style.size.width == Dimension::auto()
                };
1908387
                if !cross_size_is_auto {
181842
                    return (false, false);
1726545
                }
                // All conditions met: suppress intrinsic cross-size
1726545
                if is_row {
948376
                    (false, true) // Suppress height for row flex
                } else {
778169
                    (true, false) // Suppress width for column flex
                }
            }
            FormattingContext::Grid => {
                // TODO: Implement grid stretch detection
                // Grid is more complex because:
                // 1. Default align-items is 'start', not 'stretch'
                // 2. Items can stretch in both axes simultaneously
                // 3. Need to check grid-auto-flow and track sizing
1400
                (false, false)
            }
6799
            _ => (false, false),
        }
5353288
    }
    /// Helper to get children that participate in layout (i.e., not `display: none`).
789628
    fn get_layout_children(&self, node_idx: usize) -> Vec<usize> {
        use crate::solver3::getters::{get_display_property, MultiValue};
789628
        let Some(node) = self.tree.get(LayoutNodeId::new(node_idx)) else {
            return Vec::new();
        };
789628
        self.tree
789628
            .children(node_idx)
789628
            .iter()
1672119
            .filter(|&&child_idx| {
1672119
                let Some(child_node) = self.tree.get(LayoutNodeId::new(child_idx)) else {
                    return false;
                };
1672119
                let Some(child_dom_id) = child_node.dom_node_id else {
                    return true;
                };
                // Check if child has display: none
1672119
                let display = get_display_property(self.ctx.styled_dom, Some(child_dom_id));
1672119
                let is_display_none = matches!(display, MultiValue::Exact(LayoutDisplay::None));
1672119
                !is_display_none
1672119
            })
789628
            .copied()
789628
            .collect()
789628
    }
}
/// Main entry point for laying out a Flexbox or Grid container using Taffy.
///
/// This function now accepts a `text_cache` parameter so that IFC layout can be
/// performed inline during Taffy's measure callbacks, rather than as a post-processing step.
/// # Panics
///
/// Panics if `node_idx` is not present in the layout tree.
3714
pub fn layout_taffy_subtree<T: ParsedFontTrait>(
3714
    ctx: &mut LayoutContext<'_, T>,
3714
    tree: &mut LayoutTree,
3714
    text_cache: &mut crate::font_traits::TextLayoutCache,
3714
    node_idx: usize,
3714
    inputs: LayoutInput,
3714
) -> LayoutOutput {
3714
    let children: Vec<usize> = tree.children(node_idx).to_vec();
    // DEBUG: Log Taffy inputs
3714
    if ctx.debug_messages.is_some() {
3287
        ctx.debug_info_inner(format!(
3287
            "[TAFFY INPUT] node_idx={} known_dims=({:?}, {:?}) available=({:?}, {:?}) \
3287
             parent_size=({:?}, {:?}) children={:?}",
3287
            node_idx,
3287
            inputs.known_dimensions.width,
3287
            inputs.known_dimensions.height,
3287
            inputs.available_space.width,
3287
            inputs.available_space.height,
3287
            inputs.parent_size.width,
3287
            inputs.parent_size.height,
3287
            children
3287
        ));
3300
    }
    // NOTE (2026-08-08): the unconditional "clear every child's taffy_cache
    // to force re-measure" that used to live here (Nov 2025, pre-reconcile)
    // is GONE. Dirty-driven invalidation now happens once per pass in
    // layout_document Step 1.2 over the ancestor closure of
    // `intrinsic_dirty`; everything else is covered by taffy's own
    // (known_dimensions, available_space, run_mode) cache key. The hammer
    // was re-running full min/max-content subtree layouts for every flex
    // child on every pass — 312 of them per steady-state resize on big.md,
    // each re-breaking every IFC line in the subtree — and, worse, each
    // measure STORE evicted the Definite entry in the single-slot IFC cache
    // (`should_replace_with`: width type changed), so the final pass
    // re-flowed the text AGAIN. Measured: root_layout_pass 25.5 ms → see
    // scripts/ for the after numbers.
    // SAFETY: We pass text_cache as a raw pointer because TaffyBridge needs to call
    // layout_ifc from within compute_child_layout, but we already have &mut ctx and &mut tree.
    // The pointer is only valid for the duration of this function call.
3714
    let text_cache_ptr = core::ptr::from_mut::<crate::font_traits::TextLayoutCache>(text_cache);
3714
    let mut bridge = TaffyBridge::new(ctx, tree, text_cache_ptr);
3714
    let node = bridge.tree.get(LayoutNodeId::new(node_idx)).unwrap();
3714
    let output = match node.formatting_context {
3664
        FormattingContext::Flex => compute_flexbox_layout(&mut bridge, node_idx.into(), inputs),
50
        FormattingContext::Grid => compute_grid_layout(&mut bridge, node_idx.into(), inputs),
        _ => LayoutOutput::HIDDEN,
    };
    // DEBUG: Log Taffy output
3714
    if bridge.ctx.debug_messages.is_some() {
3287
        bridge.ctx.debug_info_inner(format!(
3287
            "[TAFFY OUTPUT] node_idx={} output_size=({:?}, {:?})",
            node_idx, output.size.width, output.size.height
        ));
        // Log child layout results
9319
        for &child_idx in &children {
6032
            if let Some(child) = bridge.tree.get(LayoutNodeId::new(child_idx)) {
6032
                bridge.ctx.debug_info_inner(format!(
6032
                    "[TAFFY CHILD RESULT] child_idx={} used_size={:?} relative_pos={:?}",
                    child_idx,
                    child.used_size,
6032
                    bridge
6032
                        .tree
6032
                        .warm(LayoutNodeId::new(child_idx))
6032
                        .and_then(|w| w.relative_position)
                ));
            }
        }
427
    }
3714
    output
3714
}
// --- Trait Implementations for the Bridge ---
impl<T: ParsedFontTrait> TraversePartialTree for TaffyBridge<'_, '_, T> {
    type ChildIter<'c>
        = std::vec::IntoIter<taffy::NodeId>
    where
        Self: 'c;
406986
    fn child_ids(&self, node_id: taffy::NodeId) -> Self::ChildIter<'_> {
406986
        let node_idx: usize = node_id.into();
406986
        let children = self.get_layout_children(node_idx);
406986
        children
406986
            .into_iter()
406986
            .map(Into::into)
406986
            .collect::<Vec<taffy::NodeId>>()
406986
            .into_iter()
406986
    }
131846
    fn child_count(&self, node_id: taffy::NodeId) -> usize {
131846
        let node_idx: usize = node_id.into();
131846
        self.get_layout_children(node_idx).len()
131846
    }
250796
    fn get_child_id(&self, node_id: taffy::NodeId, index: usize) -> taffy::NodeId {
250796
        self.get_layout_children(node_id.into())[index].into()
250796
    }
}
impl<T: ParsedFontTrait> LayoutPartialTree for TaffyBridge<'_, '_, T> {
    type CoreContainerStyle<'c>
        = Style
    where
        Self: 'c;
    type CustomIdent = String;
3358798
    fn get_core_container_style(&self, node_id: taffy::NodeId) -> Self::CoreContainerStyle<'_> {
3358798
        let node_idx: usize = node_id.into();
        // Use get_taffy_style instead of translate_style_to_taffy to apply
        // cross-axis intrinsic suppression for stretch alignment
3358798
        self.get_taffy_style(node_idx)
3358798
    }
125463
    fn set_unrounded_layout(&mut self, node_id: taffy::NodeId, layout: &Layout) {
125463
        let node_idx: usize = node_id.into();
        // FIX: Retrieve parent border/padding to adjust position.
        // Taffy positions are relative to the parent's Border Box origin.
        // Azul expects positions relative to the parent's Content Box origin.
        // We must subtract the parent's border and padding from the Taffy-returned position.
125463
        let (parent_border_left, parent_border_top, parent_padding_left, parent_padding_top) = {
125463
            if let Some(child) = self.tree.get(LayoutNodeId::new(node_idx)) {
125463
                if let Some(parent_idx) = child.parent {
125463
                    self.tree.get(LayoutNodeId::new(parent_idx)).map_or(
125463
                        (0.0, 0.0, 0.0, 0.0),
125463
                        |parent| {
125463
                            let pbp = parent.box_props.unpack();
125463
                            (
125463
                                pbp.border.left,
125463
                                pbp.border.top,
125463
                                pbp.padding.left,
125463
                                pbp.padding.top,
125463
                            )
125463
                        },
                    )
                } else {
                    (0.0, 0.0, 0.0, 0.0)
                }
            } else {
                (0.0, 0.0, 0.0, 0.0)
            }
        };
125463
        if let Some(node) = self.tree.get_mut(LayoutNodeId::new(node_idx)) {
125463
            let size = translate_taffy_size_back(layout.size);
125463
            let mut pos = translate_taffy_point_back(layout.location);
            // DEBUG: Log Taffy's raw layout result before adjustment
125463
            if self.ctx.debug_messages.is_some() {
124042
                self.ctx.debug_info_inner(format!(
124042
                    "[TAFFY set_unrounded_layout] node_idx={} taffy_size=({:.2}, {:.2}) \
124042
                     taffy_pos=({:.2}, {:.2}) parent_border=({:.2}, {:.2}) parent_padding=({:.2}, \
124042
                     {:.2})",
124042
                    node_idx,
124042
                    layout.size.width,
124042
                    layout.size.height,
124042
                    layout.location.x,
124042
                    layout.location.y,
124042
                    parent_border_left,
124042
                    parent_border_top,
124042
                    parent_padding_left,
124042
                    parent_padding_top
124042
                ));
124058
            }
            // Subtract parent's border and padding offset to convert
            // from border-box-relative to content-box-relative position
125463
            pos.x -= parent_border_left + parent_padding_left;
125463
            pos.y -= parent_border_top + parent_padding_top;
125463
            node.used_size = Some(size);
        }
125463
        if let Some(warm) = self.tree.warm_mut(LayoutNodeId::new(node_idx)) {
125463
            let mut pos = translate_taffy_point_back(layout.location);
125463
            pos.x -= parent_border_left + parent_padding_left;
125463
            pos.y -= parent_border_top + parent_padding_top;
125463
            warm.relative_position = Some(pos);
125463
        }
125463
    }
    fn resolve_calc_value(&self, val: *const (), basis: f32) -> f32 {
        // SAFETY: `val` came from `store_calc_and_make_dimension` which stored
        // a `Box<CalcResolveContext>` in `self.calc_storage`. The Box is alive for
        // the lifetime of this TaffyBridge, and taffy only clears the low 3 bits.
        let ctx = unsafe { &*val.cast::<CalcResolveContext>() };
        crate::solver3::calc::evaluate_calc(ctx, basis)
    }
1999985
    fn compute_child_layout(
1999985
        &mut self,
1999985
        node_id: taffy::NodeId,
1999985
        inputs: LayoutInput,
1999985
    ) -> LayoutOutput {
1999985
        let node_idx: usize = node_id.into();
        // DEBUG: Log the style being used for this child
1999985
        if self.ctx.debug_messages.is_some() {
1994490
            let style = self.get_taffy_style(node_idx);
1994490
            self.ctx.debug_info_inner(format!(
1994490
                "[TAFFY compute_child_layout] node_idx={} flex_grow={} flex_shrink={} \
1994490
                 flex_basis={:?} size=({:?}, {:?}) inputs.known_dims=({:?}, {:?})",
1994490
                node_idx,
1994490
                style.flex_grow,
1994490
                style.flex_shrink,
1994490
                style.flex_basis,
1994490
                style.size.width,
1994490
                style.size.height,
1994490
                inputs.known_dimensions.width,
1994490
                inputs.known_dimensions.height
1994490
            ));
1994564
        }
        // Get formatting context
1999985
        let fc = self
1999985
            .tree
1999985
            .get(LayoutNodeId::new(node_idx))
1999985
            .map(|s| s.formatting_context)
1999985
            .unwrap_or_default();
        // PURE CONTENT MEASURE cache (min-/max-content, no known dimensions).
        // These answers are viewport-independent, but taffy's own cache
        // cannot keep them alive: the flex algorithm's candidate-width
        // probes share their slot class and evict them within every pass.
        // Serve them from the warm node instead — invalidated with
        // `taffy_cache` by the intrinsic-dirty ancestor closure. Gated off
        // for documents that use viewport units (vw/vh in font sizes make
        // "content size" viewport-dependent), mirroring the collect gate.
1999985
        let pure_measure_slot = if inputs.run_mode == RunMode::ComputeSize
1874522
            && inputs.known_dimensions.width.is_none()
1317770
            && inputs.known_dimensions.height.is_none()
937080
            && !self
937080
                .ctx
937080
                .styled_dom
937080
                .css_property_cache
937080
                .ptr
937080
                .compact_cache
937080
                .as_ref()
937080
                .is_none_or(|cc| cc.uses_viewport_units)
        {
937080
            match inputs.available_space.width {
497466
                AvailableSpace::MinContent => Some(0usize),
358884
                AvailableSpace::MaxContent => Some(1usize),
80730
                AvailableSpace::Definite(_) => None,
            }
        } else {
1062905
            None
        };
1999985
        if let Some(slot) = pure_measure_slot {
856350
            if let Some(warm) = self.tree.warm(LayoutNodeId::new(node_idx)) {
856350
                let cached = match slot {
497466
                    0 => warm.measured_content_sizes.0,
358884
                    _ => warm.measured_content_sizes.1,
                };
856350
                if let Some(out) = cached {
709323
                    drop(crate::probe::Probe::span("taffy_pure_measure_hit"));
709323
                    return out;
147027
                }
            }
147027
            drop(crate::probe::Probe::span("taffy_pure_measure_miss"));
1143635
        }
1290662
        let mut result = compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
703335
            let node_idx: usize = node_id.into();
703335
            let fc = tree
703335
                .tree
703335
                .get(LayoutNodeId::new(node_idx))
703335
                .map(|s| s.formatting_context)
703335
                .unwrap_or_default();
703335
            match fc {
403122
                FormattingContext::Flex => compute_flexbox_layout(tree, node_id, inputs),
                FormattingContext::Grid => compute_grid_layout(tree, node_id, inputs),
                // For Block, Inline, Table, InlineBlock - delegate to layout_formatting_context
                // This ensures proper recursive layout of all formatting contexts
300213
                _ => tree.compute_non_flex_layout(node_idx, inputs),
            }
703335
        });
        // Populate the pure-measure cache from the result we just computed.
1290662
        if let Some(slot) = pure_measure_slot {
147027
            if let Some(warm) = self.tree.warm_mut(LayoutNodeId::new(node_idx)) {
147027
                match slot {
73734
                    0 => warm.measured_content_sizes.0 = Some(result),
73293
                    _ => warm.measured_content_sizes.1 = Some(result),
                }
            }
1143635
        }
        // Store layout for container nodes - Taffy only calls set_unrounded_layout for leaf nodes
1290662
        if let Some(node) = self.tree.get_mut(LayoutNodeId::new(node_idx)) {
1290662
            let size = translate_taffy_size_back(result.size);
1290662
            node.used_size = Some(size);
1290662
        }
        // CRITICAL FIX: For Flex/Grid children with overflow:auto/scroll,
        // compute scrollbar_info by comparing Taffy's content_size against the
        // CSS-specified container size.
        //
        // We skip when content_size is (0,0) because that's the sizing pass
        // where Taffy hasn't determined actual content size yet. The final
        // layout pass always has non-zero content_size for nodes that need
        // scroll. This avoids 2/3 of the compute_taffy_scrollbar_info calls
        // (one sizing pass per axis) while still getting correct final values.
1290662
        if matches!(fc, FormattingContext::Flex | FormattingContext::Grid) {
667852
            let taffy_content_width = result.content_size.width;
667852
            let taffy_content_height = result.content_size.height;
            // Skip on sizing pass where content_size is still zero:
            // scrollbar_info computed from zero content would be wrong anyway.
667852
            if taffy_content_width <= 0.0 && taffy_content_height <= 0.0 {
609663
                return result;
58189
            }
58189
            let (scrollbar_info, eff_content_w, eff_content_h) = compute_taffy_scrollbar_info(
58189
                self.ctx,
58189
                self.tree,
58189
                node_idx,
58189
                result.size.width,
58189
                result.size.height,
58189
                taffy_content_width,
58189
                taffy_content_height,
58189
                ContentSizeOrigin::BorderBox,
58189
            );
58189
            if let Some(warm) = self.tree.warm_mut(LayoutNodeId::new(node_idx)) {
58189
                warm.scrollbar_info = Some(scrollbar_info);
58189
                // eff_content_w/h are already in content-box coordinates
58189
                // (the border+padding inset is subtracted in
58189
                // compute_taffy_scrollbar_info), so store directly without
58189
                // further subtraction.
58189
                warm.overflow_content_size = Some(LogicalSize::new(eff_content_w, eff_content_h));
58189
            }
622810
        }
680999
        result
1999985
    }
}
impl<T: ParsedFontTrait> TaffyBridge<'_, '_, T> {
    /// Compute layout for non-flex/grid nodes by delegating to `layout_formatting_context`.
    /// This handles Block, Inline, Table, `InlineBlock` formatting contexts recursively.
    #[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)] // large but cohesive: single-purpose layout/render/parse
                                     // routine (one branch per case)
300213
    fn compute_non_flex_layout(&mut self, node_idx: usize, inputs: LayoutInput) -> LayoutOutput {
        // Taffy's known_dimensions are BORDER-BOX sizes (the child's outer size
        // as determined by the parent flex/grid algorithm, e.g. via stretch alignment).
        // Our BFC/IFC layout expects the available_size to be the CONTENT-BOX width
        // (i.e. the space available for the child's own content, excluding the child's
        // own padding and border).
        //
        // Get padding/border early so we can convert border-box → content-box.
300213
        let (node_padding_width, node_padding_height, node_border_width, node_border_height) = self
300213
            .tree
300213
            .get(LayoutNodeId::new(node_idx))
300213
            .map_or((0.0, 0.0, 0.0, 0.0), |node| {
300213
                let bp = node.box_props.unpack();
300213
                (
300213
                    bp.padding.left + bp.padding.right,
300213
                    bp.padding.top + bp.padding.bottom,
300213
                    bp.border.left + bp.border.right,
300213
                    bp.border.top + bp.border.bottom,
300213
                )
300213
            });
        // Determine available size from Taffy's inputs.
        // When known_dimensions is set (e.g. flex stretch), subtract the child's own
        // padding+border to convert from border-box to content-box available space.
        // For MinContent/MaxContent, use INFINITY and let the text layout calculate
        // its actual intrinsic width.
300213
        let available_width = inputs
300213
            .known_dimensions
300213
            .width
300213
            .map(|kw| (kw - node_padding_width - node_border_width).max(0.0))
300213
            .or(match inputs.available_space.width {
185498
                AvailableSpace::Definite(w) => Some(w),
63854
                AvailableSpace::MinContent => None, // Use infinity, return intrinsic min-content
50861
                AvailableSpace::MaxContent => None, // Use infinity for max-content
            })
300213
            .unwrap_or(f32::INFINITY);
300213
        let available_height = inputs
300213
            .known_dimensions
300213
            .height
300213
            .map(|kh| (kh - node_padding_height - node_border_height).max(0.0))
300213
            .or(match inputs.available_space.height {
161352
                AvailableSpace::Definite(h) => Some(h),
96567
                AvailableSpace::MinContent => None, // Use infinity, return intrinsic min-content
42294
                AvailableSpace::MaxContent => None,
            })
300213
            .unwrap_or(f32::INFINITY);
300213
        let mut available_size = LogicalSize {
300213
            width: available_width,
300213
            height: available_height,
300213
        };
        // The TYPED containing block for everything that resolves a used size:
        // built straight from Taffy's sum type, so "indefinite" never becomes a
        // float on that path. The flattened `available_size` above remains for
        // the text/inline constraint plumbing, where INFINITY genuinely encodes
        // "unbounded line" inside the line breaker (stage-2 migration).
300213
        let typed_cb = {
600426
            let axis = |known: Option<f32>, pad_border: f32, avail: AvailableSpace| match known {
229440
                Some(k) => crate::text3::cache::AvailableSpace::Definite((k - pad_border).max(0.0)),
370986
                None => match avail {
117530
                    AvailableSpace::Definite(v) => crate::text3::cache::AvailableSpace::Definite(v),
160301
                    AvailableSpace::MinContent => crate::text3::cache::AvailableSpace::MinContent,
93155
                    AvailableSpace::MaxContent => crate::text3::cache::AvailableSpace::MaxContent,
                },
600426
            };
300213
            crate::solver3::geometry::ContainingBlock::from_axes(
300213
                axis(
300213
                    inputs.known_dimensions.width,
300213
                    node_padding_width + node_border_width,
300213
                    inputs.available_space.width,
300213
                ),
300213
                axis(
300213
                    inputs.known_dimensions.height,
300213
                    node_padding_height + node_border_height,
300213
                    inputs.available_space.height,
300213
                ),
300213
                available_size,
            )
        };
        // NOTE: Scrollbar reservation is handled inside layout_bfc() where it subtracts
        // scrollbar width from children_containing_block_size. We do NOT subtract here
        // to avoid double-subtraction when compute_non_flex_layout delegates to
        // layout_formatting_context → layout_bfc.
        // Convert Taffy's AvailableSpace to our Text3AvailableSpace for caching.
        // When the child has known_dimensions.width (from flex/grid layout), use that
        // instead of the parent's available_space — otherwise text centers/wraps in
        // the wrong width (e.g., 404px parent instead of 120px child).
300213
        let available_width_type = if inputs.known_dimensions.width.is_some() {
155418
            crate::text3::cache::AvailableSpace::Definite(available_width)
        } else {
144795
            match inputs.available_space.width {
30080
                AvailableSpace::Definite(w) => crate::text3::cache::AvailableSpace::Definite(w),
63854
                AvailableSpace::MinContent => crate::text3::cache::AvailableSpace::MinContent,
50861
                AvailableSpace::MaxContent => crate::text3::cache::AvailableSpace::MaxContent,
            }
        };
        // Get text-align from CSS for this node (important for centering content in flex items)
300213
        let text_align = self
300213
            .tree
300213
            .get(LayoutNodeId::new(node_idx))
300213
            .and_then(|node| node.dom_node_id)
300213
            .map(|dom_id| {
300213
                let node_state =
300213
                    &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
300213
                crate::solver3::getters::get_text_align(self.ctx.styled_dom, dom_id, node_state)
300213
                    .unwrap_or_default()
300213
            })
300213
            .unwrap_or_default();
        // Convert CSS text-align to our internal TextAlign enum
300213
        let fc_text_align = match text_align {
600
            azul_css::props::style::StyleTextAlign::Left => FcTextAlign::Start,
            azul_css::props::style::StyleTextAlign::Right => FcTextAlign::End,
43177
            azul_css::props::style::StyleTextAlign::Center => FcTextAlign::Center,
            azul_css::props::style::StyleTextAlign::Justify => FcTextAlign::Justify,
256436
            azul_css::props::style::StyleTextAlign::Start => FcTextAlign::Start,
            azul_css::props::style::StyleTextAlign::End => FcTextAlign::End,
        };
        // SAFETY: `self.text_cache` was derived from `&mut TextLayoutCache` in
        // `layout_taffy_subtree` and no other reference to it exists at this point.
        // The raw pointer is necessary because we already hold `&mut self` (which
        // borrows `ctx` and `tree`), and Rust's borrow checker cannot express the
        // disjointness of text_cache from ctx/tree.
300213
        let text_cache = unsafe { &mut *self.text_cache };
300213
        let constraints = LayoutConstraints {
300213
            available_size,
300213
            writing_mode: LayoutWritingMode::HorizontalTb,
300213
            writing_mode_ctx: super::geometry::WritingModeContext::default(),
300213
            bfc_state: None,
300213
            text_align: fc_text_align,
300213
            containing_block_size: available_size,
300213
            available_width_type,
300213
            fragmentainer: None,
300213
        };
        // A prior Taffy measurement pass (e.g. the min-content pass Taffy runs to
        // find a flex item's intrinsic width) stores its result in `node.used_size`
        // at the end of this function. layout_bfc then reads `used_size` as the
        // children's containing-block width. When the subsequent definite-width
        // cross-sizing pass re-enters here, that STALE min-content width (not this
        // pass's `known_dimensions.width`) drives child wrapping — so a flex item
        // with long text wraps at min-content and reports an over-tall cross size,
        // over-sizing the container (invoice `.head` measured 125px for ~45px of
        // content). Reset `used_size` to the border-box dims Taffy fixed for THIS
        // measure. When width is unknown (an intrinsic pass), clear it so layout_bfc
        // falls back to `constraints.available_size` (INFINITY → true intrinsic).
300213
        if let Some(n) = self.tree.get_mut(LayoutNodeId::new(node_idx)) {
            n.used_size = match (
300213
                inputs.known_dimensions.width,
300213
                inputs.known_dimensions.height,
            ) {
63244
                (Some(w), Some(h)) => Some(LogicalSize {
63244
                    width: w,
63244
                    height: h,
63244
                }),
92174
                (Some(w), None) if available_height.is_finite() => Some(LogicalSize {
64596
                    width: w,
64596
                    height: available_height + node_padding_height + node_border_height,
64596
                }),
                // Height genuinely unknown with INFINITE available height —
                // the main-axis content-measure pass of a COLUMN flex
                // container (cross width is known via stretch, height is
                // what taffy is asking us to compute). The old arm
                // fabricated height 0.0 here, and layout_bfc then used that
                // used_size as the children's containing block: every
                // descendant laid out inside a 0-HEIGHT box, the results
                // were cached, and auto-height text content inside a
                // fixed-height column flex item rendered as NOTHING (row
                // containers dodged it because the UNKNOWN axis there is
                // the width, which maps to None). Clear instead — layout_bfc
                // falls back to constraints.available_size (the true
                // content-measure request), same as the width-unknown case.
172373
                _ => None,
            };
        }
        // Use a temporary float cache for this subtree
300213
        let mut float_cache = HashMap::new();
        // Call layout_formatting_context - this handles ALL formatting context types
        // including nested flex/grid, tables, BFC, and IFC
300213
        let fc_result = crate::solver3::fc::layout_formatting_context(
300213
            self.ctx,
300213
            self.tree,
300213
            text_cache,
300213
            node_idx,
300213
            &constraints,
300213
            &mut float_cache,
        );
300213
        match fc_result {
300213
            Ok(bfc_result) => {
300213
                let output = bfc_result.output;
300213
                let content_width = output.overflow_size.width;
300213
                let content_height = output.overflow_size.height;
                // Padding/border already computed at start of function
300213
                let padding_width = node_padding_width;
300213
                let padding_height = node_padding_height;
300213
                let border_width = node_border_width;
300213
                let border_height = node_border_height;
                // Get intrinsic sizes for min/max-content queries
300213
                let intrinsic = self
300213
                    .tree
300213
                    .warm(LayoutNodeId::new(node_idx))
300213
                    .and_then(|w| w.intrinsic_sizes)
300213
                    .unwrap_or_default();
                // min-content size in the main axis; for items with a preferred aspect ratio, it
                // should be clamped by definite min/max cross sizes converted through the ratio.
                // For MinContent/MaxContent queries, use intrinsic sizes instead of layout result.
                // HOWEVER: If intrinsic sizes are 0 but content_width is non-zero, use
                // content_width. This happens for FormattingContext::Inline nodes
                // that are measured by their parent IFC root and don't have their
                // own intrinsic sizes stored.
                //
                // CRITICAL FIX: For InlineBlock elements with width: auto (known_dimensions.width =
                // None), we must use intrinsic max-content width instead of
                // content_width from BFC layout. The BFC layout was done with the
                // full container width, but InlineBlock should shrink-to-fit its
                // content. This is per CSS 2.1 § 10.3.9: "shrink-to-fit width".
300213
                let fc = self
300213
                    .tree
300213
                    .get(LayoutNodeId::new(node_idx))
300213
                    .map(|s| s.formatting_context)
300213
                    .unwrap_or_default();
300213
                let is_shrink_to_fit = matches!(fc, FormattingContext::InlineBlock)
                    && inputs.known_dimensions.width.is_none();
300213
                let effective_content_width = match inputs.available_space.width {
                    AvailableSpace::MinContent => {
63854
                        if intrinsic.min_content_width > 0.0 {
44552
                            intrinsic.min_content_width
                        } else {
19302
                            content_width
                        }
                    }
                    AvailableSpace::MaxContent => {
50861
                        if intrinsic.max_content_width > 0.0 {
31601
                            intrinsic.max_content_width
                        } else {
19260
                            content_width
                        }
                    }
                    AvailableSpace::Definite(_) => {
                        // For shrink-to-fit elements (InlineBlock with auto width),
                        // use intrinsic max-content width clamped by available space.
                        // CSS 2.1 § 10.3.9: shrink-to-fit = min(max(preferred minimum, available),
                        // preferred)
185498
                        if is_shrink_to_fit && intrinsic.max_content_width > 0.0 {
                            // Use max-content (preferred width) - already clamped by min/max-width
                            // in sizing
                            intrinsic.max_content_width
                        } else {
185498
                            content_width
                        }
                    }
                };
                // Replaced elements (image / VirtualView) have NO flow content, so the
                // BFC content_height above is 0 (and shrink-to-fit width may be wrong).
                // Their content size is the CSS/intrinsic-resolved size from
                // calculate_used_size_for_node (border-box) — strip padding+border back
                // to content-box. Fixes blank / 0-height images as flex/grid items.
300213
                let (effective_content_width, content_height) = {
300213
                    let dom_id = self
300213
                        .tree
300213
                        .get(LayoutNodeId::new(node_idx))
300213
                        .and_then(|n| n.dom_node_id);
300213
                    let is_replaced = dom_id.is_some_and(|id| {
300213
                        let nd = &self.ctx.styled_dom.node_data.as_container()[id];
300213
                        matches!(nd.get_node_type(), azul_core::dom::NodeType::Image(_))
300039
                            || nd.is_virtual_view_node()
300213
                    });
300213
                    match (is_replaced, dom_id) {
1534
                        (true, Some(id)) => {
1534
                            let bp = self
1534
                                .tree
1534
                                .get(LayoutNodeId::new(node_idx))
1534
                                .unwrap()
1534
                                .box_props
1534
                                .unpack();
1534
                            crate::solver3::sizing::calculate_used_size_for_node(
1534
                                self.ctx.styled_dom,
1534
                                Some(id),
1534
                                &typed_cb,
1534
                                intrinsic,
1534
                                &bp,
1534
                                &self.ctx.viewport_size,
                            )
1534
                            .map_or(
1534
                                (effective_content_width, content_height),
1534
                                |sz| {
1534
                                    (
1534
                                        (sz.width - padding_width - border_width).max(0.0),
1534
                                        (sz.height - padding_height - border_height).max(0.0),
1534
                                    )
1534
                                },
                            )
                        }
298679
                        _ => (effective_content_width, content_height),
                    }
                };
                // Convert content-box size to border-box size (for when we compute our own size)
300213
                let border_box_width = effective_content_width + padding_width + border_width;
300213
                let border_box_height = content_height + padding_height + border_height;
                // CRITICAL: Taffy's known_dimensions is BORDER-BOX (the child's
                // outer size as set by the parent flex/grid algorithm). Our BFC/IFC
                // layout computes content-box sizes, but Taffy expects the returned
                // `size` to be BORDER-BOX for correct positioning of subsequent items.
                //
                // When known_dimensions is set: use it directly (it's already border-box).
                // When it's None: add padding+border to our content-box result.
300213
                let final_width = inputs
300213
                    .known_dimensions
300213
                    .width
300213
                    .map_or(border_box_width, |border_box_w| border_box_w);
                // For grid items: if known_dimensions.height is None but available_space.height
                // is definite, use the available space. This ensures empty grid items stretch
                // to fill their grid cell, per CSS Grid spec behavior.
300213
                let final_height = if let Some(border_box_h) = inputs.known_dimensions.height {
74022
                    border_box_h
                } else {
                    // Check if parent is a grid container and available_space is definite
226191
                    let parent_is_grid = self
226191
                        .tree
226191
                        .get(LayoutNodeId::new(node_idx))
226191
                        .and_then(|n| n.parent)
226191
                        .and_then(|p| self.tree.get(LayoutNodeId::new(p)))
226191
                        .is_some_and(|p| matches!(p.formatting_context, FormattingContext::Grid));
226191
                    let content_sized = if parent_is_grid {
                        // For grid items, use available space if content is smaller
360
                        match inputs.available_space.height {
                            AvailableSpace::Definite(h) => {
                                // Grid items stretch to fill their cell by default
                                // Use the larger of content size or available space
                                h.max(border_box_height)
                            }
360
                            _ => border_box_height,
                        }
                    } else {
225831
                        border_box_height
                    };
                    // A CONTENT-SIZED leaf honours its own explicit min/max-height
                    // here, not only through taffy's `min_size` clamp. The slot a
                    // flex container reserved for a `min-height: 64px` textarea
                    // came out as its 26 px of content; the node's own layout then
                    // applied the min-height and painted 64 px into that slot —
                    // over the widget beneath. Measuring the clamped size is the
                    // one answer both authorities agree on.
226191
                    let (min_h, max_h) = self
226191
                        .own_px_height_bounds(node_idx, node_padding_height + node_border_height);
226191
                    let clamped = min_h.map_or(content_sized, |m| content_sized.max(m));
226191
                    max_h.map_or(clamped, |m| clamped.min(m.max(min_h.unwrap_or(0.0))))
                };
                // CRITICAL: Transfer positions from layout_formatting_context to child nodes.
                // Without this, children of flex items won't have their relative_position set,
                // causing them to all render at (0,0) relative to their parent.
302908
                for (child_idx, child_pos) in &output.positions {
2695
                    if let Some(child_warm) = self.tree.warm_mut(LayoutNodeId::new(*child_idx)) {
2695
                        child_warm.relative_position = Some(*child_pos);
2695
                    }
                }
                // Compute scrollbar_info for this node (it's a child of a Flex/Grid container,
                // so calculate_layout_for_subtree won't be called for it).
                // Uses the unified compute_scrollbar_info_core path.
                //
                // content_width/height come from our own BFC/IFC overflow_size,
                // which is already content-box relative — unlike Taffy's
                // border-box-origin content_size.
300213
                let (scrollbar_info, _, _) = compute_taffy_scrollbar_info(
300213
                    self.ctx,
300213
                    self.tree,
300213
                    node_idx,
300213
                    final_width,
300213
                    final_height,
300213
                    content_width,
300213
                    content_height,
300213
                    ContentSizeOrigin::ContentBox,
300213
                );
                // Store the border-box size and scrollbar_info on the node for display list
                // generation
300213
                if let Some(node) = self.tree.get_mut(LayoutNodeId::new(node_idx)) {
300213
                    node.used_size = Some(LogicalSize {
300213
                        width: final_width,
300213
                        height: final_height,
300213
                    });
300213
                }
300213
                if let Some(warm) = self.tree.warm_mut(LayoutNodeId::new(node_idx)) {
300213
                    warm.scrollbar_info = Some(scrollbar_info);
300213
                    // Store the actual content size for scroll calculations
300213
                    warm.overflow_content_size = Some(LogicalSize {
300213
                        width: content_width,
300213
                        height: content_height,
300213
                    });
300213
                }
                // Return the same size to Taffy for correct positioning
300213
                LayoutOutput {
300213
                    size: Size {
300213
                        width: final_width,
300213
                        height: final_height,
300213
                    },
300213
                    content_size: Size {
300213
                        width: content_width,
300213
                        height: content_height,
300213
                    },
300213
                    first_baselines: taffy::Point {
300213
                        x: None,
300213
                        y: output.baseline,
300213
                    },
300213
                    top_margin: taffy::CollapsibleMarginSet::ZERO,
300213
                    bottom_margin: taffy::CollapsibleMarginSet::ZERO,
300213
                    margins_can_collapse_through: false,
300213
                }
            }
            Err(_e) => {
                // Fallback to intrinsic sizes if layout fails
                let intrinsic = self
                    .tree
                    .warm(LayoutNodeId::new(node_idx))
                    .and_then(|w| w.intrinsic_sizes)
                    .unwrap_or_default();
                let width = inputs
                    .known_dimensions
                    .width
                    .unwrap_or(intrinsic.max_content_width);
                let height = inputs
                    .known_dimensions
                    .height
                    .unwrap_or(intrinsic.max_content_height);
                LayoutOutput {
                    size: Size { width, height },
                    content_size: Size { width, height },
                    first_baselines: taffy::Point { x: None, y: None },
                    top_margin: taffy::CollapsibleMarginSet::ZERO,
                    bottom_margin: taffy::CollapsibleMarginSet::ZERO,
                    margins_can_collapse_through: false,
                }
            }
        }
300213
    }
}
impl<T: ParsedFontTrait> CacheTree for TaffyBridge<'_, '_, T> {
1290662
    fn cache_get(&self, node_id: taffy::NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
1290662
        let node_idx: usize = node_id.into();
1290662
        let hit = self
1290662
            .tree
1290662
            .warm(LayoutNodeId::new(node_idx))?
            .taffy_cache
1290662
            .get(input);
1290662
        drop(crate::probe::Probe::span(if hit.is_some() {
587327
            "taffy_cache_get_hit"
        } else {
703335
            "taffy_cache_get_miss"
        }));
        // AZ_TAFFY_DEBUG: one line per lookup with the full taffy cache key.
        // Diffing two passes' lines for the same node names WHICH component
        // (known_dimensions / available_space / run_mode) moved and broke
        // the key — aggregates can't tell that.
1290662
        if std::env::var_os("AZ_TAFFY_DEBUG").is_some() {
            eprintln!(
                "[taffy] {} n{} kd=({:?},{:?}) avail=({:?},{:?}) mode={:?}",
                if hit.is_some() { "HIT " } else { "MISS" },
                node_idx,
                input.known_dimensions.width,
                input.known_dimensions.height,
                input.available_space.width,
                input.available_space.height,
                input.run_mode,
            );
1290662
        }
1290662
        hit
1290662
    }
703335
    fn cache_store(
703335
        &mut self,
703335
        node_id: taffy::NodeId,
703335
        input: &LayoutInput,
703335
        layout_output: LayoutOutput,
703335
    ) {
703335
        let node_idx: usize = node_id.into();
703335
        if let Some(warm) = self.tree.warm_mut(LayoutNodeId::new(node_idx)) {
703335
            warm.taffy_cache.store(input, layout_output);
703335
        }
703335
    }
    fn cache_clear(&mut self, node_id: taffy::NodeId) {
        drop(crate::probe::Probe::span("taffy_cache_clear"));
        let node_idx: usize = node_id.into();
        if let Some(warm) = self.tree.warm_mut(LayoutNodeId::new(node_idx)) {
            warm.taffy_cache.clear();
            warm.measured_content_sizes = (None, None);
        }
    }
}
impl<T: ParsedFontTrait> LayoutFlexboxContainer for TaffyBridge<'_, '_, T> {
    type FlexboxContainerStyle<'c>
        = Style
    where
        Self: 'c;
    type FlexboxItemStyle<'c>
        = Style
    where
        Self: 'c;
1047739
    fn get_flexbox_container_style(
1047739
        &self,
1047739
        node_id: taffy::NodeId,
1047739
    ) -> Self::FlexboxContainerStyle<'_> {
1047739
        self.get_core_container_style(node_id)
1047739
    }
2310229
    fn get_flexbox_child_style(&self, child_node_id: taffy::NodeId) -> Self::FlexboxItemStyle<'_> {
2310229
        self.get_core_container_style(child_node_id)
2310229
    }
}
impl<T: ParsedFontTrait> LayoutGridContainer for TaffyBridge<'_, '_, T> {
    type GridContainerStyle<'c>
        = Style
    where
        Self: 'c;
    type GridItemStyle<'c>
        = Style
    where
        Self: 'c;
50
    fn get_grid_container_style(&self, node_id: taffy::NodeId) -> Self::GridContainerStyle<'_> {
50
        self.get_core_container_style(node_id)
50
    }
780
    fn get_grid_child_style(&self, child_node_id: taffy::NodeId) -> Self::GridItemStyle<'_> {
780
        self.get_core_container_style(child_node_id)
780
    }
}
// --- Conversion Functions ---
#[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::vec_box)] // calc_storage Box gives stable addresses for taffy calc() pointers
129608
fn from_layout_width(
129608
    val: LayoutWidth,
129608
    calc_storage: &std::cell::RefCell<Vec<Box<CalcResolveContext>>>,
129608
    em_size: f32,
129608
    rem_size: f32,
129608
) -> Dimension {
129608
    match val {
114207
        LayoutWidth::Auto => Dimension::auto(),
15394
        LayoutWidth::Px(px) => pixel_value_to_pixels_fallback(&px).map_or_else(
445
            || {
445
                px.to_percent()
445
                    .map_or_else(Dimension::auto, |p| Dimension::percent(p.get()))
445
            },
            Dimension::length,
        ),
        LayoutWidth::MinContent | LayoutWidth::MaxContent | LayoutWidth::FitContent(_) => {
6
            Dimension::auto()
        }
1
        LayoutWidth::Calc(items) => {
1
            store_calc_and_make_dimension(items, calc_storage, em_size, rem_size)
        }
    }
129608
}
#[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::vec_box)] // calc_storage Box gives stable addresses for taffy calc() pointers
129599
fn from_layout_height(
129599
    val: LayoutHeight,
129599
    calc_storage: &std::cell::RefCell<Vec<Box<CalcResolveContext>>>,
129599
    em_size: f32,
129599
    rem_size: f32,
129599
) -> Dimension {
129599
    match val {
96785
        LayoutHeight::Auto => Dimension::auto(),
32811
        LayoutHeight::Px(px) => pixel_value_to_pixels_fallback(&px).map_or_else(
496
            || {
496
                px.to_percent()
496
                    .map_or_else(Dimension::auto, |p| Dimension::percent(p.get()))
496
            },
            Dimension::length,
        ),
        LayoutHeight::MinContent | LayoutHeight::MaxContent | LayoutHeight::FitContent(_) => {
3
            Dimension::auto()
        }
        LayoutHeight::Calc(items) => {
            store_calc_and_make_dimension(items, calc_storage, em_size, rem_size)
        }
    }
129599
}
/// Stores the calc AST + font-size context in heap-pinned storage and returns
/// a `Dimension::calc(ptr)` with a stable pointer to the `CalcResolveContext`.
///
/// The `Box` ensures the address doesn't move when the outer `Vec` reallocates.
/// The `RefCell<Vec<…>>` keeps all boxes alive for the layout pass duration.
#[allow(clippy::vec_box)] // calc_storage Box gives stable addresses for taffy calc() pointers
260
fn store_calc_and_make_dimension(
260
    items: CalcAstItemVec,
260
    storage: &std::cell::RefCell<Vec<Box<CalcResolveContext>>>,
260
    em_size: f32,
260
    rem_size: f32,
260
) -> Dimension {
260
    let boxed = Box::new(CalcResolveContext {
260
        items,
260
        em_size,
260
        rem_size,
260
    });
260
    let ptr: *const CalcResolveContext = &raw const *boxed;
260
    storage.borrow_mut().push(boxed);
    // SAFETY: Box gives ≥8-byte-aligned heap pointer; taffy masks low 3 bits.
260
    Dimension::calc(ptr.cast::<()>())
260
}
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
                                  // (or cross-type bindings that can't merge)
129601
const fn from_layout_position(val: LayoutPosition) -> Position {
129601
    match val {
127823
        LayoutPosition::Static => Position::Relative, // Taffy treats Static as Relative
1762
        LayoutPosition::Relative => Position::Relative,
12
        LayoutPosition::Absolute => Position::Absolute,
2
        LayoutPosition::Fixed => Position::Absolute, // Taffy doesn't distinguish Fixed
2
        LayoutPosition::Sticky => Position::Relative, // Sticky = Relative for Taffy
    }
129601
}
#[cfg(test)]
#[allow(
    clippy::float_cmp,
    clippy::too_many_lines,
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation
)]
mod autotest_generated {
    use azul_css::props::layout::{
        dimensions::CalcAstItem,
        grid::{
            GridLine as AzGridLine, GridMinMax, GridPlacement as AzGridPlacement,
            GridTrackSizingVec, LayoutJustifyItems, NamedGridLine,
        },
        LayoutOverflow,
    };
    use super::*;
    // ==================================================================
    // Fixtures
    // ==================================================================
    fn track_vec(v: Vec<GridTrackSizing>) -> GridTrackSizingVec {
        GridTrackSizingVec::from_vec(v)
    }
    fn template(v: Vec<GridTrackSizing>) -> GridTemplate {
        GridTemplate {
            tracks: track_vec(v),
        }
    }
    fn auto_tracks(v: Vec<GridTrackSizing>) -> GridAutoTracks {
        GridAutoTracks {
            tracks: track_vec(v),
        }
    }
    /// The absolute metrics `pixel_value_to_pixels_fallback` can resolve.
    const ABSOLUTE_METRICS: [SizeMetric; 7] = [
        SizeMetric::Px,
        SizeMetric::Pt,
        SizeMetric::In,
        SizeMetric::Cm,
        SizeMetric::Mm,
        SizeMetric::Em,
        SizeMetric::Rem,
    ];
    /// The metrics that need a resolution context this function does not have.
    const CONTEXTUAL_METRICS: [SizeMetric; 5] = [
        SizeMetric::Percent,
        SizeMetric::Vw,
        SizeMetric::Vh,
        SizeMetric::Vmin,
        SizeMetric::Vmax,
    ];
    fn approx(actual: f32, expected: f32) {
        assert!(
            (actual - expected).abs() < 1e-3,
            "expected ~{expected}, got {actual}"
        );
    }
    // ==================================================================
    // pixel_value_to_pixels_fallback — numeric
    // ==================================================================
    #[test]
    fn pixel_value_to_pixels_fallback_is_zero_at_zero_for_every_absolute_metric() {
        for m in ABSOLUTE_METRICS {
            assert_eq!(
                pixel_value_to_pixels_fallback(&PixelValue::from_metric(m, 0.0)),
                Some(0.0),
                "{m:?}"
            );
        }
    }
    #[test]
    fn pixel_value_to_pixels_fallback_converts_each_absolute_unit_to_css_px() {
        assert_eq!(
            pixel_value_to_pixels_fallback(&PixelValue::px(10.5)),
            Some(10.5)
        );
        assert_eq!(
            pixel_value_to_pixels_fallback(&PixelValue::inch(1.0)),
            Some(96.0)
        );
        assert_eq!(
            pixel_value_to_pixels_fallback(&PixelValue::em(2.0)),
            Some(2.0 * DEFAULT_FONT_SIZE)
        );
        assert_eq!(
            pixel_value_to_pixels_fallback(&PixelValue::rem(2.0)),
            Some(2.0 * DEFAULT_FONT_SIZE)
        );
        approx(
            pixel_value_to_pixels_fallback(&PixelValue::pt(72.0)).unwrap(),
            96.0,
        );
        approx(
            pixel_value_to_pixels_fallback(&PixelValue::cm(2.54)).unwrap(),
            96.0,
        );
        approx(
            pixel_value_to_pixels_fallback(&PixelValue::mm(25.4)).unwrap(),
            96.0,
        );
        // PT_TO_PX is the documented factor — 1pt = 96/72 px.
        approx(
            pixel_value_to_pixels_fallback(&PixelValue::pt(1.0)).unwrap(),
            PT_TO_PX,
        );
    }
    #[test]
    fn pixel_value_to_pixels_fallback_keeps_the_sign_of_negative_lengths() {
        for m in ABSOLUTE_METRICS {
            let out = pixel_value_to_pixels_fallback(&PixelValue::from_metric(m, -4.0))
                .expect("absolute metric resolves");
            assert!(out < 0.0, "{m:?} produced {out} for -4");
        }
    }
    #[test]
    fn pixel_value_to_pixels_fallback_returns_none_for_context_dependent_metrics() {
        for m in CONTEXTUAL_METRICS {
            assert_eq!(
                pixel_value_to_pixels_fallback(&PixelValue::from_metric(m, 50.0)),
                None,
                "{m:?} must not be resolved without a containing block / viewport"
            );
        }
    }
    #[test]
    fn pixel_value_to_pixels_fallback_sanitises_nan_and_infinite_inputs() {
        // `FloatValue` stores `f32 * 1000` in an `isize` via an `as` cast, which
        // saturates: NaN → 0, ±inf → isize::MIN/MAX. So no NaN and no infinity can
        // reach the layout through a PixelValue, whatever the caller passes in.
        assert_eq!(
            pixel_value_to_pixels_fallback(&PixelValue::px(f32::NAN)),
            Some(0.0),
            "NaN must be flattened to 0, not propagated"
        );
        let pos =
            pixel_value_to_pixels_fallback(&PixelValue::px(f32::INFINITY)).expect("px resolves");
        assert!(pos.is_finite() && pos > 0.0, "+inf px became {pos}");
        let neg = pixel_value_to_pixels_fallback(&PixelValue::px(f32::NEG_INFINITY))
            .expect("px resolves");
        assert!(neg.is_finite() && neg < 0.0, "-inf px became {neg}");
    }
    #[test]
    fn pixel_value_to_pixels_fallback_stays_finite_at_the_f32_extremes() {
        for v in [f32::MAX, f32::MIN, f32::MIN_POSITIVE, -f32::MIN_POSITIVE] {
            for m in ABSOLUTE_METRICS {
                let out = pixel_value_to_pixels_fallback(&PixelValue::from_metric(m, v))
                    .expect("absolute metric resolves");
                assert!(out.is_finite(), "{m:?} at {v} overflowed to {out}");
            }
        }
    }
    // ==================================================================
    // minmax + translate_track
    // ==================================================================
    #[test]
    fn minmax_puts_the_arguments_where_it_says_it_does() {
        let t = minmax(
            MinTrackSizingFunction::length(1.0),
            MaxTrackSizingFunction::fr(2.0),
        );
        assert_eq!(t.min, MinTrackSizingFunction::length(1.0));
        assert_eq!(t.max, MaxTrackSizingFunction::fr(2.0));
    }
    #[test]
    fn translate_track_maps_the_intrinsic_keywords() {
        assert_eq!(
            translate_track(&GridTrackSizing::MinContent),
            minmax(
                MinTrackSizingFunction::min_content(),
                MaxTrackSizingFunction::min_content()
            )
        );
        assert_eq!(
            translate_track(&GridTrackSizing::MaxContent),
            minmax(
                MinTrackSizingFunction::max_content(),
                MaxTrackSizingFunction::max_content()
            )
        );
        // `auto` is minmax(min-content, max-content) per CSS Grid §7.2.
        assert_eq!(
            translate_track(&GridTrackSizing::Auto),
            minmax(
                MinTrackSizingFunction::min_content(),
                MaxTrackSizingFunction::max_content()
            )
        );
    }
    #[test]
    fn translate_track_resolves_fixed_tracks_through_the_absolute_unit_table() {
        assert_eq!(
            translate_track(&GridTrackSizing::Fixed(PixelValue::px(120.0))),
            minmax(
                MinTrackSizingFunction::length(120.0),
                MaxTrackSizingFunction::length(120.0)
            )
        );
        assert_eq!(
            translate_track(&GridTrackSizing::Fixed(PixelValue::em(2.0))),
            minmax(
                MinTrackSizingFunction::length(32.0),
                MaxTrackSizingFunction::length(32.0)
            )
        );
        assert_eq!(
            translate_track(&GridTrackSizing::FitContent(PixelValue::px(50.0))),
            minmax(
                MinTrackSizingFunction::length(50.0),
                MaxTrackSizingFunction::max_content()
            )
        );
    }
    #[test]
    fn translate_track_collapses_unresolvable_track_units_to_zero_px() {
        // % / vw / vh cannot be expressed as a taffy track sizing fn here, and the
        // `.unwrap_or(0.0)` inside translate_track turns them into a 0px track
        // rather than dropping the track. Locking the (lossy) behaviour in.
        for m in CONTEXTUAL_METRICS {
            let pv = PixelValue::from_metric(m, 50.0);
            assert_eq!(
                translate_track(&GridTrackSizing::Fixed(pv)),
                minmax(
                    MinTrackSizingFunction::length(0.0),
                    MaxTrackSizingFunction::length(0.0)
                ),
                "{m:?}"
            );
            assert_eq!(
                translate_track(&GridTrackSizing::FitContent(pv)),
                minmax(
                    MinTrackSizingFunction::length(0.0),
                    MaxTrackSizingFunction::max_content()
                ),
                "{m:?}"
            );
        }
    }
    #[test]
    fn translate_track_divides_fr_by_the_hundredfold_scaling_factor() {
        assert_eq!(
            translate_track(&GridTrackSizing::Fr(100)),
            minmax(
                MinTrackSizingFunction::auto(),
                MaxTrackSizingFunction::fr(1.0)
            )
        );
        assert_eq!(
            translate_track(&GridTrackSizing::Fr(50)),
            minmax(
                MinTrackSizingFunction::auto(),
                MaxTrackSizingFunction::fr(0.5)
            )
        );
        assert_eq!(
            translate_track(&GridTrackSizing::Fr(0)),
            minmax(
                MinTrackSizingFunction::auto(),
                MaxTrackSizingFunction::fr(0.0)
            )
        );
    }
    #[test]
    fn translate_track_does_not_overflow_at_the_fr_integer_bounds() {
        for fr in [i32::MIN, i32::MIN + 1, -100, i32::MAX, i32::MAX - 1] {
            let t = translate_track(&GridTrackSizing::Fr(fr));
            let v = t.max.into_raw().value();
            assert!(v.is_finite(), "Fr({fr}) produced a non-finite fr: {v}");
            assert_eq!(v, fr as f32 / 100.0, "Fr({fr})");
        }
    }
    #[test]
    fn translate_track_minmax_takes_the_min_of_the_min_and_the_max_of_the_max() {
        let t = GridTrackSizing::MinMax(GridMinMax::new(
            GridTrackSizing::Fixed(PixelValue::px(10.0)),
            GridTrackSizing::Fr(200),
        ));
        assert_eq!(
            translate_track(&t),
            minmax(
                MinTrackSizingFunction::length(10.0),
                MaxTrackSizingFunction::fr(2.0)
            )
        );
        // The *other* halves are discarded: only minmax_box.min.min and
        // minmax_box.max.max survive the translation.
        let t = GridTrackSizing::MinMax(GridMinMax::new(
            GridTrackSizing::MaxContent,
            GridTrackSizing::MinContent,
        ));
        assert_eq!(
            translate_track(&t),
            minmax(
                MinTrackSizingFunction::max_content(),
                MaxTrackSizingFunction::min_content()
            )
        );
    }
    #[test]
    fn translate_track_terminates_on_a_left_nested_minmax_chain() {
        // Nesting only on the `min` side keeps the recursion linear.
        let mut t = GridTrackSizing::Fixed(PixelValue::px(7.0));
        for _ in 0..64 {
            t = GridTrackSizing::MinMax(GridMinMax::new(t, GridTrackSizing::MaxContent));
        }
        assert_eq!(
            translate_track(&t),
            minmax(
                MinTrackSizingFunction::length(7.0),
                MaxTrackSizingFunction::max_content()
            )
        );
    }
    #[test]
    fn translate_track_terminates_on_a_doubly_nested_minmax_chain() {
        // NOTE: translate_track calls itself on BOTH halves of a MinMax, so a
        // minmax nested on both sides costs O(2^depth). CSS grammar forbids
        // minmax() inside minmax(), so the parser can't reach this — but the type
        // can express it. Depth 10 = ~1k calls; it must still terminate and pick
        // the leaf on each side.
        let mut t = GridTrackSizing::Fixed(PixelValue::px(3.0));
        for _ in 0..10 {
            t = GridTrackSizing::MinMax(GridMinMax::new(t.clone(), t));
        }
        assert_eq!(
            translate_track(&t),
            minmax(
                MinTrackSizingFunction::length(3.0),
                MaxTrackSizingFunction::length(3.0)
            )
        );
    }
    // ==================================================================
    // grid-template-* / grid-auto-* → taffy
    // ==================================================================
    #[test]
    fn grid_templates_are_empty_for_every_non_exact_css_value() {
        for v in [
            CssPropertyValue::None,
            CssPropertyValue::Inherit,
            CssPropertyValue::Revert,
            CssPropertyValue::Unset,
            CssPropertyValue::Auto,
            CssPropertyValue::Initial,
        ] {
            assert!(grid_template_rows_to_taffy(v.clone()).is_empty(), "{v:?}");
            assert!(grid_template_columns_to_taffy(v).is_empty());
        }
        assert!(
            grid_template_rows_to_taffy(CssPropertyValue::Exact(template(Vec::new()))).is_empty()
        );
    }
    #[test]
    fn grid_auto_tracks_are_empty_for_every_non_exact_css_value() {
        for v in [
            CssPropertyValue::None,
            CssPropertyValue::Inherit,
            CssPropertyValue::Revert,
            CssPropertyValue::Unset,
            CssPropertyValue::Auto,
            CssPropertyValue::Initial,
        ] {
            assert!(grid_auto_rows_to_taffy(v.clone()).is_empty(), "{v:?}");
            assert!(grid_auto_columns_to_taffy(v).is_empty());
        }
    }
    #[test]
    fn grid_template_rows_and_columns_translate_each_track_in_order() {
        let t = template(vec![
            GridTrackSizing::Fr(100),
            GridTrackSizing::Fixed(PixelValue::px(20.0)),
            GridTrackSizing::Auto,
        ]);
        let rows = grid_template_rows_to_taffy(CssPropertyValue::Exact(t.clone()));
        let cols = grid_template_columns_to_taffy(CssPropertyValue::Exact(t));
        assert_eq!(rows.len(), 3);
        assert_eq!(rows, cols, "rows and columns share one translation path");
        assert_eq!(
            rows[0],
            GridTemplateComponent::Single(minmax(
                MinTrackSizingFunction::auto(),
                MaxTrackSizingFunction::fr(1.0)
            ))
        );
        assert_eq!(
            rows[1],
            GridTemplateComponent::Single(minmax(
                MinTrackSizingFunction::length(20.0),
                MaxTrackSizingFunction::length(20.0)
            ))
        );
        assert_eq!(
            rows[2],
            GridTemplateComponent::Single(minmax(
                MinTrackSizingFunction::min_content(),
                MaxTrackSizingFunction::max_content()
            ))
        );
    }
    #[test]
    fn grid_auto_rows_and_columns_agree_on_every_track() {
        let tracks = vec![
            GridTrackSizing::Fr(250),
            GridTrackSizing::MinContent,
            GridTrackSizing::FitContent(PixelValue::px(9.0)),
            GridTrackSizing::MinMax(GridMinMax::new(
                GridTrackSizing::Fixed(PixelValue::px(1.0)),
                GridTrackSizing::MaxContent,
            )),
        ];
        let rows = grid_auto_rows_to_taffy(CssPropertyValue::Exact(auto_tracks(tracks.clone())));
        let cols = grid_auto_columns_to_taffy(CssPropertyValue::Exact(auto_tracks(tracks.clone())));
        assert_eq!(rows.len(), tracks.len());
        // grid_auto_rows_to_taffy rebuilds the MinMax by calling translate_track
        // twice; it must land on exactly the same value as the single-call path.
        assert_eq!(rows, cols);
        for (i, track) in tracks.iter().enumerate() {
            assert_eq!(rows[i], translate_track(track), "track #{i}");
        }
    }
    #[test]
    fn grid_templates_handle_a_very_long_track_list() {
        let tracks: Vec<GridTrackSizing> = (0..2048).map(GridTrackSizing::Fr).collect();
        let out = grid_template_columns_to_taffy(CssPropertyValue::Exact(template(tracks)));
        assert_eq!(out.len(), 2048);
        assert_eq!(
            out[2047],
            GridTemplateComponent::Single(minmax(
                MinTrackSizingFunction::auto(),
                MaxTrackSizingFunction::fr(20.47)
            ))
        );
    }
    // ==================================================================
    // decode_compact_grid_line — numeric
    // ==================================================================
    #[test]
    fn decode_compact_grid_line_maps_both_sentinels_to_auto() {
        assert_eq!(
            decode_compact_grid_line(azul_css::compact_cache::I16_AUTO),
            GridPlacement::<String>::Auto
        );
        assert_eq!(
            decode_compact_grid_line(azul_css::compact_cache::I16_SENTINEL),
            GridPlacement::<String>::Auto
        );
        // i16::MAX *is* the sentinel, so the top of the range is Auto, not a line.
        assert_eq!(
            decode_compact_grid_line(i16::MAX),
            GridPlacement::<String>::Auto
        );
    }
    #[test]
    fn decode_compact_grid_line_zero_is_line_zero_not_auto() {
        assert_eq!(
            decode_compact_grid_line(0),
            GridPlacement::<String>::from_line_index(0)
        );
    }
    #[test]
    fn decode_compact_grid_line_positive_is_a_line_and_negative_is_a_span() {
        assert_eq!(
            decode_compact_grid_line(3),
            GridPlacement::<String>::from_line_index(3)
        );
        assert_eq!(
            decode_compact_grid_line(32_765),
            GridPlacement::<String>::from_line_index(32_765),
            "the largest value below I16_SENTINEL_THRESHOLD is still a line"
        );
        assert_eq!(
            decode_compact_grid_line(-1),
            GridPlacement::<String>::from_span(1)
        );
        assert_eq!(
            decode_compact_grid_line(-4),
            GridPlacement::<String>::from_span(4)
        );
        assert_eq!(
            decode_compact_grid_line(-32_767),
            GridPlacement::<String>::from_span(32_767)
        );
    }
    #[test]
    fn decode_compact_grid_line_at_i16_min_overflows_the_negation() {
        // `(-v) as u16` on i16::MIN: -(-32768) is not representable in i16.
        // Debug builds panic ("attempt to negate with overflow"); release wraps
        // back to i16::MIN, whose bit pattern as u16 is 32768. Neither is a
        // sensible span. Accept both so the test is profile-independent, and see
        // the report: this input should be rejected (or the negation widened to
        // i32) inside decode_compact_grid_line.
        let decoded = std::panic::catch_unwind(|| decode_compact_grid_line(i16::MIN));
        match decoded {
            Err(_) => { /* debug: overflow panic */ }
            Ok(p) => assert_eq!(
                p,
                GridPlacement::<String>::from_span(32_768),
                "release build: the negation wraps"
            ),
        }
    }
    // ==================================================================
    // grid_line_to_taffy / grid_placement_to_taffy
    // ==================================================================
    #[test]
    fn grid_line_to_taffy_maps_auto_lines_and_spans() {
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Auto),
            GridPlacement::<String>::Auto
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Line(0)),
            GridPlacement::<String>::from_line_index(0)
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Line(4)),
            GridPlacement::<String>::from_line_index(4)
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Line(-2)),
            GridPlacement::<String>::from_line_index(-2),
            "negative lines count from the end of the explicit grid"
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Span(3)),
            GridPlacement::<String>::from_span(3)
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Span(0)),
            GridPlacement::<String>::from_span(0)
        );
    }
    #[test]
    fn grid_line_to_taffy_truncates_out_of_range_line_numbers_instead_of_clamping() {
        // azul stores grid lines as i32, taffy as i16 — the `as i16` cast wraps.
        // A `grid-column: 70000` therefore silently becomes line 4464 rather than
        // being clamped to i16::MAX. Documented here; see the report.
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Line(70_000)),
            GridPlacement::<String>::from_line_index(70_000_i32 as i16)
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Line(i32::MAX)),
            GridPlacement::<String>::from_line_index(-1),
            "i32::MAX wraps to line -1 — the far end of the grid"
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Line(i32::MIN)),
            GridPlacement::<String>::from_line_index(0)
        );
    }
    #[test]
    fn grid_line_to_taffy_wraps_out_of_range_and_negative_spans() {
        // `span -1` is not valid CSS, but the i32 → u16 cast turns it into the
        // largest possible span rather than rejecting it.
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Span(-1)),
            GridPlacement::<String>::from_span(u16::MAX)
        );
        // `span 65536` wraps to `span 0`.
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Span(65_536)),
            GridPlacement::<String>::from_span(0)
        );
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Span(i32::MIN)),
            GridPlacement::<String>::from_span(0)
        );
    }
    #[test]
    fn grid_line_to_taffy_named_lines_keep_their_name_and_split_on_the_span_count() {
        let named = |name: &str, span: i32| {
            AzGridLine::Named(NamedGridLine {
                grid_line_name: name.into(),
                span_count: span,
            })
        };
        assert_eq!(
            grid_line_to_taffy(&named("sidebar", 0)),
            GridPlacement::NamedLine("sidebar".to_string(), 0)
        );
        assert_eq!(
            grid_line_to_taffy(&named("sidebar", 2)),
            GridPlacement::NamedSpan("sidebar".to_string(), 2)
        );
        // A negative span_count is not > 0, so it falls back to a named *line*.
        assert_eq!(
            grid_line_to_taffy(&named("sidebar", -5)),
            GridPlacement::NamedLine("sidebar".to_string(), 0)
        );
        // Empty and non-ASCII names must survive the AzString → String hop.
        assert_eq!(
            grid_line_to_taffy(&named("", 0)),
            GridPlacement::NamedLine(String::new(), 0)
        );
        assert_eq!(
            grid_line_to_taffy(&named("行 🎉 col", 1)),
            GridPlacement::NamedSpan("行 🎉 col".to_string(), 1)
        );
    }
    #[test]
    fn grid_line_to_taffy_named_span_count_wraps_at_u16() {
        assert_eq!(
            grid_line_to_taffy(&AzGridLine::Named(NamedGridLine {
                grid_line_name: "x".into(),
                span_count: 65_536,
            })),
            GridPlacement::NamedSpan("x".to_string(), 0),
            "span_count 65536 wraps to a 0-track named span"
        );
    }
    #[test]
    fn grid_placement_to_taffy_does_not_swap_start_and_end() {
        let p = AzGridPlacement {
            grid_start: AzGridLine::Line(2),
            grid_end: AzGridLine::Span(3),
        };
        let out = grid_placement_to_taffy(&p);
        assert_eq!(out.start, GridPlacement::<String>::from_line_index(2));
        assert_eq!(out.end, GridPlacement::<String>::from_span(3));
        let both_auto = AzGridPlacement {
            grid_start: AzGridLine::Auto,
            grid_end: AzGridLine::Auto,
        };
        let out = grid_placement_to_taffy(&both_auto);
        assert_eq!(out.start, GridPlacement::<String>::Auto);
        assert_eq!(out.end, GridPlacement::<String>::Auto);
    }
    // ==================================================================
    // enum → taffy mapping tables
    // ==================================================================
    #[test]
    fn layout_display_to_taffy_maps_flex_and_grid_and_folds_the_rest_into_block() {
        assert_eq!(
            layout_display_to_taffy(CssPropertyValue::Exact(LayoutDisplay::None)),
            Display::None
        );
        for d in [LayoutDisplay::Flex, LayoutDisplay::InlineFlex] {
            assert_eq!(
                layout_display_to_taffy(CssPropertyValue::Exact(d)),
                Display::Flex,
                "{d:?}"
            );
        }
        for d in [LayoutDisplay::Grid, LayoutDisplay::InlineGrid] {
            assert_eq!(
                layout_display_to_taffy(CssPropertyValue::Exact(d)),
                Display::Grid,
                "{d:?}"
            );
        }
        // Everything else — including `contents`, `table*` and `list-item` — is
        // handed to taffy as a plain block box.
        for d in [
            LayoutDisplay::Block,
            LayoutDisplay::Inline,
            LayoutDisplay::InlineBlock,
            LayoutDisplay::Table,
            LayoutDisplay::TableCell,
            LayoutDisplay::TableRow,
            LayoutDisplay::FlowRoot,
            LayoutDisplay::ListItem,
            LayoutDisplay::Contents,
        ] {
            assert_eq!(
                layout_display_to_taffy(CssPropertyValue::Exact(d)),
                Display::Block,
                "{d:?}"
            );
        }
    }
    #[test]
    fn layout_display_to_taffy_distinguishes_css_wide_none_from_display_none() {
        // `CssPropertyValue::None` means "the property is absent", NOT `display: none`.
        // It must fall back to the initial value (block), or nothing would render.
        assert_eq!(
            layout_display_to_taffy(CssPropertyValue::None),
            Display::Block
        );
        assert_eq!(
            layout_display_to_taffy(CssPropertyValue::Inherit),
            Display::Block
        );
        assert_eq!(
            layout_display_to_taffy(CssPropertyValue::Auto),
            Display::Block
        );
        assert_eq!(
            layout_display_to_taffy(CssPropertyValue::Exact(LayoutDisplay::None)),
            Display::None,
            "…but an explicit `display: none` still means none"
        );
    }
    #[test]
    fn layout_position_to_taffy_and_from_layout_position_agree_on_every_variant() {
        let all = [
            LayoutPosition::Static,
            LayoutPosition::Relative,
            LayoutPosition::Absolute,
            LayoutPosition::Fixed,
            LayoutPosition::Sticky,
        ];
        for p in all {
            assert_eq!(
                layout_position_to_taffy(CssPropertyValue::Exact(p)),
                from_layout_position(p),
                "the two position paths disagree on {p:?}"
            );
        }
        assert_eq!(
            from_layout_position(LayoutPosition::Static),
            Position::Relative
        );
        assert_eq!(
            from_layout_position(LayoutPosition::Relative),
            Position::Relative
        );
        assert_eq!(
            from_layout_position(LayoutPosition::Sticky),
            Position::Relative
        );
        assert_eq!(
            from_layout_position(LayoutPosition::Absolute),
            Position::Absolute
        );
        assert_eq!(
            from_layout_position(LayoutPosition::Fixed),
            Position::Absolute
        );
        // Absent property → `static` → relative.
        assert_eq!(
            layout_position_to_taffy(CssPropertyValue::None),
            Position::Relative
        );
        assert_eq!(
            layout_position_to_taffy(CssPropertyValue::Inherit),
            Position::Relative
        );
    }
    #[test]
    fn grid_auto_flow_to_taffy_maps_all_four_variants_and_defaults_to_row() {
        assert_eq!(
            grid_auto_flow_to_taffy(CssPropertyValue::Exact(LayoutGridAutoFlow::Row)),
            GridAutoFlow::Row
        );
        assert_eq!(
            grid_auto_flow_to_taffy(CssPropertyValue::Exact(LayoutGridAutoFlow::Column)),
            GridAutoFlow::Column
        );
        assert_eq!(
            grid_auto_flow_to_taffy(CssPropertyValue::Exact(LayoutGridAutoFlow::RowDense)),
            GridAutoFlow::RowDense
        );
        assert_eq!(
            grid_auto_flow_to_taffy(CssPropertyValue::Exact(LayoutGridAutoFlow::ColumnDense)),
            GridAutoFlow::ColumnDense
        );
        for v in [
            CssPropertyValue::None,
            CssPropertyValue::Inherit,
            CssPropertyValue::Revert,
            CssPropertyValue::Unset,
            CssPropertyValue::Auto,
            CssPropertyValue::Initial,
        ] {
            assert_eq!(grid_auto_flow_to_taffy(v), GridAutoFlow::Row, "{v:?}");
        }
    }
    #[test]
    fn layout_flex_direction_to_taffy_maps_all_four_variants_and_defaults_to_row() {
        assert_eq!(
            layout_flex_direction_to_taffy(CssPropertyValue::Exact(LayoutFlexDirection::Row)),
            FlexDirection::Row
        );
        assert_eq!(
            layout_flex_direction_to_taffy(CssPropertyValue::Exact(
                LayoutFlexDirection::RowReverse
            )),
            FlexDirection::RowReverse
        );
        assert_eq!(
            layout_flex_direction_to_taffy(CssPropertyValue::Exact(LayoutFlexDirection::Column)),
            FlexDirection::Column
        );
        assert_eq!(
            layout_flex_direction_to_taffy(CssPropertyValue::Exact(
                LayoutFlexDirection::ColumnReverse
            )),
            FlexDirection::ColumnReverse
        );
        assert_eq!(
            layout_flex_direction_to_taffy(CssPropertyValue::Inherit),
            FlexDirection::Row
        );
    }
    #[test]
    fn layout_flex_wrap_to_taffy_maps_all_three_variants_and_defaults_to_nowrap() {
        assert_eq!(
            layout_flex_wrap_to_taffy(CssPropertyValue::Exact(LayoutFlexWrap::NoWrap)),
            FlexWrap::NoWrap
        );
        assert_eq!(
            layout_flex_wrap_to_taffy(CssPropertyValue::Exact(LayoutFlexWrap::Wrap)),
            FlexWrap::Wrap
        );
        assert_eq!(
            layout_flex_wrap_to_taffy(CssPropertyValue::Exact(LayoutFlexWrap::WrapReverse)),
            FlexWrap::WrapReverse
        );
        assert_eq!(
            layout_flex_wrap_to_taffy(CssPropertyValue::Inherit),
            FlexWrap::NoWrap
        );
    }
    #[test]
    fn layout_align_items_to_taffy_maps_start_and_end_onto_the_flex_variants() {
        assert_eq!(
            layout_align_items_to_taffy(CssPropertyValue::Exact(LayoutAlignItems::Stretch)),
            AlignItems::Stretch
        );
        assert_eq!(
            layout_align_items_to_taffy(CssPropertyValue::Exact(LayoutAlignItems::Center)),
            AlignItems::Center
        );
        assert_eq!(
            layout_align_items_to_taffy(CssPropertyValue::Exact(LayoutAlignItems::Start)),
            AlignItems::FlexStart
        );
        assert_eq!(
            layout_align_items_to_taffy(CssPropertyValue::Exact(LayoutAlignItems::End)),
            AlignItems::FlexEnd
        );
        assert_eq!(
            layout_align_items_to_taffy(CssPropertyValue::Exact(LayoutAlignItems::Baseline)),
            AlignItems::Baseline
        );
        // Absent → the CSS initial value, `stretch`.
        assert_eq!(
            layout_align_items_to_taffy(CssPropertyValue::Inherit),
            AlignItems::Stretch
        );
    }
    #[test]
    fn layout_align_self_to_taffy_returns_none_only_for_auto() {
        assert_eq!(
            layout_align_self_to_taffy(CssPropertyValue::Exact(LayoutAlignSelf::Auto)),
            None
        );
        // `auto` is the initial value, so an absent property is None too — that is
        // what lets taffy inherit the parent's align-items.
        assert_eq!(layout_align_self_to_taffy(CssPropertyValue::Inherit), None);
        assert_eq!(layout_align_self_to_taffy(CssPropertyValue::Initial), None);
        assert_eq!(
            layout_align_self_to_taffy(CssPropertyValue::Exact(LayoutAlignSelf::Start)),
            Some(AlignSelf::FlexStart)
        );
        assert_eq!(
            layout_align_self_to_taffy(CssPropertyValue::Exact(LayoutAlignSelf::End)),
            Some(AlignSelf::FlexEnd)
        );
        assert_eq!(
            layout_align_self_to_taffy(CssPropertyValue::Exact(LayoutAlignSelf::Center)),
            Some(AlignSelf::Center)
        );
        assert_eq!(
            layout_align_self_to_taffy(CssPropertyValue::Exact(LayoutAlignSelf::Baseline)),
            Some(AlignSelf::Baseline)
        );
        assert_eq!(
            layout_align_self_to_taffy(CssPropertyValue::Exact(LayoutAlignSelf::Stretch)),
            Some(AlignSelf::Stretch)
        );
    }
    #[test]
    fn layout_align_content_to_taffy_maps_every_variant_and_defaults_to_stretch() {
        assert_eq!(
            layout_align_content_to_taffy(CssPropertyValue::Exact(LayoutAlignContent::Start)),
            AlignContent::FlexStart
        );
        assert_eq!(
            layout_align_content_to_taffy(CssPropertyValue::Exact(LayoutAlignContent::End)),
            AlignContent::FlexEnd
        );
        assert_eq!(
            layout_align_content_to_taffy(CssPropertyValue::Exact(LayoutAlignContent::Center)),
            AlignContent::Center
        );
        assert_eq!(
            layout_align_content_to_taffy(CssPropertyValue::Exact(LayoutAlignContent::Stretch)),
            AlignContent::Stretch
        );
        assert_eq!(
            layout_align_content_to_taffy(CssPropertyValue::Exact(
                LayoutAlignContent::SpaceBetween
            )),
            AlignContent::SpaceBetween
        );
        assert_eq!(
            layout_align_content_to_taffy(CssPropertyValue::Exact(LayoutAlignContent::SpaceAround)),
            AlignContent::SpaceAround
        );
        assert_eq!(
            layout_align_content_to_taffy(CssPropertyValue::Inherit),
            AlignContent::Stretch
        );
    }
    #[test]
    fn layout_justify_content_to_taffy_keeps_start_distinct_from_flex_start() {
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(
                LayoutJustifyContent::FlexStart
            )),
            JustifyContent::FlexStart
        );
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(LayoutJustifyContent::Start)),
            JustifyContent::Start
        );
        assert_ne!(JustifyContent::Start, JustifyContent::FlexStart);
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(LayoutJustifyContent::FlexEnd)),
            JustifyContent::FlexEnd
        );
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(LayoutJustifyContent::End)),
            JustifyContent::End
        );
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(LayoutJustifyContent::Center)),
            JustifyContent::Center
        );
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(
                LayoutJustifyContent::SpaceBetween
            )),
            JustifyContent::SpaceBetween
        );
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(
                LayoutJustifyContent::SpaceAround
            )),
            JustifyContent::SpaceAround
        );
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Exact(
                LayoutJustifyContent::SpaceEvenly
            )),
            JustifyContent::SpaceEvenly
        );
        // Initial value of justify-content in this codebase is `start`.
        assert_eq!(
            layout_justify_content_to_taffy(CssPropertyValue::Inherit),
            JustifyContent::Start
        );
    }
    #[test]
    fn layout_justify_items_to_taffy_maps_all_four_variants_and_defaults_to_stretch() {
        assert_eq!(
            layout_justify_items_to_taffy(CssPropertyValue::Exact(LayoutJustifyItems::Start)),
            AlignItems::Start
        );
        assert_eq!(
            layout_justify_items_to_taffy(CssPropertyValue::Exact(LayoutJustifyItems::End)),
            AlignItems::End
        );
        assert_eq!(
            layout_justify_items_to_taffy(CssPropertyValue::Exact(LayoutJustifyItems::Center)),
            AlignItems::Center
        );
        assert_eq!(
            layout_justify_items_to_taffy(CssPropertyValue::Exact(LayoutJustifyItems::Stretch)),
            AlignItems::Stretch
        );
        assert_eq!(
            layout_justify_items_to_taffy(CssPropertyValue::Inherit),
            AlignItems::Stretch
        );
        // justify-items uses the *logical* Start/End, unlike align-items, which is
        // mapped onto FlexStart/FlexEnd. Guard the asymmetry.
        assert_ne!(
            layout_justify_items_to_taffy(CssPropertyValue::Exact(LayoutJustifyItems::Start)),
            layout_align_items_to_taffy(CssPropertyValue::Exact(LayoutAlignItems::Start))
        );
    }
    #[test]
    fn azul_overflow_to_taffy_treats_auto_as_scroll_and_everything_unset_as_visible() {
        assert_eq!(
            azul_overflow_to_taffy(MultiValue::Exact(LayoutOverflow::Visible)),
            taffy::Overflow::Visible
        );
        assert_eq!(
            azul_overflow_to_taffy(MultiValue::Exact(LayoutOverflow::Hidden)),
            taffy::Overflow::Hidden
        );
        assert_eq!(
            azul_overflow_to_taffy(MultiValue::Exact(LayoutOverflow::Scroll)),
            taffy::Overflow::Scroll
        );
        assert_eq!(
            azul_overflow_to_taffy(MultiValue::Exact(LayoutOverflow::Clip)),
            taffy::Overflow::Clip
        );
        // Taffy has no `auto`; `auto` constrains the box exactly like `scroll`.
        assert_eq!(
            azul_overflow_to_taffy(MultiValue::Exact(LayoutOverflow::Auto)),
            taffy::Overflow::Scroll
        );
        for v in [MultiValue::Auto, MultiValue::Initial, MultiValue::Inherit] {
            assert_eq!(azul_overflow_to_taffy(v), taffy::Overflow::Visible);
        }
    }
    // ==================================================================
    // css_width_to_px / css_height_to_px
    // ==================================================================
    #[test]
    fn css_width_and_height_to_px_only_resolve_absolute_px_lengths() {
        assert_eq!(
            css_width_to_px(&LayoutWidth::Px(PixelValue::px(120.0))),
            Some(120.0)
        );
        assert_eq!(
            css_height_to_px(&LayoutHeight::Px(PixelValue::px(120.0))),
            Some(120.0)
        );
        // em/rem go through the 16px fallback rather than returning None.
        assert_eq!(
            css_width_to_px(&LayoutWidth::Px(PixelValue::em(2.0))),
            Some(32.0)
        );
        assert_eq!(
            css_height_to_px(&LayoutHeight::Px(PixelValue::rem(2.0))),
            Some(32.0)
        );
        // …but a percentage width has no containing block here.
        assert_eq!(
            css_width_to_px(&LayoutWidth::Px(PixelValue::percent(50.0))),
            None
        );
        assert_eq!(
            css_height_to_px(&LayoutHeight::Px(PixelValue::percent(50.0))),
            None
        );
    }
    #[test]
    fn css_width_and_height_to_px_return_none_for_every_non_px_variant() {
        let widths = [
            LayoutWidth::Auto,
            LayoutWidth::MinContent,
            LayoutWidth::MaxContent,
            LayoutWidth::FitContent(PixelValue::px(10.0)),
            LayoutWidth::Calc(CalcAstItemVec::from_vec(vec![CalcAstItem::Value(
                PixelValue::px(10.0),
            )])),
        ];
        for w in &widths {
            assert_eq!(css_width_to_px(w), None, "{w:?}");
        }
        let heights = [
            LayoutHeight::Auto,
            LayoutHeight::MinContent,
            LayoutHeight::MaxContent,
            LayoutHeight::FitContent(PixelValue::px(10.0)),
            LayoutHeight::Calc(CalcAstItemVec::from_vec(Vec::new())),
        ];
        for h in &heights {
            assert_eq!(css_height_to_px(h), None, "{h:?}");
        }
    }
    #[test]
    fn css_width_to_px_never_returns_nan_for_a_nan_pixel_value() {
        let w = css_width_to_px(&LayoutWidth::Px(PixelValue::px(f32::NAN)));
        assert_eq!(w, Some(0.0));
        let h = css_height_to_px(&LayoutHeight::Px(PixelValue::px(f32::INFINITY)));
        assert!(h.expect("px resolves").is_finite());
    }
    // ==================================================================
    // MultiValue<PixelValue> → taffy lengths
    // ==================================================================
    #[test]
    fn multi_value_to_lpa_maps_the_css_wide_keywords_to_auto() {
        for mv in [MultiValue::Auto, MultiValue::Initial, MultiValue::Inherit] {
            assert!(
                multi_value_to_lpa(mv).is_auto(),
                "inset keywords must stay auto"
            );
        }
    }
    #[test]
    fn multi_value_to_lpa_resolves_lengths_percentages_and_falls_back_to_auto() {
        assert_eq!(
            multi_value_to_lpa(MultiValue::Exact(PixelValue::px(0.0))),
            LengthPercentageAuto::length(0.0)
        );
        assert_eq!(
            multi_value_to_lpa(MultiValue::Exact(PixelValue::px(-12.5))),
            LengthPercentageAuto::length(-12.5),
            "negative insets are legal and must not be clamped"
        );
        assert_eq!(
            multi_value_to_lpa(MultiValue::Exact(PixelValue::percent(50.0))),
            LengthPercentageAuto::percent(0.5),
            "taffy percentages are 0..1, azul's are 0..100"
        );
        assert_eq!(
            multi_value_to_lpa(MultiValue::Exact(PixelValue::em(2.0))),
            LengthPercentageAuto::length(32.0)
        );
        // Viewport units resolve to neither a length nor a percent → auto.
        for m in [
            SizeMetric::Vw,
            SizeMetric::Vh,
            SizeMetric::Vmin,
            SizeMetric::Vmax,
        ] {
            assert!(
                multi_value_to_lpa(MultiValue::Exact(PixelValue::from_metric(m, 10.0))).is_auto(),
                "{m:?} is silently dropped to auto"
            );
        }
    }
    /// Bug class: a relative unit resolved against a CONSTANT. The fallback's
    /// 16 px is only right for a 16 px font; the UA `<p>` margin is `1em`, so
    /// an 11 px widget label carried 16 px of margin top and bottom. With the
    /// node's font sizes in hand, `em`/`rem` resolve against them and every
    /// absolute unit is untouched.
    #[test]
    fn margins_paddings_and_borders_resolve_em_and_rem_against_the_nodes_font() {
        let (em, rem) = (11.0, 16.0);
        assert_eq!(
            multi_value_to_lpa_margin_ctx(MultiValue::Exact(PixelValue::em(1.0)), em, rem),
            LengthPercentageAuto::length(11.0)
        );
        assert_eq!(
            multi_value_to_lpa_margin_ctx(
                MultiValue::Exact(PixelValue::from_metric(SizeMetric::Rem, 2.0)),
                em,
                rem
            ),
            LengthPercentageAuto::length(32.0)
        );
        assert_eq!(
            multi_value_to_lp_ctx(MultiValue::Exact(PixelValue::em(0.5)), em, rem),
            LengthPercentage::length(5.5)
        );
        // Absolute units and the keywords go through the plain converters unchanged.
        assert_eq!(
            multi_value_to_lpa_margin_ctx(MultiValue::Exact(PixelValue::px(7.0)), em, rem),
            multi_value_to_lpa_margin(MultiValue::Exact(PixelValue::px(7.0)))
        );
        assert!(multi_value_to_lpa_margin_ctx(MultiValue::Auto, em, rem).is_auto());
        assert_eq!(
            multi_value_to_lp_ctx(MultiValue::Initial, em, rem),
            LengthPercentage::ZERO
        );
        // And the constant-based fallback still says 16 — which is the point.
        assert_eq!(
            pixel_value_to_pixels_fallback(&PixelValue::em(1.0)),
            Some(DEFAULT_FONT_SIZE)
        );
    }
    #[test]
    fn multi_value_to_lpa_margin_keeps_auto_but_zeroes_the_other_keywords() {
        // The whole point of the margin variant: `auto` survives (flex centering),
        // `initial`/`inherit` become 0 (the CSS initial margin).
        assert!(multi_value_to_lpa_margin(MultiValue::Auto).is_auto());
        assert_eq!(
            multi_value_to_lpa_margin(MultiValue::Initial),
            LengthPercentageAuto::length(0.0)
        );
        assert_eq!(
            multi_value_to_lpa_margin(MultiValue::Inherit),
            LengthPercentageAuto::length(0.0)
        );
        // …which is exactly where it differs from the inset variant.
        assert!(multi_value_to_lpa(MultiValue::Initial).is_auto());
    }
    #[test]
    fn multi_value_to_lpa_margin_falls_back_to_zero_not_auto_for_unresolvable_units() {
        assert_eq!(
            multi_value_to_lpa_margin(MultiValue::Exact(PixelValue::from_metric(
                SizeMetric::Vw,
                10.0
            ))),
            LengthPercentageAuto::length(0.0),
            "an unresolvable margin must not turn into `margin: auto` (it would centre the item)"
        );
        assert_eq!(
            multi_value_to_lpa_margin(MultiValue::Exact(PixelValue::percent(25.0))),
            LengthPercentageAuto::percent(0.25)
        );
        assert_eq!(
            multi_value_to_lpa_margin(MultiValue::Exact(PixelValue::px(-8.0))),
            LengthPercentageAuto::length(-8.0),
            "negative margins are legal CSS"
        );
        assert_eq!(
            multi_value_to_lpa_margin(MultiValue::Exact(PixelValue::px(f32::NAN))),
            LengthPercentageAuto::length(0.0)
        );
    }
    #[test]
    fn multi_value_to_lp_maps_every_keyword_and_unresolvable_unit_to_zero() {
        for mv in [MultiValue::Auto, MultiValue::Initial, MultiValue::Inherit] {
            assert_eq!(multi_value_to_lp(mv), LengthPercentage::ZERO);
        }
        for m in CONTEXTUAL_METRICS
            .iter()
            .filter(|m| **m != SizeMetric::Percent)
        {
            assert_eq!(
                multi_value_to_lp(MultiValue::Exact(PixelValue::from_metric(*m, 10.0))),
                LengthPercentage::ZERO,
                "{m:?}"
            );
        }
        assert_eq!(
            multi_value_to_lp(MultiValue::Exact(PixelValue::px(4.0))),
            LengthPercentage::length(4.0)
        );
        assert_eq!(
            multi_value_to_lp(MultiValue::Exact(PixelValue::percent(10.0))),
            LengthPercentage::percent(0.1)
        );
    }
    #[test]
    fn pixel_to_lp_agrees_with_multi_value_to_lp_on_every_exact_value() {
        let values = [
            PixelValue::px(0.0),
            PixelValue::px(12.0),
            PixelValue::px(-12.0),
            PixelValue::px(f32::NAN),
            PixelValue::px(f32::INFINITY),
            PixelValue::em(1.5),
            PixelValue::rem(1.5),
            PixelValue::pt(12.0),
            PixelValue::percent(33.0),
            PixelValue::from_metric(SizeMetric::Vw, 100.0),
            PixelValue::from_metric(SizeMetric::Vmax, 100.0),
        ];
        for pv in values {
            assert_eq!(
                pixel_to_lp(pv),
                multi_value_to_lp(MultiValue::Exact(pv)),
                "{pv:?}"
            );
        }
        assert_eq!(
            pixel_to_lp(PixelValue::from_metric(SizeMetric::Vw, 100.0)),
            LengthPercentage::ZERO
        );
    }
    // ==================================================================
    // from_layout_width / from_layout_height / store_calc_and_make_dimension
    // ==================================================================
    #[allow(clippy::vec_box)] // return type must mirror the production calc_storage (Box = stable
                              // element addresses)
    fn empty_calc_storage() -> std::cell::RefCell<Vec<Box<CalcResolveContext>>> {
        std::cell::RefCell::new(Vec::new())
    }
    #[test]
    fn from_layout_width_and_height_agree_on_every_shared_variant() {
        let storage = empty_calc_storage();
        let pairs: [(LayoutWidth, LayoutHeight); 6] = [
            (LayoutWidth::Auto, LayoutHeight::Auto),
            (
                LayoutWidth::Px(PixelValue::px(100.0)),
                LayoutHeight::Px(PixelValue::px(100.0)),
            ),
            (
                LayoutWidth::Px(PixelValue::percent(50.0)),
                LayoutHeight::Px(PixelValue::percent(50.0)),
            ),
            (LayoutWidth::MinContent, LayoutHeight::MinContent),
            (LayoutWidth::MaxContent, LayoutHeight::MaxContent),
            (
                LayoutWidth::FitContent(PixelValue::px(10.0)),
                LayoutHeight::FitContent(PixelValue::px(10.0)),
            ),
        ];
        for (w, h) in pairs {
            assert_eq!(
                from_layout_width(w.clone(), &storage, 16.0, 16.0),
                from_layout_height(h, &storage, 16.0, 16.0),
                "{w:?}"
            );
        }
        assert!(storage.borrow().is_empty(), "no calc() → no storage growth");
    }
    #[test]
    fn from_layout_width_maps_the_intrinsic_keywords_to_auto() {
        let storage = empty_calc_storage();
        for v in [
            LayoutWidth::Auto,
            LayoutWidth::MinContent,
            LayoutWidth::MaxContent,
            LayoutWidth::FitContent(PixelValue::px(10.0)),
        ] {
            assert_eq!(
                from_layout_width(v.clone(), &storage, 16.0, 16.0),
                Dimension::auto(),
                "{v:?} is not forwarded to taffy — it becomes auto"
            );
        }
    }
    #[test]
    fn from_layout_width_resolves_lengths_and_percentages_and_defaults_to_auto() {
        let storage = empty_calc_storage();
        assert_eq!(
            from_layout_width(LayoutWidth::Px(PixelValue::px(0.0)), &storage, 16.0, 16.0),
            Dimension::length(0.0)
        );
        assert_eq!(
            from_layout_width(LayoutWidth::Px(PixelValue::px(-50.0)), &storage, 16.0, 16.0),
            Dimension::length(-50.0),
            "a negative width is nonsense CSS, but the bridge passes it straight through"
        );
        assert_eq!(
            from_layout_width(
                LayoutWidth::Px(PixelValue::percent(100.0)),
                &storage,
                16.0,
                16.0
            ),
            Dimension::percent(1.0)
        );
        assert_eq!(
            from_layout_height(LayoutHeight::Px(PixelValue::em(3.0)), &storage, 16.0, 16.0),
            Dimension::length(48.0),
            "em uses the 16px fallback, NOT the em_size argument"
        );
        // Viewport units cannot be resolved here → auto.
        assert_eq!(
            from_layout_width(
                LayoutWidth::Px(PixelValue::from_metric(SizeMetric::Vw, 100.0)),
                &storage,
                16.0,
                16.0
            ),
            Dimension::auto()
        );
        // NaN is already flattened to 0 by PixelValue itself.
        assert_eq!(
            from_layout_width(
                LayoutWidth::Px(PixelValue::px(f32::NAN)),
                &storage,
                16.0,
                16.0
            ),
            Dimension::length(0.0)
        );
        let huge = from_layout_height(
            LayoutHeight::Px(PixelValue::px(f32::INFINITY)),
            &storage,
            16.0,
            16.0,
        );
        assert!(huge.value().is_finite(), "an infinite height reached taffy");
    }
    #[test]
    fn from_layout_width_ignores_the_font_sizes_for_non_calc_values() {
        // em_size/rem_size are only wired into the calc() context; the Px path uses
        // the hard-coded 16px fallback. Passing NaN font sizes must therefore not
        // corrupt a plain `width: 2em`.
        let storage = empty_calc_storage();
        assert_eq!(
            from_layout_width(
                LayoutWidth::Px(PixelValue::em(2.0)),
                &storage,
                f32::NAN,
                f32::INFINITY
            ),
            Dimension::length(32.0)
        );
    }
    #[test]
    fn from_layout_width_calc_produces_a_calc_dimension_and_pins_the_context() {
        let storage = empty_calc_storage();
        let items = CalcAstItemVec::from_vec(vec![
            CalcAstItem::Value(PixelValue::percent(100.0)),
            CalcAstItem::Sub,
            CalcAstItem::Value(PixelValue::px(20.0)),
        ]);
        let d = from_layout_width(LayoutWidth::Calc(items), &storage, 20.0, 10.0);
        let raw = d.into_raw();
        assert!(raw.is_calc(), "calc() must reach taffy as a calc Dimension");
        assert_eq!(storage.borrow().len(), 1);
        // SAFETY: the Box is still owned by `storage`, exactly as during a layout pass.
        let ctx = unsafe { &*raw.calc_value().cast::<CalcResolveContext>() };
        assert_eq!(ctx.em_size, 20.0);
        assert_eq!(ctx.rem_size, 10.0);
        assert_eq!(ctx.items.as_ref().len(), 3);
    }
    #[test]
    fn store_calc_and_make_dimension_keeps_every_pointer_valid_across_vec_growth() {
        // The whole reason for Box<CalcResolveContext>: the outer Vec reallocates
        // many times while taffy is still holding raw pointers into it.
        let storage = empty_calc_storage();
        let dims: Vec<Dimension> = (0..256usize)
            .map(|i| {
                let items =
                    CalcAstItemVec::from_vec(vec![CalcAstItem::Value(PixelValue::px(i as f32))]);
                store_calc_and_make_dimension(items, &storage, i as f32, 16.0)
            })
            .collect();
        assert_eq!(storage.borrow().len(), 256);
        for (i, d) in dims.iter().enumerate() {
            let raw = d.into_raw();
            assert!(raw.is_calc(), "#{i} is not a calc dimension");
            // SAFETY: every Box is still alive in `storage`.
            let ctx = unsafe { &*raw.calc_value().cast::<CalcResolveContext>() };
            assert_eq!(
                ctx.em_size, i as f32,
                "context #{i} moved when the Vec reallocated"
            );
            assert_eq!(ctx.rem_size, 16.0);
            assert_eq!(ctx.items.as_ref().len(), 1);
        }
    }
    #[test]
    fn store_calc_and_make_dimension_accepts_an_empty_ast_and_nan_font_sizes() {
        let storage = empty_calc_storage();
        let d = store_calc_and_make_dimension(
            CalcAstItemVec::from_vec(Vec::new()),
            &storage,
            f32::NAN,
            f32::INFINITY,
        );
        let raw = d.into_raw();
        assert!(raw.is_calc());
        assert_eq!(storage.borrow().len(), 1);
        // SAFETY: the Box is still owned by `storage`.
        let ctx = unsafe { &*raw.calc_value().cast::<CalcResolveContext>() };
        assert!(ctx.items.as_ref().is_empty());
        assert!(
            ctx.em_size.is_nan() && ctx.rem_size.is_infinite(),
            "the font sizes are stored verbatim — evaluate_calc has to cope"
        );
    }
    #[test]
    fn store_calc_and_make_dimension_hands_out_a_distinct_pointer_per_call() {
        let storage = empty_calc_storage();
        let a =
            store_calc_and_make_dimension(CalcAstItemVec::from_vec(Vec::new()), &storage, 1.0, 1.0);
        let b =
            store_calc_and_make_dimension(CalcAstItemVec::from_vec(Vec::new()), &storage, 2.0, 2.0);
        assert_ne!(
            a.into_raw().calc_value(),
            b.into_raw().calc_value(),
            "two calc() values must not alias the same context"
        );
        assert_ne!(a, b);
    }
    // ==================================================================
    // compute_taffy_scrollbar_info — needs a real StyledDom + LayoutTree
    // ==================================================================
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    mod with_layout_context {
        use azul_core::{
            dom::{Dom, DomId},
            selection::TextSelection,
        };
        use azul_css::{props::basic::FontRef, LayoutDebugMessage};
        use super::*;
        use crate::{
            font_traits::FontManager,
            solver3::{cache, layout_tree::generate_layout_tree},
        };
        /// Owns everything a `LayoutContext` borrows.
        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() -> Self {
                let mut dom = Dom::create_body();
                let (css, _warnings) = azul_css::parser2::new_from_str("");
                Self {
                    styled_dom: StyledDom::create(&mut dom, css),
                    font_manager: FontManager::new(rust_fontconfig::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: std::collections::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: LogicalSize::new(800.0, 600.0),
                    fragmentation_context: None,
                    cursor_is_visible: true,
                    cursor_locations: Vec::new(),
                    preedit_text: None,
                    cache_map: 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,
                    },
                }
            }
        }
        #[test]
        fn compute_taffy_scrollbar_info_returns_defaults_for_an_out_of_range_node() {
            let mut env = Env::new();
            let mut ctx = env.ctx();
            let tree = generate_layout_tree(&mut ctx).expect("a plain body dom builds");
            for idx in [usize::MAX, tree.nodes.len(), tree.nodes.len() + 1] {
                let (info, w, h) = compute_taffy_scrollbar_info(
                    &ctx,
                    &tree,
                    idx,
                    100.0,
                    100.0,
                    500.0,
                    500.0,
                    ContentSizeOrigin::BorderBox,
                );
                assert!(!info.needs_horizontal, "#{idx}");
                assert!(!info.needs_vertical, "#{idx}");
                assert_eq!(w, 0.0);
                assert_eq!(h, 0.0);
            }
        }
        #[test]
        fn compute_taffy_scrollbar_info_never_reports_a_negative_or_nan_content_size() {
            let mut env = Env::new();
            let mut ctx = env.ctx();
            let tree = generate_layout_tree(&mut ctx).expect("a plain body dom builds");
            let root = tree.root;
            let extremes = [
                0.0f32,
                -1.0,
                f32::NAN,
                f32::INFINITY,
                f32::NEG_INFINITY,
                f32::MAX,
                f32::MIN,
            ];
            for v in extremes {
                for c in extremes {
                    let (_info, w, h) = compute_taffy_scrollbar_info(
                        &ctx,
                        &tree,
                        root,
                        v,
                        v,
                        c,
                        c,
                        ContentSizeOrigin::BorderBox,
                    );
                    assert!(
                        !w.is_nan() && w >= 0.0,
                        "result={v} content={c} → content width {w}"
                    );
                    assert!(
                        !h.is_nan() && h >= 0.0,
                        "result={v} content={c} → content height {h}"
                    );
                }
            }
        }
        #[test]
        fn compute_taffy_scrollbar_info_needs_no_scrollbars_for_an_overflow_visible_body() {
            let mut env = Env::new();
            let mut ctx = env.ctx();
            let tree = generate_layout_tree(&mut ctx).expect("a plain body dom builds");
            let root = tree.root;
            // Content far larger than the box: `overflow: visible` still must not
            // ask for scrollbars (only `auto`/`scroll` do).
            let (info, w, h) = compute_taffy_scrollbar_info(
                &ctx,
                &tree,
                root,
                100.0,
                100.0,
                10_000.0,
                10_000.0,
                ContentSizeOrigin::BorderBox,
            );
            assert!(!info.needs_horizontal);
            assert!(!info.needs_vertical);
            assert_eq!(info.scrollbar_width, 0.0);
            assert_eq!(info.scrollbar_height, 0.0);
            assert!(w > 0.0 && h > 0.0, "the taffy content size is passed back");
        }
    }
}