Skip to main content

parsec_css/
supports.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! `@supports` and `CSS.supports()`, CSS Conditional Rules Level 5: a
5//! condition parsed and evaluated against what this crate parses. A
6//! declaration is supported when its value parses for its property, a
7//! `selector()` when Parsec's selector engine parses it, and
8//! `font-format()` and `font-tech()` when they name a format or
9//! technology the specs define.
10
11use crate::parser::{Bracket, ComponentValue};
12use crate::tokenizer::Token;
13
14/// The at-rules `at-rule()` says are supported: those this crate reads.
15const AT_RULES: &[&str] = &[
16    "media",
17    "supports",
18    "layer",
19    "import",
20    "container",
21    "scope",
22    "property",
23    "keyframes",
24    "counter-style",
25];
26
27const FORMATS: &[&str] = &[
28    "collection",
29    "embedded-opentype",
30    "opentype",
31    "svg",
32    "truetype",
33    "woff",
34    "woff2",
35];
36const TECHS: &[&str] = &[
37    "color-cbdt",
38    "color-colrv0",
39    "color-colrv1",
40    "color-sbix",
41    "color-svg",
42    "features-aat",
43    "features-graphite",
44    "features-opentype",
45    "incremental",
46    "palettes",
47    "variations",
48];
49
50/// How deep conditions may nest.
51const MAX_DEPTH: usize = 64;
52
53fn solid<'v, 'a>(values: &'v [ComponentValue<'a>]) -> Vec<&'v ComponentValue<'a>> {
54    values.iter().filter(|v| !v.is_whitespace()).collect()
55}
56
57fn word(v: Option<&&ComponentValue<'_>>, w: &str) -> bool {
58    matches!(v, Some(ComponentValue::Token(Token::Ident(s), _)) if s.eq_ignore_ascii_case(w))
59}
60
61/// Whether a `<supports-condition>` holds, or `None` if it doesn't parse,
62/// which makes an `@supports` rule invalid. `selector()` holds for a
63/// selector Parsec can match, which takes the default `cascade` feature;
64/// without it, `selector()` is always false.
65///
66/// ```
67/// use parsec_css::supports::supports;
68///
69/// let c = parsec_css::parse_component_values("(display: grid) and (not (color: nonsense))");
70/// assert_eq!(supports(&c), Some(true));
71/// let c = parsec_css::parse_component_values("(display: grid) or selector(a > b)");
72/// assert_eq!(supports(&c), Some(true));
73/// assert_eq!(supports(&parsec_css::parse_component_values("color: red")), None);
74/// ```
75pub fn supports(condition: &[ComponentValue<'_>]) -> Option<bool> {
76    condition_at(&solid(condition), 0)
77}
78
79/// `CSS.supports(property, value)`.
80pub fn supports_declaration(property: &str, value: &[ComponentValue<'_>]) -> bool {
81    crate::values::parse_value(property, value).is_ok()
82}
83
84/// `CSS.supports(conditionText)`: a condition, or a declaration without
85/// its parentheses.
86pub fn supports_text(css: &str) -> bool {
87    let values = crate::parse_component_values(css);
88    if let Some(r) = supports(&values) {
89        return r;
90    }
91    let wrapped = format!("({css})");
92    supports(&crate::parse_component_values(&wrapped)).unwrap_or(false)
93}
94
95fn condition_at(v: &[&ComponentValue<'_>], depth: usize) -> Option<bool> {
96    if depth > MAX_DEPTH || v.is_empty() {
97        return None;
98    }
99    if word(v.first(), "not") {
100        if v.len() != 2 {
101            return None;
102        }
103        return in_parens(v[1], depth).map(|b| !b);
104    }
105    let first = in_parens(v[0], depth)?;
106    if v.len() == 1 {
107        return Some(first);
108    }
109    let and = word(v.get(1), "and");
110    if !and && !word(v.get(1), "or") {
111        return None;
112    }
113    let joiner = if and { "and" } else { "or" };
114    let mut result = first;
115    let mut i = 1;
116    while i < v.len() {
117        if !word(v.get(i), joiner) {
118            return None;
119        }
120        let next = in_parens(v.get(i + 1)?, depth)?;
121        result = if and { result && next } else { result || next };
122        i += 2;
123    }
124    Some(result)
125}
126
127fn in_parens(v: &ComponentValue<'_>, depth: usize) -> Option<bool> {
128    match v {
129        ComponentValue::Block(b) if b.bracket == Bracket::Paren => {
130            let inner = solid(&b.contents);
131            if let Some(r) = condition_at(&inner, depth + 1) {
132                return Some(r);
133            }
134            // A declaration, `(property: value)`.
135            if let Ok(d) = crate::parse_declaration(&crate::to_css(&b.contents)) {
136                return Some(crate::values::parse_value(&d.name, &d.value).is_ok());
137            }
138            // `<general-enclosed>`: false.
139            Some(false)
140        }
141        ComponentValue::Function(f) => {
142            let args = solid(&f.arguments);
143            let one = |list: &[&str]| match args[..] {
144                [ComponentValue::Token(Token::Ident(w), _)] => {
145                    list.iter().any(|l| w.eq_ignore_ascii_case(l))
146                }
147                _ => false,
148            };
149            Some(match f.name.to_ascii_lowercase().as_str() {
150                #[cfg(feature = "cascade")]
151                "selector" => {
152                    parsec::css::SelectorList::parse(crate::to_css(&f.arguments).trim()).is_ok()
153                }
154                // Without the `cascade` feature there's no selector parser,
155                // so no selector is supported.
156                #[cfg(not(feature = "cascade"))]
157                "selector" => false,
158                "font-format" => one(FORMATS),
159                "font-tech" => one(TECHS),
160                // CSS Conditional 5 ยง2.5: an at-rule this crate reads.
161                "at-rule" => match args[..] {
162                    [ComponentValue::Token(Token::AtKeyword(w), _)] => {
163                        AT_RULES.iter().any(|a| w.eq_ignore_ascii_case(a))
164                    }
165                    _ => false,
166                },
167                _ => false,
168            })
169        }
170        _ => None,
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn conditions() {
180        for (css, want) in [
181            ("(color: red)", true),
182            ("color: red", true),
183            ("(color: red) and (color: blue)", true),
184            ("not (foobar)", true),
185            ("color: something-pointless var(--foo)", true),
186            ("unknownproperty: blah", false),
187            ("width: blah", false),
188            ("--foo: blah", true),
189            // Without the cascade there's nothing to match against.
190            ("selector(div > p)", cfg!(feature = "cascade")),
191            ("selector(:::)", false),
192            ("font-format(opentype)", true),
193            ("font-format(xyzzy)", false),
194            ("font-tech(color-COLRv1)", true),
195            ("(color: red) or (width: blah)", true),
196            ("(color: red) and (width: blah)", false),
197        ] {
198            assert_eq!(supports_text(css), want, "{css}");
199        }
200        // `and` and `or` don't mix without parentheses.
201        let c = crate::parse_component_values("(a: b) and (c: d) or (e: f)");
202        assert_eq!(supports(&c), None);
203    }
204}