tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 985HTML 469Markdown 10TOML 52789 Definitions

⎇ float-layout src/compute/block.rs Rust · 829 lines · 37.6 KB History Who touched what raw

Setup BFC inheritance 3a7cffaca · 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::{BlockContainerStyle, BlockItemStyle, BoxGenerationMode, BoxSizing, LayoutBlockContainer, TextAlign};
13
14#[cfg(feature = "float_layout")]
15use super::{FloatContext, FloatDirection, FloatedBox};
16
17/// Context for positioning Block and Float boxes within a Block Formatting Context
18pub struct BlockFormattingContext {
19    #[cfg(feature = "float_layout")]
20    float_context: super::FloatContext,
21}
22
23impl BlockFormattingContext {
24    /// Create a new `BlockFormattingContext` with the specified width constraint
25    pub fn new(available_space: AvailableSpace) -> Self {
26        Self {
27            #[cfg(feature = "float_layout")]
28            float_context: FloatContext::new(available_space),
29        }
30    }
31
32    #[cfg(feature = "float_layout")]
33    pub fn place_floated_box(&mut self, floated_box: FloatedBox, float_direction: FloatDirection) -> Point<f32> {
34        self.float_context.place_floated_box(floated_box, float_direction)
35    }
36}
37
38#[cfg(feature = "content_size")]
39use super::common::content_size::compute_content_size_contribution;
40
41/// Per-child data that is accumulated and modified over the course of the layout algorithm
42struct BlockItem {
43    /// The identifier for the associated node
44    node_id: NodeId,
45
46    /// The "source order" of the item. This is the index of the item within the children iterator,
47    /// and controls the order in which the nodes are placed
48    order: u32,
49
50    /// Items that are tables don't have stretch sizing applied to them
51    is_table: bool,
52
53    /// The base size of this item
54    size: Size<Option<f32>>,
55    /// The minimum allowable size of this item
56    min_size: Size<Option<f32>>,
57    /// The maximum allowable size of this item
58    max_size: Size<Option<f32>>,
59
60    /// The overflow style of the item
61    overflow: Point<Overflow>,
62    /// The width of the item's scrollbars (if it has scrollbars)
63    scrollbar_width: f32,
64
65    /// The position style of the item
66    position: Position,
67    /// The final offset of this item
68    inset: Rect<LengthPercentageAuto>,
69    /// The margin of this item
70    margin: Rect<LengthPercentageAuto>,
71    /// The margin of this item
72    padding: Rect<f32>,
73    /// The margin of this item
74    border: Rect<f32>,
75    /// The sum of padding and border for this item
76    padding_border_sum: Size<f32>,
77
78    /// The computed border box size of this item
79    computed_size: Size<f32>,
80    /// The computed "static position" of this item. The static position is the position
81    /// taking into account padding, border, margins, and scrollbar_gutters but not inset
82    static_position: Point<f32>,
83    /// Whether margins can be collapsed through this item
84    can_be_collapsed_through: bool,
85}
86
87/// Computes the layout of [`LayoutPartialTree`] according to the block layout algorithm
88pub fn compute_block_layout(
89    tree: &mut impl LayoutBlockContainer,
90    node_id: NodeId,
91    inputs: LayoutInput,
92    bfc: Option<&mut BlockFormattingContext>,
93) -> LayoutOutput {
94    let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
95    let style = tree.get_block_container_style(node_id);
96
97    // Pull these out earlier to avoid borrowing issues
98    let aspect_ratio = style.aspect_ratio();
99    let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
100    let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
101    let padding_border_size = (padding + border).sum_axes();
102    let box_sizing_adjustment =
103        if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
104
105    let min_size = style
106        .min_size()
107        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
108        .maybe_apply_aspect_ratio(aspect_ratio)
109        .maybe_add(box_sizing_adjustment);
110    let max_size = style
111        .max_size()
112        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
113        .maybe_apply_aspect_ratio(aspect_ratio)
114        .maybe_add(box_sizing_adjustment);
115    let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
116        style
117            .size()
118            .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
119            .maybe_apply_aspect_ratio(aspect_ratio)
120            .maybe_add(box_sizing_adjustment)
121            .maybe_clamp(min_size, max_size)
122    } else {
123        Size::NONE
124    };
125
126    drop(style);
127
128    // If both min and max in a given axis are set and max <= min then this determines the size in that axis
129    let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
130        (Some(min), Some(max)) if max <= min => Some(min),
131        _ => None,
132    });
133
134    let styled_based_known_dimensions =
135        known_dimensions.or(min_max_definite_size).or(clamped_style_size).maybe_max(padding_border_size);
136
137    // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
138    // is ComputeSize (and thus the container's size is all that we're interested in)
139    if run_mode == RunMode::ComputeSize {
140        if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
141            return LayoutOutput::from_outer_size(Size { width, height });
142        }
143    }
144
145    // Unwrap the block formatting context if one was passed, or else create a new one
146    let mut new_bfc: BlockFormattingContext;
147    let bfc_ref: &mut BlockFormattingContext;
148    match bfc {
149        Some(inherited_bfc) => bfc_ref = inherited_bfc,
150        None => {
151            new_bfc = BlockFormattingContext::new(inputs.available_space.width);
152            bfc_ref = &mut new_bfc;
153        }
154    }
155
156    debug_log!("BLOCK");
157    compute_inner(tree, node_id, LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs }, bfc_ref)
158}
159
160/// Computes the layout of [`LayoutBlockContainer`] according to the block layout algorithm
161fn compute_inner(
162    tree: &mut impl LayoutBlockContainer,
163    node_id: NodeId,
164    inputs: LayoutInput,
165    bfc: &mut BlockFormattingContext,
166) -> LayoutOutput {
167    let LayoutInput {
168        known_dimensions, parent_size, available_space, run_mode, vertical_margins_are_collapsible, ..
169    } = inputs;
170
171    let style = tree.get_block_container_style(node_id);
172    let raw_padding = style.padding();
173    let raw_border = style.border();
174    let raw_margin = style.margin();
175    let aspect_ratio = style.aspect_ratio();
176    let padding = raw_padding.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
177    let border = raw_border.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
178
179    // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
180    // However, the axis are switched (transposed) because a node that scrolls vertically needs
181    // *horizontal* space to be reserved for a scrollbar
182    let scrollbar_gutter = {
183        let offsets = style.overflow().transpose().map(|overflow| match overflow {
184            Overflow::Scroll => style.scrollbar_width(),
185            _ => 0.0,
186        });
187        // TODO: make side configurable based on the `direction` property
188        Rect { top: 0.0, left: 0.0, right: offsets.x, bottom: offsets.y }
189    };
190    let padding_border = padding + border;
191    let padding_border_size = padding_border.sum_axes();
192    let content_box_inset = padding_border + scrollbar_gutter;
193    let container_content_box_size = known_dimensions.maybe_sub(content_box_inset.sum_axes());
194
195    let box_sizing_adjustment =
196        if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
197    let size = style
198        .size()
199        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
200        .maybe_apply_aspect_ratio(aspect_ratio)
201        .maybe_add(box_sizing_adjustment);
202    let min_size = style
203        .min_size()
204        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
205        .maybe_apply_aspect_ratio(aspect_ratio)
206        .maybe_add(box_sizing_adjustment);
207    let max_size = style
208        .max_size()
209        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
210        .maybe_apply_aspect_ratio(aspect_ratio)
211        .maybe_add(box_sizing_adjustment);
212
213    // Determine margin collapsing behaviour
214    let own_margins_collapse_with_children = Line {
215        start: vertical_margins_are_collapsible.start
216            && !style.overflow().x.is_scroll_container()
217            && !style.overflow().y.is_scroll_container()
218            && style.position() == Position::Relative
219            && padding.top == 0.0
220            && border.top == 0.0,
221        end: vertical_margins_are_collapsible.end
222            && !style.overflow().x.is_scroll_container()
223            && !style.overflow().y.is_scroll_container()
224            && style.position() == Position::Relative
225            && padding.bottom == 0.0
226            && border.bottom == 0.0
227            && size.height.is_none(),
228    };
229    let has_styles_preventing_being_collapsed_through = !style.is_block()
230        || style.overflow().x.is_scroll_container()
231        || style.overflow().y.is_scroll_container()
232        || style.position() == Position::Absolute
233        || padding.top > 0.0
234        || padding.bottom > 0.0
235        || border.top > 0.0
236        || border.bottom > 0.0
237        || matches!(size.height, Some(h) if h > 0.0)
238        || matches!(min_size.height, Some(h) if h > 0.0);
239
240    let text_align = style.text_align();
241
242    drop(style);
243
244    // 1. Generate items
245    let mut items = generate_item_list(tree, node_id, container_content_box_size);
246
247    // 2. Compute container width
248    let container_outer_width = known_dimensions.width.unwrap_or_else(|| {
249        let available_width = available_space.width.maybe_sub(content_box_inset.horizontal_axis_sum());
250        let intrinsic_width = determine_content_based_container_width(tree, &items, available_width)
251            + content_box_inset.horizontal_axis_sum();
252        intrinsic_width.maybe_clamp(min_size.width, max_size.width).maybe_max(Some(padding_border_size.width))
253    });
254
255    // Short-circuit if computing size and both dimensions known
256    if let (RunMode::ComputeSize, Some(container_outer_height)) = (run_mode, known_dimensions.height) {
257        return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: container_outer_height });
258    }
259
260    // 3. Perform final item layout and return content height
261    let resolved_padding = raw_padding.resolve_or_zero(Some(container_outer_width), |val, basis| tree.calc(val, basis));
262    let resolved_border = raw_border.resolve_or_zero(Some(container_outer_width), |val, basis| tree.calc(val, basis));
263    let resolved_content_box_inset = resolved_padding + resolved_border + scrollbar_gutter;
264    let (inflow_content_size, intrinsic_outer_height, first_child_top_margin_set, last_child_bottom_margin_set) =
265        perform_final_layout_on_in_flow_children(
266            tree,
267            &mut items,
268            container_outer_width,
269            content_box_inset,
270            resolved_content_box_inset,
271            text_align,
272            own_margins_collapse_with_children,
273        );
274    let container_outer_height = known_dimensions
275        .height
276        .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
277        .maybe_max(Some(padding_border_size.height));
278    let final_outer_size = Size { width: container_outer_width, height: container_outer_height };
279
280    // Short-circuit if computing size
281    if run_mode == RunMode::ComputeSize {
282        return LayoutOutput::from_outer_size(final_outer_size);
283    }
284
285    // 4. Layout absolutely positioned children
286    let absolute_position_inset = resolved_border + scrollbar_gutter;
287    let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
288    let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
289    let absolute_content_size =
290        perform_absolute_layout_on_absolute_children(tree, &items, absolute_position_area, absolute_position_offset);
291
292    // 5. Perform hidden layout on hidden children
293    let len = tree.child_count(node_id);
294    for order in 0..len {
295        let child = tree.get_child_id(node_id, order);
296        if tree.get_block_child_style(child).box_generation_mode() == BoxGenerationMode::None {
297            tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
298            tree.perform_child_layout(
299                child,
300                Size::NONE,
301                Size::NONE,
302                Size::MAX_CONTENT,
303                SizingMode::InherentSize,
304                Line::FALSE,
305            );
306        }
307    }
308
309    // 7. Determine whether this node can be collapsed through
310    let all_in_flow_children_can_be_collapsed_through =
311        items.iter().all(|item| item.position == Position::Absolute || item.can_be_collapsed_through);
312    let can_be_collapsed_through =
313        !has_styles_preventing_being_collapsed_through && all_in_flow_children_can_be_collapsed_through;
314
315    #[cfg_attr(not(feature = "content_size"), allow(unused_variables))]
316    let content_size = inflow_content_size.f32_max(absolute_content_size);
317
318    LayoutOutput {
319        size: final_outer_size,
320        #[cfg(feature = "content_size")]
321        content_size,
322        first_baselines: Point::NONE,
323        top_margin: if own_margins_collapse_with_children.start {
324            first_child_top_margin_set
325        } else {
326            let margin_top = raw_margin.top.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
327            CollapsibleMarginSet::from_margin(margin_top)
328        },
329        bottom_margin: if own_margins_collapse_with_children.end {
330            last_child_bottom_margin_set
331        } else {
332            let margin_bottom =
333                raw_margin.bottom.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
334            CollapsibleMarginSet::from_margin(margin_bottom)
335        },
336        margins_can_collapse_through: can_be_collapsed_through,
337    }
338}
339
340/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
341#[inline]
342fn generate_item_list(
343    tree: &impl LayoutBlockContainer,
344    node: NodeId,
345    node_inner_size: Size<Option<f32>>,
346) -> Vec<BlockItem> {
347    tree.child_ids(node)
348        .map(|child_node_id| (child_node_id, tree.get_block_child_style(child_node_id)))
349        .filter(|(_, style)| style.box_generation_mode() != BoxGenerationMode::None)
350        .enumerate()
351        .map(|(order, (child_node_id, child_style))| {
352            let aspect_ratio = child_style.aspect_ratio();
353            let padding = child_style.padding().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
354            let border = child_style.border().resolve_or_zero(node_inner_size, |val, basis| tree.calc(val, basis));
355            let pb_sum = (padding + border).sum_axes();
356            let box_sizing_adjustment =
357                if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
358            BlockItem {
359                node_id: child_node_id,
360                order: order as u32,
361                is_table: child_style.is_table(),
362                size: child_style
363                    .size()
364                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
365                    .maybe_apply_aspect_ratio(aspect_ratio)
366                    .maybe_add(box_sizing_adjustment),
367                min_size: child_style
368                    .min_size()
369                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
370                    .maybe_apply_aspect_ratio(aspect_ratio)
371                    .maybe_add(box_sizing_adjustment),
372                max_size: child_style
373                    .max_size()
374                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
375                    .maybe_apply_aspect_ratio(aspect_ratio)
376                    .maybe_add(box_sizing_adjustment),
377                overflow: child_style.overflow(),
378                scrollbar_width: child_style.scrollbar_width(),
379                position: child_style.position(),
380                inset: child_style.inset(),
381                margin: child_style.margin(),
382                padding,
383                border,
384                padding_border_sum: pb_sum,
385
386                // Fields to be computed later (for now we initialise with dummy values)
387                computed_size: Size::zero(),
388                static_position: Point::zero(),
389                can_be_collapsed_through: false,
390            }
391        })
392        .collect()
393}
394
395/// Compute the content-based width in the case that the width of the container is not known
396#[inline]
397fn determine_content_based_container_width(
398    tree: &mut impl LayoutPartialTree,
399    items: &[BlockItem],
400    available_width: AvailableSpace,
401) -> f32 {
402    let available_space = Size { width: available_width, height: AvailableSpace::MinContent };
403
404    let mut max_child_width = 0.0;
405    for item in items.iter().filter(|item| item.position != Position::Absolute) {
406        let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);
407
408        let width = known_dimensions.width.unwrap_or_else(|| {
409            let item_x_margin_sum = item
410                .margin
411                .resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis))
412                .horizontal_axis_sum();
413            let size_and_baselines = tree.perform_child_layout(
414                item.node_id,
415                known_dimensions,
416                Size::NONE,
417                available_space.map_width(|w| w.maybe_sub(item_x_margin_sum)),
418                SizingMode::InherentSize,
419                Line::TRUE,
420            );
421
422            size_and_baselines.size.width + item_x_margin_sum
423        });
424        let width = f32_max(width, item.padding_border_sum.width);
425
426        max_child_width = f32_max(max_child_width, width);
427    }
428
429    max_child_width
430}
431
432/// Compute each child's final size and position
433#[inline]
434fn perform_final_layout_on_in_flow_children(
435    tree: &mut impl LayoutPartialTree,
436    items: &mut [BlockItem],
437    container_outer_width: f32,
438    content_box_inset: Rect<f32>,
439    resolved_content_box_inset: Rect<f32>,
440    text_align: TextAlign,
441    own_margins_collapse_with_children: Line<bool>,
442) -> (Size<f32>, f32, CollapsibleMarginSet, CollapsibleMarginSet) {
443    // Resolve container_inner_width for sizing child nodes using initial content_box_inset
444    let container_inner_width = container_outer_width - content_box_inset.horizontal_axis_sum();
445    let parent_size = Size { width: Some(container_outer_width), height: None };
446    let available_space =
447        Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MinContent };
448
449    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
450    let mut inflow_content_size = Size::ZERO;
451    let mut committed_y_offset = resolved_content_box_inset.top;
452    let mut y_offset_for_absolute = resolved_content_box_inset.top;
453    let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
454    let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
455    let mut is_collapsing_with_first_margin_set = true;
456    for item in items.iter_mut() {
457        if item.position == Position::Absolute {
458            item.static_position = Point { x: resolved_content_box_inset.left, y: y_offset_for_absolute }
459        } else {
460            let item_margin = item
461                .margin
462                .map(|margin| margin.resolve_to_option(container_outer_width, |val, basis| tree.calc(val, basis)));
463            let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
464            let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();
465            let known_dimensions = if item.is_table {
466                Size::NONE
467            } else {
468                item.size
469                    .map_width(|width| {
470                        // TODO: Allow stretch-sizing to be conditional, as there are exceptions.
471                        // e.g. Table children of blocks do not stretch fit
472                        Some(
473                            width
474                                .unwrap_or(container_inner_width - item_non_auto_x_margin_sum)
475                                .maybe_clamp(item.min_size.width, item.max_size.width),
476                        )
477                    })
478                    .maybe_clamp(item.min_size, item.max_size)
479            };
480
481            let item_layout = tree.perform_child_layout(
482                item.node_id,
483                known_dimensions,
484                parent_size,
485                available_space.map_width(|w| w.maybe_sub(item_non_auto_x_margin_sum)),
486                SizingMode::InherentSize,
487                Line::TRUE,
488            );
489            let final_size = item_layout.size;
490
491            let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
492            let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
493
494            // Expand auto margins to fill available space
495            // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
496            // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
497            let free_x_space = f32_max(0.0, container_inner_width - final_size.width - item_non_auto_x_margin_sum);
498            let x_axis_auto_margin_size = {
499                let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
500                if auto_margin_count > 0 {
501                    free_x_space / auto_margin_count as f32
502                } else {
503                    0.0
504                }
505            };
506            let resolved_margin = Rect {
507                left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
508                right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
509                top: top_margin_set.resolve(),
510                bottom: bottom_margin_set.resolve(),
511            };
512
513            // Resolve item inset
514            let inset = item.inset.zip_size(Size { width: container_inner_width, height: 0.0 }, |p, s| {
515                p.maybe_resolve(s, |val, basis| tree.calc(val, basis))
516            });
517            let inset_offset = Point {
518                x: inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0),
519                y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
520            };
521
522            let y_margin_offset = if is_collapsing_with_first_margin_set && own_margins_collapse_with_children.start {
523                0.0
524            } else {
525                active_collapsible_margin_set.collapse_with_margin(resolved_margin.top).resolve()
526            };
527
528            item.computed_size = item_layout.size;
529            item.can_be_collapsed_through = item_layout.margins_can_collapse_through;
530            item.static_position = Point {
531                x: resolved_content_box_inset.left,
532                y: committed_y_offset + active_collapsible_margin_set.resolve(),
533            };
534            let mut location = Point {
535                x: resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
536                y: committed_y_offset + inset_offset.y + y_margin_offset,
537            };
538
539            // Apply alignment
540            let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
541            if item_outer_width < container_inner_width {
542                match text_align {
543                    TextAlign::Auto => {
544                        // Do nothing
545                    }
546                    TextAlign::LegacyLeft => {
547                        // Do nothing. Left aligned by default.
548                    }
549                    TextAlign::LegacyRight => location.x += container_inner_width - item_outer_width,
550                    TextAlign::LegacyCenter => location.x += (container_inner_width - item_outer_width) / 2.0,
551                }
552            }
553
554            let scrollbar_size = Size {
555                width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
556                height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
557            };
558
559            tree.set_unrounded_layout(
560                item.node_id,
561                &Layout {
562                    order: item.order,
563                    size: item_layout.size,
564                    #[cfg(feature = "content_size")]
565                    content_size: item_layout.content_size,
566                    scrollbar_size,
567                    location,
568                    padding: item.padding,
569                    border: item.border,
570                    margin: resolved_margin,
571                },
572            );
573
574            #[cfg(feature = "content_size")]
575            {
576                inflow_content_size = inflow_content_size.f32_max(compute_content_size_contribution(
577                    location,
578                    final_size,
579                    item_layout.content_size,
580                    item.overflow,
581                ));
582            }
583
584            // Update first_child_top_margin_set
585            if is_collapsing_with_first_margin_set {
586                if item.can_be_collapsed_through {
587                    first_child_top_margin_set = first_child_top_margin_set
588                        .collapse_with_set(top_margin_set)
589                        .collapse_with_set(bottom_margin_set);
590                } else {
591                    first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
592                    is_collapsing_with_first_margin_set = false;
593                }
594            }
595
596            // Update active_collapsible_margin_set
597            if item.can_be_collapsed_through {
598                active_collapsible_margin_set = active_collapsible_margin_set
599                    .collapse_with_set(top_margin_set)
600                    .collapse_with_set(bottom_margin_set);
601                y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
602            } else {
603                committed_y_offset += item_layout.size.height + y_margin_offset;
604                active_collapsible_margin_set = bottom_margin_set;
605                y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
606            }
607        }
608    }
609
610    let last_child_bottom_margin_set = active_collapsible_margin_set;
611    let bottom_y_margin_offset =
612        if own_margins_collapse_with_children.end { 0.0 } else { last_child_bottom_margin_set.resolve() };
613
614    committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
615    let content_height = f32_max(0.0, committed_y_offset);
616    (inflow_content_size, content_height, first_child_top_margin_set, last_child_bottom_margin_set)
617}
618
619/// Perform absolute layout on all absolutely positioned children.
620#[inline]
621fn perform_absolute_layout_on_absolute_children(
622    tree: &mut impl LayoutBlockContainer,
623    items: &[BlockItem],
624    area_size: Size<f32>,
625    area_offset: Point<f32>,
626) -> Size<f32> {
627    let area_width = area_size.width;
628    let area_height = area_size.height;
629
630    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
631    let mut absolute_content_size = Size::ZERO;
632
633    for item in items.iter().filter(|item| item.position == Position::Absolute) {
634        let child_style = tree.get_block_child_style(item.node_id);
635
636        // Skip items that are display:none or are not position:absolute
637        if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
638        {
639            continue;
640        }
641
642        let aspect_ratio = child_style.aspect_ratio();
643        let margin =
644            child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
645        let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
646        let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
647        let padding_border_sum = (padding + border).sum_axes();
648        let box_sizing_adjustment =
649            if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
650
651        // Resolve inset
652        let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
653        let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
654        let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
655        let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
656
657        // Compute known dimensions from min/max/inherent size styles
658        let style_size = child_style
659            .size()
660            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
661            .maybe_apply_aspect_ratio(aspect_ratio)
662            .maybe_add(box_sizing_adjustment);
663        let min_size = child_style
664            .min_size()
665            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
666            .maybe_apply_aspect_ratio(aspect_ratio)
667            .maybe_add(box_sizing_adjustment)
668            .or(padding_border_sum.map(Some))
669            .maybe_max(padding_border_sum);
670        let max_size = child_style
671            .max_size()
672            .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
673            .maybe_apply_aspect_ratio(aspect_ratio)
674            .maybe_add(box_sizing_adjustment);
675        let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
676
677        drop(child_style);
678
679        // Fill in width from left/right and reapply aspect ratio if:
680        //   - Width is not already known
681        //   - Item has both left and right inset properties set
682        if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
683            let new_width_raw = area_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
684            known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
685            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
686        }
687
688        // Fill in height from top/bottom and reapply aspect ratio if:
689        //   - Height is not already known
690        //   - Item has both top and bottom inset properties set
691        if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
692            let new_height_raw = area_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
693            known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
694            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
695        }
696
697        let layout_output = tree.perform_child_layout(
698            item.node_id,
699            known_dimensions,
700            area_size.map(Some),
701            Size {
702                width: AvailableSpace::Definite(area_width.maybe_clamp(min_size.width, max_size.width)),
703                height: AvailableSpace::Definite(area_height.maybe_clamp(min_size.height, max_size.height)),
704            },
705            SizingMode::ContentSize,
706            Line::FALSE,
707        );
708        let measured_size = layout_output.size;
709        let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
710
711        let non_auto_margin = Rect {
712            left: if left.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
713            right: if right.is_some() { margin.right.unwrap_or(0.0) } else { 0.0 },
714            top: if top.is_some() { margin.top.unwrap_or(0.0) } else { 0.0 },
715            bottom: if bottom.is_some() { margin.left.unwrap_or(0.0) } else { 0.0 },
716        };
717
718        // Expand auto margins to fill available space
719        // https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
720        let auto_margin = {
721            // Auto margins for absolutely positioned elements in block containers only resolve
722            // if inset is set. Otherwise they resolve to 0.
723            let absolute_auto_margin_space = Point {
724                x: right.map(|right| area_size.width - right - left.unwrap_or(0.0)).unwrap_or(final_size.width),
725                y: bottom.map(|bottom| area_size.height - bottom - top.unwrap_or(0.0)).unwrap_or(final_size.height),
726            };
727            let free_space = Size {
728                width: absolute_auto_margin_space.x - final_size.width - non_auto_margin.horizontal_axis_sum(),
729                height: absolute_auto_margin_space.y - final_size.height - non_auto_margin.vertical_axis_sum(),
730            };
731
732            let auto_margin_size = Size {
733                // If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0.
734                // Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the
735                // static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
736                //
737                // If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint
738                // that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is
739                // 'ltr' ('rtl'), set 'margin-left' ('margin-right') to zero and solve for 'margin-right' ('margin-left'). If one of 'margin-left' or
740                // 'margin-right' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'left' (in case
741                // the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.
742                width: {
743                    let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
744                    if auto_margin_count == 2
745                        && (style_size.width.is_none() || style_size.width.unwrap() >= free_space.width)
746                    {
747                        0.0
748                    } else if auto_margin_count > 0 {
749                        free_space.width / auto_margin_count as f32
750                    } else {
751                        0.0
752                    }
753                },
754                height: {
755                    let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
756                    if auto_margin_count == 2
757                        && (style_size.height.is_none() || style_size.height.unwrap() >= free_space.height)
758                    {
759                        0.0
760                    } else if auto_margin_count > 0 {
761                        free_space.height / auto_margin_count as f32
762                    } else {
763                        0.0
764                    }
765                },
766            };
767
768            Rect {
769                left: margin.left.map(|_| 0.0).unwrap_or(auto_margin_size.width),
770                right: margin.right.map(|_| 0.0).unwrap_or(auto_margin_size.width),
771                top: margin.top.map(|_| 0.0).unwrap_or(auto_margin_size.height),
772                bottom: margin.bottom.map(|_| 0.0).unwrap_or(auto_margin_size.height),
773            }
774        };
775
776        let resolved_margin = Rect {
777            left: margin.left.unwrap_or(auto_margin.left),
778            right: margin.right.unwrap_or(auto_margin.right),
779            top: margin.top.unwrap_or(auto_margin.top),
780            bottom: margin.bottom.unwrap_or(auto_margin.bottom),
781        };
782
783        let location = Point {
784            x: left
785                .map(|left| left + resolved_margin.left)
786                .or(right.map(|right| area_size.width - final_size.width - right - resolved_margin.right))
787                .maybe_add(area_offset.x)
788                .unwrap_or(item.static_position.x + resolved_margin.left),
789            y: top
790                .map(|top| top + resolved_margin.top)
791                .or(bottom.map(|bottom| area_size.height - final_size.height - bottom - resolved_margin.bottom))
792                .maybe_add(area_offset.y)
793                .unwrap_or(item.static_position.y + resolved_margin.top),
794        };
795        // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
796        // to the axis in which scrolling is enabled.
797        let scrollbar_size = Size {
798            width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
799            height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
800        };
801
802        tree.set_unrounded_layout(
803            item.node_id,
804            &Layout {
805                order: item.order,
806                size: final_size,
807                #[cfg(feature = "content_size")]
808                content_size: layout_output.content_size,
809                scrollbar_size,
810                location,
811                padding,
812                border,
813                margin: resolved_margin,
814            },
815        );
816
817        #[cfg(feature = "content_size")]
818        {
819            absolute_content_size = absolute_content_size.f32_max(compute_content_size_contribution(
820                location,
821                final_size,
822                layout_output.content_size,
823                item.overflow,
824            ));
825        }
826    }
827
828    absolute_content_size
829}