Skip to main content

layout/
sizing.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//! <https://drafts.csswg.org/css-sizing/>
6
7use std::cell::{Cell, LazyCell, OnceCell};
8use std::ops::{Add, AddAssign};
9use std::sync::atomic::Ordering;
10
11use app_units::{Au, MAX_AU};
12use malloc_size_of_derive::MallocSizeOf;
13use style::Zero;
14use style::logical_geometry::LogicalAxis;
15use style::values::computed::{
16    LengthPercentage, MaxSize as StyleMaxSize, Percentage, Size as StyleSize,
17};
18
19use crate::containing_block::{ConstraintSpace, IndefiniteContainingBlock};
20use crate::context::LayoutContext;
21use crate::geom::LogicalVec2;
22use crate::layout_box_base::LayoutBoxBase;
23use crate::style_ext::{AspectRatio, Clamp, ComputedValuesExt, ContentBoxSizesAndPBM, LayoutStyle};
24
25#[derive(PartialEq)]
26pub(crate) enum IntrinsicSizingMode {
27    /// Used to refer to a min-content contribution or max-content contribution.
28    /// This is the size that a box contributes to its containing block’s min-content
29    /// or max-content size. Note this is based on the outer size of the box,
30    /// and takes into account the relevant sizing properties of the element.
31    /// <https://drafts.csswg.org/css-sizing-3/#contributions>
32    Contribution,
33    /// Used to refer to a min-content size or max-content size.
34    /// This is the size based on the contents of an element, without regard for its context.
35    /// Note this is usually based on the inner (content-box) size of the box,
36    /// and ignores the relevant sizing properties of the element.
37    /// <https://drafts.csswg.org/css-sizing-3/#intrinsic>
38    Size,
39}
40
41#[derive(Clone, Copy, Debug, Default, MallocSizeOf)]
42pub(crate) struct ContentSizes {
43    pub min_content: Au,
44    pub max_content: Au,
45}
46
47/// <https://drafts.csswg.org/css-sizing/#intrinsic-sizes>
48impl ContentSizes {
49    pub fn max(&self, other: Self) -> Self {
50        Self {
51            min_content: self.min_content.max(other.min_content),
52            max_content: self.max_content.max(other.max_content),
53        }
54    }
55
56    pub fn max_assign(&mut self, other: Self) {
57        *self = self.max(other);
58    }
59
60    pub fn union(&self, other: &Self) -> Self {
61        Self {
62            min_content: self.min_content.max(other.min_content),
63            max_content: self.max_content + other.max_content,
64        }
65    }
66
67    pub fn union_assign(&mut self, other: &Self) {
68        self.min_content.max_assign(other.min_content);
69        self.max_content += other.max_content;
70    }
71
72    pub fn map(&self, f: impl Fn(Au) -> Au) -> Self {
73        Self {
74            min_content: f(self.min_content),
75            max_content: f(self.max_content),
76        }
77    }
78}
79
80impl Zero for ContentSizes {
81    fn zero() -> Self {
82        Au::zero().into()
83    }
84
85    fn is_zero(&self) -> bool {
86        self.min_content.is_zero() && self.max_content.is_zero()
87    }
88}
89
90impl Add for ContentSizes {
91    type Output = Self;
92
93    fn add(self, rhs: Self) -> Self {
94        Self {
95            min_content: self.min_content + rhs.min_content,
96            max_content: self.max_content + rhs.max_content,
97        }
98    }
99}
100
101impl AddAssign for ContentSizes {
102    fn add_assign(&mut self, rhs: Self) {
103        *self = self.add(rhs)
104    }
105}
106
107impl ContentSizes {
108    /// Clamps the provided amount to be between the min-content and the max-content.
109    /// This is called "shrink-to-fit" in CSS2, and "fit-content" in CSS Sizing.
110    /// <https://drafts.csswg.org/css2/visudet.html#shrink-to-fit-float>
111    /// <https://drafts.csswg.org/css-sizing/#funcdef-width-fit-content>
112    pub fn shrink_to_fit(&self, available_size: Au) -> Au {
113        // This formula is slightly different than what the spec says,
114        // to ensure that the minimum wins for a malformed ContentSize
115        // whose min_content is larger than its max_content.
116        available_size.min(self.max_content).max(self.min_content)
117    }
118}
119
120impl From<Au> for ContentSizes {
121    fn from(size: Au) -> Self {
122        Self {
123            min_content: size,
124            max_content: size,
125        }
126    }
127}
128
129#[expect(clippy::too_many_arguments)]
130pub(crate) fn outer_inline(
131    base: &LayoutBoxBase,
132    layout_style: &LayoutStyle,
133    containing_block: &IndefiniteContainingBlock,
134    auto_minimum: &LogicalVec2<Au>,
135    auto_block_size_stretches_to_containing_block: bool,
136    is_replaced: bool,
137    establishes_containing_block: bool,
138    skippable_for_block_percentage_quirk: bool,
139    get_preferred_aspect_ratio: impl FnOnce(&LogicalVec2<Au>) -> Option<AspectRatio>,
140    get_inline_content_size: impl FnOnce(&ConstraintSpace) -> InlineContentSizesResult,
141    get_tentative_block_content_size: impl FnOnce(Option<AspectRatio>) -> Option<ContentSizes>,
142) -> InlineContentSizesResult {
143    let ContentBoxSizesAndPBM {
144        content_box_sizes,
145        pbm,
146        mut depends_on_block_constraints,
147        preferred_size_computes_to_auto,
148    } = layout_style.content_box_sizes_and_padding_border_margin(containing_block);
149    let margin = pbm.margin.map(|v| v.auto_is(Au::zero));
150    let pbm_sums = LogicalVec2 {
151        block: pbm.padding_border_sums.block + margin.block_sum(),
152        inline: pbm.padding_border_sums.inline + margin.inline_sum(),
153    };
154    let style = layout_style.style();
155    let is_table = layout_style.is_table();
156    // TODO: Replace `depends_on_contents` with `content_size.get().is_some()` once `LazyCell::get()`
157    // becomes stable.
158    let depends_on_contents = Cell::new(false);
159    let content_size = LazyCell::new(|| {
160        depends_on_contents.set(true);
161        let constraint_space = if establishes_containing_block {
162            let block_stretch_size = containing_block.block_stretch_size(pbm_sums.block);
163            let automatic_size = if preferred_size_computes_to_auto.block &&
164                auto_block_size_stretches_to_containing_block
165            {
166                depends_on_block_constraints = true;
167                Size::Stretch
168            } else {
169                Size::FitContent
170            };
171            let aspect_ratio = get_preferred_aspect_ratio(&pbm.padding_border_sums);
172            let mut block_size =
173                if let Some(block_content_size) = get_tentative_block_content_size(aspect_ratio) {
174                    SizeConstraint::Definite(content_box_sizes.block.resolve(
175                        LogicalAxis::Block,
176                        automatic_size,
177                        || auto_minimum.block,
178                        block_stretch_size,
179                        || block_content_size,
180                        is_table,
181                    ))
182                } else {
183                    content_box_sizes.block.resolve_extrinsic(
184                        automatic_size,
185                        auto_minimum.block,
186                        block_stretch_size,
187                    )
188                };
189            let mut has_quirky_block_size = false;
190            if skippable_for_block_percentage_quirk {
191                has_quirky_block_size = !block_size.is_definite();
192                block_size
193                    .replace_if_indefinite_with(containing_block.maybe_quirky_block_size().into())
194            }
195            if has_quirky_block_size {
196                ConstraintSpace::new_quirky(block_size, style, aspect_ratio)
197            } else {
198                ConstraintSpace::new(block_size, style, aspect_ratio)
199            }
200        } else {
201            // Even if the size doesn't directly depend on block constraints, since this box
202            // doesn't establish a containing block, its contents can depend on its block
203            // constraints. And thus have a dependency via the intrinsic size.
204            depends_on_block_constraints = true;
205            let block_size = containing_block.maybe_quirky_block_size().into();
206            // This assumes that there is no preferred aspect ratio, or that there is no
207            // block size constraint to be transferred so the ratio is irrelevant.
208            // We only get into here for anonymous blocks, for which the assumption holds.
209            if containing_block.has_quirky_block_size() {
210                ConstraintSpace::new_quirky(block_size, containing_block.style, None)
211            } else {
212                ConstraintSpace::new(block_size, containing_block.style, None)
213            }
214        };
215        get_inline_content_size(&constraint_space)
216    });
217    let resolve_non_initial = |inline_size, stretch_values| {
218        Some(match inline_size {
219            Size::Initial => return None,
220            Size::Numeric(numeric) => (numeric, numeric, false),
221            Size::MinContent => (
222                content_size.sizes.min_content,
223                content_size.sizes.min_content,
224                content_size.depends_on_block_constraints,
225            ),
226            Size::MaxContent => (
227                content_size.sizes.max_content,
228                content_size.sizes.max_content,
229                content_size.depends_on_block_constraints,
230            ),
231            Size::FitContent => (
232                content_size.sizes.min_content,
233                content_size.sizes.max_content,
234                content_size.depends_on_block_constraints,
235            ),
236            Size::FitContentFunction(size) => {
237                let size = content_size.sizes.shrink_to_fit(size);
238                (size, size, content_size.depends_on_block_constraints)
239            },
240            Size::Stretch => return stretch_values,
241            Size::QuirkyStretch => unreachable!("Quirky stretch can't be an inline size"),
242        })
243    };
244    let (mut preferred_min_content, preferred_max_content, preferred_depends_on_block_constraints) =
245        resolve_non_initial(content_box_sizes.inline.preferred, None)
246            .unwrap_or_else(|| resolve_non_initial(Size::FitContent, None).unwrap());
247    let (mut min_min_content, mut min_max_content, mut min_depends_on_block_constraints) =
248        resolve_non_initial(
249            content_box_sizes.inline.min,
250            Some((Au::zero(), Au::zero(), false)),
251        )
252        .unwrap_or((auto_minimum.inline, auto_minimum.inline, false));
253    let (mut max_min_content, max_max_content, max_depends_on_block_constraints) =
254        resolve_non_initial(content_box_sizes.inline.max, None)
255            .map(|(min_content, max_content, depends_on_block_constraints)| {
256                (
257                    Some(min_content),
258                    Some(max_content),
259                    depends_on_block_constraints,
260                )
261            })
262            .unwrap_or_default();
263
264    // https://drafts.csswg.org/css-sizing-3/#replaced-percentage-min-contribution
265    // > If the box is replaced, a cyclic percentage in the value of any max size property
266    // > or preferred size property (width/max-width/height/max-height), is resolved against
267    // > zero when calculating the min-content contribution in the corresponding axis.
268    //
269    // This means that e.g. the min-content contribution of `width: calc(100% + 100px)`
270    // should be 100px, but it's just zero on other browsers, so we do the same.
271    if is_replaced {
272        let has_percentage = |size: Size<LengthPercentage>| {
273            // We need a comment here to avoid breaking `./mach test-tidy`.
274            matches!(size, Size::Numeric(numeric) if numeric.has_percentage())
275        };
276        let writing_mode = containing_block.style.writing_mode;
277        if content_box_sizes.inline.preferred.is_initial() &&
278            has_percentage(style.box_size(writing_mode).inline)
279        {
280            preferred_min_content = Au::zero();
281        }
282        if content_box_sizes.inline.max.is_initial() &&
283            has_percentage(style.max_box_size(writing_mode).inline)
284        {
285            max_min_content = Some(Au::zero());
286        }
287    }
288
289    // Regardless of their sizing properties, tables are always forced to be at least
290    // as big as their min-content size, so floor the minimums.
291    if is_table {
292        min_min_content.max_assign(content_size.sizes.min_content);
293        min_max_content.max_assign(content_size.sizes.min_content);
294        min_depends_on_block_constraints |= content_size.depends_on_block_constraints;
295    }
296
297    base.outer_inline_content_sizes_depend_on_content
298        .store(depends_on_contents.get(), Ordering::Relaxed);
299    InlineContentSizesResult {
300        sizes: ContentSizes {
301            min_content: preferred_min_content
302                .clamp_between_extremums(min_min_content, max_min_content) +
303                pbm_sums.inline,
304            max_content: preferred_max_content
305                .clamp_between_extremums(min_max_content, max_max_content) +
306                pbm_sums.inline,
307        },
308        depends_on_block_constraints: depends_on_block_constraints &&
309            (preferred_depends_on_block_constraints ||
310                min_depends_on_block_constraints ||
311                max_depends_on_block_constraints),
312    }
313}
314
315#[derive(Clone, Copy, Debug, MallocSizeOf)]
316pub(crate) struct InlineContentSizesResult {
317    pub sizes: ContentSizes,
318    pub depends_on_block_constraints: bool,
319}
320
321pub(crate) trait ComputeInlineContentSizes {
322    fn compute_inline_content_sizes(
323        &self,
324        layout_context: &LayoutContext,
325        constraint_space: &ConstraintSpace,
326    ) -> InlineContentSizesResult;
327
328    /// Returns the same result as [`Self::compute_inline_content_sizes()`], but adjusted
329    /// to floor the max-content size by the min-content size.
330    /// This is being discussed in <https://github.com/w3c/csswg-drafts/issues/12076>.
331    fn compute_inline_content_sizes_with_fixup(
332        &self,
333        layout_context: &LayoutContext,
334        constraint_space: &ConstraintSpace,
335    ) -> InlineContentSizesResult {
336        let mut result = self.compute_inline_content_sizes(layout_context, constraint_space);
337        let sizes = &mut result.sizes;
338        sizes.max_content.max_assign(sizes.min_content);
339        result
340    }
341}
342
343/// The possible values accepted by the sizing properties.
344/// <https://drafts.csswg.org/css-sizing/#sizing-properties>
345#[derive(Clone, Debug, PartialEq)]
346pub(crate) enum Size<T> {
347    /// Represents an `auto` value for the preferred and minimum size properties,
348    /// or `none` for the maximum size properties.
349    /// <https://drafts.csswg.org/css-sizing/#valdef-width-auto>
350    /// <https://drafts.csswg.org/css-sizing/#valdef-max-width-none>
351    Initial,
352    /// <https://drafts.csswg.org/css-sizing/#valdef-width-min-content>
353    MinContent,
354    /// <https://drafts.csswg.org/css-sizing/#valdef-width-max-content>
355    MaxContent,
356    /// <https://drafts.csswg.org/css-sizing-4/#valdef-width-fit-content>
357    FitContent,
358    /// <https://drafts.csswg.org/css-sizing-3/#funcdef-width-fit-content>
359    FitContentFunction(T),
360    /// <https://drafts.csswg.org/css-sizing-4/#valdef-width-stretch>
361    Stretch,
362    /// Represents the special stretching behavior of `<html>` and `<body>`
363    /// in quirks mode. Roughly, it behaves as the maximum of `fit-content`
364    /// and `stretch`. It can only be used as a preferred block size.
365    /// <https://quirks.spec.whatwg.org/#the-html-element-fills-the-viewport-quirk>
366    /// <https://quirks.spec.whatwg.org/#the-body-element-fills-the-html-element-quirk>
367    QuirkyStretch,
368    /// Represents a numeric `<length-percentage>`, but resolved as a `T`.
369    /// <https://drafts.csswg.org/css-sizing/#valdef-width-length-percentage-0>
370    Numeric(T),
371}
372
373impl<T: Copy> Copy for Size<T> {}
374
375impl<T> Default for Size<T> {
376    #[inline]
377    fn default() -> Self {
378        Self::Initial
379    }
380}
381
382impl<T> Size<T> {
383    #[inline]
384    pub(crate) fn is_initial(&self) -> bool {
385        matches!(self, Self::Initial)
386    }
387}
388
389impl<T: Clone> Size<T> {
390    #[inline]
391    pub(crate) fn to_numeric(&self) -> Option<T> {
392        match self {
393            Self::Numeric(numeric) => Some(numeric).cloned(),
394            _ => None,
395        }
396    }
397
398    #[inline]
399    pub(crate) fn map<U>(&self, f: impl FnOnce(T) -> U) -> Size<U> {
400        match self {
401            Size::Initial => Size::Initial,
402            Size::MinContent => Size::MinContent,
403            Size::MaxContent => Size::MaxContent,
404            Size::FitContent => Size::FitContent,
405            Size::FitContentFunction(size) => Size::FitContentFunction(f(size.clone())),
406            Size::Stretch => Size::Stretch,
407            Size::QuirkyStretch => Size::QuirkyStretch,
408            Size::Numeric(numeric) => Size::Numeric(f(numeric.clone())),
409        }
410    }
411}
412
413impl From<&StyleSize> for Size<LengthPercentage> {
414    fn from(size: &StyleSize) -> Self {
415        match size {
416            StyleSize::LengthPercentage(lp) => Size::Numeric(lp.0.clone()),
417            StyleSize::Auto => Size::Initial,
418            StyleSize::MinContent => Size::MinContent,
419            StyleSize::MaxContent => Size::MaxContent,
420            StyleSize::FitContent => Size::FitContent,
421            StyleSize::FitContentFunction(lp) => Size::FitContentFunction(lp.0.clone()),
422            StyleSize::Stretch | StyleSize::WebkitFillAvailable => Size::Stretch,
423            StyleSize::AnchorSizeFunction(_) | StyleSize::AnchorContainingCalcFunction(_) => {
424                unreachable!("anchor-size() should be disabled")
425            },
426        }
427    }
428}
429
430impl From<&StyleMaxSize> for Size<LengthPercentage> {
431    fn from(max_size: &StyleMaxSize) -> Self {
432        match max_size {
433            StyleMaxSize::LengthPercentage(lp) => Size::Numeric(lp.0.clone()),
434            StyleMaxSize::None => Size::Initial,
435            StyleMaxSize::MinContent => Size::MinContent,
436            StyleMaxSize::MaxContent => Size::MaxContent,
437            StyleMaxSize::FitContent => Size::FitContent,
438            StyleMaxSize::FitContentFunction(lp) => Size::FitContentFunction(lp.0.clone()),
439            StyleMaxSize::Stretch | StyleMaxSize::WebkitFillAvailable => Size::Stretch,
440            StyleMaxSize::AnchorSizeFunction(_) | StyleMaxSize::AnchorContainingCalcFunction(_) => {
441                unreachable!("anchor-size() should be disabled")
442            },
443        }
444    }
445}
446
447impl Size<LengthPercentage> {
448    #[inline]
449    pub(crate) fn to_percentage(&self) -> Option<Percentage> {
450        self.to_numeric()
451            .and_then(|length_percentage| length_percentage.to_percentage())
452    }
453
454    /// Resolves percentages in a preferred size, against the provided basis.
455    /// If the basis is missing, percentages are considered cyclic.
456    /// <https://www.w3.org/TR/css-sizing-3/#preferred-size-properties>
457    /// <https://www.w3.org/TR/css-sizing-3/#cyclic-percentage-size>
458    #[inline]
459    pub(crate) fn resolve_percentages_for_preferred(&self, basis: Option<Au>) -> Size<Au> {
460        match self {
461            Size::Numeric(numeric) => numeric
462                .maybe_to_used_value(basis)
463                .map_or(Size::Initial, Size::Numeric),
464            Size::FitContentFunction(numeric) => {
465                // Under discussion in https://github.com/w3c/csswg-drafts/issues/11805
466                numeric
467                    .maybe_to_used_value(basis)
468                    .map_or(Size::FitContent, Size::FitContentFunction)
469            },
470            _ => self.map(|_| unreachable!("This shouldn't be called for keywords")),
471        }
472    }
473
474    /// Resolves percentages in a maximum size, against the provided basis.
475    /// If the basis is missing, percentages are considered cyclic.
476    /// <https://www.w3.org/TR/css-sizing-3/#preferred-size-properties>
477    /// <https://www.w3.org/TR/css-sizing-3/#cyclic-percentage-size>
478    #[inline]
479    pub(crate) fn resolve_percentages_for_max(&self, basis: Option<Au>) -> Size<Au> {
480        match self {
481            Size::Numeric(numeric) => numeric
482                .maybe_to_used_value(basis)
483                .map_or(Size::Initial, Size::Numeric),
484            Size::FitContentFunction(numeric) => {
485                // Under discussion in https://github.com/w3c/csswg-drafts/issues/11805
486                numeric
487                    .maybe_to_used_value(basis)
488                    .map_or(Size::MaxContent, Size::FitContentFunction)
489            },
490            _ => self.map(|_| unreachable!("This shouldn't be called for keywords")),
491        }
492    }
493}
494
495impl LogicalVec2<Size<LengthPercentage>> {
496    pub(crate) fn percentages_relative_to_basis(
497        &self,
498        basis: &LogicalVec2<Au>,
499    ) -> LogicalVec2<Size<Au>> {
500        LogicalVec2 {
501            inline: self.inline.map(|value| value.to_used_value(basis.inline)),
502            block: self.block.map(|value| value.to_used_value(basis.block)),
503        }
504    }
505}
506
507impl Size<Au> {
508    /// Resolves a preferred size into a numerical value.
509    /// <https://www.w3.org/TR/css-sizing-3/#preferred-size-properties>
510    #[inline]
511    pub(crate) fn resolve_for_preferred<F: FnOnce() -> ContentSizes>(
512        &self,
513        automatic_size: Size<Au>,
514        stretch_size: Option<Au>,
515        content_size: &LazyCell<ContentSizes, F>,
516    ) -> Au {
517        match self {
518            Self::Initial => {
519                assert!(!automatic_size.is_initial());
520                automatic_size.resolve_for_preferred(automatic_size, stretch_size, content_size)
521            },
522            Self::MinContent => content_size.min_content,
523            Self::MaxContent => content_size.max_content,
524            Self::FitContentFunction(size) => content_size.shrink_to_fit(*size),
525            Self::FitContent => {
526                content_size.shrink_to_fit(stretch_size.unwrap_or_else(|| content_size.max_content))
527            },
528            Self::Stretch => stretch_size.unwrap_or_else(|| content_size.max_content),
529            Self::QuirkyStretch => stretch_size
530                .unwrap_or_else(|| content_size.max_content)
531                .max(content_size.min_content),
532            Self::Numeric(numeric) => *numeric,
533        }
534    }
535
536    /// Resolves a minimum size into a numerical value.
537    /// <https://www.w3.org/TR/css-sizing-3/#min-size-properties>
538    #[inline]
539    pub(crate) fn resolve_for_min<F: FnOnce() -> ContentSizes>(
540        &self,
541        get_automatic_minimum_size: impl FnOnce() -> Au,
542        stretch_size: Option<Au>,
543        content_size: &LazyCell<ContentSizes, F>,
544        is_table: bool,
545    ) -> Au {
546        let result = match self {
547            Self::Initial => get_automatic_minimum_size(),
548            Self::MinContent => content_size.min_content,
549            Self::MaxContent => content_size.max_content,
550            Self::FitContentFunction(size) => content_size.shrink_to_fit(*size),
551            Self::FitContent => content_size.shrink_to_fit(stretch_size.unwrap_or_default()),
552            Self::Stretch => stretch_size.unwrap_or_default(),
553            Self::QuirkyStretch => unreachable!("Quirky stretch can't be a min size"),
554            Self::Numeric(numeric) => *numeric,
555        };
556        if is_table {
557            // In addition to the specified minimum, the inline size of a table is forced to be
558            // at least as big as its min-content size.
559            //
560            // Note that if there are collapsed columns, only the inline size of the table grid will
561            // shrink, while the size of the table wrapper (being computed here) won't be affected.
562            // However, collapsed rows should typically affect the block size of the table wrapper,
563            // so it might be wrong to use this function for that case.
564            // This is being discussed in https://github.com/w3c/csswg-drafts/issues/11408
565            result.max(content_size.min_content)
566        } else {
567            result
568        }
569    }
570
571    /// Resolves a maximum size into a numerical value.
572    /// <https://www.w3.org/TR/css-sizing-3/#max-size-properties>
573    #[inline]
574    pub(crate) fn resolve_for_max<F: FnOnce() -> ContentSizes>(
575        &self,
576        stretch_size: Option<Au>,
577        content_size: &LazyCell<ContentSizes, F>,
578    ) -> Option<Au> {
579        Some(match self {
580            Self::Initial => return None,
581            Self::MinContent => content_size.min_content,
582            Self::MaxContent => content_size.max_content,
583            Self::FitContentFunction(size) => content_size.shrink_to_fit(*size),
584            Self::FitContent => content_size.shrink_to_fit(stretch_size.unwrap_or(MAX_AU)),
585            Self::Stretch => return stretch_size,
586            Self::QuirkyStretch => unreachable!("Quirky stretch can't be a max size"),
587            Self::Numeric(numeric) => *numeric,
588        })
589    }
590
591    /// Tries to resolve an extrinsic size into a numerical value.
592    /// Extrinsic sizes are those based on the context of an element, without regard for its contents.
593    /// <https://drafts.csswg.org/css-sizing-3/#extrinsic>
594    ///
595    /// Returns `None` if either:
596    /// - The size is intrinsic. A quirky stretch doesn't count as intrinsic here.
597    /// - The size is the initial one.
598    ///   TODO: should we allow it to behave as `stretch` instead of assuming it's intrinsic?
599    /// - The provided `stretch_size` is `None` but we need its value.
600    #[inline]
601    pub(crate) fn maybe_resolve_extrinsic(&self, stretch_size: Option<Au>) -> Option<Au> {
602        match self {
603            Self::Initial |
604            Self::MinContent |
605            Self::MaxContent |
606            Self::FitContent |
607            Self::FitContentFunction(_) => None,
608            Self::Stretch | Self::QuirkyStretch => stretch_size,
609            Self::Numeric(numeric) => Some(*numeric),
610        }
611    }
612}
613
614/// Represents the sizing constraint that the preferred, min and max sizing properties
615/// impose on one axis.
616#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
617pub(crate) enum SizeConstraint {
618    /// Represents a definite preferred size, clamped by minimum and maximum sizes (if any).
619    Definite(Au),
620    /// Represents an indefinite preferred size that allows a range of values between
621    /// the first argument (minimum size) and the second one (maximum size).
622    MinMax(Au, Option<Au>),
623}
624
625impl Default for SizeConstraint {
626    #[inline]
627    fn default() -> Self {
628        Self::MinMax(Au::default(), None)
629    }
630}
631
632impl SizeConstraint {
633    #[inline]
634    pub(crate) fn new(preferred_size: Option<Au>, min_size: Au, max_size: Option<Au>) -> Self {
635        preferred_size.map_or_else(
636            || Self::MinMax(min_size, max_size),
637            |size| Self::Definite(size.clamp_between_extremums(min_size, max_size)),
638        )
639    }
640
641    #[inline]
642    pub(crate) fn is_definite(self) -> bool {
643        matches!(self, Self::Definite(_))
644    }
645
646    #[inline]
647    pub(crate) fn to_definite(self) -> Option<Au> {
648        match self {
649            Self::Definite(size) => Some(size),
650            _ => None,
651        }
652    }
653
654    #[inline]
655    pub(crate) fn definite_or_min(self) -> Au {
656        match self {
657            Self::Definite(size) => size,
658            Self::MinMax(min, _) => min,
659        }
660    }
661
662    #[inline]
663    pub(crate) fn replace_if_indefinite_with(&mut self, replacement: Self) {
664        if !self.is_definite() {
665            *self = replacement
666        }
667    }
668}
669
670impl From<Option<Au>> for SizeConstraint {
671    fn from(size: Option<Au>) -> Self {
672        size.map(SizeConstraint::Definite).unwrap_or_default()
673    }
674}
675
676#[derive(Clone, Debug, Default)]
677pub(crate) struct Sizes {
678    /// <https://drafts.csswg.org/css-sizing-3/#preferred-size-properties>
679    pub preferred: Size<Au>,
680    /// <https://drafts.csswg.org/css-sizing-3/#min-size-properties>
681    pub min: Size<Au>,
682    /// <https://drafts.csswg.org/css-sizing-3/#max-size-properties>
683    pub max: Size<Au>,
684}
685
686impl Sizes {
687    #[inline]
688    pub(crate) fn new(preferred: Size<Au>, min: Size<Au>, max: Size<Au>) -> Self {
689        Self {
690            preferred,
691            min,
692            max,
693        }
694    }
695
696    /// Resolves the three sizes into a single numerical value.
697    #[inline]
698    pub(crate) fn resolve(
699        &self,
700        axis: LogicalAxis,
701        automatic_size: Size<Au>,
702        get_automatic_minimum_size: impl FnOnce() -> Au,
703        stretch_size: Option<Au>,
704        get_content_size: impl FnOnce() -> ContentSizes,
705        is_table: bool,
706    ) -> Au {
707        if is_table && axis == LogicalAxis::Block {
708            // The intrinsic block size of a table already takes sizing properties into account,
709            // but it can be a smaller amount if there are collapsed rows.
710            // Therefore, disregard sizing properties and just defer to the intrinsic size.
711            // This is being discussed in https://github.com/w3c/csswg-drafts/issues/11408
712            return get_content_size().max_content;
713        }
714        let (preferred, min, max) = self.resolve_each(
715            automatic_size,
716            get_automatic_minimum_size,
717            stretch_size,
718            get_content_size,
719            is_table,
720        );
721        preferred.clamp_between_extremums(min, max)
722    }
723
724    /// Resolves each of the three sizes into a numerical value, separately.
725    /// - The 1st returned value is the resolved preferred size.
726    /// - The 2nd returned value is the resolved minimum size.
727    /// - The 3rd returned value is the resolved maximum size. `None` means no maximum.
728    #[inline]
729    pub(crate) fn resolve_each(
730        &self,
731        automatic_size: Size<Au>,
732        get_automatic_minimum_size: impl FnOnce() -> Au,
733        stretch_size: Option<Au>,
734        get_content_size: impl FnOnce() -> ContentSizes,
735        is_table: bool,
736    ) -> (Au, Au, Option<Au>) {
737        // The provided `get_content_size` is a FnOnce but we may need its result multiple times.
738        // A LazyCell will only invoke it once if needed, and then reuse the result.
739        let content_size = LazyCell::new(get_content_size);
740        (
741            self.preferred
742                .resolve_for_preferred(automatic_size, stretch_size, &content_size),
743            self.min.resolve_for_min(
744                get_automatic_minimum_size,
745                stretch_size,
746                &content_size,
747                is_table,
748            ),
749            self.max.resolve_for_max(stretch_size, &content_size),
750        )
751    }
752
753    /// Tries to extrinsically resolve the three sizes into a single [`SizeConstraint`].
754    /// Values that are intrinsic or need `stretch_size` when it's `None` are handled as such:
755    /// - On the preferred size, they make the returned value be an indefinite [`SizeConstraint::MinMax`].
756    /// - On the min size, they are treated as `auto`, enforcing the automatic minimum size.
757    /// - On the max size, they are treated as `none`, enforcing no maximum.
758    #[inline]
759    pub(crate) fn resolve_extrinsic(
760        &self,
761        automatic_size: Size<Au>,
762        automatic_minimum_size: Au,
763        stretch_size: Option<Au>,
764    ) -> SizeConstraint {
765        let (preferred, min, max) =
766            self.resolve_each_extrinsic(automatic_size, automatic_minimum_size, stretch_size);
767        SizeConstraint::new(preferred, min, max)
768    }
769
770    /// Tries to extrinsically resolve each of the three sizes into a numerical value, separately.
771    /// This can't resolve values that are intrinsic or need `stretch_size` but it's `None`.
772    /// - The 1st returned value is the resolved preferred size. If it can't be resolved then
773    ///   the returned value is `None`. Note that this is different than treating it as `auto`.
774    ///   TODO: This needs to be discussed in <https://github.com/w3c/csswg-drafts/issues/11387>.
775    /// - The 2nd returned value is the resolved minimum size. If it can't be resolved then we
776    ///   treat it as the initial `auto`, returning the automatic minimum size.
777    /// - The 3rd returned value is the resolved maximum size. If it can't be resolved then we
778    ///   treat it as the initial `none`, returning `None`.
779    #[inline]
780    pub(crate) fn resolve_each_extrinsic(
781        &self,
782        automatic_size: Size<Au>,
783        automatic_minimum_size: Au,
784        stretch_size: Option<Au>,
785    ) -> (Option<Au>, Au, Option<Au>) {
786        (
787            if self.preferred.is_initial() {
788                automatic_size.maybe_resolve_extrinsic(stretch_size)
789            } else {
790                self.preferred.maybe_resolve_extrinsic(stretch_size)
791            },
792            self.min
793                .maybe_resolve_extrinsic(stretch_size)
794                .unwrap_or(automatic_minimum_size),
795            self.max.maybe_resolve_extrinsic(stretch_size),
796        )
797    }
798}
799
800struct LazySizeData<'a> {
801    sizes: &'a Sizes,
802    axis: LogicalAxis,
803    automatic_size: Size<Au>,
804    get_automatic_minimum_size: fn() -> Au,
805    stretch_size: Option<Au>,
806    is_table: bool,
807}
808
809/// Represents a size that can't be fully resolved until the intrinsic size
810/// is known. This is useful in the block axis, since the intrinsic size
811/// depends on layout, but the other inputs are known beforehand.
812pub(crate) struct LazySize<'a> {
813    result: OnceCell<Au>,
814    data: Option<LazySizeData<'a>>,
815}
816
817impl<'a> LazySize<'a> {
818    pub(crate) fn new(
819        sizes: &'a Sizes,
820        axis: LogicalAxis,
821        automatic_size: Size<Au>,
822        get_automatic_minimum_size: fn() -> Au,
823        stretch_size: Option<Au>,
824        is_table: bool,
825    ) -> Self {
826        Self {
827            result: OnceCell::new(),
828            data: Some(LazySizeData {
829                sizes,
830                axis,
831                automatic_size,
832                get_automatic_minimum_size,
833                stretch_size,
834                is_table,
835            }),
836        }
837    }
838
839    /// Creates a [`LazySize`] that will resolve to the intrinsic size.
840    /// Should be equivalent to [`LazySize::new()`] with default parameters,
841    /// but avoiding the trouble of getting a reference to a [`Sizes::default()`]
842    /// which lives long enough.
843    ///
844    /// TODO: It's not clear what this should do if/when [`LazySize::resolve()`]
845    /// is changed to accept a [`ContentSizes`] as the intrinsic size.
846    pub(crate) fn intrinsic() -> Self {
847        Self {
848            result: OnceCell::new(),
849            data: None,
850        }
851    }
852
853    /// Resolves the [`LazySize`] into [`Au`], caching the result.
854    /// The argument is a callback that computes the intrinsic size lazily.
855    ///
856    /// TODO: The intrinsic size should probably be a [`ContentSizes`] instead of [`Au`].
857    pub(crate) fn resolve(&self, get_content_size: impl FnOnce() -> Au) -> Au {
858        *self.result.get_or_init(|| {
859            let Some(ref data) = self.data else {
860                return get_content_size();
861            };
862            data.sizes.resolve(
863                data.axis,
864                data.automatic_size,
865                data.get_automatic_minimum_size,
866                data.stretch_size,
867                || get_content_size().into(),
868                data.is_table,
869            )
870        })
871    }
872}
873
874impl From<Au> for LazySize<'_> {
875    /// Creates a [`LazySize`] that will resolve to the given [`Au`],
876    /// ignoring the intrinsic size.
877    fn from(value: Au) -> Self {
878        let result = OnceCell::new();
879        result.set(value).unwrap();
880        LazySize { result, data: None }
881    }
882}