Skip to main content

rspack_lightningcss/rules/
container.rs

1//! The `@container` rule.
2
3use cssparser::*;
4
5use super::Location;
6use super::{CssRuleList, MinifyContext};
7use crate::error::{MinifyError, ParserError, PrinterError};
8use crate::media_query::{
9  define_query_features, operation_to_css, parse_query_condition, to_css_with_parens_if_needed, FeatureToCss,
10  MediaFeatureType, Operator, QueryCondition, QueryConditionFlags, QueryFeature, ValueType,
11};
12use crate::parser::{DefaultAtRule, ParserOptions};
13use crate::properties::custom::TokenList;
14use crate::properties::{Property, PropertyId};
15#[cfg(feature = "serde")]
16use crate::serialization::ValueWrapper;
17use crate::targets::{Features, Targets};
18use crate::traits::{Parse, ParseWithOptions, ToCss};
19use crate::values::ident::CustomIdent;
20#[cfg(feature = "visitor")]
21use crate::visitor::Visit;
22
23/// A [@container](https://drafts.csswg.org/css-contain-3/#container-rule) rule.
24#[derive(Debug, PartialEq, Clone)]
25#[cfg_attr(feature = "visitor", derive(Visit))]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
28#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
29pub struct ContainerRule<'i, R = DefaultAtRule> {
30  /// The name of the container.
31  #[cfg_attr(feature = "serde", serde(borrow))]
32  pub name: Option<ContainerName<'i>>,
33  /// The container condition.
34  pub condition: Option<ContainerCondition<'i>>,
35  /// The rules within the `@container` rule.
36  pub rules: CssRuleList<'i, R>,
37  /// The location of the rule in the source file.
38  #[cfg_attr(feature = "visitor", skip_visit)]
39  pub loc: Location,
40}
41
42/// Represents a container condition.
43#[derive(Clone, Debug, PartialEq)]
44#[cfg_attr(feature = "visitor", derive(Visit))]
45#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
46#[cfg_attr(
47  feature = "serde",
48  derive(serde::Serialize, serde::Deserialize),
49  serde(tag = "type", rename_all = "kebab-case")
50)]
51#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
52pub enum ContainerCondition<'i> {
53  /// A size container feature, implicitly parenthesized.
54  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<ContainerSizeFeature>"))]
55  Feature(ContainerSizeFeature<'i>),
56  /// A negation of a condition.
57  #[cfg_attr(feature = "visitor", skip_type)]
58  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<ContainerCondition>>"))]
59  Not(Box<ContainerCondition<'i>>),
60  /// A set of joint operations.
61  #[cfg_attr(feature = "visitor", skip_type)]
62  Operation {
63    /// The operator for the conditions.
64    operator: Operator,
65    /// The conditions for the operator.
66    conditions: Vec<ContainerCondition<'i>>,
67  },
68  /// A style query.
69  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<StyleQuery>"))]
70  Style(StyleQuery<'i>),
71  /// A scroll state query.
72  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<ScrollStateQuery>"))]
73  ScrollState(ScrollStateQuery<'i>),
74  /// Unknown tokens.
75  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<TokenList>"))]
76  Unknown(TokenList<'i>),
77}
78
79/// A container query size feature.
80pub type ContainerSizeFeature<'i> = QueryFeature<'i, ContainerSizeFeatureId>;
81
82define_query_features! {
83  /// A container query size feature identifier.
84  pub enum ContainerSizeFeatureId {
85    /// The [width](https://w3c.github.io/csswg-drafts/css-contain-3/#width) size container feature.
86    "width": Width = Length,
87    /// The [height](https://w3c.github.io/csswg-drafts/css-contain-3/#height) size container feature.
88    "height": Height = Length,
89    /// The [inline-size](https://w3c.github.io/csswg-drafts/css-contain-3/#inline-size) size container feature.
90    "inline-size": InlineSize = Length,
91    /// The [block-size](https://w3c.github.io/csswg-drafts/css-contain-3/#block-size) size container feature.
92    "block-size": BlockSize = Length,
93    /// The [aspect-ratio](https://w3c.github.io/csswg-drafts/css-contain-3/#aspect-ratio) size container feature.
94    "aspect-ratio": AspectRatio = Ratio,
95    /// The [orientation](https://w3c.github.io/csswg-drafts/css-contain-3/#orientation) size container feature.
96    "orientation": Orientation = Ident,
97  }
98}
99
100impl FeatureToCss for ContainerSizeFeatureId {
101  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
102    &self,
103    prefix: &str,
104    dest: &mut PrinterT,
105  ) -> Result<(), PrinterError> {
106    dest.write_str(prefix)?;
107    self.to_css(dest)
108  }
109}
110
111/// Represents a style query within a container condition.
112#[derive(Clone, Debug, PartialEq)]
113#[cfg_attr(feature = "visitor", derive(Visit))]
114#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
115#[cfg_attr(
116  feature = "serde",
117  derive(serde::Serialize, serde::Deserialize),
118  serde(tag = "type", rename_all = "kebab-case")
119)]
120#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
121pub enum StyleQuery<'i> {
122  /// A property declaration.
123  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<Property>"))]
124  Declaration(Property<'i>),
125  /// A property name, without a value.
126  /// This matches if the property value is different from the initial value.
127  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<PropertyId>"))]
128  Property(PropertyId<'i>),
129  /// A negation of a condition.
130  #[cfg_attr(feature = "visitor", skip_type)]
131  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<StyleQuery>>"))]
132  Not(Box<StyleQuery<'i>>),
133  /// A set of joint operations.
134  #[cfg_attr(feature = "visitor", skip_type)]
135  Operation {
136    /// The operator for the conditions.
137    operator: Operator,
138    /// The conditions for the operator.
139    conditions: Vec<StyleQuery<'i>>,
140  },
141}
142
143/// Represents a scroll state query within a container condition.
144#[derive(Clone, Debug, PartialEq)]
145#[cfg_attr(feature = "visitor", derive(Visit))]
146#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
147#[cfg_attr(
148  feature = "serde",
149  derive(serde::Serialize, serde::Deserialize),
150  serde(tag = "type", rename_all = "kebab-case")
151)]
152#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
153pub enum ScrollStateQuery<'i> {
154  /// A size container feature, implicitly parenthesized.
155  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<ScrollStateFeature>"))]
156  Feature(ScrollStateFeature<'i>),
157  /// A negation of a condition.
158  #[cfg_attr(feature = "visitor", skip_type)]
159  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<ScrollStateQuery>>"))]
160  Not(Box<ScrollStateQuery<'i>>),
161  /// A set of joint operations.
162  #[cfg_attr(feature = "visitor", skip_type)]
163  Operation {
164    /// The operator for the conditions.
165    operator: Operator,
166    /// The conditions for the operator.
167    conditions: Vec<ScrollStateQuery<'i>>,
168  },
169}
170
171/// A container query size feature.
172pub type ScrollStateFeature<'i> = QueryFeature<'i, ScrollStateFeatureId>;
173
174define_query_features! {
175  /// A container query scroll state feature identifier.
176  pub enum ScrollStateFeatureId {
177    /// The [stuck](https://drafts.csswg.org/css-conditional-5/#stuck) scroll state feature.
178    "stuck": Stuck = Ident,
179    /// The [snapped](https://drafts.csswg.org/css-conditional-5/#snapped) scroll state feature.
180    "snapped": Snapped = Ident,
181    /// The [scrollable](https://drafts.csswg.org/css-conditional-5/#scrollable) scroll state feature.
182    "scrollable": Scrollable = Ident,
183    /// The [scrolled](https://drafts.csswg.org/css-conditional-5/#scrolled) scroll state feature.
184    "scrolled": Scrolled = Ident,
185  }
186}
187
188impl FeatureToCss for ScrollStateFeatureId {
189  fn to_css_with_prefix<PrinterT: crate::printer::PrinterTrait>(
190    &self,
191    prefix: &str,
192    dest: &mut PrinterT,
193  ) -> Result<(), PrinterError> {
194    dest.write_str(prefix)?;
195    self.to_css(dest)
196  }
197}
198
199impl<'i> QueryCondition<'i> for ContainerCondition<'i> {
200  #[inline]
201  fn parse_feature<'t>(
202    input: &mut Parser<'i, 't>,
203    options: &ParserOptions<'i>,
204  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
205    let feature = QueryFeature::parse_with_options(input, options)?;
206    Ok(Self::Feature(feature))
207  }
208
209  #[inline]
210  fn create_negation(condition: Box<ContainerCondition<'i>>) -> Self {
211    Self::Not(condition)
212  }
213
214  #[inline]
215  fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self {
216    Self::Operation { operator, conditions }
217  }
218
219  fn parse_style_query<'t>(
220    input: &mut Parser<'i, 't>,
221    options: &ParserOptions<'i>,
222  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
223    input.parse_nested_block(|input| {
224      if let Ok(res) =
225        input.try_parse(|input| parse_query_condition(input, QueryConditionFlags::ALLOW_OR, options))
226      {
227        return Ok(Self::Style(res));
228      }
229
230      Ok(Self::Style(StyleQuery::parse_feature(input, options)?))
231    })
232  }
233
234  fn parse_scroll_state_query<'t>(
235    input: &mut Parser<'i, 't>,
236    options: &ParserOptions<'i>,
237  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
238    input.parse_nested_block(|input| {
239      if let Ok(res) =
240        input.try_parse(|input| parse_query_condition(input, QueryConditionFlags::ALLOW_OR, options))
241      {
242        return Ok(Self::ScrollState(res));
243      }
244
245      Ok(Self::ScrollState(ScrollStateQuery::parse_feature(input, options)?))
246    })
247  }
248
249  fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool {
250    match self {
251      ContainerCondition::Not(_) => true,
252      ContainerCondition::Operation { operator, .. } => Some(*operator) != parent_operator,
253      ContainerCondition::Feature(f) => f.needs_parens(parent_operator, targets),
254      ContainerCondition::Style(_) => false,
255      ContainerCondition::ScrollState(_) => false,
256      ContainerCondition::Unknown(_) => false,
257    }
258  }
259}
260
261impl<'i> QueryCondition<'i> for ScrollStateQuery<'i> {
262  #[inline]
263  fn parse_feature<'t>(
264    input: &mut Parser<'i, 't>,
265    options: &ParserOptions<'i>,
266  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
267    let feature = QueryFeature::parse_with_options(input, options)?;
268    Ok(Self::Feature(feature))
269  }
270
271  #[inline]
272  fn create_negation(condition: Box<Self>) -> Self {
273    Self::Not(condition)
274  }
275
276  #[inline]
277  fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self {
278    Self::Operation { operator, conditions }
279  }
280
281  fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool {
282    match self {
283      ScrollStateQuery::Not(_) => true,
284      ScrollStateQuery::Operation { operator, .. } => Some(*operator) != parent_operator,
285      ScrollStateQuery::Feature(f) => f.needs_parens(parent_operator, targets),
286    }
287  }
288}
289
290impl<'i> QueryCondition<'i> for StyleQuery<'i> {
291  #[inline]
292  fn parse_feature<'t>(
293    input: &mut Parser<'i, 't>,
294    options: &ParserOptions<'i>,
295  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
296    let property_id = PropertyId::parse(input)?;
297    if input.try_parse(|input| input.expect_colon()).is_ok() {
298      input.skip_whitespace();
299      let feature = Self::Declaration(Property::parse(property_id, input, options)?);
300      let _ = input.try_parse(|input| parse_important(input));
301      Ok(feature)
302    } else {
303      Ok(Self::Property(property_id))
304    }
305  }
306
307  #[inline]
308  fn create_negation(condition: Box<Self>) -> Self {
309    Self::Not(condition)
310  }
311
312  #[inline]
313  fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self {
314    Self::Operation { operator, conditions }
315  }
316
317  fn needs_parens(&self, parent_operator: Option<Operator>, _targets: &Targets) -> bool {
318    match self {
319      StyleQuery::Not(_) => true,
320      StyleQuery::Operation { operator, .. } => Some(*operator) != parent_operator,
321      StyleQuery::Declaration(_) | StyleQuery::Property(_) => true,
322    }
323  }
324}
325
326impl<'i> ParseWithOptions<'i> for ContainerCondition<'i> {
327  fn parse_with_options<'t>(
328    input: &mut Parser<'i, 't>,
329    options: &ParserOptions<'i>,
330  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
331    input
332      .try_parse(|input| {
333        parse_query_condition(
334          input,
335          QueryConditionFlags::ALLOW_OR
336            | QueryConditionFlags::ALLOW_STYLE
337            | QueryConditionFlags::ALLOW_SCROLL_STATE,
338          options,
339        )
340      })
341      .or_else(|e| {
342        if options.error_recovery {
343          options.warn(e);
344          Ok(ContainerCondition::Unknown(TokenList::parse(input, options, 0)?))
345        } else {
346          Err(e)
347        }
348      })
349  }
350}
351
352impl<'i> ToCss for ContainerCondition<'i> {
353  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
354    match *self {
355      ContainerCondition::Feature(ref f) => f.to_css(dest),
356      ContainerCondition::Not(ref c) => {
357        dest.write_str("not ")?;
358        to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.state().targets.current))
359      }
360      ContainerCondition::Operation {
361        ref conditions,
362        operator,
363      } => operation_to_css(operator, conditions, dest),
364      ContainerCondition::Style(ref query) => {
365        dest.write_str("style(")?;
366        query.to_css(dest)?;
367        dest.write_char(')')?;
368        Ok(())
369      }
370      ContainerCondition::ScrollState(ref query) => {
371        let needs_parens = !matches!(query, ScrollStateQuery::Feature(_));
372        dest.write_str("scroll-state")?;
373        if needs_parens {
374          dest.write_char('(')?;
375        }
376        query.to_css(dest)?;
377        if needs_parens {
378          dest.write_char(')')?;
379        }
380        Ok(())
381      }
382      ContainerCondition::Unknown(ref tokens) => tokens.to_css(dest, false),
383    }
384  }
385}
386
387impl<'i> ToCss for StyleQuery<'i> {
388  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
389    match *self {
390      StyleQuery::Declaration(ref f) => f.to_css(dest, false),
391      StyleQuery::Property(ref f) => f.to_css(dest),
392      StyleQuery::Not(ref c) => {
393        dest.write_str("not ")?;
394        to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.state().targets.current))
395      }
396      StyleQuery::Operation {
397        ref conditions,
398        operator,
399      } => operation_to_css(operator, conditions, dest),
400    }
401  }
402}
403
404impl<'i> ToCss for ScrollStateQuery<'i> {
405  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
406    match *self {
407      ScrollStateQuery::Feature(ref f) => f.to_css(dest),
408      ScrollStateQuery::Not(ref c) => {
409        dest.write_str("not ")?;
410        to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.state().targets.current))
411      }
412      ScrollStateQuery::Operation {
413        ref conditions,
414        operator,
415      } => operation_to_css(operator, conditions, dest),
416    }
417  }
418}
419
420/// A [`<container-name>`](https://drafts.csswg.org/css-contain-3/#typedef-container-name) in a `@container` rule.
421#[derive(Debug, Clone, PartialEq)]
422#[cfg_attr(feature = "visitor", derive(Visit))]
423#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
424#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
425#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
426pub struct ContainerName<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub CustomIdent<'i>);
427
428impl<'i> Parse<'i> for ContainerName<'i> {
429  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
430    let ident = CustomIdent::parse(input)?;
431    match_ignore_ascii_case! { &*ident.0,
432      "none" | "and" | "not" | "or" => Err(input.new_unexpected_token_error(Token::Ident(ident.0.as_ref().to_owned().into()))),
433      _ => Ok(ContainerName(ident))
434    }
435  }
436}
437
438impl<'i> ToCss for ContainerName<'i> {
439  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
440    // Container name should not be hashed
441    // https://github.com/vercel/next.js/issues/71233
442    self.0.to_css_with_options(
443      dest,
444      match dest.state().css_module.as_ref() {
445        Some(css_module) => css_module.config.container,
446        None => false,
447      },
448    )
449  }
450}
451
452impl<'i, T: Clone> ContainerRule<'i, T> {
453  pub(crate) fn minify(
454    &mut self,
455    context: &mut MinifyContext<'_, 'i>,
456    parent_is_unused: bool,
457  ) -> Result<bool, MinifyError> {
458    self.rules.minify(context, parent_is_unused)?;
459    Ok(self.rules.0.is_empty())
460  }
461}
462
463impl<'a, 'i, T: ToCss> ToCss for ContainerRule<'i, T> {
464  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
465    dest.add_mapping(self.loc);
466    dest.write_str("@container ")?;
467    let has_condition = self.condition.is_some();
468
469    if let Some(name) = &self.name {
470      name.to_css(dest)?;
471      if has_condition {
472        dest.write_char(' ')?;
473      }
474    }
475
476    if let Some(condition) = &self.condition {
477      // Don't downlevel range syntax in container queries.
478      let exclude = dest.state().targets.current.exclude;
479      dest.state_mut().targets.current.exclude.insert(Features::MediaQueries);
480      let res = condition.to_css(dest);
481      dest.state_mut().targets.current.exclude = exclude;
482      res?;
483    }
484
485    dest.whitespace()?;
486    dest.write_char('{')?;
487    dest.indent();
488    dest.newline()?;
489    self.rules.to_css(dest)?;
490    dest.dedent();
491    dest.newline()?;
492    dest.write_char('}')?;
493    Ok(())
494  }
495}