Skip to main content

parsec_css/
media.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Media queries, Media Queries Level 5: a `<media-query-list>` parsed,
5//! written back as CSSOM's `mediaText` writes it, and evaluated against
6//! an [`Environment`] you give, with the three-valued logic §3.2 has, so
7//! a feature nobody knows makes its query false rather than an error.
8
9use std::fmt::{self, Write};
10
11use crate::parser::{Bracket, ComponentValue};
12use crate::tokenizer::Token;
13use crate::values::{Expect, Kind, Leaf, Math, Unit, write_number};
14
15/// What a media query is evaluated against: the viewport and the device.
16/// [`Environment::default`] is a 1280×720 colour screen at 1dppx with a
17/// fine pointer that can hover, light colour scheme, no preferences set.
18#[derive(Clone, Debug, PartialEq)]
19pub struct Environment {
20    /// `screen` or `print`; every other media type matches nothing.
21    pub media_type: MediaType,
22    /// The viewport, in CSS pixels.
23    pub width: f64,
24    pub height: f64,
25    /// The whole screen, in CSS pixels.
26    pub device_width: f64,
27    pub device_height: f64,
28    /// Device pixels per CSS pixel.
29    pub resolution: f64,
30    /// Bits per colour component, 0 for a monochrome device.
31    pub color: u32,
32    pub color_index: u32,
33    /// Bits per pixel of a monochrome device, 0 otherwise.
34    pub monochrome: u32,
35    /// The font size `em` in a media query is relative to, in pixels.
36    pub font_size: f64,
37    /// The value of each discrete feature, by name: `hover` to `hover`,
38    /// `prefers-color-scheme` to `light`. A feature not here is unknown.
39    pub keywords: Vec<(&'static str, &'static str)>,
40}
41
42impl Default for Environment {
43    fn default() -> Environment {
44        Environment {
45            media_type: MediaType::Screen,
46            width: 1280.0,
47            height: 720.0,
48            device_width: 1280.0,
49            device_height: 720.0,
50            resolution: 1.0,
51            color: 8,
52            color_index: 0,
53            monochrome: 0,
54            font_size: 16.0,
55            keywords: vec![
56                // A screen isn't scanned: `(scan)` is known and false.
57                ("scan", "none"),
58                ("grid", "0"),
59                ("update", "fast"),
60                ("overflow-block", "scroll"),
61                ("overflow-inline", "scroll"),
62                ("color-gamut", "srgb"),
63                ("dynamic-range", "standard"),
64                ("video-dynamic-range", "standard"),
65                ("inverted-colors", "none"),
66                ("pointer", "fine"),
67                ("any-pointer", "fine"),
68                ("hover", "hover"),
69                ("any-hover", "hover"),
70                ("scripting", "none"),
71                ("prefers-reduced-motion", "no-preference"),
72                ("prefers-reduced-transparency", "no-preference"),
73                ("prefers-reduced-data", "no-preference"),
74                ("prefers-contrast", "no-preference"),
75                ("prefers-color-scheme", "light"),
76                ("forced-colors", "none"),
77                ("display-mode", "browser"),
78                ("environment-blending", "opaque"),
79            ],
80        }
81    }
82}
83
84impl Environment {
85    fn keyword(&self, feature: &str) -> Option<&'static str> {
86        self.keywords
87            .iter()
88            .find(|(f, _)| *f == feature)
89            .map(|(_, v)| *v)
90    }
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub enum MediaType {
95    Screen,
96    Print,
97}
98
99/// The discrete features and the values each can take. `none` (or `0`)
100/// is the value that makes the boolean form false.
101const DISCRETE: &[(&str, &[&str])] = &[
102    ("orientation", &["portrait", "landscape"]),
103    ("scan", &["interlace", "progressive"]),
104    ("grid", &[]),
105    ("update", &["none", "slow", "fast"]),
106    ("overflow-block", &["none", "scroll", "paged"]),
107    ("overflow-inline", &["none", "scroll"]),
108    ("color-gamut", &["srgb", "p3", "rec2020"]),
109    ("dynamic-range", &["standard", "high"]),
110    ("video-dynamic-range", &["standard", "high"]),
111    ("inverted-colors", &["none", "inverted"]),
112    ("pointer", &["none", "coarse", "fine"]),
113    ("any-pointer", &["none", "coarse", "fine"]),
114    ("hover", &["none", "hover"]),
115    ("any-hover", &["none", "hover"]),
116    ("scripting", &["none", "initial-only", "enabled"]),
117    ("prefers-reduced-motion", &["no-preference", "reduce"]),
118    ("prefers-reduced-transparency", &["no-preference", "reduce"]),
119    ("prefers-reduced-data", &["no-preference", "reduce"]),
120    (
121        "prefers-contrast",
122        &["no-preference", "less", "more", "custom"],
123    ),
124    ("prefers-color-scheme", &["light", "dark"]),
125    ("forced-colors", &["none", "active"]),
126    (
127        "display-mode",
128        &[
129            "fullscreen",
130            "standalone",
131            "minimal-ui",
132            "browser",
133            "picture-in-picture",
134        ],
135    ),
136    (
137        "environment-blending",
138        &["opaque", "additive", "subtractive"],
139    ),
140];
141
142/// The range features, and what their values are.
143#[derive(Clone, Copy, PartialEq, Eq)]
144enum RangeType {
145    Length,
146    Ratio,
147    Resolution,
148    Integer,
149}
150
151const RANGE: &[(&str, RangeType)] = &[
152    ("width", RangeType::Length),
153    ("height", RangeType::Length),
154    ("device-width", RangeType::Length),
155    ("device-height", RangeType::Length),
156    ("aspect-ratio", RangeType::Ratio),
157    ("device-aspect-ratio", RangeType::Ratio),
158    ("resolution", RangeType::Resolution),
159    ("color", RangeType::Integer),
160    ("color-index", RangeType::Integer),
161    ("monochrome", RangeType::Integer),
162];
163
164/// A value in a media feature.
165#[derive(Clone, Debug, PartialEq)]
166pub enum FeatureValue {
167    Number(f64),
168    /// A number written with a fraction or an exponent, `1.0`: not an
169    /// `<integer>`.
170    Real(f64),
171    /// A length or resolution, as written.
172    Dimension(f64, Unit),
173    Math(Math),
174    /// `a / b`.
175    Ratio(f64, f64),
176    Ident(String),
177}
178
179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
180pub enum Comparison {
181    Lt,
182    Le,
183    Gt,
184    Ge,
185    Eq,
186}
187
188impl Comparison {
189    fn as_str(self) -> &'static str {
190        match self {
191            Comparison::Lt => "<",
192            Comparison::Le => "<=",
193            Comparison::Gt => ">",
194            Comparison::Ge => ">=",
195            Comparison::Eq => "=",
196        }
197    }
198
199    fn flip(self) -> Comparison {
200        match self {
201            Comparison::Lt => Comparison::Gt,
202            Comparison::Le => Comparison::Ge,
203            Comparison::Gt => Comparison::Lt,
204            Comparison::Ge => Comparison::Le,
205            Comparison::Eq => Comparison::Eq,
206        }
207    }
208
209    pub(crate) fn test(self, a: f64, b: f64) -> bool {
210        match self {
211            Comparison::Lt => a < b,
212            Comparison::Le => a <= b,
213            Comparison::Gt => a > b,
214            Comparison::Ge => a >= b,
215            Comparison::Eq => a == b,
216        }
217    }
218}
219
220/// `( … )` in a query.
221#[derive(Clone, Debug, PartialEq)]
222pub enum Feature {
223    /// `(name)`.
224    Boolean(String),
225    /// `(name: value)`, `min-` and `max-` names included.
226    Plain(String, FeatureValue),
227    /// `(name >= value)` or `(value < name < value)`, written in the
228    /// order it was, the name on the side given.
229    Range {
230        name: String,
231        /// `value op name`.
232        before: Option<(FeatureValue, Comparison)>,
233        /// `name op value`.
234        after: Option<(Comparison, FeatureValue)>,
235    },
236}
237
238/// A media condition.
239#[derive(Clone, Debug, PartialEq)]
240pub enum Condition {
241    Feature(Feature),
242    Not(Box<Condition>),
243    And(Vec<Condition>),
244    Or(Vec<Condition>),
245    /// `( … )` around a condition.
246    Parens(Box<Condition>),
247    /// Anything else in parentheses or a function: unknown, kept as text.
248    Unknown(String),
249}
250
251/// One media query.
252#[derive(Clone, Debug, PartialEq)]
253pub enum MediaQuery {
254    /// A query that didn't parse, which is `not all`.
255    Invalid,
256    /// `[not | only] type [and condition]`, or a bare condition.
257    Query {
258        qualifier: Option<Qualifier>,
259        media_type: Option<String>,
260        condition: Option<Condition>,
261    },
262}
263
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub enum Qualifier {
266    Not,
267    Only,
268}
269
270/// A comma-separated list of media queries: what `@media` and the
271/// `media` attribute hold.
272///
273/// ```
274/// use parsec_css::media::{Environment, MediaQueryList};
275///
276/// let list = MediaQueryList::parse(&parsec_css::parse_component_values("screen AND (min-width:600px), PRINT"));
277/// assert_eq!(list.to_string(), "screen and (min-width: 600px), print");
278/// assert!(list.matches(&Environment::default()));
279/// let narrow = Environment { width: 500.0, ..Environment::default() };
280/// assert!(!list.matches(&narrow));
281/// ```
282#[derive(Clone, Debug, PartialEq, Default)]
283pub struct MediaQueryList {
284    pub queries: Vec<MediaQuery>,
285}
286
287// ---- parsing ---------------------------------------------------------------
288
289/// How deep conditions may nest in parentheses.
290const MAX_DEPTH: usize = 64;
291
292pub(crate) fn solid<'v, 'a>(values: &'v [ComponentValue<'a>]) -> Vec<&'v ComponentValue<'a>> {
293    values.iter().filter(|v| !v.is_whitespace()).collect()
294}
295
296fn ident<'v>(v: Option<&&'v ComponentValue<'_>>) -> Option<&'v str> {
297    match v {
298        Some(ComponentValue::Token(Token::Ident(s), _)) => Some(s),
299        _ => None,
300    }
301}
302
303fn is_word(v: Option<&&ComponentValue<'_>>, word: &str) -> bool {
304    ident(v).is_some_and(|s| s.eq_ignore_ascii_case(word))
305}
306
307impl MediaQueryList {
308    /// Parses a media query list; a query that doesn't parse becomes
309    /// `not all`, as the spec says, and the rest stand.
310    pub fn parse(values: &[ComponentValue<'_>]) -> MediaQueryList {
311        if values.iter().all(ComponentValue::is_whitespace) {
312            return MediaQueryList::default();
313        }
314        let queries = values
315            .split(|v| matches!(v, ComponentValue::Token(Token::Comma, _)))
316            .map(|q| parse_query(q).unwrap_or(MediaQuery::Invalid))
317            .collect();
318        MediaQueryList { queries }
319    }
320
321    /// [`MediaQueryList::parse`] from text.
322    pub fn parse_str(css: &str) -> MediaQueryList {
323        MediaQueryList::parse(&crate::parse_component_values(css))
324    }
325
326    /// Whether any query matches; an empty list matches everything.
327    pub fn matches(&self, env: &Environment) -> bool {
328        self.queries.is_empty() || self.queries.iter().any(|q| q.evaluate(env) == Some(true))
329    }
330}
331
332fn parse_query(values: &[ComponentValue<'_>]) -> Option<MediaQuery> {
333    let v = solid(values);
334    if v.is_empty() {
335        return None;
336    }
337    // A condition on its own.
338    let bare_not = is_word(v.first(), "not")
339        && !matches!(v.get(1), Some(ComponentValue::Token(Token::Ident(_), _)));
340    if !matches!(v[0], ComponentValue::Token(Token::Ident(_), _)) || bare_not {
341        let condition = parse_condition(&v, true, 0)?;
342        return Some(MediaQuery::Query {
343            qualifier: None,
344            media_type: None,
345            condition: Some(condition),
346        });
347    }
348    let mut i = 0;
349    let qualifier = if is_word(v.first(), "not") {
350        i += 1;
351        Some(Qualifier::Not)
352    } else if is_word(v.first(), "only") {
353        i += 1;
354        Some(Qualifier::Only)
355    } else {
356        None
357    };
358    let media_type = ident(v.get(i))?;
359    if ["only", "not", "and", "or", "layer"]
360        .iter()
361        .any(|w| media_type.eq_ignore_ascii_case(w))
362    {
363        return None;
364    }
365    i += 1;
366    let condition = if i < v.len() {
367        if !is_word(v.get(i), "and") {
368            return None;
369        }
370        Some(parse_condition(&v[i + 1..], false, 0)?)
371    } else {
372        None
373    };
374    Some(MediaQuery::Query {
375        qualifier,
376        media_type: Some(media_type.to_ascii_lowercase()),
377        condition,
378    })
379}
380
381/// A condition: `not X`, or `X [and X]*`, or (if `or_ok`) `X [or X]*`.
382pub(crate) fn parse_condition(
383    v: &[&ComponentValue<'_>],
384    or_ok: bool,
385    depth: usize,
386) -> Option<Condition> {
387    if depth > MAX_DEPTH || v.is_empty() {
388        return None;
389    }
390    if is_word(v.first(), "not") {
391        if v.len() != 2 {
392            return None;
393        }
394        return Some(Condition::Not(Box::new(in_parens(v[1], depth)?)));
395    }
396    let first = in_parens(v[0], depth)?;
397    if v.len() == 1 {
398        return Some(first);
399    }
400    let joiner = ident(v.get(1))?.to_ascii_lowercase();
401    if joiner != "and" && !(joiner == "or" && or_ok) {
402        return None;
403    }
404    let mut items = vec![first];
405    let mut i = 1;
406    while i < v.len() {
407        if !is_word(v.get(i), &joiner) {
408            return None;
409        }
410        items.push(in_parens(v.get(i + 1)?, depth)?);
411        i += 2;
412    }
413    Some(if joiner == "and" {
414        Condition::And(items)
415    } else {
416        Condition::Or(items)
417    })
418}
419
420/// `( condition )`, `( feature )`, or anything else in parentheses or a
421/// function, which is unknown.
422fn in_parens(v: &ComponentValue<'_>, depth: usize) -> Option<Condition> {
423    match v {
424        ComponentValue::Block(b) if b.bracket == Bracket::Paren => {
425            let inner = solid(&b.contents);
426            if let Some(c) = parse_condition(&inner, true, depth + 1) {
427                return Some(Condition::Parens(Box::new(c)));
428            }
429            if let Some(f) = parse_feature(&inner) {
430                return Some(Condition::Feature(f));
431            }
432            Some(Condition::Unknown(crate::to_css(std::slice::from_ref(v))))
433        }
434        ComponentValue::Function(_) => {
435            Some(Condition::Unknown(crate::to_css(std::slice::from_ref(v))))
436        }
437        _ => None,
438    }
439}
440
441fn value(v: &[&ComponentValue<'_>]) -> Option<FeatureValue> {
442    match v {
443        [ComponentValue::Token(Token::Number(n), _)] if n.integer => {
444            Some(FeatureValue::Number(n.value))
445        }
446        [ComponentValue::Token(Token::Number(n), _)] => Some(FeatureValue::Real(n.value)),
447        [ComponentValue::Token(Token::Dimension { number, unit }, _)] => {
448            Some(FeatureValue::Dimension(number.value, Unit::parse(unit)?))
449        }
450        [ComponentValue::Token(Token::Ident(s), _)] => {
451            Some(FeatureValue::Ident(s.to_ascii_lowercase()))
452        }
453        [ComponentValue::Function(f)] if Math::is_math_function(&f.name) => {
454            Some(FeatureValue::Math(Math::parse(f)?))
455        }
456        [a, ComponentValue::Token(Token::Delim('/'), _), b] => {
457            let num = |v: &ComponentValue<'_>| match v {
458                ComponentValue::Token(Token::Number(n), _) => Some(n.value),
459                ComponentValue::Function(f) if Math::is_math_function(&f.name) => {
460                    match Math::parse(f)?.leaf()? {
461                        Leaf::Number(x) => Some(x),
462                        _ => None,
463                    }
464                }
465                _ => None,
466            };
467            Some(FeatureValue::Ratio(num(a)?, num(b)?))
468        }
469        _ => None,
470    }
471}
472
473pub(crate) fn comparison(v: &[&ComponentValue<'_>]) -> Option<(Comparison, usize)> {
474    let delim = |i: usize| match v.get(i) {
475        Some(ComponentValue::Token(Token::Delim(c), _)) => Some(*c),
476        _ => None,
477    };
478    let c = delim(0)?;
479    // `>=` is two delims written together; `> =` isn't one.
480    let together = match (v.first(), v.get(1)) {
481        (Some(a), Some(b)) => a.span().end == b.span().start,
482        _ => false,
483    };
484    Some(match (c, delim(1)) {
485        ('<', Some('=')) if together => (Comparison::Le, 2),
486        ('>', Some('=')) if together => (Comparison::Ge, 2),
487        ('<', _) => (Comparison::Lt, 1),
488        ('>', _) => (Comparison::Gt, 1),
489        ('=', _) => (Comparison::Eq, 1),
490        _ => return None,
491    })
492}
493
494fn parse_feature(v: &[&ComponentValue<'_>]) -> Option<Feature> {
495    // `(name)` and `(name: value)`.
496    if let Some(name) = ident(v.first()) {
497        if v.len() == 1 {
498            return Some(Feature::Boolean(name.to_ascii_lowercase()));
499        }
500        if matches!(v.get(1), Some(ComponentValue::Token(Token::Colon, _))) {
501            return Some(Feature::Plain(name.to_ascii_lowercase(), value(&v[2..])?));
502        }
503        // `name op value`.
504        let (op, n) = comparison(&v[1..])?;
505        return Some(Feature::Range {
506            name: name.to_ascii_lowercase(),
507            before: None,
508            after: Some((op, value(&v[1 + n..])?)),
509        });
510    }
511    // `value op name [op value]`: find the name, the one ident.
512    let at = v
513        .iter()
514        .position(|x| matches!(x, ComponentValue::Token(Token::Ident(_), _)))?;
515    let name = ident(v.get(at))?.to_ascii_lowercase();
516    // The value before it ends at the comparison before the name.
517    let mut op_start = at;
518    while op_start > 0 && matches!(v[op_start - 1], ComponentValue::Token(Token::Delim(_), _)) {
519        op_start -= 1;
520    }
521    let (op1, n1) = comparison(&v[op_start..at])?;
522    if op_start + n1 != at {
523        return None;
524    }
525    let first = value(&v[..op_start])?;
526    let after = if at + 1 < v.len() {
527        let (op2, n2) = comparison(&v[at + 1..])?;
528        // Both `<`-ish or both `>`-ish, never `=`.
529        let lt = |o: Comparison| matches!(o, Comparison::Lt | Comparison::Le);
530        let gt = |o: Comparison| matches!(o, Comparison::Gt | Comparison::Ge);
531        if !(lt(op1) && lt(op2) || gt(op1) && gt(op2)) {
532            return None;
533        }
534        Some((op2, value(&v[at + 1 + n2..])?))
535    } else {
536        None
537    };
538    Some(Feature::Range {
539        name,
540        before: Some((first, op1)),
541        after,
542    })
543}
544
545// ---- evaluation ------------------------------------------------------------
546
547/// What a query's relative lengths are relative to. For a media query
548/// that's all the environment; a container query's `em` is the
549/// container's, and its `cq*` units are the container's own query
550/// containers'.
551#[derive(Clone, Copy, Debug, PartialEq)]
552pub struct QueryLengths {
553    /// For `em` and `rem`, in pixels.
554    pub font_size: f64,
555    /// The viewport's width and height, for `vw` and the rest.
556    pub viewport: (f64, f64),
557    /// The width and height `cqw` and `cqh` are 1% of.
558    pub container: (f64, f64),
559    /// Whether the writing mode is vertical, so `cqi` is of the height.
560    pub vertical: bool,
561}
562
563impl QueryLengths {
564    /// A media query's: with no containers, `cq*` units are the small
565    /// viewport's, CSS Conditional 5 §6.3.
566    pub fn of(env: &Environment) -> QueryLengths {
567        QueryLengths {
568            font_size: env.font_size,
569            viewport: (env.width, env.height),
570            container: (env.width, env.height),
571            vertical: false,
572        }
573    }
574
575    /// Pixels in one `u`, or `None` if it isn't a length.
576    pub fn px(&self, u: Unit) -> Option<f64> {
577        let (w, h) = self.viewport;
578        let (cw, ch) = self.container;
579        let (ci, cb) = if self.vertical { (ch, cw) } else { (cw, ch) };
580        Some(match u {
581            Unit::Em | Unit::Rem => self.font_size,
582            Unit::Ex
583            | Unit::Rex
584            | Unit::Cap
585            | Unit::Rcap
586            | Unit::Ch
587            | Unit::Rch
588            | Unit::Ic
589            | Unit::Ric => self.font_size / 2.0,
590            Unit::Lh | Unit::Rlh => self.font_size * 1.2,
591            Unit::Vw
592            | Unit::Svw
593            | Unit::Lvw
594            | Unit::Dvw
595            | Unit::Vi
596            | Unit::Svi
597            | Unit::Lvi
598            | Unit::Dvi => w / 100.0,
599            Unit::Vh
600            | Unit::Svh
601            | Unit::Lvh
602            | Unit::Dvh
603            | Unit::Vb
604            | Unit::Svb
605            | Unit::Lvb
606            | Unit::Dvb => h / 100.0,
607            Unit::Vmin | Unit::Svmin | Unit::Lvmin | Unit::Dvmin => w.min(h) / 100.0,
608            Unit::Vmax | Unit::Svmax | Unit::Lvmax | Unit::Dvmax => w.max(h) / 100.0,
609            Unit::Cqw => cw / 100.0,
610            Unit::Cqh => ch / 100.0,
611            Unit::Cqi => ci / 100.0,
612            Unit::Cqb => cb / 100.0,
613            Unit::Cqmin => ci.min(cb) / 100.0,
614            Unit::Cqmax => ci.max(cb) / 100.0,
615            u if u.kind() == Kind::Length => u.to_canonical()?,
616            _ => return None,
617        })
618    }
619}
620
621/// A value in the feature's canonical unit: pixels, dppx, or a number.
622fn resolve(v: &FeatureValue, t: RangeType, lengths: &QueryLengths) -> Option<f64> {
623    let length = |x: f64, u: Unit| -> Option<f64> { Some(x * lengths.px(u)?) };
624    match (t, v) {
625        (RangeType::Length, FeatureValue::Number(n) | FeatureValue::Real(n)) if *n == 0.0 => {
626            Some(0.0)
627        }
628        (RangeType::Length, FeatureValue::Dimension(x, u)) => length(*x, *u),
629        (RangeType::Length, FeatureValue::Math(m)) if m.fits(Expect::Dimension(Kind::Length)) => {
630            // Each length in pixels first, so `calc(10px + 10em)` sums.
631            let m = m.map_leaves(&|l| match l {
632                Leaf::Dimension(x, u) => length(x, u).map_or(l, |p| Leaf::Dimension(p, Unit::Px)),
633                l => l,
634            });
635            match m.leaf()? {
636                Leaf::Dimension(x, u) => length(x, u),
637                _ => None,
638            }
639        }
640        (RangeType::Resolution, FeatureValue::Dimension(x, u))
641            if u.kind() == Kind::Resolution && *x >= 0.0 =>
642        {
643            Some(x * u.to_canonical()?)
644        }
645        (RangeType::Resolution, FeatureValue::Math(m)) => match m.leaf()? {
646            Leaf::Dimension(x, u) if u.kind() == Kind::Resolution => Some(x * u.to_canonical()?),
647            _ => None,
648        },
649        (RangeType::Integer, FeatureValue::Number(n)) if n.fract() == 0.0 => Some(*n),
650        (RangeType::Integer, FeatureValue::Math(m)) => match m.leaf()? {
651            Leaf::Number(x) => Some(x.round()),
652            _ => None,
653        },
654        (RangeType::Ratio, FeatureValue::Number(n) | FeatureValue::Real(n)) if *n >= 0.0 => {
655            Some(*n)
656        }
657        (RangeType::Ratio, FeatureValue::Ratio(a, b)) if *a >= 0.0 && *b >= 0.0 => {
658            Some(if *b == 0.0 {
659                if *a == 0.0 { f64::NAN } else { f64::INFINITY }
660            } else {
661                a / b
662            })
663        }
664        _ => None,
665    }
666}
667
668fn actual(name: &str, env: &Environment) -> f64 {
669    match name {
670        "width" => env.width,
671        "height" => env.height,
672        "device-width" => env.device_width,
673        "device-height" => env.device_height,
674        "aspect-ratio" => env.width / env.height,
675        "device-aspect-ratio" => env.device_width / env.device_height,
676        "resolution" => env.resolution,
677        "color" => f64::from(env.color),
678        "color-index" => f64::from(env.color_index),
679        "monochrome" => f64::from(env.monochrome),
680        _ => f64::NAN,
681    }
682}
683
684/// Exact for ratios, which are compared as fractions: 59/80 is 413/560.
685fn cmp(op: Comparison, a: f64, b: f64, t: RangeType) -> bool {
686    if t == RangeType::Ratio && op == Comparison::Eq {
687        return (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
688    }
689    op.test(a, b)
690}
691
692impl Feature {
693    /// `Some(true)`, `Some(false)`, or `None` for unknown.
694    pub fn evaluate(&self, env: &Environment) -> Option<bool> {
695        self.evaluate_with(env, &QueryLengths::of(env))
696    }
697
698    /// [`Feature::evaluate`], with relative lengths relative to `lengths`.
699    pub fn evaluate_with(&self, env: &Environment, lengths: &QueryLengths) -> Option<bool> {
700        match self {
701            Feature::Boolean(name) => {
702                if RANGE.iter().any(|(n, _)| n == name) {
703                    let a = actual(name, env);
704                    return Some(a != 0.0 && !a.is_nan());
705                }
706                if name == "orientation" {
707                    return Some(true);
708                }
709                if name == "grid" {
710                    return Some(env.keyword("grid")? != "0");
711                }
712                DISCRETE.iter().find(|(n, _)| n == name)?;
713                // False only for the value that says there's nothing.
714                Some(!matches!(env.keyword(name)?, "none" | "no-preference"))
715            }
716            Feature::Plain(name, v) => {
717                let (prefix, base) = match name.strip_prefix("min-") {
718                    Some(b) => (Some(Comparison::Ge), b),
719                    None => match name.strip_prefix("max-") {
720                        Some(b) => (Some(Comparison::Le), b),
721                        None => (None, name.as_str()),
722                    },
723                };
724                if let Some((_, t)) = RANGE.iter().find(|(n, _)| *n == base) {
725                    let want = resolve(v, *t, lengths)?;
726                    let op = prefix.unwrap_or(Comparison::Eq);
727                    return Some(cmp(op, actual(base, env), want, *t));
728                }
729                if prefix.is_some() {
730                    return None;
731                }
732                let FeatureValue::Ident(word) = v else {
733                    if name == "grid"
734                        && let FeatureValue::Number(n) = v
735                        && (*n == 0.0 || *n == 1.0)
736                    {
737                        return Some((*n == 1.0) == (env.keyword("grid")? != "0"));
738                    }
739                    return None;
740                };
741                if name == "orientation" {
742                    let portrait = env.height >= env.width;
743                    return match word.as_str() {
744                        "portrait" => Some(portrait),
745                        "landscape" => Some(!portrait),
746                        _ => None,
747                    };
748                }
749                let (_, values) = DISCRETE.iter().find(|(n, _)| *n == name)?;
750                if !values.contains(&word.as_str()) {
751                    return None;
752                }
753                Some(env.keyword(name)? == word)
754            }
755            Feature::Range {
756                name,
757                before,
758                after,
759            } => {
760                let (_, t) = RANGE.iter().find(|(n, _)| n == name)?;
761                let a = actual(name, env);
762                let mut ok = true;
763                if let Some((v, op)) = before {
764                    // `v op name` is `name flip(op) v`.
765                    ok &= cmp(op.flip(), a, resolve(v, *t, lengths)?, *t);
766                }
767                if let Some((op, v)) = after {
768                    ok &= cmp(*op, a, resolve(v, *t, lengths)?, *t);
769                }
770                Some(ok)
771            }
772        }
773    }
774}
775
776impl Condition {
777    pub fn evaluate(&self, env: &Environment) -> Option<bool> {
778        match self {
779            Condition::Feature(f) => f.evaluate(env),
780            Condition::Parens(c) => c.evaluate(env),
781            Condition::Not(c) => c.evaluate(env).map(|b| !b),
782            Condition::Unknown(_) => None,
783            // Three-valued: false beats unknown in `and`, true in `or`.
784            Condition::And(cs) => {
785                let mut unknown = false;
786                for c in cs {
787                    match c.evaluate(env) {
788                        Some(false) => return Some(false),
789                        None => unknown = true,
790                        Some(true) => {}
791                    }
792                }
793                if unknown { None } else { Some(true) }
794            }
795            Condition::Or(cs) => {
796                let mut unknown = false;
797                for c in cs {
798                    match c.evaluate(env) {
799                        Some(true) => return Some(true),
800                        None => unknown = true,
801                        Some(false) => {}
802                    }
803                }
804                if unknown { None } else { Some(false) }
805            }
806        }
807    }
808}
809
810impl MediaQuery {
811    /// Whether the query matches; unknown counts as false at the top.
812    pub fn evaluate(&self, env: &Environment) -> Option<bool> {
813        let MediaQuery::Query {
814            qualifier,
815            media_type,
816            condition,
817        } = self
818        else {
819            return Some(false);
820        };
821        let type_ok = match media_type.as_deref() {
822            None | Some("all") => true,
823            Some("screen") => env.media_type == MediaType::Screen,
824            Some("print") => env.media_type == MediaType::Print,
825            Some(_) => false,
826        };
827        let result = match condition {
828            Some(c) if type_ok => c.evaluate(env),
829            Some(_) => Some(false),
830            None => Some(type_ok),
831        };
832        // Unknown is false, `not` or no `not`: `not all and (foo: bar)`
833        // matches nothing, which is how a feature is told to be unknown.
834        match qualifier {
835            Some(Qualifier::Not) => Some(result.map(|b| !b).unwrap_or(false)),
836            _ => Some(result.unwrap_or(false)),
837        }
838    }
839}
840
841// ---- serialization ---------------------------------------------------------
842
843impl fmt::Display for FeatureValue {
844    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845        match self {
846            FeatureValue::Number(n) | FeatureValue::Real(n) => write_number(f, *n),
847            FeatureValue::Dimension(v, u) => {
848                write_number(f, *v)?;
849                f.write_str(u.as_str())
850            }
851            FeatureValue::Math(m) => write!(f, "{m}"),
852            FeatureValue::Ratio(a, b) => {
853                write_number(f, *a)?;
854                f.write_str(" / ")?;
855                write_number(f, *b)
856            }
857            FeatureValue::Ident(s) => crate::write_identifier(f, s),
858        }
859    }
860}
861
862impl fmt::Display for Feature {
863    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864        f.write_char('(')?;
865        match self {
866            Feature::Boolean(n) => crate::write_identifier(f, n)?,
867            Feature::Plain(n, v) => {
868                crate::write_identifier(f, n)?;
869                write!(f, ": {v}")?;
870            }
871            Feature::Range {
872                name,
873                before,
874                after,
875            } => {
876                if let Some((v, op)) = before {
877                    write!(f, "{v} {} ", op.as_str())?;
878                }
879                crate::write_identifier(f, name)?;
880                if let Some((op, v)) = after {
881                    write!(f, " {} {v}", op.as_str())?;
882                }
883            }
884        }
885        f.write_char(')')
886    }
887}
888
889impl fmt::Display for Condition {
890    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891        match self {
892            Condition::Feature(x) => write!(f, "{x}"),
893            Condition::Parens(c) => write!(f, "({c})"),
894            Condition::Not(c) => write!(f, "not {c}"),
895            Condition::Unknown(s) => f.write_str(s),
896            Condition::And(cs) | Condition::Or(cs) => {
897                let join = if matches!(self, Condition::And(_)) {
898                    " and "
899                } else {
900                    " or "
901                };
902                for (i, c) in cs.iter().enumerate() {
903                    if i > 0 {
904                        f.write_str(join)?;
905                    }
906                    write!(f, "{c}")?;
907                }
908                Ok(())
909            }
910        }
911    }
912}
913
914impl fmt::Display for MediaQuery {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        let MediaQuery::Query {
917            qualifier,
918            media_type,
919            condition,
920        } = self
921        else {
922            return f.write_str("not all");
923        };
924        match qualifier {
925            Some(Qualifier::Not) => f.write_str("not ")?,
926            Some(Qualifier::Only) => f.write_str("only ")?,
927            None => {}
928        }
929        match (media_type, condition) {
930            // `all and X` is written `X`, unless a qualifier needs the type.
931            (Some(t), Some(c)) if t == "all" && qualifier.is_none() => write!(f, "{c}"),
932            (Some(t), Some(c)) => {
933                crate::write_identifier(f, t)?;
934                write!(f, " and {c}")
935            }
936            (Some(t), None) => crate::write_identifier(f, t),
937            (None, Some(c)) => write!(f, "{c}"),
938            (None, None) => Ok(()),
939        }
940    }
941}
942
943impl fmt::Display for MediaQueryList {
944    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945        for (i, q) in self.queries.iter().enumerate() {
946            if i > 0 {
947                f.write_str(", ")?;
948            }
949            write!(f, "{q}")?;
950        }
951        Ok(())
952    }
953}