tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 231Rust 10TOML 3CSS 1348 Sutichaykuna

⎇ units src/compute/block.rs Rust · 1311 siq'ikuna · 57.1 KB Ñawpa willay Pi imata llamkarqan ch'uya

Implement `direction` property (#906) 60601a657 · Kane Wang ·

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