1
//! Final positioning of layout nodes (relative, absolute, and fixed schemes)
2
// +spec:positioning:79d47e - Implements relative, absolute, and fixed positioning schemes
3

            
4
use std::collections::BTreeMap;
5

            
6
use azul_core::{
7
    dom::{NodeId, NodeType},
8
    geom::{LogicalPosition, LogicalRect, LogicalSize},
9
    hit_test::ScrollPosition,
10
    resources::RendererResources,
11
    styled_dom::StyledDom,
12
};
13
use azul_css::{
14
    corety::LayoutDebugMessage,
15
    css::CssPropertyValue,
16
    props::{
17
        basic::pixel::PixelValue,
18
        layout::{LayoutPosition, LayoutWritingMode},
19
        property::{CssProperty, CssPropertyType},
20
    },
21
};
22

            
23
use crate::{
24
    debug_log,
25
    font_traits::{FontLoaderTrait, ParsedFontTrait, TextLayoutCache},
26
    solver3::{
27
        fc::{layout_formatting_context, FloatingContext, LayoutConstraints, TextAlign},
28
        getters::{
29
            get_aspect_ratio_property, get_css_bottom, get_css_height, get_css_left, get_css_right,
30
            get_css_top, get_css_width, get_direction_property, get_display_property, get_position,
31
            get_writing_mode, MultiValue,
32
        },
33
        layout_tree::{LayoutNodeId, LayoutTree},
34
        LayoutContext, LayoutError, Result,
35
    },
36
};
37

            
38
#[derive(Debug, Default)]
39
pub(crate) struct PositionOffsets {
40
    pub(crate) top: Option<f32>,
41
    pub(crate) right: Option<f32>,
42
    pub(crate) bottom: Option<f32>,
43
    pub(crate) left: Option<f32>,
44
}
45

            
46
// +spec:positioning:94ef0f - position property: static|relative|absolute|sticky|fixed, initial
47
// static, applies to all elements except table-column-group/table-column
48
/// Looks up the `position` property using the compact-cache-aware getter.
49
// +spec:positioning:ba937d - positioned elements have position != static
50
#[must_use]
51
3030465
pub fn get_position_type(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> LayoutPosition {
52
3030465
    let Some(id) = dom_id else {
53
1068
        return LayoutPosition::Static;
54
    };
55
3029397
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
56
3029397
    get_position(styled_dom, id, node_state).unwrap_or_default()
57
3030465
}
58

            
59
// +spec:positioning:bda1d5 - resolves inset properties (top/right/bottom/left) as inward offsets
60
// per CSS Position 3 §3.1 +spec:positioning:bf9168 - resolves inset properties
61
// (top/right/bottom/left) to control positioned box location +spec:positioning:f8e0a1 - inset
62
// properties (top/right/bottom/left) resolved for positioned elements; auto = unconstrained
63
/// Reads and resolves `top`, `right`, `bottom`, `left` properties,
64
/// including percentages relative to the containing block's size, and em/rem units.
65
// +spec:positioning:7ec143 - top/right/bottom/left offset resolution with percentage against
66
// containing block
67
#[allow(clippy::field_reassign_with_default)] // struct built incrementally / test setup; a struct
68
                                              // literal is not clearer here
69
7126
pub(crate) fn resolve_position_offsets(
70
7126
    styled_dom: &StyledDom,
71
7126
    dom_id: Option<NodeId>,
72
7126
    cb_size: LogicalSize,
73
7126
    viewport_size: LogicalSize,
74
7126
) -> PositionOffsets {
75
    use azul_css::props::basic::pixel::{PhysicalSize, PropertyContext, ResolutionContext};
76

            
77
    use crate::solver3::getters::{
78
        get_element_font_size, get_parent_font_size, get_root_font_size,
79
    };
80

            
81
7126
    let Some(id) = dom_id else {
82
1
        return PositionOffsets::default();
83
    };
84
7125
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
85

            
86
    // Create resolution context with font sizes and containing block size
87
7125
    let element_font_size = get_element_font_size(styled_dom, id, node_state);
88
7125
    let parent_font_size = get_parent_font_size(styled_dom, id, node_state);
89
7125
    let root_font_size = get_root_font_size(styled_dom, node_state);
90

            
91
7125
    let containing_block_size = PhysicalSize::new(cb_size.width, cb_size.height);
92

            
93
7125
    let resolution_context = ResolutionContext {
94
7125
        vertical_writing_mode: false,
95
7125
        element_font_size,
96
7125
        parent_font_size,
97
7125
        root_font_size,
98
7125
        containing_block_size,
99
7125
        element_size: None, // Not needed for position offsets
100
7125
        viewport_size: PhysicalSize::new(viewport_size.width, viewport_size.height),
101
7125
    };
102

            
103
7125
    let mut offsets = PositionOffsets::default();
104

            
105
    // +spec:containing-block:d4b3b9 - percentage offsets resolve against CB width (left/right) or
106
    // height (top/bottom) Resolve offsets using compact-cache-aware getters
107
    // top/bottom use Height context (% refers to containing block height)
108
7125
    offsets.top = match get_css_top(styled_dom, id, node_state) {
109
4911
        MultiValue::Exact(pv) => {
110
4911
            Some(pv.resolve_with_context(&resolution_context, PropertyContext::Height))
111
        }
112
2214
        _ => None,
113
    };
114

            
115
7125
    offsets.bottom = match get_css_bottom(styled_dom, id, node_state) {
116
554
        MultiValue::Exact(pv) => {
117
554
            Some(pv.resolve_with_context(&resolution_context, PropertyContext::Height))
118
        }
119
6571
        _ => None,
120
    };
121

            
122
    // left/right use Width context (% refers to containing block width)
123
7125
    offsets.left = match get_css_left(styled_dom, id, node_state) {
124
4889
        MultiValue::Exact(pv) => {
125
4889
            Some(pv.resolve_with_context(&resolution_context, PropertyContext::Width))
126
        }
127
2236
        _ => None,
128
    };
129

            
130
7125
    offsets.right = match get_css_right(styled_dom, id, node_state) {
131
564
        MultiValue::Exact(pv) => {
132
564
            Some(pv.resolve_with_context(&resolution_context, PropertyContext::Width))
133
        }
134
6561
        _ => None,
135
    };
136

            
137
7125
    offsets
138
7126
}
139

            
140
// +spec:block-formatting-context:f5f992 - Out-of-flow: floated or absolutely positioned boxes laid
141
// out outside normal flow +spec:positioning:bb19f8 - absolute/fixed positioning: out-of-flow,
142
// positioned relative to containing block/viewport
143
/// After the main layout pass, this function iterates through the tree and correctly
144
/// calculates the final positions of out-of-flow elements (`absolute`, `fixed`).
145
// +spec:positioning:5bfef3 - abspos elements use static position for auto offsets, resolve against
146
// nearest positioned ancestor CB +spec:positioning:7fff75 - Absolute positioning: removed from
147
// flow, offset relative to containing block, establishes new CB +spec:positioning:839cbb - absolute
148
// elements positioned/sized solely relative to their containing block, modified by inset properties
149
// +spec:positioning:898590 - absolute positioning takes elements out of flow and positions them
150
// relative to containing block +spec:positioning:c37c1b - abspos boxes laid out in containing block
151
// after its final size is determined +spec:positioning:cbe481 - absolute positioning removes
152
// elements from flow and positions them relative to containing block +spec:positioning:ebff77 -
153
// absolute positioning layout model (replaces old §6 abspos model) +spec:positioning:3b3ba4 -
154
// Absolute positioning: box offset from containing block, removed from normal flow; fixed
155
// positioning: CB = viewport
156
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
157
/// # Panics
158
///
159
/// Panics if a resolved offset (`top`/`bottom`) is None where both edges are expected.
160
8906
pub fn position_out_of_flow_elements<T: ParsedFontTrait>(
161
8906
    ctx: &mut LayoutContext<'_, T>,
162
8906
    tree: &mut LayoutTree,
163
8906
    text_cache: &mut TextLayoutCache,
164
8906
    calculated_positions: &mut super::PositionVec,
165
8906
    viewport: LogicalRect,
166
8906
) {
167
    use azul_css::props::style::StyleDirection;
168
    // Returns `()` (not Result<()>): inner fallible calls use skip-on-err (see above), so this fn
169
    // never propagates Err. Avoids the lift-fragile Result<(),LayoutError> Ok-niche read.
170
248294
    for node_index in 0..tree.nodes.len() {
171
248294
        let node = &tree.nodes[node_index];
172
248294
        let Some(dom_id) = node.dom_node_id else {
173
151
            continue;
174
        };
175

            
176
248143
        let position_type = get_position_type(ctx.styled_dom, Some(dom_id));
177

            
178
        // +spec:positioning:1d87f6 - Fixed/absolute positioning schemes with box offset resolution
179
        // (top/right/bottom/left) +spec:positioning:8bde1d - absolute: out of flow,
180
        // positioned by containing block +spec:positioning:c11be9 - absolute positioning:
181
        // effect of box offsets depends on which properties are auto (non-replaced) or intrinsic
182
        // dimensions (replaced) +spec:positioning:9020aa - "absolutely positioned" means
183
        // position:absolute or position:fixed
184
248143
        if position_type == LayoutPosition::Absolute || position_type == LayoutPosition::Fixed {
185
            // is a grid container have their CB determined by grid-placement properties;
186
            // Taffy already handles this during grid layout, so skip re-positioning here.
187
            // Same applies to flex containers (Flexbox §4.1).
188
            {
189
                use azul_core::dom::FormattingContext;
190
2510
                let parent_is_flex_or_grid = node
191
2510
                    .parent
192
2510
                    .and_then(|p| tree.get(LayoutNodeId::new(p)))
193
2510
                    .is_some_and(|pn| {
194
2438
                        matches!(
195
2440
                            pn.formatting_context,
196
                            FormattingContext::Flex | FormattingContext::Grid
197
                        )
198
2440
                    });
199
2510
                if parent_is_flex_or_grid {
200
2
                    continue;
201
2508
                }
202
            }
203

            
204
            // Get parent info before any mutable borrows
205
2508
            let parent_info: Option<(usize, LogicalPosition, f32, f32, f32, f32)> = {
206
2508
                let node = &tree.nodes[node_index];
207
2508
                node.parent.and_then(|parent_idx| {
208
2438
                    let parent_node = tree.get(LayoutNodeId::new(parent_idx))?;
209
2438
                    let parent_dom_id = parent_node.dom_node_id?;
210
2438
                    let parent_position = get_position_type(ctx.styled_dom, Some(parent_dom_id));
211
2438
                    if parent_position == LayoutPosition::Absolute
212
336
                        || parent_position == LayoutPosition::Fixed
213
                    {
214
2102
                        calculated_positions.get(parent_idx).map(|parent_pos| {
215
2102
                            let pbp = parent_node.box_props.unpack();
216
2102
                            (
217
2102
                                parent_idx,
218
2102
                                *parent_pos,
219
2102
                                pbp.border.left,
220
2102
                                pbp.border.top,
221
2102
                                pbp.padding.left,
222
2102
                                pbp.padding.top,
223
2102
                            )
224
2102
                        })
225
                    } else {
226
336
                        None
227
                    }
228
2438
                })
229
            };
230

            
231
            // +spec:containing-block:17a946 - fixed boxes use viewport as containing block
232
            // +spec:containing-block:83a32a - fixed positioning: containing block is viewport;
233
            // absolute: nearest positioned ancestor or initial CB
234
            // +spec:containing-block:9b617d - fixed elements use viewport (initial fixed containing
235
            // block) +spec:containing-block:899e47 - fixed elements use viewport
236
            // (initial fixed containing block) +spec:containing-block:faa9a3 - fixed
237
            // positioning falls back to initial containing block (viewport) when no ancestor
238
            // establishes one +spec:containing-block:faa9a3 - fixed positioning CB
239
            // falls back to initial containing block (viewport) when no ancestor establishes one
240
            // +spec:positioning:067eab - CB for fixed = viewport, for absolute = nearest positioned
241
            // ancestor +spec:positioning:067eab - fixed CB is viewport; absolute CB is
242
            // nearest positioned ancestor's padding-box +spec:positioning:9777da -
243
            // fixed positioning uses viewport as containing block +spec:positioning:
244
            // 9777da - Fixed positioning uses viewport as containing block
245
            // +spec:positioning:9ccf9a - fixed-position CB is viewport
246
            // (transform/will-change/contain could override, not yet implemented)
247
            // +spec:positioning:a68970 - fixed positioning uses viewport as containing block
248
            // +spec:positioning:8fff44 - fixed: same as absolute but positioned relative to
249
            // viewport +spec:positioning:744713 - fixed position uses viewport as
250
            // containing block +spec:positioning:f0ad47 - fixed elements use viewport
251
            // as containing block; content outside viewport cannot be scrolled to
252
            // +spec:containing-block:df8387 - fixed positioning: containing block is the viewport
253
2508
            let containing_block_rect = if position_type == LayoutPosition::Fixed {
254
3
                viewport
255
            } else {
256
                // skip-on-err (was `?`): a CB-resolution failure for one out-of-flow node skips
257
                // that node rather than aborting the whole layout. Lets this fn return `()`
258
                // (no Result<(),LayoutError> Ok-niche read, which the remill→wasm lift mis-lowers).
259
2505
                match find_absolute_containing_block_rect(
260
2505
                    tree,
261
2505
                    node_index,
262
2505
                    ctx.styled_dom,
263
2505
                    calculated_positions,
264
2505
                    viewport,
265
2505
                ) {
266
2505
                    Ok(r) => r,
267
                    Err(_) => continue,
268
                }
269
            };
270

            
271
            // Get node again after containing block calculation
272
2508
            let node = &tree.nodes[node_index];
273

            
274
            // Calculate used size for out-of-flow elements. ALWAYS solve from
275
            // the containing block + own CSS + intrinsics: abs elements are
276
            // skipped by the in-flow pass, so a pre-existing `used_size` here
277
            // is junk from that skip (typically Some(0x0)) — trusting it made
278
            // an auto-sized abs box (`top/left` only) keep 0x0 forever and
279
            // its children disappear. §10.3.7: their used size never depends
280
            // on in-flow layout, so recomputing is deterministic.
281
2508
            let element_size = {
282
2508
                let intrinsic = tree
283
2508
                    .warm(LayoutNodeId::new(node_index))
284
2508
                    .and_then(|w| w.intrinsic_sizes)
285
2508
                    .unwrap_or_default();
286
2508
                let Ok(size) = crate::solver3::sizing::calculate_used_size_for_node(
287
2508
                    ctx.styled_dom,
288
2508
                    Some(dom_id),
289
2508
                    // An abs-pos box resolves against its containing block's
290
2508
                    // RESOLVED rect — definite by construction here.
291
2508
                    &crate::solver3::geometry::ContainingBlock::definite(
292
2508
                        containing_block_rect.size,
293
2508
                    ),
294
2508
                    intrinsic,
295
2508
                    &node.box_props.unpack(),
296
2508
                    &ctx.viewport_size,
297
2508
                ) else {
298
                    continue;
299
                };
300

            
301
                // Store the calculated size in the tree node
302
2508
                if let Some(node_mut) = tree.get_mut(LayoutNodeId::new(node_index)) {
303
2508
                    node_mut.used_size = Some(size);
304
2508
                }
305

            
306
2508
                size
307
            };
308

            
309
            // +spec:positioning:dc23fa - sizing/positioning into inset-modified containing block
310
            // (§4) +spec:positioning:623e45 - inset properties reduce the containing
311
            // block into the inset-modified containing block Resolve offsets using the
312
            // now-known containing block size.
313
2508
            let offsets = resolve_position_offsets(
314
2508
                ctx.styled_dom,
315
2508
                Some(dom_id),
316
2508
                containing_block_rect.size,
317
2508
                viewport.size,
318
            );
319

            
320
            // +spec:box-model:ae3899 - static position is the margin-edge position from normal flow
321
            // +spec:positioning:9a90a3 - static position: the position the element would have had
322
            // in normal flow +spec:positioning:ca3e89 - static-position rectangle uses
323
            // block-start inline-start alignment (CSS2.1 hypothetical box)
324
2508
            let mut static_pos = calculated_positions
325
2508
                .get(node_index)
326
2508
                .copied()
327
2508
                .unwrap_or_default();
328

            
329
            // Special case: If this is a fixed-position element and it has a positioned
330
            // parent, update static_pos to be relative to the parent's final absolute
331
            // position (content-box). The initial static_pos from process_out_of_flow_children
332
            // may include border/padding offsets, so we must always recalculate here.
333
2508
            if position_type == LayoutPosition::Fixed {
334
                if let Some((_, parent_pos, border_left, border_top, padding_left, padding_top)) =
335
3
                    parent_info
336
                {
337
                    // Add parent's border and padding to get content-box position
338
                    static_pos = LogicalPosition::new(
339
                        parent_pos.x + border_left + padding_left,
340
                        parent_pos.y + border_top + padding_top,
341
                    );
342
3
                }
343
2505
            }
344

            
345
2508
            let mut final_pos = LogicalPosition::zero();
346

            
347
            // +spec:box-model:ea2f43 - top + margin + border + padding + height + bottom = CB
348
            // height +spec:box-model:b4f5b3 - vertical constraint equation for abs-pos
349
            // non-replaced elements +spec:positioning:16d82c - vertical dimension
350
            // constraint for abs-positioned non-replaced elements +spec:positioning:
351
            // 8f474b - §10.6.4 vertical constraint for absolutely positioned non-replaced elements
352
            // +spec:positioning:50218d - absolute: top margin edge offset below containing block
353
            // top edge top + margin-top + border-top + padding-top + height +
354
            // padding-bottom + border-bottom + margin-bottom + bottom = containing
355
            // block height
356
2508
            let node_state = &ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
357

            
358
            // Extract all box_props values upfront to avoid borrow conflicts with tree.get_mut()
359
            let (
360
2508
                margin_top_val,
361
2508
                margin_bottom_val,
362
2508
                margin_auto,
363
2508
                margin_left_val,
364
2508
                margin_right_val,
365
2508
                margin_left_auto_flag,
366
2508
                margin_right_auto_flag,
367
2508
            ) = {
368
2508
                let node = &tree.nodes[node_index];
369
2508
                let nbp = node.box_props.unpack();
370
2508
                (
371
2508
                    nbp.margin.top,
372
2508
                    nbp.margin.bottom,
373
2508
                    nbp.margin_auto,
374
2508
                    nbp.margin.left,
375
2508
                    nbp.margin.right,
376
2508
                    nbp.margin_auto.left,
377
2508
                    nbp.margin_auto.right,
378
2508
                )
379
2508
            };
380
            // +spec:positioning:d730e5 - CB height is independent of the abspos element, so
381
            // percentage heights always resolve
382
2508
            let cb_height = containing_block_rect.size.height;
383

            
384
2508
            let css_height = get_css_height(ctx.styled_dom, dom_id, node_state);
385
            // +spec:replaced-elements:7d8ba8 - §10.6.5: for absolutely positioned replaced
386
            // elements, height is determined first (as for inline replaced elements), so treat
387
            // it as "not auto" in the constraint equation even if CSS says auto.
388
2508
            let node_data = &ctx.styled_dom.node_data.as_container()[dom_id];
389
2508
            let is_replaced = matches!(node_data.node_type, NodeType::Image(_))
390
2508
                || node_data.is_virtual_view_node();
391
2508
            let height_is_auto = css_height.is_auto() && !is_replaced;
392
            // +spec:overflow:941a06 - resolve auto inset properties: if only one is auto, solved to
393
            // zero via constraint; if both auto, use static position
394
2508
            let top_is_auto = offsets.top.is_none();
395
2508
            let bottom_is_auto = offsets.bottom.is_none();
396

            
397
            // element_size is border-box (includes border + padding + content).
398
            // The constraint equation is:
399
            //   top + margin-top + border-box-height + margin-bottom + bottom = CB height
400
            // (border-top, padding-top, content-height, padding-bottom, border-bottom
401
            //  are all inside border-box-height)
402
2508
            let mut used_height = element_size.height;
403
            // +spec:height-calculation:44939a - set auto values for margin-top/margin-bottom to 0
404
            // +spec:height-calculation:2f6e10 - if bottom is auto, replace auto
405
            // margin-top/margin-bottom with 0
406
2508
            let mut used_margin_top = if margin_auto.top { 0.0 } else { margin_top_val };
407
2508
            let mut used_margin_bottom = if margin_auto.bottom {
408
1
                0.0
409
            } else {
410
2507
                margin_bottom_val
411
            };
412

            
413
            // +spec:box-model:3a9c2a - resolving auto insets: static position fallback when insets
414
            // are auto +spec:box-model:bd442c - weaker inset resolves to align margin
415
            // box with inset-modified CB edge +spec:height-calculation:93e91c - abs
416
            // non-replaced height: auto margin centering, single auto margin solve,
417
            // over-constrained ignore bottom +spec:positioning:6e7732 - §10.6.4
418
            // vertical constraint equation for abspos non-replaced elements
419
            // +spec:positioning:b63d0f - absolute positioning with top:auto uses static position
420
            // (change bars example) +spec:positioning:da8a0c - resolving auto insets:
421
            // normal alignment treated as start, so auto insets resolve to static position
422
            // +spec:positioning:820b22 - 10.6.4: absolutely positioned non-replaced elements
423
            // vertical constraint equation and 6 rules
424
2508
            if top_is_auto && height_is_auto && bottom_is_auto {
425
11
                // +spec:positioning:08e0ac - absolute element with top:auto uses static position
426
11
                // (current line) +spec:positioning:aab294 - both inset properties
427
11
                // auto: resolve to static position +spec:positioning:d9bb3c -
428
11
                // hypothetical position: UA may guess static position rather than fully computing
429
11
                // hypothetical box All three auto: set top to static position,
430
11
                // height from content, solve for bottom +spec:height-calculation:
431
11
                // 51627d - auto margins to 0, top = static position, height from content (rule 3)
432
11
                // +spec:positioning:460f2f - All three auto: set top to static position, height
433
11
                // from content, solve for bottom
434
11
                final_pos.y = static_pos.y;
435
2497
            } else if !top_is_auto && !height_is_auto && !bottom_is_auto {
436
                // +spec:overflow:fc0c9e - over-constrained abspos: auto margins minimize overflow
437
                // (CSS2.1 equivalent of Box Alignment 3 safe alignment)
438
                // +spec:positioning:88f760 - auto margins of absolutely-positioned boxes (vertical)
439
                // None are auto: over-constrained case
440
                // +spec:height-calculation:03c071 - none auto: equal auto margins, solve single
441
                // auto margin, or ignore bottom if over-constrained
442
10
                let top_val = offsets.top.unwrap();
443
10
                let bottom_val = offsets.bottom.unwrap();
444
10
                if margin_auto.top && margin_auto.bottom {
445
1
                    // +spec:height-calculation:5112a4 - both margin-top/bottom auto: solve with
446
1
                    // equal values
447
1
                    let available = cb_height - top_val - used_height - bottom_val;
448
1
                    let each = available / 2.0;
449
1
                    used_margin_top = each;
450
1
                    used_margin_bottom = each;
451
9
                } else if margin_auto.top {
452
                    used_margin_top =
453
                        cb_height - top_val - used_height - used_margin_bottom - bottom_val;
454
9
                } else if margin_auto.bottom {
455
                    used_margin_bottom =
456
                        cb_height - top_val - used_height - used_margin_top - bottom_val;
457
9
                }
458
                // else: over-constrained, ignore bottom
459
10
                final_pos.y = containing_block_rect.origin.y + top_val + used_margin_top;
460
2487
            } else if top_is_auto && height_is_auto && !bottom_is_auto {
461
8
                // +spec:height-calculation:909b50 - top and height auto, bottom not auto: height
462
8
                // from BFC auto heights, solve for top Rule 1: height from content,
463
8
                // auto margins to 0, solve for top
464
8
                let bottom_val = offsets.bottom.unwrap();
465
8
                let top_val =
466
8
                    cb_height - used_margin_top - used_height - used_margin_bottom - bottom_val;
467
8
                final_pos.y = containing_block_rect.origin.y + top_val + used_margin_top;
468
2479
            } else if top_is_auto && bottom_is_auto && !height_is_auto {
469
8
                // +spec:positioning:64e1ba - top+bottom auto, height not auto: set top to static
470
8
                // position, solve for bottom
471
8
                final_pos.y = static_pos.y;
472
2471
            } else if height_is_auto && bottom_is_auto && !top_is_auto {
473
1075
                // Rule 3: height from content, auto margins to 0, solve for bottom
474
1075
                let top_val = offsets.top.unwrap();
475
1075
                final_pos.y = containing_block_rect.origin.y + top_val + used_margin_top;
476
1396
            } else if top_is_auto && !height_is_auto && !bottom_is_auto {
477
8
                // +spec:height-calculation:33dce8 - top auto, height and bottom not auto: solve for
478
8
                // top Rule 4: auto margins to 0, solve for top
479
8
                let bottom_val = offsets.bottom.unwrap();
480
8
                let top_val =
481
8
                    cb_height - used_margin_top - used_height - used_margin_bottom - bottom_val;
482
8
                final_pos.y = containing_block_rect.origin.y + top_val + used_margin_top;
483
1388
            } else if height_is_auto && !top_is_auto && !bottom_is_auto {
484
                // +spec:intrinsic-sizing:566a43 - abspos auto height with non-auto insets:
485
                // stretch-fit size +spec:intrinsic-sizing:c7227f - except: if box
486
                // has aspect-ratio, ratio-dependent axis uses max-content
487
234
                let has_aspect_ratio = matches!(
488
234
                    get_aspect_ratio_property(ctx.styled_dom, dom_id, node_state),
489
                    MultiValue::Exact(azul_css::props::style::effects::StyleAspectRatio::Ratio(_))
490
                );
491
234
                let top_val = offsets.top.unwrap();
492
234
                let bottom_val = offsets.bottom.unwrap();
493
234
                if !has_aspect_ratio {
494
234
                    // solve for height from constraint equation (stretch-fit):
495
234
                    // height = cb_height - top - margin_top - margin_bottom - bottom
496
234
                    // +spec:containing-block:b3f0dd - clamp effective CB size to zero when insets
497
234
                    // exceed it (weaker inset reduced)
498
234
                    used_height =
499
234
                        (cb_height - top_val - used_margin_top - used_margin_bottom - bottom_val)
500
234
                            .max(0.0);
501
234
                }
502
                // else: keep content-based height (max-content) per aspect-ratio exception
503
234
                final_pos.y = containing_block_rect.origin.y + top_val + used_margin_top;
504
                // Update the element size with the resolved height
505
234
                if let Some(node_mut) = tree.get_mut(LayoutNodeId::new(node_index)) {
506
234
                    if let Some(ref mut size) = node_mut.used_size {
507
234
                        size.height = used_height;
508
234
                    }
509
                }
510
1154
            } else if bottom_is_auto && !top_is_auto && !height_is_auto {
511
1154
                // Rule 6: auto margins to 0, solve for bottom
512
1154
                let top_val = offsets.top.unwrap();
513
1154
                final_pos.y = containing_block_rect.origin.y + top_val + used_margin_top;
514
1154
            } else {
515
                // Fallback to static position
516
                final_pos.y = static_pos.y;
517
            }
518

            
519
            // +spec:box-model:984243 - horizontal constraint equation for abs-pos non-replaced
520
            // elements +spec:positioning:3be194 - position abs replaced element after
521
            // establishing width Constraint: left + margin-left + border-left +
522
            // padding-left + width + +spec:width-calculation:1661b4 - constraint
523
            // equation and six rules for abs-pos horizontal (§10.3.7)
524
            // left + margin-left + border-left + padding-left + width +
525
            //   padding-right + border-right + margin-right + right = CB width
526
            // Since element_size.width is border-box (border + padding + content),
527
            // simplifies to: left + margin-left + border_box_width + margin-right + right = CB
528
            // width
529
            {
530
2508
                let margin_left = margin_left_val;
531
2508
                let margin_right = margin_right_val;
532
2508
                let margin_left_auto = margin_left_auto_flag;
533
2508
                let margin_right_auto = margin_right_auto_flag;
534
2508
                let cb_width = containing_block_rect.size.width;
535
2508
                let border_box_width = element_size.width;
536
2508
                let left_val = offsets.left;
537
2508
                let right_val = offsets.right;
538
2508
                let left_is_auto = left_val.is_none();
539
2508
                let right_is_auto = right_val.is_none();
540

            
541
                // Get direction of containing block for over-constrained resolution
542
2508
                let cb_direction = {
543
2508
                    let cb_dom_id = if position_type == LayoutPosition::Fixed {
544
3
                        None // viewport CB, default LTR
545
                    } else {
546
2505
                        let mut parent = tree.nodes[node_index].parent;
547
2505
                        let mut found = None;
548
2510
                        while let Some(pidx) = parent {
549
2438
                            if let Some(pnode) = tree.get(LayoutNodeId::new(pidx)) {
550
2438
                                if get_position_type(ctx.styled_dom, pnode.dom_node_id)
551
2438
                                    .is_positioned()
552
                                {
553
2433
                                    found = pnode.dom_node_id;
554
2433
                                    break;
555
5
                                }
556
5
                                parent = pnode.parent;
557
                            } else {
558
                                break;
559
                            }
560
                        }
561
2505
                        found
562
                    };
563
2508
                    match cb_dom_id {
564
2433
                        Some(cb_id) => {
565
2433
                            let cb_ns = &ctx.styled_dom.styled_nodes.as_container()[cb_id]
566
2433
                                .styled_node_state;
567
2433
                            match get_direction_property(ctx.styled_dom, cb_id, cb_ns) {
568
2433
                                MultiValue::Exact(v) => v,
569
                                _ => StyleDirection::Ltr,
570
                            }
571
                        }
572
75
                        None => StyleDirection::Ltr,
573
                    }
574
                };
575

            
576
                // +spec:replaced-elements:7d8ba8 - §10.3.8: for absolutely positioned replaced
577
                // elements, width is determined first (as for inline replaced), so
578
                // treat as "not auto" in the constraint.
579
2508
                let width_is_auto =
580
2508
                    get_css_width(ctx.styled_dom, dom_id, node_state).is_auto() && !is_replaced;
581

            
582
2508
                if !left_is_auto && !width_is_auto && !right_is_auto {
583
                    // +spec:positioning:88f760 - auto margins of absolutely-positioned boxes
584
                    // (horizontal) +spec:width-calculation:942c77 - abs-pos
585
                    // non-replaced width: auto margins, over-constrained resolution
586
                    // None of left/width/right are auto — solve for margins or handle
587
                    // over-constrained +spec:width-calculation:dff69d - §10.3.7
588
                    // abs-pos non-replaced: none auto → equal auto margins, solve single auto
589
                    // margin, or over-constrained
590
12
                    let left = left_val.unwrap();
591
12
                    let right = right_val.unwrap();
592
12
                    let remaining = cb_width - left - border_box_width - right;
593

            
594
                    // +spec:writing-modes:9c3b40 - abspos auto margins: if negative remaining in
595
                    // inline axis, start margin=0, end margin gets remainder
596
12
                    if margin_left_auto && margin_right_auto {
597
                        // +spec:positioning:ab47b3 - auto margins can be negative in absolute
598
                        // positioning Both margins auto: equal values
599
                        // unless negative
600
2
                        let each_margin = remaining / 2.0;
601
2
                        if each_margin < 0.0 {
602
1
                            match cb_direction {
603
1
                                StyleDirection::Ltr => {
604
1
                                    final_pos.x = containing_block_rect.origin.x + left;
605
1
                                }
606
                                StyleDirection::Rtl => {
607
                                    final_pos.x = containing_block_rect.origin.x + left + remaining;
608
                                }
609
                            }
610
1
                        } else {
611
1
                            final_pos.x = containing_block_rect.origin.x + left + each_margin;
612
1
                        }
613
10
                    } else if margin_left_auto {
614
                        let solved_margin_left = remaining - margin_right;
615
                        final_pos.x = containing_block_rect.origin.x + left + solved_margin_left;
616
10
                    } else if margin_right_auto {
617
                        final_pos.x = containing_block_rect.origin.x + left + margin_left;
618
                    } else {
619
                        // Over-constrained: ignore right (LTR) or left (RTL)
620
10
                        match cb_direction {
621
9
                            StyleDirection::Ltr => {
622
9
                                final_pos.x = containing_block_rect.origin.x + left + margin_left;
623
9
                            }
624
1
                            StyleDirection::Rtl => {
625
1
                                let solved_left = cb_width
626
1
                                    - margin_left
627
1
                                    - border_box_width
628
1
                                    - margin_right
629
1
                                    - right;
630
1
                                final_pos.x =
631
1
                                    containing_block_rect.origin.x + solved_left + margin_left;
632
1
                            }
633
                        }
634
                    }
635
                } else {
636
                    // +spec:overflow:f323cb - auto inset: align margin box to stronger inset edge
637
                    // (may overflow CB) +spec:width-calculation:bbf97a - set
638
                    // auto margins to 0 for abspos when left/width/right has auto
639
                    // Set auto margins to 0, apply six rules
640
                    // +spec:box-model:2da091 - if either inset is auto, auto margins resolve to
641
                    // zero +spec:intrinsic-sizing:087b57 - abspos auto margins
642
                    // resolve to 0 when any inset is auto
643
                    // +spec:width-calculation:0c29ce - set auto margins to 0, then apply six rules
644
                    // for abs pos width
645
2496
                    let m_left = if margin_left_auto { 0.0 } else { margin_left };
646
2496
                    let m_right = if margin_right_auto { 0.0 } else { margin_right };
647

            
648
                    // +spec:width-calculation:2b2852 - all three auto: set auto margins to 0, use
649
                    // static position for left (LTR) +spec:width-calculation:
650
                    // c120b3 - all three of left/width/right auto: set auto margins to 0, then use
651
                    // direction to pick static position
652
2496
                    if left_is_auto && width_is_auto && right_is_auto {
653
11
                        match cb_direction {
654
11
                            StyleDirection::Ltr => {
655
11
                                // Set left to static position, apply rule 3 (width from content,
656
11
                                // solve for right)
657
11
                                final_pos.x = static_pos.x;
658
11
                            }
659
                            StyleDirection::Rtl => {
660
                                // Set right to static position, apply rule 1 (width from content,
661
                                // solve for left)
662
                                let static_offset = static_pos.x - containing_block_rect.origin.x;
663
                                let right_static =
664
                                    (cb_width - static_offset - border_box_width).max(0.0);
665
                                let solved_left =
666
                                    cb_width - m_left - border_box_width - m_right - right_static;
667
                                final_pos.x = containing_block_rect.origin.x + solved_left + m_left;
668
                            }
669
                        }
670
2485
                    } else if left_is_auto && width_is_auto && !right_is_auto {
671
8
                        // left+width auto, right not auto: width from content, solve for left
672
8
                        let right = right_val.unwrap();
673
8
                        let solved_left = cb_width - m_left - border_box_width - m_right - right;
674
8
                        final_pos.x = containing_block_rect.origin.x + solved_left + m_left;
675
2477
                    } else if left_is_auto && !width_is_auto && right_is_auto {
676
8
                        // left+right auto: set left to static position (LTR)
677
8
                        final_pos.x = static_pos.x;
678
2469
                    } else if !left_is_auto && width_is_auto && right_is_auto {
679
1075
                        // width+right auto: position from left
680
1075
                        let left = left_val.unwrap();
681
1075
                        final_pos.x = containing_block_rect.origin.x + left + m_left;
682
1394
                    } else if left_is_auto && !width_is_auto && !right_is_auto {
683
18
                        // left auto: solve for left
684
18
                        let right = right_val.unwrap();
685
18
                        let solved_left = cb_width - m_left - border_box_width - m_right - right;
686
18
                        final_pos.x = containing_block_rect.origin.x + solved_left + m_left;
687
1376
                    } else if !left_is_auto && width_is_auto && !right_is_auto {
688
                        // +spec:intrinsic-sizing:566a43 - abspos auto width with non-auto insets:
689
                        // stretch-fit size +spec:intrinsic-sizing:c7227f -
690
                        // except: if box has aspect-ratio, ratio-dependent axis uses max-content
691
232
                        let has_aspect_ratio = matches!(
692
232
                            get_aspect_ratio_property(ctx.styled_dom, dom_id, node_state),
693
                            MultiValue::Exact(
694
                                azul_css::props::style::effects::StyleAspectRatio::Ratio(_)
695
                            )
696
                        );
697
232
                        let left = left_val.unwrap();
698
232
                        let right = right_val.unwrap();
699
232
                        if !has_aspect_ratio {
700
                            // width = cb_width - left - margin_left - margin_right - right
701
232
                            let used_width = (cb_width - left - m_left - m_right - right).max(0.0);
702
232
                            if let Some(node_mut) = tree.get_mut(LayoutNodeId::new(node_index)) {
703
232
                                if let Some(ref mut size) = node_mut.used_size {
704
232
                                    size.width = used_width;
705
232
                                }
706
                            }
707
                        }
708
                        // else: keep content-based width (max-content) per aspect-ratio exception
709
232
                        final_pos.x = containing_block_rect.origin.x + left + m_left;
710
1144
                    } else if !left_is_auto && !width_is_auto && right_is_auto {
711
1144
                        // right auto: position from left
712
1144
                        let left = left_val.unwrap();
713
1144
                        final_pos.x = containing_block_rect.origin.x + left + m_left;
714
1144
                    } else {
715
                        final_pos.x = static_pos.x;
716
                    }
717
                }
718
            }
719

            
720
2508
            super::pos_set(calculated_positions, node_index, final_pos);
721

            
722
            // The absolute box is now at its FINAL, definite size (§10.3.7 /
723
            // §10.6.4) — "abspos boxes laid out in containing block after its
724
            // final size is determined". The in-flow pass deliberately skips
725
            // abs subtrees, so THIS is the one authoritative interior layout:
726
            // against the solved box, unconditionally (before, a collapsed-
727
            // child heuristic left block interiors unlaid — children of an
728
            // abs box simply disappeared — and the flex path let the taffy
729
            // root re-derive the box's own height from content, clobbering
730
            // the §10.6.4 stretch-fit). The solved border-box size is
731
            // restored after the run precisely because a formatting-context
732
            // root may re-derive its own size; child positions are then
733
            // propagated from the final box (the interior run only writes
734
            // warm relative positions). The abs box's used size is
735
            // independent of its content, so this cannot loop.
736
2508
            let mut solved_size = tree.nodes[node_index].used_size.unwrap_or(element_size);
737
2508
            if !tree.children(node_index).is_empty() {
738
2267
                let inner = tree.nodes[node_index]
739
2267
                    .box_props
740
2267
                    .inner_size(solved_size, LayoutWritingMode::HorizontalTb);
741
2267
                let constraints = LayoutConstraints {
742
2267
                    available_size: inner,
743
2267
                    writing_mode: LayoutWritingMode::HorizontalTb,
744
2267
                    writing_mode_ctx: super::geometry::WritingModeContext::default(),
745
2267
                    bfc_state: None,
746
2267
                    text_align: TextAlign::Start,
747
2267
                    containing_block_size: inner,
748
2267
                    available_width_type: crate::text3::cache::AvailableSpace::Definite(
749
2267
                        inner.width,
750
2267
                    ),
751
2267
                    fragmentainer: None,
752
2267
                };
753
2267
                let mut reflow_float_cache: std::collections::HashMap<usize, FloatingContext> =
754
2267
                    std::collections::HashMap::new();
755
2267
                let interior = layout_formatting_context(
756
2267
                    ctx,
757
2267
                    tree,
758
2267
                    text_cache,
759
2267
                    node_index,
760
2267
                    &constraints,
761
2267
                    &mut reflow_float_cache,
762
                );
763

            
764
                // The interior run writes each child's position into
765
                // `output.positions` but NOT into `warm.relative_position`,
766
                // which `position_bfc_child_descendants` (below) reads. Without
767
                // this transfer, an absolutely-positioned box's 2nd+ in-flow
768
                // children all collapse onto its content-box origin — a
769
                // multi-item dropdown/list draws every row on top of the first.
770
                // Mirrors the flex-item transfer in taffy_bridge.rs (~L2110).
771
2267
                if let Ok(res) = &interior {
772
2359
                    for (child_idx, child_pos) in &res.output.positions {
773
92
                        if let Some(child_warm) = tree.warm_mut(LayoutNodeId::new(*child_idx)) {
774
92
                            child_warm.relative_position = Some(*child_pos);
775
92
                        }
776
                    }
777
                }
778

            
779
                // §10.6.4 rules 1 and 3: with height:auto and at most one
780
                // vertical inset, the used height IS the laid-out content
781
                // height — adopt it from the interior run (the pre-layout
782
                // value was the 0 placeholder). Rule 1 (bottom set, top
783
                // auto) then re-derives top with the REAL height.
784
2267
                if height_is_auto && (top_is_auto || bottom_is_auto) {
785
1060
                    if let Ok(res) = &interior {
786
1060
                        let bp = tree.nodes[node_index].box_props.unpack();
787
1060
                        solved_size.height = res.output.overflow_size.height
788
1060
                            + bp.padding.top
789
1060
                            + bp.padding.bottom
790
1060
                            + bp.border.top
791
1060
                            + bp.border.bottom;
792
1060
                        if top_is_auto && !bottom_is_auto {
793
                            let bottom_val = offsets.bottom.unwrap_or(0.0);
794
                            let top_val = cb_height
795
                                - used_margin_top
796
                                - solved_size.height
797
                                - used_margin_bottom
798
                                - bottom_val;
799
                            final_pos.y =
800
                                containing_block_rect.origin.y + top_val + used_margin_top;
801
                            super::pos_set(calculated_positions, node_index, final_pos);
802
1060
                        }
803
                    }
804
1207
                }
805

            
806
2267
                if let Some(node_mut) = tree.get_mut(LayoutNodeId::new(node_index)) {
807
2267
                    node_mut.used_size = Some(solved_size);
808
2267
                }
809
2267
                let bp = tree.nodes[node_index].box_props.unpack();
810
2267
                let content_pos = LogicalPosition::new(
811
2267
                    final_pos.x + bp.border.left + bp.padding.left,
812
2267
                    final_pos.y + bp.border.top + bp.padding.top,
813
                );
814
2267
                crate::solver3::cache::position_bfc_child_descendants(
815
2267
                    tree,
816
2267
                    node_index,
817
2267
                    content_pos,
818
2267
                    calculated_positions,
819
                );
820
241
            }
821
245633
        }
822
    }
823
8906
}
824

            
825
// +spec:positioning:5b0d7f - relative positioning: offset from normal flow position, siblings
826
// unaffected +spec:positioning:8afbe2 - Relative positioning preserves normal flow size and space;
827
// only visual offset applied after layout +spec:positioning:3502d5 - relative and absolute
828
// positioning supported for combined use +spec:positioning:b22222 - relative positioning: offset
829
// from static position, purely visual effect +spec:positioning:b814b6 - relative/absolute/fixed
830
// positioning scheme (CSS Positioned Layout Module Level 3)
831
/// Final pass to shift relatively positioned elements from their static flow position.
832
// +spec:block-formatting-context:60ccf9 - relative positioning shifts inline boxes as a unit after
833
// normal flow +spec:display-property:17239f - relative positioning offsets element after normal
834
// flow; abspos elements taken out of flow +spec:positioning:cbe066 - relative positioning
835
// implementation
836
///
837
/// Resolves percentage-based offsets for `top`, `left`, etc.
838
/// For relatively positioned elements, percentages are
839
/// relative to the dimensions of the parent element's content box.
840
// +spec:positioning:2d8e15 - relative positioning shifts elements as a unit after normal flow
841
// without affecting surrounding content
842
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
843
                                 // (one branch per case)
844
8841
pub fn adjust_relative_positions<T: ParsedFontTrait>(
845
8841
    ctx: &mut LayoutContext<'_, T>,
846
8841
    tree: &LayoutTree,
847
8841
    calculated_positions: &mut super::PositionVec,
848
8841
    viewport: LogicalRect, // The viewport is needed if the root element is relative.
849
8841
) {
850
    use azul_css::props::style::StyleDirection;
851
    // NOTE: returns `()` (not `Result<()>`). This fn is Ok-always — its only `?` are on `Option`
852
    // inside `.and_then` closures, never propagating to the fn body. The previous `Result<(),
853
    // LayoutError>` return forced the `?` at the call site to read an Ok-niche discriminant, which
854
    // the remill→wasm lift mis-lowers (per-build, ASLR-dependent) → a FALSE Err that aborted the
855
    // whole layout in the web backend (rect=0). Matches sibling reposition_* fns that return ().
856
    // Iterate through all nodes. We need the index to modify the position map.
857
248165
    for node_index in 0..tree.nodes.len() {
858
248165
        let node = &tree.nodes[node_index];
859
248165
        let position_type = get_position_type(ctx.styled_dom, node.dom_node_id);
860

            
861
        // +spec:block-formatting-context:faa1cf - static boxes: top/right/bottom/left do not apply
862
        // Early continue for non-relative positioning
863
        // +spec:overflow:cfb09a - Sticky positioning uses relative-like offsets, clamped to nearest
864
        // scrollport at scroll time
865
248165
        if position_type != LayoutPosition::Relative && position_type != LayoutPosition::Sticky {
866
246015
            continue;
867
2150
        }
868

            
869
        // +spec:table-layout:6cb73b - position:relative effect on table elements is undefined; skip
870
        // them +spec:table-layout:718f91 - relative positioning on table-row/row-group
871
        // shifts all contents
872
        {
873
            use azul_css::props::layout::LayoutDisplay;
874
2150
            let display = get_display_property(ctx.styled_dom, node.dom_node_id);
875
2150
            if let MultiValue::Exact(d) = display {
876
                // +spec:positioning:4614dd - position does not apply to table-column-group or
877
                // table-column boxes Table-row and row-group elements DO support
878
                // relative positioning: the shift affects all contents including
879
                // cells originating in the row. Table-column, table-column-group,
880
                // table-cell, and table-caption do not.
881
2147
                if matches!(
882
2150
                    d,
883
                    LayoutDisplay::TableColumnGroup
884
                        | LayoutDisplay::TableColumn
885
                        | LayoutDisplay::TableCell
886
                        | LayoutDisplay::TableCaption
887
                ) {
888
3
                    continue;
889
2147
                }
890
            }
891
        }
892

            
893
        // Determine the containing block size for resolving percentages.
894
        // For `position: relative`, this is the parent's content box size.
895
2147
        let containing_block_size = node
896
2147
            .parent
897
2147
            .and_then(|parent_idx| tree.get(LayoutNodeId::new(parent_idx)))
898
2147
            .map_or(viewport.size, |parent_node| {
899
                // Get parent's writing mode to correctly calculate its inner (content) size.
900
2147
                let parent_wm = parent_node
901
2147
                    .dom_node_id
902
2147
                    .map(|pid| {
903
2137
                        let ps = &ctx.styled_dom.styled_nodes.as_container()[pid].styled_node_state;
904
2137
                        get_writing_mode(ctx.styled_dom, pid, ps).unwrap_or_default()
905
2137
                    })
906
2147
                    .unwrap_or_default();
907
2147
                let parent_used_size = parent_node.used_size.unwrap_or_default();
908
2147
                parent_node
909
2147
                    .box_props
910
2147
                    .inner_size(parent_used_size, parent_wm)
911
2147
            });
912

            
913
        // +spec:positioning:418c74 - inset percentages resolve against containing block size per
914
        // axis; auto is unconstrained
915
2147
        let offsets = resolve_position_offsets(
916
2147
            ctx.styled_dom,
917
2147
            node.dom_node_id,
918
2147
            containing_block_size,
919
2147
            viewport.size,
920
        );
921

            
922
        // Get a mutable reference to the position and apply the offsets.
923
2147
        let Some(current_pos) = calculated_positions.get_mut(node_index) else {
924
1
            continue;
925
        };
926

            
927
2146
        let initial_pos = *current_pos;
928

            
929
        // +spec:positioning:5eb813 - relative positioning offsets contents from normal flow
930
        // position +spec:positioning:a2e5f1 - relative positioning shifts element from
931
        // static position (vs absolute/float) top/bottom/left/right offsets are applied
932
        // relative to the static position.
933
2146
        let mut delta_x = 0.0;
934
2146
        let mut delta_y = 0.0;
935

            
936
        // +spec:positioning:218b50 - Relative positioning: top=-bottom, left=-right,
937
        // direction-dependent resolution, top wins over bottom According to CSS 2.1 Section
938
        // 9.4.3:
939
        // - For `top` and `bottom`: if both are specified, `top` wins and `bottom` is ignored
940
        // - For `left` and `right`: depends on direction (ltr/rtl)
941
        //   - In LTR: if both specified, `left` wins and `right` is ignored
942
        //   - In RTL: if both specified, `right` wins and `left` is ignored
943

            
944
        // +spec:overflow:53dffd - both left/right auto → used values are 0, boxes stay in original
945
        // position +spec:positioning:5a099e - negative offsets can cause overlapping (no
946
        // clamping applied) +spec:positioning:d189de - bottom offset for relative
947
        // positioning is with respect to the box's own bottom edge +spec:positioning:d80f47
948
        // - opposing inset values are negations: top wins over bottom, left/right per direction
949
        // +spec:positioning:ecc27c - relative positioning: left/right move box horizontally without
950
        // changing size, left = -right +spec:positioning:50218d - relative: offset from
951
        // static position (top edges of box itself) both auto → 0; one auto → negative of
952
        // other; neither auto → bottom ignored (top wins) +spec:positioning:ac768b -
953
        // relative positioning: both auto→0, one auto→neg of other, neither→top wins;
954
        // direction-aware left/right +spec:positioning:e3727e - top/bottom: both auto→0,
955
        // one auto→negative of other, neither auto→bottom ignored Vertical positioning:
956
        // `top` takes precedence over `bottom`
957
2146
        if let Some(top) = offsets.top {
958
9
            delta_y = top;
959
2142
        } else if let Some(bottom) = offsets.bottom {
960
1
            delta_y = -bottom;
961
2136
        }
962

            
963
        // +spec:positioning:1732e8 - left/right for relatively positioned elements determined by
964
        // 9.4.3 rules Spec: "If the 'direction' property of the containing block is 'ltr',
965
        // the value of 'left' wins" Get the direction of the containing block (parent), not
966
        // the element itself
967
2146
        let cb_direction = node
968
2146
            .parent
969
2146
            .and_then(|parent_idx| tree.get(LayoutNodeId::new(parent_idx)))
970
2146
            .and_then(|parent_node| {
971
2146
                let parent_dom_id = parent_node.dom_node_id?;
972
2136
                let parent_state =
973
2136
                    &ctx.styled_dom.styled_nodes.as_container()[parent_dom_id].styled_node_state;
974
2136
                match get_direction_property(ctx.styled_dom, parent_dom_id, parent_state) {
975
2136
                    MultiValue::Exact(v) => Some(v),
976
                    _ => None,
977
                }
978
2146
            })
979
2146
            .unwrap_or(StyleDirection::Ltr);
980
        // +spec:containing-block:6d4fb1 - over-constrained relative positioning: ltr→left wins,
981
        // rtl→right wins
982
2146
        match cb_direction {
983
            StyleDirection::Ltr => {
984
2145
                if let Some(left) = offsets.left {
985
7
                    delta_x = left;
986
2140
                } else if let Some(right) = offsets.right {
987
1
                    // +spec:overflow:fb426c - left auto: used value is minus the value of right
988
1
                    delta_x = -right;
989
2137
                }
990
            }
991
            StyleDirection::Rtl => {
992
1
                if let Some(right) = offsets.right {
993
1
                    delta_x = -right;
994
1
                } else if let Some(left) = offsets.left {
995
                    delta_x = left;
996
                }
997
            }
998
        }
999

            
        // +spec:overflow:f1e1ce - relative positioning may cause overflow:auto/scroll boxes to need
        // scrollbars Only apply the shift if there is a non-zero delta.
2146
        if delta_x != 0.0 || delta_y != 0.0 {
12
            current_pos.x += delta_x;
12
            current_pos.y += delta_y;
12
            debug_log!(
                ctx,
                "Adjusted relative element #{} from {:?} to {:?} (delta: {}, {})",
                node_index,
                initial_pos,
                *current_pos,
                delta_x,
                delta_y
            );
            // +spec:table-layout:ec2600 - For table-row-group, table-header-group,
            // table-footer-group, or table-row, the relative shift affects all contents
            // of the box including table cells. Propagate the delta to all descendant
            // nodes.
            {
                use azul_css::props::layout::LayoutDisplay;
12
                let display = get_display_property(ctx.styled_dom, node.dom_node_id);
12
                let is_table_row_like = matches!(
12
                    display,
                    MultiValue::Exact(
                        LayoutDisplay::TableRowGroup
                            | LayoutDisplay::TableHeaderGroup
                            | LayoutDisplay::TableFooterGroup
                            | LayoutDisplay::TableRow
                    )
                );
12
                if is_table_row_like {
                    // Shift all children (and their descendants) by the same delta
1
                    let mut stack = tree.children(node_index).to_vec();
2
                    while let Some(child_idx) = stack.pop() {
1
                        if let Some(child_pos) = calculated_positions.get_mut(child_idx) {
1
                            child_pos.x += delta_x;
1
                            child_pos.y += delta_y;
1
                        }
1
                        stack.extend_from_slice(tree.children(child_idx));
                    }
11
                }
            }
2134
        }
    }
8841
}
// +spec:overflow:bac4e5 - sticky view rectangle from inset properties relative to nearest
// scrollport
/// Finds the nearest scrollport (ancestor with overflow: scroll or auto) for a node.
/// Returns the content-box rect of the scrollport, or the viewport if none found.
27
fn find_nearest_scrollport(
27
    tree: &LayoutTree,
27
    node_index: usize,
27
    styled_dom: &StyledDom,
27
    calculated_positions: &super::PositionVec,
27
    viewport: LogicalRect,
27
) -> LogicalRect {
    use azul_css::props::layout::LayoutOverflow;
    use crate::solver3::getters::{get_overflow_x, get_overflow_y};
27
    let mut current_parent_idx = tree
27
        .get(LayoutNodeId::new(node_index))
27
        .and_then(|n| n.parent);
34
    while let Some(parent_index) = current_parent_idx {
28
        let Some(parent_node) = tree.get(LayoutNodeId::new(parent_index)) else {
            break;
        };
28
        let Some(parent_dom_id) = parent_node.dom_node_id else {
1
            current_parent_idx = parent_node.parent;
1
            continue;
        };
27
        let node_state = &styled_dom.styled_nodes.as_container()[parent_dom_id].styled_node_state;
27
        let ox = get_overflow_x(styled_dom, parent_dom_id, node_state);
27
        let oy = get_overflow_y(styled_dom, parent_dom_id, node_state);
27
        let is_scrollport = matches!(
27
            ox,
            MultiValue::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto)
6
        ) || matches!(
23
            oy,
            MultiValue::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto)
        );
27
        if is_scrollport {
21
            let margin_box_pos = calculated_positions
21
                .get(parent_index)
21
                .copied()
21
                .unwrap_or_default();
21
            let border_box_size = parent_node.used_size.unwrap_or_default();
            // Content-box = margin-box pos + border + padding, size - border - padding
21
            let pbp = parent_node.box_props.unpack();
21
            let content_pos = LogicalPosition::new(
21
                margin_box_pos.x + pbp.border.left + pbp.padding.left,
21
                margin_box_pos.y + pbp.border.top + pbp.padding.top,
            );
21
            let content_size = LogicalSize::new(
21
                (border_box_size.width
21
                    - pbp.border.left
21
                    - pbp.border.right
21
                    - pbp.padding.left
21
                    - pbp.padding.right)
21
                    .max(0.0),
21
                (border_box_size.height
21
                    - pbp.border.top
21
                    - pbp.border.bottom
21
                    - pbp.padding.top
21
                    - pbp.padding.bottom)
21
                    .max(0.0),
            );
21
            return LogicalRect::new(content_pos, content_size);
6
        }
6
        current_parent_idx = parent_node.parent;
    }
