Skip to main content

layout/
dom.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::marker::PhantomData;
6
7use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
8use layout_api::{
9    GenericLayoutDataTrait, LayoutDataTrait, LayoutElement, LayoutElementType, LayoutNode,
10    LayoutNodeType as ScriptLayoutNodeType, NodeRenderingType, SVGElementData,
11};
12use malloc_size_of_derive::MallocSizeOf;
13use script::layout_dom::ServoLayoutNode;
14use servo_arc::Arc as ServoArc;
15use smallvec::SmallVec;
16use style::context::SharedStyleContext;
17use style::properties::ComputedValues;
18use style::selector_parser::PseudoElement;
19use style::values::specified::box_::DisplayOutside as StyloDisplayOutside;
20use web_atoms::{local_name, ns};
21
22use crate::cell::{ArcRefCell, WeakRefCell};
23use crate::context::LayoutContext;
24use crate::dom_traversal::{Contents, NodeAndStyleInfo};
25use crate::flexbox::FlexLevelBox;
26use crate::flow::inline::text_run::TextRun;
27use crate::flow::inline::{InlineItem, SharedInlineStyles, WeakInlineItem};
28use crate::flow::{BlockLevelBox, BlockLevelCreator};
29use crate::fragment_tree::{Fragment, FragmentFlags};
30use crate::geom::PhysicalSize;
31use crate::layout_box_base::LayoutBoxBase;
32use crate::replaced::{CanvasInfo, IFrameInfo, ImageInfo, VideoInfo};
33use crate::style_ext::{
34    ComputedValuesExt, Display, DisplayGeneratingBox, DisplayLayoutInternal, DisplayOutside,
35};
36use crate::table::{TableLevelBox, WeakTableLevelBox};
37use crate::taffy::TaffyItemBox;
38
39#[derive(MallocSizeOf)]
40pub struct PseudoLayoutData {
41    pseudo: PseudoElement,
42    data: ArcRefCell<InnerDOMLayoutData>,
43}
44
45/// The data that is stored in each DOM node that is used by layout.
46#[derive(Default, MallocSizeOf)]
47pub struct InnerDOMLayoutData {
48    pub(super) self_box: ArcRefCell<Option<LayoutBox>>,
49    pub(super) pseudo_boxes: SmallVec<[PseudoLayoutData; 2]>,
50}
51
52impl InnerDOMLayoutData {
53    fn pseudo_layout_data(
54        &self,
55        pseudo_element: PseudoElement,
56    ) -> Option<ArcRefCell<InnerDOMLayoutData>> {
57        for pseudo_layout_data in self.pseudo_boxes.iter() {
58            if pseudo_element == pseudo_layout_data.pseudo {
59                return Some(pseudo_layout_data.data.clone());
60            }
61        }
62        None
63    }
64
65    fn create_pseudo_layout_data(
66        &mut self,
67        pseudo_element: PseudoElement,
68    ) -> ArcRefCell<InnerDOMLayoutData> {
69        let data: ArcRefCell<InnerDOMLayoutData> = Default::default();
70        self.pseudo_boxes.push(PseudoLayoutData {
71            pseudo: pseudo_element,
72            data: data.clone(),
73        });
74        data
75    }
76
77    fn fragments(&self) -> Vec<Fragment> {
78        self.self_box
79            .borrow()
80            .as_ref()
81            .and_then(|layout_box| layout_box.with_base(LayoutBoxBase::fragments))
82            .unwrap_or_default()
83    }
84
85    fn repair_style(&self, node: &ServoLayoutNode, context: &SharedStyleContext) {
86        if let Some(layout_object) = &*self.self_box.borrow() {
87            layout_object.repair_style(context, node, &node.style(context));
88        }
89
90        for pseudo_layout_data in self.pseudo_boxes.iter() {
91            let Some(node_with_pseudo) = node.with_pseudo(pseudo_layout_data.pseudo) else {
92                continue;
93            };
94            pseudo_layout_data
95                .data
96                .borrow()
97                .repair_style(&node_with_pseudo, context);
98        }
99    }
100
101    fn with_layout_box_base(&self, callback: impl Fn(&LayoutBoxBase)) {
102        if let Some(data) = self.self_box.borrow().as_ref() {
103            data.with_base(callback);
104        }
105    }
106
107    fn with_layout_box_base_including_pseudos(&self, callback: impl Fn(&LayoutBoxBase)) {
108        self.with_layout_box_base(&callback);
109        for pseudo_layout_data in self.pseudo_boxes.iter() {
110            pseudo_layout_data
111                .data
112                .borrow()
113                .with_layout_box_base(&callback);
114        }
115    }
116}
117
118/// A box that is stored in one of the `DOMLayoutData` slots.
119#[derive(Debug, MallocSizeOf)]
120pub(super) enum LayoutBox {
121    DisplayContents(SharedInlineStyles),
122    BlockLevel(ArcRefCell<BlockLevelBox>),
123    InlineLevel(InlineItem),
124    FlexLevel(ArcRefCell<FlexLevelBox>),
125    TableLevelBox(TableLevelBox),
126    TaffyItemBox(ArcRefCell<TaffyItemBox>),
127    Text(ArcRefCell<TextRun>),
128}
129
130impl LayoutBox {
131    pub(crate) fn with_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> Option<T> {
132        Some(match self {
133            LayoutBox::DisplayContents(..) | LayoutBox::Text(..) => return None,
134            LayoutBox::BlockLevel(block_level_box) => block_level_box.borrow().with_base(callback),
135            LayoutBox::InlineLevel(inline_item) => inline_item.with_base(callback),
136            LayoutBox::FlexLevel(flex_level_box) => flex_level_box.borrow().with_base(callback),
137            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box.borrow().with_base(callback),
138            LayoutBox::TableLevelBox(table_box) => table_box.with_base(callback),
139        })
140    }
141
142    pub(crate) fn with_base_mut<T>(
143        &mut self,
144        callback: impl FnOnce(&mut LayoutBoxBase) -> T,
145    ) -> Option<T> {
146        Some(match self {
147            LayoutBox::DisplayContents(..) | LayoutBox::Text(..) => return None,
148            LayoutBox::BlockLevel(block_level_box) => {
149                block_level_box.borrow_mut().with_base_mut(callback)
150            },
151            LayoutBox::InlineLevel(inline_item) => inline_item.with_base_mut(callback),
152            LayoutBox::FlexLevel(flex_level_box) => {
153                flex_level_box.borrow_mut().with_base_mut(callback)
154            },
155            LayoutBox::TaffyItemBox(taffy_item_box) => {
156                taffy_item_box.borrow_mut().with_base_mut(callback)
157            },
158            LayoutBox::TableLevelBox(table_box) => table_box.with_base_mut(callback),
159        })
160    }
161
162    fn repair_style(
163        &self,
164        context: &SharedStyleContext,
165        node: &ServoLayoutNode,
166        new_style: &ServoArc<ComputedValues>,
167    ) {
168        match self {
169            LayoutBox::DisplayContents(inline_shared_styles) => {
170                *inline_shared_styles.style.borrow_mut() = new_style.clone();
171                *inline_shared_styles.selected.borrow_mut() = node.selected_style(context);
172            },
173            LayoutBox::BlockLevel(block_level_box) => {
174                block_level_box
175                    .borrow_mut()
176                    .repair_style(context, node, new_style);
177            },
178            LayoutBox::InlineLevel(inline_item) => {
179                inline_item.repair_style(context, node, new_style);
180            },
181            LayoutBox::FlexLevel(flex_level_box) => flex_level_box
182                .borrow_mut()
183                .repair_style(context, node, new_style),
184            LayoutBox::TableLevelBox(table_level_box) => {
185                table_level_box.repair_style(context, node, new_style)
186            },
187            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box
188                .borrow_mut()
189                .repair_style(context, node, new_style),
190            LayoutBox::Text(..) => {
191                // There is nothing to update in this case.
192            },
193        }
194    }
195
196    fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
197        match self {
198            Self::DisplayContents(_) => {
199                // This box can't have children, its contents get reparented to its parent.
200                // Therefore, no need to do anything.
201            },
202            Self::BlockLevel(block_level_box) => {
203                block_level_box.borrow().attached_to_tree(layout_box)
204            },
205            Self::InlineLevel(inline_item) => inline_item.attached_to_tree(layout_box),
206            Self::FlexLevel(flex_level_box) => flex_level_box.borrow().attached_to_tree(layout_box),
207            Self::TableLevelBox(table_level_box) => table_level_box.attached_to_tree(layout_box),
208            Self::TaffyItemBox(taffy_item_box) => {
209                taffy_item_box.borrow().attached_to_tree(layout_box)
210            },
211            Self::Text(..) => {
212                // This kind of box cannot have children, so no need to do anything.
213            },
214        }
215    }
216
217    fn downgrade(&self) -> WeakLayoutBox {
218        match self {
219            Self::DisplayContents(inline_shared_styles) => {
220                WeakLayoutBox::DisplayContents(inline_shared_styles.clone())
221            },
222            Self::BlockLevel(block_level_box) => {
223                WeakLayoutBox::BlockLevel(block_level_box.downgrade())
224            },
225            Self::InlineLevel(inline_item) => WeakLayoutBox::InlineLevel(inline_item.downgrade()),
226            Self::FlexLevel(flex_level_box) => WeakLayoutBox::FlexLevel(flex_level_box.downgrade()),
227            Self::TableLevelBox(table_level_box) => {
228                WeakLayoutBox::TableLevelBox(table_level_box.downgrade())
229            },
230            Self::TaffyItemBox(taffy_item_box) => {
231                WeakLayoutBox::TaffyItemBox(taffy_item_box.downgrade())
232            },
233            Self::Text(text_run) => WeakLayoutBox::Text(text_run.downgrade()),
234        }
235    }
236}
237
238#[derive(Clone, Debug, MallocSizeOf)]
239pub(super) enum WeakLayoutBox {
240    DisplayContents(SharedInlineStyles),
241    BlockLevel(WeakRefCell<BlockLevelBox>),
242    InlineLevel(WeakInlineItem),
243    FlexLevel(WeakRefCell<FlexLevelBox>),
244    TableLevelBox(WeakTableLevelBox),
245    TaffyItemBox(WeakRefCell<TaffyItemBox>),
246    Text(WeakRefCell<TextRun>),
247}
248
249impl WeakLayoutBox {
250    pub(crate) fn upgrade(&self) -> Option<LayoutBox> {
251        Some(match self {
252            Self::DisplayContents(inline_shared_styles) => {
253                LayoutBox::DisplayContents(inline_shared_styles.clone())
254            },
255            Self::BlockLevel(block_level_box) => LayoutBox::BlockLevel(block_level_box.upgrade()?),
256            Self::InlineLevel(inline_item) => LayoutBox::InlineLevel(inline_item.upgrade()?),
257            Self::FlexLevel(flex_level_box) => LayoutBox::FlexLevel(flex_level_box.upgrade()?),
258            Self::TableLevelBox(table_level_box) => {
259                LayoutBox::TableLevelBox(table_level_box.upgrade()?)
260            },
261            Self::TaffyItemBox(taffy_item_box) => {
262                LayoutBox::TaffyItemBox(taffy_item_box.upgrade()?)
263            },
264            Self::Text(text_run) => LayoutBox::Text(text_run.upgrade()?),
265        })
266    }
267}
268
269/// A wrapper for [`InnerDOMLayoutData`]. This is necessary to give the entire data
270/// structure interior mutability, as we will need to mutate the layout data of
271/// non-mutable DOM nodes.
272#[derive(Default, MallocSizeOf)]
273pub struct DOMLayoutData(AtomicRefCell<InnerDOMLayoutData>);
274
275// The implementation of this trait allows the data to be stored in the DOM.
276impl LayoutDataTrait for DOMLayoutData {}
277impl GenericLayoutDataTrait for DOMLayoutData {
278    fn as_any(&self) -> &dyn std::any::Any {
279        self
280    }
281}
282
283pub struct BoxSlot<'dom> {
284    pub(crate) slot: ArcRefCell<Option<LayoutBox>>,
285    pub(crate) marker: PhantomData<&'dom ()>,
286}
287
288impl From<ArcRefCell<Option<LayoutBox>>> for BoxSlot<'_> {
289    fn from(slot: ArcRefCell<Option<LayoutBox>>) -> Self {
290        Self {
291            slot,
292            marker: PhantomData,
293        }
294    }
295}
296
297/// A mutable reference to a `LayoutBox` stored in a DOM element.
298impl BoxSlot<'_> {
299    pub(crate) fn set(self, layout_box: LayoutBox) {
300        layout_box.attached_to_tree(layout_box.downgrade());
301        *self.slot.borrow_mut() = Some(layout_box);
302    }
303
304    pub(crate) fn take_layout_box(&self) -> Option<LayoutBox> {
305        self.slot.borrow_mut().take()
306    }
307
308    /// Call [`Self::take_layout_box`] and try to unwrap it into a [`TextRun`], returning `None` if
309    /// the slot is empty or it does not contain a [`TextRun`]. Note that this will *always* clear
310    /// the [`BoxSlot`].
311    pub(crate) fn take_layout_box_as_text_run(&self) -> Option<ArcRefCell<TextRun>> {
312        match self.take_layout_box()? {
313            LayoutBox::Text(old_text_run) => Some(old_text_run),
314            _ => None,
315        }
316    }
317}
318
319impl Drop for BoxSlot<'_> {
320    fn drop(&mut self) {
321        if !std::thread::panicking() {
322            assert!(self.slot.borrow().is_some(), "failed to set a layout box");
323        }
324    }
325}
326
327pub(crate) trait NodeExt<'dom> {
328    /// Returns the relevant data wrapping into respective struct and its size in pixels.
329    fn as_image(&self) -> Option<(ImageInfo, PhysicalSize<f64>)>;
330    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)>;
331    fn as_iframe(&self) -> Option<IFrameInfo>;
332    fn as_video(&self) -> Option<(VideoInfo, Option<PhysicalSize<f64>>)>;
333    fn as_svg(&self) -> Option<SVGElementData<'dom>>;
334    fn as_typeless_object_with_data_attribute(&self) -> Option<String>;
335
336    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData>;
337    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>>;
338    fn inner_layout_data_mut(&self) -> Option<AtomicRefMut<'dom, InnerDOMLayoutData>>;
339    fn box_slot(&self) -> BoxSlot<'dom>;
340
341    /// Remove boxes for the element itself, and all of its pseudo-element boxes.
342    fn unset_all_boxes(&self);
343
344    /// Returns the [`NodeRenderingType`] for this [`LayoutNode`] which describes whether
345    /// the node is being rendered, delegating rendering, or not being rendered at all
346    /// based on whether it has a [`LayoutBox`] and what kind.
347    fn rendering_type(&self) -> NodeRenderingType;
348
349    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment>;
350    fn with_layout_box_base_including_pseudos(&self, callback: impl Fn(&LayoutBoxBase));
351
352    fn repair_style(&self, context: &SharedStyleContext);
353
354    /// Whether or not this node isolates downward flowing box tree rebuild damage and
355    /// fragment tree layout cache damage. Roughly, this corresponds to independent
356    /// formatting context boundaries.
357    ///
358    /// - The node's boxes themselves will be rebuilt, but not the descendant node's
359    ///   boxes.
360    /// - The node's fragment tree layout will be rebuilt, not the descendent node's
361    ///   fragment tree layout cache.
362    ///
363    /// When this node has no box yet, `false` is returned.
364    fn isolates_damage_for_damage_propagation(&self) -> bool;
365
366    /// Try to re-run box tree reconstruction from this point. This can succeed if the
367    /// node itself is still valid and isolates box tree damage from ancestors (for
368    /// instance, if it starts an independent formatting context). **Note:** This assumes
369    /// that no ancestors have box damage.
370    ///
371    /// Returns `true` if box tree reconstruction was sucessful and `false` otherwise.
372    fn rebuild_box_tree_from_independent_formatting_context(
373        &self,
374        layout_context: &LayoutContext,
375    ) -> bool;
376
377    /// Whether or not the style of this node indicates that it should be absolutely
378    /// positioned.
379    fn is_absolutely_positioned(&self) -> bool;
380}
381
382impl<'dom> NodeExt<'dom> for ServoLayoutNode<'dom> {
383    fn as_image(&self) -> Option<(ImageInfo, PhysicalSize<f64>)> {
384        let (resource, metadata) = self.image_data()?;
385        let width = metadata.map(|metadata| metadata.width).unwrap_or_default();
386        let height = metadata.map(|metadata| metadata.height).unwrap_or_default();
387        let (mut width, mut height) = (width as f64, height as f64);
388        // Take `image_density` into account for calculating the size in pixels for images.
389        if let Some(density) = self.image_density().filter(|density| *density != 1.) {
390            width /= density;
391            height /= density;
392        }
393        Some((
394            ImageInfo {
395                image: resource,
396                showing_broken_image_icon: self.showing_broken_image_icon(),
397                url: self.image_url(),
398            },
399            PhysicalSize::new(width, height),
400        ))
401    }
402
403    fn as_svg(&self) -> Option<SVGElementData<'dom>> {
404        self.svg_data()
405    }
406
407    fn as_video(&self) -> Option<(VideoInfo, Option<PhysicalSize<f64>>)> {
408        let data = self.media_data()?;
409        let natural_size = if let Some(frame) = data.current_frame {
410            Some(PhysicalSize::new(frame.width.into(), frame.height.into()))
411        } else {
412            data.metadata
413                .map(|meta| PhysicalSize::new(meta.width.into(), meta.height.into()))
414        };
415        Some((
416            VideoInfo {
417                image_key: data.current_frame.map(|frame| frame.image_key),
418            },
419            natural_size,
420        ))
421    }
422
423    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)> {
424        let canvas_data = self.canvas_data()?;
425        let source = canvas_data.image_key;
426        Some((
427            CanvasInfo { source },
428            PhysicalSize::new(canvas_data.width.into(), canvas_data.height.into()),
429        ))
430    }
431
432    fn as_iframe(&self) -> Option<IFrameInfo> {
433        match (self.iframe_pipeline_id(), self.iframe_browsing_context_id()) {
434            (Some(pipeline_id), Some(browsing_context_id)) => Some(IFrameInfo {
435                pipeline_id,
436                browsing_context_id,
437            }),
438            _ => None,
439        }
440    }
441
442    fn as_typeless_object_with_data_attribute(&self) -> Option<String> {
443        if self.type_id() !=
444            Some(ScriptLayoutNodeType::Element(
445                LayoutElementType::HTMLObjectElement,
446            ))
447        {
448            return None;
449        }
450
451        // TODO: This is the what the legacy layout system did, but really if Servo
452        // supports any `<object>` that's an image, it should support those with URLs
453        // and `type` attributes with image mime types.
454        let element = self.as_element()?;
455        if element.attribute(&ns!(), &local_name!("type")).is_some() {
456            return None;
457        }
458        element
459            .attribute_as_str(&ns!(), &local_name!("data"))
460            .map(|string| string.to_owned())
461    }
462
463    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData> {
464        if self.layout_data().is_none() {
465            self.initialize_layout_data::<DOMLayoutData>();
466        }
467        self.layout_data()
468            .unwrap()
469            .as_any()
470            .downcast_ref::<DOMLayoutData>()
471            .unwrap()
472            .0
473            .borrow_mut()
474    }
475
476    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>> {
477        self.layout_data().map(|data| {
478            data.as_any()
479                .downcast_ref::<DOMLayoutData>()
480                .unwrap()
481                .0
482                .borrow()
483        })
484    }
485
486    fn inner_layout_data_mut(&self) -> Option<AtomicRefMut<'dom, InnerDOMLayoutData>> {
487        self.layout_data().map(|data| {
488            data.as_any()
489                .downcast_ref::<DOMLayoutData>()
490                .unwrap()
491                .0
492                .borrow_mut()
493        })
494    }
495
496    fn box_slot(&self) -> BoxSlot<'dom> {
497        let pseudo_element_chain = self.pseudo_element_chain();
498        let Some(primary) = pseudo_element_chain.primary else {
499            return self.ensure_inner_layout_data().self_box.clone().into();
500        };
501
502        let Some(secondary) = pseudo_element_chain.secondary else {
503            let primary_layout_data = self
504                .ensure_inner_layout_data()
505                .create_pseudo_layout_data(primary);
506            return primary_layout_data.borrow().self_box.clone().into();
507        };
508
509        // It's *very* important that this not borrow the element's main
510        // `InnerLayoutData`. Primary pseudo-elements are processed at the same recursion
511        // level as the main data, so the `BoxSlot` is created sequentially with other
512        // primary pseudo-elements and the element itself. The secondary pseudo-element is
513        // one level deep, so could be happening in parallel with the primary
514        // pseudo-elements or main element layout.
515        let primary_layout_data = self
516            .inner_layout_data()
517            .expect("Should already have element InnerLayoutData here.")
518            .pseudo_layout_data(primary)
519            .expect("Should already have primary pseudo-element InnerLayoutData here");
520        let secondary_layout_data = primary_layout_data
521            .borrow_mut()
522            .create_pseudo_layout_data(secondary);
523        secondary_layout_data.borrow().self_box.clone().into()
524    }
525
526    fn unset_all_boxes(&self) {
527        let mut layout_data = self.ensure_inner_layout_data();
528        *layout_data.self_box.borrow_mut() = None;
529        layout_data.pseudo_boxes.clear();
530
531        // Stylo already takes care of removing all layout data
532        // for DOM descendants of elements with `display: none`.
533    }
534
535    fn rendering_type(&self) -> NodeRenderingType {
536        let Some(layout_data) = self.inner_layout_data() else {
537            return NodeRenderingType::NotRendered;
538        };
539        match &*layout_data.self_box.borrow() {
540            Some(LayoutBox::DisplayContents(..)) => NodeRenderingType::DelegatesRendering,
541            Some(..) => NodeRenderingType::Rendered,
542            None => NodeRenderingType::NotRendered,
543        }
544    }
545
546    fn with_layout_box_base_including_pseudos(&self, callback: impl Fn(&LayoutBoxBase)) {
547        if let Some(inner_layout_data) = self.inner_layout_data() {
548            inner_layout_data.with_layout_box_base_including_pseudos(callback);
549        }
550    }
551
552    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment> {
553        let Some(layout_data) = self.inner_layout_data() else {
554            return vec![];
555        };
556        match pseudo_element {
557            Some(pseudo_element) => layout_data
558                .pseudo_layout_data(pseudo_element)
559                .map(|pseudo_layout_data| pseudo_layout_data.borrow().fragments())
560                .unwrap_or_default(),
561            None => layout_data.fragments(),
562        }
563    }
564
565    fn repair_style(&self, context: &SharedStyleContext) {
566        if let Some(layout_data) = self.inner_layout_data() {
567            layout_data.repair_style(self, context);
568        }
569    }
570
571    fn isolates_damage_for_damage_propagation(&self) -> bool {
572        // Do not run incremental box and fragment tree layout at the `<body>` or root element as
573        // there is some special processing that must happen for these elements and it currently
574        // only happens when doing a full box tree construction traversal.
575        if self.as_element().is_some_and(|element| {
576            element.is_body_element_of_html_element_root() || element.is_root()
577        }) {
578            return false;
579        }
580
581        let Some(inner_layout_data) = self.inner_layout_data() else {
582            return false;
583        };
584        let self_box = inner_layout_data.self_box.borrow();
585        let Some(self_box) = &*self_box else {
586            return false;
587        };
588
589        match self_box {
590            LayoutBox::DisplayContents(..) => false,
591            LayoutBox::BlockLevel(block_level) => matches!(
592                &*block_level.borrow(),
593                BlockLevelBox::Independent(..) |
594                    BlockLevelBox::OutOfFlowFloatBox(..) |
595                    BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(..)
596            ),
597            LayoutBox::InlineLevel(inline_level) => matches!(
598                inline_level,
599                InlineItem::OutOfFlowAbsolutelyPositionedBox(..) | InlineItem::Atomic(..)
600            ),
601            LayoutBox::FlexLevel(..) => true,
602            LayoutBox::TableLevelBox(table_level_box) => matches!(
603                table_level_box,
604                TableLevelBox::Cell(..) | TableLevelBox::Caption(..),
605            ),
606            LayoutBox::TaffyItemBox(..) => true,
607            LayoutBox::Text(..) => unreachable!("An element should never be a text node"),
608        }
609    }
610
611    fn rebuild_box_tree_from_independent_formatting_context(
612        &self,
613        layout_context: &LayoutContext,
614    ) -> bool {
615        // Do not run incremental box tree layout at the `<body>` or root element as there
616        // is some special processing that must happen for these elements and it currently
617        // only happens when doing a full box tree construction traversal.
618        if self.as_element().is_some_and(|element| {
619            element.is_body_element_of_html_element_root() || element.is_root()
620        }) {
621            return false;
622        }
623
624        let layout_box = {
625            let Some(mut inner_layout_data) = self.inner_layout_data_mut() else {
626                return false;
627            };
628            inner_layout_data.pseudo_boxes.clear();
629            inner_layout_data.self_box.clone()
630        };
631
632        let layout_box = layout_box.borrow();
633        let Some(layout_box) = &*layout_box else {
634            return false;
635        };
636
637        let info = NodeAndStyleInfo::new(*self, self.style(&layout_context.style_context));
638        let box_style = info.style.get_box();
639        let Display::GeneratingBox(display) = box_style.display.into() else {
640            return false;
641        };
642        let contents = || {
643            assert!(
644                self.pseudo_element_chain().is_empty(),
645                "Shouldn't try to rebuild box tree from a pseudo-element"
646            );
647            Contents::for_element(info.node, layout_context)
648        };
649        match layout_box {
650            LayoutBox::DisplayContents(..) => false,
651            LayoutBox::BlockLevel(block_level) => {
652                let mut block_level = block_level.borrow_mut();
653                match &mut *block_level {
654                    BlockLevelBox::Independent(independent_formatting_context) => {
655                        let DisplayGeneratingBox::OutsideInside {
656                            outside: DisplayOutside::Block,
657                            inside: display_inside,
658                        } = display
659                        else {
660                            return false;
661                        };
662                        if !matches!(
663                            BlockLevelCreator::new_for_inflow_block_level_element(
664                                &info,
665                                display_inside,
666                                contents(),
667                                independent_formatting_context.propagated_data,
668                            ),
669                            BlockLevelCreator::Independent { .. }
670                        ) {
671                            return false;
672                        }
673                        independent_formatting_context.rebuild(layout_context, &info);
674                        true
675                    },
676                    BlockLevelBox::OutOfFlowFloatBox(float_box) => {
677                        if !info.style.clone_float().is_floating() {
678                            return false;
679                        }
680                        float_box.contents.rebuild(layout_context, &info);
681                        true
682                    },
683                    BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned_box) => {
684                        // Even if absolute positioning blockifies the outer display type, if the
685                        // original display was inline-level, then the box needs to be handled as
686                        // an inline-level in order to compute the static position correctly.
687                        // See `BlockContainerBuilder::handle_absolutely_positioned_element()`.
688                        if !info.style.clone_position().is_absolutely_positioned() ||
689                            box_style.original_display.outside() != StyloDisplayOutside::Block
690                        {
691                            return false;
692                        }
693                        positioned_box
694                            .borrow_mut()
695                            .context
696                            .rebuild(layout_context, &info);
697                        true
698                    },
699                    _ => false,
700                }
701            },
702            LayoutBox::InlineLevel(inline_level) => match inline_level {
703                InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
704                    if !info.style.clone_position().is_absolutely_positioned() {
705                        return false;
706                    }
707                    positioned_box
708                        .borrow_mut()
709                        .context
710                        .rebuild(layout_context, &info);
711                    true
712                },
713                InlineItem::Atomic(atomic_box, _, _) => {
714                    let flags = match contents() {
715                        Contents::NonReplaced(_) => FragmentFlags::empty(),
716                        Contents::Replaced(_) => FragmentFlags::IS_REPLACED,
717                        Contents::Widget(_) => FragmentFlags::IS_WIDGET,
718                    };
719                    if !info.style.is_atomic_inline_level(flags) {
720                        return false;
721                    }
722                    atomic_box.borrow_mut().rebuild(layout_context, &info);
723                    true
724                },
725                _ => false,
726            },
727            LayoutBox::FlexLevel(flex_level_box) => {
728                let mut flex_level_box = flex_level_box.borrow_mut();
729                match &mut *flex_level_box {
730                    FlexLevelBox::FlexItem(flex_item_box) => {
731                        if info.style.clone_position().is_absolutely_positioned() ||
732                            flex_item_box.style().clone_order() != info.style.clone_order()
733                        {
734                            return false;
735                        }
736                        flex_item_box
737                            .independent_formatting_context
738                            .rebuild(layout_context, &info)
739                    },
740                    FlexLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned_box) => {
741                        if !info.style.clone_position().is_absolutely_positioned() {
742                            return false;
743                        }
744                        positioned_box
745                            .borrow_mut()
746                            .context
747                            .rebuild(layout_context, &info);
748                    },
749                }
750                true
751            },
752            LayoutBox::TableLevelBox(table_level_box) => match table_level_box {
753                TableLevelBox::Caption(caption) => {
754                    if display !=
755                        DisplayGeneratingBox::LayoutInternal(DisplayLayoutInternal::TableCaption)
756                    {
757                        return false;
758                    }
759                    caption.borrow_mut().context.rebuild(layout_context, &info);
760                    true
761                },
762                TableLevelBox::Cell(table_cell) => {
763                    if display !=
764                        DisplayGeneratingBox::LayoutInternal(DisplayLayoutInternal::TableCell)
765                    {
766                        return false;
767                    }
768                    table_cell
769                        .borrow_mut()
770                        .context
771                        .rebuild(layout_context, &info);
772                    true
773                },
774                _ => false,
775            },
776            LayoutBox::TaffyItemBox(..) => false,
777            LayoutBox::Text(..) => unreachable!("An element should never be a text node"),
778        }
779    }
780
781    fn is_absolutely_positioned(&self) -> bool {
782        self.as_element().is_some_and(|element| {
783            element
784                .element_data()
785                .styles
786                .primary()
787                .clone_position()
788                .is_absolutely_positioned()
789        })
790    }
791}