1use 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#[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 #[cfg_attr(feature = "serde", serde(borrow))]
32 pub name: Option<ContainerName<'i>>,
33 pub condition: Option<ContainerCondition<'i>>,
35 pub rules: CssRuleList<'i, R>,
37 #[cfg_attr(feature = "visitor", skip_visit)]
39 pub loc: Location,
40}
41
42#[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 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<ContainerSizeFeature>"))]
55 Feature(ContainerSizeFeature<'i>),
56 #[cfg_attr(feature = "visitor", skip_type)]
58 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<ContainerCondition>>"))]
59 Not(Box<ContainerCondition<'i>>),
60 #[cfg_attr(feature = "visitor", skip_type)]
62 Operation {
63 operator: Operator,
65 conditions: Vec<ContainerCondition<'i>>,
67 },
68 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<StyleQuery>"))]
70 Style(StyleQuery<'i>),
71 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<ScrollStateQuery>"))]
73 ScrollState(ScrollStateQuery<'i>),
74 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<TokenList>"))]
76 Unknown(TokenList<'i>),
77}
78
79pub type ContainerSizeFeature<'i> = QueryFeature<'i, ContainerSizeFeatureId>;
81
82define_query_features! {
83 pub enum ContainerSizeFeatureId {
85 "width": Width = Length,
87 "height": Height = Length,
89 "inline-size": InlineSize = Length,
91 "block-size": BlockSize = Length,
93 "aspect-ratio": AspectRatio = Ratio,
95 "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#[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 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<Property>"))]
124 Declaration(Property<'i>),
125 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<PropertyId>"))]
128 Property(PropertyId<'i>),
129 #[cfg_attr(feature = "visitor", skip_type)]
131 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<StyleQuery>>"))]
132 Not(Box<StyleQuery<'i>>),
133 #[cfg_attr(feature = "visitor", skip_type)]
135 Operation {
136 operator: Operator,
138 conditions: Vec<StyleQuery<'i>>,
140 },
141}
142
143#[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 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<ScrollStateFeature>"))]
156 Feature(ScrollStateFeature<'i>),
157 #[cfg_attr(feature = "visitor", skip_type)]
159 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<ScrollStateQuery>>"))]
160 Not(Box<ScrollStateQuery<'i>>),
161 #[cfg_attr(feature = "visitor", skip_type)]
163 Operation {
164 operator: Operator,
166 conditions: Vec<ScrollStateQuery<'i>>,
168 },
169}
170
171pub type ScrollStateFeature<'i> = QueryFeature<'i, ScrollStateFeatureId>;
173
174define_query_features! {
175 pub enum ScrollStateFeatureId {
177 "stuck": Stuck = Ident,
179 "snapped": Snapped = Ident,
181 "scrollable": Scrollable = Ident,
183 "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.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.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.targets().current))
411 }
412 ScrollStateQuery::Operation {
413 ref conditions,
414 operator,
415 } => operation_to_css(operator, conditions, dest),
416 }
417 }
418}
419
420#[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 self
443 .0
444 .to_css_with_options(dest, dest.css_module_config().is_some_and(|config| config.container))
445 }
446}
447
448impl<'i, T: Clone> ContainerRule<'i, T> {
449 pub(crate) fn minify(
450 &mut self,
451 context: &mut MinifyContext<'_, 'i>,
452 parent_is_unused: bool,
453 ) -> Result<bool, MinifyError> {
454 self.rules.minify(context, parent_is_unused)?;
455 Ok(self.rules.0.is_empty())
456 }
457}
458
459impl<'a, 'i, T: ToCss> ToCss for ContainerRule<'i, T> {
460 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
461 #[cfg(feature = "custom_sourcemap")]
462 dest.add_mapping(self.loc);
463 dest.write_str("@container ")?;
464 let has_condition = self.condition.is_some();
465
466 if let Some(name) = &self.name {
467 name.to_css(dest)?;
468 if has_condition {
469 dest.write_char(' ')?;
470 }
471 }
472
473 if let Some(condition) = &self.condition {
474 let exclude = dest.targets().current.exclude;
476 dest.targets_mut().current.exclude.insert(Features::MediaQueries);
477 condition.to_css(dest)?;
478 dest.targets_mut().current.exclude = exclude;
479 }
480
481 dest.whitespace()?;
482 dest.write_char('{')?;
483 dest.indent();
484 dest.newline()?;
485 self.rules.to_css(dest)?;
486 dest.dedent();
487 dest.newline()?;
488 dest.write_char('}')?;
489 Ok(())
490 }
491}