1use 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 pub titlebar_area: Option<[f32; 4]>,
22 pub coarse_pointer: bool,
25 pub safe_area_insets: [f32; 4],
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum DisplayMode {
32 Standalone,
33 WindowControlsOverlay,
34 Fullscreen,
35}
36
37impl DisplayMode {
38 pub fn as_str(self) -> &'static str {
39 match self {
40 DisplayMode::Standalone => "standalone",
41 DisplayMode::WindowControlsOverlay => "window-controls-overlay",
42 DisplayMode::Fullscreen => "fullscreen",
43 }
44 }
45}
46
47impl Default for Env {
48 fn default() -> Self {
49 Env {
50 viewport_width: 1024.0,
51 viewport_height: 768.0,
52 dark: false,
53 reduce_motion: false,
54 scale_factor: 1.0,
55 display_mode: DisplayMode::WindowControlsOverlay,
56 titlebar_area: Some([0.0, 0.0, 1024.0, 32.0]),
57 coarse_pointer: false,
58 safe_area_insets: [0.0; 4],
59 }
60 }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq)]
64pub(crate) enum Cmp {
65 Lt,
66 Le,
67 Gt,
68 Ge,
69 Eq,
70}
71
72impl Cmp {
73 fn from(op: MediaFeatureComparison) -> Cmp {
74 match op {
75 MediaFeatureComparison::LessThan => Cmp::Lt,
76 MediaFeatureComparison::LessThanEqual => Cmp::Le,
77 MediaFeatureComparison::GreaterThan => Cmp::Gt,
78 MediaFeatureComparison::GreaterThanEqual => Cmp::Ge,
79 MediaFeatureComparison::Equal => Cmp::Eq,
80 }
81 }
82
83 fn flip(self) -> Cmp {
84 match self {
85 Cmp::Lt => Cmp::Gt,
86 Cmp::Le => Cmp::Ge,
87 Cmp::Gt => Cmp::Lt,
88 Cmp::Ge => Cmp::Le,
89 Cmp::Eq => Cmp::Eq,
90 }
91 }
92
93 fn eval(self, lhs: f32, rhs: f32) -> bool {
94 match self {
95 Cmp::Lt => lhs < rhs,
96 Cmp::Le => lhs <= rhs,
97 Cmp::Gt => lhs > rhs,
98 Cmp::Ge => lhs >= rhs,
99 Cmp::Eq => lhs == rhs,
102 }
103 }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub(crate) enum Feature {
108 Width(Cmp, f32),
109 Height(Cmp, f32),
110 ColorScheme(bool),
111 ReducedMotion(bool),
112 Resolution(Cmp, f32),
113 Display(DisplayMode),
114 Pointer { any: bool, want: PointerKind },
115 Hover { any: bool, want: bool },
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119pub(crate) enum PointerKind {
120 None,
121 Coarse,
122 Fine,
123}
124
125impl Feature {
126 fn eval(&self, env: &Env) -> bool {
127 match *self {
128 Feature::Width(cmp, px) => cmp.eval(env.viewport_width, px),
129 Feature::Height(cmp, px) => cmp.eval(env.viewport_height, px),
130 Feature::ColorScheme(dark) => env.dark == dark,
131 Feature::ReducedMotion(reduce) => env.reduce_motion == reduce,
132 Feature::Resolution(cmp, dppx) => cmp.eval(env.scale_factor, dppx),
133 Feature::Display(mode) => env.display_mode == mode,
134 Feature::Pointer { any, want } => match want {
138 PointerKind::None => false,
139 PointerKind::Fine => true,
140 PointerKind::Coarse => any && env.coarse_pointer,
141 },
142 Feature::Hover { any, want } => {
143 let _ = any;
144 want
145 }
146 }
147 }
148}
149
150#[derive(Clone, Debug, PartialEq)]
151pub(crate) enum Cond {
152 Always,
153 Never,
154 Feature(Feature),
155 Not(Box<Cond>),
156 And(Vec<Cond>),
157 Or(Vec<Cond>),
158}
159
160impl Cond {
161 pub(crate) fn eval(&self, env: &Env) -> bool {
162 match self {
163 Cond::Always => true,
164 Cond::Never => false,
165 Cond::Feature(f) => f.eval(env),
166 Cond::Not(c) => !c.eval(env),
167 Cond::And(cs) => cs.iter().all(|c| c.eval(env)),
168 Cond::Or(cs) => cs.iter().any(|c| c.eval(env)),
169 }
170 }
171
172 pub(crate) fn and(self, other: Cond) -> Cond {
173 match (self, other) {
174 (Cond::Never, _) | (_, Cond::Never) => Cond::Never,
175 (Cond::Always, c) | (c, Cond::Always) => c,
176 (Cond::And(mut a), Cond::And(b)) => {
177 a.extend(b);
178 Cond::And(a)
179 }
180 (Cond::And(mut a), c) => {
181 a.push(c);
182 Cond::And(a)
183 }
184 (c, Cond::And(mut b)) => {
185 b.insert(0, c);
186 Cond::And(b)
187 }
188 (a, b) => Cond::And(vec![a, b]),
189 }
190 }
191}
192
193pub(crate) type Unsupported = &'static str;
194
195pub(crate) const SUPPORTED: &str = "supported: `screen`/`all`/`print` media types, \
196 `width`/`min-width`/`max-width`, `height`/`min-height`/`max-height` (px lengths, \
197 range and interval syntax), `prefers-color-scheme`, `prefers-reduced-motion`, \
198 `resolution`/`min-resolution`/`max-resolution` (dppx/dpi/dpcm), `display-mode`, \
199 `pointer`/`any-pointer`, `hover`/`any-hover`, \
200 combined with `and`/`or`/`not`/`,`";
201
202pub(crate) fn parse_list(list: &MediaList<'_>) -> Result<Cond, Unsupported> {
203 let mut queries = Vec::with_capacity(list.media_queries.len());
204 for q in &list.media_queries {
205 queries.push(parse_query(q)?);
206 }
207 Ok(match queries.len() {
208 0 => Cond::Always,
209 1 => queries.pop().unwrap(),
210 _ => Cond::Or(queries),
211 })
212}
213
214fn parse_query(q: &MediaQuery<'_>) -> Result<Cond, Unsupported> {
215 let type_cond = match &q.media_type {
218 MediaType::All | MediaType::Screen => Cond::Always,
219 MediaType::Print => Cond::Never,
220 MediaType::Custom(_) => return Err("an unknown media type"),
221 };
222 let cond = match &q.condition {
223 Some(c) => type_cond.and(parse_condition(c)?),
224 None => type_cond,
225 };
226 Ok(match q.qualifier {
227 Some(Qualifier::Not) => match cond {
228 Cond::Always => Cond::Never,
229 Cond::Never => Cond::Always,
230 c => Cond::Not(Box::new(c)),
231 },
232 Some(Qualifier::Only) | None => cond,
233 })
234}
235
236fn parse_condition(c: &MediaCondition<'_>) -> Result<Cond, Unsupported> {
237 Ok(match c {
238 MediaCondition::Feature(f) => parse_feature(f)?,
239 MediaCondition::Not(inner) => Cond::Not(Box::new(parse_condition(inner)?)),
240 MediaCondition::Operation {
241 operator,
242 conditions,
243 } => {
244 let mut parsed = Vec::with_capacity(conditions.len());
245 for c in conditions {
246 parsed.push(parse_condition(c)?);
247 }
248 match operator {
249 Operator::And => Cond::And(parsed),
250 Operator::Or => Cond::Or(parsed),
251 }
252 }
253 MediaCondition::Unknown(_) => return Err("tokens the media parser could not interpret"),
254 })
255}
256
257fn standard(name: &MediaFeatureName<'_, MediaFeatureId>) -> Result<MediaFeatureId, Unsupported> {
258 match name {
259 MediaFeatureName::Standard(id) => Ok(*id),
260 MediaFeatureName::Custom(_) => Err("a custom media feature (`--var`)"),
261 MediaFeatureName::Unknown(_) => Err("an unknown media feature"),
262 }
263}
264
265fn length_px(value: &MediaFeatureValue<'_>) -> Result<f32, Unsupported> {
266 match value {
267 MediaFeatureValue::Length(l) => l
268 .to_px()
269 .ok_or("a media length that is not convertible to px (`em`/`%`/`calc()`/`env()`)"),
270 _ => Err("a media feature value of the wrong type"),
271 }
272}
273
274fn ident<'a>(value: &'a MediaFeatureValue<'_>) -> Result<&'a str, Unsupported> {
275 match value {
276 MediaFeatureValue::Ident(i) => Ok(i.0.as_ref()),
277 _ => Err("a media feature value of the wrong type"),
278 }
279}
280
281fn dppx(value: &MediaFeatureValue<'_>) -> Result<f32, Unsupported> {
282 use lightningcss::values::resolution::Resolution;
283 match value {
284 MediaFeatureValue::Resolution(r) => Ok(match r {
285 Resolution::Dppx(v) => *v,
286 Resolution::Dpi(v) => *v / 96.0,
287 Resolution::Dpcm(v) => *v * 2.54 / 96.0,
288 }),
289 _ => Err("a media feature value of the wrong type"),
290 }
291}
292
293fn display_mode(value: &MediaFeatureValue<'_>) -> Result<Cond, Unsupported> {
296 Ok(match ident(value)? {
297 "standalone" => Cond::Feature(Feature::Display(DisplayMode::Standalone)),
298 "window-controls-overlay" => {
299 Cond::Feature(Feature::Display(DisplayMode::WindowControlsOverlay))
300 }
301 "fullscreen" => Cond::Feature(Feature::Display(DisplayMode::Fullscreen)),
302 "browser" | "minimal-ui" | "picture-in-picture" => Cond::Never,
303 _ => return Err("an unknown `display-mode` value"),
304 })
305}
306
307fn sized(id: MediaFeatureId, cmp: Cmp, px: f32) -> Feature {
308 match id {
309 MediaFeatureId::Width => Feature::Width(cmp, px),
310 _ => Feature::Height(cmp, px),
311 }
312}
313
314fn pointer(value: &MediaFeatureValue<'_>, any: bool) -> Result<Cond, Unsupported> {
315 Ok(Cond::Feature(Feature::Pointer {
316 any,
317 want: match ident(value)? {
318 "none" => PointerKind::None,
319 "coarse" => PointerKind::Coarse,
320 "fine" => PointerKind::Fine,
321 _ => return Err("an unknown `pointer` value"),
322 },
323 }))
324}
325
326fn hover(value: &MediaFeatureValue<'_>, any: bool) -> Result<Cond, Unsupported> {
327 Ok(Cond::Feature(Feature::Hover {
328 any,
329 want: match ident(value)? {
330 "hover" => true,
331 "none" => false,
332 _ => return Err("an unknown `hover` value"),
333 },
334 }))
335}
336
337fn parse_feature(f: &MediaFeature<'_>) -> Result<Cond, Unsupported> {
338 use MediaFeatureId::{
339 AnyHover, AnyPointer, DisplayMode as DisplayModeId, Height, Hover as HoverId,
340 Pointer as PointerId, PrefersColorScheme, PrefersReducedMotion, Resolution, Width,
341 };
342 Ok(match f {
343 QueryFeature::Plain { name, value } => match standard(name)? {
344 id @ (Width | Height) => Cond::Feature(sized(id, Cmp::Eq, length_px(value)?)),
345 Resolution => Cond::Feature(Feature::Resolution(Cmp::Eq, dppx(value)?)),
346 DisplayModeId => display_mode(value)?,
347 PointerId => pointer(value, false)?,
348 AnyPointer => pointer(value, true)?,
349 HoverId => hover(value, false)?,
350 AnyHover => hover(value, true)?,
351 PrefersColorScheme => match ident(value)? {
352 "dark" => Cond::Feature(Feature::ColorScheme(true)),
353 "light" => Cond::Feature(Feature::ColorScheme(false)),
354 _ => return Err("an unknown `prefers-color-scheme` value"),
355 },
356 PrefersReducedMotion => match ident(value)? {
357 "reduce" => Cond::Feature(Feature::ReducedMotion(true)),
358 "no-preference" => Cond::Feature(Feature::ReducedMotion(false)),
359 _ => return Err("an unknown `prefers-reduced-motion` value"),
360 },
361 _ => return Err("an unsupported media feature"),
362 },
363 QueryFeature::Boolean { name } => match standard(name)? {
364 Width | Height => Cond::Always,
365 PrefersColorScheme => Cond::Always,
366 PrefersReducedMotion => Cond::Feature(Feature::ReducedMotion(true)),
367 PointerId | AnyPointer | HoverId | AnyHover => Cond::Always,
368 Resolution | DisplayModeId => Cond::Always,
369 _ => return Err("an unsupported media feature"),
370 },
371 QueryFeature::Range {
372 name,
373 operator,
374 value,
375 } => match standard(name)? {
376 id @ (Width | Height) => {
377 Cond::Feature(sized(id, Cmp::from(*operator), length_px(value)?))
378 }
379 Resolution => Cond::Feature(Feature::Resolution(Cmp::from(*operator), dppx(value)?)),
380 _ => return Err("a range comparison on a feature that has no numeric value"),
381 },
382 QueryFeature::Interval {
383 name,
384 start,
385 start_operator,
386 end,
387 end_operator,
388 } => match standard(name)? {
389 id @ (Width | Height) => Cond::And(vec![
390 Cond::Feature(sized(
391 id,
392 Cmp::from(*start_operator).flip(),
393 length_px(start)?,
394 )),
395 Cond::Feature(sized(id, Cmp::from(*end_operator), length_px(end)?)),
396 ]),
397 Resolution => Cond::And(vec![
398 Cond::Feature(Feature::Resolution(
399 Cmp::from(*start_operator).flip(),
400 dppx(start)?,
401 )),
402 Cond::Feature(Feature::Resolution(Cmp::from(*end_operator), dppx(end)?)),
403 ]),
404 _ => return Err("a range comparison on a feature that has no numeric value"),
405 },
406 })
407}
408
409pub fn match_media(query: &str, env: &Env) -> Result<bool, String> {
412 use lightningcss::rules::CssRule;
413 use lightningcss::stylesheet::{ParserOptions, StyleSheet};
414
415 let css = format!("@media {query} {{ }}");
416 let sheet = StyleSheet::parse(&css, ParserOptions::default())
417 .map_err(|e| format!("could not be parsed ({e})"))?;
418 let Some(CssRule::Media(m)) = sheet.rules.0.first() else {
419 return Err("is not a media query".to_string());
420 };
421 parse_list(&m.query)
422 .map(|cond| cond.eval(env))
423 .map_err(|why| format!("uses {why} — {SUPPORTED}"))
424}
425
426pub(crate) fn list_text(list: &MediaList<'_>) -> String {
427 list.to_css_string(lightningcss::printer::PrinterOptions::default())
428 .unwrap_or_else(|_| "<media query>".into())
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434 use lightningcss::rules::CssRule;
435 use lightningcss::stylesheet::{ParserOptions, StyleSheet};
436
437 fn cond(prelude: &str) -> Result<Cond, Unsupported> {
438 let css = format!("@media {prelude} {{ .x {{ color: red }} }}");
439 let sheet = StyleSheet::parse(&css, ParserOptions::default()).expect("parses");
440 match &sheet.rules.0[0] {
441 CssRule::Media(m) => parse_list(&m.query),
442 other => panic!("expected @media, got {other:?}"),
443 }
444 }
445
446 fn env(w: f32, dark: bool, reduce: bool) -> Env {
447 Env {
448 viewport_width: w,
449 viewport_height: 800.0,
450 dark,
451 reduce_motion: reduce,
452 ..Env::default()
453 }
454 }
455
456 #[test]
457 fn min_width_becomes_a_ge_range() {
458 let c = cond("(min-width: 640px)").unwrap();
459 assert_eq!(c, Cond::Feature(Feature::Width(Cmp::Ge, 640.0)));
460 assert!(!c.eval(&env(639.0, false, false)));
461 assert!(c.eval(&env(640.0, false, false)));
462 assert!(c.eval(&env(1200.0, false, false)));
463 }
464
465 #[test]
466 fn max_width_is_inclusive_like_a_browser() {
467 let c = cond("(max-width: 640px)").unwrap();
468 assert_eq!(c, Cond::Feature(Feature::Width(Cmp::Le, 640.0)));
469 assert!(c.eval(&env(640.0, false, false)));
470 assert!(!c.eval(&env(641.0, false, false)));
471 }
472
473 #[test]
474 fn range_and_interval_syntax() {
475 assert!(cond("(width > 400px)")
476 .unwrap()
477 .eval(&env(500.0, false, false)));
478 assert!(!cond("(width > 400px)")
479 .unwrap()
480 .eval(&env(400.0, false, false)));
481 let i = cond("(400px < width < 800px)").unwrap();
482 assert!(!i.eval(&env(400.0, false, false)));
483 assert!(i.eval(&env(401.0, false, false)));
484 assert!(i.eval(&env(799.0, false, false)));
485 assert!(!i.eval(&env(800.0, false, false)));
486 }
487
488 #[test]
489 fn screen_and_all_match_print_never_does() {
490 assert!(cond("screen").unwrap().eval(&Env::default()));
491 assert!(cond("all").unwrap().eval(&Env::default()));
492 assert_eq!(cond("print").unwrap(), Cond::Never);
493 assert!(!cond("print").unwrap().eval(&Env::default()));
494 assert_eq!(
495 cond("screen and (min-width: 100px)").unwrap(),
496 Cond::Feature(Feature::Width(Cmp::Ge, 100.0))
497 );
498 }
499
500 #[test]
501 fn color_scheme_and_reduced_motion() {
502 let dark = cond("(prefers-color-scheme: dark)").unwrap();
503 assert!(dark.eval(&env(800.0, true, false)));
504 assert!(!dark.eval(&env(800.0, false, false)));
505 let light = cond("(prefers-color-scheme: light)").unwrap();
506 assert!(light.eval(&env(800.0, false, false)));
507 let rm = cond("(prefers-reduced-motion: reduce)").unwrap();
508 assert!(rm.eval(&env(800.0, false, true)));
509 assert!(!rm.eval(&env(800.0, false, false)));
510 assert!(cond("(prefers-reduced-motion: no-preference)")
511 .unwrap()
512 .eval(&env(800.0, false, false)));
513 }
514
515 #[test]
516 fn and_or_not_and_comma_combine() {
517 let c = cond("(min-width: 640px) and (prefers-color-scheme: dark)").unwrap();
518 assert!(c.eval(&env(700.0, true, false)));
519 assert!(!c.eval(&env(700.0, false, false)));
520 assert!(!c.eval(&env(600.0, true, false)));
521
522 let c = cond("(max-width: 400px), (min-width: 1200px)").unwrap();
523 assert!(c.eval(&env(300.0, false, false)));
524 assert!(!c.eval(&env(800.0, false, false)));
525 assert!(c.eval(&env(1300.0, false, false)));
526
527 let c = cond("not all and (min-width: 640px)").unwrap();
528 assert!(c.eval(&env(600.0, false, false)));
529 assert!(!c.eval(&env(700.0, false, false)));
530
531 let c = cond("(width > 300px) or (prefers-reduced-motion: reduce)").unwrap();
532 assert!(c.eval(&env(100.0, false, true)));
533 assert!(!c.eval(&env(100.0, false, false)));
534 }
535
536 #[test]
537 fn unsupported_features_are_rejected_not_silently_compiled() {
538 for prelude in [
539 "(hover: sometimes)",
540 "(orientation: landscape)",
541 "(prefers-contrast: more)",
542 "tv",
543 "(min-width: 40em)",
544 "(aspect-ratio: 16/9)",
545 ] {
546 assert!(cond(prelude).is_err(), "{prelude} should be rejected");
547 }
548 }
549
550 #[test]
551 fn the_pointer_and_hover_features_answer_for_a_desktop_window() {
552 let mouse = Env::default();
553 let touch = Env {
554 coarse_pointer: true,
555 ..Env::default()
556 };
557 let t = |q: &str, env: &Env| cond(q).unwrap().eval(env);
558
559 for env in [&mouse, &touch] {
560 assert!(
561 t("(pointer: fine)", env),
562 "the primary pointer is the mouse"
563 );
564 assert!(!t("(pointer: coarse)", env));
565 assert!(!t("(pointer: none)", env));
566 assert!(t("(hover: hover)", env));
567 assert!(!t("(hover: none)", env));
568 assert!(t("(any-hover: hover)", env), "the mouse can always hover");
569 assert!(!t("(any-hover: none)", env));
570 assert!(t("(any-pointer: fine)", env));
571 assert!(t("(pointer)", env) && t("(hover)", env));
572 }
573 assert!(!t("(any-pointer: coarse)", &mouse));
574 assert!(t("(any-pointer: coarse)", &touch));
575
576 assert!(t("not (pointer: coarse)", &mouse));
577 assert!(t("(hover: hover) and (pointer: fine)", &mouse));
578 }
579
580 #[test]
583 fn resolution_normalises_every_unit_to_dppx() {
584 let hidpi = Env {
585 scale_factor: 2.0,
586 ..Env::default()
587 };
588 let lodpi = Env {
589 scale_factor: 1.0,
590 ..Env::default()
591 };
592
593 let c = cond("(min-resolution: 2dppx)").unwrap();
594 assert_eq!(c, Cond::Feature(Feature::Resolution(Cmp::Ge, 2.0)));
595 assert!(c.eval(&hidpi));
596 assert!(!c.eval(&lodpi));
597
598 assert_eq!(
599 cond("(min-resolution: 192dpi)").unwrap(),
600 Cond::Feature(Feature::Resolution(Cmp::Ge, 2.0))
601 );
602 let dpcm = cond("(min-resolution: 96dpcm)").unwrap();
603 assert!(dpcm.eval(&Env {
604 scale_factor: 3.0,
605 ..Env::default()
606 }));
607
608 assert!(cond("(resolution: 1.5dppx)").unwrap().eval(&Env {
609 scale_factor: 1.5,
610 ..Env::default()
611 }));
612 assert!(cond("(resolution > 1dppx)").unwrap().eval(&hidpi));
613 let i = cond("(1dppx < resolution < 3dppx)").unwrap();
614 assert!(i.eval(&hidpi));
615 assert!(!i.eval(&lodpi));
616 assert_eq!(cond("(resolution)").unwrap(), Cond::Always);
617 }
618
619 #[test]
620 fn display_mode_reports_the_chrome_mode() {
621 let wco = Env {
622 display_mode: DisplayMode::WindowControlsOverlay,
623 ..Env::default()
624 };
625 let standalone = Env {
626 display_mode: DisplayMode::Standalone,
627 ..Env::default()
628 };
629 let fs = Env {
630 display_mode: DisplayMode::Fullscreen,
631 ..Env::default()
632 };
633
634 let c = cond("(display-mode: window-controls-overlay)").unwrap();
635 assert!(c.eval(&wco));
636 assert!(!c.eval(&standalone));
637 assert!(!c.eval(&fs));
638
639 assert!(cond("(display-mode: standalone)")
640 .unwrap()
641 .eval(&standalone));
642 assert!(cond("(display-mode: fullscreen)").unwrap().eval(&fs));
643
644 let browser = cond("(display-mode: browser)").unwrap();
645 assert_eq!(browser, Cond::Never);
646 assert!(!browser.eval(&wco));
647
648 assert!(cond("(display-mode: nonsense)").is_err());
649 }
650}