Skip to main content

leptos_css/
box_model.rs

1use std::fmt;
2
3use crate::checked_value::impl_checked_value;
4use crate::{
5    CssDimension, CssDimensionExpr, DeclarationValue, LengthPercentageAuto,
6    LengthPercentageCalculation, serialization::CssWriteTo,
7};
8
9macro_rules! box_model_shorthand {
10    ($(#[$meta:meta])* $name:ident, $value:ty) => {
11        $(#[$meta])*
12        #[derive(Debug, Clone, PartialEq)]
13        #[non_exhaustive]
14        pub enum $name {
15            /// Only on the top edge (other edges are `0`).
16            Top($value),
17            /// Only on the right edge (other edges are `0`).
18            Right($value),
19            /// Only on the bottom edge (other edges are `0`).
20            Bottom($value),
21            /// Only on the left edge (other edges are `0`).
22            Left($value),
23            /// Equal on all four edges.
24            All($value),
25            /// Separate vertical (top/bottom) and horizontal (left/right).
26            Double($value, $value),
27            /// Explicit for each edge: top, right, bottom, left.
28            Full($value, $value, $value, $value),
29        }
30
31        impl CssWriteTo for $name {
32            fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
33                match self {
34                    Self::Top(size) => {
35                        size.css_fmt(w)?;
36                        w.write_str(" 0 0 0")
37                    }
38                    Self::Right(size) => {
39                        w.write_str("0 ")?;
40                        size.css_fmt(w)?;
41                        w.write_str(" 0 0")
42                    }
43                    Self::Bottom(size) => {
44                        w.write_str("0 0 ")?;
45                        size.css_fmt(w)?;
46                        w.write_str(" 0")
47                    }
48                    Self::Left(size) => {
49                        w.write_str("0 0 0 ")?;
50                        size.css_fmt(w)
51                    }
52                    Self::All(size) => size.css_fmt(w),
53                    Self::Double(vertical, horizontal) => {
54                        vertical.css_fmt(w)?;
55                        w.write_char(' ')?;
56                        horizontal.css_fmt(w)
57                    }
58                    Self::Full(top, right, bottom, left) => {
59                        top.css_fmt(w)?;
60                        w.write_char(' ')?;
61                        right.css_fmt(w)?;
62                        w.write_char(' ')?;
63                        bottom.css_fmt(w)?;
64                        w.write_char(' ')?;
65                        left.css_fmt(w)
66                    }
67                }
68            }
69        }
70
71    };
72}
73
74box_model_shorthand!(
75    /// CSS margin shorthand values.
76    ///
77    /// Represents the `margin` CSS shorthand as a typed enum. Each variant maps to
78    /// a different shorthand form:
79    ///
80    /// - `All(dim)` → `margin: dim`
81    /// - `Double(v, h)` → `margin: v h`
82    /// - `Full(t, r, b, l)` → `margin: t r b l`
83    /// - `Top(dim)` → `margin: dim 0 0 0` (and similarly for other sides)
84    ///
85    /// [CSS Box Model margin grammar]: https://www.w3.org/TR/css-box-3/#margin-physical
86    Margin,
87    LengthPercentageAuto
88);
89
90box_model_shorthand!(
91    /// CSS `inset` shorthand values.
92    ///
93    /// Each component accepts `auto`, a direct length-percentage, or a typed calculation.
94    ///
95    /// [CSS Positioned Layout inset grammar]: https://www.w3.org/TR/css-position-3/#insets
96    Inset,
97    LengthPercentageAuto
98);
99
100/// A non-negative `<length-percentage>` suitable for grammars such as `padding` and `gap`.
101///
102/// `auto`, negative values, and non-finite values cannot be represented.
103#[derive(Debug, Clone, Copy, PartialEq)]
104pub struct NonNegativeLengthPercentage(CssDimension);
105
106impl NonNegativeLengthPercentage {
107    /// Construct a non-negative length-percentage.
108    ///
109    /// # Panics
110    ///
111    /// Panics if `value` is negative.
112    #[track_caller]
113    pub fn new(value: CssDimension) -> Self {
114        Self::try_from(value).unwrap_or_else(|error| panic!("{error}"))
115    }
116
117    /// Return the underlying typed dimension.
118    pub const fn get(self) -> CssDimension {
119        self.0
120    }
121}
122
123/// Error returned when a dimension is not a non-negative `<length-percentage>`.
124#[derive(Clone, Copy, Debug, PartialEq)]
125#[non_exhaustive]
126pub enum InvalidNonNegativeLengthPercentage {
127    /// The numeric value is negative.
128    Negative(f64),
129}
130
131impl fmt::Display for InvalidNonNegativeLengthPercentage {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        match self {
134            Self::Negative(value) => write!(f, "CSS value must be non-negative, got {value}"),
135        }
136    }
137}
138
139impl std::error::Error for InvalidNonNegativeLengthPercentage {}
140
141impl TryFrom<CssDimension> for NonNegativeLengthPercentage {
142    type Error = InvalidNonNegativeLengthPercentage;
143
144    fn try_from(value: CssDimension) -> Result<Self, Self::Error> {
145        let number = match value {
146            CssDimension::Length(length) => length.value(),
147            CssDimension::Percent(number) => number.get(),
148            CssDimension::Zero => 0.0,
149        };
150        if number < 0.0 {
151            Err(InvalidNonNegativeLengthPercentage::Negative(number))
152        } else {
153            Ok(Self(value))
154        }
155    }
156}
157
158impl CssWriteTo for NonNegativeLengthPercentage {
159    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
160        self.0.css_fmt(w)
161    }
162}
163
164/// A direct or calculated `<length-percentage [0,∞]>` value.
165///
166/// Direct values are checked before construction. Calculations stay inside a CSS math function so
167/// the specification's top-level range clamping applies after evaluation and substitution.
168#[derive(Clone, Debug, PartialEq)]
169#[non_exhaustive]
170pub enum NonNegativeLengthPercentageValue {
171    /// A directly non-negative length or percentage.
172    Direct(NonNegativeLengthPercentage),
173    /// A typed calculation whose result is clamped to the property's non-negative range.
174    Calculation(LengthPercentageCalculation),
175}
176
177impl From<NonNegativeLengthPercentage> for NonNegativeLengthPercentageValue {
178    fn from(value: NonNegativeLengthPercentage) -> Self {
179        Self::Direct(value)
180    }
181}
182
183impl From<LengthPercentageCalculation> for NonNegativeLengthPercentageValue {
184    fn from(value: LengthPercentageCalculation) -> Self {
185        Self::Calculation(value)
186    }
187}
188
189impl From<NonNegativeLengthPercentage> for DeclarationValue<NonNegativeLengthPercentageValue> {
190    fn from(value: NonNegativeLengthPercentage) -> Self {
191        NonNegativeLengthPercentageValue::from(value).into()
192    }
193}
194
195impl From<LengthPercentageCalculation> for DeclarationValue<NonNegativeLengthPercentageValue> {
196    fn from(value: LengthPercentageCalculation) -> Self {
197        NonNegativeLengthPercentageValue::from(value).into()
198    }
199}
200
201impl CssWriteTo for NonNegativeLengthPercentageValue {
202    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
203        match self {
204            Self::Direct(value) => value.css_fmt(w),
205            Self::Calculation(value) => value.css_fmt(w),
206        }
207    }
208}
209
210/// A logical or physical corner-radius longhand value.
211///
212/// The grammar is `<length-percentage [0,∞]>{1,2}`: one value creates a circular radius and two
213/// values specify the horizontal and vertical radii of an ellipse.
214///
215/// [CSS Logical Properties § 4.6]: https://www.w3.org/TR/css-logical-1/#border-radius-properties
216#[derive(Clone, Debug, PartialEq)]
217#[non_exhaustive]
218pub enum BorderCornerRadius {
219    /// One radius used in both dimensions.
220    Circular(NonNegativeLengthPercentageValue),
221    /// Separate horizontal and vertical radii.
222    Elliptical(
223        NonNegativeLengthPercentageValue,
224        NonNegativeLengthPercentageValue,
225    ),
226}
227
228impl BorderCornerRadius {
229    /// Construct a circular radius from a direct non-negative value.
230    pub fn circular(value: CssDimension) -> Self {
231        Self::Circular(NonNegativeLengthPercentage::new(value).into())
232    }
233
234    /// Construct an elliptical radius from direct non-negative values.
235    pub fn elliptical(horizontal: CssDimension, vertical: CssDimension) -> Self {
236        Self::Elliptical(
237            NonNegativeLengthPercentage::new(horizontal).into(),
238            NonNegativeLengthPercentage::new(vertical).into(),
239        )
240    }
241
242    /// Construct a circular radius from a typed calculation.
243    pub fn calculated(expression: impl Into<CssDimensionExpr>) -> Self {
244        Self::Circular(LengthPercentageCalculation::new(expression).into())
245    }
246}
247
248impl CssWriteTo for BorderCornerRadius {
249    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
250        match self {
251            Self::Circular(radius) => radius.css_fmt(w),
252            Self::Elliptical(horizontal, vertical) => {
253                horizontal.css_fmt(w)?;
254                w.write_char(' ')?;
255                vertical.css_fmt(w)
256            }
257        }
258    }
259}
260
261box_model_shorthand!(
262    /// CSS padding shorthand values.
263    ///
264    /// Mirrors the [`Margin`] type but for the `padding` property.
265    ///
266    /// - `All(dim)` → `padding: dim`
267    /// - `Double(v, h)` → `padding: v h`
268    /// - `Full(t, r, b, l)` → `padding: t r b l`
269    /// - `Top(dim)` → `padding: dim 0 0 0` (and similarly for other sides)
270    ///
271    /// [CSS Box Model padding grammar]: https://www.w3.org/TR/css-box-3/#padding-physical
272    Padding,
273    NonNegativeLengthPercentageValue
274);
275
276impl Padding {
277    /// Construct equal padding on all four edges.
278    #[track_caller]
279    pub fn all(value: CssDimension) -> Self {
280        Self::All(NonNegativeLengthPercentage::new(value).into())
281    }
282
283    /// Construct vertical and horizontal padding.
284    #[track_caller]
285    pub fn double(vertical: CssDimension, horizontal: CssDimension) -> Self {
286        Self::Double(
287            NonNegativeLengthPercentage::new(vertical).into(),
288            NonNegativeLengthPercentage::new(horizontal).into(),
289        )
290    }
291
292    /// Construct explicit top, right, bottom, and left padding.
293    #[track_caller]
294    pub fn full(
295        top: CssDimension,
296        right: CssDimension,
297        bottom: CssDimension,
298        left: CssDimension,
299    ) -> Self {
300        Self::Full(
301            NonNegativeLengthPercentage::new(top).into(),
302            NonNegativeLengthPercentage::new(right).into(),
303            NonNegativeLengthPercentage::new(bottom).into(),
304            NonNegativeLengthPercentage::new(left).into(),
305        )
306    }
307
308    /// Construct equal calculated padding on all four edges.
309    pub fn calculated(expression: impl Into<CssDimensionExpr>) -> Self {
310        Self::All(LengthPercentageCalculation::new(expression).into())
311    }
312}
313
314macro_rules! axis_shorthand {
315    ($(#[$meta:meta])* $name:ident, $value:ty) => {
316        $(#[$meta])*
317        #[derive(Clone, Debug, PartialEq)]
318        #[non_exhaustive]
319        pub enum $name {
320            /// One value for both the start and end edges.
321            One($value),
322            /// Separate start-edge and end-edge values.
323            StartEnd($value, $value),
324        }
325
326        impl CssWriteTo for $name {
327            fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
328                match self {
329                    Self::One(value) => value.css_fmt(w),
330                    Self::StartEnd(start, end) => {
331                        start.css_fmt(w)?;
332                        w.write_char(' ')?;
333                        end.css_fmt(w)
334                    }
335                }
336            }
337        }
338    };
339}
340
341axis_shorthand!(
342    /// Values for the `padding-block` and `padding-inline` shorthands.
343    PaddingAxis,
344    NonNegativeLengthPercentageValue
345);
346
347impl PaddingAxis {
348    /// Construct equal direct padding on both axis edges.
349    pub fn one(value: CssDimension) -> Self {
350        Self::One(NonNegativeLengthPercentage::new(value).into())
351    }
352
353    /// Construct separate direct padding on the start and end edges.
354    pub fn start_end(start: CssDimension, end: CssDimension) -> Self {
355        Self::StartEnd(
356            NonNegativeLengthPercentage::new(start).into(),
357            NonNegativeLengthPercentage::new(end).into(),
358        )
359    }
360
361    /// Construct equal calculated padding on both axis edges.
362    pub fn calculated(expression: impl Into<CssDimensionExpr>) -> Self {
363        Self::One(LengthPercentageCalculation::new(expression).into())
364    }
365}
366
367axis_shorthand!(
368    /// Values for the `margin-block` and `margin-inline` shorthands.
369    MarginAxis,
370    LengthPercentageAuto
371);
372
373axis_shorthand!(
374    /// Values for the `inset-block` and `inset-inline` shorthands.
375    InsetAxis,
376    LengthPercentageAuto
377);
378
379impl_checked_value!(
380    Margin,
381    Inset,
382    Padding,
383    PaddingAxis,
384    MarginAxis,
385    InsetAxis,
386    NonNegativeLengthPercentage,
387    NonNegativeLengthPercentageValue,
388    BorderCornerRadius,
389);