tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 1077HTML 1008Markdown 12TOML 83209 Definitions

⎇ 99a5944d4d7558bd30fdf867611839e77b01b9f2 src/compute/block.rs Rust · 1324 lines · 57.4 KB History Who touched what raw

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