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            NonReplacedContents::OfPseudoElement(contents).into(),
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(
480                || ArcRefCell::new(InlineBox::new(info)),
481                None,
482                old_layout_box,
483            );
484
485        if is_list_item {
486            if let Some((marker_info, marker_contents)) =
487                crate::lists::make_marker(self.context, info)
488            {
489                // Ignore `list-style-position` here:
490                // “If the list item is an inline box: this value is equivalent to `inside`.”
491                // https://drafts.csswg.org/css-lists/#list-style-position-outside
492                self.handle_list_item_marker_inside(&marker_info, marker_contents)
493            }
494        }
495
496        // `unwrap` doesn’t panic here because `is_replaced` returned `false`.
497        non_replaced_contents.traverse(self.context, info, self);
498
499        self.finish_anonymous_table_if_needed();
500
501        // As we are ending this inline box, during the course of the `traverse()` above, the ongoing
502        // inline formatting context may have been split around block-level elements. In that case,
503        // more than a single inline box tree item may have been produced for this inline-level box.
504        // `InlineFormattingContextBuilder::end_inline_box()` is returning all of those box tree
505        // items.
506        box_slot.set(LayoutBox::InlineLevel(
507            self.inline_formatting_context_builder
508                .as_mut()
509                .expect("Should be building an InlineFormattingContext")
510                .end_inline_box(),
511        ));
512    }
513
514    fn handle_block_level_element(
515        &mut self,
516        info: &NodeAndStyleInfo<'dom>,
517        display_inside: DisplayInside,
518        contents: Contents,
519        box_slot: BoxSlot<'dom>,
520    ) {
521        // We just found a block level element, all ongoing inline level boxes
522        // need to be split around it.
523        //
524        // After calling `split_around_block_and_finish`,
525        // `self.inline_formatting_context_builder` is set up with the state
526        // that we want to have after we push the block below.
527        if let Some(inline_formatting_context) = self
528            .inline_formatting_context_builder
529            .as_mut()
530            .and_then(|builder| {
531                builder.split_around_block_and_finish(
532                    self.context,
533                    !self.have_already_seen_first_line_for_text_indent,
534                    self.info.style.to_bidi_level(),
535                )
536            })
537        {
538            self.push_block_level_job_for_inline_formatting_context(inline_formatting_context);
539        }
540
541        let propagated_data = self.propagated_data;
542        let kind = match contents {
543            Contents::NonReplaced(contents) => match display_inside {
544                DisplayInside::Flow { is_list_item }
545                    // Fragment flags are just used to indicate that the element is not replaced, so empty
546                    // flags are okay here.
547                    if !info.style.establishes_block_formatting_context(
548                        FragmentFlags::empty()
549                    ) =>
550                {
551                    BlockLevelCreator::SameFormattingContextBlock(
552                        IntermediateBlockContainer::Deferred {
553                            contents,
554                            propagated_data,
555                            is_list_item,
556                        },
557                    )
558                },
559                _ => BlockLevelCreator::Independent {
560                    display_inside,
561                    contents: contents.into(),
562                },
563            },
564            Contents::Replaced(contents) => {
565                let contents = Contents::Replaced(contents);
566                BlockLevelCreator::Independent {
567                    display_inside,
568                    contents,
569                }
570            },
571        };
572        self.block_level_boxes.push(BlockLevelJob {
573            info: info.clone(),
574            box_slot,
575            kind,
576            propagated_data,
577        });
578
579        // Any block also counts as the first line for the purposes of text indent. Even if
580        // they don't actually indent.
581        self.have_already_seen_first_line_for_text_indent = true;
582    }
583
584    fn handle_absolutely_positioned_element(
585        &mut self,
586        info: &NodeAndStyleInfo<'dom>,
587        display_inside: DisplayInside,
588        contents: Contents,
589        box_slot: BoxSlot<'dom>,
590    ) {
591        // If the original display was inline-level, then we need an inline formatting context
592        // in order to compute the static position correctly.
593        // If it was block-level, we don't want to break an existing inline formatting context,
594        // so push it there (`LineItemLayout::layout_absolute` can handle this well). But if
595        // there is no inline formatting context, then we can avoid creating one.
596        let needs_inline_builder =
597            info.style.get_box().original_display.outside() == StyloDisplayOutside::Inline;
598        if needs_inline_builder {
599            self.ensure_inline_formatting_context_builder();
600        }
601        let inline_builder = self
602            .inline_formatting_context_builder
603            .as_mut()
604            .filter(|builder| needs_inline_builder || !builder.is_empty);
605        if let Some(inline_builder) = inline_builder {
606            let constructor = || {
607                ArcRefCell::new(AbsolutelyPositionedBox::construct(
608                    self.context,
609                    info,
610                    display_inside,
611                    contents,
612                ))
613            };
614            let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
615            let inline_level_box =
616                inline_builder.push_absolutely_positioned_box(constructor, old_layout_box);
617            box_slot.set(LayoutBox::InlineLevel(vec![inline_level_box]));
618            return;
619        }
620
621        let kind = BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
622            contents,
623            display_inside,
624        };
625        self.block_level_boxes.push(BlockLevelJob {
626            info: info.clone(),
627            box_slot,
628            kind,
629            propagated_data: self.propagated_data,
630        });
631    }
632
633    fn handle_float_element(
634        &mut self,
635        info: &NodeAndStyleInfo<'dom>,
636        display_inside: DisplayInside,
637        contents: Contents,
638        box_slot: BoxSlot<'dom>,
639    ) {
640        if let Some(builder) = self.inline_formatting_context_builder.as_mut() {
641            if !builder.is_empty {
642                let constructor = || {
643                    ArcRefCell::new(FloatBox::construct(
644                        self.context,
645                        info,
646                        display_inside,
647                        contents,
648                        self.propagated_data,
649                    ))
650                };
651                let old_layout_box = box_slot.take_layout_box_if_undamaged(info.damage);
652                let inline_level_box = builder.push_float_box(constructor, old_layout_box);
653                box_slot.set(LayoutBox::InlineLevel(vec![inline_level_box]));
654                return;
655            }
656        }
657
658        let kind = BlockLevelCreator::OutOfFlowFloatBox {
659            contents,
660            display_inside,
661        };
662        self.block_level_boxes.push(BlockLevelJob {
663            info: info.clone(),
664            box_slot,
665            kind,
666            propagated_data: self.propagated_data,
667        });
668    }
669
670    fn push_block_level_job_for_inline_formatting_context(
671        &mut self,
672        inline_formatting_context: InlineFormattingContext,
673    ) {
674        let layout_context = self.context;
675        let anonymous_info = self
676            .anonymous_box_info
677            .get_or_insert_with(|| {
678                self.info
679                    .with_pseudo_element(layout_context, PseudoElement::ServoAnonymousBox)
680                    .expect("Should never fail to create anonymous box")
681            })
682            .clone();
683
684        let box_slot = anonymous_info.node.box_slot();
685        self.block_level_boxes.push(BlockLevelJob {
686            info: anonymous_info,
687            box_slot,
688            kind: BlockLevelCreator::SameFormattingContextBlock(
689                IntermediateBlockContainer::InlineFormattingContext(
690                    BlockContainer::InlineFormattingContext(inline_formatting_context),
691                ),
692            ),
693            propagated_data: self.propagated_data,
694        });
695
696        self.have_already_seen_first_line_for_text_indent = true;
697    }
698}
699
700impl BlockLevelJob<'_> {
701    fn finish(self, context: &LayoutContext) -> ArcRefCell<BlockLevelBox> {
702        let info = &self.info;
703
704        // If this `BlockLevelBox` is undamaged and it has been laid out before, reuse
705        // the old one, while being sure to clear the layout cache.
706        if !info.damage.has_box_damage() {
707            if let Some(block_level_box) = match self.box_slot.slot.as_ref() {
708                Some(box_slot) => match &*box_slot.borrow() {
709                    Some(LayoutBox::BlockLevel(block_level_box)) => Some(block_level_box.clone()),
710                    _ => None,
711                },
712                None => None,
713            } {
714                return block_level_box;
715            }
716        }
717
718        let block_level_box = match self.kind {
719            BlockLevelCreator::SameFormattingContextBlock(intermediate_block_container) => {
720                let contents = intermediate_block_container.finish(context, info);
721                let contains_floats = contents.contains_floats();
722                ArcRefCell::new(BlockLevelBox::SameFormattingContextBlock {
723                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
724                    contents,
725                    contains_floats,
726                })
727            },
728            BlockLevelCreator::Independent {
729                display_inside,
730                contents,
731            } => {
732                let context = IndependentFormattingContext::construct(
733                    context,
734                    info,
735                    display_inside,
736                    contents,
737                    self.propagated_data,
738                );
739                ArcRefCell::new(BlockLevelBox::Independent(context))
740            },
741            BlockLevelCreator::OutOfFlowAbsolutelyPositionedBox {
742                display_inside,
743                contents,
744            } => ArcRefCell::new(BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(
745                ArcRefCell::new(AbsolutelyPositionedBox::construct(
746                    context,
747                    info,
748                    display_inside,
749                    contents,
750                )),
751            )),
752            BlockLevelCreator::OutOfFlowFloatBox {
753                display_inside,
754                contents,
755            } => ArcRefCell::new(BlockLevelBox::OutOfFlowFloatBox(FloatBox::construct(
756                context,
757                info,
758                display_inside,
759                contents,
760                self.propagated_data,
761            ))),
762            BlockLevelCreator::OutsideMarker {
763                contents,
764                list_item_style,
765            } => {
766                let contents = NonReplacedContents::OfPseudoElement(contents);
767                let block_container = BlockContainer::construct(
768                    context,
769                    info,
770                    contents,
771                    self.propagated_data,
772                    false, /* is_list_item */
773                );
774                // An outside ::marker must establish a BFC, and can't contain floats.
775                let block_formatting_context = BlockFormattingContext {
776                    contents: block_container,
777                    contains_floats: false,
778                };
779                ArcRefCell::new(BlockLevelBox::OutsideMarker(OutsideMarker {
780                    base: LayoutBoxBase::new(info.into(), info.style.clone()),
781                    block_formatting_context,
782                    list_item_style,
783                }))
784            },
785            BlockLevelCreator::AnonymousTable { table_block } => table_block,
786        };
787        self.box_slot
788            .set(LayoutBox::BlockLevel(block_level_box.clone()));
789        block_level_box
790    }
791}
792
793impl IntermediateBlockContainer {
794    fn finish(self, context: &LayoutContext, info: &NodeAndStyleInfo<'_>) -> BlockContainer {
795        match self {
796            IntermediateBlockContainer::Deferred {
797                contents,
798                propagated_data,
799                is_list_item,
800            } => BlockContainer::construct(context, info, contents, propagated_data, is_list_item),
801            IntermediateBlockContainer::InlineFormattingContext(block_container) => block_container,
802        }
803    }
804}