gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 492HTML 245JavaScript 7CSS 51137 Sutichaykuna

⎇ 75456ae18d076fb4c79145910c9bf1e584705157 src/compute/block.rs Rust · 1395 siq'ikuna · 62.0 KB Ñawpa willay Pi imata llamkarqan ch'uya

Block: don't set_unrounded_layout when measuring (#971) 75456ae18 · Nico Burns ·

1//! Computes the CSS block layout algorithm in the case that the block container being laid out contains only block-level boxes
2use crate::geometry::{Line, Point, Rect, Size};
3use crate::style::{AvailableSpace, CoreStyle, LengthPercentageAuto, Overflow, Position};
4use crate::style_helpers::TaffyMaxContent;
5use crate::tree::{CollapsibleMarginSet, Layout, LayoutInput, LayoutOutput, RunMode, SizingMode};
6use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, NodeId};
7use crate::util::debug::debug_log;
8use crate::util::sys::f32_max;
9use crate::util::sys::Vec;
10use crate::util::MaybeMath;
11use crate::util::{MaybeResolve, ResolveOrZero};
12use crate::{
13    BlockContainerStyle, BlockItemStyle, BoxGenerationMode, BoxSizing, Direction, LayoutBlockContainer, RequestedAxis,
14    TextAlign,
15};
16
17#[cfg(feature = "float_layout")]
18use super::float::{ContentSlot, FloatContext, FloatIntrinsicWidthCalculator};
19#[cfg(feature = "float_layout")]
20use crate::{Clear, Float, FloatDirection};
21
22/// Context for positioning Block and Float boxes within a Block Formatting Context
23pub struct BlockFormattingContext {
24    /// The float positioning context that handles positioning floats within this Block Formatting Context
25    #[cfg(feature = "float_layout")]
26    float_context: FloatContext,
27}
28
29impl Default for BlockFormattingContext {
30    fn default() -> Self {
31        Self {
32            #[cfg(feature = "float_layout")]
33            float_context: FloatContext::new(),
34        }
35    }
36}
37
38impl BlockFormattingContext {
39    /// Create a new `BlockFormattingContext` with the specified width constraint
40    pub fn new() -> Self {
41        Default::default()
42    }
43
44    /// Create an initial `BlockContext` for this `BlockFormattingContext`
45    pub fn root_block_context(&mut self) -> BlockContext<'_> {
46        BlockContext {
47            bfc: self,
48            y_offset: 0.0,
49            insets: [0.0, 0.0],
50            content_box_insets: [0.0, 0.0],
51            float_content_contribution: 0.0,
52            is_root: true,
53        }
54    }
55}
56
57/// Context for each individual Block within a Block Formatting Context
58///
59/// Contains a mutable reference to the BlockFormattingContext + block-specific data
60pub struct BlockContext<'bfc> {
61    /// A mutable reference to the root BlockFormatttingContext that this BlockContext belongs to
62    bfc: &'bfc mut BlockFormattingContext,
63    /// The y-offset of the border-top of the block node, relative to the to the border-top of the
64    /// root node of the Block Formatting Context it belongs to.
65    y_offset: f32,
66    /// The x-inset of the border-box in from each side of the block node, relative to the root node of the Block Formatting Context it belongs to.
67    insets: [f32; 2],
68    /// The x-insets of the content box
69    content_box_insets: [f32; 2],
70    /// The height that floats take up in the element
71    float_content_contribution: f32,
72    /// Whether the node is the root of the Block Formatting Context is belongs to.
73    is_root: bool,
74}
75
76impl BlockContext<'_> {
77    /// Create a sub-`BlockContext` for a child block node
78    pub fn sub_context(&mut self, additional_y_offset: f32, insets: [f32; 2]) -> BlockContext<'_> {
79        let insets = [self.insets[0] + insets[0], self.insets[1] + insets[1]];
80        BlockContext {
81            bfc: self.bfc,
82            y_offset: self.y_offset + additional_y_offset,
83            insets,
84            content_box_insets: insets,
85            float_content_contribution: 0.0,
86            is_root: false,
87        }
88    }
89
90    /// Returns whether this block is the root block of it's Block Formatting Context
91    pub fn is_bfc_root(&self) -> bool {
92        self.is_root
93    }
94}
95
96#[cfg(feature = "float_layout")]
97impl BlockContext<'_> {
98    /// Set the width of the overall Block Formatting Context. This is used to resolve positions
99    /// that are relative to the right of the context such as right-floated boxes.
100    ///
101    /// Sub-blocks within a Block Formatting Context should use the `Self::sub_context` method to create
102    /// a sub-`BlockContext` with `insets` instead.
103    pub fn set_width(&mut self, available_width: f32) {
104        self.bfc.float_context.set_width(available_width);
105    }
106
107    /// Set the x-axis content-box insets of the `BlockContext`. These are the difference between the border-box
108    /// and the content-box of the box (padding + border + scrollbar_gutter).
109    pub fn apply_content_box_inset(&mut self, content_box_x_insets: [f32; 2]) {
110        self.content_box_insets[0] = self.insets[0] + content_box_x_insets[0];
111        self.content_box_insets[1] = self.insets[1] + content_box_x_insets[1];
112    }
113
114    /// Whether the float context contains any floats
115    #[inline(always)]
116    pub fn has_floats(&self) -> bool {
117        self.bfc.float_context.has_floats()
118    }
119
120    /// Whether the float context contains any floats that extend to or below min_y
121    #[inline(always)]
122    pub fn has_active_floats(&self, min_y: f32) -> bool {
123        self.bfc.float_context.has_active_floats(min_y + self.y_offset)
124    }
125
126    /// Position a floated box with the context
127    pub fn place_floated_box(
128        &mut self,
129        floated_box: Size<f32>,
130        min_y: f32,
131        direction: FloatDirection,
132        clear: Clear,
133    ) -> Point<f32> {
134        let mut pos = self.bfc.float_context.place_floated_box(
135            floated_box,
136            min_y + self.y_offset,
137            self.content_box_insets,
138            direction,
139            clear,
140        );
141        pos.y -= self.y_offset;
142        pos.x -= self.insets[0];
143
144        self.float_content_contribution = self.float_content_contribution.max(pos.y + floated_box.height);
145
146        pos
147    }
148
149    /// Search a space suitable for laying out non-floated content into
150    pub fn find_content_slot(&self, min_y: f32, clear: Clear, after: Option<usize>) -> ContentSlot {
151        let mut slot =
152            self.bfc.float_context.find_content_slot(min_y + self.y_offset, self.content_box_insets, clear, after);
153        slot.y -= self.y_offset;
154        slot.x -= self.insets[0];
155        slot
156    }
157
158    /// Get the bottom of lowest relevant float for the specific clear property
159    pub fn cleared_threshold(&self, clear: Clear) -> Option<f32> {
160        self.bfc.float_context.cleared_threshold(clear).map(|threshold| threshold - self.y_offset)
161    }
162
163    /// Update the height that descendent floats with the height that floats consume
164    /// within a particular child
165    fn add_child_floated_content_height_contribution(&mut self, child_contribution: f32) {
166        self.float_content_contribution = self.float_content_contribution.max(child_contribution);
167    }
168
169    /// Returns the height that descendent floats consume
170    pub fn floated_content_height_contribution(&self) -> f32 {
171        self.float_content_contribution
172    }
173}
174
175#[cfg(not(feature = "float_layout"))]
176impl BlockContext<'_> {
177    #[inline(always)]
178    /// Returns the height that descendent floats consume (always 0.0 when the float feature is disabled)
179    fn float_content_contribution(&self) -> f32 {
180        0.0
181    }
182}
183
184use super::common::alignment::{apply_alignment_fallback, compute_alignment_offset};
185#[cfg(feature = "content_size")]
186use super::common::content_size::compute_content_size_contribution;
187
188/// Per-child data that is accumulated and modified over the course of the layout algorithm
189struct BlockItem {
190    /// The identifier for the associated node
191    node_id: NodeId,
192
193    /// The "source order" of the item. This is the index of the item within the children iterator,
194    /// and controls the order in which the nodes are placed
195    order: u32,
196
197    /// Items that are tables don't have stretch sizing applied to them
198    is_table: bool,
199
200    /// Whether the child is a non-independent block or inline node
201    is_in_same_bfc: bool,
202
203    #[cfg(feature = "float_layout")]
204    /// The `float` style of the node
205    float: Float,
206    #[cfg(feature = "float_layout")]
207    /// The `clear` style of the node
208    clear: Clear,
209
210    /// The base size of this item
211    size: Size<Option<f32>>,
212    /// The minimum allowable size of this item
213    min_size: Size<Option<f32>>,
214    /// The maximum allowable size of this item
215    max_size: Size<Option<f32>>,
216
217    /// The overflow style of the item
218    overflow: Point<Overflow>,
219    /// The width of the item's scrollbars (if it has scrollbars)
220    scrollbar_width: f32,
221
222    /// The position style of the item
223    position: Position,
224    /// The final offset of this item
225    inset: Rect<LengthPercentageAuto>,
226    /// The margin of this item
227    margin: Rect<LengthPercentageAuto>,
228    /// The margin of this item
229    padding: Rect<f32>,
230    /// The margin of this item
231    border: Rect<f32>,
232    /// The sum of padding and border for this item
233    padding_border_sum: Size<f32>,
234
235    /// The computed border box size of this item
236    computed_size: Size<f32>,
237    /// The computed "static position" of this item. The static position is the position
238    /// taking into account padding, border, margins, and scrollbar_gutters but not inset
239    static_position: Point<f32>,
240    /// Whether margins can be collapsed through this item
241    can_be_collapsed_through: bool,
242
243    /// Pending layout for in-flow non-floated items. Held back from `set_unrounded_layout` so the
244    /// post-loop `align-content` pass in `compute_inner` can shift `location.y` before commit.
245    final_layout: Option<Layout>,
246}
247
248/// Computes the layout of [`LayoutPartialTree`] according to the block layout algorithm
249pub fn compute_block_layout(
250    tree: &mut impl LayoutBlockContainer,
251    node_id: NodeId,
252    inputs: LayoutInput,
253    block_ctx: Option<&mut BlockContext<'_>>,
254) -> LayoutOutput {
255    let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
256    let style = tree.get_block_container_style(node_id);
257
258    // Pull these out earlier to avoid borrowing issues
259    let overflow = style.overflow();
260    let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
261    let aspect_ratio = style.aspect_ratio();
262    let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
263    let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
264    let padding_border_size = (padding + border).sum_axes();
265    let box_sizing_adjustment =
266        if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
267
268    let min_size = style
269        .min_size()
270        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
271        .maybe_apply_aspect_ratio(aspect_ratio)
272        .maybe_add(box_sizing_adjustment);
273    let max_size = style
274        .max_size()
275        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
276        .maybe_apply_aspect_ratio(aspect_ratio)
277        .maybe_add(box_sizing_adjustment);
278    let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
279        style
280            .size()
281            .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
282            .maybe_apply_aspect_ratio(aspect_ratio)
283            .maybe_add(box_sizing_adjustment)
284            .maybe_clamp(min_size, max_size)
285    } else {
286        Size::NONE
287    };
288
289    drop(style);
290
291    // If both min and max in a given axis are set and max <= min then this determines the size in that axis
292    let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
293        (Some(min), Some(max)) if max <= min => Some(min),
294        _ => None,
295    });
296
297    let styled_based_known_dimensions =
298        known_dimensions.or(min_max_definite_size).or(clamped_style_size).maybe_max(padding_border_size);
299
300    // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
301    // is ComputeSize (and thus the container's size is all that we're interested in)
302    if run_mode == RunMode::ComputeSize {
303        if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
304            return LayoutOutput::from_outer_size(Size { width, height });
305        }
306
307        // We can also short-circuit if the width is known and only the width has been requested.
308        if inputs.axis == RequestedAxis::Horizontal {
309            if let Some(width) = styled_based_known_dimensions.width {
310                return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
311            }
312        }
313    }
314
315    // Unwrap the block formatting context if one was passed, or else create a new one
316    debug_log!("BLOCK");
317    match block_ctx {
318        Some(inherited_bfc) if !is_scroll_container => compute_inner(
319            tree,
320            node_id,
321            LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
322            inherited_bfc,
323        ),
324        _ => {
325            let mut root_bfc = BlockFormattingContext::new();
326            let mut root_ctx = root_bfc.root_block_context();
327            compute_inner(
328                tree,
329                node_id,
330                LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
331                &mut root_ctx,
332            )
333        }
334    }
335}
336
337/// Computes the layout of [`LayoutBlockContainer`] according to the block layout algorithm
338fn compute_inner(
339    tree: &mut impl LayoutBlockContainer,
340    node_id: NodeId,
341    inputs: LayoutInput,
342    #[allow(unused_mut)] mut block_ctx: &mut BlockContext<'_>,
343) -> LayoutOutput {
344    let LayoutInput {
345        known_dimensions, parent_size, available_space, run_mode, vertical_margins_are_collapsible, ..
346    } = inputs;
347
348    let style = tree.get_block_container_style(node_id);
349    let raw_padding = style.padding();
350    let raw_border = style.border();
351    let raw_margin = style.margin();
352    let aspect_ratio = style.aspect_ratio();
353    let padding = raw_padding.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
354    let border = raw_border.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
355    let direction = style.direction();
356
357    // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
358    // However, the axis are switched (transposed) because a node that scrolls vertically needs
359    // *horizontal* space to be reserved for a scrollbar
360    let scrollbar_gutter = {
361        let offsets = style.overflow().transpose().map(|overflow| match overflow {
362            Overflow::Scroll => style.scrollbar_width(),
363            _ => 0.0,
364        });
365        match direction {
366            Direction::Ltr => Rect { top: 0.0, left: 0.0, right: offsets.x, bottom: offsets.y },
367            Direction::Rtl => Rect { top: 0.0, left: offsets.x, right: 0.0, bottom: offsets.y },
368        }
369    };
370    let padding_border = padding + border;
371    let padding_border_size = padding_border.sum_axes();
372    let content_box_inset = padding_border + scrollbar_gutter;
373
374    // Apply content box inset
375    #[cfg(feature = "float_layout")]
376    block_ctx.apply_content_box_inset([content_box_inset.left, content_box_inset.right]);
377
378    let box_sizing_adjustment =
379        if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
380    let size = style
381        .size()
382        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
383        .maybe_apply_aspect_ratio(aspect_ratio)
384        .maybe_add(box_sizing_adjustment);
385    let min_size = style
386        .min_size()
387        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
388        .maybe_apply_aspect_ratio(aspect_ratio)
389        .maybe_add(box_sizing_adjustment);
390    let max_size = style
391        .max_size()
392        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
393        .maybe_apply_aspect_ratio(aspect_ratio)
394        .maybe_add(box_sizing_adjustment);
395
396    // css-sizing-4: a definite size in one axis transfers through `aspect-ratio`
397    // to make the other definite. Deriving it from `known_dimensions` self-gates
398    // the transfer — a block parent fills an axis only when it's a real
399    // constraint (e.g. the stretched width at final layout) and leaves it None
400    // while probing intrinsic sizes, so measure passes stay content-based. Only a
401    // newly-filled axis is adopted (and clamped); an incoming known size is left
402    // as the parent resolved it (re-clamping would undo padding/border overrides).
403    let known_dimensions = {
404        let derived = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
405        Size { width: known_dimensions.width.or(derived.width), height: known_dimensions.height.or(derived.height) }
406    };
407    let container_content_box_size = known_dimensions.maybe_sub(content_box_inset.sum_axes());
408
409    let overflow = style.overflow();
410    let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
411
412    // Determine margin collapsing behaviour
413    let own_margins_collapse_with_children = Line {
414        start: vertical_margins_are_collapsible.start
415            && !is_scroll_container
416            && style.position() == Position::Relative
417            && padding.top == 0.0
418            && border.top == 0.0,
419        end: vertical_margins_are_collapsible.end
420            && !is_scroll_container
421            && style.position() == Position::Relative
422            && padding.bottom == 0.0
423            && border.bottom == 0.0
424            && size.height.is_none(),
425    };
426    let has_styles_preventing_being_collapsed_through = !style.is_block()
427        || block_ctx.is_bfc_root()
428        || is_scroll_container
429        || style.position() == Position::Absolute
430        || padding.top > 0.0
431        || padding.bottom > 0.0
432        || border.top > 0.0
433        || border.bottom > 0.0
434        || matches!(size.height, Some(h) if h > 0.0)
435        || matches!(min_size.height, Some(h) if h > 0.0);
436
437    let text_align = style.text_align();
438    let align_content = style.align_content();
439    drop(style);
440
441    // 1. Generate items
442    let mut items = generate_item_list(tree, node_id, container_content_box_size);
443
444    // 2. Compute container width
445    let container_outer_width = known_dimensions.width.unwrap_or_else(|| {
446        let available_width = available_space.width.maybe_sub(content_box_inset.horizontal_axis_sum());
447        let intrinsic_width = determine_content_based_container_width(tree, &items, available_width)
448            + content_box_inset.horizontal_axis_sum();
449        intrinsic_width.maybe_clamp(min_size.width, max_size.width).maybe_max(Some(padding_border_size.width))
450    });
451
452    // Short-circuit if computing size and both dimensions known
453    if let (RunMode::ComputeSize, Some(container_outer_height)) = (run_mode, known_dimensions.height) {
454        return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: container_outer_height });
455    }
456
457    // We can also short-circuit if the width is known and only the width has been requested.
458    if run_mode == RunMode::ComputeSize && inputs.axis == RequestedAxis::Horizontal {
459        return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: 0.0 });
460    }
461
462    let container_percentage_resolution_height =
463        known_dimensions.height.or(size.height.maybe_max(min_size.height)).or(min_size.height);
464
465    // 3. Perform final item layout and return content height
466    let resolved_padding = raw_padding.resolve_or_zero(Some(container_outer_width), |val, basis| tree.calc(val, basis));
467    let resolved_border = raw_border.resolve_or_zero(Some(container_outer_width), |val, basis| tree.calc(val, basis));
468    let resolved_content_box_inset = resolved_padding + resolved_border + scrollbar_gutter;
469    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
470    let (mut inflow_content_size, mut intrinsic_outer_height, first_child_top_margin_set, last_child_bottom_margin_set) =
471        perform_final_layout_on_in_flow_children(
472            tree,
473            &mut items,
474            container_outer_width,
475            container_percentage_resolution_height,
476            content_box_inset,
477            resolved_content_box_inset,
478            text_align,
479            direction,
480            own_margins_collapse_with_children,
481            block_ctx,
482        );
483
484    // Root BFCs contain floats
485    #[cfg(feature = "float_layout")]
486    if block_ctx.is_bfc_root() || is_scroll_container {
487        intrinsic_outer_height = intrinsic_outer_height.max(block_ctx.floated_content_height_contribution());
488    }
489
490    let container_outer_height = known_dimensions
491        .height
492        .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
493        .maybe_max(Some(padding_border_size.height));
494    let final_outer_size = Size { width: container_outer_width, height: container_outer_height };
495
496    // Apply `align-content` to in-flow non-floated items if requested. The per-item layouts were
497    // held back in `item.final_layout` so that this step can shift `location.y` before tree commit.
498    //
499    // For block layout the entire stack of in-flow children is treated as a single alignment
500    // subject. That means distribution keywords (`space-between`, `space-around`,
501    // `space-evenly`, `stretch`) must invoke the single-subject fallback unconditionally —
502    // which is what passing `num_items = 1` to `apply_alignment_fallback` does. The whole
503    // group then shifts by one offset, with zero inter-item gap.
504    if let Some(align_content) = align_content {
505        let container_inner_height = container_outer_height - resolved_content_box_inset.vertical_axis_sum();
506        let inflow_content_height = intrinsic_outer_height - resolved_content_box_inset.vertical_axis_sum();
507        let free_space = container_inner_height - inflow_content_height;
508        let any_in_flow = items.iter().any(|item| item.final_layout.is_some());
509        if any_in_flow {
510            let keyword = apply_alignment_fallback(free_space, 1, align_content);
511            let group_offset = compute_alignment_offset(free_space, 1, 0.0, keyword, false, true);
512            for item in items.iter_mut() {
513                if let Some(layout) = item.final_layout.as_mut() {
514                    layout.location.y += group_offset;
515                }
516            }
517
518            #[cfg(feature = "content_size")]
519            {
520                inflow_content_size = Size::ZERO;
521                for item in items.iter() {
522                    if let Some(layout) = item.final_layout.as_ref() {
523                        inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
524                            layout.location
525                                + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
526                            layout.size,
527                            layout.content_size,
528                            item.overflow,
529                        ));
530                    }
531                }
532            }
533        }
534    }
535
536    // Short-circuit if computing size
537    if run_mode == RunMode::ComputeSize {
538        return LayoutOutput::from_outer_size(final_outer_size);
539    }
540
541    // Commit deferred in-flow layouts to the tree. Floated items already wrote their own layouts.
542    for item in items.iter() {
543        if let Some(layout) = item.final_layout.as_ref() {
544            tree.set_unrounded_layout(item.node_id, layout);
545        }
546    }
547
548    // 4. Layout absolutely positioned children
549    let absolute_position_inset = resolved_border + scrollbar_gutter;
550    let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
551    let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
552    let absolute_content_size = perform_absolute_layout_on_absolute_children(
553        tree,
554        &items,
555        absolute_position_area,
556        absolute_position_offset,
557        direction,
558    );
559
560    // 5. Perform hidden layout on hidden children
561    let len = tree.child_count(node_id);
562    for order in 0..len {
563        let child = tree.get_child_id(node_id, order);
564        let child_style = tree.get_block_child_style(child);
565        if child_style.box_generation_mode() == BoxGenerationMode::None {
566            drop(child_style);
567            tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
568            tree.perform_child_layout(
569                child,
570                Size::NONE,
571                Size::NONE,
572                Size::MAX_CONTENT,
573                SizingMode::InherentSize,
574                Line::FALSE,
575            );
576        }
577    }
578
579    // 7. Determine whether this node can be collapsed through
580    let all_in_flow_children_can_be_collapsed_through =
581        items.iter().all(|item| item.position == Position::Absolute || item.can_be_collapsed_through);
582    let can_be_collapsed_through =
583        !has_styles_preventing_being_collapsed_through && all_in_flow_children_can_be_collapsed_through;
584
585    #[cfg_attr(not(feature = "content_size"), allow(unused_variables))]
586    let content_size = inflow_content_size.f32_max(absolute_content_size);
587
588    LayoutOutput {
589        size: final_outer_size,
590        #[cfg(feature = "content_size")]
591        content_size,
592        first_baselines: Point::NONE,
593        top_margin: if own_margins_collapse_with_children.start {
594            first_child_top_margin_set
595        } else {
596            let margin_top = raw_margin.top.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
597            CollapsibleMarginSet::from_margin(margin_top)
598        },
599        bottom_margin: if own_margins_collapse_with_children.end {
600            last_child_bottom_margin_set
601        } else {
602            let margin_bottom =
603                raw_margin.bottom.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
604            CollapsibleMarginSet::from_margin(margin_bottom)
605        },
606        margins_can_collapse_through: can_be_collapsed_through,
607    }
608}
609
610/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
611#[inline]
612fn generate_item_list(
613    tree: &impl LayoutBlockContainer,
614    node: NodeId,
615    node_inner_size: Size<Option<f32>>,
616) -> Vec<BlockItem> {
617    tree.child_ids(node)
618        .map(|child_node_id| (child_node_id, tree.get_block_child_style(child_node_id)))
619        .filter(|(_, style)| style.box_generation_mode() != BoxGenerationMode::None)
620        .enumerate()
621        .map(|(order, (child_node_id, child_style))| {
622            let aspect_ratio = child_style.aspect_ratio();
623            let padding = child_style.padding().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
624            let border = child_style.border().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
625            let pb_sum = (padding + border).sum_axes();
626            let box_sizing_adjustment =
627                if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
628
629            let position = child_style.position();
630            let overflow = child_style.overflow();
631
632            #[cfg(feature = "float_layout")]
633            let float = child_style.float();
634            #[cfg(feature = "float_layout")]
635            let is_not_floated = float == Float::None;
636
637            #[cfg(not(feature = "float_layout"))]
638            let is_not_floated = true;
639
640            let is_block = child_style.is_block();
641            let is_table = child_style.is_table();
642            let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
643
644            let is_in_same_bfc: bool =
645                is_block && !is_table && position != Position::Absolute && is_not_floated && !is_scroll_container;
646
647            BlockItem {
648                node_id: child_node_id,
649                order: order as u32,
650                is_table,
651                is_in_same_bfc,
652                #[cfg(feature = "float_layout")]
653                float,
654                #[cfg(feature = "float_layout")]
655                clear: child_style.clear(),
656                size: child_style
657                    .size()
658                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
659                    .maybe_apply_aspect_ratio(aspect_ratio)
660                    .maybe_add(box_sizing_adjustment),
661                min_size: child_style
662                    .min_size()
663                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
664                    .maybe_apply_aspect_ratio(aspect_ratio)
665                    .maybe_add(box_sizing_adjustment),
666                max_size: child_style
667                    .max_size()
668                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
669                    .maybe_apply_aspect_ratio(aspect_ratio)
670                    .maybe_add(box_sizing_adjustment),
671                overflow,
672                scrollbar_width: child_style.scrollbar_width(),
673                position,
674                inset: child_style.inset(),
675                margin: child_style.margin(),
676                padding,
677                border,
678                padding_border_sum: pb_sum,
679
680                // Fields to be computed later (for now we initialise with dummy values)
681                computed_size: Size::zero(),
682                static_position: Point::zero(),
683                can_be_collapsed_through: false,
684                final_layout: None,
685            }
686        })
687        .collect()
688}
689
690/// Compute the content-based width in the case that the width of the container is not known
691#[inline]
692fn determine_content_based_container_width(
693    tree: &mut impl LayoutPartialTree,
694    items: &[BlockItem],
695    available_width: AvailableSpace,
696) -> f32 {
697    let available_space = Size { width: available_width, height: AvailableSpace::MinContent };
698
699    let mut max_child_width = 0.0;
700    #[cfg(feature = "float_layout")]
701    let mut float_contribution = FloatIntrinsicWidthCalculator::new(available_width);
702    for item in items.iter().filter(|item| item.position != Position::Absolute) {
703        let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);
704
705        let item_x_margin_sum = item
706            .margin
707            .resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis))
708            .horizontal_axis_sum();
709        let width = known_dimensions.width.unwrap_or_else(|| {
710            tree.measure_child_size(
711                item.node_id,
712                known_dimensions,
713                Size::NONE,
714                available_space.map_width(|w| w.maybe_sub(item_x_margin_sum)),
715                SizingMode::InherentSize,
716                crate::AbsoluteAxis::Horizontal,
717                Line::TRUE,
718            )
719        });
720
721        let width = f32_max(width, item.padding_border_sum.width) + item_x_margin_sum;
722
723        #[cfg(feature = "float_layout")]
724        if let Some(direction) = item.float.float_direction() {
725            float_contribution.add_float(width, direction, item.clear);
726            continue;
727        }
728
729        max_child_width = f32_max(max_child_width, width);
730    }
731
732    #[cfg(feature = "float_layout")]
733    {
734        max_child_width = max_child_width.max(float_contribution.result());
735    }
736
737    max_child_width
738}
739
740/// Compute each child's final size and position
741#[inline]
742#[allow(clippy::too_many_arguments)]
743fn perform_final_layout_on_in_flow_children(
744    tree: &mut impl LayoutBlockContainer,
745    items: &mut [BlockItem],
746    container_outer_width: f32,
747    container_percentage_resolution_height: Option<f32>,
748    content_box_inset: Rect<f32>,
749    resolved_content_box_inset: Rect<f32>,
750    text_align: TextAlign,
751    direction: Direction,
752    own_margins_collapse_with_children: Line<bool>,
753    block_ctx: &mut BlockContext<'_>,
754) -> (Size<f32>, f32, CollapsibleMarginSet, CollapsibleMarginSet) {
755    // Resolve container_inner_width for sizing child nodes using initial content_box_inset
756    let container_inner_width = container_outer_width - resolved_content_box_inset.horizontal_axis_sum();
757    let container_percentage_resolution_height =
758        container_percentage_resolution_height.maybe_sub(resolved_content_box_inset.vertical_axis_sum());
759    let parent_size = Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
760    // Vertical available space in block flow is indefinite, NOT a min-content
761    // constraint: MaxContent is taffy's representation of "indefinite".
762    // Passing MinContent here made every descendant grid believe it was being
763    // sized under a min-content constraint, in which the maximize-tracks step
764    // has zero free space — so auto rows containing only scroll-container
765    // items (overflow != visible, automatic minimum size = 0) collapsed to
766    // zero height. Browsers size such rows to the item's content.
767    let available_space =
768        Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MaxContent };
769
770    // TODO: handle nested blocks with different widths
771    #[cfg(feature = "float_layout")]
772    if block_ctx.is_bfc_root() {
773        block_ctx.set_width(container_outer_width);
774        block_ctx.apply_content_box_inset([resolved_content_box_inset.left, resolved_content_box_inset.right]);
775    }
776
777    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
778    let mut inflow_content_size = Size::ZERO;
779    let mut committed_y_offset = resolved_content_box_inset.top;
780    let mut y_offset_for_absolute = resolved_content_box_inset.top;
781    let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
782    let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
783    let mut is_collapsing_with_first_margin_set = true;
784
785    #[cfg(feature = "float_layout")]
786    let mut has_active_floats = block_ctx.has_active_floats(committed_y_offset);
787    #[cfg(not(feature = "float_layout"))]
788    let has_active_floats = false;
789    #[cfg(feature = "float_layout")]
790    let mut y_offset_for_float = resolved_content_box_inset.top;
791
792    for item in items.iter_mut() {
793        if item.position == Position::Absolute {
794            let x = match direction {
795                Direction::Ltr => resolved_content_box_inset.left,
796                Direction::Rtl => container_outer_width - resolved_content_box_inset.right,
797            };
798            item.static_position = Point { x, y: y_offset_for_absolute }
799        } else {
800            let item_margin = item
801                .margin
802                .map(|margin| margin.resolve_to_option(container_outer_width, |val, basis| tree.calc(val, basis)));
803            let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
804            let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();
805
806            let scrollbar_size = Size {
807                width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
808                height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
809            };
810
811            // Handle floated boxes
812            #[cfg(feature = "float_layout")]
813            if let Some(float_direction) = item.float.float_direction() {
814                has_active_floats = true;
815
816                let item_layout = tree.perform_child_layout(
817                    item.node_id,
818                    Size::NONE,
819                    parent_size,
820                    // available_space,
821                    Size::MAX_CONTENT,
822                    SizingMode::InherentSize,
823                    Line::TRUE,
824                );
825                let margin_box = item_layout.size + item_non_auto_margin.sum_axes();
826
827                let mut location =
828                    block_ctx.place_floated_box(margin_box, y_offset_for_float, float_direction, item.clear);
829
830                // Ensure that content that appears after a float does not get positioned before/above the float
831                //
832                // FIXME: this isn't quite right, because a second float at the same location
833                // shouldn't cause content to push down to it's level
834                // committed_y_offset = committed_y_offset.max(location.y);
835                // y_offset_for_absolute = y_offset_for_absolute.max(location.y);
836                // y_offset_for_float = y_offset_for_float.max(location.y);
837
838                // Convert the margin-box location returned by float placement into a border-box location
839                // for the output Layout
840                location.y += item_non_auto_margin.top;
841                location.x += item_non_auto_margin.left;
842
843                // println!("BLOCK FLOATED BOX ({:?}) {:?}", item.node_id, float_direction);
844                // println!("w:{} h:{} x:{}, y:{}", margin_box.width, margin_box.height, location.x, location.y);
845
846                tree.set_unrounded_layout(
847                    item.node_id,
848                    &Layout {
849                        order: item.order,
850                        size: item_layout.size,
851                        #[cfg(feature = "content_size")]
852                        content_size: item_layout.content_size,
853                        scrollbar_size,
854                        location,
855                        padding: item.padding,
856                        border: item.border,
857                        margin: item_non_auto_margin,
858                    },
859                );
860
861                #[cfg(feature = "content_size")]
862                {
863                    // TODO: Should content size of floated boxes count as "inflow_content_size"
864                    // or should it be counted separately?
865                    inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
866                        location,
867                        item_layout.size,
868                        item_layout.content_size,
869                        item.overflow,
870                    ));
871                }
872
873                continue;
874            }
875
876            // Handle non-floated boxes
877
878            let mut y_margin_offset: f32 = 0.0;
879
880            let (stretch_width, float_avoiding_position, float_avoiding_width) = if item.is_in_same_bfc {
881                let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
882                let position = Point { x: 0.0, y: 0.0 };
883                let width = 0.0;
884
885                (stretch_width, position, width)
886            } else {
887                'block: {
888                    // Set y_margin_offset (different bfc child)
889                    if !is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start {
890                        y_margin_offset =
891                            active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
892                    };
893                    let min_y = committed_y_offset + y_margin_offset;
894
895                    #[cfg(feature = "float_layout")]
896                    if has_active_floats {
897                        let slot = block_ctx.find_content_slot(min_y, item.clear, None);
898                        has_active_floats = slot.segment_id.is_some();
899                        let stretch_width = slot.width - item_non_auto_x_margin_sum;
900                        break 'block (stretch_width, Point { x: slot.x, y: slot.y }, slot.width);
901                    }
902
903                    if !has_active_floats {
904                        let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
905                        break 'block (
906                            stretch_width,
907                            Point { x: resolved_content_box_inset.left, y: min_y },
908                            container_inner_width,
909                        );
910                    }
911
912                    unreachable!("One of the above cases will always be hit");
913                }
914            };
915
916            let known_dimensions = if item.is_table {
917                Size::NONE
918            } else {
919                item.size
920                    .map_width(|width| {
921                        // TODO: Allow stretch-sizing to be conditional, as there are exceptions.
922                        // e.g. Table children of blocks do not stretch fit
923                        Some(width.unwrap_or(stretch_width).maybe_clamp(item.min_size.width, item.max_size.width))
924                    })
925                    .maybe_clamp(item.min_size, item.max_size)
926            };
927
928            //
929
930            let inputs = LayoutInput {
931                run_mode: RunMode::PerformLayout,
932                sizing_mode: SizingMode::InherentSize,
933                axis: RequestedAxis::Both,
934                known_dimensions,
935                parent_size,
936                available_space: available_space.map_width(|_| AvailableSpace::Definite(stretch_width)),
937                vertical_margins_are_collapsible: if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
938            };
939
940            #[cfg(feature = "float_layout")]
941            let clear_pos = block_ctx.cleared_threshold(item.clear).unwrap_or(0.0);
942            #[cfg(not(feature = "float_layout"))]
943            let clear_pos = 0.0;
944
945            let item_layout = if item.is_in_same_bfc {
946                let width = known_dimensions
947                    .width
948                    .expect("Same-bfc child will always have defined width due to stretch sizing");
949
950                // TODO: account for auto margins
951                let inset_left = item_non_auto_margin.left + content_box_inset.left;
952                let inset_right = container_outer_width - width - inset_left;
953                let insets = [inset_left, inset_right];
954
955                // Compute child layout
956                let mut child_block_ctx =
957                    block_ctx.sub_context((y_offset_for_absolute + item_non_auto_margin.top).max(clear_pos), insets);
958                let output = tree.compute_block_child_layout(item.node_id, inputs, Some(&mut child_block_ctx));
959
960                // Extract float contribution from child block context
961                #[cfg(feature = "float_layout")]
962                {
963                    let child_contribution = child_block_ctx.floated_content_height_contribution();
964                    block_ctx.add_child_floated_content_height_contribution(y_offset_for_absolute + child_contribution);
965                }
966
967                output
968            } else {
969                tree.compute_child_layout(item.node_id, inputs)
970            };
971            let final_size = item_layout.size;
972
973            let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
974            let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
975
976            // Expand auto margins to fill available space
977            // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
978            // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
979            let free_x_space = f32_max(0.0, stretch_width - final_size.width);
980            let x_axis_auto_margin_size = {
981                let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
982                if auto_margin_count > 0 {
983                    free_x_space / auto_margin_count as f32
984                } else {
985                    0.0
986                }
987            };
988            let resolved_margin = Rect {
989                left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
990                right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
991                top: top_margin_set.resolve(),
992                bottom: bottom_margin_set.resolve(),
993            };
994
995            // Resolve item inset
996            let inset = item.inset.zip_size(Size { width: container_inner_width, height: 0.0 }, |p, s| {
997                p.maybe_resolve(s, |val, basis| tree.calc(val, basis))
998            });
999            let inset_offset = Point {
1000                x: if direction.is_rtl() {
1001                    inset.right.map(|x| -x).or(inset.left).unwrap_or(0.0)
1002                } else {
1003                    inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0)
1004                },
1005                y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
1006            };
1007
1008            // Set y_margin_offset (same bfc child)
1009            if item.is_in_same_bfc
1010                && (!is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start)
1011            {
1012                y_margin_offset = active_collapsible_margin_set.collapse_with_margin(resolved_margin.top).resolve()
1013            };
1014
1015            #[cfg(feature = "float_layout")]
1016            let float_or_not_clear = item.float.is_floated() || item.clear == Clear::None;
1017            #[cfg(not(feature = "float_layout"))]
1018            let float_or_not_clear = true;
1019
1020            item.computed_size = item_layout.size;
1021            item.can_be_collapsed_through = item_layout.margins_can_collapse_through && float_or_not_clear;
1022            item.static_position = if item.is_in_same_bfc {
1023                let uncleared_y = committed_y_offset + active_collapsible_margin_set.resolve();
1024                Point {
1025                    x: match direction {
1026                        Direction::Ltr => resolved_content_box_inset.left,
1027                        Direction::Rtl => container_outer_width - resolved_content_box_inset.right - final_size.width,
1028                    },
1029                    y: uncleared_y.max(clear_pos),
1030                }
1031            } else {
1032                // TODO: handle inset and margins
1033                Point {
1034                    x: match direction {
1035                        Direction::Ltr => float_avoiding_position.x,
1036                        Direction::Rtl => float_avoiding_position.x + float_avoiding_width - final_size.width,
1037                    },
1038                    y: float_avoiding_position.y,
1039                }
1040            };
1041            let mut location = if item.is_in_same_bfc {
1042                Point {
1043                    x: match direction {
1044                        Direction::Ltr => resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
1045                        Direction::Rtl => {
1046                            container_outer_width
1047                                - resolved_content_box_inset.right
1048                                - final_size.width
1049                                - resolved_margin.right
1050                                + inset_offset.x
1051                        }
1052                    },
1053                    y: committed_y_offset.max(clear_pos) + y_margin_offset + inset_offset.y,
1054                }
1055            } else {
1056                // TODO: handle inset and margins
1057                Point {
1058                    x: match direction {
1059                        Direction::Ltr => float_avoiding_position.x + resolved_margin.left + inset_offset.x,
1060                        Direction::Rtl => {
1061                            float_avoiding_position.x + float_avoiding_width - final_size.width - resolved_margin.right
1062                                + inset_offset.x
1063                        }
1064                    },
1065                    y: float_avoiding_position.y + inset_offset.y,
1066                }
1067            };
1068
1069            // Apply alignment
1070            let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
1071            if item_outer_width < container_inner_width {
1072                let free_x_space = container_inner_width - item_outer_width;
1073                match (text_align, direction) {
1074                    (TextAlign::Auto, _) => {
1075                        // Do nothing
1076                    }
1077                    (TextAlign::LegacyLeft, Direction::Ltr) => {
1078                        // Do nothing. Left aligned by default.
1079                    }
1080                    (TextAlign::LegacyLeft, Direction::Rtl) => location.x -= free_x_space,
1081                    (TextAlign::LegacyRight, Direction::Ltr) => location.x += free_x_space,
1082                    (TextAlign::LegacyRight, Direction::Rtl) => {
1083                        // Do nothing. Right aligned by default.
1084                    }
1085                    (TextAlign::LegacyCenter, Direction::Ltr) => location.x += free_x_space / 2.0,
1086                    (TextAlign::LegacyCenter, Direction::Rtl) => location.x -= free_x_space / 2.0,
1087                }
1088            }
1089
1090            // Defer `set_unrounded_layout` to the post-loop pass in `compute_inner` so that
1091            // `align-content` can shift `location.y` before the layout is committed to the tree.
1092            item.final_layout = Some(Layout {
1093                order: item.order,
1094                size: item_layout.size,
1095                #[cfg(feature = "content_size")]
1096                content_size: item_layout.content_size,
1097                scrollbar_size,
1098                location,
1099                padding: item.padding,
1100                border: item.border,
1101                margin: resolved_margin,
1102            });
1103
1104            #[cfg(feature = "content_size")]
1105            {
1106                inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
1107                    location + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
1108                    final_size,
1109                    item_layout.content_size,
1110                    item.overflow,
1111                ));
1112            }
1113
1114            // Update first_child_top_margin_set
1115            if is_collapsing_with_first_margin_set {
1116                if item.can_be_collapsed_through {
1117                    first_child_top_margin_set = first_child_top_margin_set
1118                        .collapse_with_set(top_margin_set)
1119                        .collapse_with_set(bottom_margin_set);
1120                } else {
1121                    first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
1122                    is_collapsing_with_first_margin_set = false;
1123                }
1124            }
1125
1126            // Update active_collapsible_margin_set
1127            if item.can_be_collapsed_through {
1128                active_collapsible_margin_set = active_collapsible_margin_set
1129                    .collapse_with_set(top_margin_set)
1130                    .collapse_with_set(bottom_margin_set);
1131                y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
1132                #[cfg(feature = "float_layout")]
1133                {
1134                    y_offset_for_float = committed_y_offset + item_layout.size.height + y_margin_offset;
1135                }
1136            } else {
1137                committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
1138                active_collapsible_margin_set = bottom_margin_set;
1139                y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
1140                #[cfg(feature = "float_layout")]
1141                {
1142                    y_offset_for_float = committed_y_offset;
1143                }
1144            }
1145        }
1146    }
1147
1148    let last_child_bottom_margin_set = active_collapsible_margin_set;
1149    let bottom_y_margin_offset =
1150        if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
1151
1152    committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
1153    let content_height = f32_max(0.0, committed_y_offset);
1154    (inflow_content_size, content_height, first_child_top_margin_set, last_child_bottom_margin_set)
1155}
1156
1157/// Perform absolute layout on all absolutely positioned children.
1158#[inline]
1159fn perform_absolute_layout_on_absolute_children(
1160    tree: &mut impl LayoutBlockContainer,
1161    items: &[BlockItem],
1162    area_size: Size<f32>,
1163    area_offset: Point<f32>,
1164    direction: Direction,
1165) -> Size<f32> {
1166    let area_width = area_size.width;
1167    let area_height = area_size.height;
1168
1169    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
1170    let mut absolute_content_size = Size::ZERO;
1171
1172    for item in items.iter().filter(|item| item.position == Position::Absolute) {
1173        let child_style = tree.get_block_child_style(item.node_id);
1174
1175        // Skip items that are display:none or are not position:absolute
1176        if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
1177        {
1178            continue;
1179        }
1180
1181        let aspect_ratio = child_style.aspect_ratio();
1182        let margin =
1183            child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
1184        let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1185        let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1186        let padding_border_sum = (padding + border).sum_axes();
1187        let box_sizing_adjustment =
1188            if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
1189
1190        // Resolve inset
1191        let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1192        let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1193        let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1194        let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1195
1196        // Compute known dimensions from min/max/inherent size styles
1197        let style_size = child_style
1198            .size()
1199            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1200            .maybe_apply_aspect_ratio(aspect_ratio)
1201            .maybe_add(box_sizing_adjustment);
1202        let min_size = child_style
1203            .min_size()
1204            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1205            .maybe_apply_aspect_ratio(aspect_ratio)
1206            .maybe_add(box_sizing_adjustment)
1207            .or(padding_border_sum.map(Some))
1208            .maybe_max(padding_border_sum);
1209        let max_size = child_style
1210            .max_size()
1211            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1212            .maybe_apply_aspect_ratio(aspect_ratio)
1213            .maybe_add(box_sizing_adjustment);
1214        let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
1215
1216        drop(child_style);
1217
1218        // Fill in width from left/right and reapply aspect ratio if:
1219        //   - Width is not already known
1220        //   - Item has both left and right inset properties set
1221        if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
1222            let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
1223            known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
1224            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1225        }
1226
1227        // Fill in height from top/bottom and reapply aspect ratio if:
1228        //   - Height is not already known
1229        //   - Item has both top and bottom inset properties set
1230        if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
1231            let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
1232            known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
1233            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1234        }
1235
1236        let measured_size = tree.measure_child_size_both(
1237            item.node_id,
1238            known_dimensions,
1239            area_size.map(Some),
1240            Size {
1241                width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1242                height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1243            },
1244            SizingMode::ContentSize,
1245            Line::FALSE,
1246        );
1247
1248        let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
1249
1250        let layout_output = tree.perform_child_layout(
1251            item.node_id,
1252            final_size.map(Some),
1253            area_size.map(Some),
1254            Size {
1255                width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1256                height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1257            },
1258            SizingMode::ContentSize,
1259            Line::FALSE,
1260        );
1261
1262        let non_auto_margin = Rect {
1263            left: if left.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
1264            right: if right.is_some() { margin.right.unwrap_or(0.0) } else { 0.0 },
1265            top: if top.is_some() { margin.top.unwrap_or(0.0) } else { 0.0 },
1266            bottom: if bottom.is_some() { margin.bottom.unwrap_or(0.0) } else { 0.0 },
1267        };
1268
1269        // Expand auto margins to fill available space
1270        // https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
1271        let auto_margin = {
1272            // Auto margins for absolutely positioned elements in block containers only resolve
1273            // if inset is set. Otherwise they resolve to 0.
1274            let absolute_auto_margin_space = Point {
1275                x: right.map(|right| area_size.width - right - left.unwrap_or(0.0)).unwrap_or(final_size.width),
1276                y: bottom.map(|bottom| area_size.height - bottom - top.unwrap_or(0.0)).unwrap_or(final_size.height),
1277            };
1278            let free_space = Size {
1279                width: absolute_auto_margin_space.x - final_size.width - non_auto_margin.horizontal_axis_sum(),
1280                height: absolute_auto_margin_space.y - final_size.height - non_auto_margin.vertical_axis_sum(),
1281            };
1282
1283            let auto_margin_size = Size {
1284                // If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0.
1285                // Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the
1286                // static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
1287                //
1288                // If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint
1289                // that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is
1290                // 'ltr' ('rtl'), set 'margin-left' ('margin-right') to zero and solve for 'margin-right' ('margin-left'). If one of 'margin-left' or
1291                // 'margin-right' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'left' (in case
1292                // the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.
1293                width: {
1294                    let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
1295                    if auto_margin_count == 2
1296                        && (style_size.width.is_none() || style_size.width.unwrap() >= free_space.width)
1297                    {
1298                        0.0
1299                    } else if auto_margin_count > 0 {
1300                        free_space.width / auto_margin_count as f32
1301                    } else {
1302                        0.0
1303                    }
1304                },
1305                height: {
1306                    let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
1307                    if auto_margin_count == 2
1308                        && (style_size.height.is_none() || style_size.height.unwrap() >= free_space.height)
1309                    {
1310                        0.0
1311                    } else if auto_margin_count > 0 {
1312                        free_space.height / auto_margin_count as f32
1313                    } else {
1314                        0.0
1315                    }
1316                },
1317            };
1318
1319            Rect {
1320                left: margin.left.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1321                right: margin.right.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1322                top: margin.top.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1323                bottom: margin.bottom.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1324            }
1325        };
1326
1327        let resolved_margin = Rect {
1328            left: margin.left.unwrap_or(auto_margin.left),
1329            right: margin.right.unwrap_or(auto_margin.right),
1330            top: margin.top.unwrap_or(auto_margin.top),
1331            bottom: margin.bottom.unwrap_or(auto_margin.bottom),
1332        };
1333
1334        let x_offset = match (left, right) {
1335            (Some(left), Some(right)) => {
1336                if direction.is_rtl() {
1337                    area_size.width - final_size.width - right - resolved_margin.right
1338                } else {
1339                    left + resolved_margin.left
1340                }
1341            }
1342            (Some(left), None) => left + resolved_margin.left,
1343            (None, Some(right)) => area_size.width - final_size.width - right - resolved_margin.right,
1344            (None, None) => {
1345                if direction.is_rtl() {
1346                    item.static_position.x - final_size.width - resolved_margin.right - area_offset.x
1347                } else {
1348                    item.static_position.x + resolved_margin.left - area_offset.x
1349                }
1350            }
1351        };
1352        let location = Point {
1353            x: x_offset + area_offset.x,
1354            y: top
1355                .map(|top| top + resolved_margin.top)
1356                .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
1357                .maybe_add(area_offset.y)
1358                .unwrap_or(item.static_position.y + resolved_margin.top),
1359        };
1360        // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
1361        // to the axis in which scrolling is enabled.
1362        let scrollbar_size = Size {
1363            width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1364            height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1365        };
1366
1367        tree.set_unrounded_layout(
1368            item.node_id,
1369            &Layout {
1370                order: item.order,
1371                size: final_size,
1372                #[cfg(feature = "content_size")]
1373                content_size: layout_output.content_size,
1374                scrollbar_size,
1375                location,
1376                padding,
1377                border,
1378                margin: resolved_margin,
1379            },
1380        );
1381
1382        #[cfg(feature = "content_size")]
1383        {
1384            let relative_location = Point { x: location.x - area_offset.x, y: location.y - area_offset.y };
1385            absolute_content_size = absolute_content_size.f32_max(compute_content_size_contribution(
1386                relative_location,
1387                final_size,
1388                layout_output.content_size,
1389                item.overflow,
1390            ));
1391        }
1392    }
1393
1394    absolute_content_size
1395}