Skip to main content

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::sync::OnceLock;
8
9use layout_api::LayoutNode;
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::{BoxTreeString, 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 = InlineFormattingContextBuilder::new(
60                    builder.info,
61                    builder.context,
62                    false, /* should_process_first_letter */
63                );
64                let mut last_style_from_display_contents: Option<SharedInlineStyles> = None;
65                for flex_text_run in runs.into_iter() {
66                    match (
67                        last_style_from_display_contents.as_ref(),
68                        flex_text_run.style_from_display_contents.as_ref(),
69                    ) {
70                        (None, None) => {},
71                        (Some(old_style), Some(new_style)) if old_style.ptr_eq(new_style) => {},
72                        _ => {
73                            // If we have nested `display: contents`, then this logic will leave the
74                            // outer one before entering the new one. This is fine, because the inline
75                            // formatting context builder only uses the last style on the stack.
76                            if last_style_from_display_contents.is_some() {
77                                inline_formatting_context_builder.leave_display_contents();
78                            }
79                            if let Some(ref new_style) = flex_text_run.style_from_display_contents {
80                                inline_formatting_context_builder
81                                    .enter_display_contents(new_style.clone());
82                            }
83                        },
84                    }
85                    last_style_from_display_contents = flex_text_run.style_from_display_contents;
86                    inline_formatting_context_builder.push_text(
87                        flex_text_run.text,
88                        &flex_text_run.info,
89                        flex_text_run.info.node.text_node_selection(),
90                    );
91                }
92
93                let inline_formatting_context = inline_formatting_context_builder
94                    .finish(
95                        builder.context,
96                        true,  /* has_first_formatted_line */
97                        false, /* is_single_line_text_box */
98                        builder.info.style.to_bidi_level(),
99                    )
100                    .expect("Did not expect document white space only text runs");
101
102                let block_formatting_context = BlockFormattingContext::from_block_container(
103                    BlockContainer::InlineFormattingContext(inline_formatting_context),
104                    /* is_table_cell = */ false,
105                    /* textarea_size = */ None,
106                );
107
108                let info = builder.anonymous_info();
109                let formatting_context = IndependentFormattingContext::new(
110                    LayoutBoxBase::new(info.into(), info.style.clone()),
111                    IndependentFormattingContextContents::Flow(block_formatting_context),
112                    // This is just a series of anonymous text runs, so we don't need to worry
113                    // about what kind of PropagatedBoxTreeData is used here.
114                    Default::default(),
115                );
116
117                Some(ModernItem {
118                    kind: ModernItemKind::InFlow(formatting_context),
119                    order: 0,
120                    box_slot,
121                })
122            },
123            ModernContainerJob::ElementOrPseudoElement {
124                info,
125                display,
126                contents,
127                box_slot,
128            } => {
129                let is_abspos = info.style.get_box().position.is_absolutely_positioned();
130                let order = if is_abspos {
131                    0
132                } else {
133                    info.style.slow_clone_order()
134                };
135
136                if let Some(layout_box) =
137                    box_slot
138                        .take_layout_box()
139                        .and_then(|layout_box| match &layout_box {
140                            LayoutBox::FlexLevel(_) | LayoutBox::TaffyItemBox(_) => {
141                                Some(layout_box)
142                            },
143                            _ => None,
144                        })
145                {
146                    return Some(ModernItem {
147                        kind: ModernItemKind::ReusedBox(layout_box),
148                        order,
149                        box_slot,
150                    });
151                }
152
153                // Text decorations are not propagated to any out-of-flow descendants. In addition,
154                // absolutes don't affect the size of ancestors so it is fine to allow descendent
155                // tables to resolve percentage columns.
156                let propagated_data = match is_abspos {
157                    false => builder.propagated_data,
158                    true => PropagatedBoxTreeData::default(),
159                };
160
161                let formatting_context = IndependentFormattingContext::construct(
162                    builder.context,
163                    &info,
164                    display.display_inside(),
165                    contents,
166                    propagated_data,
167                );
168
169                let kind = if is_abspos {
170                    ModernItemKind::OutOfFlow(formatting_context)
171                } else {
172                    ModernItemKind::InFlow(formatting_context)
173                };
174                Some(ModernItem {
175                    kind,
176                    order,
177                    box_slot,
178                })
179            },
180        }
181    }
182}
183
184struct ModernContainerTextRun<'dom> {
185    info: NodeAndStyleInfo<'dom>,
186    text: BoxTreeString<'dom>,
187    style_from_display_contents: Option<SharedInlineStyles>,
188}
189
190impl ModernContainerTextRun<'_> {
191    /// <https://drafts.csswg.org/css-flexbox/#flex-items>:
192    /// > However, if the entire text sequences contains only document white space characters (i.e.
193    /// > characters that can be affected by the white-space property) it is instead not rendered
194    /// > (just as if its text nodes were display:none).
195    fn is_only_document_white_space(&self) -> bool {
196        self.text
197            .bytes()
198            .all(|byte| InlineFormattingContextBuilder::is_document_white_space(byte.into()))
199    }
200}
201
202pub(crate) enum ModernItemKind {
203    InFlow(IndependentFormattingContext),
204    OutOfFlow(IndependentFormattingContext),
205    ReusedBox(LayoutBox),
206}
207
208pub(crate) struct ModernItem<'dom> {
209    pub kind: ModernItemKind,
210    pub order: i32,
211    pub box_slot: BoxSlot<'dom>,
212}
213
214impl<'dom> TraversalHandler<'dom> for ModernContainerBuilder<'_, 'dom> {
215    fn handle_text(&mut self, info: &NodeAndStyleInfo<'dom>, text: BoxTreeString<'dom>) {
216        self.contiguous_text_runs.push(ModernContainerTextRun {
217            info: info.clone(),
218            text,
219            style_from_display_contents: self.display_contents_shared_styles.last().cloned(),
220        })
221    }
222
223    fn enter_display_contents(&mut self, styles: SharedInlineStyles) {
224        self.display_contents_shared_styles.push(styles);
225    }
226
227    fn leave_display_contents(&mut self) {
228        self.display_contents_shared_styles.pop();
229    }
230
231    /// Or pseudo-element
232    fn handle_element(
233        &mut self,
234        info: &NodeAndStyleInfo<'dom>,
235        display: DisplayGeneratingBox,
236        contents: Contents,
237        box_slot: BoxSlot<'dom>,
238    ) {
239        self.wrap_any_text_in_anonymous_block_container();
240
241        self.jobs.push(ModernContainerJob::ElementOrPseudoElement {
242            info: info.clone(),
243            display,
244            contents,
245            box_slot,
246        })
247    }
248}
249
250impl<'a, 'dom> ModernContainerBuilder<'a, 'dom> {
251    pub fn new(
252        context: &'a LayoutContext<'a>,
253        info: &'a NodeAndStyleInfo<'dom>,
254        propagated_data: PropagatedBoxTreeData,
255    ) -> Self {
256        ModernContainerBuilder {
257            context,
258            info,
259            anonymous_info: Default::default(),
260            propagated_data: propagated_data.disallowing_percentage_table_columns(),
261            contiguous_text_runs: Vec::new(),
262            jobs: Vec::new(),
263            has_text_runs: false,
264            display_contents_shared_styles: Vec::new(),
265        }
266    }
267
268    fn anonymous_info(&self) -> &NodeAndStyleInfo<'dom> {
269        self.anonymous_info.get_or_init(|| {
270            self.info
271                .with_pseudo_element(self.context, PseudoElement::ServoAnonymousBox)
272                .expect("Should always be able to construct info for anonymous boxes.")
273        })
274    }
275
276    fn wrap_any_text_in_anonymous_block_container(&mut self) {
277        let runs = std::mem::take(&mut self.contiguous_text_runs);
278
279        // If there is no text run or they all only contain document white space
280        // characters, do nothing.
281        if runs
282            .iter()
283            .all(ModernContainerTextRun::is_only_document_white_space)
284        {
285            return;
286        }
287
288        let box_slot = self.anonymous_info().node.box_slot();
289        self.jobs.push(ModernContainerJob::TextRuns(runs, box_slot));
290        self.has_text_runs = true;
291    }
292
293    pub(crate) fn finish(mut self) -> Vec<ModernItem<'dom>> {
294        self.wrap_any_text_in_anonymous_block_container();
295
296        let jobs = std::mem::take(&mut self.jobs);
297        let mut children: Vec<_> = if self.context.should_parallelize(jobs.iter().len()) {
298            jobs.into_par_iter()
299                .filter_map(|job| job.finish(&self))
300                .collect()
301        } else {
302            jobs.into_iter()
303                .filter_map(|job| job.finish(&self))
304                .collect()
305        };
306
307        // https://drafts.csswg.org/css-flexbox/#order-modified-document-order
308        children.sort_by_key(|child| child.order);
309
310        children
311    }
312}