Skip to main content

layout/taffy/
layout.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 atomic_refcell::{AtomicRef, AtomicRefCell};
7use style::logical_geometry::LogicalAxis;
8use style::properties::ComputedValues;
9use style::values::computed::CSSPixelLength;
10use style::values::computed::length_percentage::CalcLengthPercentage;
11use style::values::specified::align::AlignFlags;
12use style::values::specified::box_::DisplayInside;
13use style::{Atom, Zero};
14use taffy::style_helpers::{TaffyMaxContent, TaffyMinContent};
15use taffy::{AvailableSpace, MaybeMath, RequestedAxis, RunMode};
16
17use super::{
18    SpecificTaffyGridInfo, TaffyContainer, TaffyItemBox, TaffyItemBoxInner, TaffyStyloStyle,
19};
20use crate::cell::ArcRefCell;
21use crate::containing_block::{
22    ConstraintSpace, ContainingBlock, ContainingBlockSize, IndefiniteContainingBlock,
23    IndefiniteContainingBlockSize,
24};
25use crate::context::LayoutContext;
26use crate::dom::WeakLayoutBox;
27use crate::formatting_contexts::{Baselines, IndependentFormattingContext};
28use crate::fragment_tree::{
29    BoxFragment, CollapsedBlockMargins, Fragment, FragmentChildren, FragmentFlags,
30    SpecificLayoutInfo,
31};
32use crate::geom::{
33    LogicalRect, LogicalVec2, PhysicalPoint, PhysicalRect, PhysicalSides, PhysicalSize, PhysicalVec,
34};
35use crate::layout_box_base::IndependentFormattingContextLayoutResult;
36use crate::positioned::{
37    AbsolutelyPositionedBox, PositioningContext, PositioningContextLength, StaticPositionRect,
38};
39use crate::sizing::{
40    ComputeInlineContentSizes, ContentSizes, InlineContentSizesResult, LazySize, Size,
41    SizeConstraint,
42};
43use crate::style_ext::{Clamp, ContentBoxSizesAndPBM, LayoutStyle};
44
45const DUMMY_NODE_ID: taffy::NodeId = taffy::NodeId::new(u64::MAX);
46
47fn resolve_content_size(constraint: AvailableSpace, content_sizes: ContentSizes) -> f32 {
48    match constraint {
49        AvailableSpace::Definite(limit) => {
50            let min = content_sizes.min_content.to_f32_px();
51            let max = content_sizes.max_content.to_f32_px();
52            limit.min(max).max(min)
53        },
54        AvailableSpace::MinContent => content_sizes.min_content.to_f32_px(),
55        AvailableSpace::MaxContent => content_sizes.max_content.to_f32_px(),
56    }
57}
58
59#[inline(always)]
60fn with_independent_formatting_context<T>(
61    item: &mut TaffyItemBoxInner,
62    cb: impl FnOnce(&IndependentFormattingContext) -> T,
63) -> T {
64    match item {
65        TaffyItemBoxInner::InFlowBox(context) => cb(context),
66        TaffyItemBoxInner::OutOfFlowAbsolutelyPositionedBox(abspos_box) => {
67            cb(&AtomicRefCell::borrow(abspos_box).context)
68        },
69    }
70}
71
72/// Layout parameters and intermediate results about a taffy container,
73/// grouped to avoid passing around many parameters
74struct TaffyContainerContext<'a> {
75    source_child_nodes: &'a [ArcRefCell<TaffyItemBox>],
76    layout_context: &'a LayoutContext<'a>,
77    positioning_context: &'a mut PositioningContext,
78    content_box_size_override: &'a ContainingBlock<'a>,
79    style: &'a ComputedValues,
80    fragment_flags: FragmentFlags,
81    specific_layout_info: Option<SpecificLayoutInfo>,
82
83    /// Temporary location for children specific info, which will be moved into child fragments
84    child_specific_layout_infos: Vec<Option<SpecificLayoutInfo>>,
85}
86
87struct ChildIter(std::ops::Range<usize>);
88impl Iterator for ChildIter {
89    type Item = taffy::NodeId;
90    fn next(&mut self) -> Option<Self::Item> {
91        self.0.next().map(taffy::NodeId::from)
92    }
93
94    fn size_hint(&self) -> (usize, Option<usize>) {
95        (self.0.len(), Some(self.0.len()))
96    }
97}
98
99impl taffy::TraversePartialTree for TaffyContainerContext<'_> {
100    type ChildIter<'a>
101        = ChildIter
102    where
103        Self: 'a;
104
105    fn child_ids(&self, _node_id: taffy::NodeId) -> Self::ChildIter<'_> {
106        ChildIter(0..self.source_child_nodes.len())
107    }
108
109    fn child_count(&self, _node_id: taffy::NodeId) -> usize {
110        self.source_child_nodes.len()
111    }
112
113    fn get_child_id(&self, _node_id: taffy::NodeId, index: usize) -> taffy::NodeId {
114        taffy::NodeId::from(index)
115    }
116}
117
118impl taffy::LayoutPartialTree for TaffyContainerContext<'_> {
119    type CustomIdent = Atom;
120
121    type CoreContainerStyle<'a>
122        = TaffyStyloStyle<&'a ComputedValues>
123    where
124        Self: 'a;
125
126    fn get_core_container_style(&self, _node_id: taffy::NodeId) -> Self::CoreContainerStyle<'_> {
127        TaffyStyloStyle::new(self.style, self.fragment_flags)
128    }
129
130    fn set_unrounded_layout(&mut self, node_id: taffy::NodeId, layout: &taffy::Layout) {
131        let id = usize::from(node_id);
132        (*self.source_child_nodes[id]).borrow_mut().taffy_layout = *layout;
133    }
134
135    #[expect(unsafe_code)]
136    fn resolve_calc_value(&self, val: *const (), basis: f32) -> f32 {
137        // SAFETY:
138        // - The calc `val` here is the same pointer we return to Taffy in `convert::length_percentage`
139        //   so it is safe to cast the type back to `*const CalcLengthPercentage`
140        // - Taffy guarantees that it never retains style values beyond the scope of it's style
141        //   computation methods, so we can be sure that the pointer we have passed it is still valid.
142        // - The reference we create here has a lifetime that does not escape this function, so it does
143        //   not matter if the pointer is later destroyed.
144        let calc = unsafe { &*(val as *const CalcLengthPercentage) };
145        calc.resolve(CSSPixelLength::new(basis)).px()
146    }
147
148    fn compute_child_layout(
149        &mut self,
150        node_id: taffy::NodeId,
151        inputs: taffy::LayoutInput,
152    ) -> taffy::LayoutOutput {
153        let mut child = (*self.source_child_nodes[usize::from(node_id)]).borrow_mut();
154        let child = &mut *child;
155
156        let output = with_independent_formatting_context(
157            &mut child.taffy_level_box,
158            |independent_context| -> taffy::LayoutOutput {
159                // TODO: re-evaluate sizing constraint conversions in light of recent layout changes
160                let containing_block = self.content_box_size_override;
161                let style = independent_context.style();
162
163                let child_containing_block = IndefiniteContainingBlock {
164                    size: IndefiniteContainingBlockSize::new(
165                        inputs.parent_size.width.map(Au::from_f32_px), /* inline_size */
166                        inputs.parent_size.height.map(Au::from_f32_px), /* block_size */
167                    ),
168                    style: containing_block.style,
169                };
170
171                // Adjust known_dimensions from border box to content box
172                let ContentBoxSizesAndPBM {
173                    content_box_sizes,
174                    pbm,
175                    ..
176                } = independent_context
177                    .layout_style()
178                    .content_box_sizes_and_padding_border_margin(&child_containing_block);
179                let pb_sum = pbm.padding_border_sums.map(|v| v.to_f32_px());
180                let content_box_known_dimensions = taffy::Size {
181                    width: inputs
182                        .known_dimensions
183                        .width
184                        .map(|width| width - pb_sum.inline),
185                    height: inputs
186                        .known_dimensions
187                        .height
188                        .map(|height| height - pb_sum.block),
189                };
190                let preferred_aspect_ratio =
191                    independent_context.preferred_aspect_ratio(&pbm.padding_border_sums);
192
193                // TODO: pass min- and max- size
194                let tentative_block_size = content_box_known_dimensions
195                    .height
196                    .map(Au::from_f32_px)
197                    .map_or_else(SizeConstraint::default, SizeConstraint::Definite);
198
199                // Compute inline size
200                let inline_size = content_box_known_dimensions.width.unwrap_or_else(|| {
201                    let constraint_space =
202                        ConstraintSpace::new(tentative_block_size, style, preferred_aspect_ratio);
203
204                    // TODO: pass min- and max- size
205                    let result = independent_context
206                        .inline_content_sizes(self.layout_context, &constraint_space);
207                    let adjusted_available_space = inputs
208                        .available_space
209                        .width
210                        .map_definite_value(|width| (width - pb_sum.inline).max(0.0));
211
212                    let stretch_size = adjusted_available_space.into_option().map(Au::from_f32_px);
213                    let (_, min_size, max_size) = content_box_sizes.inline.resolve_each(
214                        Size::FitContent,
215                        Au::zero,
216                        stretch_size,
217                        || result.sizes,
218                        independent_context.layout_style().is_table(),
219                    );
220                    Au::from_f32_px(resolve_content_size(adjusted_available_space, result.sizes))
221                        .clamp_between_extremums(min_size, max_size)
222                        .to_f32_px()
223                });
224
225                // Return early if only inline content sizes are requested
226                if inputs.run_mode == RunMode::ComputeSize &&
227                    inputs.axis == RequestedAxis::Horizontal
228                {
229                    return taffy::LayoutOutput::from_outer_size(taffy::Size {
230                        width: inline_size + pb_sum.inline,
231                        // If RequestedAxis is Horizontal then height will be ignored.
232                        height: 0.0,
233                    });
234                }
235
236                let lazy_block_size = match content_box_known_dimensions.height {
237                    None => LazySize::new(
238                        &content_box_sizes.block,
239                        LogicalAxis::Block,
240                        Size::FitContent,
241                        Au::zero,
242                        None,
243                        independent_context.layout_style().is_table(),
244                    ),
245                    Some(height) => Au::from_f32_px(height).into(),
246                };
247
248                if inputs.run_mode == RunMode::ComputeSize {
249                    if let Some(height) = inputs.known_dimensions.height {
250                        return taffy::LayoutOutput::from_outer_size(taffy::Size {
251                            width: inline_size + pb_sum.inline,
252                            height,
253                        });
254                    }
255
256                    // When the height is unknown we can use a cached block size under default
257                    // constraints.
258                    //
259                    // Note: This throws away baselines, but that's okay because Taffy internally
260                    // performs a full layout of the item when sizing items for baseline alignment.
261                    // This is slow, but correct.
262                    let content_block_size = independent_context
263                        .content_block_size_under_default_constraint(
264                            self.layout_context,
265                            &mut PositioningContext::default(),
266                            Au::from_f32_px(inline_size),
267                            containing_block,
268                            preferred_aspect_ratio,
269                            &lazy_block_size,
270                        );
271                    let block_size = lazy_block_size.resolve(|| content_block_size).to_f32_px();
272                    return taffy::LayoutOutput::from_outer_size(taffy::Size {
273                        width: inline_size + pb_sum.inline,
274                        height: block_size + pb_sum.block,
275                    });
276                }
277
278                let content_box_size_override = ContainingBlock {
279                    size: ContainingBlockSize::new(
280                        Au::from_f32_px(inline_size),
281                        tentative_block_size,
282                    ),
283                    style,
284                };
285
286                child.positioning_context = PositioningContext::default();
287                let layout = independent_context.layout(
288                    self.layout_context,
289                    &mut child.positioning_context,
290                    &content_box_size_override,
291                    containing_block,
292                    preferred_aspect_ratio,
293                    &lazy_block_size,
294                );
295
296                child.child_fragments = layout.fragments;
297                self.child_specific_layout_infos[usize::from(node_id)] =
298                    layout.specific_layout_info;
299
300                let block_size = lazy_block_size
301                    .resolve(|| layout.content_block_size)
302                    .to_f32_px();
303
304                let computed_size = taffy::Size {
305                    width: inline_size + pb_sum.inline,
306                    height: block_size + pb_sum.block,
307                };
308                let size = inputs.known_dimensions.unwrap_or(computed_size);
309
310                taffy::LayoutOutput {
311                    size,
312                    baselines: taffy::Baselines {
313                        first: layout.baselines.first.map(|baseline| {
314                            (baseline + pbm.padding.block_start + pbm.border.block_start)
315                                .to_f32_px()
316                        }),
317                        last: layout.baselines.last.map(|baseline| {
318                            (baseline + pbm.padding.block_start + pbm.border.block_start)
319                                .to_f32_px()
320                        }),
321                    },
322                    ..taffy::LayoutOutput::DEFAULT
323                }
324            },
325        );
326        child.taffy_baselines = output.baselines;
327        output
328    }
329}
330
331impl taffy::LayoutGridContainer for TaffyContainerContext<'_> {
332    type GridContainerStyle<'a>
333        = TaffyStyloStyle<&'a ComputedValues>
334    where
335        Self: 'a;
336
337    type GridItemStyle<'a>
338        = TaffyStyloStyle<AtomicRef<'a, ComputedValues>>
339    where
340        Self: 'a;
341
342    fn get_grid_container_style(
343        &self,
344        _node_id: taffy::prelude::NodeId,
345    ) -> Self::GridContainerStyle<'_> {
346        TaffyStyloStyle::new(self.style, self.fragment_flags)
347    }
348
349    fn get_grid_child_style(
350        &self,
351        child_node_id: taffy::prelude::NodeId,
352    ) -> Self::GridItemStyle<'_> {
353        let id = usize::from(child_node_id);
354        let child = (*self.source_child_nodes[id]).borrow();
355        let fragment_flags = child.with_base(|base| base.base_fragment_info.flags);
356        let stylo_style = AtomicRef::map(child, |c| &*c.style);
357        TaffyStyloStyle::new(stylo_style, fragment_flags)
358    }
359
360    fn set_detailed_grid_info(
361        &mut self,
362        _node_id: taffy::NodeId,
363        specific_layout_info: taffy::DetailedGridInfo<Atom>,
364    ) {
365        self.specific_layout_info = Some(SpecificLayoutInfo::Grid(Box::new(
366            SpecificTaffyGridInfo::from_detailed_grid_layout(specific_layout_info),
367        )));
368    }
369}
370
371impl ComputeInlineContentSizes for TaffyContainer {
372    fn compute_inline_content_sizes(
373        &self,
374        layout_context: &LayoutContext,
375        _constraint_space: &ConstraintSpace,
376    ) -> InlineContentSizesResult {
377        let style = &self.style;
378
379        let max_content_inputs = taffy::LayoutInput {
380            run_mode: taffy::RunMode::ComputeSize,
381            sizing_mode: taffy::SizingMode::InherentSize,
382            axis: taffy::RequestedAxis::Horizontal,
383            vertical_margins_are_collapsible: taffy::Line::FALSE,
384
385            known_dimensions_are_definite: taffy::Size {
386                width: true,
387                height: true,
388            },
389            known_dimensions: taffy::Size::NONE,
390            parent_size: taffy::Size::NONE,
391            available_space: taffy::Size::MAX_CONTENT,
392        };
393
394        let min_content_inputs = taffy::LayoutInput {
395            available_space: taffy::Size::MIN_CONTENT,
396            ..max_content_inputs
397        };
398
399        let containing_block = &ContainingBlock {
400            size: ContainingBlockSize::new(
401                Au::zero(),                /* inline_size */
402                SizeConstraint::default(), /* block_size */
403            ),
404            style,
405        };
406
407        let mut grid_context = TaffyContainerContext {
408            layout_context,
409            positioning_context: &mut PositioningContext::default(),
410            content_box_size_override: containing_block,
411            style,
412            fragment_flags: self.fragment_flags,
413            source_child_nodes: &self.children,
414            specific_layout_info: None,
415            child_specific_layout_infos: vec![None; self.children.len()],
416        };
417
418        let (max_content_output, min_content_output) = match style.get_display().inside() {
419            DisplayInside::Grid => {
420                let max_content_output = taffy::compute_grid_layout(
421                    &mut grid_context,
422                    DUMMY_NODE_ID,
423                    max_content_inputs,
424                );
425                let min_content_output = taffy::compute_grid_layout(
426                    &mut grid_context,
427                    DUMMY_NODE_ID,
428                    min_content_inputs,
429                );
430                (max_content_output, min_content_output)
431            },
432            _ => panic!("Servo is only configured to use Taffy for CSS Grid layout"),
433        };
434
435        let pb_sums = self
436            .layout_style()
437            .padding_border_margin(containing_block)
438            .padding_border_sums;
439
440        InlineContentSizesResult {
441            sizes: ContentSizes {
442                max_content: Au::from_f32_px(max_content_output.size.width) - pb_sums.inline,
443                min_content: Au::from_f32_px(min_content_output.size.width) - pb_sums.inline,
444            },
445
446            // TODO: determine this accurately
447            //
448            // "true" is a safe default as it will prevent Servo from performing optimizations based
449            // on the assumption that the node's size does not depend on block constraints.
450            depends_on_block_constraints: true,
451        }
452    }
453}
454
455impl TaffyContainer {
456    /// <https://drafts.csswg.org/css-grid/#layout-algorithm>
457    pub(crate) fn layout(
458        &self,
459        layout_context: &LayoutContext,
460        positioning_context: &mut PositioningContext,
461        content_box_size_override: &ContainingBlock,
462        containing_block: &ContainingBlock,
463    ) -> IndependentFormattingContextLayoutResult {
464        let mut container_ctx = TaffyContainerContext {
465            layout_context,
466            positioning_context,
467            content_box_size_override,
468            style: content_box_size_override.style,
469            fragment_flags: self.fragment_flags,
470            source_child_nodes: &self.children,
471            specific_layout_info: None,
472            child_specific_layout_infos: vec![None; self.children.len()],
473        };
474
475        let container_style = &content_box_size_override.style;
476        let align_items = container_style.get_align_items();
477        let justify_items = container_style.get_justify_items();
478        let pbm = self.layout_style().padding_border_margin(containing_block);
479
480        let known_dimensions = taffy::Size {
481            width: Some(
482                (content_box_size_override.inline_size() + pbm.padding_border_sums.inline)
483                    .to_f32_px(),
484            ),
485            height: content_box_size_override
486                .block_size()
487                .map(Au::to_f32_px)
488                .maybe_add(pbm.padding_border_sums.block.to_f32_px()),
489        };
490
491        let taffy_containing_block = taffy::Size {
492            width: Some(containing_block.inline_size().to_f32_px()),
493            height: containing_block.block_size().map(Au::to_f32_px),
494        };
495
496        let layout_input = taffy::LayoutInput {
497            run_mode: taffy::RunMode::PerformLayout,
498            sizing_mode: taffy::SizingMode::InherentSize,
499            axis: taffy::RequestedAxis::Vertical,
500            vertical_margins_are_collapsible: taffy::Line::FALSE,
501
502            known_dimensions_are_definite: taffy::Size {
503                width: true,
504                height: true,
505            },
506            known_dimensions,
507            parent_size: taffy_containing_block,
508            available_space: taffy::Size {
509                width: AvailableSpace::from(taffy_containing_block.width),
510                height: AvailableSpace::MaxContent,
511            },
512        };
513
514        let output = match container_ctx.style.get_display().inside() {
515            DisplayInside::Grid => {
516                taffy::compute_grid_layout(&mut container_ctx, DUMMY_NODE_ID, layout_input)
517            },
518            _ => panic!("Servo is only configured to use Taffy for CSS Grid layout"),
519        };
520
521        let writing_mode = containing_block.style.writing_mode;
522        let physical_padding = pbm.padding.to_physical(writing_mode);
523        let physical_border = pbm.border.to_physical(writing_mode);
524        let content_box_offset = PhysicalVec::new(
525            physical_padding.left + physical_border.left,
526            physical_padding.top + physical_border.top,
527        );
528        let mut out_of_flow_candidates = output.oof_candidates.iter();
529        let container_content_size = LogicalVec2 {
530            inline: content_box_size_override.inline_size(),
531            block: Au::from_f32_px(output.size.height) - pbm.padding_border_sums.block,
532        };
533
534        // Convert `taffy::Layout` into Servo `Fragment`s
535        // with container_ctx.child_specific_layout_infos will also moved to the corresponding `Fragment`s
536        let fragments: Vec<Fragment> = self
537            .children
538            .iter()
539            .map(|child| (**child).borrow_mut())
540            .enumerate()
541            .map(|(child_id, mut child)| {
542                fn rect_to_physical_sides<T>(rect: taffy::Rect<T>) -> PhysicalSides<T> {
543                    PhysicalSides::new(rect.top, rect.right, rect.bottom, rect.left)
544                }
545
546                fn size_and_pos_to_physical_rect<T: Default>(
547                    position: taffy::Point<T>,
548                    size: taffy::Size<T>,
549                ) -> PhysicalRect<T> {
550                    PhysicalRect::new(
551                        PhysicalPoint::new(position.x, position.y),
552                        PhysicalSize::new(size.width, size.height),
553                    )
554                }
555
556                let layout = &child.taffy_layout;
557
558                let padding = rect_to_physical_sides(layout.padding.map(Au::from_f32_px));
559                let border = rect_to_physical_sides(layout.border.map(Au::from_f32_px));
560                let margin = rect_to_physical_sides(layout.margin.map(Au::from_f32_px));
561
562                // Compute content box size and position.
563                //
564                // For the x/y position we have to correct for the difference between the
565                // content box and the border box for both the parent and the child.
566                let content_rect = size_and_pos_to_physical_rect(
567                    taffy::Point {
568                        x: Au::from_f32_px(
569                            layout.location.x + layout.padding.left + layout.border.left,
570                        ) - content_box_offset.x,
571                        y: Au::from_f32_px(
572                            layout.location.y + layout.padding.top + layout.border.top,
573                        ) - content_box_offset.y,
574                    },
575                    taffy::Size {
576                        width: layout.size.width -
577                            layout.padding.left -
578                            layout.padding.right -
579                            layout.border.left -
580                            layout.border.right,
581                        height: layout.size.height -
582                            layout.padding.top -
583                            layout.padding.bottom -
584                            layout.border.top -
585                            layout.border.bottom,
586                    }
587                    .map(Au::from_f32_px),
588                );
589
590                let child_specific_layout_info: Option<SpecificLayoutInfo> =
591                    std::mem::take(&mut container_ctx.child_specific_layout_infos[child_id]);
592
593                let fragment = match &mut child.taffy_level_box {
594                    TaffyItemBoxInner::InFlowBox(independent_box) => {
595                        let mut fragment_info = independent_box.base_fragment_info();
596                        fragment_info
597                            .flags
598                            .insert(FragmentFlags::IS_FLEX_OR_GRID_ITEM);
599                        let mut box_fragment = BoxFragment::new(
600                            fragment_info,
601                            independent_box.style().clone(),
602                            std::mem::take(&mut child.child_fragments),
603                            content_rect,
604                            padding,
605                            border,
606                            margin,
607                            child_specific_layout_info,
608                        )
609                        .with_baselines(Baselines {
610                            first: child.taffy_baselines.first.map(|baseline| {
611                                Au::from_f32_px(baseline) - padding.top - border.top
612                            }),
613                            last: child.taffy_baselines.last.map(|baseline| {
614                                Au::from_f32_px(baseline) - padding.top - border.top
615                            }),
616                        });
617
618                        child.positioning_context.layout_collected_children(
619                            container_ctx.layout_context,
620                            &mut box_fragment,
621                        );
622
623                        let logical_content_rect = &LogicalRect::from_physical(
624                            content_rect,
625                            container_style.writing_mode,
626                            container_content_size,
627                        );
628                        child
629                            .positioning_context
630                            .adjust_static_position_of_hoisted_fragments(
631                                logical_content_rect,
632                                container_style.writing_mode,
633                                PositioningContextLength::zero(),
634                            );
635                        container_ctx
636                            .positioning_context
637                            .append(std::mem::take(&mut child.positioning_context));
638
639                        Fragment::Box(box_fragment.into())
640                    },
641                    TaffyItemBoxInner::OutOfFlowAbsolutelyPositionedBox(abs_pos_box) => {
642                        fn resolve_alignment(value: AlignFlags, auto: AlignFlags) -> AlignFlags {
643                            match value {
644                                AlignFlags::AUTO => auto,
645                                AlignFlags::NORMAL => AlignFlags::STRETCH,
646                                value => value,
647                            }
648                        }
649
650                        let candidate = out_of_flow_candidates.next();
651                        debug_assert_eq!(
652                            candidate.map(|candidate| usize::from(candidate.node)),
653                            Some(child_id)
654                        );
655                        let static_position_rect = candidate
656                            .map(|candidate| {
657                                let taffy::Point { x, y } = candidate.static_position;
658                                PhysicalRect::new(
659                                    PhysicalPoint::new(
660                                        Au::from_f32_px(x.area.start),
661                                        Au::from_f32_px(y.area.start),
662                                    ) - content_box_offset,
663                                    PhysicalSize::new(
664                                        Au::from_f32_px(x.area.end - x.area.start),
665                                        Au::from_f32_px(y.area.end - y.area.start),
666                                    ),
667                                )
668                            })
669                            .unwrap_or_default();
670
671                        let static_position_rect = LogicalRect::from_physical(
672                            static_position_rect,
673                            container_style.writing_mode,
674                            container_content_size,
675                        );
676
677                        let hoisted_box = AbsolutelyPositionedBox::to_hoisted(
678                            abs_pos_box.clone(),
679                            StaticPositionRect::new(
680                                static_position_rect,
681                                container_style.writing_mode,
682                            ),
683                            LogicalVec2 {
684                                inline: resolve_alignment(
685                                    child.style.get_justify_self().0,
686                                    justify_items.computed.0.0,
687                                ),
688                                block: resolve_alignment(
689                                    child.style.get_align_self().0,
690                                    align_items.0,
691                                ),
692                            },
693                            container_ctx.style.writing_mode,
694                        );
695                        let hoisted_fragment = hoisted_box.fragment.clone();
696                        container_ctx.positioning_context.push(hoisted_box);
697                        Fragment::AbsoluteOrFixedPositionedPlaceholder(hoisted_fragment)
698                    },
699                };
700
701                if let TaffyItemBoxInner::InFlowBox(independent_formatting_context) =
702                    &child.taffy_level_box
703                {
704                    independent_formatting_context
705                        .base
706                        .set_fragment(fragment.clone());
707                }
708                fragment
709            })
710            .collect();
711        debug_assert!(out_of_flow_candidates.next().is_none());
712
713        IndependentFormattingContextLayoutResult {
714            fragments: FragmentChildren::PhysicalDeprecated(fragments),
715            content_block_size: container_content_size.block,
716            content_inline_size_for_table: None,
717            baselines: Baselines {
718                first: output.baselines.first.map(|baseline| {
719                    Au::from_f32_px(baseline) - pbm.padding.block_start - pbm.border.block_start
720                }),
721                last: output.baselines.last.map(|baseline| {
722                    Au::from_f32_px(baseline) - pbm.padding.block_start - pbm.border.block_start
723                }),
724            },
725
726            // TODO: determine this accurately
727            //
728            // "true" is a safe default as it will prevent Servo from performing optimizations based
729            // on the assumption that the node's size does not depend on block constraints.
730            depends_on_block_constraints: true,
731            specific_layout_info: container_ctx.specific_layout_info,
732            collapsible_margins_in_children: CollapsedBlockMargins::zero(),
733        }
734    }
735
736    #[inline]
737    pub(crate) fn layout_style(&self) -> LayoutStyle<'_> {
738        LayoutStyle::Default(&self.style)
739    }
740
741    pub(crate) fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
742        for child in &self.children {
743            child.borrow_mut().with_base_mut(|base| {
744                base.parent_box.replace(layout_box.clone());
745            });
746        }
747    }
748
749    pub(crate) fn subtree_size(&self) -> usize {
750        self.children
751            .iter()
752            .map(|child| child.borrow().with_base(|base| base.subtree_size()))
753            .sum()
754    }
755}