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