Skip to main content

layout/flow/
root.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 app_units::Au;
6use euclid::Rect;
7use euclid::default::Size2D as UntypedSize2D;
8use layout_api::{AxesOverflow, LayoutElement, LayoutNode};
9use malloc_size_of_derive::MallocSizeOf;
10use paint_api::display_list::AxesScrollSensitivity;
11use script::layout_dom::ServoLayoutNode;
12use servo_arc::Arc as ServoArc;
13use style::context::SharedStyleContext;
14use style::logical_geometry::WritingMode;
15use style::properties::ComputedValues;
16use style::values::computed::{Display as StyleDisplay, Overflow};
17use style_traits::CSSPixel;
18
19use crate::PropagatedBoxTreeData;
20use crate::cell::ArcRefCell;
21use crate::containing_block::DefiniteContainingBlock;
22use crate::context::LayoutContext;
23use crate::dom::{LayoutBox, NodeExt};
24use crate::dom_traversal::{Contents, NodeAndStyleInfo};
25use crate::flow::float::FloatBox;
26use crate::flow::{BlockContainer, BlockFormattingContext, BlockLevelBox};
27use crate::formatting_contexts::IndependentFormattingContext;
28use crate::fragment_tree::{FragmentFlags, FragmentTree};
29use crate::geom::{LogicalVec2, PhysicalSize};
30use crate::positioned::{AbsolutelyPositionedBox, PositioningContext};
31use crate::style_ext::Display;
32
33#[derive(MallocSizeOf)]
34pub struct BoxTree {
35    /// Contains typically exactly one block-level box, which was generated by the root element.
36    /// There may be zero if that element has `display: none`.
37    root: BlockFormattingContext,
38    /// Whether or not the viewport should be sensitive to scrolling input events in two axes
39    pub(crate) viewport_overflow: AxesOverflow,
40    /// The style to use for the initial containing block.
41    pub(crate) initial_containing_block_style: ServoArc<ComputedValues>,
42}
43
44impl BoxTree {
45    #[servo_tracing::instrument(name = "Box Tree Construction", skip_all)]
46    pub(crate) fn construct(context: &LayoutContext, root_element: ServoLayoutNode<'_>) -> Self {
47        let style_for_writing_mode =
48            Self::writing_mode_source_style(&context.style_context, root_element);
49        let boxes = construct_for_root_element(context, root_element, &style_for_writing_mode);
50
51        // Zero box for `:root { display: none }`, one for the root element otherwise.
52        assert!(boxes.len() <= 1);
53
54        let default_style = context
55            .style_context
56            .stylist
57            .device()
58            .default_computed_values_arc();
59        let initial_containing_block_style = BoxTree::style_with_writing_mode_source_style(
60            default_style.clone(),
61            &style_for_writing_mode,
62        );
63
64        let viewport_overflow = Self::viewport_overflow(root_element, boxes.first());
65        let contents = BlockContainer::BlockLevelBoxes(boxes);
66        Self {
67            root: BlockFormattingContext::from_block_container(
68                contents, /* is_table_cell = */ false, /* textarea_size = */ None,
69            ),
70            // From https://www.w3.org/TR/css-overflow-3/#overflow-propagation:
71            // > If visible is applied to the viewport, it must be interpreted as auto.
72            // > If clip is applied to the viewport, it must be interpreted as hidden.
73            viewport_overflow: viewport_overflow.to_scrollable(),
74            initial_containing_block_style,
75        }
76    }
77
78    /// From <https://drafts.csswg.org/css-writing-modes/#principal-flow>:
79    ///
80    /// > The principal writing mode of the document is determined by the used
81    /// > writing-mode, direction, and text-orientation values of the root element. This
82    /// > writing mode is used, for example, to determine the direction of scrolling and
83    /// > the default page progression direction.
84    /// >
85    /// > As a special case for handling HTML documents, if the root element has a body
86    /// > child element [HTML] whose display value is not none, the used value of the of
87    /// > writing-mode and direction properties on root element are taken from the
88    /// > computed writing-mode and direction of the first such child element instead of
89    /// > from the root element’s own values. The UA may also propagate the value of
90    /// > text-orientation in this manner. Note that this does not affect the computed
91    /// > values of writing-mode, direction, or text-orientation of the root element
92    /// > itself.
93    pub(crate) fn writing_mode_source_style(
94        context: &SharedStyleContext,
95        root_element: ServoLayoutNode<'_>,
96    ) -> ServoArc<ComputedValues> {
97        // See the similar check in viewport_overflow. If there's no root box, then there
98        // will never be a box for the body either.
99        let root_element_style = root_element.style(context);
100
101        // https://drafts.csswg.org/css-display-3/#transformations
102        // “'display' of 'contents' computes to 'block' on the root element”
103        debug_assert_ne!(*root_element_style.get_display(), StyleDisplay::Contents);
104
105        if *root_element_style.get_display() == StyleDisplay::None {
106            return root_element_style;
107        }
108
109        // Unlike what the spec implies, we stop iterating when we find the first <body>,
110        // even if it's not suitable because it lacks a box. This matches other browsers.
111        // See https://github.com/w3c/csswg-drafts/issues/12644
112        let Some(body) = root_element.flat_tree_children().find(|child| {
113            child
114                .as_element()
115                .is_some_and(|element| element.is_body_element_of_html_element_root())
116        }) else {
117            return root_element_style;
118        };
119
120        // We only propagate from the <body> if it generates a box. The spec only checks for
121        // `display: none`, but Blink and WebKit don't propagate for `display: contents` either.
122        // Gecko propagates from the <body> regardless of its `display`.
123        // See https://github.com/w3c/csswg-drafts/issues/12643
124        let body_style = body.style(context);
125        let body_display = body_style.get_display();
126        if *body_display == StyleDisplay::Contents || *body_display == StyleDisplay::None {
127            return root_element.style(context);
128        }
129        body_style.clone()
130    }
131
132    pub(crate) fn style_with_writing_mode_source_style(
133        base_style: ServoArc<ComputedValues>,
134        writing_mode_source_style: &ServoArc<ComputedValues>,
135    ) -> ServoArc<ComputedValues> {
136        if base_style.writing_mode == writing_mode_source_style.writing_mode &&
137            base_style.get_direction() == writing_mode_source_style.get_direction() &&
138            base_style.get_text_orientation() == writing_mode_source_style.get_text_orientation()
139        {
140            return base_style;
141        }
142
143        let mut new_style = (*base_style).clone();
144        let inherited_box = new_style.mutate_inherited_box();
145        inherited_box.writing_mode = writing_mode_source_style.get_inherited_box().writing_mode;
146        inherited_box.direction = writing_mode_source_style.get_inherited_box().direction;
147        inherited_box.text_orientation = writing_mode_source_style
148            .get_inherited_box()
149            .text_orientation;
150        new_style.writing_mode = writing_mode_source_style.writing_mode;
151        ServoArc::new(new_style)
152    }
153
154    pub(crate) fn writing_mode(&self) -> WritingMode {
155        self.initial_containing_block_style.writing_mode
156    }
157
158    fn viewport_overflow(
159        root_element: ServoLayoutNode<'_>,
160        root_box: Option<&ArcRefCell<BlockLevelBox>>,
161    ) -> AxesOverflow {
162        // From <https://www.w3.org/TR/css-overflow-3/#overflow-propagation>:
163        // > UAs must apply the overflow-* values set on the root element to the viewport when the
164        // > root element’s display value is not none. However, when the root element is an [HTML]
165        // > html element (including XML syntax for HTML) whose overflow value is visible (in both
166        // > axes), and that element has as a child a body element whose display value is also not
167        // > none, user agents must instead apply the overflow-* values of the first such child
168        // > element to the viewport. The element from which the value is propagated must then have a
169        // > used overflow value of visible.
170
171        // If there is no root box, the root element has `display: none`, so don't propagate.
172        // The spec isn't very clear about what value to use, but the initial value seems fine.
173        // See https://github.com/w3c/csswg-drafts/issues/12649
174        let Some(root_box) = root_box else {
175            return AxesOverflow::default();
176        };
177
178        let propagate_from_body = || {
179            // Unlike what the spec implies, we stop iterating when we find the first <body>,
180            // even if it's not suitable because it lacks a box. This matches other browsers.
181            // See https://github.com/w3c/csswg-drafts/issues/12644
182            let body = root_element.flat_tree_children().find(|child| {
183                child
184                    .as_element()
185                    .is_some_and(|element| element.is_body_element_of_html_element_root())
186            })?;
187
188            // We only propagate from the <body> if it generates a box. The spec only checks for
189            // `display: none`, but other browsers don't propagate for `display: contents` either.
190            // See https://github.com/w3c/csswg-drafts/issues/12643
191            let body_layout_data = body.inner_layout_data()?;
192            let mut body_box = body_layout_data.self_box.borrow_mut();
193            body_box.as_mut()?.with_base_mut(|base| {
194                base.base_fragment_info
195                    .flags
196                    .insert(FragmentFlags::PROPAGATED_OVERFLOW_TO_VIEWPORT);
197                AxesOverflow::from(&*base.style)
198            })
199        };
200
201        root_box.borrow_mut().with_base_mut(|base| {
202            let root_overflow = AxesOverflow::from(&*base.style);
203            if root_overflow.x == Overflow::Visible &&
204                root_overflow.y == Overflow::Visible &&
205                let Some(body_overflow) = propagate_from_body()
206            {
207                return body_overflow;
208            }
209            base.base_fragment_info
210                .flags
211                .insert(FragmentFlags::PROPAGATED_OVERFLOW_TO_VIEWPORT);
212            root_overflow
213        })
214    }
215}
216
217fn construct_for_root_element(
218    context: &LayoutContext,
219    root_element: ServoLayoutNode<'_>,
220    style_for_writing_mode: &ServoArc<ComputedValues>,
221) -> Vec<ArcRefCell<BlockLevelBox>> {
222    let root_style = BoxTree::style_with_writing_mode_source_style(
223        root_element.style(&context.style_context),
224        style_for_writing_mode,
225    );
226    let info = NodeAndStyleInfo::new(root_element, root_style);
227    let box_style = info.style.get_box();
228
229    let display_inside = match Display::from(box_style.display) {
230        Display::None => return Vec::new(),
231        Display::Contents => {
232            // Unreachable because the style crate adjusts the computed values:
233            // https://drafts.csswg.org/css-display-3/#transformations
234            // “'display' of 'contents' computes to 'block' on the root element”
235            unreachable!()
236        },
237        // The root element is blockified, ignore DisplayOutside
238        Display::GeneratingBox(display_generating_box) => display_generating_box.display_inside(),
239    };
240
241    let contents = Contents::for_element(root_element, context);
242
243    let propagated_data = PropagatedBoxTreeData::default();
244    let root_box = if box_style.position.is_absolutely_positioned() {
245        BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(ArcRefCell::new(
246            AbsolutelyPositionedBox::construct(context, &info, display_inside, contents),
247        ))
248    } else if box_style.float.is_floating() {
249        BlockLevelBox::OutOfFlowFloatBox(FloatBox::construct(
250            context,
251            &info,
252            display_inside,
253            contents,
254            propagated_data,
255        ))
256    } else {
257        BlockLevelBox::Independent(IndependentFormattingContext::construct(
258            context,
259            &info,
260            display_inside,
261            contents,
262            propagated_data,
263        ))
264    };
265
266    let root_box = ArcRefCell::new(root_box);
267    root_element
268        .box_slot()
269        .set(LayoutBox::BlockLevel(root_box.clone()));
270    vec![root_box]
271}
272
273impl BoxTree {
274    #[servo_tracing::instrument(name = "Fragment Tree Construction", skip_all)]
275    pub(crate) fn layout(
276        &self,
277        layout_context: &LayoutContext,
278        viewport: UntypedSize2D<Au>,
279    ) -> FragmentTree {
280        let physical_containing_block: Rect<Au, CSSPixel> =
281            PhysicalSize::from_untyped(viewport).into();
282
283        let initial_containing_block_size = LogicalVec2::from_physical_size(
284            &physical_containing_block.size,
285            self.initial_containing_block_style.writing_mode,
286        );
287        let initial_containing_block = DefiniteContainingBlock {
288            size: initial_containing_block_size,
289            style: &self.initial_containing_block_style,
290        };
291
292        let mut positioning_context = PositioningContext::default();
293        let independent_layout = self.root.layout(
294            layout_context,
295            &mut positioning_context,
296            &(&initial_containing_block).into(),
297            &initial_containing_block.size.block.into(),
298            None,
299        );
300
301        let root_fragments = independent_layout.fragments;
302        let mut root_fragments = root_fragments.into_physical_fragments(
303            self.initial_containing_block_style.writing_mode,
304            initial_containing_block_size,
305        );
306
307        // Zero box for `:root { display: none }`, one for the root element otherwise.
308        assert!(root_fragments.len() <= 1);
309
310        // There may be more fragments at the top-level
311        // (for positioned boxes whose containing is the initial containing block)
312        // but only if there was one fragment for the root element.
313        positioning_context.layout_initial_containing_block_children(
314            layout_context,
315            &initial_containing_block,
316            &mut root_fragments,
317        );
318
319        let viewport_scroll_sensitivity = AxesScrollSensitivity {
320            x: self.viewport_overflow.x.into(),
321            y: self.viewport_overflow.y.into(),
322        };
323
324        FragmentTree::new(
325            root_fragments,
326            physical_containing_block,
327            viewport_scroll_sensitivity,
328        )
329    }
330}