Skip to main content

rspack_lightningcss/
media_query.rs

1//! Media queries.
2use crate::error::{ErrorWithLocation, MinifyError, MinifyErrorKind, ParserError, PrinterError};
3use crate::macros::enum_property;
4use crate::parser::starts_with_ignore_ascii_case;
5use crate::properties::custom::{EnvironmentVariable, TokenList};
6#[cfg(feature = "visitor")]
7use crate::rules::container::{ContainerSizeFeatureId, ScrollStateFeatureId};
8use crate::rules::custom_media::CustomMediaRule;
9use crate::rules::Location;
10use crate::stylesheet::ParserOptions;
11use crate::targets::{should_compile, Targets};
12use crate::traits::{Parse, ParseWithOptions, ToCss};
13use crate::values::ident::{DashedIdent, Ident};
14use crate::values::number::{CSSInteger, CSSNumber};
15use crate::values::string::CowArcStr;
16use crate::values::{length::Length, ratio::Ratio, resolution::Resolution};
17use crate::vendor_prefix::VendorPrefix;
18#[cfg(feature = "visitor")]
19use crate::visitor::Visit;
20use bitflags::bitflags;
21use cssparser::*;
22#[cfg(feature = "into_owned")]
23use rspack_lightningcss_static_self::IntoOwned;
24use std::borrow::Cow;
25use std::collections::{HashMap, HashSet};
26
27#[cfg(feature = "serde")]
28use crate::serialization::ValueWrapper;
29
30/// A [media query list](https://drafts.csswg.org/mediaqueries/#mq-list).
31#[derive(Clone, Debug, PartialEq, Default)]
32#[cfg_attr(feature = "visitor", derive(Visit), visit(visit_media_list, MEDIA_QUERIES))]
33#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
34#[cfg_attr(
35  feature = "serde",
36  derive(serde::Serialize, serde::Deserialize),
37  serde(rename_all = "camelCase")
38)]
39#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
40pub struct MediaList<'i> {
41  /// The list of media queries.
42  #[cfg_attr(feature = "serde", serde(borrow))]
43  pub media_queries: Vec<MediaQuery<'i>>,
44}
45
46impl<'i> MediaList<'i> {
47  /// Creates an empty media query list.
48  pub fn new() -> Self {
49    MediaList { media_queries: vec![] }
50  }
51
52  /// Parse a media query list from CSS.
53  pub fn parse<'t>(
54    input: &mut Parser<'i, 't>,
55    options: &ParserOptions<'i>,
56  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
57    let mut media_queries = vec![];
58    if input.is_exhausted() {
59      return Ok(MediaList { media_queries });
60    }
61
62    loop {
63      match input.parse_until_before(Delimiter::Comma, |i| MediaQuery::parse_with_options(i, options)) {
64        Ok(mq) => {
65          media_queries.push(mq);
66        }
67        Err(err) => match err.kind {
68          ParseErrorKind::Basic(BasicParseErrorKind::EndOfInput) => break,
69          _ => return Err(err),
70        },
71      }
72
73      match input.next() {
74        Ok(&Token::Comma) => {}
75        Ok(_) => unreachable!(),
76        Err(_) => break,
77      }
78    }
79
80    Ok(MediaList { media_queries })
81  }
82
83  pub(crate) fn transform_custom_media(
84    &mut self,
85    loc: Location,
86    custom_media: &HashMap<CowArcStr<'i>, CustomMediaRule<'i>>,
87  ) -> Result<(), MinifyError> {
88    for query in self.media_queries.iter_mut() {
89      query.transform_custom_media(loc, custom_media)?;
90    }
91    Ok(())
92  }
93
94  pub(crate) fn transform_resolution(&mut self, targets: Targets) {
95    let mut i = 0;
96    while i < self.media_queries.len() {
97      let query = &self.media_queries[i];
98      let mut prefixes = query.get_necessary_prefixes(targets);
99      prefixes.remove(VendorPrefix::None);
100      if !prefixes.is_empty() {
101        let query = query.clone();
102        for prefix in prefixes {
103          let mut transformed = query.clone();
104          transformed.transform_resolution(prefix);
105          if !self.media_queries.contains(&transformed) {
106            self.media_queries.insert(i, transformed);
107          }
108          i += 1;
109        }
110      }
111
112      i += 1;
113    }
114  }
115
116  /// Returns whether the media query list always matches.
117  pub fn always_matches(&self) -> bool {
118    // If the media list is empty, it always matches.
119    self.media_queries.is_empty() || self.media_queries.iter().all(|mq| mq.always_matches())
120  }
121
122  /// Returns whether the media query list never matches.
123  pub fn never_matches(&self) -> bool {
124    !self.media_queries.is_empty() && self.media_queries.iter().all(|mq| mq.never_matches())
125  }
126
127  /// Attempts to combine the given media query list into this one. The resulting media query
128  /// list matches if both the original media query lists would have matched.
129  ///
130  /// Returns an error if the boolean logic is not possible.
131  pub fn and(&mut self, b: &MediaList<'i>) -> Result<(), ()> {
132    if self.media_queries.is_empty() {
133      self.media_queries.extend(b.media_queries.iter().cloned());
134      return Ok(());
135    }
136
137    for b in &b.media_queries {
138      if self.media_queries.contains(&b) {
139        continue;
140      }
141
142      for a in &mut self.media_queries {
143        a.and(&b)?;
144      }
145    }
146
147    Ok(())
148  }
149
150  /// Combines the given media query list into this one. The resulting media query list
151  /// matches if either of the original media query lists would have matched.
152  pub fn or(&mut self, b: &MediaList<'i>) {
153    for mq in &b.media_queries {
154      if !self.media_queries.contains(&mq) {
155        self.media_queries.push(mq.clone())
156      }
157    }
158  }
159}
160
161impl<'i> ToCss for MediaList<'i> {
162  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
163    if self.media_queries.is_empty() {
164      dest.write_str("not all")?;
165      return Ok(());
166    }
167
168    let mut first = true;
169    for query in &self.media_queries {
170      if !first {
171        dest.delim(',', false)?;
172      }
173      first = false;
174      query.to_css(dest)?;
175    }
176    Ok(())
177  }
178}
179
180enum_property! {
181  /// A [media query qualifier](https://drafts.csswg.org/mediaqueries/#mq-prefix).
182  pub enum Qualifier {
183    /// Prevents older browsers from matching the media query.
184    Only,
185    /// Negates a media query.
186    Not,
187  }
188}
189
190/// A [media type](https://drafts.csswg.org/mediaqueries/#media-types) within a media query.
191#[derive(Clone, Debug, PartialEq)]
192#[cfg_attr(feature = "visitor", derive(Visit))]
193#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
194#[cfg_attr(
195  feature = "serde",
196  derive(serde::Serialize, serde::Deserialize),
197  serde(rename_all = "kebab-case", into = "CowArcStr", from = "CowArcStr")
198)]
199pub enum MediaType<'i> {
200  /// Matches all devices.
201  All,
202  /// Matches printers, and devices intended to reproduce a printed
203  /// display, such as a web browser showing a document in “Print Preview”.
204  Print,
205  /// Matches all devices that aren’t matched by print.
206  Screen,
207  /// An unknown media type.
208  #[cfg_attr(feature = "serde", serde(borrow))]
209  Custom(CowArcStr<'i>),
210}
211
212impl<'i> From<CowArcStr<'i>> for MediaType<'i> {
213  fn from(name: CowArcStr<'i>) -> Self {
214    match_ignore_ascii_case! { &*name,
215      "all" => MediaType::All,
216      "print" => MediaType::Print,
217      "screen" => MediaType::Screen,
218      _ => MediaType::Custom(name)
219    }
220  }
221}
222
223impl<'i> Into<CowArcStr<'i>> for MediaType<'i> {
224  fn into(self) -> CowArcStr<'i> {
225    match self {
226      MediaType::All => "all".into(),
227      MediaType::Print => "print".into(),
228      MediaType::Screen => "screen".into(),
229      MediaType::Custom(desc) => desc,
230    }
231  }
232}
233
234impl<'i> Parse<'i> for MediaType<'i> {
235  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
236    let name: CowArcStr = input.expect_ident()?.into();
237    Ok(Self::from(name))
238  }
239}
240
241#[cfg(feature = "jsonschema")]
242#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
243impl<'a> schemars::JsonSchema for MediaType<'a> {
244  fn is_referenceable() -> bool {
245    true
246  }
247
248  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
249    str::json_schema(gen)
250  }
251
252  fn schema_name() -> String {
253    "MediaType".into()
254  }
255}
256
257/// A [media query](https://drafts.csswg.org/mediaqueries/#media).
258#[derive(Clone, Debug, PartialEq)]
259#[cfg_attr(feature = "visitor", derive(Visit))]
260#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
261#[cfg_attr(feature = "visitor", visit(visit_media_query, MEDIA_QUERIES))]
262#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(rename_all = "camelCase"))]
263#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
264pub struct MediaQuery<'i> {
265  /// The qualifier for this query.
266  pub qualifier: Option<Qualifier>,
267  /// The media type for this query, that can be known, unknown, or "all".
268  #[cfg_attr(feature = "serde", serde(borrow))]
269  pub media_type: MediaType<'i>,
270  /// The condition that this media query contains. This cannot have `or`
271  /// in the first level.
272  pub condition: Option<MediaCondition<'i>>,
273}
274
275impl<'i> ParseWithOptions<'i> for MediaQuery<'i> {
276  fn parse_with_options<'t>(
277    input: &mut Parser<'i, 't>,
278    options: &ParserOptions<'i>,
279  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
280    let (qualifier, explicit_media_type) = input
281      .try_parse(|input| -> Result<_, ParseError<'i, ParserError<'i>>> {
282        let qualifier = input.try_parse(Qualifier::parse).ok();
283        let media_type = MediaType::parse(input)?;
284        Ok((qualifier, Some(media_type)))
285      })
286      .unwrap_or_default();
287
288    let condition = if explicit_media_type.is_none() {
289      Some(MediaCondition::parse_with_flags(
290        input,
291        QueryConditionFlags::ALLOW_OR,
292        options,
293      )?)
294    } else if input.try_parse(|i| i.expect_ident_matching("and")).is_ok() {
295      Some(MediaCondition::parse_with_flags(
296        input,
297        QueryConditionFlags::empty(),
298        options,
299      )?)
300    } else {
301      None
302    };
303
304    let media_type = explicit_media_type.unwrap_or(MediaType::All);
305    Ok(Self {
306      qualifier,
307      media_type,
308      condition,
309    })
310  }
311}
312
313impl<'i> MediaQuery<'i> {
314  fn transform_custom_media(
315    &mut self,
316    loc: Location,
317    custom_media: &HashMap<CowArcStr<'i>, CustomMediaRule<'i>>,
318  ) -> Result<(), MinifyError> {
319    if let Some(condition) = &mut self.condition {
320      let used = process_condition(
321        loc,
322        custom_media,
323        &mut self.media_type,
324        &mut self.qualifier,
325        condition,
326        &mut HashSet::new(),
327      )?;
328      if !used {
329        self.condition = None;
330      }
331    }
332    Ok(())
333  }
334
335  fn get_necessary_prefixes(&self, targets: Targets) -> VendorPrefix {
336    if let Some(condition) = &self.condition {
337      condition.get_necessary_prefixes(targets)
338    } else {
339      VendorPrefix::empty()
340    }
341  }
342
343  fn transform_resolution(&mut self, prefix: VendorPrefix) {
344    if let Some(condition) = &mut self.condition {
345      condition.transform_resolution(prefix)
346    }
347  }
348
349  /// Returns whether the media query is guaranteed to always match.
350  pub fn always_matches(&self) -> bool {
351    self.qualifier == None && self.media_type == MediaType::All && self.condition == None
352  }
353
354  /// Returns whether the media query is guaranteed to never match.
355  pub fn never_matches(&self) -> bool {
356    self.qualifier == Some(Qualifier::Not) && self.media_type == MediaType::All && self.condition == None
357  }
358
359  /// Attempts to combine the given media query into this one. The resulting media query
360  /// matches if both of the original media queries would have matched.
361  ///
362  /// Returns an error if the boolean logic is not possible.
363  pub fn and<'a>(&mut self, b: &MediaQuery<'i>) -> Result<(), ()> {
364    let at = (&self.qualifier, &self.media_type);
365    let bt = (&b.qualifier, &b.media_type);
366    let (qualifier, media_type) = match (at, bt) {
367      // `not all and screen` => not all
368      // `screen and not all` => not all
369      ((&Some(Qualifier::Not), &MediaType::All), _) |
370      (_, (&Some(Qualifier::Not), &MediaType::All)) => (Some(Qualifier::Not), MediaType::All),
371      // `not screen and not print` => ERROR
372      // `not screen and not screen` => not screen
373      ((&Some(Qualifier::Not), a), (&Some(Qualifier::Not), b)) => {
374        if a == b {
375          (Some(Qualifier::Not), a.clone())
376        } else {
377          return Err(())
378        }
379      },
380      // `all and print` => print
381      // `print and all` => print
382      // `all and not print` => not print
383      ((_, MediaType::All), (q, t)) |
384      ((q, t), (_, MediaType::All)) |
385      // `not screen and print` => print
386      // `print and not screen` => print
387      ((&Some(Qualifier::Not), _), (q, t)) |
388      ((q, t), (&Some(Qualifier::Not), _)) => (q.clone(), t.clone()),
389      // `print and screen` => not all
390      ((_, a), (_, b)) if a != b => (Some(Qualifier::Not), MediaType::All),
391      ((_, a), _) => (None, a.clone())
392    };
393
394    self.qualifier = qualifier;
395    self.media_type = media_type;
396
397    if let Some(cond) = &b.condition {
398      self.condition = if let Some(condition) = &self.condition {
399        if condition != cond {
400          Some(MediaCondition::Operation {
401            conditions: vec![condition.clone(), cond.clone()],
402            operator: Operator::And,
403          })
404        } else {
405          Some(condition.clone())
406        }
407      } else {
408        Some(cond.clone())
409      }
410    }
411
412    Ok(())
413  }
414}
415
416impl<'i> ToCss for MediaQuery<'i> {
417  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
418    if let Some(qual) = self.qualifier {
419      qual.to_css(dest)?;
420      dest.write_char(' ')?;
421    }
422
423    match self.media_type {
424      MediaType::All => {
425        // We need to print "all" if there's a qualifier, or there's
426        // just an empty list of expressions.
427        //
428        // Otherwise, we'd serialize media queries like "(min-width:
429        // 40px)" in "all (min-width: 40px)", which is unexpected.
430        if self.qualifier.is_some() || self.condition.is_none() {
431          dest.write_str("all")?;
432        }
433      }
434      MediaType::Print => dest.write_str("print")?,
435      MediaType::Screen => dest.write_str("screen")?,
436      MediaType::Custom(ref desc) => dest.write_str(desc)?,
437    }
438
439    let condition = match self.condition {
440      Some(ref c) => c,
441      None => return Ok(()),
442    };
443
444    let needs_parens = if self.media_type != MediaType::All || self.qualifier.is_some() {
445      dest.write_str(" and ")?;
446      matches!(condition, MediaCondition::Operation { operator, .. } if *operator != Operator::And)
447    } else {
448      false
449    };
450
451    to_css_with_parens_if_needed(condition, dest, needs_parens)
452  }
453}
454
455#[cfg(feature = "serde")]
456#[derive(serde::Deserialize)]
457#[serde(untagged)]
458#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
459enum MediaQueryOrRaw<'i> {
460  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
461  MediaQuery {
462    qualifier: Option<Qualifier>,
463    #[cfg_attr(feature = "serde", serde(borrow))]
464    media_type: MediaType<'i>,
465    condition: Option<MediaCondition<'i>>,
466  },
467  Raw {
468    raw: CowArcStr<'i>,
469  },
470}
471
472#[cfg(feature = "serde")]
473impl<'i, 'de: 'i> serde::Deserialize<'de> for MediaQuery<'i> {
474  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
475  where
476    D: serde::Deserializer<'de>,
477  {
478    let mq = MediaQueryOrRaw::deserialize(deserializer)?;
479    match mq {
480      MediaQueryOrRaw::MediaQuery {
481        qualifier,
482        media_type,
483        condition,
484      } => Ok(MediaQuery {
485        qualifier,
486        media_type,
487        condition,
488      }),
489      MediaQueryOrRaw::Raw { raw } => {
490        let res = MediaQuery::parse_string_with_options(raw.as_ref(), ParserOptions::default())
491          .map_err(|_| serde::de::Error::custom("Could not parse value"))?;
492        Ok(res.into_owned())
493      }
494    }
495  }
496}
497
498enum_property! {
499  /// A binary `and` or `or` operator.
500  pub enum Operator {
501    /// The `and` operator.
502    And,
503    /// The `or` operator.
504    Or,
505  }
506}
507
508/// Represents a media condition.
509#[derive(Clone, Debug, PartialEq)]
510#[cfg_attr(feature = "visitor", derive(Visit))]
511#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
512#[cfg_attr(
513  feature = "serde",
514  derive(serde::Serialize, serde::Deserialize),
515  serde(tag = "type", rename_all = "kebab-case")
516)]
517#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
518pub enum MediaCondition<'i> {
519  /// A media feature, implicitly parenthesized.
520  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<MediaFeature>"))]
521  Feature(MediaFeature<'i>),
522  /// A negation of a condition.
523  #[cfg_attr(feature = "visitor", skip_type)]
524  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<MediaCondition>>"))]
525  Not(Box<MediaCondition<'i>>),
526  /// A set of joint operations.
527  #[cfg_attr(feature = "visitor", skip_type)]
528  Operation {
529    /// The operator for the conditions.
530    operator: Operator,
531    /// The conditions for the operator.
532    conditions: Vec<MediaCondition<'i>>,
533  },
534  /// Unknown tokens.
535  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<TokenList>"))]
536  Unknown(TokenList<'i>),
537}
538
539/// A trait for conditions such as media queries and container queries.
540pub(crate) trait QueryCondition<'i>: Sized {
541  fn parse_feature<'t>(
542    input: &mut Parser<'i, 't>,
543    options: &ParserOptions<'i>,
544  ) -> Result<Self, ParseError<'i, ParserError<'i>>>;
545  fn create_negation(condition: Box<Self>) -> Self;
546  fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self;
547  fn parse_style_query<'t>(
548    input: &mut Parser<'i, 't>,
549    _options: &ParserOptions<'i>,
550  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
551    Err(input.new_error_for_next_token())
552  }
553
554  fn parse_scroll_state_query<'t>(
555    input: &mut Parser<'i, 't>,
556    _options: &ParserOptions<'i>,
557  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
558    Err(input.new_error_for_next_token())
559  }
560
561  fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool;
562}
563
564impl<'i> QueryCondition<'i> for MediaCondition<'i> {
565  #[inline]
566  fn parse_feature<'t>(
567    input: &mut Parser<'i, 't>,
568    options: &ParserOptions<'i>,
569  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
570    let feature = MediaFeature::parse_with_options(input, options)?;
571    Ok(Self::Feature(feature))
572  }
573
574  #[inline]
575  fn create_negation(condition: Box<MediaCondition<'i>>) -> Self {
576    Self::Not(condition)
577  }
578
579  #[inline]
580  fn create_operation(operator: Operator, conditions: Vec<MediaCondition<'i>>) -> Self {
581    Self::Operation { operator, conditions }
582  }
583
584  fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool {
585    match self {
586      MediaCondition::Not(_) => true,
587      MediaCondition::Operation { operator, .. } => Some(*operator) != parent_operator,
588      MediaCondition::Feature(f) => f.needs_parens(parent_operator, targets),
589      MediaCondition::Unknown(_) => false,
590    }
591  }
592}
593
594bitflags! {
595  /// Flags for `parse_query_condition`.
596  #[derive(PartialEq, Eq, Clone, Copy)]
597  pub(crate) struct QueryConditionFlags: u8 {
598    /// Whether to allow top-level "or" boolean logic.
599    const ALLOW_OR = 1 << 0;
600    /// Whether to allow style container queries.
601    const ALLOW_STYLE = 1 << 1;
602    /// Whether to allow scroll state container queries.
603    const ALLOW_SCROLL_STATE = 1 << 2;
604  }
605}
606
607impl<'i> MediaCondition<'i> {
608  /// Parse a single media condition.
609  fn parse_with_flags<'t>(
610    input: &mut Parser<'i, 't>,
611    flags: QueryConditionFlags,
612    options: &ParserOptions<'i>,
613  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
614    input
615      .try_parse(|input| parse_query_condition(input, flags, options))
616      .or_else(|e| {
617        if options.error_recovery {
618          options.warn(e);
619          Ok(MediaCondition::Unknown(TokenList::parse(input, options, 0)?))
620        } else {
621          Err(e)
622        }
623      })
624  }
625
626  fn get_necessary_prefixes(&self, targets: Targets) -> VendorPrefix {
627    match self {
628      MediaCondition::Feature(MediaFeature::Range {
629        name: MediaFeatureName::Standard(MediaFeatureId::Resolution),
630        ..
631      }) => targets.prefixes(VendorPrefix::None, crate::prefixes::Feature::AtResolution),
632      MediaCondition::Not(not) => not.get_necessary_prefixes(targets),
633      MediaCondition::Operation { conditions, .. } => {
634        let mut prefixes = VendorPrefix::empty();
635        for condition in conditions {
636          prefixes |= condition.get_necessary_prefixes(targets);
637        }
638        prefixes
639      }
640      _ => VendorPrefix::empty(),
641    }
642  }
643
644  fn transform_resolution(&mut self, prefix: VendorPrefix) {
645    match self {
646      MediaCondition::Feature(MediaFeature::Range {
647        name: MediaFeatureName::Standard(MediaFeatureId::Resolution),
648        operator,
649        value: MediaFeatureValue::Resolution(value),
650      }) => match prefix {
651        VendorPrefix::WebKit | VendorPrefix::Moz => {
652          *self = MediaCondition::Feature(MediaFeature::Range {
653            name: MediaFeatureName::Standard(match prefix {
654              VendorPrefix::WebKit => MediaFeatureId::WebKitDevicePixelRatio,
655              VendorPrefix::Moz => MediaFeatureId::MozDevicePixelRatio,
656              _ => unreachable!(),
657            }),
658            operator: *operator,
659            value: MediaFeatureValue::Number(match value {
660              Resolution::Dpi(dpi) => *dpi / 96.0,
661              Resolution::Dpcm(dpcm) => *dpcm * 2.54 / 96.0,
662              Resolution::Dppx(dppx) => *dppx,
663            }),
664          });
665        }
666        _ => {}
667      },
668      MediaCondition::Not(not) => not.transform_resolution(prefix),
669      MediaCondition::Operation { conditions, .. } => {
670        for condition in conditions {
671          condition.transform_resolution(prefix);
672        }
673      }
674      _ => {}
675    }
676  }
677}
678
679impl<'i> ParseWithOptions<'i> for MediaCondition<'i> {
680  fn parse_with_options<'t>(
681    input: &mut Parser<'i, 't>,
682    options: &ParserOptions<'i>,
683  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
684    Self::parse_with_flags(input, QueryConditionFlags::ALLOW_OR, options)
685  }
686}
687
688/// Parse a single query condition.
689pub(crate) fn parse_query_condition<'t, 'i, P: QueryCondition<'i>>(
690  input: &mut Parser<'i, 't>,
691  flags: QueryConditionFlags,
692  options: &ParserOptions<'i>,
693) -> Result<P, ParseError<'i, ParserError<'i>>> {
694  let location = input.current_source_location();
695  enum QueryFunction {
696    None,
697    Style,
698    ScrollState,
699  }
700
701  let (is_negation, function) = match *input.next()? {
702    Token::ParenthesisBlock => (false, QueryFunction::None),
703    Token::Ident(ref ident) if ident.eq_ignore_ascii_case("not") => (true, QueryFunction::None),
704    Token::Function(ref f)
705      if flags.contains(QueryConditionFlags::ALLOW_STYLE) && f.eq_ignore_ascii_case("style") =>
706    {
707      (false, QueryFunction::Style)
708    }
709    Token::Function(ref f)
710      if flags.contains(QueryConditionFlags::ALLOW_SCROLL_STATE) && f.eq_ignore_ascii_case("scroll-state") =>
711    {
712      (false, QueryFunction::ScrollState)
713    }
714    ref t => return Err(location.new_unexpected_token_error(t.clone())),
715  };
716
717  let first_condition = match (is_negation, function) {
718    (true, QueryFunction::None) => {
719      let inner_condition = parse_parens_or_function(input, flags, options)?;
720      return Ok(P::create_negation(Box::new(inner_condition)));
721    }
722    (true, QueryFunction::Style) => {
723      let inner_condition = P::parse_style_query(input, options)?;
724      return Ok(P::create_negation(Box::new(inner_condition)));
725    }
726    (true, QueryFunction::ScrollState) => {
727      let inner_condition = P::parse_scroll_state_query(input, options)?;
728      return Ok(P::create_negation(Box::new(inner_condition)));
729    }
730    (false, QueryFunction::None) => parse_paren_block(input, flags, options)?,
731    (false, QueryFunction::Style) => P::parse_style_query(input, options)?,
732    (false, QueryFunction::ScrollState) => P::parse_scroll_state_query(input, options)?,
733  };
734
735  let operator = match input.try_parse(Operator::parse) {
736    Ok(op) => op,
737    Err(..) => return Ok(first_condition),
738  };
739
740  if !flags.contains(QueryConditionFlags::ALLOW_OR) && operator == Operator::Or {
741    return Err(location.new_unexpected_token_error(Token::Ident("or".into())));
742  }
743
744  let mut conditions = vec![];
745  conditions.push(first_condition);
746  conditions.push(parse_parens_or_function(input, flags, options)?);
747
748  let delim = match operator {
749    Operator::And => "and",
750    Operator::Or => "or",
751  };
752
753  loop {
754    if input.try_parse(|i| i.expect_ident_matching(delim)).is_err() {
755      return Ok(P::create_operation(operator, conditions));
756    }
757
758    conditions.push(parse_parens_or_function(input, flags, options)?);
759  }
760}
761
762/// Parse a media condition in parentheses, or a style() function.
763fn parse_parens_or_function<'t, 'i, P: QueryCondition<'i>>(
764  input: &mut Parser<'i, 't>,
765  flags: QueryConditionFlags,
766  options: &ParserOptions<'i>,
767) -> Result<P, ParseError<'i, ParserError<'i>>> {
768  let location = input.current_source_location();
769  match *input.next()? {
770    Token::ParenthesisBlock => parse_paren_block(input, flags, options),
771    Token::Function(ref f)
772      if flags.contains(QueryConditionFlags::ALLOW_STYLE) && f.eq_ignore_ascii_case("style") =>
773    {
774      P::parse_style_query(input, options)
775    }
776    Token::Function(ref f)
777      if flags.contains(QueryConditionFlags::ALLOW_SCROLL_STATE) && f.eq_ignore_ascii_case("scroll-state") =>
778    {
779      P::parse_scroll_state_query(input, options)
780    }
781    ref t => return Err(location.new_unexpected_token_error(t.clone())),
782  }
783}
784
785fn parse_paren_block<'t, 'i, P: QueryCondition<'i>>(
786  input: &mut Parser<'i, 't>,
787  flags: QueryConditionFlags,
788  options: &ParserOptions<'i>,
789) -> Result<P, ParseError<'i, ParserError<'i>>> {
790  input.parse_nested_block(|input| {
791    // Detect empty brackets and provide a clearer error message.
792    if input.is_exhausted() {
793      return Err(input.new_custom_error(ParserError::EmptyBracketInCondition));
794    }
795
796    if let Ok(inner) =
797      input.try_parse(|i| parse_query_condition(i, flags | QueryConditionFlags::ALLOW_OR, options))
798    {
799      return Ok(inner);
800    }
801
802    P::parse_feature(input, options)
803  })
804}
805
806pub(crate) fn to_css_with_parens_if_needed<V: ToCss, PrinterT: crate::printer::PrinterTrait>(
807  value: V,
808  dest: &mut PrinterT,
809  needs_parens: bool,
810) -> Result<(), PrinterError> {
811  if needs_parens {
812    dest.write_char('(')?;
813  }
814  value.to_css(dest)?;
815  if needs_parens {
816    dest.write_char(')')?;
817  }
818  Ok(())
819}
820
821pub(crate) fn operation_to_css<'i, V: ToCss + QueryCondition<'i>, PrinterT: crate::printer::PrinterTrait>(
822  operator: Operator,
823  conditions: &Vec<V>,
824  dest: &mut PrinterT,
825) -> Result<(), PrinterError> {
826  let mut iter = conditions.iter();
827  let first = iter.next().unwrap();
828  to_css_with_parens_if_needed(first, dest, first.needs_parens(Some(operator), &dest.targets().current))?;
829  for item in iter {
830    dest.write_char(' ')?;
831    operator.to_css(dest)?;
832    dest.write_char(' ')?;
833    to_css_with_parens_if_needed(item, dest, item.needs_parens(Some(operator), &dest.targets().current))?;
834  }
835
836  Ok(())
837}
838
839impl<'i> MediaCondition<'i> {
840  fn negate(&self) -> Option<MediaCondition<'i>> {
841    match self {
842      MediaCondition::Not(not) => Some((**not).clone()),
843      MediaCondition::Feature(f) => f.negate().map(MediaCondition::Feature),
844      _ => None,
845    }
846  }
847}
848
849impl<'i> ToCss for MediaCondition<'i> {
850  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
851    match *self {
852      MediaCondition::Feature(ref f) => f.to_css(dest),
853      MediaCondition::Not(ref c) => {
854        if let Some(negated) = c.negate() {
855          negated.to_css(dest)
856        } else {
857          dest.write_str("not ")?;
858          to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.targets().current))
859        }
860      }
861      MediaCondition::Operation {
862        ref conditions,
863        operator,
864      } => operation_to_css(operator, conditions, dest),
865      MediaCondition::Unknown(ref tokens) => tokens.to_css(dest, false),
866    }
867  }
868}
869
870/// A [comparator](https://drafts.csswg.org/mediaqueries/#typedef-mf-comparison) within a media query.
871#[derive(Clone, Copy, Debug, Eq, PartialEq)]
872#[cfg_attr(feature = "visitor", derive(Visit))]
873#[cfg_attr(
874  feature = "serde",
875  derive(serde::Serialize, serde::Deserialize),
876  serde(rename_all = "kebab-case")
877)]
878#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
879#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
880pub enum MediaFeatureComparison {
881  /// `=`
882  Equal,
883  /// `>`
884  GreaterThan,
885  /// `>=`
886  GreaterThanEqual,
887  /// `<`
888  LessThan,
889  /// `<=`
890  LessThanEqual,
891}
892
893impl ToCss for MediaFeatureComparison {
894  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
895    use MediaFeatureComparison::*;
896    match self {
897      Equal => dest.delim('=', true),
898      GreaterThan => dest.delim('>', true),
899      GreaterThanEqual => {
900        dest.whitespace()?;
901        dest.write_str(">=")?;
902        dest.whitespace()
903      }
904      LessThan => dest.delim('<', true),
905      LessThanEqual => {
906        dest.whitespace()?;
907        dest.write_str("<=")?;
908        dest.whitespace()
909      }
910    }
911  }
912}
913
914impl MediaFeatureComparison {
915  fn opposite(&self) -> MediaFeatureComparison {
916    match self {
917      MediaFeatureComparison::GreaterThan => MediaFeatureComparison::LessThan,
918      MediaFeatureComparison::GreaterThanEqual => MediaFeatureComparison::LessThanEqual,
919      MediaFeatureComparison::LessThan => MediaFeatureComparison::GreaterThan,
920      MediaFeatureComparison::LessThanEqual => MediaFeatureComparison::GreaterThanEqual,
921      MediaFeatureComparison::Equal => MediaFeatureComparison::Equal,
922    }
923  }
924
925  fn negate(&self) -> MediaFeatureComparison {
926    match self {
927      MediaFeatureComparison::GreaterThan => MediaFeatureComparison::LessThanEqual,
928      MediaFeatureComparison::GreaterThanEqual => MediaFeatureComparison::LessThan,
929      MediaFeatureComparison::LessThan => MediaFeatureComparison::GreaterThanEqual,
930      MediaFeatureComparison::LessThanEqual => MediaFeatureComparison::GreaterThan,
931      MediaFeatureComparison::Equal => MediaFeatureComparison::Equal,
932    }
933  }
934}
935
936/// A generic media feature or container feature.
937#[derive(Clone, Debug, PartialEq)]
938#[cfg_attr(
939  feature = "visitor",
940  derive(Visit),
941  visit(visit_media_feature, MEDIA_QUERIES, <'i, MediaFeatureId>),
942  visit(<'i, ContainerSizeFeatureId>),
943  visit(<'i, ScrollStateFeatureId>)
944)]
945#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
946#[cfg_attr(
947  feature = "serde",
948  derive(serde::Serialize, serde::Deserialize),
949  serde(tag = "type", rename_all = "kebab-case")
950)]
951#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
952pub enum QueryFeature<'i, FeatureId> {
953  /// A plain media feature, e.g. `(min-width: 240px)`.
954  Plain {
955    /// The name of the feature.
956    #[cfg_attr(feature = "serde", serde(borrow))]
957    name: MediaFeatureName<'i, FeatureId>,
958    /// The feature value.
959    value: MediaFeatureValue<'i>,
960  },
961  /// A boolean feature, e.g. `(hover)`.
962  Boolean {
963    /// The name of the feature.
964    name: MediaFeatureName<'i, FeatureId>,
965  },
966  /// A range, e.g. `(width > 240px)`.
967  Range {
968    /// The name of the feature.
969    name: MediaFeatureName<'i, FeatureId>,
970    /// A comparator.
971    operator: MediaFeatureComparison,
972    /// The feature value.
973    value: MediaFeatureValue<'i>,
974  },
975  /// An interval, e.g. `(120px < width < 240px)`.
976  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
977  Interval {
978    /// The name of the feature.
979    name: MediaFeatureName<'i, FeatureId>,
980    /// A start value.
981    start: MediaFeatureValue<'i>,
982    /// A comparator for the start value.
983    start_operator: MediaFeatureComparison,
984    /// The end value.
985    end: MediaFeatureValue<'i>,
986    /// A comparator for the end value.
987    end_operator: MediaFeatureComparison,
988  },
989}
990
991/// A [media feature](https://drafts.csswg.org/mediaqueries/#typedef-media-feature)
992pub type MediaFeature<'i> = QueryFeature<'i, MediaFeatureId>;
993
994impl<'i, FeatureId> ParseWithOptions<'i> for QueryFeature<'i, FeatureId>
995where
996  FeatureId: for<'x> Parse<'x> + std::fmt::Debug + PartialEq + ValueType + Clone,
997{
998  fn parse_with_options<'t>(
999    input: &mut Parser<'i, 't>,
1000    options: &ParserOptions<'i>,
1001  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1002    match input.try_parse(|input| Self::parse_name_first(input, options)) {
1003      Ok(res) => Ok(res),
1004      Err(
1005        err @ ParseError {
1006          kind: ParseErrorKind::Custom(ParserError::InvalidMediaQuery),
1007          ..
1008        },
1009      ) => Err(err),
1010      _ => Self::parse_value_first(input),
1011    }
1012  }
1013}
1014
1015impl<'i, FeatureId> QueryFeature<'i, FeatureId>
1016where
1017  FeatureId: for<'x> Parse<'x> + std::fmt::Debug + PartialEq + ValueType + Clone,
1018{
1019  fn parse_name_first<'t>(
1020    input: &mut Parser<'i, 't>,
1021    options: &ParserOptions<'i>,
1022  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1023    let (name, legacy_op) = MediaFeatureName::parse(input)?;
1024
1025    let operator = input.try_parse(|input| consume_operation_or_colon(input, true));
1026    let operator = match operator {
1027      Err(..) => return Ok(QueryFeature::Boolean { name }),
1028      Ok(operator) => operator,
1029    };
1030
1031    if operator.is_some() && legacy_op.is_some() {
1032      return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1033    }
1034
1035    let value = MediaFeatureValue::parse(input, name.value_type())?;
1036    if !value.check_type(name.value_type()) {
1037      if options.error_recovery {
1038        options.warn(ParseError {
1039          kind: ParseErrorKind::Custom(ParserError::InvalidMediaQuery),
1040          location: input.current_source_location(),
1041        });
1042      } else {
1043        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1044      }
1045    }
1046
1047    if let Some(operator) = operator.or(legacy_op) {
1048      if !name.value_type().allows_ranges() {
1049        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1050      }
1051
1052      Ok(QueryFeature::Range { name, operator, value })
1053    } else {
1054      Ok(QueryFeature::Plain { name, value })
1055    }
1056  }
1057
1058  fn parse_value_first<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1059    // We need to find the feature name first so we know the type.
1060    let start = input.state();
1061    let name = loop {
1062      if let Ok((name, legacy_op)) = MediaFeatureName::parse(input) {
1063        if legacy_op.is_some() {
1064          return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1065        }
1066        break name;
1067      }
1068      if input.is_exhausted() {
1069        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1070      }
1071    };
1072
1073    input.reset(&start);
1074
1075    // Now we can parse the first value.
1076    let value = MediaFeatureValue::parse(input, name.value_type())?;
1077    let operator = consume_operation_or_colon(input, false)?;
1078
1079    // Skip over the feature name again.
1080    {
1081      let (feature_name, _) = MediaFeatureName::parse(input)?;
1082      debug_assert_eq!(name, feature_name);
1083    }
1084
1085    if !name.value_type().allows_ranges() || !value.check_type(name.value_type()) {
1086      return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1087    }
1088
1089    if let Ok(end_operator) = input.try_parse(|input| consume_operation_or_colon(input, false)) {
1090      let start_operator = operator.unwrap();
1091      let end_operator = end_operator.unwrap();
1092      // Start and end operators must be matching.
1093      match (start_operator, end_operator) {
1094        (MediaFeatureComparison::GreaterThan, MediaFeatureComparison::GreaterThan)
1095        | (MediaFeatureComparison::GreaterThan, MediaFeatureComparison::GreaterThanEqual)
1096        | (MediaFeatureComparison::GreaterThanEqual, MediaFeatureComparison::GreaterThanEqual)
1097        | (MediaFeatureComparison::GreaterThanEqual, MediaFeatureComparison::GreaterThan)
1098        | (MediaFeatureComparison::LessThan, MediaFeatureComparison::LessThan)
1099        | (MediaFeatureComparison::LessThan, MediaFeatureComparison::LessThanEqual)
1100        | (MediaFeatureComparison::LessThanEqual, MediaFeatureComparison::LessThanEqual)
1101        | (MediaFeatureComparison::LessThanEqual, MediaFeatureComparison::LessThan) => {}
1102        _ => return Err(input.new_custom_error(ParserError::InvalidMediaQuery)),
1103      };
1104
1105      let end_value = MediaFeatureValue::parse(input, name.value_type())?;
1106      if !end_value.check_type(name.value_type()) {
1107        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1108      }
1109
1110      Ok(QueryFeature::Interval {
1111        name,
1112        start: value,
1113        start_operator,
1114        end: end_value,
1115        end_operator,
1116      })
1117    } else {
1118      let operator = operator.unwrap().opposite();
1119      Ok(QueryFeature::Range { name, operator, value })
1120    }
1121  }
1122
1123  pub(crate) fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool {
1124    match self {
1125      QueryFeature::Interval { .. } => {
1126        should_compile!(targets, MediaIntervalSyntax) && parent_operator != Some(Operator::And)
1127      }
1128      QueryFeature::Range { operator, .. } => {
1129        should_compile!(targets, MediaRangeSyntax)
1130          && matches!(
1131            operator,
1132            MediaFeatureComparison::GreaterThan | MediaFeatureComparison::LessThan
1133          )
1134      }
1135      _ => false,
1136    }
1137  }
1138
1139  fn negate(&self) -> Option<QueryFeature<'i, FeatureId>> {
1140    match self {
1141      QueryFeature::Range { name, operator, value } => Some(QueryFeature::Range {
1142        name: (*name).clone(),
1143        operator: operator.negate(),
1144        value: value.clone(),
1145      }),
1146      _ => None,
1147    }
1148  }
1149}
1150
1151impl<'i, FeatureId: FeatureToCss> ToCss for QueryFeature<'i, FeatureId> {
1152  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1153    match self {
1154      QueryFeature::Boolean { name } => {
1155        dest.write_char('(')?;
1156        name.to_css(dest)?;
1157      }
1158      QueryFeature::Plain { name, value } => {
1159        dest.write_char('(')?;
1160        name.to_css(dest)?;
1161        dest.delim(':', false)?;
1162        value.to_css(dest)?;
1163      }
1164      QueryFeature::Range { name, operator, value } => {
1165        // If range syntax is unsupported, use min/max prefix if possible.
1166        if should_compile!(dest.targets().current, MediaRangeSyntax) {
1167          return write_min_max(operator, name, value, dest, false);
1168        }
1169
1170        dest.write_char('(')?;
1171        name.to_css(dest)?;
1172        operator.to_css(dest)?;
1173        value.to_css(dest)?;
1174      }
1175      QueryFeature::Interval {
1176        name,
1177        start,
1178        start_operator,
1179        end,
1180        end_operator,
1181      } => {
1182        if should_compile!(dest.targets().current, MediaIntervalSyntax) {
1183          write_min_max(&start_operator.opposite(), name, start, dest, true)?;
1184          dest.write_str(" and ")?;
1185          return write_min_max(end_operator, name, end, dest, true);
1186        }
1187
1188        dest.write_char('(')?;
1189        start.to_css(dest)?;
1190        start_operator.to_css(dest)?;
1191        name.to_css(dest)?;
1192        end_operator.to_css(dest)?;
1193        end.to_css(dest)?;
1194      }
1195    }
1196
1197    dest.write_char(')')?;
1198
1199    Ok(())
1200  }
1201}
1202
1203/// A media feature name.
1204#[derive(Debug, Clone, PartialEq)]
1205#[cfg_attr(feature = "visitor", derive(Visit))]
1206#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1207#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(untagged))]
1208#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1209pub enum MediaFeatureName<'i, FeatureId> {
1210  /// A standard media query feature identifier.
1211  Standard(FeatureId),
1212  /// A custom author-defined environment variable.
1213  #[cfg_attr(feature = "serde", serde(borrow))]
1214  Custom(DashedIdent<'i>),
1215  /// An unknown environment variable.
1216  Unknown(Ident<'i>),
1217}
1218
1219impl<'i, FeatureId: for<'x> Parse<'x>> MediaFeatureName<'i, FeatureId> {
1220  /// Parses a media feature name.
1221  pub fn parse<'t>(
1222    input: &mut Parser<'i, 't>,
1223  ) -> Result<(Self, Option<MediaFeatureComparison>), ParseError<'i, ParserError<'i>>> {
1224    let ident = input.expect_ident()?;
1225
1226    if ident.starts_with("--") {
1227      return Ok((MediaFeatureName::Custom(DashedIdent(ident.into())), None));
1228    }
1229
1230    let mut name = ident.as_ref();
1231
1232    // Webkit places its prefixes before "min" and "max". Remove it first, and
1233    // re-add after removing min/max.
1234    let is_webkit = starts_with_ignore_ascii_case(&name, "-webkit-");
1235    if is_webkit {
1236      name = &name[8..];
1237    }
1238
1239    let comparator = if starts_with_ignore_ascii_case(&name, "min-") {
1240      name = &name[4..];
1241      Some(MediaFeatureComparison::GreaterThanEqual)
1242    } else if starts_with_ignore_ascii_case(&name, "max-") {
1243      name = &name[4..];
1244      Some(MediaFeatureComparison::LessThanEqual)
1245    } else {
1246      None
1247    };
1248
1249    let name = if is_webkit {
1250      Cow::Owned(format!("-webkit-{}", name))
1251    } else {
1252      Cow::Borrowed(name)
1253    };
1254
1255    if let Ok(standard) = FeatureId::parse_string(&name) {
1256      return Ok((MediaFeatureName::Standard(standard), comparator));
1257    }
1258
1259    Ok((MediaFeatureName::Unknown(Ident(ident.into())), None))
1260  }
1261}
1262
1263mod private {
1264  use super::*;
1265
1266  /// A trait for feature ids which can get a value type.
1267  pub trait ValueType {
1268    /// Returns the value type for this feature id.
1269    fn value_type(&self) -> MediaFeatureType;
1270  }
1271}
1272
1273pub(crate) use private::ValueType;
1274
1275impl<'i, FeatureId: ValueType> ValueType for MediaFeatureName<'i, FeatureId> {
1276  fn value_type(&self) -> MediaFeatureType {
1277    match self {
1278      Self::Standard(standard) => standard.value_type(),
1279      _ => MediaFeatureType::Unknown,
1280    }
1281  }
1282}
1283
1284impl<'i, FeatureId: FeatureToCss> ToCss for MediaFeatureName<'i, FeatureId> {
1285  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1286    match self {
1287      Self::Standard(v) => v.to_css(dest),
1288      Self::Custom(v) => v.to_css(dest),
1289      Self::Unknown(v) => v.to_css(dest),
1290    }
1291  }
1292}
1293
1294impl<'i, FeatureId: FeatureToCss> FeatureToCss for MediaFeatureName<'i, FeatureId> {
1295  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
1296    &self,
1297    prefix: &str,
1298    dest: &mut PrinterT,
1299  ) -> Result<(), PrinterError> {
1300    match self {
1301      Self::Standard(v) => v.to_css_with_prefix(prefix, dest),
1302      Self::Custom(v) => {
1303        dest.write_str(prefix)?;
1304        v.to_css(dest)
1305      }
1306      Self::Unknown(v) => {
1307        dest.write_str(prefix)?;
1308        v.to_css(dest)
1309      }
1310    }
1311  }
1312}
1313
1314/// The type of a media feature.
1315#[derive(PartialEq)]
1316pub enum MediaFeatureType {
1317  /// A length value.
1318  Length,
1319  /// A number value.
1320  Number,
1321  /// An integer value.
1322  Integer,
1323  /// A boolean value, either 0 or 1.
1324  Boolean,
1325  /// A resolution.
1326  Resolution,
1327  /// A ratio.
1328  Ratio,
1329  /// An identifier.
1330  Ident,
1331  /// An unknown type.
1332  Unknown,
1333}
1334
1335impl MediaFeatureType {
1336  fn allows_ranges(&self) -> bool {
1337    use MediaFeatureType::*;
1338    match self {
1339      Length => true,
1340      Number => true,
1341      Integer => true,
1342      Boolean => false,
1343      Resolution => true,
1344      Ratio => true,
1345      Ident => false,
1346      Unknown => true,
1347    }
1348  }
1349}
1350
1351macro_rules! define_query_features {
1352  (
1353    $(#[$outer:meta])*
1354    $vis:vis enum $name:ident {
1355      $(
1356        $(#[$meta: meta])*
1357        $str: literal: $id: ident = $ty: ident,
1358      )+
1359    }
1360  ) => {
1361    crate::macros::enum_property! {
1362      $(#[$outer])*
1363      $vis enum $name {
1364        $(
1365          $(#[$meta])*
1366          $str: $id,
1367        )+
1368      }
1369    }
1370
1371    impl ValueType for $name {
1372      fn value_type(&self) -> MediaFeatureType {
1373        match self {
1374          $(
1375            Self::$id => MediaFeatureType::$ty,
1376          )+
1377        }
1378      }
1379    }
1380  }
1381}
1382
1383pub(crate) use define_query_features;
1384
1385define_query_features! {
1386  /// A media query feature identifier.
1387  pub enum MediaFeatureId {
1388    /// The [width](https://w3c.github.io/csswg-drafts/mediaqueries-5/#width) media feature.
1389    "width": Width = Length,
1390    /// The [height](https://w3c.github.io/csswg-drafts/mediaqueries-5/#height) media feature.
1391    "height": Height = Length,
1392    /// The [aspect-ratio](https://w3c.github.io/csswg-drafts/mediaqueries-5/#aspect-ratio) media feature.
1393    "aspect-ratio": AspectRatio = Ratio,
1394    /// The [orientation](https://w3c.github.io/csswg-drafts/mediaqueries-5/#orientation) media feature.
1395    "orientation": Orientation = Ident,
1396    /// The [overflow-block](https://w3c.github.io/csswg-drafts/mediaqueries-5/#overflow-block) media feature.
1397    "overflow-block": OverflowBlock = Ident,
1398    /// The [overflow-inline](https://w3c.github.io/csswg-drafts/mediaqueries-5/#overflow-inline) media feature.
1399    "overflow-inline": OverflowInline = Ident,
1400    /// The [horizontal-viewport-segments](https://w3c.github.io/csswg-drafts/mediaqueries-5/#horizontal-viewport-segments) media feature.
1401    "horizontal-viewport-segments": HorizontalViewportSegments = Integer,
1402    /// The [vertical-viewport-segments](https://w3c.github.io/csswg-drafts/mediaqueries-5/#vertical-viewport-segments) media feature.
1403    "vertical-viewport-segments": VerticalViewportSegments = Integer,
1404    /// The [display-mode](https://w3c.github.io/csswg-drafts/mediaqueries-5/#display-mode) media feature.
1405    "display-mode": DisplayMode = Ident,
1406    /// The [resolution](https://w3c.github.io/csswg-drafts/mediaqueries-5/#resolution) media feature.
1407    "resolution": Resolution = Resolution, // | infinite??
1408    /// The [scan](https://w3c.github.io/csswg-drafts/mediaqueries-5/#scan) media feature.
1409    "scan": Scan = Ident,
1410    /// The [grid](https://w3c.github.io/csswg-drafts/mediaqueries-5/#grid) media feature.
1411    "grid": Grid = Boolean,
1412    /// The [update](https://w3c.github.io/csswg-drafts/mediaqueries-5/#update) media feature.
1413    "update": Update = Ident,
1414    /// The [environment-blending](https://w3c.github.io/csswg-drafts/mediaqueries-5/#environment-blending) media feature.
1415    "environment-blending": EnvironmentBlending = Ident,
1416    /// The [color](https://w3c.github.io/csswg-drafts/mediaqueries-5/#color) media feature.
1417    "color": Color = Integer,
1418    /// The [color-index](https://w3c.github.io/csswg-drafts/mediaqueries-5/#color-index) media feature.
1419    "color-index": ColorIndex = Integer,
1420    /// The [monochrome](https://w3c.github.io/csswg-drafts/mediaqueries-5/#monochrome) media feature.
1421    "monochrome": Monochrome = Integer,
1422    /// The [color-gamut](https://w3c.github.io/csswg-drafts/mediaqueries-5/#color-gamut) media feature.
1423    "color-gamut": ColorGamut = Ident,
1424    /// The [dynamic-range](https://w3c.github.io/csswg-drafts/mediaqueries-5/#dynamic-range) media feature.
1425    "dynamic-range": DynamicRange = Ident,
1426    /// The [inverted-colors](https://w3c.github.io/csswg-drafts/mediaqueries-5/#inverted-colors) media feature.
1427    "inverted-colors": InvertedColors = Ident,
1428    /// The [pointer](https://w3c.github.io/csswg-drafts/mediaqueries-5/#pointer) media feature.
1429    "pointer": Pointer = Ident,
1430    /// The [hover](https://w3c.github.io/csswg-drafts/mediaqueries-5/#hover) media feature.
1431    "hover": Hover = Ident,
1432    /// The [any-pointer](https://w3c.github.io/csswg-drafts/mediaqueries-5/#any-pointer) media feature.
1433    "any-pointer": AnyPointer = Ident,
1434    /// The [any-hover](https://w3c.github.io/csswg-drafts/mediaqueries-5/#any-hover) media feature.
1435    "any-hover": AnyHover = Ident,
1436    /// The [nav-controls](https://w3c.github.io/csswg-drafts/mediaqueries-5/#nav-controls) media feature.
1437    "nav-controls": NavControls = Ident,
1438    /// The [video-color-gamut](https://w3c.github.io/csswg-drafts/mediaqueries-5/#video-color-gamut) media feature.
1439    "video-color-gamut": VideoColorGamut = Ident,
1440    /// The [video-dynamic-range](https://w3c.github.io/csswg-drafts/mediaqueries-5/#video-dynamic-range) media feature.
1441    "video-dynamic-range": VideoDynamicRange = Ident,
1442    /// The [scripting](https://w3c.github.io/csswg-drafts/mediaqueries-5/#scripting) media feature.
1443    "scripting": Scripting = Ident,
1444    /// The [prefers-reduced-motion](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-reduced-motion) media feature.
1445    "prefers-reduced-motion": PrefersReducedMotion = Ident,
1446    /// The [prefers-reduced-transparency](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-reduced-transparency) media feature.
1447    "prefers-reduced-transparency": PrefersReducedTransparency = Ident,
1448    /// The [prefers-contrast](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-contrast) media feature.
1449    "prefers-contrast": PrefersContrast = Ident,
1450    /// The [forced-colors](https://w3c.github.io/csswg-drafts/mediaqueries-5/#forced-colors) media feature.
1451    "forced-colors": ForcedColors = Ident,
1452    /// The [prefers-color-scheme](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-color-scheme) media feature.
1453    "prefers-color-scheme": PrefersColorScheme = Ident,
1454    /// The [prefers-reduced-data](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-reduced-data) media feature.
1455    "prefers-reduced-data": PrefersReducedData = Ident,
1456    /// The [device-width](https://w3c.github.io/csswg-drafts/mediaqueries-5/#device-width) media feature.
1457    "device-width": DeviceWidth = Length,
1458    /// The [device-height](https://w3c.github.io/csswg-drafts/mediaqueries-5/#device-height) media feature.
1459    "device-height": DeviceHeight = Length,
1460    /// The [device-aspect-ratio](https://w3c.github.io/csswg-drafts/mediaqueries-5/#device-aspect-ratio) media feature.
1461    "device-aspect-ratio": DeviceAspectRatio = Ratio,
1462
1463    /// The non-standard -webkit-device-pixel-ratio media feature.
1464    "-webkit-device-pixel-ratio": WebKitDevicePixelRatio = Number,
1465    /// The non-standard -moz-device-pixel-ratio media feature.
1466    "-moz-device-pixel-ratio": MozDevicePixelRatio = Number,
1467
1468    // TODO: parse non-standard media queries?
1469    // -moz-device-orientation
1470    // -webkit-transform-3d
1471  }
1472}
1473
1474pub(crate) trait FeatureToCss: ToCss {
1475  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
1476    &self,
1477    prefix: &str,
1478    dest: &mut PrinterT,
1479  ) -> Result<(), PrinterError>;
1480}
1481
1482impl FeatureToCss for MediaFeatureId {
1483  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
1484    &self,
1485    prefix: &str,
1486    dest: &mut PrinterT,
1487  ) -> Result<(), PrinterError> {
1488    match self {
1489      MediaFeatureId::WebKitDevicePixelRatio => {
1490        dest.write_str("-webkit-")?;
1491        dest.write_str(prefix)?;
1492        dest.write_str("device-pixel-ratio")?;
1493        Ok(())
1494      }
1495      _ => {
1496        dest.write_str(prefix)?;
1497        self.to_css(dest)
1498      }
1499    }
1500  }
1501}
1502
1503#[inline]
1504fn write_min_max<PrinterT: crate::printer::PrinterTrait, FeatureId: FeatureToCss>(
1505  operator: &MediaFeatureComparison,
1506  name: &MediaFeatureName<FeatureId>,
1507  value: &MediaFeatureValue,
1508  dest: &mut PrinterT,
1509  is_range: bool,
1510) -> Result<(), PrinterError> {
1511  let prefix = match operator {
1512    MediaFeatureComparison::GreaterThan => {
1513      if is_range {
1514        dest.write_char('(')?;
1515      }
1516      dest.write_str("not ")?;
1517      Some("max-")
1518    }
1519    MediaFeatureComparison::GreaterThanEqual => Some("min-"),
1520    MediaFeatureComparison::LessThan => {
1521      if is_range {
1522        dest.write_char('(')?;
1523      }
1524      dest.write_str("not ")?;
1525      Some("min-")
1526    }
1527    MediaFeatureComparison::LessThanEqual => Some("max-"),
1528    MediaFeatureComparison::Equal => None,
1529  };
1530
1531  dest.write_char('(')?;
1532  if let Some(prefix) = prefix {
1533    name.to_css_with_prefix(prefix, dest)?;
1534  } else {
1535    name.to_css(dest)?;
1536  }
1537
1538  dest.delim(':', false)?;
1539  value.to_css(dest)?;
1540
1541  if is_range
1542    && matches!(
1543      operator,
1544      MediaFeatureComparison::GreaterThan | MediaFeatureComparison::LessThan
1545    )
1546  {
1547    dest.write_char(')')?;
1548  }
1549
1550  dest.write_char(')')?;
1551  Ok(())
1552}
1553
1554/// [media feature value](https://drafts.csswg.org/mediaqueries/#typedef-mf-value) within a media query.
1555///
1556/// See [MediaFeature](MediaFeature).
1557#[derive(Clone, Debug, PartialEq)]
1558#[cfg_attr(feature = "visitor", derive(Visit), visit(visit_media_feature_value, MEDIA_QUERIES))]
1559#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1560#[cfg_attr(
1561  feature = "serde",
1562  derive(serde::Serialize, serde::Deserialize),
1563  serde(tag = "type", content = "value", rename_all = "kebab-case")
1564)]
1565#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1566pub enum MediaFeatureValue<'i> {
1567  /// A length value.
1568  Length(Length),
1569  /// A number value.
1570  Number(CSSNumber),
1571  /// An integer value.
1572  Integer(CSSInteger),
1573  /// A boolean value.
1574  Boolean(bool),
1575  /// A resolution.
1576  Resolution(Resolution),
1577  /// A ratio.
1578  Ratio(Ratio),
1579  /// An identifier.
1580  #[cfg_attr(feature = "serde", serde(borrow))]
1581  Ident(Ident<'i>),
1582  /// An environment variable reference.
1583  Env(EnvironmentVariable<'i>),
1584}
1585
1586impl<'i> MediaFeatureValue<'i> {
1587  fn value_type(&self) -> MediaFeatureType {
1588    use MediaFeatureValue::*;
1589    match self {
1590      Length(..) => MediaFeatureType::Length,
1591      Number(..) => MediaFeatureType::Number,
1592      Integer(..) => MediaFeatureType::Integer,
1593      Boolean(..) => MediaFeatureType::Boolean,
1594      Resolution(..) => MediaFeatureType::Resolution,
1595      Ratio(..) => MediaFeatureType::Ratio,
1596      Ident(..) => MediaFeatureType::Ident,
1597      Env(..) => MediaFeatureType::Unknown,
1598    }
1599  }
1600
1601  fn check_type(&self, expected_type: MediaFeatureType) -> bool {
1602    match (expected_type, self.value_type()) {
1603      (_, MediaFeatureType::Unknown) | (MediaFeatureType::Unknown, _) => true,
1604      (a, b) => a == b,
1605    }
1606  }
1607}
1608
1609impl<'i> MediaFeatureValue<'i> {
1610  /// Parses a single media query feature value, with an expected type.
1611  /// If the type is unknown, pass MediaFeatureType::Unknown instead.
1612  pub fn parse<'t>(
1613    input: &mut Parser<'i, 't>,
1614    expected_type: MediaFeatureType,
1615  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1616    if let Ok(value) = input.try_parse(|input| Self::parse_known(input, expected_type)) {
1617      return Ok(value);
1618    }
1619
1620    Self::parse_unknown(input)
1621  }
1622
1623  fn parse_known<'t>(
1624    input: &mut Parser<'i, 't>,
1625    expected_type: MediaFeatureType,
1626  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1627    match expected_type {
1628      MediaFeatureType::Boolean => {
1629        let value = CSSInteger::parse(input)?;
1630        if value != 0 && value != 1 {
1631          return Err(input.new_custom_error(ParserError::InvalidValue));
1632        }
1633        Ok(MediaFeatureValue::Boolean(value == 1))
1634      }
1635      MediaFeatureType::Number => Ok(MediaFeatureValue::Number(CSSNumber::parse(input)?)),
1636      MediaFeatureType::Integer => Ok(MediaFeatureValue::Integer(CSSInteger::parse(input)?)),
1637      MediaFeatureType::Length => Ok(MediaFeatureValue::Length(Length::parse(input)?)),
1638      MediaFeatureType::Resolution => Ok(MediaFeatureValue::Resolution(Resolution::parse(input)?)),
1639      MediaFeatureType::Ratio => Ok(MediaFeatureValue::Ratio(Ratio::parse(input)?)),
1640      MediaFeatureType::Ident => Ok(MediaFeatureValue::Ident(Ident::parse(input)?)),
1641      MediaFeatureType::Unknown => Err(input.new_custom_error(ParserError::InvalidValue)),
1642    }
1643  }
1644
1645  fn parse_unknown<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1646    // Ratios are ambiguous with numbers because the second param is optional (e.g. 2/1 == 2).
1647    // We require the / delimiter when parsing ratios so that 2/1 ends up as a ratio and 2 is
1648    // parsed as a number.
1649    if let Ok(ratio) = input.try_parse(Ratio::parse_required) {
1650      return Ok(MediaFeatureValue::Ratio(ratio));
1651    }
1652
1653    // Parse number next so that unitless values are not parsed as lengths.
1654    if let Ok(num) = input.try_parse(CSSNumber::parse) {
1655      return Ok(MediaFeatureValue::Number(num));
1656    }
1657
1658    if let Ok(length) = input.try_parse(Length::parse) {
1659      return Ok(MediaFeatureValue::Length(length));
1660    }
1661
1662    if let Ok(res) = input.try_parse(Resolution::parse) {
1663      return Ok(MediaFeatureValue::Resolution(res));
1664    }
1665
1666    if let Ok(env) = input.try_parse(|input| EnvironmentVariable::parse(input, &ParserOptions::default(), 0)) {
1667      return Ok(MediaFeatureValue::Env(env));
1668    }
1669
1670    let ident = Ident::parse(input)?;
1671    Ok(MediaFeatureValue::Ident(ident))
1672  }
1673}
1674
1675impl<'i> ToCss for MediaFeatureValue<'i> {
1676  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1677    match self {
1678      MediaFeatureValue::Length(len) => len.to_css(dest),
1679      MediaFeatureValue::Number(num) => num.to_css(dest),
1680      MediaFeatureValue::Integer(num) => num.to_css(dest),
1681      MediaFeatureValue::Boolean(b) => {
1682        if *b {
1683          dest.write_char('1')?;
1684          Ok(())
1685        } else {
1686          dest.write_char('0')?;
1687          Ok(())
1688        }
1689      }
1690      MediaFeatureValue::Resolution(res) => res.to_css(dest),
1691      MediaFeatureValue::Ratio(ratio) => ratio.to_css(dest),
1692      MediaFeatureValue::Ident(id) => {
1693        id.to_css(dest)?;
1694        Ok(())
1695      }
1696      MediaFeatureValue::Env(env) => env.to_css(dest, false),
1697    }
1698  }
1699}
1700
1701/// Consumes an operation or a colon, or returns an error.
1702fn consume_operation_or_colon<'i, 't>(
1703  input: &mut Parser<'i, 't>,
1704  allow_colon: bool,
1705) -> Result<Option<MediaFeatureComparison>, ParseError<'i, ParserError<'i>>> {
1706  let location = input.current_source_location();
1707  let first_delim = {
1708    let location = input.current_source_location();
1709    let next_token = input.next()?;
1710    match next_token {
1711      Token::Colon if allow_colon => return Ok(None),
1712      Token::Delim(oper) => oper,
1713      t => return Err(location.new_unexpected_token_error(t.clone())),
1714    }
1715  };
1716  Ok(Some(match first_delim {
1717    '=' => MediaFeatureComparison::Equal,
1718    '>' => {
1719      if input.try_parse(|i| i.expect_delim('=')).is_ok() {
1720        MediaFeatureComparison::GreaterThanEqual
1721      } else {
1722        MediaFeatureComparison::GreaterThan
1723      }
1724    }
1725    '<' => {
1726      if input.try_parse(|i| i.expect_delim('=')).is_ok() {
1727        MediaFeatureComparison::LessThanEqual
1728      } else {
1729        MediaFeatureComparison::LessThan
1730      }
1731    }
1732    d => return Err(location.new_unexpected_token_error(Token::Delim(*d))),
1733  }))
1734}
1735
1736fn process_condition<'i>(
1737  loc: Location,
1738  custom_media: &HashMap<CowArcStr<'i>, CustomMediaRule<'i>>,
1739  media_type: &mut MediaType<'i>,
1740  qualifier: &mut Option<Qualifier>,
1741  condition: &mut MediaCondition<'i>,
1742  seen: &mut HashSet<DashedIdent<'i>>,
1743) -> Result<bool, MinifyError> {
1744  match condition {
1745    MediaCondition::Not(cond) => {
1746      let used = process_condition(loc, custom_media, media_type, qualifier, &mut *cond, seen)?;
1747      if !used {
1748        // If unused, only a media type remains so apply a not qualifier.
1749        // If it is already not, then it cancels out.
1750        *qualifier = if *qualifier == Some(Qualifier::Not) {
1751          None
1752        } else {
1753          Some(Qualifier::Not)
1754        };
1755        return Ok(false);
1756      }
1757
1758      // Unwrap nested nots
1759      match &**cond {
1760        MediaCondition::Not(cond) => {
1761          *condition = (**cond).clone();
1762        }
1763        _ => {}
1764      }
1765    }
1766    MediaCondition::Operation { conditions, .. } => {
1767      let mut res = Ok(true);
1768      conditions.retain_mut(|condition| {
1769        let r = process_condition(loc, custom_media, media_type, qualifier, condition, seen);
1770        if let Ok(used) = r {
1771          used
1772        } else {
1773          res = r;
1774          false
1775        }
1776      });
1777      return res;
1778    }
1779    MediaCondition::Feature(QueryFeature::Boolean { name }) => {
1780      let name = match name {
1781        MediaFeatureName::Custom(name) => name,
1782        _ => return Ok(true),
1783      };
1784
1785      if seen.contains(name) {
1786        return Err(ErrorWithLocation {
1787          kind: MinifyErrorKind::CircularCustomMedia { name: name.to_string() },
1788          loc,
1789        });
1790      }
1791
1792      let rule = custom_media.get(&name.0).ok_or_else(|| ErrorWithLocation {
1793        kind: MinifyErrorKind::CustomMediaNotDefined { name: name.to_string() },
1794        loc,
1795      })?;
1796
1797      seen.insert(name.clone());
1798
1799      let mut res = Ok(true);
1800      let mut conditions: Vec<MediaCondition> = rule
1801        .query
1802        .media_queries
1803        .iter()
1804        .filter_map(|query| {
1805          if query.media_type != MediaType::All || query.qualifier != None {
1806            if *media_type == MediaType::All {
1807              // `not all` will never match.
1808              if *qualifier == Some(Qualifier::Not) {
1809                res = Ok(false);
1810                return None;
1811              }
1812
1813              // Propagate media type and qualifier to @media rule.
1814              *media_type = query.media_type.clone();
1815              *qualifier = query.qualifier.clone();
1816            } else if query.media_type != *media_type || query.qualifier != *qualifier {
1817              // Boolean logic with media types is hard to emulate, so we error for now.
1818              res = Err(ErrorWithLocation {
1819                kind: MinifyErrorKind::UnsupportedCustomMediaBooleanLogic {
1820                  custom_media_loc: rule.loc,
1821                },
1822                loc,
1823              });
1824              return None;
1825            }
1826          }
1827
1828          if let Some(condition) = &query.condition {
1829            let mut condition = condition.clone();
1830            let r = process_condition(loc, custom_media, media_type, qualifier, &mut condition, seen);
1831            if r.is_err() {
1832              res = r;
1833            }
1834            // Parentheses are required around the condition unless there is a single media feature.
1835            match condition {
1836              MediaCondition::Feature(..) => Some(condition),
1837              _ => Some(condition),
1838            }
1839          } else {
1840            None
1841          }
1842        })
1843        .collect();
1844
1845      seen.remove(name);
1846
1847      if res.is_err() {
1848        return res;
1849      }
1850
1851      if conditions.is_empty() {
1852        return Ok(false);
1853      }
1854
1855      if conditions.len() == 1 {
1856        *condition = conditions.pop().unwrap();
1857      } else {
1858        *condition = MediaCondition::Operation {
1859          conditions,
1860          operator: Operator::Or,
1861        };
1862      }
1863    }
1864    _ => {}
1865  }
1866
1867  Ok(true)
1868}
1869
1870#[cfg(test)]
1871mod tests {
1872  use super::*;
1873  use crate::{
1874    stylesheet::PrinterOptions,
1875    targets::{Browsers, Targets},
1876  };
1877
1878  fn parse(s: &str) -> MediaQuery<'_> {
1879    let mut input = ParserInput::new(&s);
1880    let mut parser = Parser::new(&mut input);
1881    MediaQuery::parse_with_options(&mut parser, &ParserOptions::default()).unwrap()
1882  }
1883
1884  fn and(a: &str, b: &str) -> String {
1885    let mut a = parse(a);
1886    let b = parse(b);
1887    a.and(&b).unwrap();
1888    a.to_css_string(PrinterOptions::default()).unwrap()
1889  }
1890
1891  #[test]
1892  fn test_and() {
1893    assert_eq!(and("(min-width: 250px)", "(color)"), "(width >= 250px) and (color)");
1894    assert_eq!(
1895      and("(min-width: 250px) or (color)", "(orientation: landscape)"),
1896      "((width >= 250px) or (color)) and (orientation: landscape)"
1897    );
1898    assert_eq!(
1899      and("(min-width: 250px) and (color)", "(orientation: landscape)"),
1900      "(width >= 250px) and (color) and (orientation: landscape)"
1901    );
1902    assert_eq!(and("all", "print"), "print");
1903    assert_eq!(and("print", "all"), "print");
1904    assert_eq!(and("all", "not print"), "not print");
1905    assert_eq!(and("not print", "all"), "not print");
1906    assert_eq!(and("not all", "print"), "not all");
1907    assert_eq!(and("print", "not all"), "not all");
1908    assert_eq!(and("print", "screen"), "not all");
1909    assert_eq!(and("not print", "screen"), "screen");
1910    assert_eq!(and("print", "not screen"), "print");
1911    assert_eq!(and("not screen", "print"), "print");
1912    assert_eq!(and("not screen", "not all"), "not all");
1913    assert_eq!(and("print", "(min-width: 250px)"), "print and (width >= 250px)");
1914    assert_eq!(and("(min-width: 250px)", "print"), "print and (width >= 250px)");
1915    assert_eq!(
1916      and("print and (min-width: 250px)", "(color)"),
1917      "print and (width >= 250px) and (color)"
1918    );
1919    assert_eq!(and("all", "only screen"), "only screen");
1920    assert_eq!(and("only screen", "all"), "only screen");
1921    assert_eq!(and("print", "print"), "print");
1922  }
1923
1924  #[test]
1925  fn test_negated_interval_parens() {
1926    let media_query = parse("screen and not (200px <= width < 500px)");
1927    let printer_options = PrinterOptions {
1928      targets: Targets {
1929        browsers: Some(Browsers {
1930          chrome: Some(95 << 16),
1931          ..Default::default()
1932        }),
1933        ..Default::default()
1934      },
1935      ..Default::default()
1936    };
1937    assert_eq!(
1938      media_query.to_css_string(printer_options).unwrap(),
1939      "screen and not ((min-width: 200px) and (not (min-width: 500px)))"
1940    );
1941  }
1942}