Skip to main content

eternal_styler/
properties.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//! The properties this crate understands, and how their values are parsed.
6
7use cssparser::Parser;
8
9use crate::error::StyleError;
10use crate::specified::{
11    self, BorderWidth, ColorValue, FontSize, LengthPercentage, LetterSpacing, LineHeight, MaxSize,
12    Size, parse_opacity,
13};
14use crate::values::{BorderStyle, FontFamily, FontStyle, TextAlign};
15
16macro_rules! longhands {
17    ($( $variant:ident: $name:literal, $ty:ty, inherited: $inherited:literal, parse: $parse:expr; )*) => {
18        /// Every longhand property. Shorthands expand to these when parsed,
19        /// so the cascade only ever deals with longhands.
20        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21        pub enum LonghandId {
22            $( #[doc = concat!("`", $name, "`")] $variant, )*
23        }
24
25        impl LonghandId {
26            pub const ALL: &'static [LonghandId] = &[ $( LonghandId::$variant, )* ];
27
28            /// The CSS name, such as `border-top-width`.
29            pub fn name(self) -> &'static str {
30                match self { $( Self::$variant => $name, )* }
31            }
32
33            /// Whether the property inherits from the parent by default.
34            pub fn is_inherited(self) -> bool {
35                match self { $( Self::$variant => $inherited, )* }
36            }
37
38            /// Looks a property up by its CSS name, ignoring ASCII case.
39            pub fn from_name(name: &str) -> Option<Self> {
40                cssparser::match_ignore_ascii_case! { name,
41                    $( $name => Some(Self::$variant), )*
42                    _ => None,
43                }
44            }
45
46            pub(crate) fn index(self) -> usize {
47                self as usize
48            }
49
50            fn parse_value<'i>(
51                self,
52                input: &mut Parser<'i, '_>,
53            ) -> Result<PropertyDeclaration, StyleError<'i>> {
54                match self {
55                    $( Self::$variant => $parse(input).map(PropertyDeclaration::$variant), )*
56                }
57            }
58        }
59
60        /// A parsed declaration: one longhand and its specified value.
61        #[derive(Clone, Debug, PartialEq)]
62        pub enum PropertyDeclaration {
63            $( #[doc = concat!("`", $name, "`")] $variant($ty), )*
64            /// `inherit`, `initial`, `unset` or `revert` for the given longhand.
65            CssWide(LonghandId, CssWideKeyword),
66        }
67
68        impl PropertyDeclaration {
69            pub fn id(&self) -> LonghandId {
70                match self {
71                    $( Self::$variant(_) => LonghandId::$variant, )*
72                    Self::CssWide(id, _) => *id,
73                }
74            }
75        }
76    };
77}
78
79longhands! {
80    // Dimensions
81    Width: "width", Size, inherited: false, parse: Size::parse_non_negative;
82    Height: "height", Size, inherited: false, parse: Size::parse_non_negative;
83    MinWidth: "min-width", Size, inherited: false, parse: Size::parse_non_negative;
84    MinHeight: "min-height", Size, inherited: false, parse: Size::parse_non_negative;
85    MaxWidth: "max-width", MaxSize, inherited: false, parse: MaxSize::parse;
86    MaxHeight: "max-height", MaxSize, inherited: false, parse: MaxSize::parse;
87    // Spacing
88    MarginTop: "margin-top", Size, inherited: false, parse: Size::parse;
89    MarginRight: "margin-right", Size, inherited: false, parse: Size::parse;
90    MarginBottom: "margin-bottom", Size, inherited: false, parse: Size::parse;
91    MarginLeft: "margin-left", Size, inherited: false, parse: Size::parse;
92    PaddingTop: "padding-top", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
93    PaddingRight: "padding-right", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
94    PaddingBottom: "padding-bottom", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
95    PaddingLeft: "padding-left", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
96    RowGap: "row-gap", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
97    ColumnGap: "column-gap", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
98    // Colours
99    Color: "color", ColorValue, inherited: true, parse: ColorValue::parse;
100    BackgroundColor: "background-color", ColorValue, inherited: false, parse: ColorValue::parse;
101    Opacity: "opacity", f32, inherited: false, parse: parse_opacity;
102    // Borders
103    BorderTopWidth: "border-top-width", BorderWidth, inherited: false, parse: BorderWidth::parse;
104    BorderRightWidth: "border-right-width", BorderWidth, inherited: false, parse: BorderWidth::parse;
105    BorderBottomWidth: "border-bottom-width", BorderWidth, inherited: false, parse: BorderWidth::parse;
106    BorderLeftWidth: "border-left-width", BorderWidth, inherited: false, parse: BorderWidth::parse;
107    BorderTopStyle: "border-top-style", BorderStyle, inherited: false, parse: BorderStyle::parse;
108    BorderRightStyle: "border-right-style", BorderStyle, inherited: false, parse: BorderStyle::parse;
109    BorderBottomStyle: "border-bottom-style", BorderStyle, inherited: false, parse: BorderStyle::parse;
110    BorderLeftStyle: "border-left-style", BorderStyle, inherited: false, parse: BorderStyle::parse;
111    BorderTopColor: "border-top-color", ColorValue, inherited: false, parse: ColorValue::parse;
112    BorderRightColor: "border-right-color", ColorValue, inherited: false, parse: ColorValue::parse;
113    BorderBottomColor: "border-bottom-color", ColorValue, inherited: false, parse: ColorValue::parse;
114    BorderLeftColor: "border-left-color", ColorValue, inherited: false, parse: ColorValue::parse;
115    BorderTopLeftRadius: "border-top-left-radius", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
116    BorderTopRightRadius: "border-top-right-radius", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
117    BorderBottomRightRadius: "border-bottom-right-radius", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
118    BorderBottomLeftRadius: "border-bottom-left-radius", LengthPercentage, inherited: false, parse: LengthPercentage::parse_non_negative;
119    // Typography
120    FontFamily: "font-family", FontFamily, inherited: true, parse: FontFamily::parse;
121    FontSize: "font-size", FontSize, inherited: true, parse: FontSize::parse;
122    FontWeight: "font-weight", specified::FontWeight, inherited: true, parse: specified::FontWeight::parse;
123    FontStyle: "font-style", FontStyle, inherited: true, parse: FontStyle::parse;
124    LineHeight: "line-height", LineHeight, inherited: true, parse: LineHeight::parse;
125    LetterSpacing: "letter-spacing", LetterSpacing, inherited: true, parse: LetterSpacing::parse;
126    TextAlign: "text-align", TextAlign, inherited: true, parse: TextAlign::parse;
127}
128
129/// The number of longhands, for tables indexed by [`LonghandId::index`].
130pub(crate) const LONGHAND_COUNT: usize = LonghandId::ALL.len();
131
132/// A shorthand property: a single declaration that sets several longhands.
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134pub enum ShorthandId {
135    /// `margin`: one to four values, top, right, bottom, left.
136    Margin,
137    /// `padding`: one to four values.
138    Padding,
139    /// `gap`: row gap, then an optional column gap.
140    Gap,
141    /// `border`: any of a width, a style and a colour, in any order, for all
142    /// four sides.
143    Border,
144    /// `border-top`: like `border` for one side.
145    BorderTop,
146    BorderRight,
147    BorderBottom,
148    BorderLeft,
149    /// `border-width`: one to four values.
150    BorderWidth,
151    /// `border-style`: one to four values.
152    BorderStyle,
153    /// `border-color`: one to four values.
154    BorderColor,
155    /// `border-radius`: one to four values, top-left, top-right,
156    /// bottom-right, bottom-left. Elliptical corners (`a / b`) are not
157    /// supported.
158    BorderRadius,
159}
160
161impl ShorthandId {
162    pub const ALL: &'static [ShorthandId] = &[
163        Self::Margin,
164        Self::Padding,
165        Self::Gap,
166        Self::Border,
167        Self::BorderTop,
168        Self::BorderRight,
169        Self::BorderBottom,
170        Self::BorderLeft,
171        Self::BorderWidth,
172        Self::BorderStyle,
173        Self::BorderColor,
174        Self::BorderRadius,
175    ];
176
177    pub fn name(self) -> &'static str {
178        match self {
179            Self::Margin => "margin",
180            Self::Padding => "padding",
181            Self::Gap => "gap",
182            Self::Border => "border",
183            Self::BorderTop => "border-top",
184            Self::BorderRight => "border-right",
185            Self::BorderBottom => "border-bottom",
186            Self::BorderLeft => "border-left",
187            Self::BorderWidth => "border-width",
188            Self::BorderStyle => "border-style",
189            Self::BorderColor => "border-color",
190            Self::BorderRadius => "border-radius",
191        }
192    }
193
194    pub fn from_name(name: &str) -> Option<Self> {
195        cssparser::match_ignore_ascii_case! { name,
196            "margin" => Some(Self::Margin),
197            "padding" => Some(Self::Padding),
198            "gap" => Some(Self::Gap),
199            "border" => Some(Self::Border),
200            "border-top" => Some(Self::BorderTop),
201            "border-right" => Some(Self::BorderRight),
202            "border-bottom" => Some(Self::BorderBottom),
203            "border-left" => Some(Self::BorderLeft),
204            "border-width" => Some(Self::BorderWidth),
205            "border-style" => Some(Self::BorderStyle),
206            "border-color" => Some(Self::BorderColor),
207            "border-radius" => Some(Self::BorderRadius),
208            _ => None,
209        }
210    }
211
212    /// The longhands this shorthand sets.
213    pub fn longhands(self) -> &'static [LonghandId] {
214        use LonghandId::*;
215        match self {
216            Self::Margin => &[MarginTop, MarginRight, MarginBottom, MarginLeft],
217            Self::Padding => &[PaddingTop, PaddingRight, PaddingBottom, PaddingLeft],
218            Self::Gap => &[RowGap, ColumnGap],
219            Self::Border => &[
220                BorderTopWidth,
221                BorderRightWidth,
222                BorderBottomWidth,
223                BorderLeftWidth,
224                BorderTopStyle,
225                BorderRightStyle,
226                BorderBottomStyle,
227                BorderLeftStyle,
228                BorderTopColor,
229                BorderRightColor,
230                BorderBottomColor,
231                BorderLeftColor,
232            ],
233            Self::BorderTop => &[BorderTopWidth, BorderTopStyle, BorderTopColor],
234            Self::BorderRight => &[BorderRightWidth, BorderRightStyle, BorderRightColor],
235            Self::BorderBottom => &[BorderBottomWidth, BorderBottomStyle, BorderBottomColor],
236            Self::BorderLeft => &[BorderLeftWidth, BorderLeftStyle, BorderLeftColor],
237            Self::BorderWidth => &[
238                BorderTopWidth,
239                BorderRightWidth,
240                BorderBottomWidth,
241                BorderLeftWidth,
242            ],
243            Self::BorderStyle => &[
244                BorderTopStyle,
245                BorderRightStyle,
246                BorderBottomStyle,
247                BorderLeftStyle,
248            ],
249            Self::BorderColor => &[
250                BorderTopColor,
251                BorderRightColor,
252                BorderBottomColor,
253                BorderLeftColor,
254            ],
255            Self::BorderRadius => &[
256                BorderTopLeftRadius,
257                BorderTopRightRadius,
258                BorderBottomRightRadius,
259                BorderBottomLeftRadius,
260            ],
261        }
262    }
263
264    fn parse_into<'i>(
265        self,
266        input: &mut Parser<'i, '_>,
267        out: &mut Vec<PropertyDeclaration>,
268    ) -> Result<(), StyleError<'i>> {
269        use PropertyDeclaration as D;
270        match self {
271            Self::Margin => {
272                let [top, right, bottom, left] = parse_sides(input, Size::parse)?;
273                out.extend([
274                    D::MarginTop(top),
275                    D::MarginRight(right),
276                    D::MarginBottom(bottom),
277                    D::MarginLeft(left),
278                ]);
279            }
280            Self::Padding => {
281                let [top, right, bottom, left] =
282                    parse_sides(input, LengthPercentage::parse_non_negative)?;
283                out.extend([
284                    D::PaddingTop(top),
285                    D::PaddingRight(right),
286                    D::PaddingBottom(bottom),
287                    D::PaddingLeft(left),
288                ]);
289            }
290            Self::Gap => {
291                let row = LengthPercentage::parse_non_negative(input)?;
292                let column = input
293                    .try_parse(LengthPercentage::parse_non_negative)
294                    .unwrap_or(row);
295                out.extend([D::RowGap(row), D::ColumnGap(column)]);
296            }
297            Self::Border => {
298                let (width, style, color) = parse_border(input)?;
299                out.extend([
300                    D::BorderTopWidth(width),
301                    D::BorderRightWidth(width),
302                    D::BorderBottomWidth(width),
303                    D::BorderLeftWidth(width),
304                    D::BorderTopStyle(style),
305                    D::BorderRightStyle(style),
306                    D::BorderBottomStyle(style),
307                    D::BorderLeftStyle(style),
308                    D::BorderTopColor(color),
309                    D::BorderRightColor(color),
310                    D::BorderBottomColor(color),
311                    D::BorderLeftColor(color),
312                ]);
313            }
314            Self::BorderTop => {
315                let (width, style, color) = parse_border(input)?;
316                out.extend([
317                    D::BorderTopWidth(width),
318                    D::BorderTopStyle(style),
319                    D::BorderTopColor(color),
320                ]);
321            }
322            Self::BorderRight => {
323                let (width, style, color) = parse_border(input)?;
324                out.extend([
325                    D::BorderRightWidth(width),
326                    D::BorderRightStyle(style),
327                    D::BorderRightColor(color),
328                ]);
329            }
330            Self::BorderBottom => {
331                let (width, style, color) = parse_border(input)?;
332                out.extend([
333                    D::BorderBottomWidth(width),
334                    D::BorderBottomStyle(style),
335                    D::BorderBottomColor(color),
336                ]);
337            }
338            Self::BorderLeft => {
339                let (width, style, color) = parse_border(input)?;
340                out.extend([
341                    D::BorderLeftWidth(width),
342                    D::BorderLeftStyle(style),
343                    D::BorderLeftColor(color),
344                ]);
345            }
346            Self::BorderWidth => {
347                let [top, right, bottom, left] = parse_sides(input, BorderWidth::parse)?;
348                out.extend([
349                    D::BorderTopWidth(top),
350                    D::BorderRightWidth(right),
351                    D::BorderBottomWidth(bottom),
352                    D::BorderLeftWidth(left),
353                ]);
354            }
355            Self::BorderStyle => {
356                let [top, right, bottom, left] = parse_sides(input, BorderStyle::parse)?;
357                out.extend([
358                    D::BorderTopStyle(top),
359                    D::BorderRightStyle(right),
360                    D::BorderBottomStyle(bottom),
361                    D::BorderLeftStyle(left),
362                ]);
363            }
364            Self::BorderColor => {
365                let [top, right, bottom, left] = parse_sides(input, ColorValue::parse)?;
366                out.extend([
367                    D::BorderTopColor(top),
368                    D::BorderRightColor(right),
369                    D::BorderBottomColor(bottom),
370                    D::BorderLeftColor(left),
371                ]);
372            }
373            Self::BorderRadius => {
374                let [top_left, top_right, bottom_right, bottom_left] =
375                    parse_sides(input, LengthPercentage::parse_non_negative)?;
376                out.extend([
377                    D::BorderTopLeftRadius(top_left),
378                    D::BorderTopRightRadius(top_right),
379                    D::BorderBottomRightRadius(bottom_right),
380                    D::BorderBottomLeftRadius(bottom_left),
381                ]);
382            }
383        }
384        Ok(())
385    }
386}
387
388/// Parses one to four values and spreads them over four sides the way
389/// `margin` and friends do.
390fn parse_sides<'i, T: Copy>(
391    input: &mut Parser<'i, '_>,
392    parse: fn(&mut Parser<'i, '_>) -> Result<T, StyleError<'i>>,
393) -> Result<[T; 4], StyleError<'i>> {
394    let first = parse(input)?;
395    let Ok(second) = input.try_parse(parse) else {
396        return Ok([first; 4]);
397    };
398    let Ok(third) = input.try_parse(parse) else {
399        return Ok([first, second, first, second]);
400    };
401    let Ok(fourth) = input.try_parse(parse) else {
402        return Ok([first, second, third, second]);
403    };
404    Ok([first, second, third, fourth])
405}
406
407/// Parses `<width> || <style> || <color>`, at least one of them, in any
408/// order. Whatever is missing takes its initial value.
409fn parse_border<'i>(
410    input: &mut Parser<'i, '_>,
411) -> Result<(BorderWidth, BorderStyle, ColorValue), StyleError<'i>> {
412    let mut width = None;
413    let mut style = None;
414    let mut color = None;
415    loop {
416        if width.is_none()
417            && let Ok(value) = input.try_parse(BorderWidth::parse)
418        {
419            width = Some(value);
420            continue;
421        }
422        if style.is_none()
423            && let Ok(value) = input.try_parse(BorderStyle::parse)
424        {
425            style = Some(value);
426            continue;
427        }
428        if color.is_none()
429            && let Ok(value) = input.try_parse(ColorValue::parse)
430        {
431            color = Some(value);
432            continue;
433        }
434        break;
435    }
436    if width.is_none() && style.is_none() && color.is_none() {
437        return Err(input.new_error_for_next_token());
438    }
439    Ok((
440        width.unwrap_or(BorderWidth::Medium),
441        style.unwrap_or(BorderStyle::None),
442        color.unwrap_or(ColorValue::CurrentColor),
443    ))
444}
445
446/// Any property name this crate accepts.
447#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
448pub enum PropertyId {
449    Longhand(LonghandId),
450    Shorthand(ShorthandId),
451}
452
453impl PropertyId {
454    pub fn from_name(name: &str) -> Option<Self> {
455        LonghandId::from_name(name)
456            .map(Self::Longhand)
457            .or_else(|| ShorthandId::from_name(name).map(Self::Shorthand))
458    }
459
460    pub fn name(self) -> &'static str {
461        match self {
462            Self::Longhand(id) => id.name(),
463            Self::Shorthand(id) => id.name(),
464        }
465    }
466
467    /// The longhands a declaration of this property sets.
468    pub fn longhands(self) -> &'static [LonghandId] {
469        match self {
470            Self::Longhand(id) => std::slice::from_ref(longhand_ref(id)),
471            Self::Shorthand(id) => id.longhands(),
472        }
473    }
474}
475
476fn longhand_ref(id: LonghandId) -> &'static LonghandId {
477    &LonghandId::ALL[id.index()]
478}
479
480/// The keywords every property accepts in place of a value.
481#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
482pub enum CssWideKeyword {
483    /// The property's initial value.
484    Initial,
485    /// The parent's computed value, whether or not the property inherits by
486    /// default.
487    Inherit,
488    /// `inherit` for inherited properties, `initial` for the rest.
489    Unset,
490    /// Treated as `unset`: there is no user-agent stylesheet to revert to.
491    Revert,
492}
493
494impl CssWideKeyword {
495    fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
496        input.skip_whitespace();
497        let location = input.current_source_location();
498        let ident = input.expect_ident()?;
499        cssparser::match_ignore_ascii_case! { ident,
500            "initial" => Ok(Self::Initial),
501            "inherit" => Ok(Self::Inherit),
502            "unset" => Ok(Self::Unset),
503            "revert" => Ok(Self::Revert),
504            _ => Err(location.new_unexpected_token_error(cssparser::Token::Ident(ident.clone()))),
505        }
506    }
507
508    /// What the keyword means for a property that does or does not inherit.
509    pub(crate) fn resolve(self, inherited: bool) -> Resolution {
510        match self {
511            Self::Initial => Resolution::Initial,
512            Self::Inherit => Resolution::Inherit,
513            Self::Unset | Self::Revert if inherited => Resolution::Inherit,
514            Self::Unset | Self::Revert => Resolution::Initial,
515        }
516    }
517}
518
519#[derive(Clone, Copy, Debug, PartialEq, Eq)]
520pub(crate) enum Resolution {
521    Initial,
522    Inherit,
523}
524
525/// Parses the value of `id` and appends the resulting longhand declarations
526/// to `out`. Does not check that the input is exhausted afterwards.
527pub(crate) fn parse_property_value<'i>(
528    id: PropertyId,
529    input: &mut Parser<'i, '_>,
530    out: &mut Vec<PropertyDeclaration>,
531) -> Result<(), StyleError<'i>> {
532    if let Ok(keyword) = input.try_parse(CssWideKeyword::parse) {
533        out.extend(
534            id.longhands()
535                .iter()
536                .map(|&longhand| PropertyDeclaration::CssWide(longhand, keyword)),
537        );
538        return Ok(());
539    }
540    match id {
541        PropertyId::Longhand(id) => out.push(id.parse_value(input)?),
542        PropertyId::Shorthand(id) => id.parse_into(input, out)?,
543    }
544    Ok(())
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550    use crate::specified::Length;
551    use cssparser::ParserInput;
552
553    fn parse(property: &str, css: &str) -> Result<Vec<PropertyDeclaration>, String> {
554        let id = PropertyId::from_name(property).expect("known property");
555        let mut input = ParserInput::new(css);
556        let mut parser = Parser::new(&mut input);
557        let mut out = Vec::new();
558        parser
559            .parse_entirely(|input| parse_property_value(id, input, &mut out))
560            .map_err(|e| crate::Error::from_parse_error(e).to_string())?;
561        Ok(out)
562    }
563
564    fn px(v: f32) -> LengthPercentage {
565        LengthPercentage::Length(Length::Px(v))
566    }
567
568    #[test]
569    fn every_name_round_trips() {
570        for &id in LonghandId::ALL {
571            assert_eq!(LonghandId::from_name(id.name()), Some(id));
572            assert_eq!(
573                LonghandId::from_name(&id.name().to_ascii_uppercase()),
574                Some(id)
575            );
576            assert!(ShorthandId::from_name(id.name()).is_none());
577        }
578        for &id in ShorthandId::ALL {
579            assert_eq!(ShorthandId::from_name(id.name()), Some(id));
580            assert!(LonghandId::from_name(id.name()).is_none());
581            assert!(!id.longhands().is_empty());
582        }
583        assert_eq!(PropertyId::from_name("colour"), None);
584        assert_eq!(LONGHAND_COUNT, LonghandId::ALL.len());
585        for (index, &id) in LonghandId::ALL.iter().enumerate() {
586            assert_eq!(id.index(), index);
587        }
588    }
589
590    #[test]
591    fn sides_spread_like_css() {
592        use PropertyDeclaration as D;
593        assert_eq!(
594            parse("padding", "1px").unwrap(),
595            [
596                D::PaddingTop(px(1.0)),
597                D::PaddingRight(px(1.0)),
598                D::PaddingBottom(px(1.0)),
599                D::PaddingLeft(px(1.0)),
600            ]
601        );
602        assert_eq!(
603            parse("padding", "1px 2px").unwrap(),
604            [
605                D::PaddingTop(px(1.0)),
606                D::PaddingRight(px(2.0)),
607                D::PaddingBottom(px(1.0)),
608                D::PaddingLeft(px(2.0)),
609            ]
610        );
611        assert_eq!(
612            parse("padding", "1px 2px 3px").unwrap(),
613            [
614                D::PaddingTop(px(1.0)),
615                D::PaddingRight(px(2.0)),
616                D::PaddingBottom(px(3.0)),
617                D::PaddingLeft(px(2.0)),
618            ]
619        );
620        assert_eq!(
621            parse("padding", "1px 2px 3px 4px").unwrap(),
622            [
623                D::PaddingTop(px(1.0)),
624                D::PaddingRight(px(2.0)),
625                D::PaddingBottom(px(3.0)),
626                D::PaddingLeft(px(4.0)),
627            ]
628        );
629        assert!(parse("padding", "1px 2px 3px 4px 5px").is_err());
630        assert!(parse("padding", "-1px").is_err());
631        assert_eq!(
632            parse("margin", "-1px auto").unwrap()[1],
633            D::MarginRight(Size::Auto)
634        );
635        assert_eq!(
636            parse("gap", "4px").unwrap(),
637            [D::RowGap(px(4.0)), D::ColumnGap(px(4.0))]
638        );
639        assert_eq!(
640            parse("gap", "4px 8px").unwrap(),
641            [D::RowGap(px(4.0)), D::ColumnGap(px(8.0))]
642        );
643    }
644
645    #[test]
646    fn border_takes_its_parts_in_any_order() {
647        use PropertyDeclaration as D;
648        let red = ColorValue::Color(crate::Color::from_rgba8(255, 0, 0, 255));
649        let decls = parse("border-top", "red 2px solid").unwrap();
650        assert_eq!(
651            decls,
652            [
653                D::BorderTopWidth(BorderWidth::Length(Length::Px(2.0))),
654                D::BorderTopStyle(BorderStyle::Solid),
655                D::BorderTopColor(red),
656            ]
657        );
658        let decls = parse("border-left", "dashed").unwrap();
659        assert_eq!(
660            decls,
661            [
662                D::BorderLeftWidth(BorderWidth::Medium),
663                D::BorderLeftStyle(BorderStyle::Dashed),
664                D::BorderLeftColor(ColorValue::CurrentColor),
665            ]
666        );
667        assert_eq!(parse("border", "thin solid").unwrap().len(), 12);
668        assert!(parse("border", "").is_err());
669        assert!(parse("border", "solid solid").is_err());
670        assert!(parse("border", "2px 3px").is_err());
671    }
672
673    #[test]
674    fn css_wide_keywords_expand_to_every_longhand() {
675        let decls = parse("border", "inherit").unwrap();
676        assert_eq!(decls.len(), 12);
677        assert!(
678            decls
679                .iter()
680                .all(|d| matches!(d, PropertyDeclaration::CssWide(_, CssWideKeyword::Inherit)))
681        );
682        assert_eq!(
683            parse("color", "UNSET").unwrap(),
684            [PropertyDeclaration::CssWide(
685                LonghandId::Color,
686                CssWideKeyword::Unset
687            )]
688        );
689        assert!(parse("color", "inherit red").is_err());
690    }
691}