gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 499HTML 245JavaScript 8Markdown 71218 Definiciones

⎇ 96169be1c1eb3352910b1ae87a2184e23bec5fa1 src/compute/block.rs Rust · 1397 líneas · 62.0 KB Historia Quién tocó qué crudo

Pass through run mode rather when performing final layout on block children (#972) 96169be1c · 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            run_mode,
474            &mut items,
475            container_outer_width,
476            container_percentage_resolution_height,
477            content_box_inset,
478            resolved_content_box_inset,
479            text_align,
480            direction,
481            own_margins_collapse_with_children,
482            block_ctx,
483        );
484
485    // Root BFCs contain floats
486    #[cfg(feature = "float_layout")]
487    if block_ctx.is_bfc_root() || is_scroll_container {
488        intrinsic_outer_height = intrinsic_outer_height.max(block_ctx.floated_content_height_contribution());
489    }
490
491    let container_outer_height = known_dimensions
492        .height
493        .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
494        .maybe_max(Some(padding_border_size.height));
495    let final_outer_size = Size { width: container_outer_width, height: container_outer_height };
496
497    // Apply `align-content` to in-flow non-floated items if requested. The per-item layouts were
498    // held back in `item.final_layout` so that this step can shift `location.y` before tree commit.
499    //
500    // For block layout the entire stack of in-flow children is treated as a single alignment
501    // subject. That means distribution keywords (`space-between`, `space-around`,
502    // `space-evenly`, `stretch`) must invoke the single-subject fallback unconditionally —
503    // which is what passing `num_items = 1` to `apply_alignment_fallback` does. The whole
504    // group then shifts by one offset, with zero inter-item gap.
505    if let Some(align_content) = align_content {
506        let container_inner_height = container_outer_height - resolved_content_box_inset.vertical_axis_sum();
507        let inflow_content_height = intrinsic_outer_height - resolved_content_box_inset.vertical_axis_sum();
508        let free_space = container_inner_height - inflow_content_height;
509        let any_in_flow = items.iter().any(|item| item.final_layout.is_some());
510        if any_in_flow {
511            let keyword = apply_alignment_fallback(free_space, 1, align_content);
512            let group_offset = compute_alignment_offset(free_space, 1, 0.0, keyword, false, true);
513            for item in items.iter_mut() {
514                if let Some(layout) = item.final_layout.as_mut() {
515                    layout.location.y += group_offset;
516                }
517            }
518
519            #[cfg(feature = "content_size")]
520            {
521                inflow_content_size = Size::ZERO;
522                for item in items.iter() {
523                    if let Some(layout) = item.final_layout.as_ref() {
524                        inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
525                            layout.location
526                                + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
527                            layout.size,
528                            layout.content_size,
529                            item.overflow,
530                        ));
531                    }
532                }
533            }
534        }
535    }
536
537    // Short-circuit if computing size
538    if run_mode == RunMode::ComputeSize {
539        return LayoutOutput::from_outer_size(final_outer_size);
540    }
541
542    // Commit deferred in-flow layouts to the tree. Floated items already wrote their own layouts.
543    for item in items.iter() {
544        if let Some(layout) = item.final_layout.as_ref() {
545            tree.set_unrounded_layout(item.node_id, layout);
546        }
547    }
548
549    // 4. Layout absolutely positioned children
550    let absolute_position_inset = resolved_border + scrollbar_gutter;
551    let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
552    let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
553    let absolute_content_size = perform_absolute_layout_on_absolute_children(
554        tree,
555        &items,
556        absolute_position_area,
557        absolute_position_offset,
558        direction,
559    );
560
561    // 5. Perform hidden layout on hidden children
562    let len = tree.child_count(node_id);
563    for order in 0..len {
564        let child = tree.get_child_id(node_id, order);
565        let child_style = tree.get_block_child_style(child);
566        if child_style.box_generation_mode() == BoxGenerationMode::None {
567            drop(child_style);
568            tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
569            tree.perform_child_layout(
570                child,
571                Size::NONE,
572                Size::NONE,
573                Size::MAX_CONTENT,
574                SizingMode::InherentSize,
575                Line::FALSE,
576            );
577        }
578    }
579
580    // 7. Determine whether this node can be collapsed through
581    let all_in_flow_children_can_be_collapsed_through =
582        items.iter().all(|item| item.position == Position::Absolute || item.can_be_collapsed_through);
583    let can_be_collapsed_through =
584        !has_styles_preventing_being_collapsed_through && all_in_flow_children_can_be_collapsed_through;
585
586    #[cfg_attr(not(feature = "content_size"), allow(unused_variables))]
587    let content_size = inflow_content_size.f32_max(absolute_content_size);
588
589    LayoutOutput {
590        size: final_outer_size,
591        #[cfg(feature = "content_size")]
592        content_size,
593        first_baselines: Point::NONE,
594        top_margin: if own_margins_collapse_with_children.start {
595            first_child_top_margin_set
596        } else {
597            let margin_top = raw_margin.top.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
598            CollapsibleMarginSet::from_margin(margin_top)
599        },
600        bottom_margin: if own_margins_collapse_with_children.end {
601            last_child_bottom_margin_set
602        } else {
603            let margin_bottom =
604                raw_margin.bottom.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
605            CollapsibleMarginSet::from_margin(margin_bottom)
606        },
607        margins_can_collapse_through: can_be_collapsed_through,
608    }
609}
610
611/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
612#[inline]
613fn generate_item_list(
614    tree: &impl LayoutBlockContainer,
615    node: NodeId,
616    node_inner_size: Size<Option<f32>>,
617) -> Vec<BlockItem> {
618    tree.child_ids(node)
619        .map(|child_node_id| (child_node_id, tree.get_block_child_style(child_node_id)))
620        .filter(|(_, style)| style.box_generation_mode() != BoxGenerationMode::None)
621        .enumerate()
622        .map(|(order, (child_node_id, child_style))| {
623            let aspect_ratio = child_style.aspect_ratio();
624            let padding = child_style.padding().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
625            let border = child_style.border().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
626            let pb_sum = (padding + border).sum_axes();
627            let box_sizing_adjustment =
628                if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
629
630            let position = child_style.position();
631            let overflow = child_style.overflow();
632
633            #[cfg(feature = "float_layout")]
634            let float = child_style.float();
635            #[cfg(feature = "float_layout")]
636            let is_not_floated = float == Float::None;
637
638            #[cfg(not(feature = "float_layout"))]
639            let is_not_floated = true;
640
641            let is_block = child_style.is_block();
642            let is_table = child_style.is_table();
643            let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
644
645            let is_in_same_bfc: bool =
646                is_block && !is_table && position != Position::Absolute && is_not_floated && !is_scroll_container;
647
648            BlockItem {
649                node_id: child_node_id,
650                order: order as u32,
651                is_table,
652                is_in_same_bfc,
653                #[cfg(feature = "float_layout")]
654                float,
655                #[cfg(feature = "float_layout")]
656                clear: child_style.clear(),
657                size: child_style
658                    .size()
659                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
660                    .maybe_apply_aspect_ratio(aspect_ratio)
661                    .maybe_add(box_sizing_adjustment),
662                min_size: child_style
663                    .min_size()
664                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
665                    .maybe_apply_aspect_ratio(aspect_ratio)
666                    .maybe_add(box_sizing_adjustment),
667                max_size: child_style
668                    .max_size()
669                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
670                    .maybe_apply_aspect_ratio(aspect_ratio)
671                    .maybe_add(box_sizing_adjustment),
672                overflow,
673                scrollbar_width: child_style.scrollbar_width(),
674                position,
675                inset: child_style.inset(),
676                margin: child_style.margin(),
677                padding,
678                border,
679                padding_border_sum: pb_sum,
680
681                // Fields to be computed later (for now we initialise with dummy values)
682                computed_size: Size::zero(),
683                static_position: Point::zero(),
684                can_be_collapsed_through: false,
685                final_layout: None,
686            }
687        })
688        .collect()
689}
690
691/// Compute the content-based width in the case that the width of the container is not known
692#[inline]
693fn determine_content_based_container_width(
694    tree: &mut impl LayoutPartialTree,
695    items: &[BlockItem],
696    available_width: AvailableSpace,
697) -> f32 {
698    let available_space = Size { width: available_width, height: AvailableSpace::MinContent };
699
700    let mut max_child_width = 0.0;
701    #[cfg(feature = "float_layout")]
702    let mut float_contribution = FloatIntrinsicWidthCalculator::new(available_width);
703    for item in items.iter().filter(|item| item.position != Position::Absolute) {
704        let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);
705
706        let item_x_margin_sum = item
707            .margin
708            .resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis))
709            .horizontal_axis_sum();
710        let width = known_dimensions.width.unwrap_or_else(|| {
711            tree.measure_child_size(
712                item.node_id,
713                known_dimensions,
714                Size::NONE,
715                available_space.map_width(|w| w.maybe_sub(item_x_margin_sum)),
716                SizingMode::InherentSize,
717                crate::AbsoluteAxis::Horizontal,
718                Line::TRUE,
719            )
720        });
721
722        let width = f32_max(width, item.padding_border_sum.width) + item_x_margin_sum;
723
724        #[cfg(feature = "float_layout")]
725        if let Some(direction) = item.float.float_direction() {
726            float_contribution.add_float(width, direction, item.clear);
727            continue;
728        }
729
730        max_child_width = f32_max(max_child_width, width);
731    }
732
733    #[cfg(feature = "float_layout")]
734    {
735        max_child_width = max_child_width.max(float_contribution.result());
736    }
737
738    max_child_width
739}
740
741/// Compute each child's final size and position
742#[inline]
743#[allow(clippy::too_many_arguments)]
744fn perform_final_layout_on_in_flow_children(
745    tree: &mut impl LayoutBlockContainer,
746    run_mode: RunMode,
747    items: &mut [BlockItem],
748    container_outer_width: f32,
749    container_percentage_resolution_height: Option<f32>,
750    content_box_inset: Rect<f32>,
751    resolved_content_box_inset: Rect<f32>,
752    text_align: TextAlign,
753    direction: Direction,
754    own_margins_collapse_with_children: Line<bool>,
755    block_ctx: &mut BlockContext<'_>,
756) -> (Size<f32>, f32, CollapsibleMarginSet, CollapsibleMarginSet) {
757    // Resolve container_inner_width for sizing child nodes using initial content_box_inset
758    let container_inner_width = container_outer_width - resolved_content_box_inset.horizontal_axis_sum();
759    let container_percentage_resolution_height =
760        container_percentage_resolution_height.maybe_sub(resolved_content_box_inset.vertical_axis_sum());
761    let parent_size = Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
762    // Vertical available space in block flow is indefinite, NOT a min-content
763    // constraint: MaxContent is taffy's representation of "indefinite".
764    // Passing MinContent here made every descendant grid believe it was being
765    // sized under a min-content constraint, in which the maximize-tracks step
766    // has zero free space — so auto rows containing only scroll-container
767    // items (overflow != visible, automatic minimum size = 0) collapsed to
768    // zero height. Browsers size such rows to the item's content.
769    let available_space =
770        Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MaxContent };
771
772    // TODO: handle nested blocks with different widths
773    #[cfg(feature = "float_layout")]
774    if block_ctx.is_bfc_root() {
775        block_ctx.set_width(container_outer_width);
776        block_ctx.apply_content_box_inset([resolved_content_box_inset.left, resolved_content_box_inset.right]);
777    }
778
779    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
780    let mut inflow_content_size = Size::ZERO;
781    let mut committed_y_offset = resolved_content_box_inset.top;
782    let mut y_offset_for_absolute = resolved_content_box_inset.top;
783    let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
784    let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
785    let mut is_collapsing_with_first_margin_set = true;
786
787    #[cfg(feature = "float_layout")]
788    let mut has_active_floats = block_ctx.has_active_floats(committed_y_offset);
789    #[cfg(not(feature = "float_layout"))]
790    let has_active_floats = false;
791    #[cfg(feature = "float_layout")]
792    let mut y_offset_for_float = resolved_content_box_inset.top;
793
794    for item in items.iter_mut() {
795        if item.position == Position::Absolute {
796            let x = match direction {
797                Direction::Ltr => resolved_content_box_inset.left,
798                Direction::Rtl => container_outer_width - resolved_content_box_inset.right,
799            };
800            item.static_position = Point { x, y: y_offset_for_absolute }
801        } else {
802            let item_margin = item
803                .margin
804                .map(|margin| margin.resolve_to_option(container_outer_width, |val, basis| tree.calc(val, basis)));
805            let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
806            let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();
807
808            let scrollbar_size = Size {
809                width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
810                height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
811            };
812
813            // Handle floated boxes
814            #[cfg(feature = "float_layout")]
815            if let Some(float_direction) = item.float.float_direction() {
816                has_active_floats = true;
817
818                let item_layout = tree.perform_child_layout(
819                    item.node_id,
820                    Size::NONE,
821                    parent_size,
822                    // available_space,
823                    Size::MAX_CONTENT,
824                    SizingMode::InherentSize,
825                    Line::TRUE,
826                );
827                let margin_box = item_layout.size + item_non_auto_margin.sum_axes();
828
829                let mut location =
830                    block_ctx.place_floated_box(margin_box, y_offset_for_float, float_direction, item.clear);
831
832                // Ensure that content that appears after a float does not get positioned before/above the float
833                //
834                // FIXME: this isn't quite right, because a second float at the same location
835                // shouldn't cause content to push down to it's level
836                // committed_y_offset = committed_y_offset.max(location.y);
837                // y_offset_for_absolute = y_offset_for_absolute.max(location.y);
838                // y_offset_for_float = y_offset_for_float.max(location.y);
839
840                // Convert the margin-box location returned by float placement into a border-box location
841                // for the output Layout
842                location.y += item_non_auto_margin.top;
843                location.x += item_non_auto_margin.left;
844
845                // println!("BLOCK FLOATED BOX ({:?}) {:?}", item.node_id, float_direction);
846                // println!("w:{} h:{} x:{}, y:{}", margin_box.width, margin_box.height, location.x, location.y);
847
848                tree.set_unrounded_layout(
849                    item.node_id,
850                    &Layout {
851                        order: item.order,
852                        size: item_layout.size,
853                        #[cfg(feature = "content_size")]
854                        content_size: item_layout.content_size,
855                        scrollbar_size,
856                        location,
857                        padding: item.padding,
858                        border: item.border,
859                        margin: item_non_auto_margin,
860                    },
861                );
862
863                #[cfg(feature = "content_size")]
864                {
865                    // TODO: Should content size of floated boxes count as "inflow_content_size"
866                    // or should it be counted separately?
867                    inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
868                        location,
869                        item_layout.size,
870                        item_layout.content_size,
871                        item.overflow,
872                    ));
873                }
874
875                continue;
876            }
877
878            // Handle non-floated boxes
879
880            let mut y_margin_offset: f32 = 0.0;
881
882            let (stretch_width, float_avoiding_position, float_avoiding_width) = if item.is_in_same_bfc {
883                let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
884                let position = Point { x: 0.0, y: 0.0 };
885                let width = 0.0;
886
887                (stretch_width, position, width)
888            } else {
889                'block: {
890                    // Set y_margin_offset (different bfc child)
891                    if !is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start {
892                        y_margin_offset =
893                            active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
894                    };
895                    let min_y = committed_y_offset + y_margin_offset;
896
897                    #[cfg(feature = "float_layout")]
898                    if has_active_floats {
899                        let slot = block_ctx.find_content_slot(min_y, item.clear, None);
900                        has_active_floats = slot.segment_id.is_some();
901                        let stretch_width = slot.width - item_non_auto_x_margin_sum;
902                        break 'block (stretch_width, Point { x: slot.x, y: slot.y }, slot.width);
903                    }
904
905                    if !has_active_floats {
906                        let stretch_width = container_inner_width - item_non_auto_x_margin_sum;
907                        break 'block (
908                            stretch_width,
909                            Point { x: resolved_content_box_inset.left, y: min_y },
910                            container_inner_width,
911                        );
912                    }
913
914                    unreachable!("One of the above cases will always be hit");
915                }
916            };
917
918            let known_dimensions = if item.is_table {
919                Size::NONE
920            } else {
921                item.size
922                    .map_width(|width| {
923                        // TODO: Allow stretch-sizing to be conditional, as there are exceptions.
924                        // e.g. Table children of blocks do not stretch fit
925                        Some(width.unwrap_or(stretch_width).maybe_clamp(item.min_size.width, item.max_size.width))
926                    })
927                    .maybe_clamp(item.min_size, item.max_size)
928            };
929
930            //
931
932            let inputs = LayoutInput {
933                run_mode,
934                sizing_mode: SizingMode::InherentSize,
935                axis: RequestedAxis::Both,
936                known_dimensions,
937                parent_size,
938                available_space: available_space.map_width(|_| AvailableSpace::Definite(stretch_width)),
939                vertical_margins_are_collapsible: if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
940            };
941
942            #[cfg(feature = "float_layout")]
943            let clear_pos = block_ctx.cleared_threshold(item.clear).unwrap_or(0.0);
944            #[cfg(not(feature = "float_layout"))]
945            let clear_pos = 0.0;
946
947            let item_layout = if item.is_in_same_bfc {
948                let width = known_dimensions
949                    .width
950                    .expect("Same-bfc child will always have defined width due to stretch sizing");
951
952                // TODO: account for auto margins
953                let inset_left = item_non_auto_margin.left + content_box_inset.left;
954                let inset_right = container_outer_width - width - inset_left;
955                let insets = [inset_left, inset_right];
956
957                // Compute child layout
958                let mut child_block_ctx =
959                    block_ctx.sub_context((y_offset_for_absolute + item_non_auto_margin.top).max(clear_pos), insets);
960                let output = tree.compute_block_child_layout(item.node_id, inputs, Some(&mut child_block_ctx));
961
962                // Extract float contribution from child block context
963                #[cfg(feature = "float_layout")]
964                {
965                    let child_contribution = child_block_ctx.floated_content_height_contribution();
966                    block_ctx.add_child_floated_content_height_contribution(y_offset_for_absolute + child_contribution);
967                }
968
969                output
970            } else {
971                tree.compute_child_layout(item.node_id, inputs)
972            };
973            let final_size = item_layout.size;
974
975            let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
976            let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
977
978            // Expand auto margins to fill available space
979            // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
980            // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
981            let free_x_space = f32_max(0.0, stretch_width - final_size.width);
982            let x_axis_auto_margin_size = {
983                let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
984                if auto_margin_count > 0 {
985                    free_x_space / auto_margin_count as f32
986                } else {
987                    0.0
988                }
989            };
990            let resolved_margin = Rect {
991                left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
992                right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
993                top: top_margin_set.resolve(),
994                bottom: bottom_margin_set.resolve(),
995            };
996
997            // Resolve item inset
998            let inset = item.inset.zip_size(Size { width: container_inner_width, height: 0.0 }, |p, s| {
999                p.maybe_resolve(s, |val, basis| tree.calc(val, basis))
1000            });
1001            let inset_offset = Point {
1002                x: if direction.is_rtl() {
1003                    inset.right.map(|x| -x).or(inset.left).unwrap_or(0.0)
1004                } else {
1005                    inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0)
1006                },
1007                y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
1008            };
1009
1010            // Set y_margin_offset (same bfc child)
1011            if item.is_in_same_bfc
1012                && (!is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start)
1013            {
1014                y_margin_offset = active_collapsible_margin_set.collapse_with_margin(resolved_margin.top).resolve()
1015            };
1016
1017            #[cfg(feature = "float_layout")]
1018            let float_or_not_clear = item.float.is_floated() || item.clear == Clear::None;
1019            #[cfg(not(feature = "float_layout"))]
1020            let float_or_not_clear = true;
1021
1022            item.computed_size = item_layout.size;
1023            item.can_be_collapsed_through = item_layout.margins_can_collapse_through && float_or_not_clear;
1024            item.static_position = if item.is_in_same_bfc {
1025                let uncleared_y = committed_y_offset + active_collapsible_margin_set.resolve();
1026                Point {
1027                    x: match direction {
1028                        Direction::Ltr => resolved_content_box_inset.left,
1029                        Direction::Rtl => container_outer_width - resolved_content_box_inset.right - final_size.width,
1030                    },
1031                    y: uncleared_y.max(clear_pos),
1032                }
1033            } else {
1034                // TODO: handle inset and margins
1035                Point {
1036                    x: match direction {
1037                        Direction::Ltr => float_avoiding_position.x,
1038                        Direction::Rtl => float_avoiding_position.x + float_avoiding_width - final_size.width,
1039                    },
1040                    y: float_avoiding_position.y,
1041                }
1042            };
1043            let mut location = if item.is_in_same_bfc {
1044                Point {
1045                    x: match direction {
1046                        Direction::Ltr => resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
1047                        Direction::Rtl => {
1048                            container_outer_width
1049                                - resolved_content_box_inset.right
1050                                - final_size.width
1051                                - resolved_margin.right
1052                                + inset_offset.x
1053                        }
1054                    },
1055                    y: committed_y_offset.max(clear_pos) + y_margin_offset + inset_offset.y,
1056                }
1057            } else {
1058                // TODO: handle inset and margins
1059                Point {
1060                    x: match direction {
1061                        Direction::Ltr => float_avoiding_position.x + resolved_margin.left + inset_offset.x,
1062                        Direction::Rtl => {
1063                            float_avoiding_position.x + float_avoiding_width - final_size.width - resolved_margin.right
1064                                + inset_offset.x
1065                        }
1066                    },
1067                    y: float_avoiding_position.y + inset_offset.y,
1068                }
1069            };
1070
1071            // Apply alignment
1072            let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
1073            if item_outer_width < container_inner_width {
1074                let free_x_space = container_inner_width - item_outer_width;
1075                match (text_align, direction) {
1076                    (TextAlign::Auto, _) => {
1077                        // Do nothing
1078                    }
1079                    (TextAlign::LegacyLeft, Direction::Ltr) => {
1080                        // Do nothing. Left aligned by default.
1081                    }
1082                    (TextAlign::LegacyLeft, Direction::Rtl) => location.x -= free_x_space,
1083                    (TextAlign::LegacyRight, Direction::Ltr) => location.x += free_x_space,
1084                    (TextAlign::LegacyRight, Direction::Rtl) => {
1085                        // Do nothing. Right aligned by default.
1086                    }
1087                    (TextAlign::LegacyCenter, Direction::Ltr) => location.x += free_x_space / 2.0,
1088                    (TextAlign::LegacyCenter, Direction::Rtl) => location.x -= free_x_space / 2.0,
1089                }
1090            }
1091
1092            // Defer `set_unrounded_layout` to the post-loop pass in `compute_inner` so that
1093            // `align-content` can shift `location.y` before the layout is committed to the tree.
1094            item.final_layout = Some(Layout {
1095                order: item.order,
1096                size: item_layout.size,
1097                #[cfg(feature = "content_size")]
1098                content_size: item_layout.content_size,
1099                scrollbar_size,
1100                location,
1101                padding: item.padding,
1102                border: item.border,
1103                margin: resolved_margin,
1104            });
1105
1106            #[cfg(feature = "content_size")]
1107            {
1108                inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
1109                    location + Point { x: -resolved_content_box_inset.left, y: -resolved_content_box_inset.top },
1110                    final_size,
1111                    item_layout.content_size,
1112                    item.overflow,
1113                ));
1114            }
1115
1116            // Update first_child_top_margin_set
1117            if is_collapsing_with_first_margin_set {
1118                if item.can_be_collapsed_through {
1119                    first_child_top_margin_set = first_child_top_margin_set
1120                        .collapse_with_set(top_margin_set)
1121                        .collapse_with_set(bottom_margin_set);
1122                } else {
1123                    first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
1124                    is_collapsing_with_first_margin_set = false;
1125                }
1126            }
1127
1128            // Update active_collapsible_margin_set
1129            if item.can_be_collapsed_through {
1130                active_collapsible_margin_set = active_collapsible_margin_set
1131                    .collapse_with_set(top_margin_set)
1132                    .collapse_with_set(bottom_margin_set);
1133                y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
1134                #[cfg(feature = "float_layout")]
1135                {
1136                    y_offset_for_float = committed_y_offset + item_layout.size.height + y_margin_offset;
1137                }
1138            } else {
1139                committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
1140                active_collapsible_margin_set = bottom_margin_set;
1141                y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
1142                #[cfg(feature = "float_layout")]
1143                {
1144                    y_offset_for_float = committed_y_offset;
1145                }
1146            }
1147        }
1148    }
1149
1150    let last_child_bottom_margin_set = active_collapsible_margin_set;
1151    let bottom_y_margin_offset =
1152        if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
1153
1154    committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
1155    let content_height = f32_max(0.0, committed_y_offset);
1156    (inflow_content_size, content_height, first_child_top_margin_set, last_child_bottom_margin_set)
1157}
1158
1159/// Perform absolute layout on all absolutely positioned children.
1160#[inline]
1161fn perform_absolute_layout_on_absolute_children(
1162    tree: &mut impl LayoutBlockContainer,
1163    items: &[BlockItem],
1164    area_size: Size<f32>,
1165    area_offset: Point<f32>,
1166    direction: Direction,
1167) -> Size<f32> {
1168    let area_width = area_size.width;
1169    let area_height = area_size.height;
1170
1171    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
1172    let mut absolute_content_size = Size::ZERO;
1173
1174    for item in items.iter().filter(|item| item.position == Position::Absolute) {
1175        let child_style = tree.get_block_child_style(item.node_id);
1176
1177        // Skip items that are display:none or are not position:absolute
1178        if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
1179        {
1180            continue;
1181        }
1182
1183        let aspect_ratio = child_style.aspect_ratio();
1184        let margin =
1185            child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
1186        let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1187        let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
1188        let padding_border_sum = (padding + border).sum_axes();
1189        let box_sizing_adjustment =
1190            if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
1191
1192        // Resolve inset
1193        let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1194        let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
1195        let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1196        let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
1197
1198        // Compute known dimensions from min/max/inherent size styles
1199        let style_size = child_style
1200            .size()
1201            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1202            .maybe_apply_aspect_ratio(aspect_ratio)
1203            .maybe_add(box_sizing_adjustment);
1204        let min_size = child_style
1205            .min_size()
1206            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1207            .maybe_apply_aspect_ratio(aspect_ratio)
1208            .maybe_add(box_sizing_adjustment)
1209            .or(padding_border_sum.map(Some))
1210            .maybe_max(padding_border_sum);
1211        let max_size = child_style
1212            .max_size()
1213            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
1214            .maybe_apply_aspect_ratio(aspect_ratio)
1215            .maybe_add(box_sizing_adjustment);
1216        let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
1217
1218        drop(child_style);
1219
1220        // Fill in width from left/right and reapply aspect ratio if:
1221        //   - Width is not already known
1222        //   - Item has both left and right inset properties set
1223        if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
1224            let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
1225            known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
1226            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1227        }
1228
1229        // Fill in height from top/bottom and reapply aspect ratio if:
1230        //   - Height is not already known
1231        //   - Item has both top and bottom inset properties set
1232        if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
1233            let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
1234            known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
1235            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
1236        }
1237
1238        let measured_size = tree.measure_child_size_both(
1239            item.node_id,
1240            known_dimensions,
1241            area_size.map(Some),
1242            Size {
1243                width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1244                height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1245            },
1246            SizingMode::ContentSize,
1247            Line::FALSE,
1248        );
1249
1250        let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
1251
1252        let layout_output = tree.perform_child_layout(
1253            item.node_id,
1254            final_size.map(Some),
1255            area_size.map(Some),
1256            Size {
1257                width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
1258                height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
1259            },
1260            SizingMode::ContentSize,
1261            Line::FALSE,
1262        );
1263
1264        let non_auto_margin = Rect {
1265            left: if left.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
1266            right: if right.is_some() { margin.right.unwrap_or(0.0) } else { 0.0 },
1267            top: if top.is_some() { margin.top.unwrap_or(0.0) } else { 0.0 },
1268            bottom: if bottom.is_some() { margin.bottom.unwrap_or(0.0) } else { 0.0 },
1269        };
1270
1271        // Expand auto margins to fill available space
1272        // https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
1273        let auto_margin = {
1274            // Auto margins for absolutely positioned elements in block containers only resolve
1275            // if inset is set. Otherwise they resolve to 0.
1276            let absolute_auto_margin_space = Point {
1277                x: right.map(|right| area_size.width - right - left.unwrap_or(0.0)).unwrap_or(final_size.width),
1278                y: bottom.map(|bottom| area_size.height - bottom - top.unwrap_or(0.0)).unwrap_or(final_size.height),
1279            };
1280            let free_space = Size {
1281                width: absolute_auto_margin_space.x - final_size.width - non_auto_margin.horizontal_axis_sum(),
1282                height: absolute_auto_margin_space.y - final_size.height - non_auto_margin.vertical_axis_sum(),
1283            };
1284
1285            let auto_margin_size = Size {
1286                // If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0.
1287                // Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the
1288                // static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
1289                //
1290                // If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint
1291                // that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is
1292                // 'ltr' ('rtl'), set 'margin-left' ('margin-right') to zero and solve for 'margin-right' ('margin-left'). If one of 'margin-left' or
1293                // 'margin-right' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'left' (in case
1294                // the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.
1295                width: {
1296                    let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
1297                    if auto_margin_count == 2
1298                        && (style_size.width.is_none() || style_size.width.unwrap() >= free_space.width)
1299                    {
1300                        0.0
1301                    } else if auto_margin_count > 0 {
1302                        free_space.width / auto_margin_count as f32
1303                    } else {
1304                        0.0
1305                    }
1306                },
1307                height: {
1308                    let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
1309                    if auto_margin_count == 2
1310                        && (style_size.height.is_none() || style_size.height.unwrap() >= free_space.height)
1311                    {
1312                        0.0
1313                    } else if auto_margin_count > 0 {
1314                        free_space.height / auto_margin_count as f32
1315                    } else {
1316                        0.0
1317                    }
1318                },
1319            };
1320
1321            Rect {
1322                left: margin.left.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1323                right: margin.right.map(|_| 0.0).unwrap_or(auto_margin_size.width),
1324                top: margin.top.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1325                bottom: margin.bottom.map(|_| 0.0).unwrap_or(auto_margin_size.height),
1326            }
1327        };
1328
1329        let resolved_margin = Rect {
1330            left: margin.left.unwrap_or(auto_margin.left),
1331            right: margin.right.unwrap_or(auto_margin.right),
1332            top: margin.top.unwrap_or(auto_margin.top),
1333            bottom: margin.bottom.unwrap_or(auto_margin.bottom),
1334        };
1335
1336        let x_offset = match (left, right) {
1337            (Some(left), Some(right)) => {
1338                if direction.is_rtl() {
1339                    area_size.width - final_size.width - right - resolved_margin.right
1340                } else {
1341                    left + resolved_margin.left
1342                }
1343            }
1344            (Some(left), None) => left + resolved_margin.left,
1345            (None, Some(right)) => area_size.width - final_size.width - right - resolved_margin.right,
1346            (None, None) => {
1347                if direction.is_rtl() {
1348                    item.static_position.x - final_size.width - resolved_margin.right - area_offset.x
1349                } else {
1350                    item.static_position.x + resolved_margin.left - area_offset.x
1351                }
1352            }
1353        };
1354        let location = Point {
1355            x: x_offset + area_offset.x,
1356            y: top
1357                .map(|top| top + resolved_margin.top)
1358                .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
1359                .maybe_add(area_offset.y)
1360                .unwrap_or(item.static_position.y + resolved_margin.top),
1361        };
1362        // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
1363        // to the axis in which scrolling is enabled.
1364        let scrollbar_size = Size {
1365            width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1366            height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
1367        };
1368
1369        tree.set_unrounded_layout(
1370            item.node_id,
1371            &Layout {
1372                order: item.order,
1373                size: final_size,
1374                #[cfg(feature = "content_size")]
1375                content_size: layout_output.content_size,
1376                scrollbar_size,
1377                location,
1378                padding,
1379                border,
1380                margin: resolved_margin,
1381            },
1382        );
1383
1384        #[cfg(feature = "content_size")]
1385        {
1386            let relative_location = Point { x: location.x - area_offset.x, y: location.y - area_offset.y };
1387            absolute_content_size = absolute_content_size.f32_max(compute_content_size_contribution(
1388                relative_location,
1389                final_size,
1390                layout_output.content_size,
1391                item.overflow,
1392            ));
1393        }
1394    }
1395
1396    absolute_content_size
1397}