Skip to main content

sk_css/
media.rs

1//! `@media` conditions reduced to the features a native window can answer, plus the runtime [`Env`]
2//! they are evaluated against. Anything outside that set is rejected with an advisory and the block
3//! dropped, never compiled into a rule that cannot match.
4
5use lightningcss::media_query::{
6    MediaCondition, MediaFeature, MediaFeatureComparison, MediaFeatureId, MediaFeatureName,
7    MediaFeatureValue, MediaList, MediaQuery, MediaType, Operator, Qualifier, QueryFeature,
8};
9use lightningcss::traits::ToCss;
10
11#[derive(Clone, Copy, Debug, PartialEq)]
12pub struct Env {
13    pub viewport_width: f32,
14    pub viewport_height: f32,
15    pub dark: bool,
16    pub reduce_motion: bool,
17    pub scale_factor: f32,
18    pub display_mode: DisplayMode,
19    /// `None` while the overlay is not visible (OS chrome, fullscreen, minimised): the variables are
20    /// then undefined and `env(titlebar-area-height, 40px)` takes its fallback, as in a browser.
21    pub titlebar_area: Option<[f32; 4]>,
22    /// The primary pointer of a desktop window is always the mouse (`pointer: fine`, `hover:
23    /// hover`); only `any-pointer` can widen to other hardware.
24    pub coarse_pointer: bool,
25    /// Exists so `env(safe-area-inset-*)` from PWA sheets resolves: a fallback-less unknown `env()`
26    /// invalidates its declaration.
27    pub safe_area_insets: [f32; 4],
28    /// The OS asks for opaque surfaces (Windows "Transparency effects" off, macOS "Reduce
29    /// transparency").
30    pub reduce_transparency: bool,
31    /// `device-width` / `device-height`: the window's monitor, CSS px.
32    pub device_size: (f32, f32),
33    /// `dynamic-range: high`: the window's display is in HDR and the window can draw it.
34    pub dynamic_range_high: bool,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum DisplayMode {
39    Standalone,
40    WindowControlsOverlay,
41    Fullscreen,
42}
43
44impl DisplayMode {
45    pub fn as_str(self) -> &'static str {
46        match self {
47            DisplayMode::Standalone => "standalone",
48            DisplayMode::WindowControlsOverlay => "window-controls-overlay",
49            DisplayMode::Fullscreen => "fullscreen",
50        }
51    }
52}
53
54impl Default for Env {
55    fn default() -> Self {
56        Env {
57            viewport_width: 1024.0,
58            viewport_height: 768.0,
59            dark: false,
60            reduce_motion: false,
61            scale_factor: 1.0,
62            display_mode: DisplayMode::WindowControlsOverlay,
63            titlebar_area: Some([0.0, 0.0, 1024.0, 32.0]),
64            coarse_pointer: false,
65            safe_area_insets: [0.0; 4],
66            reduce_transparency: false,
67            device_size: (1920.0, 1080.0),
68            dynamic_range_high: false,
69        }
70    }
71}
72
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub(crate) enum Cmp {
75    Lt,
76    Le,
77    Gt,
78    Ge,
79    Eq,
80}
81
82impl Cmp {
83    fn from(op: MediaFeatureComparison) -> Cmp {
84        match op {
85            MediaFeatureComparison::LessThan => Cmp::Lt,
86            MediaFeatureComparison::LessThanEqual => Cmp::Le,
87            MediaFeatureComparison::GreaterThan => Cmp::Gt,
88            MediaFeatureComparison::GreaterThanEqual => Cmp::Ge,
89            MediaFeatureComparison::Equal => Cmp::Eq,
90        }
91    }
92
93    fn flip(self) -> Cmp {
94        match self {
95            Cmp::Lt => Cmp::Gt,
96            Cmp::Le => Cmp::Ge,
97            Cmp::Gt => Cmp::Lt,
98            Cmp::Ge => Cmp::Le,
99            Cmp::Eq => Cmp::Eq,
100        }
101    }
102
103    fn eval(self, lhs: f32, rhs: f32) -> bool {
104        match self {
105            Cmp::Lt => lhs < rhs,
106            Cmp::Le => lhs <= rhs,
107            Cmp::Gt => lhs > rhs,
108            Cmp::Ge => lhs >= rhs,
109            // Exact float equality is what `(width: 800px)` means in CSS; the viewport is an
110            // integral pixel count, so this is not as fragile as it looks.
111            Cmp::Eq => lhs == rhs,
112        }
113    }
114}
115
116#[derive(Clone, Copy, Debug, PartialEq)]
117pub(crate) enum Feature {
118    Width(Cmp, f32),
119    Height(Cmp, f32),
120    ColorScheme(bool),
121    ReducedMotion(bool),
122    Resolution(Cmp, f32),
123    Display(DisplayMode),
124    Pointer { any: bool, want: PointerKind },
125    Hover { any: bool, want: bool },
126    ReducedTransparency(bool),
127    DeviceWidth(Cmp, f32),
128    DeviceHeight(Cmp, f32),
129    DynamicRange(bool),
130}
131
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub(crate) enum PointerKind {
134    None,
135    Coarse,
136    Fine,
137}
138
139impl Feature {
140    fn eval(&self, env: &Env) -> bool {
141        match *self {
142            Feature::Width(cmp, px) => cmp.eval(env.viewport_width, px),
143            Feature::Height(cmp, px) => cmp.eval(env.viewport_height, px),
144            Feature::ColorScheme(dark) => env.dark == dark,
145            Feature::ReducedMotion(reduce) => env.reduce_motion == reduce,
146            Feature::Resolution(cmp, dppx) => cmp.eval(env.scale_factor, dppx),
147            Feature::Display(mode) => env.display_mode == mode,
148            // The PRIMARY pointer of a desktop window is the mouse gpui delivers `PlatformInput`
149            // from, whatever else is plugged in — the same answer a browser gives in a desktop
150            // window on a touch laptop.
151            Feature::Pointer { any, want } => match want {
152                PointerKind::None => false,
153                PointerKind::Fine => true,
154                PointerKind::Coarse => any && env.coarse_pointer,
155            },
156            Feature::Hover { any, want } => {
157                let _ = any;
158                want
159            }
160            Feature::ReducedTransparency(reduce) => env.reduce_transparency == reduce,
161            Feature::DeviceWidth(cmp, px) => cmp.eval(env.device_size.0, px),
162            Feature::DeviceHeight(cmp, px) => cmp.eval(env.device_size.1, px),
163            Feature::DynamicRange(high) => !high || env.dynamic_range_high,
164        }
165    }
166}
167
168#[derive(Clone, Debug, PartialEq)]
169pub(crate) enum Cond {
170    Always,
171    Never,
172    Feature(Feature),
173    Not(Box<Cond>),
174    And(Vec<Cond>),
175    Or(Vec<Cond>),
176}
177
178impl Cond {
179    pub(crate) fn eval(&self, env: &Env) -> bool {
180        match self {
181            Cond::Always => true,
182            Cond::Never => false,
183            Cond::Feature(f) => f.eval(env),
184            Cond::Not(c) => !c.eval(env),
185            Cond::And(cs) => cs.iter().all(|c| c.eval(env)),
186            Cond::Or(cs) => cs.iter().any(|c| c.eval(env)),
187        }
188    }
189
190    pub(crate) fn and(self, other: Cond) -> Cond {
191        match (self, other) {
192            (Cond::Never, _) | (_, Cond::Never) => Cond::Never,
193            (Cond::Always, c) | (c, Cond::Always) => c,
194            (Cond::And(mut a), Cond::And(b)) => {
195                a.extend(b);
196                Cond::And(a)
197            }
198            (Cond::And(mut a), c) => {
199                a.push(c);
200                Cond::And(a)
201            }
202            (c, Cond::And(mut b)) => {
203                b.insert(0, c);
204                Cond::And(b)
205            }
206            (a, b) => Cond::And(vec![a, b]),
207        }
208    }
209}
210
211pub(crate) type Unsupported = &'static str;
212
213pub(crate) const SUPPORTED: &str = "supported: `screen`/`all`/`print` media types, \
214     `width`/`min-width`/`max-width`, `height`/`min-height`/`max-height` (px lengths, \
215     range and interval syntax), `device-width`/`device-height` (and their `min-`/`max-` forms), \
216     `prefers-color-scheme`, `prefers-reduced-motion`, `prefers-reduced-transparency`, \
217     `resolution`/`min-resolution`/`max-resolution` (dppx/dpi/dpcm), `display-mode`, \
218     `pointer`/`any-pointer`, `hover`/`any-hover`, `dynamic-range`/`video-dynamic-range`, \
219     combined with `and`/`or`/`not`/`,`";
220
221pub(crate) fn parse_list(list: &MediaList<'_>) -> Result<Cond, Unsupported> {
222    let mut queries = Vec::with_capacity(list.media_queries.len());
223    for q in &list.media_queries {
224        queries.push(parse_query(q)?);
225    }
226    Ok(match queries.len() {
227        0 => Cond::Always,
228        1 => queries.pop().unwrap(),
229        _ => Cond::Or(queries),
230    })
231}
232
233fn parse_query(q: &MediaQuery<'_>) -> Result<Cond, Unsupported> {
234    // `print` blocks parse fine and simply never apply — the browser-honest answer, and it keeps
235    // `print:` utilities from becoming an error every Tailwind app would hit.
236    let type_cond = match &q.media_type {
237        MediaType::All | MediaType::Screen => Cond::Always,
238        MediaType::Print => Cond::Never,
239        MediaType::Custom(_) => return Err("an unknown media type"),
240    };
241    let cond = match &q.condition {
242        Some(c) => type_cond.and(parse_condition(c)?),
243        None => type_cond,
244    };
245    Ok(match q.qualifier {
246        Some(Qualifier::Not) => match cond {
247            Cond::Always => Cond::Never,
248            Cond::Never => Cond::Always,
249            c => Cond::Not(Box::new(c)),
250        },
251        Some(Qualifier::Only) | None => cond,
252    })
253}
254
255fn parse_condition(c: &MediaCondition<'_>) -> Result<Cond, Unsupported> {
256    Ok(match c {
257        MediaCondition::Feature(f) => parse_feature(f)?,
258        MediaCondition::Not(inner) => Cond::Not(Box::new(parse_condition(inner)?)),
259        MediaCondition::Operation {
260            operator,
261            conditions,
262        } => {
263            let mut parsed = Vec::with_capacity(conditions.len());
264            for c in conditions {
265                parsed.push(parse_condition(c)?);
266            }
267            match operator {
268                Operator::And => Cond::And(parsed),
269                Operator::Or => Cond::Or(parsed),
270            }
271        }
272        MediaCondition::Unknown(_) => return Err("tokens the media parser could not interpret"),
273    })
274}
275
276fn standard(name: &MediaFeatureName<'_, MediaFeatureId>) -> Result<MediaFeatureId, Unsupported> {
277    match name {
278        MediaFeatureName::Standard(id) => Ok(*id),
279        MediaFeatureName::Custom(_) => Err("a custom media feature (`--var`)"),
280        MediaFeatureName::Unknown(_) => Err("an unknown media feature"),
281    }
282}
283
284fn length_px(value: &MediaFeatureValue<'_>) -> Result<f32, Unsupported> {
285    match value {
286        MediaFeatureValue::Length(l) => l
287            .to_px()
288            .ok_or("a media length that is not convertible to px (`em`/`%`/`calc()`/`env()`)"),
289        _ => Err("a media feature value of the wrong type"),
290    }
291}
292
293fn ident<'a>(value: &'a MediaFeatureValue<'_>) -> Result<&'a str, Unsupported> {
294    match value {
295        MediaFeatureValue::Ident(i) => Ok(i.0.as_ref()),
296        _ => Err("a media feature value of the wrong type"),
297    }
298}
299
300fn dppx(value: &MediaFeatureValue<'_>) -> Result<f32, Unsupported> {
301    use lightningcss::values::resolution::Resolution;
302    match value {
303        MediaFeatureValue::Resolution(r) => Ok(match r {
304            Resolution::Dppx(v) => *v,
305            Resolution::Dpi(v) => *v / 96.0,
306            Resolution::Dpcm(v) => *v * 2.54 / 96.0,
307        }),
308        _ => Err("a media feature value of the wrong type"),
309    }
310}
311
312/// `browser` and `minimal-ui` parse but can never match — we are permanently an installed app
313/// window — which is the browser-honest answer and keeps a ported PWA's `browser` branch compiling.
314fn display_mode(value: &MediaFeatureValue<'_>) -> Result<Cond, Unsupported> {
315    Ok(match ident(value)? {
316        "standalone" => Cond::Feature(Feature::Display(DisplayMode::Standalone)),
317        "window-controls-overlay" => {
318            Cond::Feature(Feature::Display(DisplayMode::WindowControlsOverlay))
319        }
320        "fullscreen" => Cond::Feature(Feature::Display(DisplayMode::Fullscreen)),
321        "browser" | "minimal-ui" | "picture-in-picture" => Cond::Never,
322        _ => return Err("an unknown `display-mode` value"),
323    })
324}
325
326fn sized(id: MediaFeatureId, cmp: Cmp, px: f32) -> Feature {
327    match id {
328        MediaFeatureId::Width => Feature::Width(cmp, px),
329        MediaFeatureId::DeviceWidth => Feature::DeviceWidth(cmp, px),
330        MediaFeatureId::DeviceHeight => Feature::DeviceHeight(cmp, px),
331        _ => Feature::Height(cmp, px),
332    }
333}
334
335fn pointer(value: &MediaFeatureValue<'_>, any: bool) -> Result<Cond, Unsupported> {
336    Ok(Cond::Feature(Feature::Pointer {
337        any,
338        want: match ident(value)? {
339            "none" => PointerKind::None,
340            "coarse" => PointerKind::Coarse,
341            "fine" => PointerKind::Fine,
342            _ => return Err("an unknown `pointer` value"),
343        },
344    }))
345}
346
347fn hover(value: &MediaFeatureValue<'_>, any: bool) -> Result<Cond, Unsupported> {
348    Ok(Cond::Feature(Feature::Hover {
349        any,
350        want: match ident(value)? {
351            "hover" => true,
352            "none" => false,
353            _ => return Err("an unknown `hover` value"),
354        },
355    }))
356}
357
358fn dynamic_range(value: &MediaFeatureValue<'_>) -> Result<Cond, Unsupported> {
359    Ok(Cond::Feature(Feature::DynamicRange(match ident(value)? {
360        "high" => true,
361        "standard" => false,
362        _ => return Err("an unknown `dynamic-range` value"),
363    })))
364}
365
366fn parse_feature(f: &MediaFeature<'_>) -> Result<Cond, Unsupported> {
367    use MediaFeatureId::{
368        AnyHover, AnyPointer, DeviceHeight, DeviceWidth, DisplayMode as DisplayModeId,
369        DynamicRange, Height, Hover as HoverId, Pointer as PointerId, PrefersColorScheme,
370        PrefersReducedMotion, PrefersReducedTransparency, Resolution, VideoDynamicRange, Width,
371    };
372    Ok(match f {
373        QueryFeature::Plain { name, value } => match standard(name)? {
374            id @ (Width | Height | DeviceWidth | DeviceHeight) => {
375                Cond::Feature(sized(id, Cmp::Eq, length_px(value)?))
376            }
377            Resolution => Cond::Feature(Feature::Resolution(Cmp::Eq, dppx(value)?)),
378            DisplayModeId => display_mode(value)?,
379            PointerId => pointer(value, false)?,
380            AnyPointer => pointer(value, true)?,
381            HoverId => hover(value, false)?,
382            AnyHover => hover(value, true)?,
383            DynamicRange | VideoDynamicRange => dynamic_range(value)?,
384            PrefersColorScheme => match ident(value)? {
385                "dark" => Cond::Feature(Feature::ColorScheme(true)),
386                "light" => Cond::Feature(Feature::ColorScheme(false)),
387                _ => return Err("an unknown `prefers-color-scheme` value"),
388            },
389            PrefersReducedMotion => match ident(value)? {
390                "reduce" => Cond::Feature(Feature::ReducedMotion(true)),
391                "no-preference" => Cond::Feature(Feature::ReducedMotion(false)),
392                _ => return Err("an unknown `prefers-reduced-motion` value"),
393            },
394            PrefersReducedTransparency => match ident(value)? {
395                "reduce" => Cond::Feature(Feature::ReducedTransparency(true)),
396                "no-preference" => Cond::Feature(Feature::ReducedTransparency(false)),
397                _ => return Err("an unknown `prefers-reduced-transparency` value"),
398            },
399            _ => return Err("an unsupported media feature"),
400        },
401        QueryFeature::Boolean { name } => match standard(name)? {
402            Width | Height | DeviceWidth | DeviceHeight => Cond::Always,
403            PrefersReducedTransparency => Cond::Feature(Feature::ReducedTransparency(true)),
404            PrefersColorScheme => Cond::Always,
405            PrefersReducedMotion => Cond::Feature(Feature::ReducedMotion(true)),
406            PointerId | AnyPointer | HoverId | AnyHover => Cond::Always,
407            Resolution | DisplayModeId | DynamicRange | VideoDynamicRange => Cond::Always,
408            _ => return Err("an unsupported media feature"),
409        },
410        QueryFeature::Range {
411            name,
412            operator,
413            value,
414        } => match standard(name)? {
415            id @ (Width | Height | DeviceWidth | DeviceHeight) => {
416                Cond::Feature(sized(id, Cmp::from(*operator), length_px(value)?))
417            }
418            Resolution => Cond::Feature(Feature::Resolution(Cmp::from(*operator), dppx(value)?)),
419            _ => return Err("a range comparison on a feature that has no numeric value"),
420        },
421        QueryFeature::Interval {
422            name,
423            start,
424            start_operator,
425            end,
426            end_operator,
427        } => match standard(name)? {
428            id @ (Width | Height | DeviceWidth | DeviceHeight) => Cond::And(vec![
429                Cond::Feature(sized(
430                    id,
431                    Cmp::from(*start_operator).flip(),
432                    length_px(start)?,
433                )),
434                Cond::Feature(sized(id, Cmp::from(*end_operator), length_px(end)?)),
435            ]),
436            Resolution => Cond::And(vec![
437                Cond::Feature(Feature::Resolution(
438                    Cmp::from(*start_operator).flip(),
439                    dppx(start)?,
440                )),
441                Cond::Feature(Feature::Resolution(Cmp::from(*end_operator), dppx(end)?)),
442            ]),
443            _ => return Err("a range comparison on a feature that has no numeric value"),
444        },
445    })
446}
447
448/// `Err` is the reason a prelude was rejected; a browser treats an invalid media list as `not all`,
449/// so callers report `matches: false` with the advisory.
450pub fn match_media(query: &str, env: &Env) -> Result<bool, String> {
451    use lightningcss::rules::CssRule;
452    use lightningcss::stylesheet::{ParserOptions, StyleSheet};
453
454    let css = format!("@media {query} {{ }}");
455    let sheet = StyleSheet::parse(&css, ParserOptions::default())
456        .map_err(|e| format!("could not be parsed ({e})"))?;
457    let Some(CssRule::Media(m)) = sheet.rules.0.first() else {
458        return Err("is not a media query".to_string());
459    };
460    parse_list(&m.query)
461        .map(|cond| cond.eval(env))
462        .map_err(|why| format!("uses {why} — {SUPPORTED}"))
463}
464
465pub(crate) fn list_text(list: &MediaList<'_>) -> String {
466    list.to_css_string(lightningcss::printer::PrinterOptions::default())
467        .unwrap_or_else(|_| "<media query>".into())
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473    use lightningcss::rules::CssRule;
474    use lightningcss::stylesheet::{ParserOptions, StyleSheet};
475
476    fn cond(prelude: &str) -> Result<Cond, Unsupported> {
477        let css = format!("@media {prelude} {{ .x {{ color: red }} }}");
478        let sheet = StyleSheet::parse(&css, ParserOptions::default()).expect("parses");
479        match &sheet.rules.0[0] {
480            CssRule::Media(m) => parse_list(&m.query),
481            other => panic!("expected @media, got {other:?}"),
482        }
483    }
484
485    fn env(w: f32, dark: bool, reduce: bool) -> Env {
486        Env {
487            viewport_width: w,
488            viewport_height: 800.0,
489            dark,
490            reduce_motion: reduce,
491            ..Env::default()
492        }
493    }
494
495    #[test]
496    fn min_width_becomes_a_ge_range() {
497        let c = cond("(min-width: 640px)").unwrap();
498        assert_eq!(c, Cond::Feature(Feature::Width(Cmp::Ge, 640.0)));
499        assert!(!c.eval(&env(639.0, false, false)));
500        assert!(c.eval(&env(640.0, false, false)));
501        assert!(c.eval(&env(1200.0, false, false)));
502    }
503
504    #[test]
505    fn max_width_is_inclusive_like_a_browser() {
506        let c = cond("(max-width: 640px)").unwrap();
507        assert_eq!(c, Cond::Feature(Feature::Width(Cmp::Le, 640.0)));
508        assert!(c.eval(&env(640.0, false, false)));
509        assert!(!c.eval(&env(641.0, false, false)));
510    }
511
512    #[test]
513    fn range_and_interval_syntax() {
514        assert!(cond("(width > 400px)")
515            .unwrap()
516            .eval(&env(500.0, false, false)));
517        assert!(!cond("(width > 400px)")
518            .unwrap()
519            .eval(&env(400.0, false, false)));
520        let i = cond("(400px < width < 800px)").unwrap();
521        assert!(!i.eval(&env(400.0, false, false)));
522        assert!(i.eval(&env(401.0, false, false)));
523        assert!(i.eval(&env(799.0, false, false)));
524        assert!(!i.eval(&env(800.0, false, false)));
525    }
526
527    #[test]
528    fn screen_and_all_match_print_never_does() {
529        assert!(cond("screen").unwrap().eval(&Env::default()));
530        assert!(cond("all").unwrap().eval(&Env::default()));
531        assert_eq!(cond("print").unwrap(), Cond::Never);
532        assert!(!cond("print").unwrap().eval(&Env::default()));
533        assert_eq!(
534            cond("screen and (min-width: 100px)").unwrap(),
535            Cond::Feature(Feature::Width(Cmp::Ge, 100.0))
536        );
537    }
538
539    #[test]
540    fn color_scheme_and_reduced_motion() {
541        let dark = cond("(prefers-color-scheme: dark)").unwrap();
542        assert!(dark.eval(&env(800.0, true, false)));
543        assert!(!dark.eval(&env(800.0, false, false)));
544        let light = cond("(prefers-color-scheme: light)").unwrap();
545        assert!(light.eval(&env(800.0, false, false)));
546        let rm = cond("(prefers-reduced-motion: reduce)").unwrap();
547        assert!(rm.eval(&env(800.0, false, true)));
548        assert!(!rm.eval(&env(800.0, false, false)));
549        assert!(cond("(prefers-reduced-motion: no-preference)")
550            .unwrap()
551            .eval(&env(800.0, false, false)));
552    }
553
554    #[test]
555    fn reduced_transparency_and_device_size() {
556        let reduced = Env {
557            reduce_transparency: true,
558            device_size: (2560.0, 1440.0),
559            ..Env::default()
560        };
561        let plain = Env {
562            device_size: (1280.0, 800.0),
563            ..Env::default()
564        };
565        let matches = |query: &str, env: &Env| cond(query).unwrap().eval(env);
566        assert!(matches("(prefers-reduced-transparency: reduce)", &reduced));
567        assert!(matches("(prefers-reduced-transparency)", &reduced));
568        assert!(!matches("(prefers-reduced-transparency)", &plain));
569        assert!(matches(
570            "(prefers-reduced-transparency: no-preference)",
571            &plain
572        ));
573        assert!(matches("(min-device-width: 1920px)", &reduced));
574        assert!(!matches("(min-device-width: 1920px)", &plain));
575        assert!(!matches("(max-device-height: 1080px)", &reduced));
576        assert!(matches("(device-width: 1280px)", &plain));
577        assert!(matches("(1000px < device-height <= 1440px)", &reduced));
578        assert!(
579            !matches("(min-width: 1500px)", &reduced),
580            "the viewport is not the device"
581        );
582    }
583
584    #[test]
585    fn and_or_not_and_comma_combine() {
586        let c = cond("(min-width: 640px) and (prefers-color-scheme: dark)").unwrap();
587        assert!(c.eval(&env(700.0, true, false)));
588        assert!(!c.eval(&env(700.0, false, false)));
589        assert!(!c.eval(&env(600.0, true, false)));
590
591        let c = cond("(max-width: 400px), (min-width: 1200px)").unwrap();
592        assert!(c.eval(&env(300.0, false, false)));
593        assert!(!c.eval(&env(800.0, false, false)));
594        assert!(c.eval(&env(1300.0, false, false)));
595
596        let c = cond("not all and (min-width: 640px)").unwrap();
597        assert!(c.eval(&env(600.0, false, false)));
598        assert!(!c.eval(&env(700.0, false, false)));
599
600        let c = cond("(width > 300px) or (prefers-reduced-motion: reduce)").unwrap();
601        assert!(c.eval(&env(100.0, false, true)));
602        assert!(!c.eval(&env(100.0, false, false)));
603    }
604
605    #[test]
606    fn unsupported_features_are_rejected_not_silently_compiled() {
607        for prelude in [
608            "(hover: sometimes)",
609            "(orientation: landscape)",
610            "(prefers-contrast: more)",
611            "tv",
612            "(min-width: 40em)",
613            "(aspect-ratio: 16/9)",
614        ] {
615            assert!(cond(prelude).is_err(), "{prelude} should be rejected");
616        }
617    }
618
619    #[test]
620    fn dynamic_range_high_follows_the_window_and_standard_always_matches() {
621        let sdr = Env::default();
622        let hdr = Env {
623            dynamic_range_high: true,
624            ..Env::default()
625        };
626        let t = |q: &str, env: &Env| cond(q).unwrap().eval(env);
627        for feature in ["dynamic-range", "video-dynamic-range"] {
628            assert!(!t(&format!("({feature}: high)"), &sdr));
629            assert!(t(&format!("({feature}: high)"), &hdr));
630            assert!(t(&format!("({feature}: standard)"), &sdr));
631            assert!(t(&format!("({feature}: standard)"), &hdr));
632            assert!(cond(&format!("({feature}: wide)")).is_err());
633        }
634    }
635
636    #[test]
637    fn the_pointer_and_hover_features_answer_for_a_desktop_window() {
638        let mouse = Env::default();
639        let touch = Env {
640            coarse_pointer: true,
641            ..Env::default()
642        };
643        let t = |q: &str, env: &Env| cond(q).unwrap().eval(env);
644
645        for env in [&mouse, &touch] {
646            assert!(
647                t("(pointer: fine)", env),
648                "the primary pointer is the mouse"
649            );
650            assert!(!t("(pointer: coarse)", env));
651            assert!(!t("(pointer: none)", env));
652            assert!(t("(hover: hover)", env));
653            assert!(!t("(hover: none)", env));
654            assert!(t("(any-hover: hover)", env), "the mouse can always hover");
655            assert!(!t("(any-hover: none)", env));
656            assert!(t("(any-pointer: fine)", env));
657            assert!(t("(pointer)", env) && t("(hover)", env));
658        }
659        assert!(!t("(any-pointer: coarse)", &mouse));
660        assert!(t("(any-pointer: coarse)", &touch));
661
662        assert!(t("not (pointer: coarse)", &mouse));
663        assert!(t("(hover: hover) and (pointer: fine)", &mouse));
664    }
665
666    /// `resolution` is the ONLY way a stylesheet (or `matchMedia`) can observe a DPI change —
667    /// `devicePixelRatio` has no event in any spec.
668    #[test]
669    fn resolution_normalises_every_unit_to_dppx() {
670        let hidpi = Env {
671            scale_factor: 2.0,
672            ..Env::default()
673        };
674        let lodpi = Env {
675            scale_factor: 1.0,
676            ..Env::default()
677        };
678
679        let c = cond("(min-resolution: 2dppx)").unwrap();
680        assert_eq!(c, Cond::Feature(Feature::Resolution(Cmp::Ge, 2.0)));
681        assert!(c.eval(&hidpi));
682        assert!(!c.eval(&lodpi));
683
684        assert_eq!(
685            cond("(min-resolution: 192dpi)").unwrap(),
686            Cond::Feature(Feature::Resolution(Cmp::Ge, 2.0))
687        );
688        let dpcm = cond("(min-resolution: 96dpcm)").unwrap();
689        assert!(dpcm.eval(&Env {
690            scale_factor: 3.0,
691            ..Env::default()
692        }));
693
694        assert!(cond("(resolution: 1.5dppx)").unwrap().eval(&Env {
695            scale_factor: 1.5,
696            ..Env::default()
697        }));
698        assert!(cond("(resolution > 1dppx)").unwrap().eval(&hidpi));
699        let i = cond("(1dppx < resolution < 3dppx)").unwrap();
700        assert!(i.eval(&hidpi));
701        assert!(!i.eval(&lodpi));
702        assert_eq!(cond("(resolution)").unwrap(), Cond::Always);
703    }
704
705    #[test]
706    fn display_mode_reports_the_chrome_mode() {
707        let wco = Env {
708            display_mode: DisplayMode::WindowControlsOverlay,
709            ..Env::default()
710        };
711        let standalone = Env {
712            display_mode: DisplayMode::Standalone,
713            ..Env::default()
714        };
715        let fs = Env {
716            display_mode: DisplayMode::Fullscreen,
717            ..Env::default()
718        };
719
720        let c = cond("(display-mode: window-controls-overlay)").unwrap();
721        assert!(c.eval(&wco));
722        assert!(!c.eval(&standalone));
723        assert!(!c.eval(&fs));
724
725        assert!(cond("(display-mode: standalone)")
726            .unwrap()
727            .eval(&standalone));
728        assert!(cond("(display-mode: fullscreen)").unwrap().eval(&fs));
729
730        let browser = cond("(display-mode: browser)").unwrap();
731        assert_eq!(browser, Cond::Never);
732        assert!(!browser.eval(&wco));
733
734        assert!(cond("(display-mode: nonsense)").is_err());
735    }
736}