gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 1086HTML 1018Markdown 12TOML 84406 Definiciones

⎇ 42f75c6023434c27c9d6e69e2f3f3b5818ddd8e3 src/compute/block.rs Rust · 768 líneas · 34.5 KB Historia Quién tocó qué crudo

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