layout/
construct_modern.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
5//! Layout construction code that is shared between modern layout modes (Flexbox and CSS Grid)
6
7use std::borrow::Cow;
8use std::sync::OnceLock;
9
10use rayon::iter::{IntoParallelIterator, ParallelIterator};
11use style::selector_parser::PseudoElement;
12
13use crate::PropagatedBoxTreeData;
14use crate::context::LayoutContext;
15use crate::dom::{BoxSlot, LayoutBox, NodeExt};
16use crate::dom_traversal::{Contents, NodeAndStyleInfo, TraversalHandler};
17use crate::flow::inline::SharedInlineStyles;
18use crate::flow::inline::construct::InlineFormattingContextBuilder;
19use crate::flow::{BlockContainer, BlockFormattingContext};
20use crate::formatting_contexts::{
21    IndependentFormattingContext, IndependentFormattingContextContents,
22};
23use crate::layout_box_base::LayoutBoxBase;
24use crate::style_ext::{ComputedValuesExt, DisplayGeneratingBox};
25
26/// A builder used for both flex and grid containers.
27pub(crate) struct ModernContainerBuilder<'a, 'dom> {
28    context: &'a LayoutContext<'a>,
29    info: &'a NodeAndStyleInfo<'dom>,
30    /// A [`NodeAndStyleInfo`] to use for anonymous box children. Only initialized if
31    /// there is such a child.
32    anonymous_info: OnceLock<NodeAndStyleInfo<'dom>>,
33    propagated_data: PropagatedBoxTreeData,
34    contiguous_text_runs: Vec<ModernContainerTextRun<'dom>>,
35    /// To be run in parallel with rayon in `finish`
36    jobs: Vec<ModernContainerJob<'dom>>,
37    has_text_runs: bool,
38    /// A stack of `display: contents` styles currently in scope. This matters because
39    /// `display: contents` elements do not generate boxes but still provide styling
40    /// for their children, and text runs which get different styles due to that can be
41    /// wrapped into the same anonymous flex/grid item.
42    display_contents_shared_styles: Vec<SharedInlineStyles>,
43}
44
45enum ModernContainerJob<'dom> {
46    ElementOrPseudoElement {
47        info: NodeAndStyleInfo<'dom>,
48        display: DisplayGeneratingBox,
49        contents: Contents,
50        box_slot: BoxSlot<'dom>,
51    },
52    TextRuns(Vec<ModernContainerTextRun<'dom>>, BoxSlot<'dom>),
53}
54
55impl<'dom> ModernContainerJob<'dom> {
56    fn finish(self, builder: &ModernContainerBuilder) -> Option<ModernItem<'dom>> {
57        match self {
58            ModernContainerJob::TextRuns(runs, box_slot) => {
59                let mut inline_formatting_context_builder =
60                    InlineFormattingContextBuilder::new(builder.info);
61                let mut last_style_from_display_contents: Option<SharedInlineStyles> = None;
62                for flex_text_run in runs.into_iter() {
63                    match (
64                        last_style_from_display_contents.as_ref(),
65                        flex_text_run.style_from_display_contents.as_ref(),
66                    ) {
67                        (None, None) => {},
68                        (Some(old_style), Some(new_style)) if old_style.ptr_eq(new_style) => {},
69                        _ => {
70                            // If we have nested `display: contents`, then this logic will leave the
71                            // outer one before entering the new one. This is fine, because the inline
72                            // formatting context builder only uses the last style on the stack.
73                            if last_style_from_display_contents.is_some() {
74                                inline_formatting_context_builder.leave_display_contents();
75                            }
76                            if let Some(ref new_style) = flex_text_run.style_from_display_contents {
77                                inline_formatting_context_builder
78                                    .enter_display_contents(new_style.clone());
79                            }
80                        },
81                    }
82                    last_style_from_display_contents = flex_text_run.style_from_display_contents;
83                    inline_formatting_context_builder
84                        .push_text(flex_text_run.text, &flex_text_run.info);
85                }
86
87                let inline_formatting_context = inline_formatting_context_builder.finish(
88                    builder.context,
89                    true,  /* has_first_formatted_line */
90                    false, /* is_single_line_text_box */
91                    builder.info.style.to_bidi_level(),
92                )?;
93
94                let block_formatting_context = BlockFormattingContext::from_block_container(
95                    BlockContainer::InlineFormattingContext(inline_formatting_context),
96                );
97
98                let info = builder.anonymous_info();
99                let formatting_context = IndependentFormattingContext::new(
100                    LayoutBoxBase::new(info.into(), info.style.clone()),
101                    IndependentFormattingContextContents::Flow(block_formatting_context),
102                );
103
104                Some(ModernItem {
105                    kind: ModernItemKind::InFlow(formatting_context),
106                    order: 0,
107                    box_slot,
108                })
109            },
110            ModernContainerJob::ElementOrPseudoElement {
111                info,
112                display,
113                contents,
114                box_slot,
115            } => {
116                let is_abspos = info.style.get_box().position.is_absolutely_positioned();
117                let order = if is_abspos {
118                    0
119                } else {
120                    info.style.clone_order()
121                };
122
123                if let Some(layout_box) =
124                    box_slot
125                        .take_layout_box()
126                        .and_then(|layout_box| match &layout_box {
127                            LayoutBox::FlexLevel(_) | LayoutBox::TaffyItemBox(_) => {
128                                Some(layout_box)
129                            },
130                            _ => None,
131                        })
132                {
133                    return Some(ModernItem {
134                        kind: ModernItemKind::ReusedBox(layout_box),
135                        order,
136                        box_slot,
137                    });
138                }
139
140                // Text decorations are not propagated to any out-of-flow descendants. In addition,
141                // absolutes don't affect the size of ancestors so it is fine to allow descendent
142                // tables to resolve percentage columns.
143                let propagated_data = match is_abspos {
144                    false => builder.propagated_data,
145                    true => PropagatedBoxTreeData::default(),
146                };
147
148                let formatting_context = IndependentFormattingContext::construct(
149                    builder.context,
150                    &info,
151                    display.display_inside(),
152                    contents,
153                    propagated_data,
154                );
155
156                let kind = if is_abspos {
157                    ModernItemKind::OutOfFlow(formatting_context)
158                } else {
159                    ModernItemKind::InFlow(formatting_context)
160                };
161                Some(ModernItem {
162                    kind,
163                    order,
164                    box_slot,
165                })
166            },
167        }
168    }
169}
170
171struct ModernContainerTextRun<'dom> {
172    info: NodeAndStyleInfo<'dom>,
173    text: Cow<'dom, str>,
174    style_from_display_contents: Option<SharedInlineStyles>,
175}
176
177impl ModernContainerTextRun<'_> {
178    /// <https://drafts.csswg.org/css-text/#white-space>
179    fn is_only_document_white_space(&self) -> bool {
180        // FIXME: is this the right definition? See
181        // https://github.com/w3c/csswg-drafts/issues/5146
182        // https://github.com/w3c/csswg-drafts/issues/5147
183        self.text
184            .bytes()
185            .all(|byte| matches!(byte, b' ' | b'\n' | b'\t'))
186    }
187}
188
189pub(crate) enum ModernItemKind {
190    InFlow(IndependentFormattingContext),
191    OutOfFlow(IndependentFormattingContext),
192    ReusedBox(LayoutBox),
193}
194
195pub(crate) struct ModernItem<'dom> {
196    pub kind: ModernItemKind,
197    pub order: i32,
198    pub box_slot: BoxSlot<'dom>,
199}
200
201impl<'dom> TraversalHandler<'dom> for ModernContainerBuilder<'_, 'dom> {
202    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: Cow<'dom, str>) {
203        self.contiguous_text_runs.push(ModernContainerTextRun {
204            info: info.clone(),
205            text,
206            style_from_display_contents: self.display_contents_shared_styles.last().cloned(),
207        })
208    }
209
210    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
211        self.display_contents_shared_styles.push(styles);
212    }
213
214    fn leave_display_contents(&mut self) {
215        self.display_contents_shared_styles.pop();
216    }
217
218    /// Or pseudo-element
219    fn handle_element(
220        &mut self,
221        info: &NodeAndStyleInfo<'dom>,
222        display: DisplayGeneratingBox,
223        contents: Contents,
224        box_slot: BoxSlot<'dom>,
225    ) {
226        self.wrap_any_text_in_anonymous_block_container();
227
228        self.jobs.push(ModernContainerJob::ElementOrPseudoElement {
229            info: info.clone(),
230            display,
231            contents,
232            box_slot,
233        })
234    }
235}
236
237impl<'a, 'dom> ModernContainerBuilder<'a, 'dom> {
238    pub fn new(
239        context: &'a LayoutContext<'a>,
240        info: &'a NodeAndStyleInfo<'dom>,
241        propagated_data: PropagatedBoxTreeData,
242    ) -> Self {
243        ModernContainerBuilder {
244            context,
245            info,
246            anonymous_info: Default::default(),
247            propagated_data: propagated_data.disallowing_percentage_table_columns(),
248            contiguous_text_runs: Vec::new(),
249            jobs: Vec::new(),
250            has_text_runs: false,
251            display_contents_shared_styles: Vec::new(),
252        }
253    }
254
255    fn anonymous_info(&self) -> &NodeAndStyleInfo<'dom> {
256        self.anonymous_info.get_or_init(|| {
257            self.info
258                .with_pseudo_element(self.context, PseudoElement::ServoAnonymousBox)
259                .expect("Should always be able to construct info for anonymous boxes.")
260        })
261    }
262
263    fn wrap_any_text_in_anonymous_block_container(&mut self) {
264        let runs = std::mem::take(&mut self.contiguous_text_runs);
265
266        // If there is no text run or they all only contain document white space
267        // characters, do nothing.
268        if runs
269            .iter()
270            .all(ModernContainerTextRun::is_only_document_white_space)
271        {
272            return;
273        }
274
275        let box_slot = self.anonymous_info().node.box_slot();
276        self.jobs.push(ModernContainerJob::TextRuns(runs, box_slot));
277        self.has_text_runs = true;
278    }
279
280    pub(crate) fn finish(mut self) -> Vec<ModernItem<'dom>> {
281        self.wrap_any_text_in_anonymous_block_container();
282
283        let jobs = std::mem::take(&mut self.jobs);
284        let mut children: Vec<_> = if self.context.use_rayon {
285            jobs.into_par_iter()
286                .filter_map(|job| job.finish(&self))
287                .collect()
288        } else {
289            jobs.into_iter()
290                .filter_map(|job| job.finish(&self))
291                .collect()
292        };
293
294        // https://drafts.csswg.org/css-flexbox/#order-modified-document-order
295        children.sort_by_key(|child| child.order);
296
297        children
298    }
299}