Skip to main content

layout/
positioned.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::mem;
6use std::ops::Range;
7use std::sync::Arc;
8
9use app_units::Au;
10use malloc_size_of_derive::MallocSizeOf;
11use rayon::iter::IntoParallelRefMutIterator;
12use rayon::prelude::{IndexedParallelIterator, ParallelIterator};
13use servo_arc::Arc as ServoArc;
14use style::Zero;
15use style::computed_values::position::T as Position;
16use style::logical_geometry::{LogicalAxis, PhysicalSide, WritingMode};
17use style::properties::ComputedValues;
18use style::values::specified::align::AlignFlags;
19
20use crate::PropagatedBoxTreeData;
21use crate::cell::{ArcRefCell, RefOrAtomicRef};
22use crate::containing_block::{
23    ConstraintSpace, ContainingBlock, ContainingBlockSize, DefiniteContainingBlock,
24};
25use crate::context::LayoutContext;
26use crate::dom_traversal::{Contents, NodeAndStyleInfo};
27use crate::formatting_contexts::IndependentFormattingContext;
28use crate::fragment_tree::{
29    BoxFragment, Fragment, FragmentFlags, HoistedSharedFragment, LayoutRootFragment,
30};
31use crate::geom::{
32    AuOrAuto, LogicalRect, LogicalSides, LogicalSides1D, LogicalVec2, PhysicalPoint, PhysicalRect,
33    PhysicalSize, PhysicalVec,
34};
35use crate::layout_box_base::{IndependentFormattingContextLayoutResult, LayoutBoxBase};
36use crate::sizing::{LazySize, Size, SizeConstraint, Sizes};
37use crate::style_ext::{Clamp, ComputedValuesExt, ContentBoxSizesAndPBM, DisplayInside};
38
39#[derive(Debug, MallocSizeOf)]
40pub(crate) struct AbsolutelyPositionedBox {
41    pub context: IndependentFormattingContext,
42}
43
44#[derive(Clone, Copy, MallocSizeOf)]
45pub(crate) struct StaticPositionRect {
46    rect: LogicalRect<Au>,
47    writing_mode: WritingMode,
48}
49
50impl Default for StaticPositionRect {
51    fn default() -> Self {
52        Self {
53            rect: Default::default(),
54            writing_mode: WritingMode::empty(),
55        }
56    }
57}
58
59impl StaticPositionRect {
60    pub(crate) fn new(rect: LogicalRect<Au>, writing_mode: WritingMode) -> Self {
61        Self { rect, writing_mode }
62    }
63
64    /// Return a version of this [`StaticPositionRect`] in the coordinate space of a parent
65    /// box.
66    ///  - `parent_writing_mode`: The [`WritingMode`] of the new parent box.
67    ///  - `child_container_size`: The child container size used for the translation in the
68    ///    writing mode of the new parent box.
69    pub(crate) fn in_writing_mode(
70        &self,
71        child_container_size: LogicalVec2<Au>,
72        parent_writing_mode: WritingMode,
73    ) -> Self {
74        if parent_writing_mode == self.writing_mode {
75            return *self;
76        }
77
78        let size_in_old_writing_mode = LogicalVec2::from_physical_size(
79            &child_container_size.to_physical_size(parent_writing_mode),
80            self.writing_mode,
81        );
82        let physical_rect = self
83            .rect
84            .as_physical(self.writing_mode, size_in_old_writing_mode);
85
86        Self {
87            writing_mode: parent_writing_mode,
88            rect: LogicalRect::from_physical(
89                physical_rect,
90                parent_writing_mode,
91                child_container_size,
92            ),
93        }
94    }
95
96    /// Create a new version of this [`StaticPositionRect`] in the coordinate space of
97    /// the parent box.
98    ///  - `child_rect`: The rectangle of the child in the coordinate space of the parent.
99    ///  - `parent_writing_mode`: The writing mode of the parent.
100    pub(crate) fn relative_to_parent(
101        &self,
102        child_rect: &LogicalRect<Au>,
103        parent_writing_mode: WritingMode,
104    ) -> Self {
105        let mut relative = self.in_writing_mode(child_rect.size, parent_writing_mode);
106        relative.rect.start_corner += child_rect.start_corner;
107        relative
108    }
109}
110
111#[derive(Clone, MallocSizeOf)]
112pub(crate) struct HoistedAbsolutelyPositionedBox {
113    absolutely_positioned_box: ArcRefCell<AbsolutelyPositionedBox>,
114    /// A reference to a Fragment which is shared between this `HoistedAbsolutelyPositionedBox`
115    /// and its placeholder `AbsoluteOrFixedPositionedFragment` in the original tree position.
116    /// This will be used later in order to paint this hoisted box in tree order.
117    pub fragment: ArcRefCell<HoistedSharedFragment>,
118    /// The adjusted "static-position rect" of this absolutely positioned box. This is
119    /// defined by the layout mode from which the box originates. This is the
120    /// [`HoistedSharedFragment::original_static_position_rect`] adjusted by the offests
121    /// of ancestors between the tree position of the absolute and the
122    /// [`PostioningContext`] that holds this [`HoistedAbsolutelyPositionedBox`].
123    ///
124    /// If the value is `None`, the original static position rect has not been adjusted yet.
125    ///
126    /// See <https://drafts.csswg.org/css-position-3/#staticpos-rect>
127    pub adjusted_static_position_rect: Option<StaticPositionRect>,
128    /// The resolved alignment values used for aligning this absolutely positioned element
129    /// if the "static-position rect" ends up being the "inset-modified containing block".
130    /// These values are dependent on the layout mode (currently only interesting for
131    /// flexbox).
132    pub resolved_alignment: LogicalVec2<AlignFlags>,
133    /// This is the [`WritingMode`] of the original parent of the element that created this
134    /// hoisted absolutely-positioned fragment. This helps to interpret the offset for
135    /// static positioning. If the writing mode is right-to-left or bottom-to-top, the static
136    /// offset needs to be adjusted by the absolutely positioned element's inline size.
137    pub original_parent_writing_mode: WritingMode,
138}
139
140impl AbsolutelyPositionedBox {
141    pub fn new(context: IndependentFormattingContext) -> Self {
142        Self { context }
143    }
144
145    pub fn construct(
146        context: &LayoutContext,
147        node_info: &NodeAndStyleInfo,
148        display_inside: DisplayInside,
149        contents: Contents,
150    ) -> Self {
151        Self {
152            context: IndependentFormattingContext::construct(
153                context,
154                node_info,
155                display_inside,
156                contents,
157                // Text decorations are not propagated to any out-of-flow descendants. In addition,
158                // absolutes don't affect the size of ancestors so it is fine to allow descendent
159                // tables to resolve percentage columns.
160                PropagatedBoxTreeData::default(),
161            ),
162        }
163    }
164
165    pub(crate) fn to_hoisted(
166        absolutely_positioned_box: ArcRefCell<Self>,
167        static_position_rect: StaticPositionRect,
168        resolved_alignment: LogicalVec2<AlignFlags>,
169        original_parent_writing_mode: WritingMode,
170    ) -> HoistedAbsolutelyPositionedBox {
171        HoistedAbsolutelyPositionedBox {
172            fragment: ArcRefCell::new(HoistedSharedFragment::new(static_position_rect)),
173            adjusted_static_position_rect: None,
174            resolved_alignment,
175            original_parent_writing_mode,
176            absolutely_positioned_box,
177        }
178    }
179}
180
181#[derive(Clone, Default, MallocSizeOf)]
182pub(crate) struct PositioningContext {
183    absolutes: Vec<HoistedAbsolutelyPositionedBox>,
184}
185
186impl PositioningContext {
187    #[inline]
188    pub(crate) fn is_empty(&self) -> bool {
189        self.absolutes.is_empty()
190    }
191
192    #[inline]
193    pub(crate) fn new_for_layout_box_base(layout_box_base: &LayoutBoxBase) -> Option<Self> {
194        Self::new_for_style_and_fragment_flags(
195            &layout_box_base.style,
196            &layout_box_base.base_fragment_info.flags,
197        )
198    }
199
200    fn new_for_style_and_fragment_flags(
201        style: &ComputedValues,
202        flags: &FragmentFlags,
203    ) -> Option<Self> {
204        if style.establishes_containing_block_for_absolute_descendants(*flags) {
205            Some(Self::default())
206        } else {
207            None
208        }
209    }
210
211    /// Absolute and fixed position fragments are hoisted up to their containing blocks
212    /// from their tree position. When these fragments have static inset start positions,
213    /// that position (relative to the ancestor containing block) needs to be included
214    /// with the hoisted fragment so that it can be laid out properly at the containing
215    /// block.
216    ///
217    /// This function is used to update the static position of hoisted boxes added after
218    /// the given index at every level of the fragment tree as the hoisted fragments move
219    /// up to their containing blocks. Once an ancestor fragment is laid out, this
220    /// function can be used to aggregate its offset to any descendent boxes that are
221    /// being hoisted. In this case, the appropriate index to use is the result of
222    /// [`PositioningContext::len()`] cached before laying out the [`Fragment`].
223    ///
224    /// - `child_rect`: The logical rectangle of the child in the parent's content box.
225    /// - `parent_writing_mode`: The writing mode of the parent that we are adjusting into.
226    pub(crate) fn adjust_static_position_of_hoisted_fragments(
227        &mut self,
228        child_rect: &LogicalRect<Au>,
229        parent_writing_mode: WritingMode,
230        index: PositioningContextLength,
231    ) {
232        self.adjust_static_position_of_hoisted_fragments_in_range(
233            child_rect,
234            parent_writing_mode,
235            &(index..self.len()),
236        )
237    }
238
239    /// See documentation for [PositioningContext::adjust_static_position_of_hoisted_fragments].
240    pub(crate) fn adjust_static_position_of_hoisted_fragments_in_range(
241        &mut self,
242        child_rect: &LogicalRect<Au>,
243        parent_writing_mode: WritingMode,
244        range: &Range<PositioningContextLength>,
245    ) {
246        for hoisted_box in &mut self.absolutes[range.start.0..range.end.0] {
247            hoisted_box.adjust_static_position_rect(child_rect, parent_writing_mode);
248        }
249    }
250
251    /// Given `fragment_layout_fn`, a closure which lays out a fragment in a provided
252    /// `PositioningContext`, create a new positioning context if necessary for the fragment and
253    /// lay out the fragment and all its children. Returns the newly created `BoxFragment`.
254    pub(crate) fn layout_maybe_position_relative_fragment(
255        &mut self,
256        layout_context: &LayoutContext,
257        containing_block: &ContainingBlock,
258        base: &LayoutBoxBase,
259        fragment_layout_fn: impl FnOnce(&mut Self) -> BoxFragment,
260    ) -> BoxFragment {
261        // If a new `PositioningContext` isn't necessary, simply create the fragment using
262        // the given closure and the current `PositioningContext`.
263        let establishes_containing_block_for_absolutes = base
264            .style
265            .establishes_containing_block_for_absolute_descendants(base.base_fragment_info.flags);
266        if !establishes_containing_block_for_absolutes {
267            return fragment_layout_fn(self);
268        }
269
270        let mut new_context = PositioningContext::default();
271        let mut new_fragment = fragment_layout_fn(&mut new_context);
272
273        // Lay out all of the absolutely positioned children for this fragment, and, if it
274        // isn't a containing block for fixed elements, then pass those up to the parent.
275        new_context.layout_collected_children(layout_context, &mut new_fragment);
276        self.append(new_context);
277
278        if base.style.get_box().position == Position::Relative {
279            new_fragment.base.translate_rect(
280                relative_adjustement(&base.style, containing_block)
281                    .to_physical_offset(containing_block.style.writing_mode)
282                    .into(),
283            );
284        }
285
286        new_fragment
287    }
288
289    fn forget_unhoisted_boxes(&mut self, fragment: &BoxFragment) {
290        let style = fragment.style();
291        debug_assert!(
292            style.establishes_containing_block_for_absolute_descendants(fragment.base.flags)
293        );
294        if style.establishes_containing_block_for_all_descendants(fragment.base.flags) {
295            self.absolutes.clear();
296        } else {
297            self.absolutes
298                .retain(|hoisted_box| hoisted_box.position() == Position::Fixed);
299        }
300    }
301
302    fn take_boxes_for_fragment(
303        &mut self,
304        new_fragment: &BoxFragment,
305        boxes_to_layout_out: &mut Vec<HoistedAbsolutelyPositionedBox>,
306        boxes_to_continue_hoisting_out: &mut Vec<HoistedAbsolutelyPositionedBox>,
307    ) {
308        let style = new_fragment.style();
309        debug_assert!(
310            style.establishes_containing_block_for_absolute_descendants(new_fragment.base.flags)
311        );
312
313        if style.establishes_containing_block_for_all_descendants(new_fragment.base.flags) {
314            boxes_to_layout_out.append(&mut self.absolutes);
315            return;
316        }
317
318        // TODO: This could potentially use `extract_if` when that is stabilized.
319        let (mut boxes_to_layout, mut boxes_to_continue_hoisting) = self
320            .absolutes
321            .drain(..)
322            .partition(|hoisted_box| hoisted_box.position() != Position::Fixed);
323        boxes_to_layout_out.append(&mut boxes_to_layout);
324        boxes_to_continue_hoisting_out.append(&mut boxes_to_continue_hoisting);
325    }
326
327    // Lay out the hoisted boxes collected into this `PositioningContext` and add them
328    // to the given `BoxFragment`.
329    pub(crate) fn layout_collected_children(
330        &mut self,
331        layout_context: &LayoutContext,
332        new_fragment: &mut BoxFragment,
333    ) {
334        if self.absolutes.is_empty() {
335            return;
336        }
337
338        // Sometimes we create temporary PositioningContexts just to collect hoisted absolutes and
339        // then these are processed later. In that case and if this fragment doesn't establish a
340        // containing block for absolutes at all, we just do nothing. All hoisted fragments will
341        // later be passed up to a parent PositioningContext.
342        //
343        // Handling this case here, when the PositioningContext is completely ineffectual other than
344        // as a temporary container for hoisted boxes, means that callers can execute less conditional
345        // code.
346        let style = new_fragment.style().clone();
347        if !style.establishes_containing_block_for_absolute_descendants(new_fragment.base.flags) {
348            return;
349        }
350
351        let mut fixed_position_boxes_to_hoist = Vec::new();
352        let mut boxes_to_layout = Vec::new();
353        self.take_boxes_for_fragment(
354            new_fragment,
355            &mut boxes_to_layout,
356            &mut fixed_position_boxes_to_hoist,
357        );
358
359        // The children are moved out and then replaced later so that it can be borrowed mutably
360        // while a reference to the fragment is passed to `layout_many`.
361        let mut children = std::mem::take(&mut new_fragment.children);
362
363        // Laying out a `position: absolute` child (which only establishes a containing block for
364        // `position: absolute` descendants) can result in more `position: fixed` descendants
365        // collecting in `self.absolutes`. We need to loop here in order to keep either laying them
366        // out or putting them into `fixed_position_boxes_to_hoist`. We know there aren't any more
367        // when `self.absolutes` is empty.
368        while !boxes_to_layout.is_empty() {
369            HoistedAbsolutelyPositionedBox::layout_many(
370                layout_context,
371                std::mem::take(&mut boxes_to_layout),
372                &mut children,
373                &mut self.absolutes,
374                &AbsoluteContainingBlock::Fragment(new_fragment),
375            );
376
377            self.take_boxes_for_fragment(
378                new_fragment,
379                &mut boxes_to_layout,
380                &mut fixed_position_boxes_to_hoist,
381            );
382        }
383
384        // Replace the children as they were temporarily removed to satisfy the borrow checker.
385        new_fragment.children = children;
386
387        // We replace here instead of simply preserving these in `take_boxes_for_fragment`
388        // so that we don't have to continually re-iterate over them when laying out in the
389        // loop above.
390        self.absolutes = fixed_position_boxes_to_hoist;
391    }
392
393    pub(crate) fn push(&mut self, hoisted_box: HoistedAbsolutelyPositionedBox) {
394        debug_assert!(hoisted_box.position().is_absolutely_positioned());
395        self.absolutes.push(hoisted_box);
396    }
397
398    pub(crate) fn append(&mut self, mut other: Self) {
399        if other.absolutes.is_empty() {
400            return;
401        }
402        if self.absolutes.is_empty() {
403            self.absolutes = other.absolutes;
404        } else {
405            self.absolutes.append(&mut other.absolutes)
406        }
407    }
408
409    pub(crate) fn layout_initial_containing_block_children(
410        &mut self,
411        layout_context: &LayoutContext,
412        initial_containing_block: &DefiniteContainingBlock,
413        fragments: &mut Vec<Fragment>,
414    ) {
415        // Laying out a `position: absolute` child (which only establishes a containing block for
416        // `position: absolute` descendants) can result in more `position: fixed` descendants
417        // collecting in `self.absolutes`. We need to loop here in order to keep laying them out. We
418        // know there aren't any more when `self.absolutes` is empty.
419        while !self.absolutes.is_empty() {
420            HoistedAbsolutelyPositionedBox::layout_many(
421                layout_context,
422                mem::take(&mut self.absolutes),
423                fragments,
424                &mut self.absolutes,
425                &AbsoluteContainingBlock::InitialContainingBlock(
426                    initial_containing_block
427                        .size
428                        .to_physical_size(initial_containing_block.style.writing_mode),
429                    initial_containing_block.style,
430                ),
431            )
432        }
433    }
434
435    /// Get the length of this [PositioningContext].
436    pub(crate) fn len(&self) -> PositioningContextLength {
437        PositioningContextLength(self.absolutes.len())
438    }
439
440    /// Truncate this [PositioningContext] to the given [PositioningContextLength].  This
441    /// is useful for "unhoisting" boxes in this context and returning it to the state at
442    /// the time that [`PositioningContext::len()`] was called.
443    pub(crate) fn truncate(&mut self, length: &PositioningContextLength) {
444        self.absolutes.truncate(length.0)
445    }
446}
447
448/// A data structure which stores the size of a positioning context.
449#[derive(Clone, Copy, Debug, PartialEq)]
450pub(crate) struct PositioningContextLength(usize);
451
452impl Zero for PositioningContextLength {
453    fn zero() -> Self {
454        Self(0)
455    }
456
457    fn is_zero(&self) -> bool {
458        self.0.is_zero()
459    }
460}
461
462impl HoistedAbsolutelyPositionedBox {
463    fn position(&self) -> Position {
464        let position = self
465            .absolutely_positioned_box
466            .borrow()
467            .context
468            .style()
469            .get_box()
470            .position;
471        assert!(position.is_absolutely_positioned());
472        position
473    }
474
475    fn layout_many(
476        layout_context: &LayoutContext,
477        mut boxes: Vec<Self>,
478        fragments: &mut Vec<Fragment>,
479        for_nearest_containing_block_for_all_descendants: &mut Vec<HoistedAbsolutelyPositionedBox>,
480        absolute_containing_block: &AbsoluteContainingBlock,
481    ) {
482        let job_sizes = boxes.iter().map(|hoisted_box| {
483            hoisted_box
484                .absolutely_positioned_box
485                .borrow()
486                .context
487                .subtree_size()
488        });
489        if layout_context.should_parallelize_layout(job_sizes) {
490            let mut new_fragments = Vec::new();
491            let mut new_hoisted_boxes = Vec::new();
492
493            boxes
494                .par_iter_mut()
495                .map(|hoisted_box| {
496                    let mut new_hoisted_boxes: Vec<HoistedAbsolutelyPositionedBox> = Vec::new();
497                    let new_fragment = hoisted_box.layout(
498                        layout_context,
499                        &mut new_hoisted_boxes,
500                        absolute_containing_block,
501                    );
502                    (new_fragment, new_hoisted_boxes)
503                })
504                .unzip_into_vecs(&mut new_fragments, &mut new_hoisted_boxes);
505
506            fragments.extend(new_fragments);
507            for_nearest_containing_block_for_all_descendants
508                .extend(new_hoisted_boxes.into_iter().flatten());
509        } else {
510            fragments.extend(boxes.iter_mut().map(|hoisted_box| {
511                hoisted_box.layout(
512                    layout_context,
513                    for_nearest_containing_block_for_all_descendants,
514                    absolute_containing_block,
515                )
516            }))
517        }
518    }
519
520    fn layout(
521        &mut self,
522        layout_context: &LayoutContext,
523        hoisted_absolutes_from_children: &mut Vec<HoistedAbsolutelyPositionedBox>,
524        absolute_containing_block: &AbsoluteContainingBlock,
525    ) -> Fragment {
526        let absolutely_positioned_box = self.absolutely_positioned_box.borrow();
527        let independent_formatting_context = &absolutely_positioned_box.context;
528
529        let containing_block_rect =
530            absolute_containing_block.rect_for_item(independent_formatting_context.style());
531        let containing_block_style = absolute_containing_block.style();
532        let containing_block = DefiniteContainingBlock {
533            size: LogicalVec2::from_physical_size(
534                &containing_block_rect.size,
535                containing_block_style.writing_mode,
536            ),
537            style: &containing_block_style,
538        };
539
540        // Static position adjustment: content box -> containing block
541        //
542        // The static position rect is in coordinates relative to the content box of the box that
543        // establishes its containing block. Convert it into the writing mode of the containing
544        // block and then offset it by the containing block start. The containing block of grid
545        // containers is the box's grid area. For all other containers, the containing block is just
546        // the padding box of the box that established it.
547        let containing_block_writing_mode = containing_block_style.writing_mode;
548        let containing_block_size = LogicalVec2::from_physical_size(
549            &absolute_containing_block.content_box_size(),
550            containing_block_writing_mode,
551        );
552        let static_position_rect = self
553            .static_position_rect()
554            .in_writing_mode(containing_block_size, containing_block_writing_mode);
555        let logical_containing_block_rect = LogicalRect::from_physical(
556            containing_block_rect,
557            containing_block_writing_mode,
558            containing_block_size,
559        );
560        let mut fully_adjusted_static_position_rect = static_position_rect.rect;
561        fully_adjusted_static_position_rect.start_corner -=
562            logical_containing_block_rect.start_corner;
563
564        let containing_block_origin = containing_block_rect.origin.to_vector();
565        let (box_fragment, content_rect, mut positioning_context) = independent_formatting_context
566            .layout_as_absolute(
567                layout_context,
568                &fully_adjusted_static_position_rect,
569                &containing_block,
570                containing_block_origin,
571                self.resolved_alignment,
572                self.original_parent_writing_mode,
573            );
574
575        // An absolutely-positioned box can be a layout root if it does not hoist any
576        // fixed positioned boxes out of it. This condition ensures isolation from parent
577        // layout meaning that laying out the absolutely positioned box again, will not
578        // affect ancestor layout.
579        let is_layout_root = positioning_context.is_empty();
580
581        // Any hoisted boxes that remain in this positioning context are going to be hoisted
582        // up above this absolutely positioned box. These will necessarily be fixed position
583        // elements, because absolutely positioned elements form containing blocks for all
584        // other elements. If any of them have a static start position though, we need to
585        // adjust it to account for the start corner of this absolute.
586        let mut adjusted_content_rect = content_rect;
587        adjusted_content_rect.start_corner += logical_containing_block_rect.start_corner;
588        positioning_context.adjust_static_position_of_hoisted_fragments(
589            &adjusted_content_rect,
590            containing_block.style.writing_mode,
591            PositioningContextLength::zero(),
592        );
593        hoisted_absolutes_from_children.extend(positioning_context.absolutes);
594
595        let fragment = Fragment::Box(box_fragment);
596        self.fragment.borrow_mut().fragment = Some(fragment.clone());
597
598        let fragment = match is_layout_root {
599            false => fragment,
600            true => Fragment::LayoutRoot(LayoutRootFragment {
601                fragment: self.fragment.clone(),
602            }),
603        };
604
605        independent_formatting_context
606            .base
607            .set_fragment(fragment.clone());
608
609        *independent_formatting_context
610            .layout_root_layout_inputs
611            .borrow_mut() = is_layout_root.then(|| {
612            Box::new(LayoutRootLayoutInputs {
613                fully_adjusted_static_position_rect,
614                resolved_alignment: self.resolved_alignment,
615                containing_block_size: containing_block.size,
616                containing_block_style: containing_block.style.clone(),
617                containing_block_origin,
618                original_parent_writing_mode: self.original_parent_writing_mode,
619            })
620        });
621
622        fragment
623    }
624
625    fn static_position_rect(&self) -> StaticPositionRect {
626        self.adjusted_static_position_rect
627            .unwrap_or_else(|| self.fragment.borrow().original_static_position_rect)
628    }
629
630    fn adjust_static_position_rect(
631        &mut self,
632        child_rect: &LogicalRect<Au>,
633        parent_writing_mode: WritingMode,
634    ) {
635        self.adjusted_static_position_rect = Some(
636            self.static_position_rect()
637                .relative_to_parent(child_rect, parent_writing_mode),
638        );
639    }
640}
641
642impl IndependentFormattingContext {
643    pub(crate) fn layout_as_absolute(
644        &self,
645        layout_context: &LayoutContext,
646        static_position_rect: &LogicalRect<Au>,
647        containing_block: &DefiniteContainingBlock,
648        containing_block_origin: PhysicalVec<Au>,
649        resolved_alignment: LogicalVec2<AlignFlags>,
650        original_parent_writing_mode: WritingMode,
651    ) -> (Arc<BoxFragment>, LogicalRect<Au>, PositioningContext) {
652        let cbis = containing_block.size.inline;
653        let cbbs = containing_block.size.block;
654        let containing_block_writing_mode = containing_block.style.writing_mode;
655        let style = self.style().clone();
656        let layout_style = self.layout_style();
657        let ContentBoxSizesAndPBM {
658            content_box_sizes,
659            pbm,
660            ..
661        } = layout_style.content_box_sizes_and_padding_border_margin(&containing_block.into());
662        let is_table = layout_style.is_table();
663        let is_table_or_replaced = is_table || self.is_replaced();
664        let preferred_aspect_ratio = self.preferred_aspect_ratio(&pbm.padding_border_sums);
665
666        let box_offset = style.box_offsets(containing_block.style.writing_mode);
667
668        // When the "static-position rect" doesn't come into play, we do not do any alignment
669        // in the inline axis.
670        let inline_box_offsets = box_offset.inline_sides().percentages_relative_to(cbis);
671        let inline_alignment = match inline_box_offsets.either_specified() {
672            true => style.get_justify_self().0,
673            false => resolved_alignment.inline,
674        };
675
676        let inline_axis_solver = AbsoluteAxisSolver {
677            axis: LogicalAxis::Inline,
678            containing_size: cbis,
679            padding_border_sum: pbm.padding_border_sums.inline,
680            computed_margin_start: pbm.margin.inline_start,
681            computed_margin_end: pbm.margin.inline_end,
682            computed_sizes: content_box_sizes.inline,
683            avoid_negative_margin_start: true,
684            box_offsets: inline_box_offsets,
685            static_position_rect_axis: static_position_rect.get_axis(LogicalAxis::Inline),
686            alignment: inline_alignment,
687            flip_anchor: original_parent_writing_mode.is_bidi_ltr() !=
688                containing_block_writing_mode.is_bidi_ltr(),
689            is_table_or_replaced,
690        };
691
692        // When the "static-position rect" doesn't come into play, we re-resolve "align-self"
693        // against this containing block.
694        let block_box_offsets = box_offset.block_sides().percentages_relative_to(cbbs);
695        let block_alignment = match block_box_offsets.either_specified() {
696            true => style.get_align_self().0,
697            false => resolved_alignment.block,
698        };
699        let block_axis_solver = AbsoluteAxisSolver {
700            axis: LogicalAxis::Block,
701            containing_size: cbbs,
702            padding_border_sum: pbm.padding_border_sums.block,
703            computed_margin_start: pbm.margin.block_start,
704            computed_margin_end: pbm.margin.block_end,
705            computed_sizes: content_box_sizes.block,
706            avoid_negative_margin_start: false,
707            box_offsets: block_box_offsets,
708            static_position_rect_axis: static_position_rect.get_axis(LogicalAxis::Block),
709            alignment: block_alignment,
710            flip_anchor: false,
711            is_table_or_replaced,
712        };
713
714        // The block size can depend on layout results, so we only solve it tentatively,
715        // we may have to resolve it properly later on.
716        let block_automatic_size = block_axis_solver.automatic_size();
717        let block_stretch_size = Some(block_axis_solver.stretch_size());
718        let inline_stretch_size = Some(inline_axis_solver.stretch_size());
719        let tentative_block_content_size =
720            self.tentative_block_content_size(preferred_aspect_ratio, inline_stretch_size);
721        let tentative_block_size = if let Some(block_content_size) = tentative_block_content_size {
722            SizeConstraint::Definite(block_axis_solver.computed_sizes.resolve(
723                LogicalAxis::Block,
724                block_automatic_size,
725                Au::zero,
726                block_stretch_size,
727                || block_content_size,
728                is_table,
729            ))
730        } else {
731            block_axis_solver.computed_sizes.resolve_extrinsic(
732                block_automatic_size,
733                Au::zero(),
734                block_stretch_size,
735            )
736        };
737
738        // The inline axis can be fully resolved, computing intrinsic sizes using the
739        // extrinsic block size.
740        let get_inline_content_size = || {
741            let constraint_space =
742                ConstraintSpace::new(tentative_block_size, &style, preferred_aspect_ratio);
743            self.inline_content_sizes(layout_context, &constraint_space)
744                .sizes
745        };
746        let inline_size = inline_axis_solver.computed_sizes.resolve(
747            LogicalAxis::Inline,
748            inline_axis_solver.automatic_size(),
749            Au::zero,
750            inline_stretch_size,
751            get_inline_content_size,
752            is_table,
753        );
754
755        let containing_block_for_children = ContainingBlock {
756            size: ContainingBlockSize::new(inline_size, tentative_block_size),
757            style: &style,
758        };
759        // TODO: https://drafts.csswg.org/css-writing-modes/#orthogonal-flows
760
761        let mut positioning_context = PositioningContext::default();
762        let lazy_block_size = LazySize::new(
763            &block_axis_solver.computed_sizes,
764            LogicalAxis::Block,
765            block_automatic_size,
766            Au::zero,
767            block_stretch_size,
768            is_table,
769        );
770
771        let containing_block = &containing_block.into();
772        let (layout, is_cached) = self.layout_and_is_cached(
773            layout_context,
774            &mut positioning_context,
775            &containing_block_for_children,
776            containing_block,
777            preferred_aspect_ratio,
778            &lazy_block_size,
779        );
780        let IndependentFormattingContextLayoutResult {
781            content_inline_size_for_table,
782            content_block_size,
783            fragments,
784            specific_layout_info,
785            ..
786        } = layout;
787
788        let content_size = LogicalVec2 {
789            // Tables can become narrower than predicted due to collapsed columns.
790            inline: content_inline_size_for_table.unwrap_or(inline_size),
791
792            // Now we can properly solve the block size.
793            block: lazy_block_size.resolve(|| content_block_size),
794        };
795
796        let inline_margins = inline_axis_solver.solve_margins(content_size.inline);
797        let block_margins = block_axis_solver.solve_margins(content_size.block);
798        let margin = LogicalSides {
799            inline_start: inline_margins.start,
800            inline_end: inline_margins.end,
801            block_start: block_margins.start,
802            block_end: block_margins.end,
803        };
804
805        let pb = pbm.padding + pbm.border;
806        let margin_rect_size = content_size + pbm.padding_border_sums + margin.sum();
807        let inline_origin = inline_axis_solver.origin_for_margin_box(
808            margin_rect_size.inline,
809            style.writing_mode,
810            original_parent_writing_mode,
811            containing_block_writing_mode,
812        );
813        let block_origin = block_axis_solver.origin_for_margin_box(
814            margin_rect_size.block,
815            style.writing_mode,
816            original_parent_writing_mode,
817            containing_block_writing_mode,
818        );
819        let content_rect = LogicalRect {
820            start_corner: LogicalVec2 {
821                inline: inline_origin + margin.inline_start + pb.inline_start,
822                block: block_origin + margin.block_start + pb.block_start,
823            },
824            size: content_size,
825        };
826
827        let physical_adjusted_content_rect = content_rect
828            .as_physical_deprecated(containing_block)
829            .translate(containing_block_origin);
830
831        if is_cached &&
832            let Some(old_fragment) = self.base.fragments().first() &&
833            let Some(old_box_fragment) = old_fragment
834                .retrieve_box_fragment()
835                .map(|fragment| fragment.clone()) &&
836            physical_adjusted_content_rect == old_box_fragment.content_rect()
837        {
838            // Drain the nested absolutes for which we are a containing block.
839            // However, we are reusing the fragment, so no need to lay them out again.
840            positioning_context.forget_unhoisted_boxes(&old_box_fragment);
841            return (old_box_fragment, content_rect, positioning_context);
842        }
843
844        let mut new_box_fragment = BoxFragment::new(
845            self.base_fragment_info(),
846            style,
847            fragments,
848            physical_adjusted_content_rect,
849            pbm.padding.to_physical(containing_block_writing_mode),
850            pbm.border.to_physical(containing_block_writing_mode),
851            margin.to_physical(containing_block_writing_mode),
852            specific_layout_info,
853        );
854
855        // This is an absolutely positioned element, which means it also establishes a
856        // containing block for absolutes. We lay out any absolutely positioned children
857        // here and pass the rest to `hoisted_absolutes_from_children.`
858        positioning_context.layout_collected_children(layout_context, &mut new_box_fragment);
859        (new_box_fragment.into(), content_rect, positioning_context)
860    }
861}
862
863#[derive(Clone, Copy, Debug)]
864struct RectAxis {
865    origin: Au,
866    length: Au,
867}
868
869impl LogicalRect<Au> {
870    fn get_axis(&self, axis: LogicalAxis) -> RectAxis {
871        match axis {
872            LogicalAxis::Block => RectAxis {
873                origin: self.start_corner.block,
874                length: self.size.block,
875            },
876            LogicalAxis::Inline => RectAxis {
877                origin: self.start_corner.inline,
878                length: self.size.inline,
879            },
880        }
881    }
882}
883
884struct AbsoluteAxisSolver {
885    axis: LogicalAxis,
886    containing_size: Au,
887    padding_border_sum: Au,
888    computed_margin_start: AuOrAuto,
889    computed_margin_end: AuOrAuto,
890    computed_sizes: Sizes,
891    avoid_negative_margin_start: bool,
892    box_offsets: LogicalSides1D<AuOrAuto>,
893    static_position_rect_axis: RectAxis,
894    alignment: AlignFlags,
895    flip_anchor: bool,
896    is_table_or_replaced: bool,
897}
898
899impl AbsoluteAxisSolver {
900    /// Returns the amount that we need to subtract from the containing block size in order to
901    /// obtain the inset-modified containing block that we will use for sizing purposes.
902    /// (Note that for alignment purposes, we may re-resolve auto insets to a different value.)
903    /// <https://drafts.csswg.org/css-position/#resolving-insets>
904    fn inset_sum(&self) -> Au {
905        match (
906            self.box_offsets.start.non_auto(),
907            self.box_offsets.end.non_auto(),
908        ) {
909            (None, None) => {
910                if self.flip_anchor {
911                    self.containing_size -
912                        self.static_position_rect_axis.origin -
913                        self.static_position_rect_axis.length
914                } else {
915                    self.static_position_rect_axis.origin
916                }
917            },
918            (Some(start), None) => start,
919            (None, Some(end)) => end,
920            (Some(start), Some(end)) => start + end,
921        }
922    }
923
924    /// Returns the size of the inset-modified containing block.
925    /// <https://drafts.csswg.org/css-position-3/#inset-modified-containing-block>
926    #[inline]
927    fn available_space(&self) -> Au {
928        Au::zero().max(self.containing_size - self.inset_sum())
929    }
930
931    #[inline]
932    fn automatic_size(&self) -> Size<Au> {
933        match self.alignment.value() {
934            _ if self.box_offsets.either_auto() => Size::FitContent,
935            AlignFlags::NORMAL | AlignFlags::AUTO if !self.is_table_or_replaced => Size::Stretch,
936            AlignFlags::STRETCH => Size::Stretch,
937            _ => Size::FitContent,
938        }
939    }
940
941    #[inline]
942    fn stretch_size(&self) -> Au {
943        Au::zero().max(
944            self.available_space() -
945                self.padding_border_sum -
946                self.computed_margin_start.auto_is(Au::zero) -
947                self.computed_margin_end.auto_is(Au::zero),
948        )
949    }
950
951    fn solve_margins(&self, size: Au) -> LogicalSides1D<Au> {
952        if self.box_offsets.either_auto() {
953            LogicalSides1D::new(
954                self.computed_margin_start.auto_is(Au::zero),
955                self.computed_margin_end.auto_is(Au::zero),
956            )
957        } else {
958            let free_space = self.available_space() - self.padding_border_sum - size;
959            match (self.computed_margin_start, self.computed_margin_end) {
960                (AuOrAuto::Auto, AuOrAuto::Auto) => {
961                    if self.avoid_negative_margin_start && free_space < Au::zero() {
962                        LogicalSides1D::new(Au::zero(), free_space)
963                    } else {
964                        let margin_start = free_space / 2;
965                        LogicalSides1D::new(margin_start, free_space - margin_start)
966                    }
967                },
968                (AuOrAuto::Auto, AuOrAuto::LengthPercentage(end)) => {
969                    LogicalSides1D::new(free_space - end, end)
970                },
971                (AuOrAuto::LengthPercentage(start), AuOrAuto::Auto) => {
972                    LogicalSides1D::new(start, free_space - start)
973                },
974                (AuOrAuto::LengthPercentage(start), AuOrAuto::LengthPercentage(end)) => {
975                    LogicalSides1D::new(start, end)
976                },
977            }
978        }
979    }
980
981    fn origin_for_margin_box(
982        &self,
983        size: Au,
984        self_writing_mode: WritingMode,
985        original_parent_writing_mode: WritingMode,
986        containing_block_writing_mode: WritingMode,
987    ) -> Au {
988        let (alignment_container, alignment_container_writing_mode, flip_anchor, offsets) = match (
989            self.box_offsets.start.non_auto(),
990            self.box_offsets.end.non_auto(),
991        ) {
992            (None, None) => (
993                self.static_position_rect_axis,
994                original_parent_writing_mode,
995                self.flip_anchor,
996                None,
997            ),
998            (Some(start), Some(end)) => {
999                let alignment_container = RectAxis {
1000                    origin: start,
1001                    length: self.available_space(),
1002                };
1003                (
1004                    alignment_container,
1005                    containing_block_writing_mode,
1006                    false,
1007                    Some(LogicalSides1D { start, end }),
1008                )
1009            },
1010            // If a single offset is auto, for alignment purposes it resolves to the amount
1011            // that makes the inset-modified containing block be exactly as big as the abspos.
1012            // Therefore the free space is zero and the alignment value is irrelevant.
1013            (Some(start), None) => return start,
1014            (None, Some(end)) => {
1015                return self.containing_size - size - end;
1016            },
1017        };
1018
1019        // TODO: https://drafts.csswg.org/css-writing-modes/#orthogonal-flows
1020
1021        let self_value_matches_container = || {
1022            self.axis == LogicalAxis::Block ||
1023                self_writing_mode.is_bidi_ltr() == alignment_container_writing_mode.is_bidi_ltr()
1024        };
1025
1026        // Here we resolve the alignment to either start, center, or end.
1027        // Note we need to handle both self-alignment values (when some inset isn't auto)
1028        // and distributed alignment values (when both insets are auto).
1029        // The latter are treated as their fallback alignment.
1030        let alignment = match self.alignment.value() {
1031            // https://drafts.csswg.org/css-align/#valdef-self-position-center
1032            // https://drafts.csswg.org/css-align/#valdef-align-content-space-around
1033            // https://drafts.csswg.org/css-align/#valdef-align-content-space-evenly
1034            AlignFlags::CENTER | AlignFlags::SPACE_AROUND | AlignFlags::SPACE_EVENLY => {
1035                AlignFlags::CENTER
1036            },
1037            // https://drafts.csswg.org/css-align/#valdef-self-position-self-start
1038            AlignFlags::SELF_START if self_value_matches_container() => AlignFlags::START,
1039            AlignFlags::SELF_START => AlignFlags::END,
1040            // https://drafts.csswg.org/css-align/#valdef-self-position-self-end
1041            AlignFlags::SELF_END if self_value_matches_container() => AlignFlags::END,
1042            AlignFlags::SELF_END => AlignFlags::START,
1043            // - Horizontal writing mode (block axis vertical): the keywords are
1044            //   perpendicular to the axis, so they behave as `start`.
1045            // - Vertical writing mode (block axis horizontal): align to the
1046            //   physical edge. `left` is the block-start edge in `vertical-lr`
1047            //   and the block-end edge in `vertical-rl`; `right` is the reverse.
1048            // https://drafts.csswg.org/css-align/#valdef-justify-content-left
1049            AlignFlags::LEFT if self.axis == LogicalAxis::Block => {
1050                if alignment_container_writing_mode.is_horizontal() ||
1051                    alignment_container_writing_mode.block_start_physical_side() ==
1052                        PhysicalSide::Left
1053                {
1054                    AlignFlags::START
1055                } else {
1056                    AlignFlags::END
1057                }
1058            },
1059            // https://drafts.csswg.org/css-align/#valdef-justify-content-right
1060            AlignFlags::RIGHT if self.axis == LogicalAxis::Block => {
1061                if alignment_container_writing_mode.is_horizontal() ||
1062                    alignment_container_writing_mode.block_start_physical_side() ==
1063                        PhysicalSide::Right
1064                {
1065                    AlignFlags::START
1066                } else {
1067                    AlignFlags::END
1068                }
1069            },
1070            // On the inline axis these keywords are line-left / line-right.
1071            AlignFlags::LEFT if alignment_container_writing_mode.line_left_is_inline_start() => {
1072                AlignFlags::START
1073            },
1074            AlignFlags::LEFT => AlignFlags::END,
1075            AlignFlags::RIGHT if alignment_container_writing_mode.line_left_is_inline_start() => {
1076                AlignFlags::END
1077            },
1078            AlignFlags::RIGHT => AlignFlags::START,
1079            // https://drafts.csswg.org/css-align/#valdef-self-position-end
1080            // https://drafts.csswg.org/css-align/#valdef-self-position-flex-end
1081            // https://drafts.csswg.org/css-align/#valdef-justify-self-last-baseline
1082            AlignFlags::END | AlignFlags::FLEX_END | AlignFlags::LAST_BASELINE => AlignFlags::END,
1083            // https://drafts.csswg.org/css-align/#valdef-self-position-start
1084            // https://drafts.csswg.org/css-align/#valdef-self-position-flex-start
1085            // https://drafts.csswg.org/css-align/#valdef-justify-self-first-baseline
1086            _ => AlignFlags::START,
1087        };
1088
1089        let alignment = match alignment {
1090            AlignFlags::START if flip_anchor => AlignFlags::END,
1091            AlignFlags::END if flip_anchor => AlignFlags::START,
1092            alignment => alignment,
1093        };
1094
1095        let free_space = alignment_container.length - size;
1096        let flags = self.alignment.flags();
1097        let alignment = if flags == AlignFlags::SAFE && free_space < Au::zero() {
1098            AlignFlags::START
1099        } else {
1100            alignment
1101        };
1102
1103        let origin = match alignment {
1104            AlignFlags::START => alignment_container.origin,
1105            AlignFlags::CENTER => alignment_container.origin + free_space / 2,
1106            AlignFlags::END => alignment_container.origin + free_space,
1107            _ => unreachable!(),
1108        };
1109        if matches!(flags, AlignFlags::SAFE | AlignFlags::UNSAFE) ||
1110            matches!(
1111                self.alignment,
1112                AlignFlags::NORMAL | AlignFlags::AUTO | AlignFlags::STRETCH
1113            )
1114        {
1115            return origin;
1116        }
1117        let Some(offsets) = offsets else {
1118            return origin;
1119        };
1120
1121        // Handle default overflow alignment.
1122        // https://drafts.csswg.org/css-align/#auto-safety-position
1123        let min = Au::zero().min(offsets.start);
1124        let max = self.containing_size - Au::zero().min(offsets.end) - size;
1125        origin.clamp_between_extremums(min, Some(max))
1126    }
1127}
1128
1129/// <https://drafts.csswg.org/css2/visuren.html#relative-positioning>
1130pub(crate) fn relative_adjustement(
1131    style: &ComputedValues,
1132    containing_block: &ContainingBlock,
1133) -> LogicalVec2<Au> {
1134    // It's not completely clear what to do with indefinite percentages
1135    // (https://github.com/w3c/csswg-drafts/issues/9353), so we match
1136    // other browsers and treat them as 'auto' offsets.
1137    let cbis = containing_block.inline_size();
1138    let cbbs = containing_block.block_size();
1139    let box_offsets = style
1140        .box_offsets(containing_block.style.writing_mode)
1141        .map_inline_and_block_axes(
1142            |value| value.map(|value| value.to_used_value(cbis)),
1143            |value| match cbbs {
1144                Some(cbbs) => value.map(|value| value.to_used_value(cbbs)),
1145                None => match value.non_auto().and_then(|value| value.to_length()) {
1146                    Some(value) => AuOrAuto::LengthPercentage(value.into()),
1147                    None => AuOrAuto::Auto,
1148                },
1149            },
1150        );
1151    fn adjust(start: AuOrAuto, end: AuOrAuto) -> Au {
1152        match (start, end) {
1153            (AuOrAuto::Auto, AuOrAuto::Auto) => Au::zero(),
1154            (AuOrAuto::Auto, AuOrAuto::LengthPercentage(end)) => -end,
1155            (AuOrAuto::LengthPercentage(start), _) => start,
1156        }
1157    }
1158    LogicalVec2 {
1159        inline: adjust(box_offsets.inline_start, box_offsets.inline_end),
1160        block: adjust(box_offsets.block_start, box_offsets.block_end),
1161    }
1162}
1163
1164/// These are the recorded layout inputs that were used when laying out an
1165/// absolutely-positioned element. They can be re-used when the absolutely-positioned
1166/// element is a viable layout root (no escaping fixed position elements, currently). The
1167/// information here is enough to re-run layout for an absolute.
1168#[derive(MallocSizeOf)]
1169pub(crate) struct LayoutRootLayoutInputs {
1170    /// The fully adjusted static position rectangle used to lay out the absolute. This is
1171    /// adjusted by the containing blocks of all of the boxes that come between an
1172    /// absolute's tree position and its layout containing block.
1173    fully_adjusted_static_position_rect: LogicalRect<Au>,
1174    /// The resolved alignment to use when laying out the absolute. This comes from the
1175    /// original box.
1176    resolved_alignment: LogicalVec2<AlignFlags>,
1177    /// This is the containing block size of the absolute's containing block. This is
1178    /// stored here because it's easier to access than the parent box.
1179    containing_block_size: LogicalVec2<Au>,
1180    /// This is the containing block origin of the absolute's containing block (relative
1181    /// to the containing block element's content box). This is stored here because it's
1182    /// easier to access than the parent box.
1183    containing_block_origin: PhysicalVec<Au>,
1184    /// This is the style of the containing block. This is stored here because it's easier
1185    /// to access than the parent box.
1186    #[conditional_malloc_size_of]
1187    containing_block_style: ServoArc<ComputedValues>,
1188    /// This is the writing mode of the absolute's tree parent.
1189    original_parent_writing_mode: WritingMode,
1190}
1191
1192impl std::fmt::Debug for LayoutRootLayoutInputs {
1193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1194        f.debug_struct("LayoutRootLayoutInputs")
1195            .field("containing_block_size", &self.containing_block_size)
1196            .finish()
1197    }
1198}
1199
1200impl LayoutRootLayoutInputs {
1201    /// Re-run layout for the given inputs. This is used to run layout again at layout
1202    /// roots.
1203    pub(crate) fn layout(
1204        &self,
1205        layout_context: &LayoutContext,
1206        context: &IndependentFormattingContext,
1207        shared_fragment: &ArcRefCell<HoistedSharedFragment>,
1208    ) -> Result<(), ()> {
1209        let containing_block = DefiniteContainingBlock {
1210            size: self.containing_block_size,
1211            style: &self.containing_block_style,
1212        };
1213        let (box_fragment, _, positioning_context) = context.layout_as_absolute(
1214            layout_context,
1215            &self.fully_adjusted_static_position_rect,
1216            &containing_block,
1217            self.containing_block_origin,
1218            self.resolved_alignment,
1219            self.original_parent_writing_mode,
1220        );
1221
1222        if !positioning_context.is_empty() {
1223            return Err(());
1224        }
1225
1226        shared_fragment.borrow_mut().fragment = Some(Fragment::Box(box_fragment));
1227        Ok(())
1228    }
1229}
1230
1231enum AbsoluteContainingBlock<'a> {
1232    Fragment(&'a BoxFragment),
1233    InitialContainingBlock(PhysicalSize<Au>, &'a ServoArc<ComputedValues>),
1234}
1235
1236impl<'a> AbsoluteContainingBlock<'a> {
1237    fn rect_for_item(&self, item_style: &ComputedValues) -> PhysicalRect<Au> {
1238        match self {
1239            AbsoluteContainingBlock::Fragment(box_fragment) => {
1240                box_fragment.containing_block_rect_for_absolute(item_style)
1241            },
1242            AbsoluteContainingBlock::InitialContainingBlock(size, _) => {
1243                PhysicalRect::new(PhysicalPoint::zero(), *size)
1244            },
1245        }
1246    }
1247
1248    fn content_box_size(&self) -> PhysicalSize<Au> {
1249        match self {
1250            AbsoluteContainingBlock::Fragment(box_fragment) => box_fragment.content_rect().size,
1251            AbsoluteContainingBlock::InitialContainingBlock(size, ..) => *size,
1252        }
1253    }
1254
1255    fn style(&self) -> RefOrAtomicRef<'_, ServoArc<ComputedValues>> {
1256        match self {
1257            AbsoluteContainingBlock::Fragment(box_fragment) => {
1258                RefOrAtomicRef::AtomicRef(box_fragment.style())
1259            },
1260            AbsoluteContainingBlock::InitialContainingBlock(_, style) => {
1261                RefOrAtomicRef::Ref(*style)
1262            },
1263        }
1264    }
1265}