Skip to main content

eternal_styler/
specified.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//! Values as written in a stylesheet, before the cascade resolves them.
6//!
7//! These are what [`PropertyDeclaration`](crate::PropertyDeclaration) carries.
8//! Relative units (`em`, `rem`, percentages of the parent's font size) and
9//! keywords such as `currentcolor` or `bolder` survive here and are only
10//! resolved when a [`ComputedStyle`](crate::ComputedStyle) is built.
11
12use cssparser::{Parser, Token};
13use cssparser_color::{ColorParser, FromParsedColor, parse_color_with};
14
15use crate::error::{StyleError, StyleParseErrorKind};
16use crate::values::{BorderStyle, Color, FontFamily, FontStyle, TextAlign};
17
18/// Matches an identifier against keywords, ASCII case-insensitively, and
19/// fails with an "unexpected token" error at the identifier otherwise.
20macro_rules! keyword {
21    ($input:expr, { $( $name:literal => $value:expr ),+ $(,)? }) => {{
22        $input.skip_whitespace();
23        let location = $input.current_source_location();
24        let ident = $input.expect_ident()?;
25        cssparser::match_ignore_ascii_case! { ident,
26            $( $name => Ok($value), )+
27            _ => Err(location.new_unexpected_token_error(Token::Ident(ident.clone()))),
28        }
29    }};
30}
31
32/// A length with its unit still attached, so that `em` and `rem` can be
33/// resolved against the right font size later. Absolute units other than
34/// `px` are converted to pixels when parsed.
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub enum Length {
37    Px(f32),
38    /// Relative to the element's font size (the parent's, for `font-size`
39    /// itself).
40    Em(f32),
41    /// Relative to the root font size, see
42    /// [`Styler::set_root_font_size`](crate::Styler::set_root_font_size).
43    Rem(f32),
44}
45
46impl Length {
47    pub const ZERO: Length = Length::Px(0.0);
48
49    pub(crate) fn to_px(self, font_size: f32, root_font_size: f32) -> f32 {
50        match self {
51            Self::Px(px) => px,
52            Self::Em(em) => em * font_size,
53            Self::Rem(rem) => rem * root_font_size,
54        }
55    }
56
57    fn from_dimension(value: f32, unit: &str) -> Option<Self> {
58        Some(cssparser::match_ignore_ascii_case! { unit,
59            "px" => Self::Px(value),
60            "em" => Self::Em(value),
61            "rem" => Self::Rem(value),
62            "pt" => Self::Px(value * 96.0 / 72.0),
63            "pc" => Self::Px(value * 16.0),
64            "in" => Self::Px(value * 96.0),
65            "cm" => Self::Px(value * 96.0 / 2.54),
66            "mm" => Self::Px(value * 96.0 / 25.4),
67            "q" => Self::Px(value * 96.0 / 101.6),
68            _ => return None,
69        })
70    }
71
72    fn value(self) -> f32 {
73        match self {
74            Self::Px(v) | Self::Em(v) | Self::Rem(v) => v,
75        }
76    }
77
78    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
79        input.skip_whitespace();
80        let location = input.current_source_location();
81        let token = input.next()?.clone();
82        let length = match &token {
83            Token::Dimension { value, unit, .. } => Self::from_dimension(*value, unit),
84            Token::Number { value, .. } if *value == 0.0 => Some(Self::ZERO),
85            _ => None,
86        };
87        length.ok_or_else(|| location.new_unexpected_token_error(token))
88    }
89
90    pub(crate) fn parse_non_negative<'i>(
91        input: &mut Parser<'i, '_>,
92    ) -> Result<Self, StyleError<'i>> {
93        input.skip_whitespace();
94        let location = input.current_source_location();
95        let length = Self::parse(input)?;
96        if length.value() < 0.0 {
97            return Err(location.new_custom_error(StyleParseErrorKind::NegativeValue));
98        }
99        Ok(length)
100    }
101}
102
103/// A length or a percentage.
104#[derive(Clone, Copy, Debug, PartialEq)]
105pub enum LengthPercentage {
106    Length(Length),
107    /// A fraction, so `50%` is `Percent(0.5)`.
108    Percent(f32),
109}
110
111impl LengthPercentage {
112    fn value(self) -> f32 {
113        match self {
114            Self::Length(length) => length.value(),
115            Self::Percent(p) => p,
116        }
117    }
118
119    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
120        if let Ok(unit_value) = input.try_parse(|input| input.expect_percentage()) {
121            return Ok(Self::Percent(unit_value));
122        }
123        Length::parse(input).map(Self::Length)
124    }
125
126    pub(crate) fn parse_non_negative<'i>(
127        input: &mut Parser<'i, '_>,
128    ) -> Result<Self, StyleError<'i>> {
129        input.skip_whitespace();
130        let location = input.current_source_location();
131        let value = Self::parse(input)?;
132        if value.value() < 0.0 {
133            return Err(location.new_custom_error(StyleParseErrorKind::NegativeValue));
134        }
135        Ok(value)
136    }
137}
138
139/// `auto` or a length or percentage: `width`, `height`, `min-*` and the
140/// margins.
141#[derive(Clone, Copy, Debug, PartialEq)]
142pub enum Size {
143    Auto,
144    LengthPercentage(LengthPercentage),
145}
146
147impl Size {
148    fn parse_with<'i>(
149        input: &mut Parser<'i, '_>,
150        parse: fn(&mut Parser<'i, '_>) -> Result<LengthPercentage, StyleError<'i>>,
151    ) -> Result<Self, StyleError<'i>> {
152        if input
153            .try_parse(|input| input.expect_ident_matching("auto"))
154            .is_ok()
155        {
156            return Ok(Self::Auto);
157        }
158        parse(input).map(Self::LengthPercentage)
159    }
160
161    /// For margins, which may be negative.
162    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
163        Self::parse_with(input, LengthPercentage::parse)
164    }
165
166    /// For sizes, which may not.
167    pub(crate) fn parse_non_negative<'i>(
168        input: &mut Parser<'i, '_>,
169    ) -> Result<Self, StyleError<'i>> {
170        Self::parse_with(input, LengthPercentage::parse_non_negative)
171    }
172}
173
174/// `none` or a length or percentage: `max-width` and `max-height`.
175#[derive(Clone, Copy, Debug, PartialEq)]
176pub enum MaxSize {
177    None,
178    LengthPercentage(LengthPercentage),
179}
180
181impl MaxSize {
182    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
183        if input
184            .try_parse(|input| input.expect_ident_matching("none"))
185            .is_ok()
186        {
187            return Ok(Self::None);
188        }
189        LengthPercentage::parse_non_negative(input).map(Self::LengthPercentage)
190    }
191}
192
193/// A colour, or `currentcolor`.
194#[derive(Clone, Copy, Debug, PartialEq)]
195pub enum ColorValue {
196    CurrentColor,
197    Color(Color),
198}
199
200impl ColorValue {
201    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
202        input.skip_whitespace();
203        let location = input.current_source_location();
204        match parse_color_with(&ColorParserImpl, input)? {
205            ParsedColor::Value(value) => Ok(value),
206            ParsedColor::Unsupported(space) => {
207                Err(location.new_custom_error(StyleParseErrorKind::UnsupportedColorSpace(space)))
208            }
209        }
210    }
211}
212
213/// What `cssparser-color` hands back. Colour spaces this crate cannot convert
214/// to sRGB are reported rather than silently mangled.
215enum ParsedColor {
216    Value(ColorValue),
217    Unsupported(&'static str),
218}
219
220impl ParsedColor {
221    fn color(color: Color) -> Self {
222        Self::Value(ColorValue::Color(color))
223    }
224}
225
226impl FromParsedColor for ParsedColor {
227    fn from_current_color() -> Self {
228        Self::Value(ColorValue::CurrentColor)
229    }
230
231    fn from_rgba(red: u8, green: u8, blue: u8, alpha: f32) -> Self {
232        Self::color(Color::from_rgba8(red, green, blue, 255).with_alpha(alpha))
233    }
234
235    fn from_hsl(
236        hue: Option<f32>,
237        saturation: Option<f32>,
238        lightness: Option<f32>,
239        alpha: Option<f32>,
240    ) -> Self {
241        Self::color(Color::from_hsl(
242            hue.unwrap_or(0.0),
243            saturation.unwrap_or(0.0),
244            lightness.unwrap_or(0.0),
245            alpha.unwrap_or(1.0),
246        ))
247    }
248
249    fn from_hwb(
250        hue: Option<f32>,
251        whiteness: Option<f32>,
252        blackness: Option<f32>,
253        alpha: Option<f32>,
254    ) -> Self {
255        Self::color(Color::from_hwb(
256            hue.unwrap_or(0.0),
257            whiteness.unwrap_or(0.0),
258            blackness.unwrap_or(0.0),
259            alpha.unwrap_or(1.0),
260        ))
261    }
262
263    fn from_lab(
264        lightness: Option<f32>,
265        a: Option<f32>,
266        b: Option<f32>,
267        alpha: Option<f32>,
268    ) -> Self {
269        Self::color(Color::from_lab(
270            lightness.unwrap_or(0.0),
271            a.unwrap_or(0.0),
272            b.unwrap_or(0.0),
273            alpha.unwrap_or(1.0),
274        ))
275    }
276
277    fn from_lch(
278        lightness: Option<f32>,
279        chroma: Option<f32>,
280        hue: Option<f32>,
281        alpha: Option<f32>,
282    ) -> Self {
283        Self::color(Color::from_lch(
284            lightness.unwrap_or(0.0),
285            chroma.unwrap_or(0.0),
286            hue.unwrap_or(0.0),
287            alpha.unwrap_or(1.0),
288        ))
289    }
290
291    fn from_oklab(
292        lightness: Option<f32>,
293        a: Option<f32>,
294        b: Option<f32>,
295        alpha: Option<f32>,
296    ) -> Self {
297        Self::color(Color::from_oklab(
298            lightness.unwrap_or(0.0),
299            a.unwrap_or(0.0),
300            b.unwrap_or(0.0),
301            alpha.unwrap_or(1.0),
302        ))
303    }
304
305    fn from_oklch(
306        lightness: Option<f32>,
307        chroma: Option<f32>,
308        hue: Option<f32>,
309        alpha: Option<f32>,
310    ) -> Self {
311        Self::color(Color::from_oklch(
312            lightness.unwrap_or(0.0),
313            chroma.unwrap_or(0.0),
314            hue.unwrap_or(0.0),
315            alpha.unwrap_or(1.0),
316        ))
317    }
318
319    fn from_color_function(
320        color_space: cssparser::color::PredefinedColorSpace,
321        c1: Option<f32>,
322        c2: Option<f32>,
323        c3: Option<f32>,
324        alpha: Option<f32>,
325    ) -> Self {
326        use cssparser::color::PredefinedColorSpace::*;
327        let (c1, c2, c3) = (c1.unwrap_or(0.0), c2.unwrap_or(0.0), c3.unwrap_or(0.0));
328        let alpha = alpha.unwrap_or(1.0);
329        match color_space {
330            Srgb => Self::color(Color::rgba(
331                c1.clamp(0.0, 1.0),
332                c2.clamp(0.0, 1.0),
333                c3.clamp(0.0, 1.0),
334                alpha,
335            )),
336            SrgbLinear => Self::color(Color::from_linear_srgb(c1, c2, c3, alpha)),
337            DisplayP3 => Self::color(Color::from_display_p3(c1, c2, c3, alpha)),
338            DisplayP3Linear => Self::Unsupported("display-p3-linear"),
339            A98Rgb => Self::Unsupported("a98-rgb"),
340            ProphotoRgb => Self::Unsupported("prophoto-rgb"),
341            Rec2020 => Self::Unsupported("rec2020"),
342            XyzD50 => Self::Unsupported("xyz-d50"),
343            XyzD65 => Self::Unsupported("xyz-d65"),
344        }
345    }
346}
347
348struct ColorParserImpl;
349
350impl<'i> ColorParser<'i> for ColorParserImpl {
351    type Output = ParsedColor;
352    type Error = StyleParseErrorKind<'i>;
353}
354
355/// A border width: a keyword or a length.
356#[derive(Clone, Copy, Debug, PartialEq)]
357pub enum BorderWidth {
358    /// 1px
359    Thin,
360    /// 3px
361    Medium,
362    /// 5px
363    Thick,
364    Length(Length),
365}
366
367impl BorderWidth {
368    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
369        if let Ok(keyword) = input.try_parse(|input| -> Result<Self, StyleError<'i>> {
370            keyword!(input, {
371                "thin" => Self::Thin,
372                "medium" => Self::Medium,
373                "thick" => Self::Thick,
374            })
375        }) {
376            return Ok(keyword);
377        }
378        Length::parse_non_negative(input).map(Self::Length)
379    }
380}
381
382impl BorderStyle {
383    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
384        keyword!(input, {
385            "none" => Self::None,
386            "hidden" => Self::Hidden,
387            "solid" => Self::Solid,
388            "dashed" => Self::Dashed,
389            "dotted" => Self::Dotted,
390            "double" => Self::Double,
391        })
392    }
393}
394
395/// The absolute `font-size` keywords, on the usual scale where `medium` is
396/// 16px.
397#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
398pub enum FontSizeKeyword {
399    XxSmall,
400    XSmall,
401    Small,
402    Medium,
403    Large,
404    XLarge,
405    XxLarge,
406    XxxLarge,
407}
408
409impl FontSizeKeyword {
410    pub fn to_px(self) -> f32 {
411        match self {
412            Self::XxSmall => 9.0,
413            Self::XSmall => 10.0,
414            Self::Small => 13.0,
415            Self::Medium => 16.0,
416            Self::Large => 18.0,
417            Self::XLarge => 24.0,
418            Self::XxLarge => 32.0,
419            Self::XxxLarge => 48.0,
420        }
421    }
422}
423
424#[derive(Clone, Copy, Debug, PartialEq)]
425pub enum FontSize {
426    Length(Length),
427    /// A fraction of the parent's font size.
428    Percent(f32),
429    Keyword(FontSizeKeyword),
430    /// 1.2 times the parent's font size.
431    Larger,
432    /// The parent's font size divided by 1.2.
433    Smaller,
434}
435
436impl FontSize {
437    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
438        if let Ok(keyword) = input.try_parse(|input| -> Result<Self, StyleError<'i>> {
439            keyword!(input, {
440                "xx-small" => Self::Keyword(FontSizeKeyword::XxSmall),
441                "x-small" => Self::Keyword(FontSizeKeyword::XSmall),
442                "small" => Self::Keyword(FontSizeKeyword::Small),
443                "medium" => Self::Keyword(FontSizeKeyword::Medium),
444                "large" => Self::Keyword(FontSizeKeyword::Large),
445                "x-large" => Self::Keyword(FontSizeKeyword::XLarge),
446                "xx-large" => Self::Keyword(FontSizeKeyword::XxLarge),
447                "xxx-large" => Self::Keyword(FontSizeKeyword::XxxLarge),
448                "larger" => Self::Larger,
449                "smaller" => Self::Smaller,
450            })
451        }) {
452            return Ok(keyword);
453        }
454        Ok(match LengthPercentage::parse_non_negative(input)? {
455            LengthPercentage::Length(length) => Self::Length(length),
456            LengthPercentage::Percent(p) => Self::Percent(p),
457        })
458    }
459}
460
461#[derive(Clone, Copy, Debug, PartialEq)]
462pub enum FontWeight {
463    /// 1 to 1000. `normal` is 400 and `bold` is 700.
464    Absolute(f32),
465    Bolder,
466    Lighter,
467}
468
469impl FontWeight {
470    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
471        if let Ok(keyword) = input.try_parse(|input| -> Result<Self, StyleError<'i>> {
472            keyword!(input, {
473                "normal" => Self::Absolute(400.0),
474                "bold" => Self::Absolute(700.0),
475                "bolder" => Self::Bolder,
476                "lighter" => Self::Lighter,
477            })
478        }) {
479            return Ok(keyword);
480        }
481        input.skip_whitespace();
482        let location = input.current_source_location();
483        let weight = input.expect_number()?;
484        if !(1.0..=1000.0).contains(&weight) {
485            return Err(location.new_custom_error(StyleParseErrorKind::OutOfRange));
486        }
487        Ok(Self::Absolute(weight))
488    }
489}
490
491impl FontStyle {
492    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
493        keyword!(input, {
494            "normal" => Self::Normal,
495            "italic" => Self::Italic,
496            "oblique" => Self::Oblique,
497        })
498    }
499}
500
501#[derive(Clone, Copy, Debug, PartialEq)]
502pub enum LineHeight {
503    Normal,
504    /// A multiple of the font size, inherited as the multiple.
505    Number(f32),
506    Length(Length),
507    /// A fraction of the font size, resolved to a length.
508    Percent(f32),
509}
510
511impl LineHeight {
512    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
513        if input
514            .try_parse(|input| input.expect_ident_matching("normal"))
515            .is_ok()
516        {
517            return Ok(Self::Normal);
518        }
519        input.skip_whitespace();
520        let location = input.current_source_location();
521        if let Ok(number) = input.try_parse(|input| input.expect_number()) {
522            if number < 0.0 {
523                return Err(location.new_custom_error(StyleParseErrorKind::NegativeValue));
524            }
525            return Ok(Self::Number(number));
526        }
527        Ok(match LengthPercentage::parse_non_negative(input)? {
528            LengthPercentage::Length(length) => Self::Length(length),
529            LengthPercentage::Percent(p) => Self::Percent(p),
530        })
531    }
532}
533
534#[derive(Clone, Copy, Debug, PartialEq)]
535pub enum LetterSpacing {
536    Normal,
537    Length(Length),
538}
539
540impl LetterSpacing {
541    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
542        if input
543            .try_parse(|input| input.expect_ident_matching("normal"))
544            .is_ok()
545        {
546            return Ok(Self::Normal);
547        }
548        Length::parse(input).map(Self::Length)
549    }
550}
551
552impl TextAlign {
553    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
554        keyword!(input, {
555            "start" => Self::Start,
556            "end" => Self::End,
557            "left" => Self::Left,
558            "right" => Self::Right,
559            "center" => Self::Center,
560            "justify" => Self::Justify,
561        })
562    }
563}
564
565impl FontFamily {
566    pub(crate) fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, StyleError<'i>> {
567        let names = input.parse_comma_separated(|input| {
568            if let Ok(name) = input.try_parse(|input| input.expect_string_cloned()) {
569                return Ok(name.to_string());
570            }
571            // An unquoted family is one or more identifiers: `Segoe UI`.
572            let mut name = input.expect_ident()?.to_string();
573            while let Ok(word) = input.try_parse(|input| input.expect_ident_cloned()) {
574                name.push(' ');
575                name.push_str(&word);
576            }
577            if is_generic_family(&name) {
578                name.make_ascii_lowercase();
579            }
580            Ok(name)
581        })?;
582        Ok(Self::new(names))
583    }
584}
585
586fn is_generic_family(name: &str) -> bool {
587    cssparser::match_ignore_ascii_case! { name,
588        "serif" | "sans-serif" | "monospace" | "cursive" | "fantasy" | "system-ui"
589        | "ui-serif" | "ui-sans-serif" | "ui-monospace" | "ui-rounded" | "emoji"
590        | "math" | "fangsong" => true,
591        _ => false,
592    }
593}
594
595/// `opacity`: a number or percentage, clamped to `0.0..=1.0`.
596pub(crate) fn parse_opacity<'i>(input: &mut Parser<'i, '_>) -> Result<f32, StyleError<'i>> {
597    input.skip_whitespace();
598    let location = input.current_source_location();
599    let value = match input.next()?.clone() {
600        Token::Number { value, .. } => value,
601        Token::Percentage { unit_value, .. } => unit_value,
602        token => return Err(location.new_unexpected_token_error(token)),
603    };
604    Ok(value.clamp(0.0, 1.0))
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use cssparser::ParserInput;
611
612    fn parse<T>(
613        css: &str,
614        parse: impl for<'i, 't> FnOnce(&mut Parser<'i, 't>) -> Result<T, StyleError<'i>>,
615    ) -> Result<T, String> {
616        let mut input = ParserInput::new(css);
617        let mut parser = Parser::new(&mut input);
618        parser
619            .parse_entirely(parse)
620            .map_err(|e| crate::Error::from_parse_error(e).to_string())
621    }
622
623    #[test]
624    fn lengths() {
625        assert_eq!(parse("12px", Length::parse), Ok(Length::Px(12.0)));
626        assert_eq!(parse("1.5em", Length::parse), Ok(Length::Em(1.5)));
627        assert_eq!(parse("2rem", Length::parse), Ok(Length::Rem(2.0)));
628        assert_eq!(parse("0", Length::parse), Ok(Length::Px(0.0)));
629        assert_eq!(parse("72pt", Length::parse), Ok(Length::Px(96.0)));
630        assert_eq!(parse("1in", Length::parse), Ok(Length::Px(96.0)));
631        assert!(parse("12", Length::parse).is_err());
632        assert!(parse("12vw", Length::parse).is_err());
633        assert!(parse("-1px", Length::parse_non_negative).is_err());
634        assert_eq!(parse("-1px", Length::parse), Ok(Length::Px(-1.0)));
635        assert_eq!(
636            parse("50%", LengthPercentage::parse),
637            Ok(LengthPercentage::Percent(0.5))
638        );
639        assert_eq!(parse("auto", Size::parse), Ok(Size::Auto));
640        assert_eq!(parse("none", MaxSize::parse), Ok(MaxSize::None));
641    }
642
643    #[test]
644    fn colors() {
645        let rgba8 = |css: &str| match parse(css, ColorValue::parse) {
646            Ok(ColorValue::Color(color)) => Ok(color.to_rgba8()),
647            Ok(ColorValue::CurrentColor) => Err("currentcolor".to_owned()),
648            Err(e) => Err(e),
649        };
650        assert_eq!(rgba8("#fff"), Ok([255, 255, 255, 255]));
651        assert_eq!(rgba8("#1a2b3c80"), Ok([0x1a, 0x2b, 0x3c, 0x80]));
652        assert_eq!(rgba8("rebeccapurple"), Ok([102, 51, 153, 255]));
653        assert_eq!(rgba8("Transparent"), Ok([0, 0, 0, 0]));
654        assert_eq!(rgba8("rgb(10 20 30 / 50%)"), Ok([10, 20, 30, 128]));
655        assert_eq!(rgba8("rgba(10, 20, 30, 0.5)"), Ok([10, 20, 30, 128]));
656        assert_eq!(rgba8("hsl(120 100% 50%)"), Ok([0, 255, 0, 255]));
657        assert_eq!(rgba8("hwb(0 0% 0%)"), Ok([255, 0, 0, 255]));
658        assert_eq!(rgba8("oklab(100% 0 0)"), Ok([255, 255, 255, 255]));
659        assert_eq!(rgba8("oklch(62.8% 0.2577 29.23)"), Ok([255, 0, 0, 255]));
660        assert_eq!(rgba8("lab(100% 0 0)"), Ok([255, 255, 255, 255]));
661        assert_eq!(rgba8("color(srgb 1 0 0)"), Ok([255, 0, 0, 255]));
662        assert_eq!(
663            rgba8("color(srgb-linear 1 0 0 / 0.5)"),
664            Ok([255, 0, 0, 128])
665        );
666        assert_eq!(rgba8("color(display-p3 1 1 1)"), Ok([255, 255, 255, 255]));
667        assert_eq!(
668            parse("currentColor", ColorValue::parse),
669            Ok(ColorValue::CurrentColor)
670        );
671        assert_eq!(
672            rgba8("color(rec2020 1 0 0)"),
673            Err("line 1, column 1: unsupported colour space 'rec2020'".to_owned())
674        );
675        assert!(rgba8("#12345").is_err());
676        assert!(rgba8("notacolour").is_err());
677    }
678
679    #[test]
680    fn typography() {
681        assert_eq!(
682            parse("bold", FontWeight::parse),
683            Ok(FontWeight::Absolute(700.0))
684        );
685        assert_eq!(
686            parse("550", FontWeight::parse),
687            Ok(FontWeight::Absolute(550.0))
688        );
689        assert!(parse("0", FontWeight::parse).is_err());
690        assert!(parse("1001", FontWeight::parse).is_err());
691        assert_eq!(
692            parse("x-large", FontSize::parse),
693            Ok(FontSize::Keyword(FontSizeKeyword::XLarge))
694        );
695        assert_eq!(parse("120%", FontSize::parse), Ok(FontSize::Percent(1.2)));
696        assert_eq!(parse("1.4", LineHeight::parse), Ok(LineHeight::Number(1.4)));
697        assert_eq!(parse("normal", LineHeight::parse), Ok(LineHeight::Normal));
698        assert!(parse("-1", LineHeight::parse).is_err());
699        assert_eq!(
700            parse("\"Segoe UI\", Inter Display, sans-serif", FontFamily::parse),
701            Ok(FontFamily::new(["Segoe UI", "Inter Display", "sans-serif"]))
702        );
703        assert_eq!(
704            parse("Sans-Serif", FontFamily::parse),
705            Ok(FontFamily::new(["sans-serif"]))
706        );
707        assert!(parse("", FontFamily::parse).is_err());
708        assert_eq!(parse("center", TextAlign::parse), Ok(TextAlign::Center));
709    }
710
711    #[test]
712    fn opacity_is_clamped() {
713        assert_eq!(parse("0.5", parse_opacity), Ok(0.5));
714        assert_eq!(parse("50%", parse_opacity), Ok(0.5));
715        assert_eq!(parse("7", parse_opacity), Ok(1.0));
716        assert_eq!(parse("-1", parse_opacity), Ok(0.0));
717        assert!(parse("1px", parse_opacity).is_err());
718    }
719}