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(
829    first,
830    dest,
831    first.needs_parens(Some(operator), &dest.state().targets.current),
832  )?;
833  for item in iter {
834    dest.write_char(' ')?;
835    operator.to_css(dest)?;
836    dest.write_char(' ')?;
837    to_css_with_parens_if_needed(
838      item,
839      dest,
840      item.needs_parens(Some(operator), &dest.state().targets.current),
841    )?;
842  }
843
844  Ok(())
845}
846
847impl<'i> MediaCondition<'i> {
848  fn negate(&self) -> Option<MediaCondition<'i>> {
849    match self {
850      MediaCondition::Not(not) => Some((**not).clone()),
851      MediaCondition::Feature(f) => f.negate().map(MediaCondition::Feature),
852      _ => None,
853    }
854  }
855}
856
857impl<'i> ToCss for MediaCondition<'i> {
858  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
859    match *self {
860      MediaCondition::Feature(ref f) => f.to_css(dest),
861      MediaCondition::Not(ref c) => {
862        if let Some(negated) = c.negate() {
863          negated.to_css(dest)
864        } else {
865          dest.write_str("not ")?;
866          to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.state().targets.current))
867        }
868      }
869      MediaCondition::Operation {
870        ref conditions,
871        operator,
872      } => operation_to_css(operator, conditions, dest),
873      MediaCondition::Unknown(ref tokens) => tokens.to_css(dest, false),
874    }
875  }
876}
877
878/// A [comparator](https://drafts.csswg.org/mediaqueries/#typedef-mf-comparison) within a media query.
879#[derive(Clone, Copy, Debug, Eq, PartialEq)]
880#[cfg_attr(feature = "visitor", derive(Visit))]
881#[cfg_attr(
882  feature = "serde",
883  derive(serde::Serialize, serde::Deserialize),
884  serde(rename_all = "kebab-case")
885)]
886#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
887#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
888pub enum MediaFeatureComparison {
889  /// `=`
890  Equal,
891  /// `>`
892  GreaterThan,
893  /// `>=`
894  GreaterThanEqual,
895  /// `<`
896  LessThan,
897  /// `<=`
898  LessThanEqual,
899}
900
901impl ToCss for MediaFeatureComparison {
902  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
903    use MediaFeatureComparison::*;
904    match self {
905      Equal => dest.delim('=', true),
906      GreaterThan => dest.delim('>', true),
907      GreaterThanEqual => {
908        dest.whitespace()?;
909        dest.write_str(">=")?;
910        dest.whitespace()
911      }
912      LessThan => dest.delim('<', true),
913      LessThanEqual => {
914        dest.whitespace()?;
915        dest.write_str("<=")?;
916        dest.whitespace()
917      }
918    }
919  }
920}
921
922impl MediaFeatureComparison {
923  fn opposite(&self) -> MediaFeatureComparison {
924    match self {
925      MediaFeatureComparison::GreaterThan => MediaFeatureComparison::LessThan,
926      MediaFeatureComparison::GreaterThanEqual => MediaFeatureComparison::LessThanEqual,
927      MediaFeatureComparison::LessThan => MediaFeatureComparison::GreaterThan,
928      MediaFeatureComparison::LessThanEqual => MediaFeatureComparison::GreaterThanEqual,
929      MediaFeatureComparison::Equal => MediaFeatureComparison::Equal,
930    }
931  }
932
933  fn negate(&self) -> MediaFeatureComparison {
934    match self {
935      MediaFeatureComparison::GreaterThan => MediaFeatureComparison::LessThanEqual,
936      MediaFeatureComparison::GreaterThanEqual => MediaFeatureComparison::LessThan,
937      MediaFeatureComparison::LessThan => MediaFeatureComparison::GreaterThanEqual,
938      MediaFeatureComparison::LessThanEqual => MediaFeatureComparison::GreaterThan,
939      MediaFeatureComparison::Equal => MediaFeatureComparison::Equal,
940    }
941  }
942}
943
944/// A generic media feature or container feature.
945#[derive(Clone, Debug, PartialEq)]
946#[cfg_attr(
947  feature = "visitor",
948  derive(Visit),
949  visit(visit_media_feature, MEDIA_QUERIES, <'i, MediaFeatureId>),
950  visit(<'i, ContainerSizeFeatureId>),
951  visit(<'i, ScrollStateFeatureId>)
952)]
953#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
954#[cfg_attr(
955  feature = "serde",
956  derive(serde::Serialize, serde::Deserialize),
957  serde(tag = "type", rename_all = "kebab-case")
958)]
959#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
960pub enum QueryFeature<'i, FeatureId> {
961  /// A plain media feature, e.g. `(min-width: 240px)`.
962  Plain {
963    /// The name of the feature.
964    #[cfg_attr(feature = "serde", serde(borrow))]
965    name: MediaFeatureName<'i, FeatureId>,
966    /// The feature value.
967    value: MediaFeatureValue<'i>,
968  },
969  /// A boolean feature, e.g. `(hover)`.
970  Boolean {
971    /// The name of the feature.
972    name: MediaFeatureName<'i, FeatureId>,
973  },
974  /// A range, e.g. `(width > 240px)`.
975  Range {
976    /// The name of the feature.
977    name: MediaFeatureName<'i, FeatureId>,
978    /// A comparator.
979    operator: MediaFeatureComparison,
980    /// The feature value.
981    value: MediaFeatureValue<'i>,
982  },
983  /// An interval, e.g. `(120px < width < 240px)`.
984  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
985  Interval {
986    /// The name of the feature.
987    name: MediaFeatureName<'i, FeatureId>,
988    /// A start value.
989    start: MediaFeatureValue<'i>,
990    /// A comparator for the start value.
991    start_operator: MediaFeatureComparison,
992    /// The end value.
993    end: MediaFeatureValue<'i>,
994    /// A comparator for the end value.
995    end_operator: MediaFeatureComparison,
996  },
997}
998
999/// A [media feature](https://drafts.csswg.org/mediaqueries/#typedef-media-feature)
1000pub type MediaFeature<'i> = QueryFeature<'i, MediaFeatureId>;
1001
1002impl<'i, FeatureId> ParseWithOptions<'i> for QueryFeature<'i, FeatureId>
1003where
1004  FeatureId: for<'x> Parse<'x> + std::fmt::Debug + PartialEq + ValueType + Clone,
1005{
1006  fn parse_with_options<'t>(
1007    input: &mut Parser<'i, 't>,
1008    options: &ParserOptions<'i>,
1009  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1010    match input.try_parse(|input| Self::parse_name_first(input, options)) {
1011      Ok(res) => Ok(res),
1012      Err(
1013        err @ ParseError {
1014          kind: ParseErrorKind::Custom(ParserError::InvalidMediaQuery),
1015          ..
1016        },
1017      ) => Err(err),
1018      _ => Self::parse_value_first(input),
1019    }
1020  }
1021}
1022
1023impl<'i, FeatureId> QueryFeature<'i, FeatureId>
1024where
1025  FeatureId: for<'x> Parse<'x> + std::fmt::Debug + PartialEq + ValueType + Clone,
1026{
1027  fn parse_name_first<'t>(
1028    input: &mut Parser<'i, 't>,
1029    options: &ParserOptions<'i>,
1030  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1031    let (name, legacy_op) = MediaFeatureName::parse(input)?;
1032
1033    let operator = input.try_parse(|input| consume_operation_or_colon(input, true));
1034    let operator = match operator {
1035      Err(..) => return Ok(QueryFeature::Boolean { name }),
1036      Ok(operator) => operator,
1037    };
1038
1039    if operator.is_some() && legacy_op.is_some() {
1040      return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1041    }
1042
1043    let value = MediaFeatureValue::parse(input, name.value_type())?;
1044    if !value.check_type(name.value_type()) {
1045      if options.error_recovery {
1046        options.warn(ParseError {
1047          kind: ParseErrorKind::Custom(ParserError::InvalidMediaQuery),
1048          location: input.current_source_location(),
1049        });
1050      } else {
1051        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1052      }
1053    }
1054
1055    if let Some(operator) = operator.or(legacy_op) {
1056      if !name.value_type().allows_ranges() {
1057        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1058      }
1059
1060      Ok(QueryFeature::Range { name, operator, value })
1061    } else {
1062      Ok(QueryFeature::Plain { name, value })
1063    }
1064  }
1065
1066  fn parse_value_first<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1067    // We need to find the feature name first so we know the type.
1068    let start = input.state();
1069    let name = loop {
1070      if let Ok((name, legacy_op)) = MediaFeatureName::parse(input) {
1071        if legacy_op.is_some() {
1072          return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1073        }
1074        break name;
1075      }
1076      if input.is_exhausted() {
1077        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1078      }
1079    };
1080
1081    input.reset(&start);
1082
1083    // Now we can parse the first value.
1084    let value = MediaFeatureValue::parse(input, name.value_type())?;
1085    let operator = consume_operation_or_colon(input, false)?;
1086
1087    // Skip over the feature name again.
1088    {
1089      let (feature_name, _) = MediaFeatureName::parse(input)?;
1090      debug_assert_eq!(name, feature_name);
1091    }
1092
1093    if !name.value_type().allows_ranges() || !value.check_type(name.value_type()) {
1094      return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1095    }
1096
1097    if let Ok(end_operator) = input.try_parse(|input| consume_operation_or_colon(input, false)) {
1098      let start_operator = operator.unwrap();
1099      let end_operator = end_operator.unwrap();
1100      // Start and end operators must be matching.
1101      match (start_operator, end_operator) {
1102        (MediaFeatureComparison::GreaterThan, MediaFeatureComparison::GreaterThan)
1103        | (MediaFeatureComparison::GreaterThan, MediaFeatureComparison::GreaterThanEqual)
1104        | (MediaFeatureComparison::GreaterThanEqual, MediaFeatureComparison::GreaterThanEqual)
1105        | (MediaFeatureComparison::GreaterThanEqual, MediaFeatureComparison::GreaterThan)
1106        | (MediaFeatureComparison::LessThan, MediaFeatureComparison::LessThan)
1107        | (MediaFeatureComparison::LessThan, MediaFeatureComparison::LessThanEqual)
1108        | (MediaFeatureComparison::LessThanEqual, MediaFeatureComparison::LessThanEqual)
1109        | (MediaFeatureComparison::LessThanEqual, MediaFeatureComparison::LessThan) => {}
1110        _ => return Err(input.new_custom_error(ParserError::InvalidMediaQuery)),
1111      };
1112
1113      let end_value = MediaFeatureValue::parse(input, name.value_type())?;
1114      if !end_value.check_type(name.value_type()) {
1115        return Err(input.new_custom_error(ParserError::InvalidMediaQuery));
1116      }
1117
1118      Ok(QueryFeature::Interval {
1119        name,
1120        start: value,
1121        start_operator,
1122        end: end_value,
1123        end_operator,
1124      })
1125    } else {
1126      let operator = operator.unwrap().opposite();
1127      Ok(QueryFeature::Range { name, operator, value })
1128    }
1129  }
1130
1131  pub(crate) fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool {
1132    match self {
1133      QueryFeature::Interval { .. } => {
1134        should_compile!(targets, MediaIntervalSyntax) && parent_operator != Some(Operator::And)
1135      }
1136      QueryFeature::Range { operator, .. } => {
1137        should_compile!(targets, MediaRangeSyntax)
1138          && matches!(
1139            operator,
1140            MediaFeatureComparison::GreaterThan | MediaFeatureComparison::LessThan
1141          )
1142      }
1143      _ => false,
1144    }
1145  }
1146
1147  fn negate(&self) -> Option<QueryFeature<'i, FeatureId>> {
1148    match self {
1149      QueryFeature::Range { name, operator, value } => Some(QueryFeature::Range {
1150        name: (*name).clone(),
1151        operator: operator.negate(),
1152        value: value.clone(),
1153      }),
1154      _ => None,
1155    }
1156  }
1157}
1158
1159impl<'i, FeatureId: FeatureToCss> ToCss for QueryFeature<'i, FeatureId> {
1160  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1161    match self {
1162      QueryFeature::Boolean { name } => {
1163        dest.write_char('(')?;
1164        name.to_css(dest)?;
1165      }
1166      QueryFeature::Plain { name, value } => {
1167        dest.write_char('(')?;
1168        name.to_css(dest)?;
1169        dest.delim(':', false)?;
1170        value.to_css(dest)?;
1171      }
1172      QueryFeature::Range { name, operator, value } => {
1173        // If range syntax is unsupported, use min/max prefix if possible.
1174        if should_compile!(dest.state().targets.current, MediaRangeSyntax) {
1175          return write_min_max(operator, name, value, dest, false);
1176        }
1177
1178        dest.write_char('(')?;
1179        name.to_css(dest)?;
1180        operator.to_css(dest)?;
1181        value.to_css(dest)?;
1182      }
1183      QueryFeature::Interval {
1184        name,
1185        start,
1186        start_operator,
1187        end,
1188        end_operator,
1189      } => {
1190        if should_compile!(dest.state().targets.current, MediaIntervalSyntax) {
1191          write_min_max(&start_operator.opposite(), name, start, dest, true)?;
1192          dest.write_str(" and ")?;
1193          return write_min_max(end_operator, name, end, dest, true);
1194        }
1195
1196        dest.write_char('(')?;
1197        start.to_css(dest)?;
1198        start_operator.to_css(dest)?;
1199        name.to_css(dest)?;
1200        end_operator.to_css(dest)?;
1201        end.to_css(dest)?;
1202      }
1203    }
1204
1205    dest.write_char(')')?;
1206
1207    Ok(())
1208  }
1209}
1210
1211/// A media feature name.
1212#[derive(Debug, Clone, PartialEq)]
1213#[cfg_attr(feature = "visitor", derive(Visit))]
1214#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1215#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(untagged))]
1216#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1217pub enum MediaFeatureName<'i, FeatureId> {
1218  /// A standard media query feature identifier.
1219  Standard(FeatureId),
1220  /// A custom author-defined environment variable.
1221  #[cfg_attr(feature = "serde", serde(borrow))]
1222  Custom(DashedIdent<'i>),
1223  /// An unknown environment variable.
1224  Unknown(Ident<'i>),
1225}
1226
1227impl<'i, FeatureId: for<'x> Parse<'x>> MediaFeatureName<'i, FeatureId> {
1228  /// Parses a media feature name.
1229  pub fn parse<'t>(
1230    input: &mut Parser<'i, 't>,
1231  ) -> Result<(Self, Option<MediaFeatureComparison>), ParseError<'i, ParserError<'i>>> {
1232    let ident = input.expect_ident()?;
1233
1234    if ident.starts_with("--") {
1235      return Ok((MediaFeatureName::Custom(DashedIdent(ident.into())), None));
1236    }
1237
1238    let mut name = ident.as_ref();
1239
1240    // Webkit places its prefixes before "min" and "max". Remove it first, and
1241    // re-add after removing min/max.
1242    let is_webkit = starts_with_ignore_ascii_case(&name, "-webkit-");
1243    if is_webkit {
1244      name = &name[8..];
1245    }
1246
1247    let comparator = if starts_with_ignore_ascii_case(&name, "min-") {
1248      name = &name[4..];
1249      Some(MediaFeatureComparison::GreaterThanEqual)
1250    } else if starts_with_ignore_ascii_case(&name, "max-") {
1251      name = &name[4..];
1252      Some(MediaFeatureComparison::LessThanEqual)
1253    } else {
1254      None
1255    };
1256
1257    let name = if is_webkit {
1258      Cow::Owned(format!("-webkit-{}", name))
1259    } else {
1260      Cow::Borrowed(name)
1261    };
1262
1263    if let Ok(standard) = FeatureId::parse_string(&name) {
1264      return Ok((MediaFeatureName::Standard(standard), comparator));
1265    }
1266
1267    Ok((MediaFeatureName::Unknown(Ident(ident.into())), None))
1268  }
1269}
1270
1271mod private {
1272  use super::*;
1273
1274  /// A trait for feature ids which can get a value type.
1275  pub trait ValueType {
1276    /// Returns the value type for this feature id.
1277    fn value_type(&self) -> MediaFeatureType;
1278  }
1279}
1280
1281pub(crate) use private::ValueType;
1282
1283impl<'i, FeatureId: ValueType> ValueType for MediaFeatureName<'i, FeatureId> {
1284  fn value_type(&self) -> MediaFeatureType {
1285    match self {
1286      Self::Standard(standard) => standard.value_type(),
1287      _ => MediaFeatureType::Unknown,
1288    }
1289  }
1290}
1291
1292impl<'i, FeatureId: FeatureToCss> ToCss for MediaFeatureName<'i, FeatureId> {
1293  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1294    match self {
1295      Self::Standard(v) => v.to_css(dest),
1296      Self::Custom(v) => v.to_css(dest),
1297      Self::Unknown(v) => v.to_css(dest),
1298    }
1299  }
1300}
1301
1302impl<'i, FeatureId: FeatureToCss> FeatureToCss for MediaFeatureName<'i, FeatureId> {
1303  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
1304    &self,
1305    prefix: &str,
1306    dest: &mut PrinterT,
1307  ) -> Result<(), PrinterError> {
1308    match self {
1309      Self::Standard(v) => v.to_css_with_prefix(prefix, dest),
1310      Self::Custom(v) => {
1311        dest.write_str(prefix)?;
1312        v.to_css(dest)
1313      }
1314      Self::Unknown(v) => {
1315        dest.write_str(prefix)?;
1316        v.to_css(dest)
1317      }
1318    }
1319  }
1320}
1321
1322/// The type of a media feature.
1323#[derive(PartialEq)]
1324pub enum MediaFeatureType {
1325  /// A length value.
1326  Length,
1327  /// A number value.
1328  Number,
1329  /// An integer value.
1330  Integer,
1331  /// A boolean value, either 0 or 1.
1332  Boolean,
1333  /// A resolution.
1334  Resolution,
1335  /// A ratio.
1336  Ratio,
1337  /// An identifier.
1338  Ident,
1339  /// An unknown type.
1340  Unknown,
1341}
1342
1343impl MediaFeatureType {
1344  fn allows_ranges(&self) -> bool {
1345    use MediaFeatureType::*;
1346    match self {
1347      Length => true,
1348      Number => true,
1349      Integer => true,
1350      Boolean => false,
1351      Resolution => true,
1352      Ratio => true,
1353      Ident => false,
1354      Unknown => true,
1355    }
1356  }
1357}
1358
1359macro_rules! define_query_features {
1360  (
1361    $(#[$outer:meta])*
1362    $vis:vis enum $name:ident {
1363      $(
1364        $(#[$meta: meta])*
1365        $str: literal: $id: ident = $ty: ident,
1366      )+
1367    }
1368  ) => {
1369    crate::macros::enum_property! {
1370      $(#[$outer])*
1371      $vis enum $name {
1372        $(
1373          $(#[$meta])*
1374          $str: $id,
1375        )+
1376      }
1377    }
1378
1379    impl ValueType for $name {
1380      fn value_type(&self) -> MediaFeatureType {
1381        match self {
1382          $(
1383            Self::$id => MediaFeatureType::$ty,
1384          )+
1385        }
1386      }
1387    }
1388  }
1389}
1390
1391pub(crate) use define_query_features;
1392
1393define_query_features! {
1394  /// A media query feature identifier.
1395  pub enum MediaFeatureId {
1396    /// The [width](https://w3c.github.io/csswg-drafts/mediaqueries-5/#width) media feature.
1397    "width": Width = Length,
1398    /// The [height](https://w3c.github.io/csswg-drafts/mediaqueries-5/#height) media feature.
1399    "height": Height = Length,
1400    /// The [aspect-ratio](https://w3c.github.io/csswg-drafts/mediaqueries-5/#aspect-ratio) media feature.
1401    "aspect-ratio": AspectRatio = Ratio,
1402    /// The [orientation](https://w3c.github.io/csswg-drafts/mediaqueries-5/#orientation) media feature.
1403    "orientation": Orientation = Ident,
1404    /// The [overflow-block](https://w3c.github.io/csswg-drafts/mediaqueries-5/#overflow-block) media feature.
1405    "overflow-block": OverflowBlock = Ident,
1406    /// The [overflow-inline](https://w3c.github.io/csswg-drafts/mediaqueries-5/#overflow-inline) media feature.
1407    "overflow-inline": OverflowInline = Ident,
1408    /// The [horizontal-viewport-segments](https://w3c.github.io/csswg-drafts/mediaqueries-5/#horizontal-viewport-segments) media feature.
1409    "horizontal-viewport-segments": HorizontalViewportSegments = Integer,
1410    /// The [vertical-viewport-segments](https://w3c.github.io/csswg-drafts/mediaqueries-5/#vertical-viewport-segments) media feature.
1411    "vertical-viewport-segments": VerticalViewportSegments = Integer,
1412    /// The [display-mode](https://w3c.github.io/csswg-drafts/mediaqueries-5/#display-mode) media feature.
1413    "display-mode": DisplayMode = Ident,
1414    /// The [resolution](https://w3c.github.io/csswg-drafts/mediaqueries-5/#resolution) media feature.
1415    "resolution": Resolution = Resolution, // | infinite??
1416    /// The [scan](https://w3c.github.io/csswg-drafts/mediaqueries-5/#scan) media feature.
1417    "scan": Scan = Ident,
1418    /// The [grid](https://w3c.github.io/csswg-drafts/mediaqueries-5/#grid) media feature.
1419    "grid": Grid = Boolean,
1420    /// The [update](https://w3c.github.io/csswg-drafts/mediaqueries-5/#update) media feature.
1421    "update": Update = Ident,
1422    /// The [environment-blending](https://w3c.github.io/csswg-drafts/mediaqueries-5/#environment-blending) media feature.
1423    "environment-blending": EnvironmentBlending = Ident,
1424    /// The [color](https://w3c.github.io/csswg-drafts/mediaqueries-5/#color) media feature.
1425    "color": Color = Integer,
1426    /// The [color-index](https://w3c.github.io/csswg-drafts/mediaqueries-5/#color-index) media feature.
1427    "color-index": ColorIndex = Integer,
1428    /// The [monochrome](https://w3c.github.io/csswg-drafts/mediaqueries-5/#monochrome) media feature.
1429    "monochrome": Monochrome = Integer,
1430    /// The [color-gamut](https://w3c.github.io/csswg-drafts/mediaqueries-5/#color-gamut) media feature.
1431    "color-gamut": ColorGamut = Ident,
1432    /// The [dynamic-range](https://w3c.github.io/csswg-drafts/mediaqueries-5/#dynamic-range) media feature.
1433    "dynamic-range": DynamicRange = Ident,
1434    /// The [inverted-colors](https://w3c.github.io/csswg-drafts/mediaqueries-5/#inverted-colors) media feature.
1435    "inverted-colors": InvertedColors = Ident,
1436    /// The [pointer](https://w3c.github.io/csswg-drafts/mediaqueries-5/#pointer) media feature.
1437    "pointer": Pointer = Ident,
1438    /// The [hover](https://w3c.github.io/csswg-drafts/mediaqueries-5/#hover) media feature.
1439    "hover": Hover = Ident,
1440    /// The [any-pointer](https://w3c.github.io/csswg-drafts/mediaqueries-5/#any-pointer) media feature.
1441    "any-pointer": AnyPointer = Ident,
1442    /// The [any-hover](https://w3c.github.io/csswg-drafts/mediaqueries-5/#any-hover) media feature.
1443    "any-hover": AnyHover = Ident,
1444    /// The [nav-controls](https://w3c.github.io/csswg-drafts/mediaqueries-5/#nav-controls) media feature.
1445    "nav-controls": NavControls = Ident,
1446    /// The [video-color-gamut](https://w3c.github.io/csswg-drafts/mediaqueries-5/#video-color-gamut) media feature.
1447    "video-color-gamut": VideoColorGamut = Ident,
1448    /// The [video-dynamic-range](https://w3c.github.io/csswg-drafts/mediaqueries-5/#video-dynamic-range) media feature.
1449    "video-dynamic-range": VideoDynamicRange = Ident,
1450    /// The [scripting](https://w3c.github.io/csswg-drafts/mediaqueries-5/#scripting) media feature.
1451    "scripting": Scripting = Ident,
1452    /// The [prefers-reduced-motion](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-reduced-motion) media feature.
1453    "prefers-reduced-motion": PrefersReducedMotion = Ident,
1454    /// The [prefers-reduced-transparency](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-reduced-transparency) media feature.
1455    "prefers-reduced-transparency": PrefersReducedTransparency = Ident,
1456    /// The [prefers-contrast](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-contrast) media feature.
1457    "prefers-contrast": PrefersContrast = Ident,
1458    /// The [forced-colors](https://w3c.github.io/csswg-drafts/mediaqueries-5/#forced-colors) media feature.
1459    "forced-colors": ForcedColors = Ident,
1460    /// The [prefers-color-scheme](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-color-scheme) media feature.
1461    "prefers-color-scheme": PrefersColorScheme = Ident,
1462    /// The [prefers-reduced-data](https://w3c.github.io/csswg-drafts/mediaqueries-5/#prefers-reduced-data) media feature.
1463    "prefers-reduced-data": PrefersReducedData = Ident,
1464    /// The [device-width](https://w3c.github.io/csswg-drafts/mediaqueries-5/#device-width) media feature.
1465    "device-width": DeviceWidth = Length,
1466    /// The [device-height](https://w3c.github.io/csswg-drafts/mediaqueries-5/#device-height) media feature.
1467    "device-height": DeviceHeight = Length,
1468    /// The [device-aspect-ratio](https://w3c.github.io/csswg-drafts/mediaqueries-5/#device-aspect-ratio) media feature.
1469    "device-aspect-ratio": DeviceAspectRatio = Ratio,
1470
1471    /// The non-standard -webkit-device-pixel-ratio media feature.
1472    "-webkit-device-pixel-ratio": WebKitDevicePixelRatio = Number,
1473    /// The non-standard -moz-device-pixel-ratio media feature.
1474    "-moz-device-pixel-ratio": MozDevicePixelRatio = Number,
1475
1476    // TODO: parse non-standard media queries?
1477    // -moz-device-orientation
1478    // -webkit-transform-3d
1479  }
1480}
1481
1482pub(crate) trait FeatureToCss: ToCss {
1483  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
1484    &self,
1485    prefix: &str,
1486    dest: &mut PrinterT,
1487  ) -> Result<(), PrinterError>;
1488}
1489
1490impl FeatureToCss for MediaFeatureId {
1491  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
1492    &self,
1493    prefix: &str,
1494    dest: &mut PrinterT,
1495  ) -> Result<(), PrinterError> {
1496    match self {
1497      MediaFeatureId::WebKitDevicePixelRatio => {
1498        dest.write_str("-webkit-")?;
1499        dest.write_str(prefix)?;
1500        dest.write_str("device-pixel-ratio")?;
1501        Ok(())
1502      }
1503      _ => {
1504        dest.write_str(prefix)?;
1505        self.to_css(dest)
1506      }
1507    }
1508  }
1509}
1510
1511#[inline]
1512fn write_min_max<PrinterT: crate::printer::PrinterTrait, FeatureId: FeatureToCss>(
1513  operator: &MediaFeatureComparison,
1514  name: &MediaFeatureName<FeatureId>,
1515  value: &MediaFeatureValue,
1516  dest: &mut PrinterT,
1517  is_range: bool,
1518) -> Result<(), PrinterError> {
1519  let prefix = match operator {
1520    MediaFeatureComparison::GreaterThan => {
1521      if is_range {
1522        dest.write_char('(')?;
1523      }
1524      dest.write_str("not ")?;
1525      Some("max-")
1526    }
1527    MediaFeatureComparison::GreaterThanEqual => Some("min-"),
1528    MediaFeatureComparison::LessThan => {
1529      if is_range {
1530        dest.write_char('(')?;
1531      }
1532      dest.write_str("not ")?;
1533      Some("min-")
1534    }
1535    MediaFeatureComparison::LessThanEqual => Some("max-"),
1536    MediaFeatureComparison::Equal => None,
1537  };
1538
1539  dest.write_char('(')?;
1540  if let Some(prefix) = prefix {
1541    name.to_css_with_prefix(prefix, dest)?;
1542  } else {
1543    name.to_css(dest)?;
1544  }
1545
1546  dest.delim(':', false)?;
1547  value.to_css(dest)?;
1548
1549  if is_range
1550    && matches!(
1551      operator,
1552      MediaFeatureComparison::GreaterThan | MediaFeatureComparison::LessThan
1553    )
1554  {
1555    dest.write_char(')')?;
1556  }
1557
1558  dest.write_char(')')?;
1559  Ok(())
1560}
1561
1562/// [media feature value](https://drafts.csswg.org/mediaqueries/#typedef-mf-value) within a media query.
1563///
1564/// See [MediaFeature](MediaFeature).
1565#[derive(Clone, Debug, PartialEq)]
1566#[cfg_attr(feature = "visitor", derive(Visit), visit(visit_media_feature_value, MEDIA_QUERIES))]
1567#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1568#[cfg_attr(
1569  feature = "serde",
1570  derive(serde::Serialize, serde::Deserialize),
1571  serde(tag = "type", content = "value", rename_all = "kebab-case")
1572)]
1573#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1574pub enum MediaFeatureValue<'i> {
1575  /// A length value.
1576  Length(Length),
1577  /// A number value.
1578  Number(CSSNumber),
1579  /// An integer value.
1580  Integer(CSSInteger),
1581  /// A boolean value.
1582  Boolean(bool),
1583  /// A resolution.
1584  Resolution(Resolution),
1585  /// A ratio.
1586  Ratio(Ratio),
1587  /// An identifier.
1588  #[cfg_attr(feature = "serde", serde(borrow))]
1589  Ident(Ident<'i>),
1590  /// An environment variable reference.
1591  Env(EnvironmentVariable<'i>),
1592}
1593
1594impl<'i> MediaFeatureValue<'i> {
1595  fn value_type(&self) -> MediaFeatureType {
1596    use MediaFeatureValue::*;
1597    match self {
1598      Length(..) => MediaFeatureType::Length,
1599      Number(..) => MediaFeatureType::Number,
1600      Integer(..) => MediaFeatureType::Integer,
1601      Boolean(..) => MediaFeatureType::Boolean,
1602      Resolution(..) => MediaFeatureType::Resolution,
1603      Ratio(..) => MediaFeatureType::Ratio,
1604      Ident(..) => MediaFeatureType::Ident,
1605      Env(..) => MediaFeatureType::Unknown,
1606    }
1607  }
1608
1609  fn check_type(&self, expected_type: MediaFeatureType) -> bool {
1610    match (expected_type, self.value_type()) {
1611      (_, MediaFeatureType::Unknown) | (MediaFeatureType::Unknown, _) => true,
1612      (a, b) => a == b,
1613    }
1614  }
1615}
1616
1617impl<'i> MediaFeatureValue<'i> {
1618  /// Parses a single media query feature value, with an expected type.
1619  /// If the type is unknown, pass MediaFeatureType::Unknown instead.
1620  pub fn parse<'t>(
1621    input: &mut Parser<'i, 't>,
1622    expected_type: MediaFeatureType,
1623  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1624    if let Ok(value) = input.try_parse(|input| Self::parse_known(input, expected_type)) {
1625      return Ok(value);
1626    }
1627
1628    Self::parse_unknown(input)
1629  }
1630
1631  fn parse_known<'t>(
1632    input: &mut Parser<'i, 't>,
1633    expected_type: MediaFeatureType,
1634  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1635    match expected_type {
1636      MediaFeatureType::Boolean => {
1637        let value = CSSInteger::parse(input)?;
1638        if value != 0 && value != 1 {
1639          return Err(input.new_custom_error(ParserError::InvalidValue));
1640        }
1641        Ok(MediaFeatureValue::Boolean(value == 1))
1642      }
1643      MediaFeatureType::Number => Ok(MediaFeatureValue::Number(CSSNumber::parse(input)?)),
1644      MediaFeatureType::Integer => Ok(MediaFeatureValue::Integer(CSSInteger::parse(input)?)),
1645      MediaFeatureType::Length => Ok(MediaFeatureValue::Length(Length::parse(input)?)),
1646      MediaFeatureType::Resolution => Ok(MediaFeatureValue::Resolution(Resolution::parse(input)?)),
1647      MediaFeatureType::Ratio => Ok(MediaFeatureValue::Ratio(Ratio::parse(input)?)),
1648      MediaFeatureType::Ident => Ok(MediaFeatureValue::Ident(Ident::parse(input)?)),
1649      MediaFeatureType::Unknown => Err(input.new_custom_error(ParserError::InvalidValue)),
1650    }
1651  }
1652
1653  fn parse_unknown<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1654    // Ratios are ambiguous with numbers because the second param is optional (e.g. 2/1 == 2).
1655    // We require the / delimiter when parsing ratios so that 2/1 ends up as a ratio and 2 is
1656    // parsed as a number.
1657    if let Ok(ratio) = input.try_parse(Ratio::parse_required) {
1658      return Ok(MediaFeatureValue::Ratio(ratio));
1659    }
1660
1661    // Parse number next so that unitless values are not parsed as lengths.
1662    if let Ok(num) = input.try_parse(CSSNumber::parse) {
1663      return Ok(MediaFeatureValue::Number(num));
1664    }
1665
1666    if let Ok(length) = input.try_parse(Length::parse) {
1667      return Ok(MediaFeatureValue::Length(length));
1668    }
1669
1670    if let Ok(res) = input.try_parse(Resolution::parse) {
1671      return Ok(MediaFeatureValue::Resolution(res));
1672    }
1673
1674    if let Ok(env) = input.try_parse(|input| EnvironmentVariable::parse(input, &ParserOptions::default(), 0)) {
1675      return Ok(MediaFeatureValue::Env(env));
1676    }
1677
1678    let ident = Ident::parse(input)?;
1679    Ok(MediaFeatureValue::Ident(ident))
1680  }
1681}
1682
1683impl<'i> ToCss for MediaFeatureValue<'i> {
1684  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1685    match self {
1686      MediaFeatureValue::Length(len) => len.to_css(dest),
1687      MediaFeatureValue::Number(num) => num.to_css(dest),
1688      MediaFeatureValue::Integer(num) => num.to_css(dest),
1689      MediaFeatureValue::Boolean(b) => {
1690        if *b {
1691          dest.write_char('1')?;
1692          Ok(())
1693        } else {
1694          dest.write_char('0')?;
1695          Ok(())
1696        }
1697      }
1698      MediaFeatureValue::Resolution(res) => res.to_css(dest),
1699      MediaFeatureValue::Ratio(ratio) => ratio.to_css(dest),
1700      MediaFeatureValue::Ident(id) => {
1701        id.to_css(dest)?;
1702        Ok(())
1703      }
1704      MediaFeatureValue::Env(env) => env.to_css(dest, false),
1705    }
1706  }
1707}
1708
1709/// Consumes an operation or a colon, or returns an error.
1710fn consume_operation_or_colon<'i, 't>(
1711  input: &mut Parser<'i, 't>,
1712  allow_colon: bool,
1713) -> Result<Option<MediaFeatureComparison>, ParseError<'i, ParserError<'i>>> {
1714  let location = input.current_source_location();
1715  let first_delim = {
1716    let location = input.current_source_location();
1717    let next_token = input.next()?;
1718    match next_token {
1719      Token::Colon if allow_colon => return Ok(None),
1720      Token::Delim(oper) => oper,
1721      t => return Err(location.new_unexpected_token_error(t.clone())),
1722    }
1723  };
1724  Ok(Some(match first_delim {
1725    '=' => MediaFeatureComparison::Equal,
1726    '>' => {
1727      if input.try_parse(|i| i.expect_delim('=')).is_ok() {
1728        MediaFeatureComparison::GreaterThanEqual
1729      } else {
1730        MediaFeatureComparison::GreaterThan
1731      }
1732    }
1733    '<' => {
1734      if input.try_parse(|i| i.expect_delim('=')).is_ok() {
1735        MediaFeatureComparison::LessThanEqual
1736      } else {
1737        MediaFeatureComparison::LessThan
1738      }
1739    }
1740    d => return Err(location.new_unexpected_token_error(Token::Delim(*d))),
1741  }))
1742}
1743
1744fn process_condition<'i>(
1745  loc: Location,
1746  custom_media: &HashMap<CowArcStr<'i>, CustomMediaRule<'i>>,
1747  media_type: &mut MediaType<'i>,
1748  qualifier: &mut Option<Qualifier>,
1749  condition: &mut MediaCondition<'i>,
1750  seen: &mut HashSet<DashedIdent<'i>>,
1751) -> Result<bool, MinifyError> {
1752  match condition {
1753    MediaCondition::Not(cond) => {
1754      let used = process_condition(loc, custom_media, media_type, qualifier, &mut *cond, seen)?;
1755      if !used {
1756        // If unused, only a media type remains so apply a not qualifier.
1757        // If it is already not, then it cancels out.
1758        *qualifier = if *qualifier == Some(Qualifier::Not) {
1759          None
1760        } else {
1761          Some(Qualifier::Not)
1762        };
1763        return Ok(false);
1764      }
1765
1766      // Unwrap nested nots
1767      match &**cond {
1768        MediaCondition::Not(cond) => {
1769          *condition = (**cond).clone();
1770        }
1771        _ => {}
1772      }
1773    }
1774    MediaCondition::Operation { conditions, .. } => {
1775      let mut res = Ok(true);
1776      conditions.retain_mut(|condition| {
1777        let r = process_condition(loc, custom_media, media_type, qualifier, condition, seen);
1778        if let Ok(used) = r {
1779          used
1780        } else {
1781          res = r;
1782          false
1783        }
1784      });
1785      return res;
1786    }
1787    MediaCondition::Feature(QueryFeature::Boolean { name }) => {
1788      let name = match name {
1789        MediaFeatureName::Custom(name) => name,
1790        _ => return Ok(true),
1791      };
1792
1793      if seen.contains(name) {
1794        return Err(ErrorWithLocation {
1795          kind: MinifyErrorKind::CircularCustomMedia { name: name.to_string() },
1796          loc,
1797        });
1798      }
1799
1800      let rule = custom_media.get(&name.0).ok_or_else(|| ErrorWithLocation {
1801        kind: MinifyErrorKind::CustomMediaNotDefined { name: name.to_string() },
1802        loc,
1803      })?;
1804
1805      seen.insert(name.clone());
1806
1807      let mut res = Ok(true);
1808      let mut conditions: Vec<MediaCondition> = rule
1809        .query
1810        .media_queries
1811        .iter()
1812        .filter_map(|query| {
1813          if query.media_type != MediaType::All || query.qualifier != None {
1814            if *media_type == MediaType::All {
1815              // `not all` will never match.
1816              if *qualifier == Some(Qualifier::Not) {
1817                res = Ok(false);
1818                return None;
1819              }
1820
1821              // Propagate media type and qualifier to @media rule.
1822              *media_type = query.media_type.clone();
1823              *qualifier = query.qualifier.clone();
1824            } else if query.media_type != *media_type || query.qualifier != *qualifier {
1825              // Boolean logic with media types is hard to emulate, so we error for now.
1826              res = Err(ErrorWithLocation {
1827                kind: MinifyErrorKind::UnsupportedCustomMediaBooleanLogic {
1828                  custom_media_loc: rule.loc,
1829                },
1830                loc,
1831              });
1832              return None;
1833            }
1834          }
1835
1836          if let Some(condition) = &query.condition {
1837            let mut condition = condition.clone();
1838            let r = process_condition(loc, custom_media, media_type, qualifier, &mut condition, seen);
1839            if r.is_err() {
1840              res = r;
1841            }
1842            // Parentheses are required around the condition unless there is a single media feature.
1843            match condition {
1844              MediaCondition::Feature(..) => Some(condition),
1845              _ => Some(condition),
1846            }
1847          } else {
1848            None
1849          }
1850        })
1851        .collect();
1852
1853      seen.remove(name);
1854
1855      if res.is_err() {
1856        return res;
1857      }
1858
1859      if conditions.is_empty() {
1860        return Ok(false);
1861      }
1862
1863      if conditions.len() == 1 {
1864        *condition = conditions.pop().unwrap();
1865      } else {
1866        *condition = MediaCondition::Operation {
1867          conditions,
1868          operator: Operator::Or,
1869        };
1870      }
1871    }
1872    _ => {}
1873  }
1874
1875  Ok(true)
1876}
1877
1878#[cfg(test)]
1879mod tests {
1880  use super::*;
1881  use crate::{
1882    stylesheet::PrinterOptions,
1883    targets::{Browsers, Targets},
1884  };
1885
1886  fn parse(s: &str) -> MediaQuery<'_> {
1887    let mut input = ParserInput::new(&s);
1888    let mut parser = Parser::new(&mut input);
1889    MediaQuery::parse_with_options(&mut parser, &ParserOptions::default()).unwrap()
1890  }
1891
1892  fn and(a: &str, b: &str) -> String {
1893    let mut a = parse(a);
1894    let b = parse(b);
1895    a.and(&b).unwrap();
1896    a.to_css_string(PrinterOptions::default()).unwrap()
1897  }
1898
1899  #[test]
1900  fn test_and() {
1901    assert_eq!(and("(min-width: 250px)", "(color)"), "(width >= 250px) and (color)");
1902    assert_eq!(
1903      and("(min-width: 250px) or (color)", "(orientation: landscape)"),
1904      "((width >= 250px) or (color)) and (orientation: landscape)"
1905    );
1906    assert_eq!(
1907      and("(min-width: 250px) and (color)", "(orientation: landscape)"),
1908      "(width >= 250px) and (color) and (orientation: landscape)"
1909    );
1910    assert_eq!(and("all", "print"), "print");
1911    assert_eq!(and("print", "all"), "print");
1912    assert_eq!(and("all", "not print"), "not print");
1913    assert_eq!(and("not print", "all"), "not print");
1914    assert_eq!(and("not all", "print"), "not all");
1915    assert_eq!(and("print", "not all"), "not all");
1916    assert_eq!(and("print", "screen"), "not all");
1917    assert_eq!(and("not print", "screen"), "screen");
1918    assert_eq!(and("print", "not screen"), "print");
1919    assert_eq!(and("not screen", "print"), "print");
1920    assert_eq!(and("not screen", "not all"), "not all");
1921    assert_eq!(and("print", "(min-width: 250px)"), "print and (width >= 250px)");
1922    assert_eq!(and("(min-width: 250px)", "print"), "print and (width >= 250px)");
1923    assert_eq!(
1924      and("print and (min-width: 250px)", "(color)"),
1925      "print and (width >= 250px) and (color)"
1926    );
1927    assert_eq!(and("all", "only screen"), "only screen");
1928    assert_eq!(and("only screen", "all"), "only screen");
1929    assert_eq!(and("print", "print"), "print");
1930  }
1931
1932  #[test]
1933  fn test_negated_interval_parens() {
1934    let media_query = parse("screen and not (200px <= width < 500px)");
1935    let printer_options = PrinterOptions {
1936      targets: Targets {
1937        browsers: Some(Browsers {
1938          chrome: Some(95 << 16),
1939          ..Default::default()
1940        }),
1941        ..Default::default()
1942      },
1943      ..Default::default()
1944    };
1945    assert_eq!(
1946      media_query.to_css_string(printer_options).unwrap(),
1947      "screen and not ((min-width: 200px) and (not (min-width: 500px)))"
1948    );
1949  }
1950}