Skip to main content

layout/flow/
same_formatting_context_block.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//! Same-formatting context blocks. This represents a block in block flow that does not
7//! establish a new formatting context.
8
9use std::sync::Arc;
10
11use app_units::Au;
12use malloc_size_of_derive::MallocSizeOf;
13use script::layout_dom::ServoLayoutNode;
14use servo_arc::Arc as ServoArc;
15use style::Zero;
16use style::context::SharedStyleContext;
17use style::logical_geometry::LogicalAxis;
18use style::properties::ComputedValues;
19use style::servo::selector_parser::PseudoElement;
20
21use crate::containing_block::{ConstraintSpace, ContainingBlock};
22use crate::context::LayoutContext;
23use crate::flow::float::{Clear, ContainingBlockPositionInfo, SequentialLayoutState};
24use crate::flow::{
25    BlockContainer, CollapsibleWithParentStartMargin, ContainingBlockPaddingAndBorder,
26    ResolvedMargins, solve_containing_block_padding_and_border_for_in_flow_box, solve_margins,
27};
28use crate::fragment_tree::{BoxFragment, CollapsedBlockMargins, CollapsedMargin, FragmentFlags};
29use crate::geom::{LogicalRect, LogicalSides1D, LogicalVec2};
30use crate::layout_box_base::LayoutBoxBase;
31use crate::positioned::PositioningContext;
32use crate::sizing::InlineContentSizesResult;
33use crate::style_ext::LayoutStyle;
34
35/// A block in block flow that does not establish a new formatting context.
36#[derive(Debug, MallocSizeOf)]
37pub(crate) struct SameFormattingContextBlock {
38    pub base: LayoutBoxBase,
39    pub contents: BlockContainer,
40    pub contains_floats: bool,
41}
42
43impl SameFormattingContextBlock {
44    pub(crate) fn new(
45        base: LayoutBoxBase,
46        contents: BlockContainer,
47        contains_floats: bool,
48    ) -> Self {
49        Self {
50            base,
51            contents,
52            contains_floats,
53        }
54    }
55
56    pub(crate) fn layout_style(&self) -> LayoutStyle<'_> {
57        self.contents.layout_style(&self.base)
58    }
59
60    pub(crate) fn repair_style(
61        &mut self,
62        context: &SharedStyleContext,
63        node: &ServoLayoutNode,
64        new_style: &ServoArc<ComputedValues>,
65    ) {
66        self.base.repair_style(new_style);
67        self.contents.repair_style(context, node, new_style);
68    }
69
70    pub(crate) fn inline_content_sizes(
71        &self,
72        layout_context: &LayoutContext,
73        constraint_space: &ConstraintSpace,
74    ) -> InlineContentSizesResult {
75        self.base
76            .inline_content_sizes(layout_context, constraint_space, &self.contents)
77    }
78
79    /// Lay out a normal flow non-replaced [`SameFormattingContextBlock`], properly taking
80    /// into account relative positioning. This version also handles caching the layout
81    /// results and fetching the results from the cache, if they are still valid.
82    ///
83    /// - <https://drafts.csswg.org/css2/visudet.html#blockwidth>
84    /// - <https://drafts.csswg.org/css2/visudet.html#normal-block>
85    #[expect(clippy::too_many_arguments)]
86    pub(crate) fn layout_in_flow_non_replaced_block_level_cached(
87        &self,
88        layout_context: &LayoutContext<'_>,
89        positioning_context: &mut PositioningContext,
90        containing_block: &ContainingBlock<'_>,
91        sequential_layout_state: Option<&mut SequentialLayoutState>,
92        collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
93        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
94        has_inline_parent: bool,
95    ) -> Arc<BoxFragment> {
96        let mut allows_caching = sequential_layout_state.is_none();
97
98        if allows_caching &&
99            let Some(cached_result) = self
100                .base
101                .cached_same_formatting_context_block_if_applicable(
102                    containing_block,
103                    collapsible_with_parent_start_margin,
104                    ignore_block_margins_for_stretch,
105                    has_inline_parent,
106                )
107        {
108            return cached_result;
109        };
110
111        let positioning_context_length = positioning_context.len();
112        let fragment = Arc::new(positioning_context.layout_maybe_position_relative_fragment(
113            layout_context,
114            containing_block,
115            &self.base,
116            |positioning_context| {
117                self.layout_in_flow_non_replaced_block_level(
118                    layout_context,
119                    positioning_context,
120                    containing_block,
121                    sequential_layout_state,
122                    collapsible_with_parent_start_margin,
123                    ignore_block_margins_for_stretch,
124                    has_inline_parent,
125                )
126            },
127        ));
128
129        // We currently do not allow caching `SameFormattingContextBlock` box layout results if they
130        // contain absolutely positioned children.
131        //
132        // TODO: It would be good to find a way to allow this, without having to create and store a
133        // PositioningContext for every single SameFormattingContextBlock.
134        allows_caching = allows_caching && positioning_context_length == positioning_context.len();
135
136        if !allows_caching {
137            self.base.clear_fragments_and_dirty_fragment_cache();
138        } else {
139            self.base.cache_same_formatting_context_block_layout(
140                containing_block,
141                collapsible_with_parent_start_margin,
142                ignore_block_margins_for_stretch,
143                has_inline_parent,
144                fragment.clone(),
145            );
146        }
147
148        fragment
149    }
150
151    /// Lay out a normal flow non-replaced [`SameFormattingContextBlock`].
152    ///
153    /// - <https://drafts.csswg.org/css2/visudet.html#blockwidth>
154    /// - <https://drafts.csswg.org/css2/visudet.html#normal-block>
155    #[expect(clippy::too_many_arguments)]
156    fn layout_in_flow_non_replaced_block_level(
157        &self,
158        layout_context: &LayoutContext,
159        positioning_context: &mut PositioningContext,
160        containing_block: &ContainingBlock,
161        mut sequential_layout_state: Option<&mut SequentialLayoutState>,
162        collapsible_with_parent_start_margin: Option<CollapsibleWithParentStartMargin>,
163        ignore_block_margins_for_stretch: LogicalSides1D<bool>,
164        has_inline_parent: bool,
165    ) -> BoxFragment {
166        let style = &self.base.style;
167        let layout_style = self.contents.layout_style(&self.base);
168        let containing_block_writing_mode = containing_block.style.writing_mode;
169        let get_inline_content_sizes = |constraint_space: &ConstraintSpace| {
170            self.base
171                .inline_content_sizes(layout_context, constraint_space, &self.contents)
172                .sizes
173        };
174        let ContainingBlockPaddingAndBorder {
175            containing_block: containing_block_for_children,
176            pbm,
177            block_sizes,
178            depends_on_block_constraints,
179            tentative_block_size,
180            block_stretch_size,
181            justify_self,
182            automatic_block_size,
183            ..
184        } = solve_containing_block_padding_and_border_for_in_flow_box(
185            layout_context,
186            containing_block,
187            &layout_style,
188            get_inline_content_sizes,
189            ignore_block_margins_for_stretch,
190            &self.base,
191            None,
192            has_inline_parent,
193        );
194        let ResolvedMargins {
195            margin,
196            effective_margin_inline_start,
197        } = solve_margins(
198            containing_block,
199            &pbm,
200            containing_block_for_children.inline_size(),
201            justify_self,
202        );
203
204        let start_margin_can_collapse_with_children =
205            pbm.padding.block_start.is_zero() && pbm.border.block_start.is_zero();
206
207        let mut clearance = None;
208        let parent_containing_block_position_info = match sequential_layout_state {
209            None => None,
210            Some(ref mut sequential_layout_state) => {
211                let clear = Clear::from_style_and_container_writing_mode(
212                    style,
213                    containing_block_writing_mode,
214                );
215                let mut block_start_margin = CollapsedMargin::new(margin.block_start);
216
217                // The block start margin may collapse with content margins,
218                // compute the resulting one in order to place floats correctly.
219                // Only need to do this if the element isn't also collapsing with its parent,
220                // otherwise we should have already included the margin in an ancestor.
221                // Note this lookahead stops when finding a descendant whose `clear` isn't `none`
222                // (since clearance prevents collapsing margins with the parent).
223                // But then we have to decide whether to actually add clearance or not,
224                // so look forward again regardless of `collapsible_with_parent_start_margin`.
225                // TODO: This isn't completely right: if we don't add actual clearance,
226                // the margin should have been included in the parent (or some ancestor).
227                // The lookahead should stop for actual clearance, not just for `clear`.
228                let collapsible_with_parent_start_margin = collapsible_with_parent_start_margin.expect(
229                    "We should know whether we are collapsing the block start margin with the parent \
230                    when laying out sequentially",
231                ).0 && clear == Clear::None;
232                if !collapsible_with_parent_start_margin && start_margin_can_collapse_with_children
233                {
234                    self.contents.find_block_margin_collapsing_with_parent(
235                        layout_context,
236                        &mut block_start_margin,
237                        &containing_block_for_children,
238                    );
239                }
240
241                // Introduce clearance if necessary.
242                clearance = sequential_layout_state.calculate_clearance(clear, &block_start_margin);
243                if clearance.is_some() {
244                    sequential_layout_state.commit_margin();
245                }
246                sequential_layout_state.adjoin_assign(&block_start_margin);
247                if !start_margin_can_collapse_with_children {
248                    sequential_layout_state.commit_margin();
249                }
250
251                // NB: This will be a no-op if we're collapsing margins with our children since that
252                // can only happen if we have no block-start padding and border.
253                sequential_layout_state.advance_block_position(
254                    pbm.padding.block_start +
255                        pbm.border.block_start +
256                        clearance.unwrap_or_else(Au::zero),
257                );
258
259                // We are about to lay out children. Update the offset between the block formatting
260                // context and the containing block that we create for them. This offset is used to
261                // ajust BFC relative coordinates to coordinates that are relative to our content box.
262                // Our content box establishes the containing block for non-abspos children, including
263                // floats.
264                let inline_start = sequential_layout_state
265                    .floats
266                    .containing_block_info
267                    .inline_start +
268                    pbm.padding.inline_start +
269                    pbm.border.inline_start +
270                    effective_margin_inline_start;
271                let new_cb_offsets = ContainingBlockPositionInfo {
272                    block_start: sequential_layout_state.bfc_relative_block_position,
273                    block_start_margins_not_collapsed: sequential_layout_state.current_margin,
274                    inline_start,
275                    inline_end: inline_start + containing_block_for_children.inline_size(),
276                };
277                Some(sequential_layout_state.replace_containing_block_position_info(new_cb_offsets))
278            },
279        };
280
281        let is_anonymous = matches!(
282            self.base.style.pseudo(),
283            Some(PseudoElement::ServoAnonymousBox)
284        );
285
286        // https://drafts.csswg.org/css-sizing-4/#stretch-fit-sizing
287        // > If this is a block axis size, and the element is in a Block Layout formatting context,
288        // > and the parent element does not have a block-start border or padding and is not an
289        // > independent formatting context, treat the element’s block-start margin as zero
290        // > for the purpose of calculating this size. Do the same for the block-end margin.
291        //
292        // However, as resolved in https://github.com/w3c/csswg-drafts/issues/13260, we should
293        // check the containing block instead of the parent. Note that anonymous blocks don't
294        // establish a containing block.
295        let ignore_block_margins_for_stretch = if is_anonymous {
296            ignore_block_margins_for_stretch
297        } else {
298            LogicalSides1D::new(
299                pbm.border.block_start.is_zero() && pbm.padding.block_start.is_zero(),
300                pbm.border.block_end.is_zero() && pbm.padding.block_end.is_zero(),
301            )
302        };
303
304        let flow_layout = self.contents.layout(
305            layout_context,
306            positioning_context,
307            &containing_block_for_children,
308            sequential_layout_state.as_deref_mut(),
309            CollapsibleWithParentStartMargin(start_margin_can_collapse_with_children),
310            ignore_block_margins_for_stretch,
311        );
312        let mut content_block_size = flow_layout.content_block_size;
313
314        // Update margins.
315        let mut block_margins_collapsed_with_children = CollapsedBlockMargins::from_margin(&margin);
316        let mut collapsible_margins_in_children = flow_layout.collapsible_margins_in_children;
317        if start_margin_can_collapse_with_children {
318            block_margins_collapsed_with_children
319                .start
320                .adjoin_assign(&collapsible_margins_in_children.start);
321            if collapsible_margins_in_children.collapsed_through {
322                block_margins_collapsed_with_children
323                    .start
324                    .adjoin_assign(&std::mem::replace(
325                        &mut collapsible_margins_in_children.end,
326                        CollapsedMargin::zero(),
327                    ));
328            }
329        }
330
331        let collapsed_through = collapsible_margins_in_children.collapsed_through &&
332            pbm.padding_border_sums.block.is_zero() &&
333            tentative_block_size.definite_or_min().is_zero();
334        block_margins_collapsed_with_children.collapsed_through = collapsed_through;
335
336        let end_margin_can_collapse_with_children =
337            pbm.padding.block_end.is_zero() && pbm.border.block_end.is_zero();
338        if !end_margin_can_collapse_with_children {
339            content_block_size += collapsible_margins_in_children.end.solve();
340        }
341
342        let block_size = block_sizes.resolve(
343            LogicalAxis::Block,
344            automatic_block_size,
345            Au::zero,
346            block_stretch_size,
347            || content_block_size.into(),
348            false, /* is_table */
349        );
350
351        // If the final block size is different than the intrinsic size of the contents,
352        // then we can't actually collapse the end margins. This can happen due to min
353        // or max block sizes, or due to `calc-size()` once we implement it.
354        //
355        // We also require `block-size` to have an intrinsic value, by checking whether
356        // the containing block established for the contents has an indefinite block size.
357        // However, even if `block-size: 0px` is extrinsic (so it would normally prevent
358        // collapsing the end margin with children), it doesn't prevent the top and end
359        // margins from collapsing through. If that happens, allow collapsing end margins.
360        //
361        // This is being discussed in https://github.com/w3c/csswg-drafts/issues/12218.
362        // It would probably make more sense to check the definiteness of the containing
363        // block in the logic above (when we check if there is some block-end padding or
364        // border), or maybe drop the condition altogether. But for now, we match Blink.
365        let end_margin_can_collapse_with_children = end_margin_can_collapse_with_children &&
366            block_size == content_block_size &&
367            (collapsed_through || !tentative_block_size.is_definite());
368        if end_margin_can_collapse_with_children {
369            block_margins_collapsed_with_children
370                .end
371                .adjoin_assign(&collapsible_margins_in_children.end);
372        }
373
374        if let Some(ref mut sequential_layout_state) = sequential_layout_state {
375            // Now that we're done laying out our children, we can restore the
376            // parent's containing block position information.
377            sequential_layout_state.replace_containing_block_position_info(
378                parent_containing_block_position_info.unwrap(),
379            );
380
381            // Account for padding and border. We also might have to readjust the
382            // `bfc_relative_block_position` if it was different from the content size (i.e. was
383            // non-`auto` and/or was affected by min/max block size).
384            //
385            // If this adjustment is positive, that means that a block size was specified, but
386            // the content inside had a smaller block size. If this adjustment is negative, a
387            // block size was specified, but the content inside overflowed this container in
388            // the block direction. In that case, the ceiling for floats is effectively raised
389            // as long as no floats in the overflowing content lowered it.
390            sequential_layout_state.advance_block_position(
391                block_size - content_block_size + pbm.padding.block_end + pbm.border.block_end,
392            );
393
394            if !end_margin_can_collapse_with_children {
395                sequential_layout_state.commit_margin();
396            }
397            sequential_layout_state.adjoin_assign(&CollapsedMargin::new(margin.block_end));
398        }
399
400        let content_rect = LogicalRect {
401            start_corner: LogicalVec2 {
402                block: (pbm.padding.block_start +
403                    pbm.border.block_start +
404                    clearance.unwrap_or_else(Au::zero)),
405                inline: pbm.padding.inline_start +
406                    pbm.border.inline_start +
407                    effective_margin_inline_start,
408            },
409            size: LogicalVec2 {
410                block: block_size,
411                inline: containing_block_for_children.inline_size(),
412            },
413        };
414
415        let mut base_fragment_info = self.base.base_fragment_info;
416
417        // An anonymous block doesn't establish a containing block for its contents. Therefore,
418        // if its contents depend on block constraints, its block size (which is intrinsic) also
419        // depends on block constraints.
420        if depends_on_block_constraints ||
421            (is_anonymous && flow_layout.depends_on_block_constraints)
422        {
423            base_fragment_info.flags.insert(
424                FragmentFlags::SIZE_DEPENDS_ON_BLOCK_CONSTRAINTS_AND_CAN_BE_CHILD_OF_FLEX_ITEM,
425            );
426        }
427
428        BoxFragment::new(
429            base_fragment_info,
430            style.clone(),
431            flow_layout.fragments,
432            content_rect.as_physical_deprecated(containing_block),
433            pbm.padding.to_physical(containing_block_writing_mode),
434            pbm.border.to_physical(containing_block_writing_mode),
435            margin.to_physical(containing_block_writing_mode),
436            flow_layout.specific_layout_info,
437        )
438        .with_baselines(flow_layout.baselines)
439        .with_block_level_layout_info(block_margins_collapsed_with_children, clearance)
440    }
441}