layout/flow/
construct.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
5use std::borrow::Cow;
6
7use rayon::iter::{IntoParallelIterator, ParallelIterator};
8use servo_arc::Arc;
9use style::properties::ComputedValues;
10use style::properties::longhands::list_style_position::computed_value::T as ListStylePosition;
11use style::selector_parser::PseudoElement;
12use style::str::char_is_whitespace;
13use style::values::specified::box_::DisplayOutside as StyloDisplayOutside;
14
15use super::OutsideMarker;
16use super::inline::construct::InlineFormattingContextBuilder;
17use super::inline::inline_box::InlineBox;
18use super::inline::{InlineFormattingContext, SharedInlineStyles};
19use crate::PropagatedBoxTreeData;
20use crate::cell::ArcRefCell;
21use crate::context::LayoutContext;
22use crate::dom::{BoxSlot, LayoutBox, NodeExt};
23use crate::dom_traversal::{
24    Contents, NodeAndStyleInfo, NonReplacedContents, PseudoElementContentItem, TraversalHandler,
25};
26use crate::flow::float::FloatBox;
27use crate::flow::{BlockContainer, BlockFormattingContext, BlockLevelBox};
28use crate::formatting_contexts::IndependentFormattingContext;
29use crate::fragment_tree::FragmentFlags;
30use crate::layout_box_base::LayoutBoxBase;
31use crate::positioned::AbsolutelyPositionedBox;
32use crate::style_ext::{ComputedValuesExt, DisplayGeneratingBox, DisplayInside, DisplayOutside};
33use crate::table::{AnonymousTableContent, Table};
34
35impl BlockFormattingContext {
36    pub(crate) fn construct(
37        context: &LayoutContext,
38        info: &NodeAndStyleInfo<'_>,
39        contents: NonReplacedContents,
40        propagated_data: PropagatedBoxTreeData,
41        is_list_item: bool,
42    ) -> Self {
43        Self::from_block_container(BlockContainer::construct(
44            context,
45            info,
46            contents,
47            propagated_data,
48            is_list_item,
49        ))
50    }
51
52    pub(crate) fn from_block_container(contents: BlockContainer) -> Self {
53        let contains_floats = contents.contains_floats();
54        Self {
55            contents,
56            contains_floats,
57        }
58    }
59}
60
61struct BlockLevelJob<'dom> {
62    info: NodeAndStyleInfo<'dom>,
63    box_slot: BoxSlot<'dom>,
64    propagated_data: PropagatedBoxTreeData,
65    kind: BlockLevelCreator,
66}
67
68enum BlockLevelCreator {
69    SameFormattingContextBlock(IntermediateBlockContainer),
70    Independent {
71        display_inside: DisplayInside,
72        contents: Contents,
73    },
74    OutOfFlowAbsolutelyPositionedBox {
75        display_inside: DisplayInside,
76        contents: Contents,
77    },
78    OutOfFlowFloatBox {
79        display_inside: DisplayInside,
80        contents: Contents,
81    },
82    OutsideMarker {
83        list_item_style: Arc<ComputedValues>,
84        contents: Vec<PseudoElementContentItem>,
85    },
86    AnonymousTable {
87        table_block: ArcRefCell<BlockLevelBox>,
88    },
89}
90
91/// A block container that may still have to be constructed.
92///
93/// Represents either the inline formatting context of an anonymous block
94/// box or the yet-to-be-computed block container generated from the children
95/// of a given element.
96///
97/// Deferring allows using rayon’s `into_par_iter`.
98enum IntermediateBlockContainer {
99    InlineFormattingContext(BlockContainer),
100    Deferred {
101        contents: NonReplacedContents,
102        propagated_data: PropagatedBoxTreeData,
103        is_list_item: bool,
104    },
105}
106
107/// A builder for a block container.
108///
109/// This builder starts from the first child of a given DOM node
110/// and does a preorder traversal of all of its inclusive siblings.
111pub(crate) struct BlockContainerBuilder<'dom, 'style> {
112    context: &'style LayoutContext<'style>,
113
114    /// This NodeAndStyleInfo contains the root node, the corresponding pseudo
115    /// content designator, and the block container style.
116    info: &'style NodeAndStyleInfo<'dom>,
117
118    /// The list of block-level boxes to be built for the final block container.
119    ///
120    /// Contains all the block-level jobs we found traversing the tree
121    /// so far, if this is empty at the end of the traversal and the ongoing
122    /// inline formatting context is not empty, the block container establishes
123    /// an inline formatting context (see end of `build`).
124    ///
125    /// DOM nodes which represent block-level boxes are immediately pushed
126    /// to this list with their style without ever being traversed at this
127    /// point, instead we just move to their next sibling. If the DOM node
128    /// doesn't have a next sibling, we either reached the end of the container
129    /// root or there are ongoing inline-level boxes
130    /// (see `handle_block_level_element`).
131    block_level_boxes: Vec<BlockLevelJob<'dom>>,
132
133    /// Whether or not this builder has yet produced a block which would be
134    /// be considered the first line for the purposes of `text-indent`.
135    have_already_seen_first_line_for_text_indent: bool,
136
137    /// The propagated data to use for BoxTree construction.
138    propagated_data: PropagatedBoxTreeData,
139
140    /// The [`InlineFormattingContextBuilder`] if we have encountered any inline items,
141    /// otherwise None.
142    ///
143    /// TODO: This can be `OnceCell` once `OnceCell::get_mut_or_init` is stabilized.
144    inline_formatting_context_builder: Option<InlineFormattingContextBuilder>,
145
146    /// The [`NodeAndStyleInfo`] to use for anonymous block boxes pushed to the list of
147    /// block-level boxes, lazily initialized.
148    anonymous_box_info: Option<NodeAndStyleInfo<'dom>>,
149
150    /// A collection of content that is being added to an anonymous table. This is
151    /// composed of any sequence of internal table elements or table captions that
152    /// are found outside of a table.
153    anonymous_table_content: Vec<AnonymousTableContent<'dom>>,
154
155    /// Any [`InlineFormattingContexts`] created need to know about the ongoing `display: contents`
156    /// ancestors that have been processed. This `Vec` allows passing those into new
157    /// [`InlineFormattingContext`]s that we create.
158    display_contents_shared_styles: Vec<SharedInlineStyles>,
159}
160
161impl BlockContainer {
162    pub fn construct(
163        context: &LayoutContext,
164        info: &NodeAndStyleInfo<'_>,
165        contents: NonReplacedContents,
166        propagated_data: PropagatedBoxTreeData,
167        is_list_item: bool,
168    ) -> BlockContainer {
169        let mut builder = BlockContainerBuilder::new(context, info, propagated_data);
170
171        if is_list_item {
172            if let Some((marker_info, marker_contents)) = crate::lists::make_marker(context, info) {
173                match marker_info.style.clone_list_style_position() {
174                    ListStylePosition::Inside => {
175                        builder.handle_list_item_marker_inside(&marker_info, marker_contents)
176                    },
177                    ListStylePosition::Outside => builder.handle_list_item_marker_outside(
178                        &marker_info,
179                        marker_contents,
180                        info.style.clone(),
181                    ),
182                }
183            }
184        }
185
186        contents.traverse(context, info, &mut builder);
187        builder.finish()
188    }
189}
190
191impl<'dom, 'style> BlockContainerBuilder<'dom, 'style> {
192    pub(crate) fn new(
193        context: &'style LayoutContext,
194        info: &'style NodeAndStyleInfo<'dom>,
195        propagated_data: PropagatedBoxTreeData,
196    ) -> Self {
197        BlockContainerBuilder {
198            context,
199            info,
200            block_level_boxes: Vec::new(),
201            propagated_data,
202            have_already_seen_first_line_for_text_indent: false,
203            anonymous_box_info: None,
204            anonymous_table_content: Vec::new(),
205            inline_formatting_context_builder: None,
206            display_contents_shared_styles: Vec::new(),
207        }
208    }
209
210    fn currently_processing_inline_box(&self) -> bool {
211        self.inline_formatting_context_builder
212            .as_ref()
213            .is_some_and(InlineFormattingContextBuilder::currently_processing_inline_box)
214    }
215
216    fn ensure_inline_formatting_context_builder(&mut self) -> &mut InlineFormattingContextBuilder {
217        self.inline_formatting_context_builder
218            .get_or_insert_with(|| {
219                let mut builder = InlineFormattingContextBuilder::new(self.info);
220                for shared_inline_styles in self.display_contents_shared_styles.iter() {
221                    builder.enter_display_contents(shared_inline_styles.clone());
222                }
223                builder
224            })
225    }
226
227    fn finish_ongoing_inline_formatting_context(&mut self) -> Option<InlineFormattingContext> {
228        self.inline_formatting_context_builder.take()?.finish(
229            self.context,
230            !self.have_already_seen_first_line_for_text_indent,
231            self.info.node.is_single_line_text_input(),
232            self.info.style.to_bidi_level(),
233        )
234    }
235
236    pub(crate) fn finish(mut self) -> BlockContainer {
237        debug_assert!(!self.currently_processing_inline_box());
238
239        self.finish_anonymous_table_if_needed();
240
241        if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context() {
242            // There are two options here. This block was composed of both one or more inline formatting contexts
243            // and child blocks OR this block was a single inline formatting context. In the latter case, we
244            // just return the inline formatting context as the block itself.
245            if self.block_level_boxes.is_empty() {
246                return BlockContainer::InlineFormattingContext(inline_formatting_context);
247            }
248            self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
249        }
250
251        let context = self.context;
252        let block_level_boxes = if self.context.use_rayon {
253            self.block_level_boxes
254                .into_par_iter()
255                .map(|block_level_job| block_level_job.finish(context))
256                .collect()
257        } else {
258            self.block_level_boxes
259                .into_iter()
260                .map(|block_level_job| block_level_job.finish(context))
261                .collect()
262        };
263
264        BlockContainer::BlockLevelBoxes(block_level_boxes)
265    }
266
267    fn finish_anonymous_table_if_needed(&mut self) {
268        if self.anonymous_table_content.is_empty() {
269            return;
270        }
271
272        // From https://drafts.csswg.org/css-tables/#fixup-algorithm:
273        //  > If the box’s parent is an inline, run-in, or ruby box (or any box that would perform
274        //  > inlinification of its children), then an inline-table box must be generated; otherwise
275        //  > it must be a table box.
276        //
277        // Note that text content in the inline formatting context isn't enough to force the
278        // creation of an inline table. It requires the parent to be an inline box.
279        let inline_table = self.currently_processing_inline_box();
280
281        let contents: Vec<AnonymousTableContent<'dom>> =
282            self.anonymous_table_content.drain(..).collect();
283        let last_text = match contents.last() {
284            Some(AnonymousTableContent::Text(info, text)) => Some((info.clone(), text.clone())),
285            _ => None,
286        };
287
288        let (table_info, ifc) =
289            Table::construct_anonymous(self.context, self.info, contents, self.propagated_data);
290
291        if inline_table {
292            self.ensure_inline_formatting_context_builder()
293                .push_atomic(|| ArcRefCell::new(ifc), None);
294        } else {
295            let table_block = ArcRefCell::new(BlockLevelBox::Independent(ifc));
296
297            if let Some(inline_formatting_context) = self.finish_ongoing_inline_formatting_context()
298            {
299                self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
300            }
301
302            let box_slot = table_info.node.box_slot();
303            self.block_level_boxes.push(BlockLevelJob {
304                info: table_info,
305                box_slot,
306                kind: BlockLevelCreator::AnonymousTable { table_block },
307                propagated_data: self.propagated_data,
308            });
309        }
310
311        // If the last element in the anonymous table content is whitespace, that
312        // whitespace doesn't actually belong to the table. It should be processed outside
313        // ie become a space between the anonymous table and the rest of the block
314        // content. Anonymous tables are really only constructed around internal table
315        // elements and the whitespace between them, so this trailing whitespace should
316        // not be included.
317        //
318        // See https://drafts.csswg.org/css-tables/#fixup-algorithm sections "Remove
319        // irrelevant boxes" and "Generate missing parents."
320        if let Some((info, text)) = last_text {
321            self.handle_text(&info, text);
322        }
323    }
324}
325
326impl<'dom> TraversalHandler<'dom> for BlockContainerBuilder<'dom, '_> {
327    fn handle_element(
328        &mut self,
329        info: &NodeAndStyleInfo<'dom>,
330        display: DisplayGeneratingBox,
331        contents: Contents,
332        box_slot: BoxSlot<'dom>,
333    ) {
334        match display {
335            DisplayGeneratingBox::OutsideInside { outside, inside } => {
336                self.finish_anonymous_table_if_needed();
337
338                match outside {
339                    DisplayOutside::Inline => {
340                        self.handle_inline_level_element(info, inside, contents, box_slot)
341                    },
342                    DisplayOutside::Block => {
343                        let box_style = info.style.get_box();
344                        // Floats and abspos cause blockification, so they only happen in this case.
345                        // https://drafts.csswg.org/css2/visuren.html#dis-pos-flo
346                        if box_style.position.is_absolutely_positioned() {
347                            self.handle_absolutely_positioned_element(
348                                info, inside, contents, box_slot,
349                            )
350                        } else if box_style.float.is_floating() {
351                            self.handle_float_element(info, inside, contents, box_slot)
352                        } else {
353                            self.handle_block_level_element(info, inside, contents, box_slot)
354                        }
355                    },
356                };
357            },
358            DisplayGeneratingBox::LayoutInternal(_) => {
359                self.anonymous_table_content
360                    .push(AnonymousTableContent::Element {
361                        info: info.clone(),
362                        display,
363                        contents,
364                        box_slot,
365                    });
366            },
367        }
368    }
369
370    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: Cow<'dom, str>) {
371        if text.is_empty() {
372            return;
373        }
374
375        // If we are building an anonymous table ie this text directly followed internal
376        // table elements that did not have a `<table>` ancestor, then we forward all
377        // whitespace to the table builder.
378        if !self.anonymous_table_content.is_empty() && text.chars().all(char_is_whitespace) {
379            self.anonymous_table_content
380                .push(AnonymousTableContent::Text(info.clone(), text));
381            return;
382        } else {
383            self.finish_anonymous_table_if_needed();
384        }
385
386        self.ensure_inline_formatting_context_builder()
387            .push_text(text, info);
388    }
389
390    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
391        self.display_contents_shared_styles.push(styles.clone());
392        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
393            builder.enter_display_contents(styles);
394        }
395    }
396
397    fn leave_display_contents(&mut self) {
398        self.display_contents_shared_styles.pop();
399        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
400            builder.leave_display_contents();
401        }
402    }
403}
404
405impl<'dom> BlockContainerBuilder<'dom, '_> {
406    fn handle_list_item_marker_inside(
407        &mut self,
408        marker_info: &NodeAndStyleInfo<'dom>,
409        contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
410    ) {
411        let box_slot = marker_info.node.box_slot();
412        self.handle_inline_level_element(
413            marker_info,
414            DisplayInside::Flow {
415                is_list_item: false,
416            },
417            Contents::for_pseudo_element(contents),
418            box_slot,
419        );
420    }
421
422    fn handle_list_item_marker_outside(
423        &mut self,
424        marker_info: &NodeAndStyleInfo<'dom>,
425        contents: Vec<crate::dom_traversal::PseudoElementContentItem>,
426        list_item_style: Arc<ComputedValues>,
427    ) {
428        let box_slot = marker_info.node.box_slot();
429        self.block_level_boxes.push(BlockLevelJob {
430            info: marker_info.clone(),
431            box_slot,
432            kind: BlockLevelCreator::OutsideMarker {
433                contents,
434                list_item_style,
435            },
436            propagated_data: self.propagated_data,
437        });
438    }
439
440    fn handle_inline_level_element(
441        &mut self,
442        info: &NodeAndStyleInfo<'dom>,
443        display_inside: DisplayInside,
444        contents: Contents,
445        box_slot: BoxSlot<'dom>,
446    ) {
447        let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
448        let (is_list_item, non_replaced_contents) = match (display_inside, contents) {
449            (
450                DisplayInside::Flow { is_list_item },
451                Contents::NonReplaced(non_replaced_contents),
452            ) => (is_list_item, non_replaced_contents),
453            (_, contents) => {
454                // If this inline element is an atomic, handle it and return.
455                let context = self.context;
456                let propagated_data = self.propagated_data;
457
458                let construction_callback = || {
459                    ArcRefCell::new(IndependentFormattingContext::construct(
460                        context,
461                        info,
462                        display_inside,
463                        contents,
464                        propagated_data,
465                    ))
466                };
467
468                let atomic = self
469                    .ensure_inline_formatting_context_builder()
470                    .push_atomic(construction_callback, old_layout_box);
471                box_slot.set(LayoutBox::InlineLevel(vec![atomic]));
472                return;
473            },
474        };
475
476        // Otherwise, this is just a normal inline box. Whatever happened before, all we need to do
477        // before recurring is to remember this ongoing inline level box.
478        self.ensure_inline_formatting_context_builder()
479            .start_inline_box(|| ArcRefCell::new(InlineBox::new(info)), old_layout_box);
480
481        if is_list_item {
482            if let Some((marker_info, marker_contents)) =
483                crate::lists::make_marker(self.context, info)
484            {
485                // Ignore `list-style-position` here:
486                // “If the list item is an inline box: this value is equivalent to `inside`.”
487                // https://drafts.csswg.org/css-lists/#list-style-position-outside
488                self.handle_list_item_marker_inside(&marker_info, marker_contents)
489            }
490        }
491
492        // `unwrap` doesn’t panic here because `is_replaced` returned `false`.
493        non_replaced_contents.traverse(self.context, info, self);
494
495        self.finish_anonymous_table_if_needed();
496
497        // As we are ending this inline box, during the course of the `traverse()` above, the ongoing
498        // inline formatting context may have been split around block-level elements. In that case,
499        // more than a single inline box tree item may have been produced for this inline-level box.
500        // `InlineFormattingContextBuilder::end_inline_box()` is returning all of those box tree
501        // items.
502        box_slot.set(LayoutBox::InlineLevel(
503            self.inline_formatting_context_builder
504                .as_mut()
505                .expect("Should be building an InlineFormattingContext")
506                .end_inline_box(),
507        ));
508    }
509
510    fn handle_block_level_element(
511        &mut self,
512        info: &NodeAndStyleInfo<'dom>,
513        display_inside: DisplayInside,
514        contents: Contents,
515        box_slot: BoxSlot<'dom>,
516    ) {
517        // We just found a block level element, all ongoing inline level boxes
518        // need to be split around it.
519        //
520        // After calling `split_around_block_and_finish`,
521        // `self.inline_formatting_context_builder` is set up with the state
522        // that we want to have after we push the block below.
523        if let Some(inline_formatting_context) = self
524            .inline_formatting_context_builder
525            .as_mut()
526            .and_then(|builder| {
527                builder.split_around_block_and_finish(
528                    self.context,
529                    !self.have_already_seen_first_line_for_text_indent,
530                    self.info.style.to_bidi_level(),
531                )
532            })
533        {
534            self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
535        }
536
537        let propagated_data = self.propagated_data;
538        let kind = match contents {
539            Contents::NonReplaced(contents) => match display_inside {
540                DisplayInside::Flow { is_list_item }
541                    // Fragment flags are just used to indicate that the element is not replaced, so empty
542                    // flags are okay here.
543                    if !info.style.establishes_block_formatting_context(
544                        FragmentFlags::empty()
545                    ) =>
546                {
547                    BlockLevelCreator::SameFormattingContextBlock(
548                        IntermediateBlockContainer::Deferred {
549                            contents,
550                            propagated_data,
551                            is_list_item,
552                        },
553                    )
554                },
555                _ => BlockLevelCreator::Independent {
556                    display_inside,
557                    contents: Contents::NonReplaced(contents),
558                },
559            },
560            Contents::Replaced(_) | Contents::Widget(_) => BlockLevelCreator::Independent {
561                display_inside,
562                contents,
563            },
564        };
565        self.block_level_boxes.push(BlockLevelJob {
566            info: info.clone(),
567            box_slot,
568            kind,
569            propagated_data,
570        });
571
572        // Any block also counts as the first line for the purposes of text indent. Even if
573        // they don't actually indent.
574        self.have_already_seen_first_line_for_text_indent = true;
575    }
576
577    fn handle_absolutely_positioned_element(
578        &mut self,
579        info: &NodeAndStyleInfo<'dom>,
580        display_inside: DisplayInside,
581        contents: Contents,
582        box_slot: BoxSlot<'dom>,
583    ) {
584        // If the original display was inline-level, then we need an inline formatting context
585        // in order to compute the static position correctly.
586        // If it was block-level, we don't want to break an existing inline formatting context,
587        // so push it there (`LineItemLayout::layout_absolute` can handle this well). But if
588        // there is no inline formatting context, then we can avoid creating one.
589        let needs_inline_builder =
590            info.style.get_box().original_display.outside() == StyloDisplayOutside::Inline;
591        if needs_inline_builder {
592            self.ensure_inline_formatting_context_builder();
593        }
594        let inline_builder = self
595            .inline_formatting_context_builder
596            .as_mut()
597            .filter(|builder| needs_inline_builder || !builder.is_empty);
598        if let Some(inline_builder) = inline_builder {
599            let constructor = || {
600                ArcRefCell::new(AbsolutelyPositionedBox::construct(
601                    self.context,
602                    info,
603                    display_inside,
604                    contents,
605                ))
606            };
607            let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
608            let inline_level_box =
609                inline_builder.push_absolutely_positioned_box(constructor, old_layout_box);
610            box_slot.set(LayoutBox::InlineLevel(vec![inline_level_box]));
611            return;
612        }
613
614        let kind = BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
615            contents,
616            display_inside,
617        };
618        self.block_level_boxes.push(BlockLevelJob {
619            info: info.clone(),
620            box_slot,
621            kind,
622            propagated_data: self.propagated_data,
623        });
624    }
625
626    fn handle_float_element(
627        &mut self,
628        info: &NodeAndStyleInfo<'dom>,
629        display_inside: DisplayInside,
630        contents: Contents,
631        box_slot: BoxSlot<'dom>,
632    ) {
633        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
634            if !builder.is_empty {
635                let constructor = || {
636                    ArcRefCell::new(FloatBox::construct(
637                        self.context,
638                        info,
639                        display_inside,
640                        contents,
641                        self.propagated_data,
642                    ))
643                };
644                let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
645                let inline_level_box = builder.push_float_box(constructor, old_layout_box);
646                box_slot.set(LayoutBox::InlineLevel(vec![inline_level_box]));
647                return;
648            }
649        }
650
651        let kind = BlockLevelCreator::OutOfFlowFloatBox {
652            contents,
653            display_inside,
654        };
655        self.block_level_boxes.push(BlockLevelJob {
656            info: info.clone(),
657            box_slot,
658            kind,
659            propagated_data: self.propagated_data,
660        });
661    }
662
663    fn push_block_level_job_for_inline_formatting_context(
664        &mut self,
665        inline_formatting_context: InlineFormattingContext,
666    ) {
667        let layout_context = self.context;
668        let anonymous_info = self
669            .anonymous_box_info
670            .get_or_insert_with(|| {
671                self.info
672                    .with_pseudo_element(layout_context, PseudoElement::ServoAnonymousBox)
673                    .expect("Should never fail to create anonymous box")
674            })
675            .clone();
676
677        let box_slot = anonymous_info.node.box_slot();
678        self.block_level_boxes.push(BlockLevelJob {
679            info: anonymous_info,
680            box_slot,
681            kind: BlockLevelCreator::SameFormattingContextBlock(
682                IntermediateBlockContainer::InlineFormattingContext(
683                    BlockContainer::InlineFormattingContext(inline_formatting_context),
684                ),
685            ),
686            propagated_data: self.propagated_data,
687        });
688
689        self.have_already_seen_first_line_for_text_indent = true;
690    }
691}
692
693impl BlockLevelJob<'_> {
694    fn finish(self, context: &LayoutContext) -> ArcRefCell<BlockLevelBox> {
695        let info = &self.info;
696
697        // If this `BlockLevelBox` is undamaged and it has been laid out before, reuse
698        // the old one, while being sure to clear the layout cache.
699        if !info.damage.has_box_damage() {
700            if let Some(block_level_box) = match self.box_slot.slot.as_ref() {
701                Some(box_slot) => match &*box_slot.borrow() {
702                    Some(LayoutBox::BlockLevel(block_level_box)) => Some(block_level_box.clone()),
703                    _ => None,
704                },
705                None => None,
706            } {
707                return block_level_box;
708            }
709        }
710
711        let block_level_box = match self.kind {
712            BlockLevelCreator::SameFormattingContextBlock(intermediate_block_container) => {
713                let contents = intermediate_block_container.finish(context, info);
714                let contains_floats = contents.contains_floats();
715                ArcRefCell::new(BlockLevelBox::SameFormattingContextBlock {
716                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
717                    contents,
718                    contains_floats,
719                })
720            },
721            BlockLevelCreator::Independent {
722                display_inside,
723                contents,
724            } => {
725                let context = IndependentFormattingContext::construct(
726                    context,
727                    info,
728                    display_inside,
729                    contents,
730                    self.propagated_data,
731                );
732                ArcRefCell::new(BlockLevelBox::Independent(context))
733            },
734            BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
735                display_inside,
736                contents,
737            } => ArcRefCell::new(BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(
738                ArcRefCell::new(AbsolutelyPositionedBox::construct(
739                    context,
740                    info,
741                    display_inside,
742                    contents,
743                )),
744            )),
745            BlockLevelCreator::OutOfFlowFloatBox {
746                display_inside,
747                contents,
748            } => ArcRefCell::new(BlockLevelBox::OutOfFlowFloatBox(FloatBox::construct(
749                context,
750                info,
751                display_inside,
752                contents,
753                self.propagated_data,
754            ))),
755            BlockLevelCreator::OutsideMarker {
756                contents,
757                list_item_style,
758            } => {
759                let contents = NonReplacedContents::OfPseudoElement(contents);
760                let block_container = BlockContainer::construct(
761                    context,
762                    info,
763                    contents,
764                    self.propagated_data,
765                    false, /* is_list_item */
766                );
767                // An outside ::marker must establish a BFC, and can't contain floats.
768                let block_formatting_context = BlockFormattingContext {
769                    contents: block_container,
770                    contains_floats: false,
771                };
772                ArcRefCell::new(BlockLevelBox::OutsideMarker(OutsideMarker {
773                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
774                    block_formatting_context,
775                    list_item_style,
776                }))
777            },
778            BlockLevelCreator::AnonymousTable { table_block } => table_block,
779        };
780        self.box_slot
781            .set(LayoutBox::BlockLevel(block_level_box.clone()));
782        block_level_box
783    }
784}
785
786impl IntermediateBlockContainer {
787    fn finish(self, context: &LayoutContext, info: &NodeAndStyleInfo<'_>) -> BlockContainer {
788        match self {
789            IntermediateBlockContainer::Deferred {
790                contents,
791                propagated_data,
792                is_list_item,
793            } => BlockContainer::construct(context, info, contents, propagated_data, is_list_item),
794            IntermediateBlockContainer::InlineFormattingContext(block_container) => block_container,
795        }
796    }
797}