6
    viewport
27
}
/// Find the scroll offset of the nearest scroll container ancestor.
/// Returns the scroll offset as a `LogicalPosition` (how far the content has scrolled).
///
/// `children_rect.origin` IS that offset (see
/// `ScrollManager::get_scroll_states_for_dom`), positive meaning "scrolled
/// down/right". `parent_rect.origin` is an ABSOLUTE window coordinate and must
/// NOT be subtracted from it — doing so mixed two spaces and reported a
/// container's own y as a scroll amount for every scroller below the top of
/// the window.
22
fn find_nearest_scroll_offset(
22
    tree: &LayoutTree,
22
    node_index: usize,
22
    scroll_offsets: &BTreeMap<NodeId, ScrollPosition>,
22
) -> LogicalPosition {
22
    let mut parent = tree
22
        .get(LayoutNodeId::new(node_index))
22
        .and_then(|n| n.parent);
37
    while let Some(pidx) = parent {
23
        if let Some(pnode) = tree.get(LayoutNodeId::new(pidx)) {
23
            if let Some(dom_id) = pnode.dom_node_id {
22
                if let Some(scroll_pos) = scroll_offsets.get(&dom_id) {
8
                    return scroll_pos.children_rect.origin;
14
                }
1
            }
15
            parent = pnode.parent;
        } else {
            break;
        }
    }
14
    LogicalPosition::zero()
22
}
/// Adjusts positions of sticky-positioned elements based on scroll offset.
///
/// Sticky positioning works like relative positioning, but the element's position
/// is constrained by its inset properties (top/right/bottom/left) relative to the
/// nearest scrollport (scroll container ancestor). The margin box is further
/// constrained to remain within the containing block.
///
/// +spec:position-sticky:9449f1 - for sticky positioning, insets represent offsets from scrollport
/// edge +spec:position-sticky:75412d - multiple sticky boxes in same container offset independently
/// +spec:box-model:af9af8 - sticky positioning: shift element to stay within sticky view rectangle,
/// margin box constrained to containing block +spec:overflow:bac4e5 - compute sticky view
/// rectangle, clamp end-edge insets to border box size
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
8625
pub fn adjust_sticky_positions<T: ParsedFontTrait>(
8625
    ctx: &mut LayoutContext<'_, T>,
8625
    tree: &LayoutTree,
8625
    calculated_positions: &mut super::PositionVec,
8625
    scroll_offsets: &BTreeMap<NodeId, ScrollPosition>,
8625
    viewport: LogicalRect,
8625
) {
    // Returns `()` (not `Result<()>`): Ok-always (its only `?` is Option-`?` in an `.and_then`
    // closure). Avoids the lift-fragile Result<(),LayoutError> Ok-niche read at the call site.
245559
    for node_index in 0..tree.nodes.len() {
245559
        let node = &tree.nodes[node_index];
245559
        let position_type = get_position_type(ctx.styled_dom, node.dom_node_id);
245559
        if position_type != LayoutPosition::Sticky {
245545
            continue;
14
        }
14
        let Some(dom_id) = node.dom_node_id else {
            continue;
        };
        // Find the nearest scrollport for this sticky element
14
        let scrollport = find_nearest_scrollport(
14
            tree,
14
            node_index,
14
            ctx.styled_dom,
14
            calculated_positions,
14
            viewport,
        );
        // The containing block for percentage resolution is the parent's content box
14
        let containing_block = node
14
            .parent
14
            .and_then(|parent_idx| {
14
                let parent_node = tree.get(LayoutNodeId::new(parent_idx))?;
14
                let parent_pos = calculated_positions
14
                    .get(parent_idx)
14
                    .copied()
14
                    .unwrap_or_default();
14
                let parent_size = parent_node.used_size.unwrap_or_default();
14
                let parent_wm = parent_node
14
                    .dom_node_id
14
                    .map(|pid| {
14
                        let ps = &ctx.styled_dom.styled_nodes.as_container()[pid].styled_node_state;
14
                        get_writing_mode(ctx.styled_dom, pid, ps).unwrap_or_default()
14
                    })
14
                    .unwrap_or_default();
14
                let pbp = parent_node.box_props.unpack();
14
                let content_size = pbp.inner_size(parent_size, parent_wm);
14
                let content_origin = LogicalPosition::new(
14
                    parent_pos.x + pbp.border.left + pbp.padding.left,
14
                    parent_pos.y + pbp.border.top + pbp.padding.top,
                );
14
                Some(LogicalRect::new(content_origin, content_size))
14
            })
14
            .unwrap_or(viewport);
        // Resolve inset properties (top, right, bottom, left)
14
        let offsets =
14
            resolve_position_offsets(ctx.styled_dom, Some(dom_id), scrollport.size, viewport.size);
        // Get the scroll offset from the nearest scroll container
14
        let scroll_offset = find_nearest_scroll_offset(tree, node_index, scroll_offsets);
14
        let Some(current_pos) = calculated_positions.get_mut(node_index) else {
1
            continue;
        };
13
        let static_pos = *current_pos;
13
        let element_size = node.used_size.unwrap_or_default();
13
        let nbp = node.box_props.unpack();
13
        let margin = &nbp.margin;
13
        let mut shift_x = 0.0f32;
13
        let mut shift_y = 0.0f32;
        // For each side: if inset is not auto, clamp the border edge to stay
        // within the sticky view rectangle (scrollport inset by the specified amount).
        // The scroll offset shifts the effective scrollport position.
13
        if let Some(top_inset) = offsets.top {
9
            let sticky_edge = scrollport.origin.y + scroll_offset.y + top_inset;
9
            let border_top = current_pos.y;
9
            if border_top < sticky_edge {
7
                shift_y = shift_y.max(sticky_edge - border_top);
7
            }
4
        }
13
        if let Some(bottom_inset) = offsets.bottom {
1
            let sticky_edge =
1
                scrollport.origin.y + scroll_offset.y + scrollport.size.height - bottom_inset;
1
            let border_bottom = current_pos.y + element_size.height;
1
            if border_bottom > sticky_edge {
1
                shift_y = shift_y.min(sticky_edge - border_bottom);
1
            }
12
        }
13
        if let Some(left_inset) = offsets.left {
1
            let sticky_edge = scrollport.origin.x + scroll_offset.x + left_inset;
1
            let border_left = current_pos.x;
1
            if border_left < sticky_edge {
1
                shift_x = shift_x.max(sticky_edge - border_left);
1
            }
12
        }
13
        if let Some(right_inset) = offsets.right {
1
            let sticky_edge =
1
                scrollport.origin.x + scroll_offset.x + scrollport.size.width - right_inset;
1
            let border_right = current_pos.x + element_size.width;
1
            if border_right > sticky_edge {
1
                shift_x = shift_x.min(sticky_edge - border_right);
1
            }
12
        }
        // Constrain: the margin box must remain within the containing block
13
        if shift_y != 0.0 {
8
            let margin_box_top = current_pos.y - margin.top + shift_y;
8
            let margin_box_bottom = current_pos.y + element_size.height + margin.bottom + shift_y;
8
            if margin_box_top < containing_block.origin.y {
                shift_y += containing_block.origin.y - margin_box_top;
8
            }
8
            let cb_bottom = containing_block.origin.y + containing_block.size.height;
8
            if margin_box_bottom > cb_bottom {
2
                shift_y -= margin_box_bottom - cb_bottom;
6
            }
5
        }
13
        if shift_x != 0.0 {
2
            let margin_box_left = current_pos.x - margin.left + shift_x;
2
            let margin_box_right = current_pos.x + element_size.width + margin.right + shift_x;
2
            if margin_box_left < containing_block.origin.x {
                shift_x += containing_block.origin.x - margin_box_left;
2
            }
2
            let cb_right = containing_block.origin.x + containing_block.size.width;
2
            if margin_box_right > cb_right {
                shift_x -= margin_box_right - cb_right;
2
            }
11
        }
13
        if shift_x != 0.0 || shift_y != 0.0 {
10
            current_pos.x += shift_x;
10
            current_pos.y += shift_y;
10
            debug_log!(
                ctx,
                "Adjusted sticky element #{} from {:?} to {:?}",
                node_index,
                static_pos,
                *current_pos
            );
3
        }
    }
8625
}
// +spec:positioning:22f165 - absolute/fixed containing block: nearest positioned ancestor's
// padding-box, or initial CB
/// Helper to find the containing block for an absolutely positioned element.
/// CSS 2.1 Section 10.1: The containing block for absolutely positioned elements
/// is the padding box of the nearest positioned ancestor.
// +spec:containing-block:10af51 - absolutely positioned element's CB is nearest positioned ancestor
// +spec:positioning:2d0dbb - containing block for abspos is padding-box of nearest positioned
// ancestor, or initial CB +spec:positioning:3ac06c - abspos positioned relative to containing block
// ignoring fragmentation breaks +spec:positioning:d7e4b4 - containing block of abspos element is
// always definite (returns concrete LogicalRect) +spec:positioning:fc9dba - containing block
// resolution for absolutely positioned boxes
///
/// Returns a `LogicalRect` representing the padding-box of the nearest
/// positioned ancestor, or the viewport (initial containing block) if none exists.
/// This is the unified entry point used by both sizing and positioning phases.
// +spec:containing-block:18ae8e - Absolute positioning: abs-pos box establishes new CB for normal
// flow and abs-pos (but not fixed) descendants +spec:containing-block:b6cb8b - containing block for
// abs-pos is nearest positioned ancestor +spec:display-property:5a39bc - containing block for
// abspos is nearest positioned ancestor or initial containing block +spec:positioning:09a0fa -
// Absolute positioning: CB is padding-box of nearest positioned ancestor +spec:positioning:467cb1 -
// Containing block for abs pos = nearest positioned ancestor or initial CB +spec:positioning:99d0bb
// - containing block for absolute elements is nearest positioned ancestor +spec:positioning:92e099
// - containing block for abs pos is nearest positioned ancestor or initial CB +spec:positioning:
// f57523 - containing block of abspos element is always definite (returns concrete LogicalRect)
// +spec:width-calculation:bf1aa6 - abspos CB is nearest positioned ancestor, else initial CB
// Containing block for absolutely positioned elements is established by
// nearest positioned ancestor (relative/absolute/fixed), or initial containing block if none.
// +spec:positioning:8f50de - relatively positioned parent serves as containing block for abspos
// descendants +spec:containing-block:6bcb0c - containing block is padding edge of nearest
// positioned ancestor, or initial containing block if none +spec:containing-block:bf17e5 -
// containing block for abspos is padding box of nearest positioned ancestor, or initial CB
// +spec:containing-block:d0f92d - containing block for positioned box is nearest positioned
// ancestor, or initial containing block +spec:containing-block:d7e013 - containing block for
// positioned box is nearest positioned ancestor or initial CB +spec:containing-block:05bc0d -
// positioning an element changes which ancestor establishes the CB for its descendants
// +spec:positioning:355ee4 - CB for abspos is padding edge of nearest positioned ancestor, or
// initial CB +spec:positioning:383794 - Containing block for abspos is nearest positioned ancestor,
// or initial containing block if none +spec:positioning:5b3e43 - Containing block for abs-pos is
// padding box of nearest positioned ancestor, or initial CB +spec:positioning:882e67 - containing
// block for abs pos is nearest positioned ancestor or initial CB +spec:positioning:292c5c -
// relative parent serves as containing block for absolute descendants +spec:positioning:00ce38 - CB
// for absolute is padding edge of nearest positioned ancestor
2536
pub(crate) fn find_absolute_containing_block_rect(
2536
    tree: &LayoutTree,
2536
    node_index: usize,
2536
    styled_dom: &StyledDom,
2536
    calculated_positions: &super::PositionVec,
2536
    viewport: LogicalRect,
2536
) -> Result<LogicalRect> {
    // +spec:positioning:748d87 - walk up to nearest positioned ancestor for CB
2536
    let mut current_parent_idx = tree
2536
        .get(LayoutNodeId::new(node_index))
2536
        .and_then(|n| n.parent);
    // +spec:positioning:aa361e - values other than static make a box positioned and establish an
    // abspos containing block
2543
    while let Some(parent_index) = current_parent_idx {
2468
        let parent_node = tree
2468
            .get(LayoutNodeId::new(parent_index))
2468
            .ok_or(LayoutError::InvalidTree)?;
2467
        if get_position_type(styled_dom, parent_node.dom_node_id).is_positioned() {
            // calculated_positions stores margin-box positions
2460
            let margin_box_pos = calculated_positions
2460
                .get(parent_index)
2460
                .copied()
2460
                .unwrap_or_default();
            // used_size is the border-box size
2460
            let border_box_size = parent_node.used_size.unwrap_or_default();
            // +spec:containing-block:6bcb0c - containing block formed by padding edge of nearest
            // positioned ancestor +spec:positioning:df1921 - abs-pos percentage widths
            // resolve against padding box of containing block Calculate padding-box
            // origin (margin-box + border)
2460
            let pbp = parent_node.box_props.unpack();
2460
            let padding_box_pos = LogicalPosition::new(
2460
                margin_box_pos.x + pbp.border.left,
2460
                margin_box_pos.y + pbp.border.top,
            );
            // Calculate padding-box size (border-box - borders)
2460
            let padding_box_size = LogicalSize::new(
2460
                (border_box_size.width - pbp.border.left - pbp.border.right).max(0.0),
2460
                (border_box_size.height - pbp.border.top - pbp.border.bottom).max(0.0),
            );
2460
            return Ok(LogicalRect::new(padding_box_pos, padding_box_size));
7
        }
7
        current_parent_idx = parent_node.parent;
    }
    // +spec:positioning:3d88c9 - abspos available space is always definite (viewport or positioned
    // ancestor padding box) No positioned ancestor found: fall back to initial containing block
    // (viewport) +spec:containing-block:141dcc - absolute element with no positioned ancestor
    // uses initial containing block +spec:containing-block:657f2f - containing block becomes
    // initial containing block when no positioned ancestors +spec:containing-block:7f5090 - if
    // no ancestor establishes one, absolute positioning CB is initial containing block
    // +spec:containing-block:7f5090 - fallback to initial containing block when no positioned
    // ancestor +spec:containing-block:ad5ebc - no positioned ancestor: containing block becomes
    // the initial containing block +spec:display-property:813192 - abspos containing block
    // falls back to initial containing block (viewport) when no positioned ancestor
75
    Ok(viewport)
2536
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use azul_core::dom::{Dom, FormattingContext, IdOrClass};
    use super::*;
    use crate::solver3::{
        geometry::{EdgeSizes, MarginAuto, PackedBoxProps, ResolvedBoxProps},
        layout_tree::{LayoutNodeCold, LayoutNodeHot, LayoutNodeWarm},
        pos_set, PositionVec, POSITION_UNSET,
    };
    // ==================================================================
    // Fixtures
    // ==================================================================
    fn close(a: f32, b: f32, eps: f32) -> bool {
        (a - b).abs() <= eps
    }
    fn viewport() -> LogicalRect {
        LogicalRect::new(
            LogicalPosition::new(0.0, 0.0),
            LogicalSize::new(800.0, 600.0),
        )
    }
    fn styled(dom: Dom, css_str: &str) -> StyledDom {
        let mut dom = dom;
        let (css, _warnings) = azul_css::parser2::new_from_str(css_str);
        StyledDom::create(&mut dom, css)
    }
    fn div_class(class: &str) -> Dom {
        Dom::create_div().with_ids_and_classes(vec![IdOrClass::Class(class.into())].into())
    }
    fn body_class(class: &str) -> Dom {
        Dom::create_body().with_ids_and_classes(vec![IdOrClass::Class(class.into())].into())
    }
    /// Structural lookup — never hard-code `CompactDom` pre-order indices.
    fn node_by_class(sd: &StyledDom, class: &str) -> NodeId {
        let container = sd.node_data.as_container();
        for i in 0..sd.node_data.len() {
            let id = NodeId::new(i);
            let ids_and_classes = container[id].get_ids_and_classes();
            let hit = ids_and_classes
                .as_ref()
                .iter()
                .any(|ioc| matches!(ioc, IdOrClass::Class(c) if c.as_str() == class));
            if hit {
                return id;
            }
        }
        panic!("no node with class {class:?}");
    }
    fn edges(top: f32, right: f32, bottom: f32, left: f32) -> EdgeSizes {
        EdgeSizes {
            top,
            right,
            bottom,
            left,
        }
    }
    fn uniform(v: f32) -> EdgeSizes {
        edges(v, v, v, v)
    }
    fn bp(margin: EdgeSizes, padding: EdgeSizes, border: EdgeSizes) -> PackedBoxProps {
        PackedBoxProps::pack(&ResolvedBoxProps {
            margin,
            padding,
            border,
            margin_auto: MarginAuto::default(),
        })
    }
    fn bp_auto_margins(margin_auto: MarginAuto) -> PackedBoxProps {
        PackedBoxProps::pack(&ResolvedBoxProps {
            margin: uniform(0.0),
            padding: uniform(0.0),
            border: uniform(0.0),
            margin_auto,
        })
    }
    fn hot(parent: Option<usize>, dom_node_id: Option<NodeId>) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: PackedBoxProps::default(),
            dom_node_id,
            used_size: None,
            formatting_context: FormattingContext::Block {
                establishes_new_context: false,
            },
            parent,
        }
    }
    /// Hand-assembles a `LayoutTree` so the index / dangling-parent edge cases the
    /// real builder can never produce stay reachable.
    fn raw_tree(nodes: Vec<LayoutNodeHot>, child_lists: &[Vec<usize>]) -> LayoutTree {
        let n = nodes.len();
        let mut children_arena: Vec<usize> = Vec::new();
        let mut children_offsets: Vec<(u32, u32)> = Vec::with_capacity(n);
        for cl in child_lists {
            let start = u32::try_from(children_arena.len()).unwrap();
            children_arena.extend_from_slice(cl);
            children_offsets.push((start, u32::try_from(cl.len()).unwrap()));
        }
        while children_offsets.len() < n {
            children_offsets.push((0, 0));
        }
        LayoutTree {
            nodes,
            warm: vec![LayoutNodeWarm::default(); n],
            cold: vec![LayoutNodeCold::default(); n],
            root: 0,
            dom_to_layout: BTreeMap::new(),
            children_arena,
            children_offsets,
            subtree_needs_intrinsic: Vec::new(),
        }
    }
    /// `body.root > div.child`, both mirrored 1:1 into a two-node layout tree.
    fn two_level(css: &str) -> (StyledDom, LayoutTree) {
        let sd = styled(body_class("root").with_child(div_class("child")), css);
        let root = node_by_class(&sd, "root");
        let child = node_by_class(&sd, "child");
        let tree = raw_tree(
            vec![hot(None, Some(root)), hot(Some(0), Some(child))],
            &[vec![1], vec![]],
        );
        (sd, tree)
    }
    /// `body.root > div.mid > div.child`.
    fn three_level(css: &str) -> (StyledDom, LayoutTree) {
        let sd = styled(
            body_class("root").with_child(div_class("mid").with_child(div_class("child"))),
            css,
        );
        let root = node_by_class(&sd, "root");
        let mid = node_by_class(&sd, "mid");
        let child = node_by_class(&sd, "child");
        let tree = raw_tree(
            vec![
                hot(None, Some(root)),
                hot(Some(0), Some(mid)),
                hot(Some(1), Some(child)),
            ],
            &[vec![1], vec![2], vec![]],
        );
        (sd, tree)
    }
    fn positions(list: &[(f32, f32)]) -> PositionVec {
        list.iter()
            .map(|&(x, y)| LogicalPosition::new(x, y))
            .collect()
    }
    // ==================================================================
    // get_position_type (other / no-panic smoke + invariants)
    // ==================================================================
    #[test]
    fn get_position_type_none_dom_id_is_static() {
        let (sd, _tree) = two_level("");
        assert_eq!(get_position_type(&sd, None), LayoutPosition::Static);
    }
    #[test]
    fn get_position_type_unstyled_node_is_static() {
        let (sd, _tree) = two_level("");
        let child = node_by_class(&sd, "child");
        assert_eq!(get_position_type(&sd, Some(child)), LayoutPosition::Static);
    }
    #[test]
    fn get_position_type_reads_every_keyword() {
        let sd = styled(
            body_class("root")
                .with_child(div_class("st"))
                .with_child(div_class("rel"))
                .with_child(div_class("abs"))
                .with_child(div_class("fix"))
                .with_child(div_class("sticky")),
            ".st { position: static; } .rel { position: relative; } .abs { position: absolute; } \
             .fix { position: fixed; } .sticky { position: sticky; }",
        );
        for (class, expected) in [
            ("st", LayoutPosition::Static),
            ("rel", LayoutPosition::Relative),
            ("abs", LayoutPosition::Absolute),
            ("fix", LayoutPosition::Fixed),
            ("sticky", LayoutPosition::Sticky),
        ] {
            let id = node_by_class(&sd, class);
            assert_eq!(get_position_type(&sd, Some(id)), expected, "class {class}");
        }
    }
    #[test]
    fn get_position_type_garbage_value_falls_back_to_static() {
        // An unparseable declaration must not leak a bogus enum — it is dropped
        // by the parser, so the cascade yields the initial value.
        let (sd, _tree) = two_level(".child { position: rubbish-42; }");
        let child = node_by_class(&sd, "child");
        assert_eq!(get_position_type(&sd, Some(child)), LayoutPosition::Static);
    }
    #[test]
    fn get_position_type_is_pure_and_stable_across_calls() {
        let (sd, _tree) = two_level(".child { position: sticky; }");
        let child = node_by_class(&sd, "child");
        let a = get_position_type(&sd, Some(child));
        let b = get_position_type(&sd, Some(child));
        assert_eq!(a, b);
        assert_eq!(a, LayoutPosition::Sticky);
        // The invariant the whole positioning pass leans on.
        assert!(a.is_positioned());
    }
    // ==================================================================
    // resolve_position_offsets (numeric)
    // ==================================================================
    #[test]
    fn resolve_position_offsets_none_dom_id_is_all_none() {
        let (sd, _tree) = two_level(".child { top: 10px; }");
        let o = resolve_position_offsets(
            &sd,
            None,
            LogicalSize::new(100.0, 100.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert!(o.top.is_none() && o.right.is_none() && o.bottom.is_none() && o.left.is_none());
    }
    #[test]
    fn resolve_position_offsets_unset_insets_are_none_not_zero() {
        // `auto` must stay distinguishable from `0px` — the entire abspos
        // constraint solver branches on it.
        let (sd, _tree) = two_level("");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(100.0, 100.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert!(o.top.is_none() && o.right.is_none() && o.bottom.is_none() && o.left.is_none());
    }
    #[test]
    fn resolve_position_offsets_zero_px_is_some_zero() {
        let (sd, _tree) = two_level(".child { top: 0px; left: 0px; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(0.0, 0.0),
        );
        assert_eq!(o.top, Some(0.0));
        assert_eq!(o.left, Some(0.0));
        assert!(o.right.is_none() && o.bottom.is_none());
    }
    #[test]
    fn resolve_position_offsets_px_values_round_trip() {
        let (sd, _tree) = two_level(".child { top: 11px; right: 22px; bottom: 33px; left: 44px; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(200.0, 100.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(11.0));
        assert_eq!(o.right, Some(22.0));
        assert_eq!(o.bottom, Some(33.0));
        assert_eq!(o.left, Some(44.0));
    }
    #[test]
    fn resolve_position_offsets_percent_uses_the_correct_axis() {
        // +spec:containing-block:d4b3b9 — top/bottom resolve against CB height,
        // left/right against CB width. Swapping the axes is the classic bug here.
        let (sd, _tree) = two_level(".child { top: 50%; bottom: 25%; left: 50%; right: 10%; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(400.0, 200.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(100.0), "50% of CB height 200");
        assert_eq!(o.bottom, Some(50.0), "25% of CB height 200");
        assert_eq!(o.left, Some(200.0), "50% of CB width 400");
        assert_eq!(o.right, Some(40.0), "10% of CB width 400");
    }
    #[test]
    fn resolve_position_offsets_percent_of_zero_containing_block_is_zero() {
        let (sd, _tree) = two_level(".child { top: 75%; left: 75%; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(0.0));
        assert_eq!(o.left, Some(0.0));
    }
    #[test]
    fn resolve_position_offsets_negative_values_stay_negative() {
        let (sd, _tree) = two_level(".child { top: -40px; left: -25%; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(400.0, 200.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(-40.0));
        assert_eq!(o.left, Some(-100.0), "-25% of CB width 400");
    }
    #[test]
    fn resolve_position_offsets_em_uses_element_font_size_rem_uses_root() {
        let sd = styled(
            body_class("root").with_child(div_class("child")),
            ".root { font-size: 10px; } .child { font-size: 20px; top: 2em; left: 3rem; }",
        );
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(400.0, 200.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(40.0), "2em of the element's own 20px font");
        assert_eq!(o.left, Some(30.0), "3rem of the 10px root font");
    }
    #[test]
    fn resolve_position_offsets_viewport_units_use_the_viewport_not_the_containing_block() {
        let (sd, _tree) = two_level(".child { top: 10vh; left: 10vw; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(50.0, 50.0), // deliberately not the viewport
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(60.0), "10vh of a 600px viewport");
        assert_eq!(o.left, Some(80.0), "10vw of an 800px viewport");
    }
    #[test]
    fn resolve_position_offsets_huge_px_bypasses_the_i16_compact_cache_intact() {
        // The compact cache encodes insets as i16 ×10 (±3276.7px) and emits a
        // sentinel outside that range. The sentinel MUST fall through to the slow
        // cascade path with the value intact — silently saturating to 3276.7px
        // (or wrapping to a negative!) would be the nasty failure here.
        let (sd, _tree) = two_level(".child { top: 100000px; left: -100000px; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(400.0, 200.0),
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(100_000.0));
        assert_eq!(o.left, Some(-100_000.0));
    }
    #[test]
    fn resolve_position_offsets_around_the_i16_cache_boundary_agree_within_a_tenth_px() {
        // 3276.3px is the largest encodable value; 3276.4px trips the sentinel and
        // takes the slow path. Both paths must land on the authored value.
        let (sd, _tree) = two_level(".child { top: 3276.3px; bottom: 3276.4px; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(400.0, 200.0),
            LogicalSize::new(800.0, 600.0),
        );
        let top = o.top.expect("top is set");
        let bottom = o.bottom.expect("bottom is set");
        assert!(close(top, 3276.3, 0.1), "top was {top}");
        assert!(close(bottom, 3276.4, 0.1), "bottom was {bottom}");
    }
    #[test]
    fn resolve_position_offsets_sub_tenth_px_precision_loss_is_bounded() {
        // The i16 ×10 cache quantises to 0.1px. That is allowed — but it must not
        // drift further than that.
        let (sd, _tree) = two_level(".child { top: 10.567px; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(400.0, 200.0),
            LogicalSize::new(800.0, 600.0),
        );
        let top = o.top.expect("top is set");
        assert!(close(top, 10.567, 0.05), "top was {top}");
    }
    #[test]
    fn resolve_position_offsets_nan_containing_block_yields_nan_not_a_panic() {
        let (sd, _tree) = two_level(".child { top: 50%; left: 50%; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(f32::NAN, f32::NAN),
            LogicalSize::new(800.0, 600.0),
        );
        assert!(o.top.expect("top is set").is_nan());
        assert!(o.left.expect("left is set").is_nan());
    }
    #[test]
    fn resolve_position_offsets_infinite_containing_block_yields_infinity_not_a_panic() {
        let (sd, _tree) = two_level(".child { top: 50%; left: 50%; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(f32::INFINITY, f32::INFINITY),
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(o.top, Some(f32::INFINITY));
        assert_eq!(o.left, Some(f32::INFINITY));
    }
    #[test]
    fn resolve_position_offsets_at_f32_max_containing_block_does_not_panic() {
        let (sd, _tree) = two_level(".child { top: 100%; left: 100%; }");
        let child = node_by_class(&sd, "child");
        let o = resolve_position_offsets(
            &sd,
            Some(child),
            LogicalSize::new(f32::MAX, f32::MAX),
            LogicalSize::new(f32::MAX, f32::MAX),
        );
        // 100% of MAX is MAX (the normalized 1.0 multiply is exact).
        assert_eq!(o.top, Some(f32::MAX));
        assert_eq!(o.left, Some(f32::MAX));
    }
    // ==================================================================
    // find_absolute_containing_block_rect (numeric)
    // ==================================================================
    #[test]
    fn find_absolute_cb_rect_root_without_parent_is_the_viewport() {
        let (sd, tree) = two_level(".root { position: relative; }");
        let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
        let got = find_absolute_containing_block_rect(&tree, 0, &sd, &pos, viewport())
            .expect("root resolves to the initial CB");
        assert_eq!(got, viewport());
    }
    #[test]
    fn find_absolute_cb_rect_out_of_range_index_is_the_viewport_not_a_panic() {
        let (sd, tree) = two_level(".root { position: relative; }");
        let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
        let got = find_absolute_containing_block_rect(&tree, 9_999, &sd, &pos, viewport())
            .expect("an out-of-range index falls back to the initial CB");
        assert_eq!(got, viewport());
    }
    #[test]
    fn find_absolute_cb_rect_dangling_parent_index_is_an_error_not_a_panic() {
        let (sd, mut tree) = two_level(".root { position: relative; }");
        tree.nodes[1].parent = Some(9_999); // corrupt the tree
        let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
        let got = find_absolute_containing_block_rect(&tree, 1, &sd, &pos, viewport());
        assert!(matches!(got, Err(LayoutError::InvalidTree)));
    }
    #[test]
    fn find_absolute_cb_rect_static_ancestors_fall_back_to_the_viewport() {
        let (sd, mut tree) = three_level("");
        tree.nodes[0].used_size = Some(LogicalSize::new(400.0, 300.0));
        tree.nodes[1].used_size = Some(LogicalSize::new(200.0, 100.0));
        let pos = positions(&[(0.0, 0.0), (10.0, 10.0), (20.0, 20.0)]);
        let got = find_absolute_containing_block_rect(&tree, 2, &sd, &pos, viewport())
            .expect("no positioned ancestor → initial CB");
        assert_eq!(got, viewport());
    }
    #[test]
    fn find_absolute_cb_rect_is_the_padding_box_of_the_positioned_ancestor() {
        // CSS 2.1 §10.1: padding box, i.e. margin-box origin + border, size - borders.
        let (sd, mut tree) = two_level(".root { position: relative; }");
        tree.nodes[0].used_size = Some(LogicalSize::new(400.0, 300.0));
        tree.nodes[0].box_props = bp(uniform(0.0), uniform(5.0), uniform(10.0));
        let pos = positions(&[(20.0, 30.0), (0.0, 0.0)]);
        let got = find_absolute_containing_block_rect(&tree, 1, &sd, &pos, viewport())
            .expect("relative parent is the CB");
        assert_eq!(got.origin, LogicalPosition::new(30.0, 40.0));
        assert_eq!(got.size, LogicalSize::new(380.0, 280.0));
    }
    #[test]
    fn find_absolute_cb_rect_accepts_every_positioned_ancestor_kind() {
        for keyword in ["relative", "absolute", "fixed", "sticky"] {
            let css = format!(".root {{ position: {keyword}; }}");
            let (sd, mut tree) = two_level(&css);
            tree.nodes[0].used_size = Some(LogicalSize::new(100.0, 100.0));
            let pos = positions(&[(5.0, 5.0), (0.0, 0.0)]);
            let got = find_absolute_containing_block_rect(&tree, 1, &sd, &pos, viewport())
                .expect("positioned ancestor resolves");
            assert_eq!(
                got,
                LogicalRect::new(
                    LogicalPosition::new(5.0, 5.0),
                    LogicalSize::new(100.0, 100.0)
                ),
                "position: {keyword}"
            );
        }
    }
    #[test]
    fn find_absolute_cb_rect_picks_the_nearest_positioned_ancestor() {
        let (sd, mut tree) =
            three_level(".root { position: relative; } .mid { position: absolute; }");
        tree.nodes[0].used_size = Some(LogicalSize::new(400.0, 300.0));
        tree.nodes[1].used_size = Some(LogicalSize::new(200.0, 100.0));
        let pos = positions(&[(0.0, 0.0), (50.0, 60.0), (0.0, 0.0)]);
        let got = find_absolute_containing_block_rect(&tree, 2, &sd, &pos, viewport())
            .expect("nearest positioned ancestor");
        assert_eq!(
            got.origin,
            LogicalPosition::new(50.0, 60.0),
            "mid, not root"
        );
        assert_eq!(got.size, LogicalSize::new(200.0, 100.0));
    }
    #[test]
    fn find_absolute_cb_rect_saturating_borders_clamp_the_padding_box_to_zero() {
        // PackedBoxProps saturates each edge at 3276.7px. Two of those exceed a
        // 100px border box — the padding box must clamp to 0, never go negative.
        let (sd, mut tree) = two_level(".root { position: relative; }");
        tree.nodes[0].used_size = Some(LogicalSize::new(100.0, 100.0));
        tree.nodes[0].box_props = bp(uniform(0.0), uniform(0.0), uniform(1e30));
        let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
        let got = find_absolute_containing_block_rect(&tree, 1, &sd, &pos, viewport())
            .expect("saturated borders still resolve");
        assert_eq!(got.size, LogicalSize::new(0.0, 0.0));
        assert!(got.size.width >= 0.0 && got.size.height >= 0.0);
        assert!(got.origin.x.is_finite() && got.origin.y.is_finite());
    }
    #[test]
    fn find_absolute_cb_rect_unsized_ancestor_is_a_zero_sized_padding_box() {
        let (sd, tree) = two_level(".root { position: relative; }"); // used_size stays None
        let pos = positions(&[(7.0, 9.0), (0.0, 0.0)]);
        let got = find_absolute_containing_block_rect(&tree, 1, &sd, &pos, viewport())
            .expect("an unsized ancestor still resolves");
        assert_eq!(got.origin, LogicalPosition::new(7.0, 9.0));
        assert_eq!(got.size, LogicalSize::new(0.0, 0.0));
    }
    #[test]
    fn find_absolute_cb_rect_missing_position_entry_defaults_to_the_origin() {
        let (sd, mut tree) = two_level(".root { position: relative; }");
        tree.nodes[0].used_size = Some(LogicalSize::new(100.0, 100.0));
        let pos: PositionVec = Vec::new(); // nothing laid out yet
        let got = find_absolute_containing_block_rect(&tree, 1, &sd, &pos, viewport())
            .expect("an empty position vec still resolves");
        assert_eq!(got.origin, LogicalPosition::new(0.0, 0.0));
        assert_eq!(got.size, LogicalSize::new(100.0, 100.0));
    }
    // ==================================================================
    // find_nearest_scrollport (numeric)
    // ==================================================================
    #[test]
    fn find_nearest_scrollport_without_a_scroll_ancestor_is_the_viewport() {
        let (sd, tree) = two_level("");
        let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
        assert_eq!(
            find_nearest_scrollport(&tree, 1, &sd, &pos, viewport()),
            viewport()
        );
    }
    #[test]
    fn find_nearest_scrollport_out_of_range_index_is_the_viewport_not_a_panic() {
        let (sd, tree) = two_level(".root { overflow-y: scroll; }");
        let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
        assert_eq!(
            find_nearest_scrollport(&tree, 9_999, &sd, &pos, viewport()),
            viewport()
        );
    }
    #[test]
    fn find_nearest_scrollport_returns_the_ancestor_content_box() {
        for css in [
            ".root { overflow-x: scroll; }",
            ".root { overflow-y: scroll; }",
            ".root { overflow-x: auto; }",
            ".root { overflow-y: auto; }",
        ] {
            let (sd, mut tree) = two_level(css);
            tree.nodes[0].used_size = Some(LogicalSize::new(200.0, 150.0));
            tree.nodes[0].box_props = bp(uniform(0.0), uniform(5.0), uniform(10.0));
            let pos = positions(&[(20.0, 30.0), (0.0, 0.0)]);
            let got = find_nearest_scrollport(&tree, 1, &sd, &pos, viewport());
            // content box = margin-box pos + border + padding, size - 2*(border+padding)
            assert_eq!(got.origin, LogicalPosition::new(35.0, 45.0), "{css}");
            assert_eq!(got.size, LogicalSize::new(170.0, 120.0), "{css}");
        }
    }
    #[test]
    fn find_nearest_scrollport_ignores_non_scrolling_overflow() {
        for css in [
            ".root { overflow-x: hidden; }",
            ".root { overflow-y: visible; }",
            ".root { overflow-x: clip; }",
        ] {
            let (sd, mut tree) = two_level(css);
            tree.nodes[0].used_size = Some(LogicalSize::new(200.0, 150.0));
            let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
            assert_eq!(
                find_nearest_scrollport(&tree, 1, &sd, &pos, viewport()),
                viewport(),
                "{css}"
            );
        }
    }
    #[test]
    fn find_nearest_scrollport_picks_the_nearest_of_two_scroll_ancestors() {
        let (sd, mut tree) =
            three_level(".root { overflow-y: scroll; } .mid { overflow-y: scroll; }");
        tree.nodes[0].used_size = Some(LogicalSize::new(400.0, 300.0));
        tree.nodes[1].used_size = Some(LogicalSize::new(200.0, 100.0));
        let pos = positions(&[(0.0, 0.0), (11.0, 12.0), (0.0, 0.0)]);
        let got = find_nearest_scrollport(&tree, 2, &sd, &pos, viewport());
        assert_eq!(
            got.origin,
            LogicalPosition::new(11.0, 12.0),
            "mid, not root"
        );
        assert_eq!(got.size, LogicalSize::new(200.0, 100.0));
    }
    #[test]
    fn find_nearest_scrollport_walks_past_anonymous_boxes() {
        // An anonymous box (dom_node_id: None) has no style — it must be skipped,
        // not treated as the end of the ancestor chain.
        let (sd, mut tree) = three_level(".root { overflow-y: scroll; }");
        tree.nodes[1].dom_node_id = None; // .mid becomes anonymous
        tree.nodes[0].used_size = Some(LogicalSize::new(400.0, 300.0));
        let pos = positions(&[(1.0, 2.0), (0.0, 0.0), (0.0, 0.0)]);
        let got = find_nearest_scrollport(&tree, 2, &sd, &pos, viewport());
        assert_eq!(got.origin, LogicalPosition::new(1.0, 2.0));
        assert_eq!(got.size, LogicalSize::new(400.0, 300.0));
    }
    #[test]
    fn find_nearest_scrollport_clamps_the_content_box_to_zero_when_padding_exceeds_the_box() {
        let (sd, mut tree) = two_level(".root { overflow-y: scroll; }");
        tree.nodes[0].used_size = Some(LogicalSize::new(10.0, 10.0));
        tree.nodes[0].box_props = bp(uniform(0.0), uniform(1e30), uniform(1e30));
        let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
        let got = find_nearest_scrollport(&tree, 1, &sd, &pos, viewport());
        assert_eq!(got.size, LogicalSize::new(0.0, 0.0));
        assert!(got.size.width >= 0.0 && got.size.height >= 0.0);
    }
    #[test]
    fn find_nearest_scrollport_unsized_scrollport_is_zero_sized() {
        let (sd, tree) = two_level(".root { overflow-y: scroll; }"); // used_size None
        let pos: PositionVec = Vec::new();
        let got = find_nearest_scrollport(&tree, 1, &sd, &pos, viewport());
        assert_eq!(got.origin, LogicalPosition::new(0.0, 0.0));
        assert_eq!(got.size, LogicalSize::new(0.0, 0.0));
    }
    // ==================================================================
    // find_nearest_scroll_offset (numeric)
    // ==================================================================
    /// `container_origin` is the scroller's ABSOLUTE window position, `offset`
    /// is the scroll amount — the two are deliberately different everywhere
    /// below, because a fixture with a container at (0, 0) cannot tell the two
    /// `ScrollPosition` conventions apart.
    fn scroll_at(container_origin: (f32, f32), offset: (f32, f32)) -> ScrollPosition {
        ScrollPosition {
            parent_rect: LogicalRect::new(
                LogicalPosition::new(container_origin.0, container_origin.1),
                LogicalSize::new(100.0, 100.0),
            ),
            children_rect: LogicalRect::new(
                LogicalPosition::new(offset.0, offset.1),
                LogicalSize::new(100.0, 400.0),
            ),
        }
    }
    #[test]
    fn find_nearest_scroll_offset_empty_map_is_zero() {
        let (_sd, tree) = two_level("");
        let offsets: BTreeMap<NodeId, ScrollPosition> = BTreeMap::new();
        assert_eq!(
            find_nearest_scroll_offset(&tree, 1, &offsets),
            LogicalPosition::zero()
        );
    }
    #[test]
    fn find_nearest_scroll_offset_out_of_range_index_is_zero_not_a_panic() {
        let (sd, tree) = two_level("");
        let mut offsets = BTreeMap::new();
        offsets.insert(
            node_by_class(&sd, "root"),
            scroll_at((0.0, 120.0), (0.0, 50.0)),
        );
        assert_eq!(
            find_nearest_scroll_offset(&tree, 9_999, &offsets),
            LogicalPosition::zero()
        );
    }
    #[test]
    fn find_nearest_scroll_offset_ignores_the_nodes_own_entry() {
        // The walk starts at the PARENT — a node's own scroll offset must not
        // shift the node itself.
        let (sd, tree) = two_level("");
        let mut offsets = BTreeMap::new();
        offsets.insert(
            node_by_class(&sd, "child"),
            scroll_at((0.0, 120.0), (0.0, 50.0)),
        );
        assert_eq!(
            find_nearest_scroll_offset(&tree, 1, &offsets),
            LogicalPosition::zero()
        );
    }
    #[test]
    fn find_nearest_scroll_offset_is_the_raw_offset_not_a_container_relative_one() {
        // CONVENTION PIN. `children_rect.origin` IS the scroll offset;
        // `parent_rect.origin` is an absolute window coordinate in a different
        // space. Subtracting the two (as this used to) reported the AzWriter
        // document view — a scroller at y = 120, unscrolled — as scrolled by
        // -120, which then shifted every sticky box inside it by a screenful.
        let (sd, tree) = two_level("");
        let mut offsets = BTreeMap::new();
        offsets.insert(
            node_by_class(&sd, "root"),
            scroll_at((10.0, 120.0), (0.0, 0.0)),
        );
        assert_eq!(
            find_nearest_scroll_offset(&tree, 1, &offsets),
            LogicalPosition::zero(),
            "an unscrolled container reports zero wherever it sits"
        );
        offsets.insert(
            node_by_class(&sd, "root"),
            scroll_at((10.0, 120.0), (5.0, 80.0)),
        );
        assert_eq!(
            find_nearest_scroll_offset(&tree, 1, &offsets),
            LogicalPosition::new(5.0, 80.0),
            "the offset is reported verbatim, not relative to the container"
        );
    }
    #[test]
    fn find_nearest_scroll_offset_picks_the_nearest_ancestor() {
        let (sd, tree) = three_level("");
        let mut offsets = BTreeMap::new();
        offsets.insert(
            node_by_class(&sd, "root"),
            scroll_at((0.0, 40.0), (0.0, 999.0)),
        );
        offsets.insert(
            node_by_class(&sd, "mid"),
            scroll_at((0.0, 120.0), (0.0, 7.0)),
        );
        assert_eq!(
            find_nearest_scroll_offset(&tree, 2, &offsets),
            LogicalPosition::new(0.0, 7.0),
            "mid wins over root"
        );
    }
    #[test]
    fn find_nearest_scroll_offset_walks_past_anonymous_ancestors() {
        let (sd, mut tree) = three_level("");
        tree.nodes[1].dom_node_id = None;
        let mut offsets = BTreeMap::new();
        offsets.insert(
            node_by_class(&sd, "root"),
            scroll_at((0.0, 120.0), (0.0, 30.0)),
        );
        assert_eq!(
            find_nearest_scroll_offset(&tree, 2, &offsets),
            LogicalPosition::new(0.0, 30.0)
        );
    }
    #[test]
    fn find_nearest_scroll_offset_at_f32_extremes_stays_deterministic() {
        let (sd, tree) = two_level("");
        let mut offsets = BTreeMap::new();
        offsets.insert(
            node_by_class(&sd, "root"),
            scroll_at((f32::MAX, f32::MAX), (f32::MIN, f32::MIN)),
        );
        let got = find_nearest_scroll_offset(&tree, 1, &offsets);
        // No arithmetic is performed any more, so an extreme offset passes
        // through as-is instead of overflowing to -inf. It must never be NaN
        // (which would poison every downstream sticky comparison silently).
        assert!(!got.x.is_nan() && !got.y.is_nan());
        assert_eq!(got.x, f32::MIN);
        assert_eq!(got.y, f32::MIN);
    }
    // ==================================================================
    // The three passes that need a LayoutContext (and therefore a FontManager).
    // ==================================================================
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    mod with_ctx {
        use std::collections::HashMap;
        use azul_core::{dom::DomId, selection::TextSelection};
        use azul_css::props::basic::FontRef;
        use super::*;
        use crate::{
            font_traits::{FontManager, TextLayoutCache},
            solver3::{cache, LayoutContext},
        };
        /// 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(styled_dom: StyledDom) -> Self {
                Self {
                    styled_dom,
                    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,
                    },
                }
            }
        }
        /// `.root` = relative, 400×300 border box, 10px border + 5px padding, at (20,30).
        /// Its padding box — the CB every abspos child below resolves against — is
        /// therefore origin (30,40), size 380×280.
        fn abs_fixture(css: &str) -> (Env, LayoutTree, PositionVec) {
            let (sd, mut tree) = two_level(css);
            tree.nodes[0].used_size = Some(LogicalSize::new(400.0, 300.0));
            tree.nodes[0].box_props = bp(uniform(0.0), uniform(5.0), uniform(10.0));
            tree.nodes[1].used_size = Some(LogicalSize::new(50.0, 50.0));
            let pos = positions(&[(20.0, 30.0), (0.0, 0.0)]);
            (Env::new(sd), tree, pos)
        }
        fn run_oof(env: &mut Env, tree: &mut LayoutTree, pos: &mut PositionVec, vp: LogicalRect) {
            let mut text_cache = TextLayoutCache::default();
            let mut ctx = env.ctx();
            position_out_of_flow_elements(&mut ctx, tree, &mut text_cache, pos, vp);
        }
        // --------------------------------------------------------------
        // position_out_of_flow_elements
        // --------------------------------------------------------------
        #[test]
        fn out_of_flow_top_left_offset_from_the_ancestor_padding_box() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 25px; left: \
                 15px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(45.0, 65.0));
        }
        #[test]
        fn out_of_flow_zero_insets_land_exactly_on_the_padding_box_origin() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 0px; left: 0px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(30.0, 40.0));
        }
        #[test]
        fn out_of_flow_all_auto_keeps_the_static_position() {
            // +spec:positioning:aab294 — both insets auto → static position.
            let (mut env, mut tree, mut pos) =
                abs_fixture(".root { position: relative; } .child { position: absolute; }");
            pos_set(&mut pos, 1, LogicalPosition::new(7.0, 9.0));
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(7.0, 9.0));
        }
        #[test]
        fn out_of_flow_fixed_resolves_against_the_viewport_not_the_ancestor() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: fixed; top: 25px; left: 15px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(15.0, 25.0));
        }
        #[test]
        fn out_of_flow_over_constrained_ignores_the_end_insets_in_ltr() {
            // top/height/bottom and left/width/right all given: bottom/right lose.
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 10px; bottom: \
                 10px; left: 10px; right: 10px; width: 50px; height: 50px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(40.0, 50.0));
        }
        #[test]
        fn out_of_flow_auto_margins_center_the_box_in_both_axes() {
            // +spec:height-calculation:5112a4 — both auto margins solve to equal values.
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 0px; bottom: \
                 0px; left: 0px; right: 0px; width: 100px; height: 100px; }",
            );
            tree.nodes[1].used_size = Some(LogicalSize::new(100.0, 100.0));
            tree.nodes[1].box_props = bp_auto_margins(MarginAuto {
                top: true,
                bottom: true,
                left: true,
                right: true,
            });
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            // CB 380×280 at (30,40): (380-100)/2 = 140, (280-100)/2 = 90.
            assert_eq!(pos[1], LogicalPosition::new(170.0, 130.0));
        }
        #[test]
        fn out_of_flow_negative_free_space_with_auto_margins_pins_to_the_start_edge_in_ltr() {
            // +spec:writing-modes:9c3b40 — negative remaining space: start margin is 0.
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; left: 0px; right: \
                 0px; width: 500px; }",
            );
            tree.nodes[1].used_size = Some(LogicalSize::new(500.0, 50.0));
            tree.nodes[1].box_props = bp_auto_margins(MarginAuto {
                left: true,
                right: true,
                top: false,
                bottom: false,
            });
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            // remaining = 380 - 0 - 500 - 0 = -120 → each margin < 0 → pin left.
            assert_eq!(pos[1].x, 30.0);
        }
        #[test]
        fn out_of_flow_over_constrained_ignores_the_left_inset_in_rtl() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; direction: rtl; } .child { position: absolute; left: \
                 10px; right: 10px; width: 50px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            // RTL solves for left: 380 - 50 - 10 = 320 → 30 + 320.
            assert_eq!(pos[1].x, 350.0);
        }
        #[test]
        fn out_of_flow_auto_height_and_width_stretch_between_the_insets() {
            // +spec:intrinsic-sizing:566a43 — stretch-fit sizing on both axes.
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 10px; bottom: \
                 20px; left: 30px; right: 40px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(60.0, 50.0));
            let used = tree.nodes[1].used_size.expect("size was resolved");
            assert_eq!(used, LogicalSize::new(310.0, 250.0));
        }
        #[test]
        fn out_of_flow_insets_larger_than_the_containing_block_clamp_the_size_to_zero() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 500px; bottom: \
                 500px; left: 500px; right: 500px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            let used = tree.nodes[1].used_size.expect("size was resolved");
            assert_eq!(used, LogicalSize::new(0.0, 0.0), "never negative");
            assert!(pos[1].x.is_finite() && pos[1].y.is_finite());
        }
        #[test]
        fn out_of_flow_huge_insets_bypass_the_i16_cache_and_stay_finite() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 3300px; left: \
                 100000px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(100_030.0, 3340.0));
            assert!(pos[1].x.is_finite() && pos[1].y.is_finite());
        }
        #[test]
        fn out_of_flow_negative_insets_move_the_box_outside_the_containing_block() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: -100px; left: \
                 -200px; }",
            );
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos[1], LogicalPosition::new(-170.0, -60.0));
        }
        #[test]
        fn out_of_flow_nan_viewport_clamps_the_stretch_height_to_zero_and_keeps_the_position_finite(
        ) {
            // f32::max(NaN, 0.0) == 0.0, so the stretch-fit height degrades to 0
            // rather than propagating NaN into the display list.
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: fixed; top: 10px; bottom: 20px; \
                 }",
            );
            let nan_vp = LogicalRect::new(
                LogicalPosition::new(0.0, 0.0),
                LogicalSize::new(f32::NAN, f32::NAN),
            );
            run_oof(&mut env, &mut tree, &mut pos, nan_vp);
            let used = tree.nodes[1].used_size.expect("size was resolved");
            assert_eq!(used.height, 0.0);
            assert_eq!(pos[1].y, 10.0);
            assert!(pos[1].y.is_finite());
        }
        #[test]
        fn out_of_flow_infinite_viewport_keeps_the_position_finite() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: fixed; top: 10px; bottom: 20px; \
                 }",
            );
            let inf_vp = LogicalRect::new(
                LogicalPosition::new(0.0, 0.0),
                LogicalSize::new(f32::INFINITY, f32::INFINITY),
            );
            run_oof(&mut env, &mut tree, &mut pos, inf_vp);
            assert_eq!(pos[1].y, 10.0);
            let used = tree.nodes[1].used_size.expect("size was resolved");
            assert!(used.height.is_infinite() && used.height > 0.0);
        }
        #[test]
        fn out_of_flow_every_auto_combination_of_top_height_bottom_is_panic_free() {
            // The rustdoc claims a panic when a resolved offset is None where both
            // edges are expected. Walk all 8 auto/non-auto combinations per axis and
            // prove every `unwrap()` in the constraint solver is actually guarded.
            for top in ["", "top: 10px;"] {
                for bottom in ["", "bottom: 20px;"] {
                    for height in ["", "height: 30px;"] {
                        for left in ["", "left: 10px;"] {
                            for right in ["", "right: 20px;"] {
                                for width in ["", "width: 30px;"] {
                                    let css = format!(
                                        ".root {{ position: relative; }} .child {{ position: \
                                         absolute; {top}{bottom}{height}{left}{right}{width} }}"
                                    );
                                    let (mut env, mut tree, mut pos) = abs_fixture(&css);
                                    run_oof(&mut env, &mut tree, &mut pos, viewport());
                                    assert!(
                                        pos[1].x.is_finite() && pos[1].y.is_finite(),
                                        "non-finite position for {css}"
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
        #[test]
        fn out_of_flow_skips_children_of_flex_and_grid_parents() {
            // Taffy already placed those during flex/grid layout — re-positioning
            // here would double-apply the insets.
            for fc in [FormattingContext::Flex, FormattingContext::Grid] {
                let (mut env, mut tree, mut pos) = abs_fixture(
                    ".root { position: relative; } .child { position: absolute; top: 25px; left: \
                     15px; }",
                );
                tree.nodes[0].formatting_context = fc;
                pos_set(&mut pos, 1, LogicalPosition::new(3.0, 4.0));
                run_oof(&mut env, &mut tree, &mut pos, viewport());
                assert_eq!(pos[1], LogicalPosition::new(3.0, 4.0), "{fc:?}");
            }
        }
        #[test]
        fn out_of_flow_leaves_static_and_relative_nodes_alone() {
            for keyword in ["static", "relative", "sticky"] {
                let css = format!(
                    ".root {{ position: relative; }} .child {{ position: {keyword}; top: 25px; \
                     left: 15px; }}"
                );
                let (mut env, mut tree, mut pos) = abs_fixture(&css);
                pos_set(&mut pos, 1, LogicalPosition::new(3.0, 4.0));
                run_oof(&mut env, &mut tree, &mut pos, viewport());
                assert_eq!(pos[1], LogicalPosition::new(3.0, 4.0), "{keyword}");
            }
        }
        #[test]
        fn out_of_flow_short_position_vec_grows_instead_of_panicking() {
            let (mut env, mut tree, _pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 25px; left: \
                 15px; }",
            );
            let mut pos: PositionVec = Vec::new(); // nothing laid out yet
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert_eq!(pos.len(), 2, "pos_set grew the vec");
            // The CB origin now comes from a default (0,0) ancestor position.
            assert_eq!(pos[1], LogicalPosition::new(25.0, 35.0));
        }
        #[test]
        fn out_of_flow_unsized_node_is_sized_on_the_fly_without_panicking() {
            let (mut env, mut tree, mut pos) = abs_fixture(
                ".root { position: relative; } .child { position: absolute; top: 10px; left: \
                 10px; }",
            );
            tree.nodes[1].used_size = None; // never sized by the main pass
            run_oof(&mut env, &mut tree, &mut pos, viewport());
            assert!(pos[1].x.is_finite() && pos[1].y.is_finite());
        }
        // --------------------------------------------------------------
        // adjust_relative_positions
        // --------------------------------------------------------------
        /// `.root` = 200×100 border box with 10px padding → 180×80 content box,
        /// which is the CB percentages resolve against for the relative child.
        fn rel_fixture(css: &str) -> (Env, LayoutTree, PositionVec) {
            let (sd, mut tree) = two_level(css);
            tree.nodes[0].used_size = Some(LogicalSize::new(200.0, 100.0));
            tree.nodes[0].box_props = bp(uniform(0.0), uniform(10.0), uniform(0.0));
            tree.nodes[1].used_size = Some(LogicalSize::new(50.0, 20.0));
            let pos = positions(&[(0.0, 0.0), (100.0, 100.0)]);
            (Env::new(sd), tree, pos)
        }
        fn run_rel(env: &mut Env, tree: &LayoutTree, pos: &mut PositionVec) {
            let mut ctx = env.ctx();
            adjust_relative_positions(&mut ctx, tree, pos, viewport());
        }
        #[test]
        fn relative_px_offsets_shift_from_the_static_position() {
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; top: 10px; left: 5px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1], LogicalPosition::new(105.0, 110.0));
        }
        #[test]
        fn relative_percentages_resolve_against_the_parent_content_box() {
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; top: 50%; left: 50%; }");
            run_rel(&mut env, &tree, &mut pos);
            // content box is 180×80 → +90 x, +40 y.
            assert_eq!(pos[1], LogicalPosition::new(190.0, 140.0));
        }
        #[test]
        fn relative_top_wins_over_bottom() {
            // +spec:positioning:e3727e — neither auto → bottom is ignored.
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; top: 10px; bottom: 30px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1].y, 110.0);
        }
        #[test]
        fn relative_bottom_alone_is_the_negation_of_top() {
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; bottom: 30px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1].y, 70.0);
        }
        #[test]
        fn relative_right_alone_is_the_negation_of_left() {
            // +spec:overflow:fb426c — left auto → used value is minus right.
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; right: 20px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1].x, 80.0);
        }
        #[test]
        fn relative_left_wins_in_ltr_and_right_wins_in_rtl() {
            // +spec:containing-block:6d4fb1 — direction of the CONTAINING BLOCK decides.
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; left: 5px; right: 20px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1].x, 105.0, "ltr: left wins");
            let (mut env, tree, mut pos) = rel_fixture(
                ".root { direction: rtl; } .child { position: relative; left: 5px; right: 20px; }",
            );
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1].x, 80.0, "rtl: right wins → -20");
        }
        #[test]
        fn relative_zero_offsets_are_a_no_op() {
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; top: 0px; left: 0px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1], LogicalPosition::new(100.0, 100.0));
        }
        #[test]
        fn relative_leaves_static_absolute_and_fixed_nodes_untouched() {
            for keyword in ["static", "absolute", "fixed"] {
                let css = format!(".child {{ position: {keyword}; top: 10px; left: 5px; }}");
                let (mut env, tree, mut pos) = rel_fixture(&css);
                run_rel(&mut env, &tree, &mut pos);
                assert_eq!(pos[1], LogicalPosition::new(100.0, 100.0), "{keyword}");
            }
        }
        #[test]
        fn relative_also_offsets_sticky_boxes() {
            // Sticky deliberately shares the relative path (the pre-scroll offset);
            // adjust_sticky_positions then clamps it. Pinning this so the two passes
            // can't silently start disagreeing.
            let (mut env, tree, mut pos) = rel_fixture(".child { position: relative; top: 10px; }");
            run_rel(&mut env, &tree, &mut pos);
            let relative_y = pos[1].y;
            let (mut env, tree, mut pos) = rel_fixture(".child { position: sticky; top: 10px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1].y, relative_y);
        }
        #[test]
        fn relative_is_undefined_for_table_cells_and_captions_so_they_are_skipped() {
            for display in ["table-cell", "table-caption", "table-column"] {
                let css = format!(
                    ".child {{ position: relative; display: {display}; top: 10px; left: 5px; }}"
                );
                let (mut env, tree, mut pos) = rel_fixture(&css);
                run_rel(&mut env, &tree, &mut pos);
                assert_eq!(pos[1], LogicalPosition::new(100.0, 100.0), "{display}");
            }
        }
        #[test]
        fn relative_table_rows_drag_their_whole_subtree() {
            // +spec:table-layout:ec2600 — the shift affects all contents of the row.
            let (sd, mut tree) = three_level(
                ".mid { position: relative; display: table-row; top: 10px; left: 5px; } .child { \
                 display: table-cell; }",
            );
            tree.nodes[0].used_size = Some(LogicalSize::new(200.0, 100.0));
            tree.nodes[1].used_size = Some(LogicalSize::new(200.0, 50.0));
            tree.nodes[2].used_size = Some(LogicalSize::new(100.0, 50.0));
            let mut pos = positions(&[(0.0, 0.0), (10.0, 20.0), (10.0, 20.0)]);
            let mut env = Env::new(sd);
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1], LogicalPosition::new(15.0, 30.0), "the row itself");
            assert_eq!(pos[2], LogicalPosition::new(15.0, 30.0), "the cell follows");
        }
        #[test]
        fn relative_short_position_vec_is_skipped_not_panicked_on() {
            let (mut env, tree, _pos) =
                rel_fixture(".child { position: relative; top: 10px; left: 5px; }");
            let mut pos: PositionVec = Vec::new();
            run_rel(&mut env, &tree, &mut pos);
            assert!(pos.is_empty(), "nothing to shift, nothing added");
        }
        #[test]
        fn relative_huge_and_negative_offsets_stay_finite() {
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; top: 100000px; left: -100000px; }");
            run_rel(&mut env, &tree, &mut pos);
            assert_eq!(pos[1], LogicalPosition::new(-99_900.0, 100_100.0));
            assert!(pos[1].x.is_finite() && pos[1].y.is_finite());
        }
        #[test]
        fn relative_unset_sentinel_position_is_not_silently_shifted_into_a_real_one() {
            // POSITION_UNSET is f32::MIN. Adding a finite delta to it must stay
            // absurdly negative (it must NOT round into a plausible coordinate) —
            // a caller can still detect the node was never laid out.
            let (mut env, tree, mut pos) =
                rel_fixture(".child { position: relative; top: 10px; left: 5px; }");
            pos[1] = POSITION_UNSET;
            run_rel(&mut env, &tree, &mut pos);
            assert!(pos[1].x < -1e30 && pos[1].y < -1e30);
        }
        // --------------------------------------------------------------
        // adjust_sticky_positions
        // --------------------------------------------------------------
        /// `.root` = a 200×200 scrollport at (0,0); `.child` = 50×20 sticky box at (0,0).
        fn sticky_fixture(css: &str) -> (Env, LayoutTree, PositionVec) {
            let (sd, mut tree) = two_level(css);
            tree.nodes[0].used_size = Some(LogicalSize::new(200.0, 200.0));
            tree.nodes[1].used_size = Some(LogicalSize::new(50.0, 20.0));
            let pos = positions(&[(0.0, 0.0), (0.0, 0.0)]);
            (Env::new(sd), tree, pos)
        }
        fn run_sticky(
            env: &mut Env,
            tree: &LayoutTree,
            pos: &mut PositionVec,
            offsets: &BTreeMap<NodeId, ScrollPosition>,
        ) {
            let mut ctx = env.ctx();
            adjust_sticky_positions(&mut ctx, tree, pos, offsets, viewport());
        }
        #[test]
        fn sticky_top_inset_pins_the_box_to_the_scrollport_edge() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 10px; }",
            );
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            assert_eq!(pos[1], LogicalPosition::new(0.0, 10.0));
        }
        #[test]
        fn sticky_without_insets_does_not_move() {
            let (mut env, tree, mut pos) =
                sticky_fixture(".root { overflow-y: scroll; } .child { position: sticky; }");
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            assert_eq!(pos[1], LogicalPosition::new(0.0, 0.0));
        }
        #[test]
        fn sticky_ignores_non_sticky_positions() {
            for keyword in ["static", "relative", "absolute", "fixed"] {
                let css = format!(
                    ".root {{ overflow-y: scroll; }} .child {{ position: {keyword}; top: 10px; }}"
                );
                let (mut env, tree, mut pos) = sticky_fixture(&css);
                run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
                assert_eq!(pos[1], LogicalPosition::new(0.0, 0.0), "{keyword}");
            }
        }
        #[test]
        fn sticky_edge_moves_with_the_scroll_offset_of_the_nearest_container() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 10px; }",
            );
            let root = node_by_class(&env.styled_dom, "root");
            let mut offsets = BTreeMap::new();
            // The container sits 120px down the window (the AzWriter document
            // view under the ribbon) — its absolute origin must not leak into
            // the scroll amount. Scrolled by 50, it must behave exactly like a
            // container at the window origin scrolled by 50.
            offsets.insert(root, scroll_at((0.0, 120.0), (0.0, 50.0)));
            run_sticky(&mut env, &tree, &mut pos, &offsets);
            // sticky edge = scrollport.y (0) + scroll (50) + inset (10).
            assert_eq!(pos[1].y, 60.0);
        }
        #[test]
        fn sticky_does_not_move_when_a_low_container_is_unscrolled() {
            // REGRESSION: `find_nearest_scroll_offset` used to return
            // `children_rect.origin - parent_rect.origin`, so this container —
            // at y = 120 with the scroll offset still at zero — reported -120
            // and pushed the sticky box a screenful out of its scrollport.
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 10px; }",
            );
            let root = node_by_class(&env.styled_dom, "root");
            let mut offsets = BTreeMap::new();
            offsets.insert(root, scroll_at((0.0, 120.0), (0.0, 0.0)));
            run_sticky(&mut env, &tree, &mut pos, &offsets);
            assert_eq!(pos[1].y, 10.0, "unscrolled: only the inset applies");
        }
        #[test]
        fn sticky_percentage_inset_resolves_against_the_scrollport() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 10%; }",
            );
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            assert_eq!(pos[1].y, 20.0, "10% of the 200px scrollport");
        }
        #[test]
        fn sticky_bottom_inset_pulls_the_box_back_up_into_the_scrollport() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; bottom: 10px; }",
            );
            pos_set(&mut pos, 1, LogicalPosition::new(0.0, 250.0));
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            // bottom edge must sit at 200 - 10 = 190 → top = 190 - 20.
            assert_eq!(pos[1].y, 170.0);
        }
        #[test]
        fn sticky_shift_is_clamped_by_the_containing_block() {
            // +spec:box-model:af9af8 — the margin box must stay inside the CB, even
            // when the scrollport would let the box travel further.
            let (sd, mut tree) = three_level(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 10px; }",
            );
            tree.nodes[0].used_size = Some(LogicalSize::new(200.0, 200.0));
            tree.nodes[1].used_size = Some(LogicalSize::new(200.0, 25.0)); // short CB
            tree.nodes[2].used_size = Some(LogicalSize::new(50.0, 20.0));
            let mut pos = positions(&[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]);
            let mut env = Env::new(sd);
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            // Unclamped the shift would be 10 (bottom = 30 > CB bottom 25) → 5.
            assert_eq!(pos[2].y, 5.0);
        }
        #[test]
        fn sticky_huge_inset_clamps_to_the_containing_block_instead_of_flying_away() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 100000px; }",
            );
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            // The margin box is pushed back until its bottom sits on the CB bottom
            // (200) → top = 200 - 20 = 180.
            assert_eq!(pos[1].y, 180.0);
            assert!(pos[1].y.is_finite());
        }
        #[test]
        fn sticky_negative_inset_is_deterministic_and_finite() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: -50px; }",
            );
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            // sticky edge = -50, border top = 0, already past it → no shift.
            assert_eq!(pos[1], LogicalPosition::new(0.0, 0.0));
        }
        #[test]
        fn sticky_without_a_scroll_ancestor_falls_back_to_the_viewport() {
            let (mut env, tree, mut pos) =
                sticky_fixture(".child { position: sticky; top: 10px; }"); // .root does not scroll
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            // Scrollport = viewport (0,0,800×600); CB = the parent's 200×200 content
            // box, which comfortably contains the 10px shift.
            assert_eq!(pos[1].y, 10.0);
        }
        #[test]
        fn sticky_left_and_right_insets_shift_the_inline_axis() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-x: scroll; } .child { position: sticky; left: 15px; }",
            );
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            assert_eq!(pos[1].x, 15.0);
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-x: scroll; } .child { position: sticky; right: 10px; }",
            );
            pos_set(&mut pos, 1, LogicalPosition::new(300.0, 0.0));
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            // right edge pinned at 200 - 10 = 190 → x = 190 - 50.
            assert_eq!(pos[1].x, 140.0);
        }
        #[test]
        fn sticky_short_position_vec_is_skipped_not_panicked_on() {
            let (mut env, tree, _pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 10px; }",
            );
            let mut pos: PositionVec = Vec::new();
            run_sticky(&mut env, &tree, &mut pos, &BTreeMap::new());
            assert!(pos.is_empty());
        }
        #[test]
        fn sticky_nan_scroll_offset_never_panics() {
            let (mut env, tree, mut pos) = sticky_fixture(
                ".root { overflow-y: scroll; } .child { position: sticky; top: 10px; }",
            );
            let root = node_by_class(&env.styled_dom, "root");
            let mut offsets = BTreeMap::new();
            offsets.insert(root, scroll_at((f32::NAN, f32::NAN), (f32::NAN, f32::NAN)));
            run_sticky(&mut env, &tree, &mut pos, &offsets);
            // NaN comparisons are all false → no shift is ever applied.
            assert_eq!(pos[1], LogicalPosition::new(0.0, 0.0));
        }
    }
}