Skip to main content

leptos_css/
dimension.rs

1use std::fmt;
2
3use crate::checked_value::impl_checked_value;
4use crate::{
5    CssLength, CssValue, CssVariableReference, FiniteF64, InvalidCssNumber, number::try_finite,
6    serialization::CssWriteTo,
7};
8
9/// A CSS `<length-percentage>` value.
10///
11/// This is a type-safe subset of [`CssValue`] for component props that specifically need
12/// a length or percentage. Property grammars that also accept `auto` use
13/// [`LengthPercentageAuto`] instead, so `auto` cannot leak into arithmetic or padding.
14///
15/// Converts to [`CssValue`] via `From`/`Into` for use with the style system.
16///
17/// # Example
18/// ```rust
19/// use leptos_css::{CssDimension, px, pct};
20///
21/// let gap = px(10);
22/// let width = pct(100);
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq)]
25#[non_exhaustive]
26pub enum CssDimension {
27    /// A CSS length value (px, em, rem, vh, vw, etc.).
28    Length(CssLength),
29    /// A percentage value.
30    Percent(FiniteF64),
31    /// Zero with unit for `calc()` compatibility. Renders as `"0px"`.
32    Zero,
33}
34
35/// Const constructors for [`CssDimension`].
36///
37/// Each constructor wraps a [`CssLength`] variant or [`CssDimension::Percent`]; see the
38/// crate-level helpers in [`crate`] (`px`, `em`, `rem`, …) for the equivalent free functions.
39macro_rules! dimension_constructor {
40    ($(#[$meta:meta])* $name:ident, $try_name:ident, $variant:ident, $unit:literal) => {
41        $(#[$meta])*
42        ///
43        /// # Panics
44        ///
45        /// Panics if `v` is `NaN` or infinite. Use the corresponding `try_` constructor for
46        /// runtime-derived values.
47        #[track_caller]
48        pub const fn $name(v: f64) -> Self {
49            match Self::$try_name(v) {
50                Ok(value) => value,
51                Err(_) => panic!(concat!("CSS ", $unit, " value must be finite")),
52            }
53        }
54
55        #[doc = concat!("Attempt to construct a finite `", $unit, "` dimension.")]
56        ///
57        /// # Errors
58        ///
59        /// Returns [`InvalidCssNumber::NonFinite`] if `v` is `NaN` or infinite.
60        pub const fn $try_name(v: f64) -> Result<Self, InvalidCssNumber> {
61            match try_finite(v, $unit) {
62                Ok(value) => Ok(Self::Length(CssLength::$variant(value))),
63                Err(error) => Err(error),
64            }
65        }
66    };
67}
68
69impl CssDimension {
70    dimension_constructor!(/// Construct a `px` length dimension.
71        px, try_px, Px, "px");
72    dimension_constructor!(/// Construct an `em` length dimension.
73        em, try_em, Em, "em");
74    dimension_constructor!(/// Construct a `rem` length dimension.
75        rem, try_rem, Rem, "rem");
76    dimension_constructor!(/// Construct a `vw` length dimension.
77        vw, try_vw, Vw, "vw");
78    dimension_constructor!(/// Construct a `vh` length dimension.
79        vh, try_vh, Vh, "vh");
80    dimension_constructor!(/// Construct a `vmin` length dimension.
81        vmin, try_vmin, Vmin, "vmin");
82    dimension_constructor!(/// Construct a `vmax` length dimension.
83        vmax, try_vmax, Vmax, "vmax");
84    dimension_constructor!(/// Construct a `ch` length dimension.
85        ch, try_ch, Ch, "ch");
86    dimension_constructor!(/// Construct a `dvw` length dimension.
87        dvw, try_dvw, Dvw, "dvw");
88    dimension_constructor!(/// Construct a `dvh` length dimension.
89        dvh, try_dvh, Dvh, "dvh");
90    dimension_constructor!(/// Construct an `svw` length dimension.
91        svw, try_svw, Svw, "svw");
92    dimension_constructor!(/// Construct an `svh` length dimension.
93        svh, try_svh, Svh, "svh");
94    dimension_constructor!(/// Construct an `lvw` length dimension.
95        lvw, try_lvw, Lvw, "lvw");
96    dimension_constructor!(/// Construct an `lvh` length dimension.
97        lvh, try_lvh, Lvh, "lvh");
98    dimension_constructor!(/// Construct a `cqw` length dimension.
99        cqw, try_cqw, Cqw, "cqw");
100    dimension_constructor!(/// Construct a `cqh` length dimension.
101        cqh, try_cqh, Cqh, "cqh");
102
103    /// Construct a percentage dimension, panicking if `v` is not finite.
104    ///
105    /// # Panics
106    ///
107    /// Panics if `v` is `NaN` or infinite. Use [`CssDimension::try_pct`] for runtime-derived
108    /// values.
109    #[track_caller]
110    pub const fn pct(v: f64) -> Self {
111        match Self::try_pct(v) {
112            Ok(value) => value,
113            Err(_) => panic!("CSS % value must be finite"),
114        }
115    }
116
117    /// Attempt to construct a finite percentage dimension.
118    ///
119    /// # Errors
120    ///
121    /// Returns [`InvalidCssNumber::NonFinite`] if `v` is `NaN` or infinite.
122    pub const fn try_pct(v: f64) -> Result<Self, InvalidCssNumber> {
123        match try_finite(v, "%") {
124            Ok(value) => Ok(Self::Percent(value)),
125            Err(error) => Err(error),
126        }
127    }
128}
129
130impl CssWriteTo for CssDimension {
131    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
132        match self {
133            Self::Length(l) => l.css_fmt(w),
134            Self::Percent(v) => write!(w, "{v}%"),
135            Self::Zero => w.write_str("0px"),
136        }
137    }
138}
139
140impl From<CssDimension> for CssValue {
141    fn from(dim: CssDimension) -> Self {
142        match dim {
143            CssDimension::Length(l) => Self::Length(l),
144            CssDimension::Percent(v) => Self::Percent(v),
145            CssDimension::Zero => Self::Zero,
146        }
147    }
148}
149
150impl From<CssLength> for CssDimension {
151    fn from(l: CssLength) -> Self {
152        Self::Length(l)
153    }
154}
155
156/// A `<length-percentage> | auto` value for grammars such as margin and inset offsets.
157///
158/// Typed calculations are also accepted because CSS math functions resolve to a
159/// `<length-percentage>` in these contexts.
160#[derive(Clone, Debug, PartialEq)]
161#[non_exhaustive]
162pub enum LengthPercentageAuto {
163    /// A length or percentage.
164    LengthPercentage(CssDimension),
165    /// A typed length-percentage calculation.
166    Calculation(CssDimensionExpr),
167    /// The `auto` keyword.
168    Auto,
169}
170
171impl From<CssDimension> for LengthPercentageAuto {
172    fn from(value: CssDimension) -> Self {
173        Self::LengthPercentage(value)
174    }
175}
176
177impl From<CssDimensionExpr> for LengthPercentageAuto {
178    fn from(value: CssDimensionExpr) -> Self {
179        Self::Calculation(value)
180    }
181}
182
183impl CssWriteTo for LengthPercentageAuto {
184    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
185        match self {
186            Self::LengthPercentage(value) => value.css_fmt(w),
187            Self::Calculation(value) => value.css_fmt(w),
188            Self::Auto => w.write_str("auto"),
189        }
190    }
191}
192
193/// User-agent environment variables supported by the typed `env()` expression.
194#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
195#[non_exhaustive]
196pub enum CssEnvironmentVariable {
197    /// `safe-area-inset-top`.
198    SafeAreaInsetTop,
199    /// `safe-area-inset-right`.
200    SafeAreaInsetRight,
201    /// `safe-area-inset-bottom`.
202    SafeAreaInsetBottom,
203    /// `safe-area-inset-left`.
204    SafeAreaInsetLeft,
205    /// `safe-area-max-inset-top`.
206    SafeAreaMaxInsetTop,
207    /// `safe-area-max-inset-right`.
208    SafeAreaMaxInsetRight,
209    /// `safe-area-max-inset-bottom`.
210    SafeAreaMaxInsetBottom,
211    /// `safe-area-max-inset-left`.
212    SafeAreaMaxInsetLeft,
213}
214
215impl CssEnvironmentVariable {
216    const fn as_str(self) -> &'static str {
217        match self {
218            Self::SafeAreaInsetTop => "safe-area-inset-top",
219            Self::SafeAreaInsetRight => "safe-area-inset-right",
220            Self::SafeAreaInsetBottom => "safe-area-inset-bottom",
221            Self::SafeAreaInsetLeft => "safe-area-inset-left",
222            Self::SafeAreaMaxInsetTop => "safe-area-max-inset-top",
223            Self::SafeAreaMaxInsetRight => "safe-area-max-inset-right",
224            Self::SafeAreaMaxInsetBottom => "safe-area-max-inset-bottom",
225            Self::SafeAreaMaxInsetLeft => "safe-area-max-inset-left",
226        }
227    }
228}
229
230/// A typed CSS length-percentage expression.
231///
232/// The expression tree is private. Values can only be constructed from typed dimensions,
233/// arithmetic, or the typed [`css_min`], [`css_max`], [`css_clamp`], and [`css_env`] helpers.
234/// This prevents malformed function bodies and invalid argument counts from being represented.
235#[derive(Clone, Debug, PartialEq)]
236pub struct CssDimensionExpr(DimensionExpr);
237
238#[derive(Clone, Debug, PartialEq)]
239enum DimensionExpr {
240    Simple(CssDimension),
241    Variable(CssVariableReference<CssDimension>),
242    Add(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
243    Subtract(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
244    Min(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
245    Max(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
246    Clamp {
247        min: Box<CssDimensionExpr>,
248        preferred: Box<CssDimensionExpr>,
249        max: Box<CssDimensionExpr>,
250    },
251    Env(CssEnvironmentVariable),
252}
253
254impl CssDimensionExpr {
255    fn calc_fmt<W: fmt::Write>(&self, w: &mut W, nested: bool) -> fmt::Result {
256        match &self.0 {
257            DimensionExpr::Simple(value) => value.css_fmt(w),
258            DimensionExpr::Variable(value) => value.css_fmt(w),
259            DimensionExpr::Add(lhs, rhs) | DimensionExpr::Subtract(lhs, rhs) => {
260                if nested {
261                    w.write_char('(')?;
262                }
263                lhs.calc_fmt(w, true)?;
264                if matches!(&self.0, DimensionExpr::Add(_, _)) {
265                    w.write_str(" + ")?;
266                } else {
267                    w.write_str(" - ")?;
268                }
269                rhs.calc_fmt(w, true)?;
270                if nested {
271                    w.write_char(')')?;
272                }
273                Ok(())
274            }
275            DimensionExpr::Min(_, _)
276            | DimensionExpr::Max(_, _)
277            | DimensionExpr::Clamp { .. }
278            | DimensionExpr::Env(_) => self.css_fmt(w),
279        }
280    }
281
282    /// Serialize as a top-level calculation for a range-restricted property grammar.
283    ///
284    /// Binary nodes already emit `calc()`, while `min()`, `max()`, and `clamp()` emit their own CSS
285    /// math functions. Simple dimensions, `var()`, and `env()` need an explicit `calc()` wrapper
286    /// so substituted or folded out-of-range results are clamped under CSS math-function range
287    /// checking instead of becoming invalid plain values.
288    fn css_fmt_as_top_level_calculation<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
289        if matches!(
290            &self.0,
291            DimensionExpr::Simple(_) | DimensionExpr::Variable(_) | DimensionExpr::Env(_)
292        ) {
293            w.write_str("calc(")?;
294            self.calc_fmt(w, false)?;
295            w.write_char(')')
296        } else {
297            self.css_fmt(w)
298        }
299    }
300}
301
302impl CssWriteTo for CssDimensionExpr {
303    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
304        match &self.0 {
305            DimensionExpr::Simple(value) => value.css_fmt(w),
306            DimensionExpr::Variable(value) => value.css_fmt(w),
307            DimensionExpr::Add(_, _) | DimensionExpr::Subtract(_, _) => {
308                w.write_str("calc(")?;
309                self.calc_fmt(w, false)?;
310                w.write_char(')')
311            }
312            DimensionExpr::Min(lhs, rhs) => {
313                w.write_str("min(")?;
314                lhs.css_fmt(w)?;
315                w.write_str(", ")?;
316                rhs.css_fmt(w)?;
317                w.write_char(')')
318            }
319            DimensionExpr::Max(lhs, rhs) => {
320                w.write_str("max(")?;
321                lhs.css_fmt(w)?;
322                w.write_str(", ")?;
323                rhs.css_fmt(w)?;
324                w.write_char(')')
325            }
326            DimensionExpr::Clamp {
327                min,
328                preferred,
329                max,
330            } => {
331                w.write_str("clamp(")?;
332                min.css_fmt(w)?;
333                w.write_str(", ")?;
334                preferred.css_fmt(w)?;
335                w.write_str(", ")?;
336                max.css_fmt(w)?;
337                w.write_char(')')
338            }
339            DimensionExpr::Env(variable) => write!(w, "env({})", variable.as_str()),
340        }
341    }
342}
343
344impl From<CssDimension> for CssDimensionExpr {
345    fn from(dim: CssDimension) -> Self {
346        Self(DimensionExpr::Simple(dim))
347    }
348}
349
350impl From<CssLength> for CssDimensionExpr {
351    fn from(length: CssLength) -> Self {
352        Self::from(CssDimension::Length(length))
353    }
354}
355
356impl From<CssVariableReference<CssDimension>> for CssDimensionExpr {
357    fn from(variable: CssVariableReference<CssDimension>) -> Self {
358        Self(DimensionExpr::Variable(variable))
359    }
360}
361
362/// A length-percentage math expression suitable for a property grammar.
363///
364/// This wrapper guarantees that a simple operand is emitted inside `calc()`. That distinction
365/// matters for range-restricted grammars: `calc(-1px)` is valid and is clamped by
366/// [CSS math-function range checking], while a plain `-1px` can be invalid for the same property.
367///
368/// [CSS math-function range checking]: https://drafts.csswg.org/css-values-4/#calc-range
369#[derive(Clone, Debug, PartialEq)]
370pub struct LengthPercentageCalculation(CssDimensionExpr);
371
372impl LengthPercentageCalculation {
373    /// Construct a checked length-percentage calculation.
374    ///
375    pub fn new(expression: impl Into<CssDimensionExpr>) -> Self {
376        Self(expression.into())
377    }
378}
379
380impl CssWriteTo for LengthPercentageCalculation {
381    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
382        self.0.css_fmt_as_top_level_calculation(w)
383    }
384}
385
386impl From<CssDimension> for String {
387    fn from(dim: CssDimension) -> Self {
388        let mut s = Self::new();
389        dim.write_to(&mut s);
390        s
391    }
392}
393
394impl From<CssDimension> for std::borrow::Cow<'static, str> {
395    fn from(dim: CssDimension) -> Self {
396        Self::Owned(String::from(dim))
397    }
398}
399
400impl From<CssDimensionExpr> for String {
401    fn from(expr: CssDimensionExpr) -> Self {
402        let mut s = Self::new();
403        expr.write_to(&mut s);
404        s
405    }
406}
407
408impl From<CssDimensionExpr> for std::borrow::Cow<'static, str> {
409    fn from(expr: CssDimensionExpr) -> Self {
410        Self::Owned(String::from(expr))
411    }
412}
413
414impl std::ops::Neg for CssDimension {
415    type Output = Self;
416
417    /// Negate a dimension value.
418    fn neg(self) -> Self {
419        match self {
420            Self::Length(l) => Self::Length(-l),
421            Self::Percent(v) => Self::Percent(-v),
422            Self::Zero => Self::Zero,
423        }
424    }
425}
426
427// --- Dimension arithmetic ---
428
429/// Returns true if two CssLength values use the same unit (ignoring the numeric value).
430fn same_unit(a: &CssLength, b: &CssLength) -> bool {
431    std::mem::discriminant(a) == std::mem::discriminant(b)
432}
433
434impl std::ops::Add for CssDimension {
435    type Output = CssDimensionExpr;
436
437    /// Add two dimension values. Same-unit operations fold (e.g. `px(10) + px(5)` = `px(15)`).
438    /// Mixed-unit operations produce a `calc()` expression.
439    ///
440    /// # Panics
441    ///
442    /// Panics if folding same-unit operands overflows to a non-finite result.
443    fn add(self, rhs: Self) -> CssDimensionExpr {
444        match (self, rhs) {
445            (Self::Zero, other) | (other, Self::Zero) => CssDimensionExpr::from(other),
446            (Self::Length(a), Self::Length(b)) if same_unit(&a, &b) => {
447                CssDimensionExpr::from(Self::Length(a.map_value(|v| v + b.value())))
448            }
449            (Self::Percent(a), Self::Percent(b)) => {
450                CssDimensionExpr::from(Self::Percent(FiniteF64::new(a.get() + b.get())))
451            }
452            (a, b) => CssDimensionExpr(DimensionExpr::Add(Box::new(a.into()), Box::new(b.into()))),
453        }
454    }
455}
456
457impl std::ops::Sub for CssDimension {
458    type Output = CssDimensionExpr;
459
460    /// Subtract two dimension values. Same-unit operations fold (e.g. `px(10) - px(5)` = `px(5)`).
461    /// Mixed-unit operations produce a `calc()` expression.
462    ///
463    /// # Panics
464    ///
465    /// Panics if folding same-unit operands overflows to a non-finite result.
466    fn sub(self, rhs: Self) -> CssDimensionExpr {
467        match (self, rhs) {
468            (lhs, Self::Zero) => CssDimensionExpr::from(lhs),
469            (Self::Zero, rhs) => CssDimensionExpr::from(-rhs),
470            (Self::Length(a), Self::Length(b)) if same_unit(&a, &b) => {
471                CssDimensionExpr::from(Self::Length(a.map_value(|v| v - b.value())))
472            }
473            (Self::Percent(a), Self::Percent(b)) => {
474                CssDimensionExpr::from(Self::Percent(FiniteF64::new(a.get() - b.get())))
475            }
476            (a, b) => CssDimensionExpr(DimensionExpr::Subtract(
477                Box::new(a.into()),
478                Box::new(b.into()),
479            )),
480        }
481    }
482}
483
484impl std::ops::Add<CssDimension> for CssDimensionExpr {
485    type Output = CssDimensionExpr;
486
487    fn add(self, rhs: CssDimension) -> CssDimensionExpr {
488        self + CssDimensionExpr::from(rhs)
489    }
490}
491
492impl std::ops::Sub<CssDimension> for CssDimensionExpr {
493    type Output = CssDimensionExpr;
494
495    fn sub(self, rhs: CssDimension) -> CssDimensionExpr {
496        self - CssDimensionExpr::from(rhs)
497    }
498}
499
500impl std::ops::Add for CssDimensionExpr {
501    type Output = CssDimensionExpr;
502
503    fn add(self, rhs: Self) -> Self {
504        match (self.0, rhs.0) {
505            (DimensionExpr::Simple(lhs), DimensionExpr::Simple(rhs)) => lhs + rhs,
506            (lhs, rhs) => Self(DimensionExpr::Add(Box::new(Self(lhs)), Box::new(Self(rhs)))),
507        }
508    }
509}
510
511impl std::ops::Sub for CssDimensionExpr {
512    type Output = CssDimensionExpr;
513
514    fn sub(self, rhs: Self) -> Self {
515        match (self.0, rhs.0) {
516            (DimensionExpr::Simple(lhs), DimensionExpr::Simple(rhs)) => lhs - rhs,
517            (lhs, rhs) => Self(DimensionExpr::Subtract(
518                Box::new(Self(lhs)),
519                Box::new(Self(rhs)),
520            )),
521        }
522    }
523}
524
525macro_rules! dim_fn {
526    ($(#[$meta:meta])* $fn_name:ident, $try_fn_name:ident, $unit_str:literal) => {
527        $(#[$meta])*
528        ///
529        /// # Panics
530        ///
531        /// Panics if `v` is `NaN` or infinite. Use the corresponding `try_` helper for
532        /// runtime-derived values.
533        #[track_caller]
534        pub fn $fn_name(v: impl Into<f64>) -> CssDimension {
535            CssDimension::$fn_name(v.into())
536        }
537
538        #[doc = concat!("Attempt to create a finite CSS `", $unit_str, "` value.")]
539        ///
540        /// # Errors
541        ///
542        /// Returns [`InvalidCssNumber::NonFinite`] if `v` is `NaN` or infinite.
543        pub fn $try_fn_name(v: impl Into<f64>) -> Result<CssDimension, InvalidCssNumber> {
544            CssDimension::$try_fn_name(v.into())
545        }
546    };
547}
548
549dim_fn!(/// Create a CSS pixel value.
550    px, try_px, "px");
551dim_fn!(/// Create a CSS em value (relative to the element's font size).
552    em, try_em, "em");
553dim_fn!(
554    #[allow(clippy::module_name_repetitions)]
555    /// Create a CSS rem value (relative to the root element's font size).
556    rem,
557    try_rem,
558    "rem"
559);
560dim_fn!(/// Create a CSS viewport-width value (1vw = 1% of the viewport width).
561    vw, try_vw, "vw");
562dim_fn!(/// Create a CSS viewport-height value (1vh = 1% of the viewport height).
563    vh, try_vh, "vh");
564dim_fn!(/// Create a CSS vmin value (1vmin = 1% of the smaller viewport dimension).
565    vmin, try_vmin, "vmin");
566dim_fn!(/// Create a CSS vmax value (1vmax = 1% of the larger viewport dimension).
567    vmax, try_vmax, "vmax");
568dim_fn!(/// Create a CSS ch (character width) value — the width of the `0` glyph in the element's font.
569    ch, try_ch, "ch");
570dim_fn!(/// Create a CSS dynamic viewport width value.
571    /// Unlike `vw`, adjusts when browser UI elements (e.g. mobile address bar) appear or disappear.
572    dvw, try_dvw, "dvw");
573dim_fn!(/// Create a CSS dynamic viewport height value.
574    /// Unlike `vh`, adjusts when browser UI elements (e.g. mobile address bar) appear or disappear.
575    dvh, try_dvh, "dvh");
576dim_fn!(/// Create a CSS small viewport width value.
577    /// Represents the viewport width when all dynamic browser UI is expanded/visible.
578    svw, try_svw, "svw");
579dim_fn!(/// Create a CSS small viewport height value.
580    /// Represents the viewport height when all dynamic browser UI is expanded/visible.
581    svh, try_svh, "svh");
582dim_fn!(/// Create a CSS large viewport width value.
583    /// Represents the viewport width when all dynamic browser UI is retracted/hidden.
584    lvw, try_lvw, "lvw");
585dim_fn!(/// Create a CSS large viewport height value.
586    /// Represents the viewport height when all dynamic browser UI is retracted/hidden.
587    lvh, try_lvh, "lvh");
588dim_fn!(/// Create a CSS container query width value (1cqw = 1% of the nearest size container's width).
589    cqw, try_cqw, "cqw");
590dim_fn!(/// Create a CSS container query height value (1cqh = 1% of the nearest size container's height).
591    cqh, try_cqh, "cqh");
592
593/// Create a CSS percentage value.
594///
595/// # Panics
596///
597/// Panics if `v` is `NaN` or infinite.
598pub fn pct(v: impl Into<f64>) -> CssDimension {
599    CssDimension::pct(v.into())
600}
601
602/// Attempt to create a finite CSS percentage value.
603///
604/// # Errors
605///
606/// Returns [`InvalidCssNumber::NonFinite`] if `v` is `NaN` or infinite.
607pub fn try_pct(v: impl Into<f64>) -> Result<CssDimension, InvalidCssNumber> {
608    CssDimension::try_pct(v.into())
609}
610
611/// Create a typed CSS `min()` length-percentage expression.
612///
613/// Both arguments are typed, so malformed bodies and empty argument lists are impossible.
614pub fn css_min(
615    lhs: impl Into<CssDimensionExpr>,
616    rhs: impl Into<CssDimensionExpr>,
617) -> CssDimensionExpr {
618    let lhs = lhs.into();
619    let rhs = rhs.into();
620    CssDimensionExpr(DimensionExpr::Min(Box::new(lhs), Box::new(rhs)))
621}
622
623/// Create a typed CSS `max()` length-percentage expression.
624pub fn css_max(
625    lhs: impl Into<CssDimensionExpr>,
626    rhs: impl Into<CssDimensionExpr>,
627) -> CssDimensionExpr {
628    let lhs = lhs.into();
629    let rhs = rhs.into();
630    CssDimensionExpr(DimensionExpr::Max(Box::new(lhs), Box::new(rhs)))
631}
632
633/// Create a typed CSS `clamp(min, preferred, max)` length-percentage expression.
634pub fn css_clamp(
635    min: impl Into<CssDimensionExpr>,
636    preferred: impl Into<CssDimensionExpr>,
637    max: impl Into<CssDimensionExpr>,
638) -> CssDimensionExpr {
639    let min = min.into();
640    let preferred = preferred.into();
641    let max = max.into();
642    CssDimensionExpr(DimensionExpr::Clamp {
643        min: Box::new(min),
644        preferred: Box::new(preferred),
645        max: Box::new(max),
646    })
647}
648
649/// Create a typed CSS `env()` expression for a supported user-agent variable.
650pub fn css_env(variable: CssEnvironmentVariable) -> CssDimensionExpr {
651    CssDimensionExpr(DimensionExpr::Env(variable))
652}
653
654impl_checked_value!(
655    CssDimension,
656    LengthPercentageAuto,
657    CssDimensionExpr,
658    LengthPercentageCalculation,
659);