tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 709HTML 662Markdown 12TOML 62348 Sutichaykuna

⎇ direction-floats src/compute/block.rs Rust · 1322 siq'ikuna · 57.3 KB Ñawpa willay Pi imata llamkarqan ch'uya

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