Skip to main content

layout/flow/
mod.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4#![expect(rustdoc::private_intra_doc_links)]
5
6//! Flow layout, also known as block-and-inline layout.
7
8use app_units::{Au, MAX_AU};
9use fonts::FontContext;
10use inline::InlineFormattingContext;
11use layout_api::LayoutNode;
12use malloc_size_of_derive::MallocSizeOf;
13use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
14use script::layout_dom::ServoLayoutNode;
15use servo_arc::Arc as ServoArc;
16use style::Zero;
17use style::computed_values::clear::T as StyleClear;
18use style::context::{QuirksMode, SharedStyleContext};
19use style::logical_geometry::LogicalAxis;
20use style::properties::ComputedValues;
21use style::servo::selector_parser::PseudoElement;
22use style::values::computed::{AlignmentBaseline, BaselineShift};
23use style::values::generics::box_::BaselineShiftKeyword;
24use style::values::specified::align::AlignFlags;
25use style::values::specified::{Display, TextAlignKeyword};
26
27use crate::cell::ArcRefCell;
28use crate::containing_block::{
29    ConstraintSpace, ContainingBlock, ContainingBlockSize, IndefiniteContainingBlock,
30};
31use crate::context::LayoutContext;
32use crate::dom::WeakLayoutBox;
33use crate::flow::float::{Clear, FloatBox, FloatSide, PlacementAmongFloats, SequentialLayoutState};
34use crate::flow::inline::text_run::get_font_for_first_font_for_style;
35use crate::flow::inline::{InlineContainerStateFlags, line_height};
36use crate::flow::same_formatting_context_block::SameFormattingContextBlock;
37use crate::formatting_contexts::{Baselines, IndependentFormattingContext};
38use crate::fragment_tree::{
39    BaseFragmentInfo, BlockLevelLayoutInfo, BoxFragment, CollapsedBlockMargins, CollapsedMargin,
40    Fragment, FragmentChildren, FragmentFlags, PositioningFragment,
41};
42use crate::geom::{
43    AuOrAuto, LogicalRect, LogicalSides, LogicalSides1D, LogicalVec2, PhysicalPoint, PhysicalRect,
44    PhysicalSides,
45};
46use crate::layout_box_base::{IndependentFormattingContextLayoutResult, LayoutBoxBase};
47use crate::positioned::{
48    AbsolutelyPositionedBox, PositioningContext, PositioningContextLength, StaticPositionRect,
49};
50use crate::sizing::{
51    self, ComputeInlineContentSizes, ContentSizes, InlineContentSizesResult, LazySize, Size,
52    SizeConstraint, Sizes,
53};
54use crate::style_ext::{AspectRatio, ContentBoxSizesAndPBM, LayoutStyle, PaddingBorderMargin};
55
56mod construct;
57pub mod float;
58pub mod inline;
59mod root;
60mod same_formatting_context_block;
61
62pub(crate) use construct::{BlockContainerBuilder, BlockLevelCreator};
63pub(crate) use root::BoxTree;
64
65#[derive(Debug, MallocSizeOf)]
66pub(crate) struct BlockFormattingContext {
67    pub contents: BlockContainer,
68    pub contains_floats: bool,
69    pub is_table_cell: bool,
70    /// This currently drives layouts for textareas as they require sizing based
71    /// on their number of rows. This is only Some for <textarea>s, otherwise it
72    /// is always None.
73    pub textarea_size: Option<TextareaSize>,
74}
75
76/// Helps format textareas according to their effective size as dictated by the
77/// spec.
78/// <https://html.spec.whatwg.org/multipage/#the-textarea-element-2>
79#[derive(Debug, MallocSizeOf)]
80pub(crate) struct TextareaSize {
81    /// The number of rows in this `<textarea>`, which is used to determine
82    /// its intrinsic block size when it has `field-sizing: fixed`.
83    /// <https://html.spec.whatwg.org/multipage/#textarea-effective-height>
84    /// <https://drafts.csswg.org/css-forms-1/#field-sizing>
85    rows: u32,
86    // TODO(44426): Store cols too, for the intrinsic inline size.
87}
88
89impl TextareaSize {
90    /// Effective block size of this textarea, which is the number of rows
91    /// multiplied by the line height. With no font available, this will
92    /// return None.
93    ///
94    /// <https://html.spec.whatwg.org/multipage/#textarea-effective-height>
95    // TODO(mttr): This should take scrollbar size into consideration.
96    fn effective_block_size(
97        &self,
98        style: &ComputedValues,
99        font_context: &FontContext,
100    ) -> Option<Au> {
101        let font_ref = get_font_for_first_font_for_style(style, font_context)?;
102        let line_height = line_height(
103            style,
104            font_ref.metrics(),
105            &InlineContainerStateFlags::empty(),
106        );
107        let rows = i32::try_from(self.rows).unwrap_or(i32::MAX);
108        Some(line_height * rows)
109    }
110}
111
112#[derive(Debug, MallocSizeOf)]
113pub(crate) enum BlockContainer {
114    BlockLevelBoxes(Vec<ArcRefCell<BlockLevelBox>>),
115    InlineFormattingContext(InlineFormattingContext),
116}
117
118impl BlockContainer {
119    fn contains_floats(&self) -> bool {
120        match self {
121            BlockContainer::BlockLevelBoxes(boxes) => boxes
122                .iter()
123                .any(|block_level_box| block_level_box.borrow().contains_floats()),
124            BlockContainer::InlineFormattingContext(context) => context.contains_floats,
125        }
126    }
127
128    pub(crate) fn repair_style(
129        &mut self,
130        context: &SharedStyleContext,
131        node: &ServoLayoutNode,
132        new_style: &ServoArc<ComputedValues>,
133    ) {
134        match self {
135            BlockContainer::BlockLevelBoxes(..) => {},
136            BlockContainer::InlineFormattingContext(inline_formatting_context) => {
137                inline_formatting_context.repair_style(context, node, new_style)
138            },
139        }
140    }
141
142    pub(crate) fn subtree_size(&self) -> usize {
143        match self {
144            BlockContainer::BlockLevelBoxes(boxes) => boxes
145                .iter()
146                .map(|block_level_box| block_level_box.borrow().subtree_size())
147                .sum(),
148            BlockContainer::InlineFormattingContext(inline_formatting_context) => {
149                inline_formatting_context.subtree_size()
150            },
151        }
152    }
153
154    pub(crate) fn inline_formatting_context(&self) -> Option<&InlineFormattingContext> {
155        match self {
156            BlockContainer::BlockLevelBoxes(..) => None,
157            BlockContainer::InlineFormattingContext(inline_formatting_context) => {
158                Some(inline_formatting_context)
159            },
160        }
161    }
162}
163
164#[derive(Debug, MallocSizeOf)]
165pub(crate) enum BlockLevelBox {
166    Independent(IndependentFormattingContext),
167    OutOfFlowAbsolutelyPositionedBox(ArcRefCell<AbsolutelyPositionedBox>),
168    OutOfFlowFloatBox(FloatBox),
169    OutsideMarker(OutsideMarker),
170    SameFormattingContextBlock(SameFormattingContextBlock),
171}
172
173impl BlockLevelBox {
174    pub(crate) fn repair_style(
175        &mut self,
176        context: &SharedStyleContext,
177        node: &ServoLayoutNode,
178        new_style: &ServoArc<ComputedValues>,
179    ) {
180        match self {
181            BlockLevelBox::Independent(independent_formatting_context) => {
182                independent_formatting_context.repair_style(context, node, new_style)
183            },
184            BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned_box) => positioned_box
185                .borrow_mut()
186                .context
187                .repair_style(context, node, new_style),
188            BlockLevelBox::OutOfFlowFloatBox(float_box) => {
189                float_box.contents.repair_style(context, node, new_style)
190            },
191            BlockLevelBox::OutsideMarker(outside_marker) => {
192                outside_marker.repair_style(context, node, new_style)
193            },
194            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
195                same_formatting_context_block.repair_style(context, node, new_style)
196            },
197        }
198    }
199
200    pub(crate) fn with_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> T {
201        match self {
202            BlockLevelBox::Independent(independent_formatting_context) => {
203                callback(&independent_formatting_context.base)
204            },
205            BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned_box) => {
206                callback(&positioned_box.borrow().context.base)
207            },
208            BlockLevelBox::OutOfFlowFloatBox(float_box) => callback(&float_box.contents.base),
209            BlockLevelBox::OutsideMarker(outside_marker) => callback(&outside_marker.context.base),
210            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
211                callback(&same_formatting_context_block.base)
212            },
213        }
214    }
215
216    pub(crate) fn with_base_mut<T>(&mut self, callback: impl FnOnce(&mut LayoutBoxBase) -> T) -> T {
217        match self {
218            BlockLevelBox::Independent(independent_formatting_context) => {
219                callback(&mut independent_formatting_context.base)
220            },
221            BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned_box) => {
222                callback(&mut positioned_box.borrow_mut().context.base)
223            },
224            BlockLevelBox::OutOfFlowFloatBox(float_box) => callback(&mut float_box.contents.base),
225            BlockLevelBox::OutsideMarker(outside_marker) => {
226                callback(&mut outside_marker.context.base)
227            },
228            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
229                callback(&mut same_formatting_context_block.base)
230            },
231        }
232    }
233
234    pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
235        match self {
236            Self::Independent(independent_formatting_context) => {
237                independent_formatting_context.attached_to_tree(layout_box)
238            },
239            Self::OutOfFlowAbsolutelyPositionedBox(positioned_box) => {
240                positioned_box.borrow().context.attached_to_tree(layout_box)
241            },
242            Self::OutOfFlowFloatBox(float_box) => float_box.contents.attached_to_tree(layout_box),
243            Self::OutsideMarker(outside_marker) => {
244                outside_marker.context.attached_to_tree(layout_box)
245            },
246            Self::SameFormattingContextBlock(same_formatting_context_block) => {
247                same_formatting_context_block
248                    .contents
249                    .attached_to_tree(layout_box)
250            },
251        }
252    }
253
254    fn contains_floats(&self) -> bool {
255        match self {
256            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
257                same_formatting_context_block.contains_floats
258            },
259            BlockLevelBox::OutOfFlowFloatBox { .. } => true,
260            _ => false,
261        }
262    }
263
264    fn find_block_margin_collapsing_with_parent(
265        &self,
266        layout_context: &LayoutContext,
267        collected_margin: &mut CollapsedMargin,
268        containing_block: &ContainingBlock,
269    ) -> bool {
270        let layout_style = match self {
271            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
272                same_formatting_context_block.layout_style()
273            },
274            BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(_) |
275            BlockLevelBox::OutOfFlowFloatBox(_) => return true,
276            BlockLevelBox::OutsideMarker(_) => return false,
277            BlockLevelBox::Independent(context) => {
278                // FIXME: If the element doesn't fit next to floats, it will get clearance.
279                // In that case this should be returning false.
280                context.layout_style()
281            },
282        };
283
284        // FIXME: This should only return false when 'clear' causes clearance.
285        let style = layout_style.style();
286        if style.get_box().clear != StyleClear::None {
287            return false;
288        }
289
290        let ContentBoxSizesAndPBM {
291            content_box_sizes,
292            pbm,
293            ..
294        } = layout_style.content_box_sizes_and_padding_border_margin(&containing_block.into());
295        let margin = pbm.margin.auto_is(Au::zero);
296        collected_margin.adjoin_assign(&CollapsedMargin::new(margin.block_start));
297
298        let BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) = self else {
299            return false;
300        };
301
302        if !pbm.padding.block_start.is_zero() || !pbm.border.block_start.is_zero() {
303            return false;
304        }
305
306        let inline_stretch_size = containing_block
307            .inline_stretch_size(pbm.padding_border_sums.inline + margin.inline_sum());
308        let block_stretch_size =
309            containing_block.block_stretch_size(pbm.padding_border_sums.block + margin.block_sum());
310
311        let mut tentative_block_size = content_box_sizes.block.resolve_extrinsic(
312            automatic_block_size(layout_context, &same_formatting_context_block.base),
313            Au::zero(),
314            block_stretch_size,
315        );
316        let mut has_quirky_block_size = false;
317        if skippable_for_block_percentage_quirk(
318            layout_context,
319            &same_formatting_context_block.base,
320            None,
321        ) {
322            has_quirky_block_size = !tentative_block_size.is_definite();
323            tentative_block_size
324                .replace_if_indefinite_with(containing_block.maybe_quirky_block_size());
325        }
326
327        let get_inline_content_sizes = || {
328            // TODO: support preferred aspect ratios on non-replaced boxes
329            let preferred_aspect_ratio = None;
330            let constraint_space = if has_quirky_block_size {
331                ConstraintSpace::new_quirky(tentative_block_size, style, preferred_aspect_ratio)
332            } else {
333                ConstraintSpace::new(tentative_block_size, style, preferred_aspect_ratio)
334            };
335            self.inline_content_sizes(layout_context, &constraint_space)
336                .sizes
337        };
338        let inline_size = content_box_sizes.inline.resolve(
339            LogicalAxis::Inline,
340            Size::Stretch,
341            Au::zero,
342            inline_stretch_size,
343            get_inline_content_sizes,
344            false, /* is_table */
345        );
346
347        let containing_block_for_children = ContainingBlock {
348            size: if has_quirky_block_size {
349                ContainingBlockSize::new_quirky(inline_size, tentative_block_size)
350            } else {
351                ContainingBlockSize::new(inline_size, tentative_block_size)
352            },
353            style,
354        };
355
356        if !same_formatting_context_block
357            .contents
358            .find_block_margin_collapsing_with_parent(
359                layout_context,
360                collected_margin,
361                &containing_block_for_children,
362            )
363        {
364            return false;
365        }
366
367        if !tentative_block_size.definite_or_min().is_zero() ||
368            !pbm.padding_border_sums.block.is_zero()
369        {
370            return false;
371        }
372
373        collected_margin.adjoin_assign(&CollapsedMargin::new(margin.block_end));
374
375        true
376    }
377
378    fn subtree_size(&self) -> usize {
379        self.with_base(|base| base.subtree_size())
380    }
381}
382
383#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
384pub(crate) struct CollapsibleWithParentStartMargin(bool);
385
386/// The contentes of a BlockContainer created to render a list marker
387/// for a list that has `list-style-position: outside`.
388#[derive(Debug, MallocSizeOf)]
389pub(crate) struct OutsideMarker {
390    pub list_item_style: ServoArc<ComputedValues>,
391    pub context: IndependentFormattingContext,
392}
393
394impl OutsideMarker {
395    fn layout(
396        &self,
397        layout_context: &LayoutContext<'_>,
398        containing_block: &ContainingBlock<'_>,
399        positioning_context: &mut PositioningContext,
400    ) -> Fragment {
401        let style = &self.context.base.style;
402        let preferred_aspect_ratio = self.context.preferred_aspect_ratio(&LogicalVec2::zero());
403        let constraint_space =
404            ConstraintSpace::new(SizeConstraint::default(), style, preferred_aspect_ratio);
405        let content_sizes = self
406            .context
407            .inline_content_sizes(layout_context, &constraint_space);
408        let containing_block_for_children = ContainingBlock {
409            size: ContainingBlockSize::new(
410                content_sizes.sizes.max_content, /* inline_size */
411                SizeConstraint::default(),       /* block_size */
412            ),
413            style,
414        };
415
416        let layout = self.context.layout(
417            layout_context,
418            positioning_context,
419            &containing_block_for_children,
420            containing_block,
421            preferred_aspect_ratio,
422            &LazySize::intrinsic(),
423        );
424
425        let max_inline_size = match &layout.fragments {
426            FragmentChildren::PhysicalDeprecated(fragments) => fragments
427                .iter()
428                .map(|fragment| {
429                    LogicalRect::from_physical_deprecated(
430                        fragment.base().map(|base| base.rect()).unwrap_or_default(),
431                        &containing_block_for_children,
432                    )
433                    .max_inline_position()
434                })
435                .max(),
436            FragmentChildren::Logical(fragments) => fragments
437                .iter()
438                .map(|fragment| fragment.logical_rect.max_inline_position())
439                .max(),
440        }
441        .unwrap_or_default();
442
443        // Position the marker beyond the inline start of the border box list item. This needs to
444        // take into account the border and padding of the item.
445        //
446        // TODO: This is the wrong containing block, as it should be the containing block of the
447        // parent of this list item. What this means in practice is that the writing mode could be
448        // wrong and padding defined as a percentage will be resolved incorrectly.
449        //
450        // TODO: This should use the LayoutStyle of the list item, not the default one. Currently
451        // they are the same, but this could change in the future.
452        let pbm_of_list_item =
453            LayoutStyle::Default(&self.list_item_style).padding_border_margin(containing_block);
454        let content_rect = LogicalRect {
455            start_corner: LogicalVec2 {
456                inline: -max_inline_size -
457                    (pbm_of_list_item.border.inline_start +
458                        pbm_of_list_item.padding.inline_start),
459                block: Zero::zero(),
460            },
461            size: LogicalVec2 {
462                inline: max_inline_size,
463                block: layout.content_block_size,
464            },
465        };
466
467        let mut base_fragment_info = BaseFragmentInfo::anonymous();
468        base_fragment_info.flags |= FragmentFlags::IS_OUTSIDE_LIST_ITEM_MARKER;
469
470        Fragment::Box(
471            BoxFragment::new(
472                base_fragment_info,
473                style.clone(),
474                layout.fragments,
475                content_rect.as_physical_deprecated(containing_block),
476                PhysicalSides::zero(),
477                PhysicalSides::zero(),
478                PhysicalSides::zero(),
479                layout.specific_layout_info,
480            )
481            .into(),
482        )
483    }
484
485    fn repair_style(
486        &mut self,
487        context: &SharedStyleContext,
488        node: &ServoLayoutNode,
489        new_style: &ServoArc<ComputedValues>,
490    ) {
491        self.list_item_style = node.parent_style(context);
492        self.context.repair_style(context, node, new_style);
493    }
494}
495
496/// The used value of `align-content` for a block formatting context.
497#[derive(PartialEq)]
498pub(crate) enum ContentAlignment {
499    Start,
500    SafeEnd,
501    UnsafeEnd,
502    SafeCenter,
503    UnsafeCenter,
504    Baseline,
505}
506
507impl ContentAlignment {
508    pub(crate) fn resolve_offset(
509        &self,
510        free_space: impl FnOnce() -> Au,
511        baseline: impl FnOnce() -> Au,
512    ) -> Au {
513        match self {
514            Self::Start => Au::zero(),
515            Self::SafeEnd => Au::zero().max(free_space()),
516            Self::UnsafeEnd => free_space(),
517            Self::SafeCenter => Au::zero().max(free_space() / 2),
518            Self::UnsafeCenter => free_space() / 2,
519            Self::Baseline => baseline(),
520        }
521    }
522}
523
524impl BlockFormattingContext {
525    pub(super) fn layout(
526        &self,
527        layout_context: &LayoutContext,
528        positioning_context: &mut PositioningContext,
529        containing_block: &ContainingBlock,
530        lazy_block_size: &LazySize,
531        base: Option<&LayoutBoxBase>,
532    ) -> IndependentFormattingContextLayoutResult {
533        let mut sequential_layout_state =
534            if self.contains_floats || !layout_context.allow_parallel_layout {
535                Some(SequentialLayoutState::new(containing_block.inline_size()))
536            } else {
537                None
538            };
539
540        // Since this is an independent formatting context, we don't ignore block margins when
541        // resolving a stretch block size of the children.
542        // https://drafts.csswg.org/css-sizing-4/#stretch-fit-sizing
543        let ignore_block_margins_for_stretch = LogicalSides1D::new(false, false);
544
545        // Store the current length of the positioning context, because below we may need to
546        // adjust the static positions of the abspos within this BFC.
547        let previous_positioning_context_len = positioning_context.len();
548
549        let mut flow_layout = self.contents.layout(
550            layout_context,
551            positioning_context,
552            containing_block,
553            sequential_layout_state.as_mut(),
554            CollapsibleWithParentStartMargin(false),
555            ignore_block_margins_for_stretch,
556        );
557        debug_assert!(
558            !flow_layout
559                .collapsible_margins_in_children
560                .collapsed_through
561        );
562
563        // The content height of a BFC root should include any float participating in that BFC
564        // (https://drafts.csswg.org/css2/#root-height), we implement this by imagining there is
565        // an element with `clear: both` after the actual contents.
566        let clearance = sequential_layout_state.and_then(|sequential_layout_state| {
567            sequential_layout_state.calculate_clearance(Clear::Both, &CollapsedMargin::zero())
568        });
569
570        let content_block_size = flow_layout.content_block_size +
571            flow_layout.collapsible_margins_in_children.end.solve() +
572            clearance.unwrap_or_default();
573
574        let intrinsic_block_size = self
575            .textarea_size
576            .as_ref()
577            .and_then(|textarea_size| {
578                textarea_size.effective_block_size(&base?.style, &layout_context.font_context)
579            })
580            .unwrap_or(content_block_size);
581
582        let mut apply_align_content = || {
583            // Don't handle `align-content` for table cells, since at this point we still
584            // don't know how tall they will be. It's instead handled during table layout.
585            if self.is_table_cell {
586                return;
587            }
588            // Also no need to do anything for the initial containing block.
589            let Some(base) = base else {
590                return;
591            };
592
593            let content_alignment = self.content_alignment(base);
594
595            // No need to do anything for `start`. `baseline` is broken outside table cells,
596            // treat it as `start` for now (<https://github.com/w3c/csswg-drafts/issues/13421>).
597            if matches!(
598                content_alignment,
599                ContentAlignment::Start | ContentAlignment::Baseline
600            ) {
601                return;
602            }
603
604            flow_layout.depends_on_block_constraints = true;
605            let align_offset = content_alignment.resolve_offset(
606                // Compute the free space: final block size minus block size of the contents.
607                // Note that the alignment subject is the actual contents of the box, even if
608                // the intrinsic block size is different (as is the case with <textarea>)
609                || lazy_block_size.resolve(|| intrinsic_block_size) - content_block_size,
610                || unreachable!("Should have already returned for baseline"),
611            );
612            if align_offset.is_zero() {
613                return;
614            }
615
616            // Create an `AnonymousFragment` that contains the fragments of the contents,
617            // and place it as desired.
618            let align_fragment_rect = LogicalRect {
619                start_corner: LogicalVec2 {
620                    inline: Au::zero(),
621                    block: align_offset,
622                },
623                size: LogicalVec2 {
624                    inline: containing_block.inline_size(),
625                    block: content_block_size,
626                },
627            };
628            positioning_context.adjust_static_position_of_hoisted_fragments(
629                &align_fragment_rect,
630                containing_block.style.writing_mode,
631                previous_positioning_context_len,
632            );
633            let align_fragment = PositioningFragment::new_anonymous(
634                base.style.clone(),
635                align_fragment_rect.as_physical_deprecated(containing_block),
636                std::mem::take(&mut flow_layout.fragments),
637                false, /* is_line_box */
638            );
639            flow_layout.fragments =
640                FragmentChildren::PhysicalDeprecated(vec![Fragment::Positioning(align_fragment)]);
641        };
642        apply_align_content();
643
644        IndependentFormattingContextLayoutResult {
645            fragments: flow_layout.fragments,
646            content_block_size: intrinsic_block_size,
647            content_inline_size_for_table: None,
648            baselines: flow_layout.baselines,
649            depends_on_block_constraints: flow_layout.depends_on_block_constraints,
650            specific_layout_info: None,
651            collapsible_margins_in_children: CollapsedBlockMargins::zero(),
652        }
653    }
654
655    pub(crate) fn content_alignment(&self, base: &LayoutBoxBase) -> ContentAlignment {
656        let align_content_style = base.style.get_align_content().primary();
657
658        // If no overflow alignment is specified, the spec describes a "smart" behavior.
659        // But if that isn't implemented, the default behavior must be `safe` on block
660        // containers. See <https://drafts.csswg.org/css-align/#auto-safety-default>.
661        let is_safe = align_content_style.flags() != AlignFlags::UNSAFE;
662
663        match align_content_style.value() {
664            // - On table cells, `align-content: normal` defers to `vertical-align`.
665            //   The spec still assumes that `vertical-align` is a longhand, so it's not very
666            //   clear if this logic is completely correct, but it seems to match Firefox.
667            //   See <https://github.com/w3c/csswg-drafts/issues/13458>.
668            // - On buttons, it behaves as `safe center`.
669            //   See <https://github.com/w3c/csswg-drafts/issues/14190>.
670            // - Otherwise behaves as `start`.
671            AlignFlags::NORMAL if self.is_table_cell => match base.style.get_baseline_shift() {
672                BaselineShift::Keyword(BaselineShiftKeyword::Top) => ContentAlignment::Start,
673                BaselineShift::Keyword(BaselineShiftKeyword::Bottom) => ContentAlignment::SafeEnd,
674                _ => match base.style.get_alignment_baseline() {
675                    AlignmentBaseline::Middle => ContentAlignment::SafeCenter,
676                    _ => ContentAlignment::Baseline,
677                },
678            },
679            AlignFlags::NORMAL
680                if base
681                    .base_fragment_info
682                    .flags
683                    .contains(FragmentFlags::IS_BUTTON) =>
684            {
685                ContentAlignment::SafeCenter
686            },
687            AlignFlags::NORMAL => ContentAlignment::Start,
688
689            // Explicit <content-position>.
690            AlignFlags::CENTER if is_safe => ContentAlignment::SafeCenter,
691            AlignFlags::CENTER => ContentAlignment::UnsafeCenter,
692            AlignFlags::START | AlignFlags::FLEX_START => ContentAlignment::Start,
693            AlignFlags::END | AlignFlags::FLEX_END if is_safe => ContentAlignment::SafeEnd,
694            AlignFlags::END | AlignFlags::FLEX_END => ContentAlignment::UnsafeEnd,
695
696            // For <content-distribution>, use the fallback alignment.
697            AlignFlags::SPACE_AROUND | AlignFlags::SPACE_EVENLY => ContentAlignment::SafeCenter,
698            AlignFlags::SPACE_BETWEEN | AlignFlags::STRETCH => ContentAlignment::Start,
699
700            // The CSSWG resolved to unship the baseline values for `align-content`, and Blink
701            // doesn't even parse `align-content: last baseline`, so don't bother telling them
702            // apart. For now, treat them as `vertical-align: baseline` on table cells.
703            // See <https://github.com/w3c/csswg-drafts/issues/13421>
704            AlignFlags::BASELINE | AlignFlags::LAST_BASELINE => ContentAlignment::Baseline,
705
706            // Other `AlignFlags` values shouldn't be valid for `align-content`.
707            unexpected => {
708                debug_assert!(false, "Unexpected align-content value: {:?}", unexpected);
709                ContentAlignment::Start
710            },
711        }
712    }
713
714    #[inline]
715    pub(crate) fn layout_style<'a>(&self, base: &'a LayoutBoxBase) -> LayoutStyle<'a> {
716        LayoutStyle::Default(&base.style)
717    }
718
719    pub(crate) fn repair_style(
720        &mut self,
721        context: &SharedStyleContext,
722        node: &ServoLayoutNode,
723        new_style: &ServoArc<ComputedValues>,
724    ) {
725        self.contents.repair_style(context, node, new_style);
726    }
727
728    pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
729        self.contents.attached_to_tree(layout_box);
730    }
731
732    pub(crate) fn inline_formatting_context(&self) -> Option<&InlineFormattingContext> {
733        self.contents.inline_formatting_context()
734    }
735}
736
737/// Finds the min/max-content inline size of the block-level children of a block container.
738/// The in-flow boxes will stack vertically, so we only need to consider the maximum size.
739/// But floats can flow horizontally depending on 'clear', so we may need to sum their sizes.
740/// CSS 2 does not define the exact algorithm, this logic is based on the behavior observed
741/// on Gecko and Blink.
742fn compute_inline_content_sizes_for_block_level_boxes(
743    boxes: &[ArcRefCell<BlockLevelBox>],
744    layout_context: &LayoutContext,
745    containing_block: &IndefiniteContainingBlock,
746) -> InlineContentSizesResult {
747    let get_box_info = |box_: &ArcRefCell<BlockLevelBox>| {
748        match &*box_.borrow() {
749            BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(_) |
750            BlockLevelBox::OutsideMarker { .. } => None,
751            BlockLevelBox::OutOfFlowFloatBox(float_box) => {
752                let inline_content_sizes_result = float_box.contents.outer_inline_content_sizes(
753                    layout_context,
754                    containing_block,
755                    &LogicalVec2::zero(),
756                    false, /* auto_block_size_stretches_to_containing_block */
757                    skippable_for_block_percentage_quirk(
758                        layout_context,
759                        &float_box.contents.base,
760                        Some(&float_box.contents),
761                    ),
762                );
763                let style = &float_box.contents.style();
764                let container_writing_mode = containing_block.style.writing_mode;
765                Some((
766                    inline_content_sizes_result,
767                    FloatSide::from_style_and_container_writing_mode(style, container_writing_mode),
768                    Clear::from_style_and_container_writing_mode(style, container_writing_mode),
769                ))
770            },
771            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
772                let base = &same_formatting_context_block.base;
773                let contents = &same_formatting_context_block.contents;
774                let is_anonymous_block =
775                    matches!(base.style.pseudo(), Some(PseudoElement::ServoAnonymousBox));
776                let inline_content_sizes_result = sizing::outer_inline(
777                    base,
778                    &contents.layout_style(base),
779                    containing_block,
780                    &LogicalVec2::zero(),
781                    false,               /* auto_block_size_stretches_to_containing_block */
782                    false,               /* is_replaced */
783                    !is_anonymous_block, /* establishes_containing_block */
784                    skippable_for_block_percentage_quirk(layout_context, base, None),
785                    |_| None, /* TODO: support preferred aspect ratios on non-replaced boxes */
786                    |constraint_space| {
787                        base.inline_content_sizes(layout_context, constraint_space, contents)
788                    },
789                    |_aspect_ratio| None,
790                );
791                // A block in the same BFC can overlap floats, it's not moved next to them,
792                // so we shouldn't add its size to the size of the floats.
793                // Instead, we treat it like an independent block with 'clear: both',
794                // except if it's an anonymous block.
795                // Presumably, the exception is because an anonymous block will always have
796                // inline-level contents, which don't overlap floats. However, the same might
797                // also happen with a non-anonymous block, so the logic is a bit arbitrary,
798                // but matches other browsers (see #41280).
799                let clear = if is_anonymous_block {
800                    Clear::None
801                } else {
802                    Clear::Both
803                };
804                Some((inline_content_sizes_result, None, clear))
805            },
806            BlockLevelBox::Independent(independent) => {
807                let inline_content_sizes_result = independent.outer_inline_content_sizes(
808                    layout_context,
809                    containing_block,
810                    &LogicalVec2::zero(),
811                    false, /* auto_block_size_stretches_to_containing_block */
812                    skippable_for_block_percentage_quirk(
813                        layout_context,
814                        &independent.base,
815                        Some(independent),
816                    ),
817                );
818                Some((
819                    inline_content_sizes_result,
820                    None,
821                    Clear::from_style_and_container_writing_mode(
822                        independent.style(),
823                        containing_block.style.writing_mode,
824                    ),
825                ))
826            },
827        }
828    };
829
830    /// When iterating the block-level boxes to compute the inline content sizes,
831    /// this struct contains the data accumulated up to the current box.
832    #[derive(Default)]
833    struct AccumulatedData {
834        /// Whether the inline size depends on the block one.
835        depends_on_block_constraints: bool,
836        /// The maximum size seen so far, not including trailing uncleared floats.
837        max_size: ContentSizes,
838        /// The size of the trailing uncleared floats on the inline-start and
839        /// inline-end sides of the containing block.
840        floats: LogicalSides1D<ContentSizes>,
841    }
842
843    impl AccumulatedData {
844        fn max_size_including_uncleared_floats(&self) -> ContentSizes {
845            self.max_size.max(self.floats.start.union(&self.floats.end))
846        }
847        fn clear_floats(&mut self, clear: Clear) {
848            match clear {
849                Clear::InlineStart => {
850                    self.max_size = self.max_size_including_uncleared_floats();
851                    self.floats.start = ContentSizes::default();
852                },
853                Clear::InlineEnd => {
854                    self.max_size = self.max_size_including_uncleared_floats();
855                    self.floats.end = ContentSizes::default();
856                },
857                Clear::Both => {
858                    self.max_size = self.max_size_including_uncleared_floats();
859                    self.floats = LogicalSides1D::default();
860                },
861                Clear::None => {},
862            };
863        }
864    }
865
866    let accumulate =
867        |mut data: AccumulatedData,
868         (inline_content_sizes_result, float, clear): (InlineContentSizesResult, _, _)| {
869            let size = inline_content_sizes_result.sizes.max(ContentSizes::zero());
870            let depends_on_block_constraints =
871                inline_content_sizes_result.depends_on_block_constraints;
872            data.depends_on_block_constraints |= depends_on_block_constraints;
873            data.clear_floats(clear);
874            match float {
875                Some(FloatSide::InlineStart) => data.floats.start.union_assign(&size),
876                Some(FloatSide::InlineEnd) => data.floats.end.union_assign(&size),
877                None => {
878                    data.max_size
879                        .max_assign(data.floats.start.union(&data.floats.end).union(&size));
880                    data.floats = LogicalSides1D::default();
881                },
882            }
883            data
884        };
885
886    let job_counts = boxes
887        .iter()
888        .map(|block_level_box| block_level_box.borrow().subtree_size());
889    let data = if layout_context.should_parallelize_layout(job_counts) {
890        boxes
891            .par_iter()
892            .filter_map(get_box_info)
893            .collect::<Vec<_>>()
894            .into_iter()
895            .fold(AccumulatedData::default(), accumulate)
896    } else {
897        boxes
898            .iter()
899            .filter_map(get_box_info)
900            .fold(AccumulatedData::default(), accumulate)
901    };
902    InlineContentSizesResult {
903        depends_on_block_constraints: data.depends_on_block_constraints,
904        sizes: data.max_size_including_uncleared_floats(),
905    }
906}
907
908impl BlockContainer {
909    fn layout(
910        &self,
911        layout_context: &LayoutContext,
912        positioning_context: &mut PositioningContext,
913        containing_block: &ContainingBlock,
914        sequential_layout_state: Option<&mut SequentialLayoutState>,
915        collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
916        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
917    ) -> IndependentFormattingContextLayoutResult {
918        match self {
919            BlockContainer::BlockLevelBoxes(child_boxes) => layout_block_level_children(
920                layout_context,
921                positioning_context,
922                child_boxes,
923                containing_block,
924                sequential_layout_state,
925                collapsible_with_parent_start_margin,
926                ignore_block_margins_for_stretch,
927            ),
928            BlockContainer::InlineFormattingContext(ifc) => ifc.layout(
929                layout_context,
930                positioning_context,
931                containing_block,
932                sequential_layout_state,
933                collapsible_with_parent_start_margin,
934                ignore_block_margins_for_stretch,
935            ),
936        }
937    }
938
939    #[inline]
940    pub(crate) fn layout_style<'a>(&self, base: &'a LayoutBoxBase) -> LayoutStyle<'a> {
941        LayoutStyle::Default(&base.style)
942    }
943
944    pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
945        match self {
946            Self::BlockLevelBoxes(child_boxes) => {
947                for child_box in child_boxes {
948                    child_box.borrow_mut().with_base_mut(|base| {
949                        base.parent_box.replace(layout_box.clone());
950                    });
951                }
952            },
953            Self::InlineFormattingContext(ifc) => ifc.attached_to_tree(layout_box),
954        }
955    }
956
957    fn find_block_margin_collapsing_with_parent(
958        &self,
959        layout_context: &LayoutContext,
960        collected_margin: &mut CollapsedMargin,
961        containing_block_for_children: &ContainingBlock,
962    ) -> bool {
963        match self {
964            BlockContainer::BlockLevelBoxes(boxes) => boxes.iter().all(|block_level_box| {
965                block_level_box
966                    .borrow()
967                    .find_block_margin_collapsing_with_parent(
968                        layout_context,
969                        collected_margin,
970                        containing_block_for_children,
971                    )
972            }),
973            BlockContainer::InlineFormattingContext(context) => context
974                .find_block_margin_collapsing_with_parent(
975                    layout_context,
976                    collected_margin,
977                    containing_block_for_children,
978                ),
979        }
980    }
981}
982
983impl ComputeInlineContentSizes for BlockContainer {
984    fn compute_inline_content_sizes(
985        &self,
986        layout_context: &LayoutContext,
987        constraint_space: &ConstraintSpace,
988    ) -> InlineContentSizesResult {
989        match &self {
990            Self::BlockLevelBoxes(boxes) => compute_inline_content_sizes_for_block_level_boxes(
991                boxes,
992                layout_context,
993                &constraint_space.into(),
994            ),
995            Self::InlineFormattingContext(context) => {
996                context.compute_inline_content_sizes(layout_context, constraint_space)
997            },
998        }
999    }
1000}
1001
1002fn layout_block_level_children(
1003    layout_context: &LayoutContext,
1004    positioning_context: &mut PositioningContext,
1005    child_boxes: &[ArcRefCell<BlockLevelBox>],
1006    containing_block: &ContainingBlock,
1007    mut sequential_layout_state: Option<&mut SequentialLayoutState>,
1008    collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
1009    ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1010) -> IndependentFormattingContextLayoutResult {
1011    let mut placement_state =
1012        PlacementState::new(collapsible_with_parent_start_margin, containing_block);
1013
1014    let fragments = match sequential_layout_state {
1015        Some(ref mut sequential_layout_state) => layout_block_level_children_sequentially(
1016            layout_context,
1017            positioning_context,
1018            child_boxes,
1019            sequential_layout_state,
1020            &mut placement_state,
1021            ignore_block_margins_for_stretch,
1022        ),
1023        None => layout_block_level_children_maybe_in_parallel(
1024            layout_context,
1025            positioning_context,
1026            child_boxes,
1027            &mut placement_state,
1028            ignore_block_margins_for_stretch,
1029        ),
1030    };
1031
1032    let depends_on_block_constraints = fragments.fragments().any(|fragment| {
1033        fragment.base().is_some_and(|base| {
1034            base.flags.contains(
1035                FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
1036            )
1037        })
1038    });
1039
1040    let (content_block_size, collapsible_margins_in_children, baselines) = placement_state.finish();
1041    IndependentFormattingContextLayoutResult {
1042        fragments,
1043        content_block_size,
1044        collapsible_margins_in_children,
1045        baselines,
1046        depends_on_block_constraints,
1047        content_inline_size_for_table: None,
1048        specific_layout_info: None,
1049    }
1050}
1051
1052fn layout_block_level_children_maybe_in_parallel(
1053    layout_context: &LayoutContext,
1054    positioning_context: &mut PositioningContext,
1055    child_boxes: &[ArcRefCell<BlockLevelBox>],
1056    placement_state: &mut PlacementState,
1057    ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1058) -> FragmentChildren {
1059    let mut layout_results: Vec<(Fragment, PositioningContext)> =
1060        Vec::with_capacity(child_boxes.len());
1061
1062    let layout = |child_box: &ArcRefCell<BlockLevelBox>| {
1063        let mut child_positioning_context = PositioningContext::default();
1064        let fragment = child_box.borrow().layout(
1065            layout_context,
1066            &mut child_positioning_context,
1067            placement_state.containing_block,
1068            /* sequential_layout_state = */ None,
1069            /* collapsible_with_parent_start_margin = */ None,
1070            ignore_block_margins_for_stretch,
1071            false, /* has_inline_parent */
1072        );
1073        (fragment, child_positioning_context)
1074    };
1075
1076    let job_counts = child_boxes
1077        .iter()
1078        .map(|block_level_box| block_level_box.borrow().subtree_size());
1079    if layout_context.should_parallelize_layout(job_counts) {
1080        child_boxes
1081            .par_iter()
1082            .map(layout)
1083            .collect_into_vec(&mut layout_results);
1084    } else {
1085        layout_results.extend(child_boxes.iter().map(layout));
1086    };
1087
1088    let fragments = layout_results
1089        .into_iter()
1090        .map(|(mut fragment, mut child_positioning_context)| {
1091            placement_state.place_fragment_and_update_baseline(&mut fragment, None);
1092
1093            if let Some(rect) = fragment.base().map(|base| base.rect()) {
1094                child_positioning_context.adjust_static_position_of_hoisted_fragments(
1095                    &LogicalRect::from_physical_deprecated(rect, placement_state.containing_block),
1096                    placement_state.containing_block.style.writing_mode,
1097                    PositioningContextLength::zero(),
1098                );
1099            }
1100
1101            positioning_context.append(child_positioning_context);
1102            fragment
1103        })
1104        .collect();
1105    FragmentChildren::PhysicalDeprecated(fragments)
1106}
1107
1108fn layout_block_level_children_sequentially(
1109    layout_context: &LayoutContext,
1110    positioning_context: &mut PositioningContext,
1111    child_boxes: &[ArcRefCell<BlockLevelBox>],
1112    sequential_layout_state: &mut SequentialLayoutState,
1113    placement_state: &mut PlacementState,
1114    ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1115) -> FragmentChildren {
1116    // Because floats are involved, we do layout for this block formatting context in tree
1117    // order without parallelism. This enables mutable access to a `SequentialLayoutState` that
1118    // tracks every float encountered so far (again in tree order).
1119    let fragments = child_boxes
1120        .iter()
1121        .map(|child_box| {
1122            layout_block_level_child(
1123                layout_context,
1124                positioning_context,
1125                &child_box.borrow(),
1126                Some(sequential_layout_state),
1127                placement_state,
1128                ignore_block_margins_for_stretch,
1129                false, /* has_inline_parent */
1130            )
1131        })
1132        .collect();
1133    FragmentChildren::PhysicalDeprecated(fragments)
1134}
1135
1136fn layout_block_level_child(
1137    layout_context: &LayoutContext,
1138    positioning_context: &mut PositioningContext,
1139    child_box: &BlockLevelBox,
1140    mut sequential_layout_state: Option<&mut SequentialLayoutState>,
1141    placement_state: &mut PlacementState,
1142    ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1143    has_inline_parent: bool,
1144) -> Fragment {
1145    let positioning_context_length_before_layout = positioning_context.len();
1146    let mut fragment = child_box.layout(
1147        layout_context,
1148        positioning_context,
1149        placement_state.containing_block,
1150        sequential_layout_state.as_deref_mut(),
1151        Some(CollapsibleWithParentStartMargin(
1152            placement_state.next_in_flow_margin_collapses_with_parent_start_margin,
1153        )),
1154        ignore_block_margins_for_stretch,
1155        has_inline_parent,
1156    );
1157
1158    placement_state.place_fragment_and_update_baseline(&mut fragment, sequential_layout_state);
1159    if let Some(rect) = fragment.base().map(|base| base.rect()) {
1160        positioning_context.adjust_static_position_of_hoisted_fragments(
1161            &LogicalRect::from_physical_deprecated(rect, placement_state.containing_block),
1162            placement_state.containing_block.style.writing_mode,
1163            positioning_context_length_before_layout,
1164        );
1165    }
1166
1167    fragment
1168}
1169
1170impl BlockLevelBox {
1171    #[expect(clippy::too_many_arguments)]
1172    fn layout(
1173        &self,
1174        layout_context: &LayoutContext,
1175        positioning_context: &mut PositioningContext,
1176        containing_block: &ContainingBlock,
1177        sequential_layout_state: Option<&mut SequentialLayoutState>,
1178        collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
1179        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1180        has_inline_parent: bool,
1181    ) -> Fragment {
1182        let fragment = match self {
1183            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
1184                Fragment::Box(
1185                    same_formatting_context_block.layout_in_flow_non_replaced_block_level_cached(
1186                        layout_context,
1187                        positioning_context,
1188                        containing_block,
1189                        sequential_layout_state,
1190                        collapsible_with_parent_start_margin,
1191                        ignore_block_margins_for_stretch,
1192                        has_inline_parent,
1193                    ),
1194                )
1195            },
1196            BlockLevelBox::Independent(independent) => Fragment::Box(
1197                positioning_context
1198                    .layout_maybe_position_relative_fragment(
1199                        layout_context,
1200                        containing_block,
1201                        &independent.base,
1202                        |positioning_context| {
1203                            independent.layout_in_flow_block_level(
1204                                layout_context,
1205                                positioning_context,
1206                                containing_block,
1207                                sequential_layout_state,
1208                                ignore_block_margins_for_stretch,
1209                                has_inline_parent,
1210                            )
1211                        },
1212                    )
1213                    .into(),
1214            ),
1215            BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(box_) => {
1216                // The static position of zero here is incorrect, however we do not know
1217                // the correct positioning until later, in place_block_level_fragment, and
1218                // this value will be adjusted there.
1219                let hoisted_box = AbsolutelyPositionedBox::to_hoisted(
1220                    box_.clone(),
1221                    // This is incorrect, however we do not know the correct positioning
1222                    // until later, in PlacementState::place_fragment, and this value will be
1223                    // adjusted there
1224                    StaticPositionRect::default(),
1225                    LogicalVec2 {
1226                        inline: AlignFlags::START,
1227                        block: AlignFlags::START,
1228                    },
1229                    containing_block.style.writing_mode,
1230                );
1231                let hoisted_fragment = hoisted_box.fragment.clone();
1232                positioning_context.push(hoisted_box);
1233                Fragment::AbsoluteOrFixedPositionedPlaceholder(hoisted_fragment)
1234            },
1235            BlockLevelBox::OutOfFlowFloatBox(float_box) => Fragment::Float(
1236                float_box
1237                    .layout(layout_context, positioning_context, containing_block)
1238                    .into(),
1239            ),
1240            BlockLevelBox::OutsideMarker(outside_marker) => {
1241                outside_marker.layout(layout_context, containing_block, positioning_context)
1242            },
1243        };
1244
1245        self.with_base(|base| base.set_fragment(fragment.clone()));
1246
1247        fragment
1248    }
1249
1250    fn inline_content_sizes(
1251        &self,
1252        layout_context: &LayoutContext,
1253        constraint_space: &ConstraintSpace,
1254    ) -> InlineContentSizesResult {
1255        let independent_formatting_context = match self {
1256            BlockLevelBox::Independent(independent) => independent,
1257            BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(box_) => &box_.borrow().context,
1258            BlockLevelBox::OutOfFlowFloatBox(float_box) => &float_box.contents,
1259            BlockLevelBox::OutsideMarker(outside_marker) => &outside_marker.context,
1260            BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) => {
1261                return same_formatting_context_block
1262                    .inline_content_sizes(layout_context, constraint_space);
1263            },
1264        };
1265        independent_formatting_context.inline_content_sizes(layout_context, constraint_space)
1266    }
1267}
1268
1269impl IndependentFormattingContext {
1270    /// Lay out an in-flow block-level box that establishes an independent
1271    /// formatting context in its containing formatting context.
1272    ///
1273    /// - <https://drafts.csswg.org/css2/visudet.html#blockwidth>
1274    /// - <https://drafts.csswg.org/css2/visudet.html#block-replaced-width>
1275    /// - <https://drafts.csswg.org/css2/visudet.html#normal-block>
1276    /// - <https://drafts.csswg.org/css2/visudet.html#inline-replaced-height>
1277    pub(crate) fn layout_in_flow_block_level(
1278        &self,
1279        layout_context: &LayoutContext,
1280        positioning_context: &mut PositioningContext,
1281        containing_block: &ContainingBlock,
1282        sequential_layout_state: Option<&mut SequentialLayoutState>,
1283        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1284        has_inline_parent: bool,
1285    ) -> BoxFragment {
1286        if let Some(sequential_layout_state) = sequential_layout_state {
1287            return self.layout_in_flow_block_level_sequentially(
1288                layout_context,
1289                positioning_context,
1290                containing_block,
1291                sequential_layout_state,
1292                ignore_block_margins_for_stretch,
1293                has_inline_parent,
1294                self,
1295            );
1296        }
1297
1298        let get_inline_content_sizes = |constraint_space: &ConstraintSpace| {
1299            self.inline_content_sizes(layout_context, constraint_space)
1300                .sizes
1301        };
1302        let layout_style = self.layout_style();
1303        let ContainingBlockPaddingAndBorder {
1304            containing_block: containing_block_for_children,
1305            pbm,
1306            block_sizes,
1307            depends_on_block_constraints,
1308            tentative_block_size: _,
1309            block_stretch_size,
1310            justify_self,
1311            preferred_aspect_ratio,
1312            automatic_block_size,
1313        } = solve_containing_block_padding_and_border_for_in_flow_box(
1314            layout_context,
1315            containing_block,
1316            &layout_style,
1317            get_inline_content_sizes,
1318            ignore_block_margins_for_stretch,
1319            &self.base,
1320            Some(self),
1321            has_inline_parent,
1322        );
1323
1324        let lazy_block_size = LazySize::new(
1325            &block_sizes,
1326            LogicalAxis::Block,
1327            automatic_block_size,
1328            Au::zero,
1329            block_stretch_size,
1330            layout_style.is_table(),
1331        );
1332
1333        let layout = self.layout(
1334            layout_context,
1335            positioning_context,
1336            &containing_block_for_children,
1337            containing_block,
1338            preferred_aspect_ratio,
1339            &lazy_block_size,
1340        );
1341
1342        let inline_size = layout
1343            .content_inline_size_for_table
1344            .unwrap_or(containing_block_for_children.inline_size());
1345        let block_size = lazy_block_size.resolve(|| layout.content_block_size);
1346
1347        let ResolvedMargins {
1348            margin,
1349            effective_margin_inline_start,
1350        } = solve_margins(containing_block, &pbm, inline_size, justify_self);
1351
1352        let content_rect = LogicalRect {
1353            start_corner: LogicalVec2 {
1354                block: pbm.padding.block_start + pbm.border.block_start,
1355                inline: pbm.padding.inline_start +
1356                    pbm.border.inline_start +
1357                    effective_margin_inline_start,
1358            },
1359            size: LogicalVec2 {
1360                block: block_size,
1361                inline: inline_size,
1362            },
1363        };
1364
1365        let block_margins_collapsed_with_children = CollapsedBlockMargins::from_margin(&margin);
1366        let containing_block_writing_mode = containing_block.style.writing_mode;
1367
1368        let mut base_fragment_info = self.base.base_fragment_info;
1369        if depends_on_block_constraints {
1370            base_fragment_info.flags.insert(
1371                FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
1372            );
1373        }
1374        BoxFragment::new(
1375            base_fragment_info,
1376            self.base.style.clone(),
1377            layout.fragments,
1378            content_rect.as_physical_deprecated(containing_block),
1379            pbm.padding.to_physical(containing_block_writing_mode),
1380            pbm.border.to_physical(containing_block_writing_mode),
1381            margin.to_physical(containing_block_writing_mode),
1382            layout.specific_layout_info,
1383        )
1384        .with_baselines(layout.baselines)
1385        .with_block_level_layout_info(block_margins_collapsed_with_children, None)
1386    }
1387
1388    /// Lay out a normal in flow non-replaced block that establishes an independent
1389    /// formatting context in its containing formatting context but handling sequential
1390    /// layout concerns, such clearing and placing the content next to floats.
1391    #[expect(clippy::too_many_arguments)]
1392    fn layout_in_flow_block_level_sequentially(
1393        &self,
1394        layout_context: &LayoutContext<'_>,
1395        positioning_context: &mut PositioningContext,
1396        containing_block: &ContainingBlock<'_>,
1397        sequential_layout_state: &mut SequentialLayoutState,
1398        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1399        has_inline_parent: bool,
1400        context: &IndependentFormattingContext,
1401    ) -> BoxFragment {
1402        let style = &self.base.style;
1403        let containing_block_writing_mode = containing_block.style.writing_mode;
1404        let ContentBoxSizesAndPBM {
1405            content_box_sizes,
1406            pbm,
1407            depends_on_block_constraints,
1408            ..
1409        } = self
1410            .layout_style()
1411            .content_box_sizes_and_padding_border_margin(&containing_block.into());
1412
1413        let (margin_block_start, margin_block_end) =
1414            solve_block_margins_for_in_flow_block_level(&pbm);
1415        let collapsed_margin_block_start = CollapsedMargin::new(margin_block_start);
1416
1417        // From https://drafts.csswg.org/css2/#floats:
1418        // "The border box of a table, a block-level replaced element, or an element in
1419        //  the normal flow that establishes a new block formatting context (such as an
1420        //  element with overflow other than visible) must not overlap the margin box of
1421        //  any floats in the same block formatting context as the element itself. If
1422        //  necessary, implementations should clear the said element by placing it below
1423        //  any preceding floats, but may place it adjacent to such floats if there is
1424        //  sufficient space. They may even make the border box of said element narrower
1425        //  than defined by section 10.3.3. CSS 2 does not define when a UA may put said
1426        //  element next to the float or by how much said element may become narrower."
1427        let mut content_size;
1428        let mut layout;
1429        let mut placement_rect;
1430
1431        // First compute the clear position required by the 'clear' property.
1432        // The code below may then add extra clearance when the element can't fit
1433        // next to floats not covered by 'clear'.
1434        let clear_position = sequential_layout_state.calculate_clear_position(
1435            Clear::from_style_and_container_writing_mode(style, containing_block_writing_mode),
1436            &collapsed_margin_block_start,
1437        );
1438        let ceiling = clear_position.unwrap_or_else(|| {
1439            sequential_layout_state.position_without_clearance(&collapsed_margin_block_start)
1440        });
1441
1442        // Then compute a tentative block size.
1443        let pbm_sums = pbm.sums_auto_is_zero(ignore_block_margins_for_stretch);
1444        let block_stretch_size = containing_block.block_stretch_size(pbm_sums.block);
1445        let automatic_block_size = automatic_block_size(layout_context, &self.base);
1446        let is_table = self.is_table();
1447        let preferred_aspect_ratio = self.preferred_aspect_ratio(&pbm.padding_border_sums);
1448        let skippable_for_block_percentage_quirk =
1449            skippable_for_block_percentage_quirk(layout_context, &context.base, Some(context));
1450
1451        #[derive(Default)]
1452        struct Cache {
1453            min_block_size: Au,
1454            max_block_size: Option<Au>,
1455            tentative_block_size: SizeConstraint,
1456            has_quirky_block_size: bool,
1457            depends_on_stretch_size: bool,
1458        }
1459        let mut cache = Cache {
1460            depends_on_stretch_size: true,
1461            ..Default::default()
1462        };
1463
1464        let update_cache = |cache: &mut Cache, stretch_size| {
1465            let tentative_block_content_size = self
1466                .tentative_block_content_size_with_dependency(preferred_aspect_ratio, stretch_size);
1467            let (preferred_block_size, min_block_size, max_block_size, depends_on_stretch_size) =
1468                if let Some(result) = tentative_block_content_size {
1469                    let (block_content_size, depends_on_stretch_size) = result;
1470                    let (preferred, min, max) = content_box_sizes.block.resolve_each(
1471                        automatic_block_size,
1472                        Au::zero,
1473                        block_stretch_size,
1474                        || block_content_size,
1475                        is_table,
1476                    );
1477                    (Some(preferred), min, max, depends_on_stretch_size)
1478                } else {
1479                    let (preferred, min, max) = content_box_sizes.block.resolve_each_extrinsic(
1480                        automatic_block_size,
1481                        Au::zero(),
1482                        block_stretch_size,
1483                    );
1484                    (preferred, min, max, false)
1485                };
1486            cache.min_block_size = min_block_size;
1487            cache.max_block_size = max_block_size;
1488            cache.tentative_block_size =
1489                SizeConstraint::new(preferred_block_size, min_block_size, max_block_size);
1490            cache.has_quirky_block_size = false;
1491            if skippable_for_block_percentage_quirk {
1492                cache.has_quirky_block_size = !cache.tentative_block_size.is_definite();
1493                cache
1494                    .tentative_block_size
1495                    .replace_if_indefinite_with(containing_block.maybe_quirky_block_size());
1496            }
1497            cache.depends_on_stretch_size = depends_on_stretch_size;
1498        };
1499
1500        // With the tentative block size we can compute the inline min/max-content sizes.
1501        let get_inline_content_sizes = |cache: &Cache| {
1502            let constraint_space = if cache.has_quirky_block_size {
1503                ConstraintSpace::new_quirky(
1504                    cache.tentative_block_size,
1505                    style,
1506                    preferred_aspect_ratio,
1507                )
1508            } else {
1509                ConstraintSpace::new(cache.tentative_block_size, style, preferred_aspect_ratio)
1510            };
1511            self.inline_content_sizes(layout_context, &constraint_space)
1512                .sizes
1513        };
1514
1515        let justify_self = resolve_justify_self(style, containing_block.style, has_inline_parent);
1516        let automatic_inline_size = automatic_inline_size(justify_self, Some(self));
1517        let compute_inline_size = |cache: &mut Cache, stretch_size| {
1518            let stretch_size = Some(stretch_size);
1519            if cache.depends_on_stretch_size {
1520                update_cache(cache, stretch_size);
1521            }
1522            content_box_sizes.inline.resolve(
1523                LogicalAxis::Inline,
1524                automatic_inline_size,
1525                Au::zero,
1526                stretch_size,
1527                || get_inline_content_sizes(cache),
1528                is_table,
1529            )
1530        };
1531
1532        let get_lazy_block_size = || {
1533            LazySize::new(
1534                &content_box_sizes.block,
1535                LogicalAxis::Block,
1536                automatic_block_size,
1537                Au::zero,
1538                block_stretch_size,
1539                is_table,
1540            )
1541        };
1542
1543        // The final inline size can depend on the available space, which depends on where
1544        // we are placing the box, since floats reduce the available space.
1545        // Here we assume that `compute_inline_size()` is a monotonically increasing function
1546        // with respect to the available space. Therefore, if we get the same result for 0
1547        // and for MAX_AU, it means that the function is constant.
1548        // TODO: `compute_inline_size()` may not be monotonic with `calc-size()`. For example,
1549        // `calc-size(stretch, (1px / (size + 1px) + sign(size)) * 1px)` would result in 1px
1550        // both when the available space is zero and infinity, but it's not constant.
1551        let inline_size_with_max_available_space = compute_inline_size(&mut cache, MAX_AU);
1552        let inline_size_with_no_available_space = compute_inline_size(&mut cache, Au::zero());
1553        if inline_size_with_no_available_space == inline_size_with_max_available_space {
1554            // If the inline size doesn't depend on the available inline space, we can just
1555            // compute it with an available inline space of zero. Then, after layout we can
1556            // compute the block size, and finally place among floats.
1557            let inline_size = inline_size_with_no_available_space;
1558            let lazy_block_size = get_lazy_block_size();
1559            layout = self.layout(
1560                layout_context,
1561                positioning_context,
1562                &ContainingBlock {
1563                    // `cache.tentative_block_size` can only depend on the inline stretch size
1564                    // for replaced elements, whose layout doesn't use the block size of the
1565                    // containing block for children.
1566                    size: if cache.has_quirky_block_size {
1567                        ContainingBlockSize::new_quirky(inline_size, cache.tentative_block_size)
1568                    } else {
1569                        ContainingBlockSize::new(inline_size, cache.tentative_block_size)
1570                    },
1571                    style,
1572                },
1573                containing_block,
1574                preferred_aspect_ratio,
1575                &lazy_block_size,
1576            );
1577
1578            content_size = LogicalVec2 {
1579                block: lazy_block_size.resolve(|| layout.content_block_size),
1580                inline: layout.content_inline_size_for_table.unwrap_or(inline_size),
1581            };
1582
1583            let mut placement = PlacementAmongFloats::new(
1584                &sequential_layout_state.floats,
1585                ceiling,
1586                content_size + pbm.padding_border_sums,
1587                &pbm,
1588            );
1589            placement_rect = placement.place();
1590        } else {
1591            // If the inline size depends on the available space, then we need to iterate
1592            // the various placement candidates, resolve both the inline and block sizes
1593            // on each one placement area, and then check if the box actually fits it.
1594            // As an optimization, we first compute a lower bound of the final box size,
1595            // and skip placement candidates where not even the lower bound would fit.
1596            let minimum_size_of_block = LogicalVec2 {
1597                // For the lower bound of the inline size, simply assume no available space.
1598                // TODO: this won't work for things like `calc-size(stretch, 100px - size)`,
1599                // which should result in a bigger size when the available space gets smaller.
1600                inline: inline_size_with_no_available_space,
1601                // For the lower bound of the block size, also use the cached data that was
1602                // computed with no inline available space. If there is a dependency, it will
1603                // be monotonically increasing.
1604                // TODO: won't work e.g. for `block-size: calc-size(max-content, 100px - size)`
1605                // on a stretchable replaced element with an aspect ratio of 1/1: when the
1606                // inline available space is 0, it will resolve to 100px, but for 100px it
1607                // will resolve to 0.
1608                block: match cache.tentative_block_size {
1609                    // If we were able to resolve the preferred and maximum block sizes,
1610                    // use the tentative block size (it takes the 3 sizes into account).
1611                    SizeConstraint::Definite(size) if cache.max_block_size.is_some() => size,
1612                    // Oherwise the preferred or maximum block size might end up being zero,
1613                    // so can only rely on the minimum block size.
1614                    _ => cache.min_block_size,
1615                },
1616            } + pbm.padding_border_sums;
1617            let mut placement = PlacementAmongFloats::new(
1618                &sequential_layout_state.floats,
1619                ceiling,
1620                minimum_size_of_block,
1621                &pbm,
1622            );
1623
1624            loop {
1625                // First try to place the block using the minimum size as the object size.
1626                placement_rect = placement.place();
1627
1628                // PlacementAmongFloats should guarantee that the inline size of the placement rect
1629                // is big enough, but that may fail when dealing with huge sizes that need to be
1630                // saturated to MAX_AU. So floor by zero, see #49235.
1631                let inline_stretch_size =
1632                    Au::zero().max(placement_rect.size.inline - pbm.padding_border_sums.inline);
1633                let proposed_inline_size = compute_inline_size(&mut cache, inline_stretch_size);
1634
1635                // Now lay out the block using the inline size we calculated from the placement.
1636                // Later we'll check to see if the resulting block size is compatible with the
1637                // placement.
1638                let positioning_context_length = positioning_context.len();
1639                let lazy_block_size = get_lazy_block_size();
1640                layout = self.layout(
1641                    layout_context,
1642                    positioning_context,
1643                    &ContainingBlock {
1644                        size: if cache.has_quirky_block_size {
1645                            ContainingBlockSize::new_quirky(
1646                                proposed_inline_size,
1647                                cache.tentative_block_size,
1648                            )
1649                        } else {
1650                            ContainingBlockSize::new(
1651                                proposed_inline_size,
1652                                cache.tentative_block_size,
1653                            )
1654                        },
1655                        style,
1656                    },
1657                    containing_block,
1658                    preferred_aspect_ratio,
1659                    &lazy_block_size,
1660                );
1661
1662                let inline_size = if let Some(inline_size) = layout.content_inline_size_for_table {
1663                    // This is a table that ended up being smaller than predicted because of
1664                    // collapsed columns. Note we don't backtrack to consider areas that we
1665                    // previously thought weren't big enough.
1666                    // TODO: Should `minimum_size_of_block.inline` be zero for tables?
1667                    debug_assert!(inline_size < proposed_inline_size);
1668                    inline_size
1669                } else {
1670                    proposed_inline_size
1671                };
1672                content_size = LogicalVec2 {
1673                    block: lazy_block_size.resolve(|| layout.content_block_size),
1674                    inline: inline_size,
1675                };
1676
1677                // Now we know the block size of this attempted layout of a box with block
1678                // size of auto. Try to fit it into our precalculated placement among the
1679                // floats. If it fits, then we can stop trying layout candidates.
1680                if placement.try_to_expand_for_auto_block_size(
1681                    content_size.block + pbm.padding_border_sums.block,
1682                    &placement_rect.size,
1683                ) {
1684                    break;
1685                }
1686
1687                // The previous attempt to lay out this independent formatting context
1688                // among the floats did not work, so we must unhoist any boxes from that
1689                // attempt.
1690                positioning_context.truncate(&positioning_context_length);
1691            }
1692        }
1693
1694        // Only set clearance if we would have cleared or the placement among floats moves
1695        // the block further in the block direction. These two situations are the ones that
1696        // prevent margin collapse.
1697        let has_clearance = clear_position.is_some() || placement_rect.start_corner.block > ceiling;
1698        let clearance = has_clearance.then(|| {
1699            placement_rect.start_corner.block -
1700                sequential_layout_state
1701                    .position_with_zero_clearance(&collapsed_margin_block_start)
1702        });
1703
1704        let ((margin_inline_start, margin_inline_end), effective_margin_inline_start) =
1705            solve_inline_margins_avoiding_floats(
1706                sequential_layout_state,
1707                containing_block,
1708                &pbm,
1709                content_size.inline + pbm.padding_border_sums.inline,
1710                placement_rect,
1711                justify_self,
1712            );
1713
1714        let margin = LogicalSides {
1715            inline_start: margin_inline_start,
1716            inline_end: margin_inline_end,
1717            block_start: margin_block_start,
1718            block_end: margin_block_end,
1719        };
1720
1721        // Clearance prevents margin collapse between this block and previous ones,
1722        // so in that case collapse margins before adjoining them below.
1723        if clearance.is_some() {
1724            sequential_layout_state.commit_margin();
1725        }
1726        sequential_layout_state.adjoin_assign(&collapsed_margin_block_start);
1727
1728        // Margins can never collapse into independent formatting contexts.
1729        sequential_layout_state.commit_margin();
1730        sequential_layout_state.advance_block_position(
1731            pbm.padding_border_sums.block + content_size.block + clearance.unwrap_or_else(Au::zero),
1732        );
1733        sequential_layout_state.adjoin_assign(&CollapsedMargin::new(margin.block_end));
1734
1735        let content_rect = LogicalRect {
1736            start_corner: LogicalVec2 {
1737                block: pbm.padding.block_start +
1738                    pbm.border.block_start +
1739                    clearance.unwrap_or_else(Au::zero),
1740                inline: pbm.padding.inline_start +
1741                    pbm.border.inline_start +
1742                    effective_margin_inline_start,
1743            },
1744            size: content_size,
1745        };
1746
1747        let mut base_fragment_info = self.base.base_fragment_info;
1748        if depends_on_block_constraints {
1749            base_fragment_info.flags.insert(
1750                FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
1751            );
1752        }
1753
1754        BoxFragment::new(
1755            base_fragment_info,
1756            style.clone(),
1757            layout.fragments,
1758            content_rect.as_physical_deprecated(containing_block),
1759            pbm.padding.to_physical(containing_block_writing_mode),
1760            pbm.border.to_physical(containing_block_writing_mode),
1761            margin.to_physical(containing_block_writing_mode),
1762            layout.specific_layout_info,
1763        )
1764        .with_baselines(layout.baselines)
1765        .with_block_level_layout_info(CollapsedBlockMargins::from_margin(&margin), clearance)
1766    }
1767}
1768
1769struct ContainingBlockPaddingAndBorder<'a> {
1770    containing_block: ContainingBlock<'a>,
1771    pbm: PaddingBorderMargin,
1772    block_sizes: Sizes,
1773    depends_on_block_constraints: bool,
1774    tentative_block_size: SizeConstraint,
1775    block_stretch_size: Option<Au>,
1776    justify_self: AlignFlags,
1777    preferred_aspect_ratio: Option<AspectRatio>,
1778    automatic_block_size: Size<Au>,
1779}
1780
1781struct ResolvedMargins {
1782    /// Used value for the margin properties, as exposed in getComputedStyle().
1783    pub margin: LogicalSides<Au>,
1784
1785    /// Distance between the border box and the containing block on the inline-start side.
1786    /// This is typically the same as the inline-start margin, but can be greater when
1787    /// the box is justified within the free space in the containing block.
1788    /// The reason we aren't just adjusting the used margin-inline-start is that
1789    /// this shouldn't be observable via getComputedStyle().
1790    /// <https://drafts.csswg.org/css-align/#justify-self-property>
1791    pub effective_margin_inline_start: Au,
1792}
1793
1794/// Given the style for an in-flow box and its containing block, determine the containing
1795/// block for its children.
1796/// Note that in the presence of floats, this shouldn't be used for a block-level box
1797/// that establishes an independent formatting context (or is replaced), since the
1798/// inline size could then be incorrect.
1799#[expect(clippy::too_many_arguments)]
1800fn solve_containing_block_padding_and_border_for_in_flow_box<'a>(
1801    layout_context: &LayoutContext,
1802    containing_block: &ContainingBlock<'_>,
1803    layout_style: &'a LayoutStyle,
1804    get_inline_content_sizes: impl FnOnce(&ConstraintSpace) -> ContentSizes,
1805    ignore_block_margins_for_stretch: LogicalSides1D<bool>,
1806    base: &LayoutBoxBase,
1807    context: Option<&IndependentFormattingContext>,
1808    has_inline_parent: bool,
1809) -> ContainingBlockPaddingAndBorder<'a> {
1810    let style = layout_style.style();
1811    if matches!(style.pseudo(), Some(PseudoElement::ServoAnonymousBox)) {
1812        // <https://drafts.csswg.org/css2/#anonymous-block-level>
1813        // > Anonymous block boxes are ignored when resolving percentage values that would
1814        // > refer to it: the closest non-anonymous ancestor box is used instead.
1815        let containing_block_for_children = ContainingBlock {
1816            size: containing_block.size.clone(),
1817            style,
1818        };
1819        // <https://drafts.csswg.org/css2/#anonymous-block-level>
1820        // > Non-inherited properties have their initial value.
1821        return ContainingBlockPaddingAndBorder {
1822            containing_block: containing_block_for_children,
1823            pbm: PaddingBorderMargin::zero(),
1824            block_sizes: Sizes::default(),
1825            depends_on_block_constraints: false,
1826            tentative_block_size: SizeConstraint::default(),
1827            // The block stretch size may actually be definite, but it should be irrelevant
1828            // since the sizing properties are set to their initial value.
1829            block_stretch_size: None,
1830            // The initial `justify-self` is `auto`, but use `normal` (behaving as `stretch`).
1831            // This is being discussed in <https://github.com/w3c/csswg-drafts/issues/11461>.
1832            justify_self: AlignFlags::NORMAL,
1833            preferred_aspect_ratio: None,
1834            automatic_block_size: Size::FitContent,
1835        };
1836    }
1837
1838    let ContentBoxSizesAndPBM {
1839        content_box_sizes,
1840        pbm,
1841        depends_on_block_constraints,
1842        ..
1843    } = layout_style.content_box_sizes_and_padding_border_margin(&containing_block.into());
1844
1845    let pbm_sums = pbm.sums_auto_is_zero(ignore_block_margins_for_stretch);
1846    let inline_stretch_size = containing_block.inline_stretch_size(pbm_sums.inline);
1847    let block_stretch_size = containing_block.block_stretch_size(pbm_sums.block);
1848    let automatic_block_size = automatic_block_size(layout_context, base);
1849
1850    // TODO: support preferred aspect ratios on boxes that don't establish an independent
1851    // formatting context.
1852    let preferred_aspect_ratio =
1853        context.and_then(|context| context.preferred_aspect_ratio(&pbm.padding_border_sums));
1854    let is_table = layout_style.is_table();
1855
1856    // https://drafts.csswg.org/css2/#the-height-property
1857    // https://drafts.csswg.org/css2/visudet.html#min-max-heights
1858    let tentative_block_content_size = context.and_then(|context| {
1859        context.tentative_block_content_size(preferred_aspect_ratio, inline_stretch_size)
1860    });
1861    let tentative_block_size = if let Some(block_content_size) = tentative_block_content_size {
1862        SizeConstraint::Definite(content_box_sizes.block.resolve(
1863            LogicalAxis::Block,
1864            automatic_block_size,
1865            Au::zero,
1866            block_stretch_size,
1867            || block_content_size,
1868            is_table,
1869        ))
1870    } else {
1871        content_box_sizes.block.resolve_extrinsic(
1872            automatic_block_size,
1873            Au::zero(),
1874            block_stretch_size,
1875        )
1876    };
1877    let mut block_size_for_children = tentative_block_size;
1878    let mut has_quirky_block_size = false;
1879    if skippable_for_block_percentage_quirk(layout_context, base, context) {
1880        has_quirky_block_size = !tentative_block_size.is_definite();
1881        block_size_for_children
1882            .replace_if_indefinite_with(containing_block.maybe_quirky_block_size());
1883    }
1884
1885    // https://drafts.csswg.org/css2/#the-width-property
1886    // https://drafts.csswg.org/css2/visudet.html#min-max-widths
1887    let get_inline_content_sizes = || {
1888        get_inline_content_sizes(&if has_quirky_block_size {
1889            ConstraintSpace::new_quirky(block_size_for_children, style, preferred_aspect_ratio)
1890        } else {
1891            ConstraintSpace::new(block_size_for_children, style, preferred_aspect_ratio)
1892        })
1893    };
1894    let justify_self = resolve_justify_self(style, containing_block.style, has_inline_parent);
1895    let inline_size = content_box_sizes.inline.resolve(
1896        LogicalAxis::Inline,
1897        automatic_inline_size(justify_self, context),
1898        Au::zero,
1899        inline_stretch_size,
1900        get_inline_content_sizes,
1901        is_table,
1902    );
1903
1904    let containing_block_for_children = ContainingBlock {
1905        size: if has_quirky_block_size {
1906            ContainingBlockSize::new_quirky(inline_size, block_size_for_children)
1907        } else {
1908            ContainingBlockSize::new(inline_size, block_size_for_children)
1909        },
1910        style,
1911    };
1912    // TODO: https://drafts.csswg.org/css-writing-modes/#orthogonal-flows
1913    ContainingBlockPaddingAndBorder {
1914        containing_block: containing_block_for_children,
1915        pbm,
1916        block_sizes: content_box_sizes.block,
1917        depends_on_block_constraints,
1918        tentative_block_size,
1919        block_stretch_size,
1920        justify_self,
1921        preferred_aspect_ratio,
1922        automatic_block_size,
1923    }
1924}
1925
1926/// Given the containing block and size of an in-flow box, determine the margins.
1927/// Note that in the presence of floats, this shouldn't be used for a block-level box
1928/// that establishes an independent formatting context (or is replaced), since the
1929/// margins could then be incorrect.
1930fn solve_margins(
1931    containing_block: &ContainingBlock<'_>,
1932    pbm: &PaddingBorderMargin,
1933    inline_size: Au,
1934    justify_self: AlignFlags,
1935) -> ResolvedMargins {
1936    let (inline_margins, effective_margin_inline_start) =
1937        solve_inline_margins_for_in_flow_block_level(
1938            containing_block,
1939            pbm,
1940            inline_size,
1941            justify_self,
1942        );
1943    let block_margins = solve_block_margins_for_in_flow_block_level(pbm);
1944    ResolvedMargins {
1945        margin: LogicalSides {
1946            inline_start: inline_margins.0,
1947            inline_end: inline_margins.1,
1948            block_start: block_margins.0,
1949            block_end: block_margins.1,
1950        },
1951        effective_margin_inline_start,
1952    }
1953}
1954
1955/// Resolves 'auto' margins of an in-flow block-level box in the block axis.
1956/// <https://drafts.csswg.org/css2/#normal-block>
1957/// <https://drafts.csswg.org/css2/#block-root-margin>
1958fn solve_block_margins_for_in_flow_block_level(pbm: &PaddingBorderMargin) -> (Au, Au) {
1959    (
1960        pbm.margin.block_start.auto_is(Au::zero),
1961        pbm.margin.block_end.auto_is(Au::zero),
1962    )
1963}
1964
1965/// Resolves the `justify-self` value, preserving flags.
1966fn resolve_justify_self(
1967    style: &ComputedValues,
1968    containing_block_style: &ComputedValues,
1969    has_inline_parent: bool,
1970) -> AlignFlags {
1971    // `justify-self: auto` behaves as the computed `justify-items` value of the parent box.
1972    // The parent box is generally the containing block, but it can also be an inline box.
1973    // In that case, since `justify-items` doesn't apply to inline boxes, we need to treat
1974    // `justify-self: auto` as `normal`.
1975    // See the resolution in <https://github.com/w3c/csswg-drafts/issues/11462>.
1976    let alignment = match style.get_justify_self().0 {
1977        AlignFlags::AUTO if has_inline_parent => AlignFlags::NORMAL,
1978        AlignFlags::AUTO => containing_block_style.get_justify_items().computed.0.0,
1979        alignment => alignment,
1980    };
1981    let is_ltr = |style: &ComputedValues| style.writing_mode.line_left_is_inline_start();
1982    let alignment_value = match alignment.value() {
1983        AlignFlags::LEFT if is_ltr(containing_block_style) => AlignFlags::START,
1984        AlignFlags::LEFT => AlignFlags::END,
1985        AlignFlags::RIGHT if is_ltr(containing_block_style) => AlignFlags::END,
1986        AlignFlags::RIGHT => AlignFlags::START,
1987        AlignFlags::SELF_START if is_ltr(containing_block_style) == is_ltr(style) => {
1988            AlignFlags::START
1989        },
1990        AlignFlags::SELF_START => AlignFlags::END,
1991        AlignFlags::SELF_END if is_ltr(containing_block_style) == is_ltr(style) => AlignFlags::END,
1992        AlignFlags::SELF_END => AlignFlags::START,
1993        alignment_value => alignment_value,
1994    };
1995    alignment.flags() | alignment_value
1996}
1997
1998/// Determines the automatic size for the inline axis of an in-flow block-level box.
1999/// <https://drafts.csswg.org/css-sizing-3/#automatic-size>
2000#[inline]
2001fn automatic_inline_size<T>(
2002    justify_self: AlignFlags,
2003    context: Option<&IndependentFormattingContext>,
2004) -> Size<T> {
2005    let normal_stretches = || {
2006        !context.is_some_and(|context| {
2007            context
2008                .base
2009                .base_fragment_info
2010                .flags
2011                .intersects(FragmentFlags::IS_REPLACED | FragmentFlags::IS_WIDGET) ||
2012                context.is_table()
2013        })
2014    };
2015    match justify_self {
2016        AlignFlags::STRETCH => Size::Stretch,
2017        AlignFlags::NORMAL if normal_stretches() => Size::Stretch,
2018        _ => Size::FitContent,
2019    }
2020}
2021
2022/// Determines the automatic size for the block axis of an in-flow block-level box.
2023/// <https://drafts.csswg.org/css-sizing-3/#automatic-size>
2024#[inline]
2025fn automatic_block_size<T>(layout_context: &LayoutContext, base: &LayoutBoxBase) -> Size<T> {
2026    // https://quirks.spec.whatwg.org/#the-html-element-fills-the-viewport-quirk
2027    // The spec says to only apply it if the root element is an `html` element,
2028    // but Blink and WebKit ignore that, so do we.
2029    //
2030    // https://quirks.spec.whatwg.org/#the-body-element-fills-the-html-element-quirk
2031    // The spec says to only apply it to the document's body element, so we differ
2032    // from Blink and WebKit which stretch every body element.
2033    //
2034    // Note that Gecko doesn't have these quirks, but then it needs other replacements.
2035    if layout_context.style_context.quirks_mode() == QuirksMode::Quirks &&
2036        base.base_fragment_info.flags.intersects(
2037            FragmentFlags::IS_ROOT_ELEMENT | FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT,
2038        )
2039    {
2040        Size::QuirkyStretch
2041    } else {
2042        Size::FitContent
2043    }
2044}
2045
2046/// Justifies a block-level box, distributing the free space according to `justify-self`.
2047/// Note `<center>` and `<div align>` are implemented via internal 'text-align' values,
2048/// which are also handled here.
2049/// The provided free space should already take margins into account. In particular,
2050/// it should be zero if there is an auto margin.
2051/// <https://drafts.csswg.org/css-align/#justify-block>
2052fn justify_self_alignment(
2053    containing_block: &ContainingBlock,
2054    free_space: Au,
2055    justify_self: AlignFlags,
2056) -> Au {
2057    let mut alignment = justify_self.value();
2058    let is_safe = justify_self.flags() == AlignFlags::SAFE || alignment == AlignFlags::NORMAL;
2059    if is_safe && free_space <= Au::zero() {
2060        alignment = AlignFlags::START
2061    }
2062    match alignment {
2063        AlignFlags::NORMAL => {},
2064        AlignFlags::CENTER => return free_space / 2,
2065        AlignFlags::END => return free_space,
2066        _ => return Au::zero(),
2067    }
2068
2069    // For `justify-self: normal`, fall back to the special 'text-align' values.
2070    let style = containing_block.style;
2071    match style.get_text_align() {
2072        TextAlignKeyword::MozCenter => free_space / 2,
2073        TextAlignKeyword::MozLeft if !style.writing_mode.line_left_is_inline_start() => free_space,
2074        TextAlignKeyword::MozRight if style.writing_mode.line_left_is_inline_start() => free_space,
2075        _ => Au::zero(),
2076    }
2077}
2078
2079/// Resolves 'auto' margins of an in-flow block-level box in the inline axis,
2080/// distributing the free space in the containing block.
2081///
2082/// This is based on CSS2.1 ยง 10.3.3 <https://drafts.csswg.org/css2/#blockwidth>
2083/// but without adjusting the margins in "over-contrained" cases, as mandated by
2084/// <https://drafts.csswg.org/css-align/#justify-block>.
2085///
2086/// Note that in the presence of floats, this shouldn't be used for a block-level box
2087/// that establishes an independent formatting context (or is replaced).
2088///
2089/// In addition to the used margins, it also returns the effective margin-inline-start
2090/// (see ContainingBlockPaddingAndBorder).
2091fn solve_inline_margins_for_in_flow_block_level(
2092    containing_block: &ContainingBlock,
2093    pbm: &PaddingBorderMargin,
2094    inline_size: Au,
2095    justify_self: AlignFlags,
2096) -> ((Au, Au), Au) {
2097    let free_space = containing_block.inline_size() - pbm.padding_border_sums.inline - inline_size;
2098    let mut justification = Au::zero();
2099    let inline_margins = match (pbm.margin.inline_start, pbm.margin.inline_end) {
2100        (AuOrAuto::Auto, AuOrAuto::Auto) => {
2101            let start = Au::zero().max(free_space / 2);
2102            (start, free_space - start)
2103        },
2104        (AuOrAuto::Auto, AuOrAuto::LengthPercentage(end)) => {
2105            (Au::zero().max(free_space - end), end)
2106        },
2107        (AuOrAuto::LengthPercentage(start), AuOrAuto::Auto) => (start, free_space - start),
2108        (AuOrAuto::LengthPercentage(start), AuOrAuto::LengthPercentage(end)) => {
2109            // In the cases above, the free space is zero after taking 'auto' margins into account.
2110            // But here we may still have some free space to perform 'justify-self' alignment.
2111            // This aligns the margin box within the containing block, or in other words,
2112            // aligns the border box within the margin-shrunken containing block.
2113            justification =
2114                justify_self_alignment(containing_block, free_space - start - end, justify_self);
2115            (start, end)
2116        },
2117    };
2118    let effective_margin_inline_start = inline_margins.0 + justification;
2119    (inline_margins, effective_margin_inline_start)
2120}
2121
2122/// Resolves 'auto' margins of an in-flow block-level box in the inline axis
2123/// similarly to |solve_inline_margins_for_in_flow_block_level|. However,
2124/// they align within the provided rect (instead of the containing block),
2125/// to avoid overlapping floats.
2126/// In addition to the used margins, it also returns the effective
2127/// margin-inline-start (see ContainingBlockPaddingAndBorder).
2128/// It may differ from the used inline-start margin if the computed value
2129/// wasn't 'auto' and there are floats to avoid or the box is justified.
2130/// See <https://github.com/w3c/csswg-drafts/issues/9174>
2131fn solve_inline_margins_avoiding_floats(
2132    sequential_layout_state: &SequentialLayoutState,
2133    containing_block: &ContainingBlock,
2134    pbm: &PaddingBorderMargin,
2135    inline_size: Au,
2136    placement_rect: LogicalRect<Au>,
2137    justify_self: AlignFlags,
2138) -> ((Au, Au), Au) {
2139    // PlacementAmongFloats should guarantee that the inline size of the placement rect
2140    // is at least as big as `inline_size`. However, that may fail when dealing with
2141    // huge sizes that need to be saturated to MAX_AU, so floor by zero. See #37312.
2142    let free_space = Au::zero().max(placement_rect.size.inline - inline_size);
2143    let cb_info = &sequential_layout_state.floats.containing_block_info;
2144    let start_adjustment = placement_rect.start_corner.inline - cb_info.inline_start;
2145    let end_adjustment = cb_info.inline_end - placement_rect.max_inline_position();
2146    let mut justification = Au::zero();
2147    let inline_margins = match (pbm.margin.inline_start, pbm.margin.inline_end) {
2148        (AuOrAuto::Auto, AuOrAuto::Auto) => {
2149            let half = free_space / 2;
2150            (start_adjustment + half, end_adjustment + free_space - half)
2151        },
2152        (AuOrAuto::Auto, AuOrAuto::LengthPercentage(end)) => (start_adjustment + free_space, end),
2153        (AuOrAuto::LengthPercentage(start), AuOrAuto::Auto) => (start, end_adjustment + free_space),
2154        (AuOrAuto::LengthPercentage(start), AuOrAuto::LengthPercentage(end)) => {
2155            // The spec says 'justify-self' aligns the margin box within the float-shrunken
2156            // containing block. That's wrong (https://github.com/w3c/csswg-drafts/issues/9963),
2157            // and Blink and WebKit are broken anyways. So we match Gecko instead: this aligns
2158            // the border box within the instersection of the float-shrunken containing-block
2159            // and the margin-shrunken containing-block.
2160            justification = justify_self_alignment(containing_block, free_space, justify_self);
2161            (start, end)
2162        },
2163    };
2164    let effective_margin_inline_start = inline_margins.0.max(start_adjustment) + justification;
2165    (inline_margins, effective_margin_inline_start)
2166}
2167
2168/// State that we maintain when placing blocks.
2169///
2170/// In parallel mode, this placement is done after all child blocks are laid out. In
2171/// sequential mode, this is done right after each block is laid out.
2172struct PlacementState<'container> {
2173    next_in_flow_margin_collapses_with_parent_start_margin: bool,
2174    last_in_flow_margin_collapses_with_parent_end_margin: bool,
2175    start_margin: CollapsedMargin,
2176    current_margin: CollapsedMargin,
2177    current_block_direction_position: Au,
2178    inflow_baselines: Baselines,
2179    is_inline_block_context: bool,
2180
2181    /// If this [`PlacementState`] is laying out a list item with an outside marker. Record the
2182    /// block size of that marker, because the content block size of the list item needs to be at
2183    /// least as tall as the marker size -- even though the marker doesn't advance the block
2184    /// position of the placement.
2185    marker_block_size: Option<Au>,
2186
2187    /// The [`ContainingBlock`] of the container into which this [`PlacementState`] is laying out
2188    /// fragments. This is used to convert between physical and logical geometry.
2189    containing_block: &'container ContainingBlock<'container>,
2190}
2191
2192impl<'container> PlacementState<'container> {
2193    fn new(
2194        collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
2195        containing_block: &'container ContainingBlock<'container>,
2196    ) -> PlacementState<'container> {
2197        let is_inline_block_context =
2198            containing_block.style.get_box().get_display() == &Display::InlineBlock;
2199        PlacementState {
2200            next_in_flow_margin_collapses_with_parent_start_margin:
2201                collapsible_with_parent_start_margin.0,
2202            last_in_flow_margin_collapses_with_parent_end_margin: true,
2203            start_margin: CollapsedMargin::zero(),
2204            current_margin: CollapsedMargin::zero(),
2205            current_block_direction_position: Au::zero(),
2206            inflow_baselines: Baselines::default(),
2207            is_inline_block_context,
2208            marker_block_size: None,
2209            containing_block,
2210        }
2211    }
2212
2213    fn place_fragment_and_update_baseline(
2214        &mut self,
2215        fragment: &mut Fragment,
2216        sequential_layout_state: Option<&mut SequentialLayoutState>,
2217    ) {
2218        self.place_fragment(fragment, sequential_layout_state);
2219
2220        let box_fragment = match fragment {
2221            Fragment::LayoutRoot(..) | Fragment::Box(..) => fragment
2222                .retrieve_box_fragment()
2223                .expect("Should be guaranteed by surrounding check"),
2224            _ => return,
2225        };
2226
2227        // From <https://drafts.csswg.org/css-align-3/#baseline-export>:
2228        // > When finding the first/last baseline set of an inline-block, any baselines
2229        // > contributed by table boxes must be skipped. (This quirk is a legacy behavior from
2230        // > [CSS2].)
2231        if self.is_inline_block_context && box_fragment.is_table_wrapper() {
2232            return;
2233        }
2234
2235        let box_block_offset = LogicalVec2::from_physical_point_deprecated(
2236            &box_fragment.content_rect().origin,
2237            self.containing_block,
2238        )
2239        .block;
2240        let box_fragment_baselines =
2241            box_fragment.baselines(self.containing_block.style.writing_mode);
2242        if let (None, Some(first)) = (self.inflow_baselines.first, box_fragment_baselines.first) {
2243            self.inflow_baselines.first = Some(first + box_block_offset);
2244        }
2245        if let Some(last) = box_fragment_baselines.last {
2246            self.inflow_baselines.last = Some(last + box_block_offset);
2247        }
2248    }
2249
2250    /// Place a single [Fragment] in a block level context using the state so far and
2251    /// information gathered from the [Fragment] itself.
2252    fn place_fragment(
2253        &mut self,
2254        fragment: &mut Fragment,
2255        sequential_layout_state: Option<&mut SequentialLayoutState>,
2256    ) {
2257        match fragment {
2258            Fragment::LayoutRoot(..) | Fragment::Box(..) => {
2259                let fragment = fragment
2260                    .retrieve_box_fragment()
2261                    .expect("Should be guaranteed by surrounding condition");
2262
2263                // If this child is a marker positioned outside of a list item, then record its
2264                // size, but also ensure that it doesn't advance the block position of the placment.
2265                // This ensures item content is placed next to the marker.
2266                //
2267                // This is a pretty big hack because it doesn't properly handle all interactions
2268                // between the marker and the item. For instance the marker should be positioned at
2269                // the baseline of list item content and the first line of the item content should
2270                // be at least as tall as the marker -- not the entire list item itself.
2271                let is_outside_marker = fragment
2272                    .base
2273                    .flags
2274                    .contains(FragmentFlags::IS_OUTSIDE_LIST_ITEM_MARKER);
2275                if is_outside_marker {
2276                    assert!(self.marker_block_size.is_none());
2277                    self.marker_block_size = Some(
2278                        LogicalVec2::from_physical_size(
2279                            &fragment.content_rect().size,
2280                            self.containing_block.style.writing_mode,
2281                        )
2282                        .block,
2283                    );
2284                    return;
2285                }
2286
2287                let BlockLevelLayoutInfo {
2288                    clearance,
2289                    block_margins_collapsed_with_children: fragment_block_margins,
2290                } = *fragment
2291                    .block_level_layout_info
2292                    .clone()
2293                    .expect("A block-level fragment should have a BlockLevelLayoutInfo.");
2294                let mut fragment_block_size = LogicalVec2::from_physical_size(
2295                    &fragment.border_rect().size,
2296                    self.containing_block.style.writing_mode,
2297                )
2298                .block;
2299
2300                // We use `last_in_flow_margin_collapses_with_parent_end_margin` to implement
2301                // this quote from https://drafts.csswg.org/css2/#collapsing-margins
2302                // > If the top and bottom margins of an element with clearance are adjoining,
2303                // > its margins collapse with the adjoining margins of following siblings but that
2304                // > resulting margin does not collapse with the bottom margin of the parent block.
2305                if let Some(clearance) = clearance {
2306                    fragment_block_size += clearance;
2307                    // Margins can't be adjoining if they are separated by clearance.
2308                    // Setting `next_in_flow_margin_collapses_with_parent_start_margin` to false
2309                    // prevents collapsing with the start margin of the parent, and will set
2310                    // `collapsed_through` to false, preventing the parent from collapsing through.
2311                    self.current_block_direction_position += self.current_margin.solve();
2312                    self.current_margin = CollapsedMargin::zero();
2313                    self.next_in_flow_margin_collapses_with_parent_start_margin = false;
2314                    if fragment_block_margins.collapsed_through {
2315                        self.last_in_flow_margin_collapses_with_parent_end_margin = false;
2316                    }
2317                } else if !fragment_block_margins.collapsed_through {
2318                    self.last_in_flow_margin_collapses_with_parent_end_margin = true;
2319                }
2320
2321                if self.next_in_flow_margin_collapses_with_parent_start_margin {
2322                    debug_assert!(self.current_margin.solve().is_zero());
2323                    self.start_margin
2324                        .adjoin_assign(&fragment_block_margins.start);
2325                    if fragment_block_margins.collapsed_through {
2326                        self.start_margin.adjoin_assign(&fragment_block_margins.end);
2327                        return;
2328                    }
2329                    self.next_in_flow_margin_collapses_with_parent_start_margin = false;
2330                } else {
2331                    self.current_margin
2332                        .adjoin_assign(&fragment_block_margins.start);
2333                }
2334
2335                fragment.base.translate_rect(
2336                    LogicalVec2 {
2337                        inline: Au::zero(),
2338                        block: self.current_margin.solve() + self.current_block_direction_position,
2339                    }
2340                    .to_physical_size(self.containing_block.style.writing_mode),
2341                );
2342
2343                if fragment_block_margins.collapsed_through {
2344                    // `fragment_block_size` is typically zero when collapsing through,
2345                    // but we still need to consider it in case there is clearance.
2346                    self.current_block_direction_position += fragment_block_size;
2347                    self.current_margin
2348                        .adjoin_assign(&fragment_block_margins.end);
2349                } else {
2350                    self.current_block_direction_position +=
2351                        self.current_margin.solve() + fragment_block_size;
2352                    self.current_margin = fragment_block_margins.end;
2353                }
2354            },
2355            Fragment::AbsoluteOrFixedPositionedPlaceholder(fragment) => {
2356                // The alignment of absolutes in block flow layout is always "start", so the size of
2357                // the static position rectangle does not matter.
2358                let rect = LogicalRect {
2359                    start_corner: LogicalVec2 {
2360                        block: (self.current_margin.solve() +
2361                            self.current_block_direction_position),
2362                        inline: Au::zero(),
2363                    },
2364                    size: LogicalVec2::zero(),
2365                };
2366                fragment.borrow_mut().original_static_position_rect =
2367                    StaticPositionRect::new(rect, self.containing_block.style.writing_mode);
2368            },
2369            Fragment::Float(box_fragment) => {
2370                let sequential_layout_state = sequential_layout_state
2371                    .expect("Found float fragment without SequentialLayoutState");
2372                let block_offset_from_containing_block_top =
2373                    self.current_block_direction_position + self.current_margin.solve();
2374                sequential_layout_state.place_float_fragment(
2375                    box_fragment,
2376                    self.containing_block,
2377                    self.start_margin,
2378                    block_offset_from_containing_block_top,
2379                );
2380            },
2381            Fragment::Positioning(_) => {},
2382            _ => unreachable!("Unexpected Fragment type encountered during flow layout"),
2383        }
2384    }
2385
2386    fn finish(mut self) -> (Au, CollapsedBlockMargins, Baselines) {
2387        if !self.last_in_flow_margin_collapses_with_parent_end_margin {
2388            self.current_block_direction_position += self.current_margin.solve();
2389            self.current_margin = CollapsedMargin::zero();
2390        }
2391        let (total_block_size, collapsed_through) = match self.marker_block_size {
2392            Some(marker_block_size) => (
2393                self.current_block_direction_position.max(marker_block_size),
2394                // If this is a list item (even empty) with an outside marker, then it
2395                // should not collapse through.
2396                false,
2397            ),
2398            None => (
2399                self.current_block_direction_position,
2400                self.next_in_flow_margin_collapses_with_parent_start_margin,
2401            ),
2402        };
2403
2404        (
2405            total_block_size,
2406            CollapsedBlockMargins {
2407                collapsed_through,
2408                start: self.start_margin,
2409                end: self.current_margin,
2410            },
2411            self.inflow_baselines,
2412        )
2413    }
2414}
2415
2416pub(crate) struct IndependentFloatOrAtomicLayoutResult {
2417    pub fragment: BoxFragment,
2418    pub baselines: Baselines,
2419    pub pbm_sums: LogicalSides<Au>,
2420}
2421
2422impl IndependentFormattingContext {
2423    pub(crate) fn layout_float_or_atomic_inline(
2424        &self,
2425        layout_context: &LayoutContext,
2426        child_positioning_context: &mut PositioningContext,
2427        containing_block: &ContainingBlock,
2428    ) -> IndependentFloatOrAtomicLayoutResult {
2429        let style = self.style();
2430        let container_writing_mode = containing_block.style.writing_mode;
2431        let layout_style = self.layout_style();
2432        let content_box_sizes_and_pbm =
2433            layout_style.content_box_sizes_and_padding_border_margin(&containing_block.into());
2434        let pbm = &content_box_sizes_and_pbm.pbm;
2435        let margin = pbm.margin.auto_is(Au::zero);
2436        let pbm_sums = pbm.padding + pbm.border + margin;
2437        let preferred_aspect_ratio = self.preferred_aspect_ratio(&pbm.padding_border_sums);
2438        let is_table = self.is_table();
2439
2440        let inline_stretch_size = containing_block.inline_stretch_size(pbm_sums.inline_sum());
2441        let block_stretch_size = containing_block.block_stretch_size(pbm_sums.block_sum());
2442
2443        let automatic_block_size = Size::FitContent;
2444        let tentative_block_content_size =
2445            self.tentative_block_content_size(preferred_aspect_ratio, inline_stretch_size);
2446        let mut tentative_block_size =
2447            if let Some(block_content_size) = tentative_block_content_size {
2448                SizeConstraint::Definite(content_box_sizes_and_pbm.content_box_sizes.block.resolve(
2449                    LogicalAxis::Block,
2450                    automatic_block_size,
2451                    Au::zero,
2452                    block_stretch_size,
2453                    || block_content_size,
2454                    is_table,
2455                ))
2456            } else {
2457                content_box_sizes_and_pbm
2458                    .content_box_sizes
2459                    .block
2460                    .resolve_extrinsic(automatic_block_size, Au::zero(), block_stretch_size)
2461            };
2462        let mut has_quirky_block_size = false;
2463        if skippable_for_block_percentage_quirk(layout_context, &self.base, Some(self)) {
2464            has_quirky_block_size = !tentative_block_size.is_definite();
2465            tentative_block_size
2466                .replace_if_indefinite_with(containing_block.maybe_quirky_block_size());
2467        }
2468
2469        let get_content_size = || {
2470            let constraint_space = if has_quirky_block_size {
2471                ConstraintSpace::new_quirky(tentative_block_size, style, preferred_aspect_ratio)
2472            } else {
2473                ConstraintSpace::new(tentative_block_size, style, preferred_aspect_ratio)
2474            };
2475            self.inline_content_sizes(layout_context, &constraint_space)
2476                .sizes
2477        };
2478
2479        let inline_size = content_box_sizes_and_pbm.content_box_sizes.inline.resolve(
2480            LogicalAxis::Inline,
2481            automatic_block_size,
2482            Au::zero,
2483            inline_stretch_size,
2484            get_content_size,
2485            is_table,
2486        );
2487
2488        let containing_block_for_children = ContainingBlock {
2489            size: if has_quirky_block_size {
2490                ContainingBlockSize::new_quirky(inline_size, tentative_block_size)
2491            } else {
2492                ContainingBlockSize::new(inline_size, tentative_block_size)
2493            },
2494            style,
2495        };
2496
2497        // TODO: https://drafts.csswg.org/css-writing-modes/#orthogonal-flows
2498
2499        let lazy_block_size = LazySize::new(
2500            &content_box_sizes_and_pbm.content_box_sizes.block,
2501            LogicalAxis::Block,
2502            automatic_block_size,
2503            Au::zero,
2504            block_stretch_size,
2505            is_table,
2506        );
2507
2508        let IndependentFormattingContextLayoutResult {
2509            content_inline_size_for_table,
2510            content_block_size,
2511            fragments,
2512            baselines,
2513            specific_layout_info,
2514            ..
2515        } = self.layout(
2516            layout_context,
2517            child_positioning_context,
2518            &containing_block_for_children,
2519            containing_block,
2520            preferred_aspect_ratio,
2521            &lazy_block_size,
2522        );
2523
2524        let content_size = LogicalVec2 {
2525            inline: content_inline_size_for_table.unwrap_or(inline_size),
2526            block: lazy_block_size.resolve(|| content_block_size),
2527        }
2528        .to_physical_size(container_writing_mode);
2529        let content_rect = PhysicalRect::new(PhysicalPoint::zero(), content_size);
2530
2531        let mut base_fragment_info = self.base_fragment_info();
2532        if content_box_sizes_and_pbm.depends_on_block_constraints {
2533            base_fragment_info.flags.insert(
2534                FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
2535            );
2536        }
2537
2538        // Floats can have clearance, but it's handled internally by the float placement logic,
2539        // so there's no need to store it explicitly in the fragment.
2540        // And atomic inlines don't have clearance.
2541        let fragment = BoxFragment::new(
2542            base_fragment_info,
2543            style.clone(),
2544            fragments,
2545            content_rect,
2546            pbm.padding.to_physical(container_writing_mode),
2547            pbm.border.to_physical(container_writing_mode),
2548            margin.to_physical(container_writing_mode),
2549            specific_layout_info,
2550        );
2551
2552        IndependentFloatOrAtomicLayoutResult {
2553            fragment,
2554            baselines,
2555            pbm_sums,
2556        }
2557    }
2558}
2559
2560/// Whether a box may be skipped (deferring to its containing block) when resolving percentages
2561/// in the block size of a descendant. This is known as "The percentage height calculation quirk".
2562/// Note that even if returning true, it won't be skipped if it has a definite size.
2563/// <https://quirks.spec.whatwg.org/#the-percentage-height-calculation-quirk>
2564#[inline]
2565fn skippable_for_block_percentage_quirk(
2566    layout_context: &LayoutContext,
2567    base: &LayoutBoxBase,
2568    context: Option<&IndependentFormattingContext>,
2569) -> bool {
2570    // This logic doesn't match the algorithm in the spec, but it should be roughly
2571    // equivalent to the desired behavior. The spec is written with a CSS2 mindset
2572    // that ignores modern features, and browsers aren't fully interoperable.
2573    layout_context.style_context.quirks_mode() == QuirksMode::Quirks &&
2574        !base
2575            .base_fragment_info
2576            .flags
2577            .contains(FragmentFlags::IS_WIDGET) &&
2578        context.is_none_or(|context| context.is_block_container())
2579}