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;
13use crate::printer::Printer;
14use crate::properties::{Property, PropertyId};
15#[cfg(feature = "serde")]
16use crate::serialization::ValueWrapper;
17use crate::targets::{Features, Targets};
18use crate::traits::{Parse, 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(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: 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(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}
72
73/// A container query size feature.
74pub type ContainerSizeFeature<'i> = QueryFeature<'i, ContainerSizeFeatureId>;
75
76define_query_features! {
77  /// A container query size feature identifier.
78  pub enum ContainerSizeFeatureId {
79    /// The [width](https://w3c.github.io/csswg-drafts/css-contain-3/#width) size container feature.
80    "width": Width = Length,
81    /// The [height](https://w3c.github.io/csswg-drafts/css-contain-3/#height) size container feature.
82    "height": Height = Length,
83    /// The [inline-size](https://w3c.github.io/csswg-drafts/css-contain-3/#inline-size) size container feature.
84    "inline-size": InlineSize = Length,
85    /// The [block-size](https://w3c.github.io/csswg-drafts/css-contain-3/#block-size) size container feature.
86    "block-size": BlockSize = Length,
87    /// The [aspect-ratio](https://w3c.github.io/csswg-drafts/css-contain-3/#aspect-ratio) size container feature.
88    "aspect-ratio": AspectRatio = Ratio,
89    /// The [orientation](https://w3c.github.io/csswg-drafts/css-contain-3/#orientation) size container feature.
90    "orientation": Orientation = Ident,
91  }
92}
93
94impl FeatureToCss for ContainerSizeFeatureId {
95  fn to_css_with_prefix<W>(&self, prefix: &str, dest: &mut Printer<W>) -> Result<(), PrinterError>
96  where
97    W: std::fmt::Write,
98  {
99    dest.write_str(prefix)?;
100    self.to_css(dest)
101  }
102}
103
104/// Represents a style query within a container condition.
105#[derive(Clone, Debug, PartialEq)]
106#[cfg_attr(feature = "visitor", derive(Visit))]
107#[cfg_attr(feature = "into_owned", derive(static_self::IntoOwned))]
108#[cfg_attr(
109  feature = "serde",
110  derive(serde::Serialize, serde::Deserialize),
111  serde(tag = "type", rename_all = "kebab-case")
112)]
113#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
114pub enum StyleQuery<'i> {
115  /// A style feature, implicitly parenthesized.
116  #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<Property>"))]
117  Feature(Property<'i>),
118  /// A negation of a condition.
119  #[cfg_attr(feature = "visitor", skip_type)]
120  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<StyleQuery>>"))]
121  Not(Box<StyleQuery<'i>>),
122  /// A set of joint operations.
123  #[cfg_attr(feature = "visitor", skip_type)]
124  Operation {
125    /// The operator for the conditions.
126    operator: Operator,
127    /// The conditions for the operator.
128    conditions: Vec<StyleQuery<'i>>,
129  },
130}
131
132impl<'i> QueryCondition<'i> for ContainerCondition<'i> {
133  #[inline]
134  fn parse_feature<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
135    let feature = QueryFeature::parse(input)?;
136    Ok(Self::Feature(feature))
137  }
138
139  #[inline]
140  fn create_negation(condition: Box<ContainerCondition<'i>>) -> Self {
141    Self::Not(condition)
142  }
143
144  #[inline]
145  fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self {
146    Self::Operation { operator, conditions }
147  }
148
149  fn parse_style_query<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
150    input.parse_nested_block(|input| {
151      if let Ok(res) = input.try_parse(|input| parse_query_condition(input, QueryConditionFlags::ALLOW_OR)) {
152        return Ok(Self::Style(res));
153      }
154
155      Ok(Self::Style(StyleQuery::parse_feature(input)?))
156    })
157  }
158
159  fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool {
160    match self {
161      ContainerCondition::Not(_) => true,
162      ContainerCondition::Operation { operator, .. } => Some(*operator) != parent_operator,
163      ContainerCondition::Feature(f) => f.needs_parens(parent_operator, targets),
164      ContainerCondition::Style(_) => false,
165    }
166  }
167}
168
169impl<'i> QueryCondition<'i> for StyleQuery<'i> {
170  #[inline]
171  fn parse_feature<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
172    let property_id = PropertyId::parse(input)?;
173    input.expect_colon()?;
174    input.skip_whitespace();
175    let feature = Self::Feature(Property::parse(property_id, input, &Default::default())?);
176    let _ = input.try_parse(|input| parse_important(input));
177    Ok(feature)
178  }
179
180  #[inline]
181  fn create_negation(condition: Box<Self>) -> Self {
182    Self::Not(condition)
183  }
184
185  #[inline]
186  fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self {
187    Self::Operation { operator, conditions }
188  }
189
190  fn needs_parens(&self, parent_operator: Option<Operator>, _targets: &Targets) -> bool {
191    match self {
192      StyleQuery::Not(_) => true,
193      StyleQuery::Operation { operator, .. } => Some(*operator) != parent_operator,
194      StyleQuery::Feature(_) => true,
195    }
196  }
197}
198
199impl<'i> Parse<'i> for ContainerCondition<'i> {
200  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
201    parse_query_condition(input, QueryConditionFlags::ALLOW_OR | QueryConditionFlags::ALLOW_STYLE)
202  }
203}
204
205impl<'i> ToCss for ContainerCondition<'i> {
206  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
207  where
208    W: std::fmt::Write,
209  {
210    match *self {
211      ContainerCondition::Feature(ref f) => f.to_css(dest),
212      ContainerCondition::Not(ref c) => {
213        dest.write_str("not ")?;
214        to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.targets))
215      }
216      ContainerCondition::Operation {
217        ref conditions,
218        operator,
219      } => operation_to_css(operator, conditions, dest),
220      ContainerCondition::Style(ref query) => {
221        dest.write_str("style(")?;
222        query.to_css(dest)?;
223        dest.write_char(')')
224      }
225    }
226  }
227}
228
229impl<'i> ToCss for StyleQuery<'i> {
230  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
231  where
232    W: std::fmt::Write,
233  {
234    match *self {
235      StyleQuery::Feature(ref f) => f.to_css(dest, false),
236      StyleQuery::Not(ref c) => {
237        dest.write_str("not ")?;
238        to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.targets))
239      }
240      StyleQuery::Operation {
241        ref conditions,
242        operator,
243      } => operation_to_css(operator, conditions, dest),
244    }
245  }
246}
247
248/// A [`<container-name>`](https://drafts.csswg.org/css-contain-3/#typedef-container-name) in a `@container` rule.
249#[derive(Debug, Clone, PartialEq)]
250#[cfg_attr(feature = "visitor", derive(Visit))]
251#[cfg_attr(feature = "into_owned", derive(static_self::IntoOwned))]
252#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
253#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
254pub struct ContainerName<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub CustomIdent<'i>);
255
256impl<'i> Parse<'i> for ContainerName<'i> {
257  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
258    let ident = CustomIdent::parse(input)?;
259    match_ignore_ascii_case! { &*ident.0,
260      "none" | "and" | "not" | "or" => Err(input.new_unexpected_token_error(Token::Ident(ident.0.as_ref().to_owned().into()))),
261      _ => Ok(ContainerName(ident))
262    }
263  }
264}
265
266impl<'i> ToCss for ContainerName<'i> {
267  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
268  where
269    W: std::fmt::Write,
270  {
271    self.0.to_css(dest)
272  }
273}
274
275impl<'i, T: Clone> ContainerRule<'i, T> {
276  pub(crate) fn minify(
277    &mut self,
278    context: &mut MinifyContext<'_, 'i>,
279    parent_is_unused: bool,
280  ) -> Result<bool, MinifyError> {
281    self.rules.minify(context, parent_is_unused)?;
282    Ok(self.rules.0.is_empty())
283  }
284}
285
286impl<'a, 'i, T: ToCss> ToCss for ContainerRule<'i, T> {
287  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
288  where
289    W: std::fmt::Write,
290  {
291    #[cfg(feature = "sourcemap")]
292    dest.add_mapping(self.loc);
293    dest.write_str("@container ")?;
294    if let Some(name) = &self.name {
295      name.to_css(dest)?;
296      dest.write_char(' ')?;
297    }
298
299    // Don't downlevel range syntax in container queries.
300    let exclude = dest.targets.exclude;
301    dest.targets.exclude.insert(Features::MediaQueries);
302    self.condition.to_css(dest)?;
303    dest.targets.exclude = exclude;
304
305    dest.whitespace()?;
306    dest.write_char('{')?;
307    dest.indent();
308    dest.newline()?;
309    self.rules.to_css(dest)?;
310    dest.dedent();
311    dest.newline()?;
312    dest.write_char('}')
313  }
314}