Skip to main content

rspack_lightningcss/rules/
layer.rs

1//! The `@layer` rule.
2
3use super::{CssRuleList, Location, MinifyContext};
4use crate::error::{MinifyError, ParserError, PrinterError};
5use crate::parser::DefaultAtRule;
6use crate::traits::{Parse, ToCss};
7use crate::values::string::CowArcStr;
8#[cfg(feature = "visitor")]
9use crate::visitor::Visit;
10use cssparser::*;
11use smallvec::SmallVec;
12
13/// A [`<layer-name>`](https://drafts.csswg.org/css-cascade-5/#typedef-layer-name) within
14/// a `@layer` or `@import` rule.
15///
16/// Nested layers are represented using a list of identifiers. In CSS syntax, these are dot-separated.
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
20#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
21pub struct LayerName<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub SmallVec<[CowArcStr<'i>; 1]>);
22
23macro_rules! expect_non_whitespace {
24  ($parser: ident, $($branches: tt)+) => {{
25    let start_location = $parser.current_source_location();
26    match *$parser.next_including_whitespace()? {
27      $($branches)+
28      ref token => {
29        return Err(start_location.new_basic_unexpected_token_error(token.clone()))
30      }
31    }
32  }}
33}
34
35impl<'i> Parse<'i> for LayerName<'i> {
36  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
37    let mut parts = SmallVec::new();
38    let ident = input.expect_ident()?;
39    parts.push(ident.into());
40
41    loop {
42      let name = input.try_parse(|input| {
43        expect_non_whitespace! {input,
44          Token::Delim('.') => Ok(()),
45        }?;
46
47        expect_non_whitespace! {input,
48          Token::Ident(ref id) => Ok(id.into()),
49        }
50      });
51
52      match name {
53        Ok(name) => parts.push(name),
54        Err(_) => break,
55      }
56    }
57
58    Ok(LayerName(parts))
59  }
60}
61
62impl<'i> ToCss for LayerName<'i> {
63  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
64    let mut first = true;
65    for name in &self.0 {
66      if first {
67        first = false;
68      } else {
69        dest.write_char('.')?;
70      }
71
72      serialize_identifier(name, dest)?;
73    }
74
75    Ok(())
76  }
77}
78
79/// A [@layer statement](https://drafts.csswg.org/css-cascade-5/#layer-empty) rule.
80///
81/// See also [LayerBlockRule](LayerBlockRule).
82#[derive(Debug, Clone, PartialEq)]
83#[cfg_attr(feature = "visitor", derive(Visit))]
84#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
85#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
86#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
87pub struct LayerStatementRule<'i> {
88  /// The layer names to declare.
89  #[cfg_attr(feature = "serde", serde(borrow))]
90  #[cfg_attr(feature = "visitor", skip_visit)]
91  pub names: Vec<LayerName<'i>>,
92  /// The location of the rule in the source file.
93  #[cfg_attr(feature = "visitor", skip_visit)]
94  pub loc: Location,
95}
96
97impl<'i> ToCss for LayerStatementRule<'i> {
98  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
99    #[cfg(feature = "custom_sourcemap")]
100    dest.add_mapping(self.loc);
101    dest.write_str("@layer ")?;
102    self.names.to_css(dest)?;
103    dest.write_char(';')?;
104    Ok(())
105  }
106}
107
108/// A [@layer block](https://drafts.csswg.org/css-cascade-5/#layer-block) rule.
109#[derive(Debug, Clone, PartialEq)]
110#[cfg_attr(feature = "visitor", derive(Visit))]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
113#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
114pub struct LayerBlockRule<'i, R = DefaultAtRule> {
115  /// The name of the layer to declare, or `None` to declare an anonymous layer.
116  #[cfg_attr(feature = "serde", serde(borrow))]
117  #[cfg_attr(feature = "visitor", skip_visit)]
118  pub name: Option<LayerName<'i>>,
119  /// The rules within the `@layer` rule.
120  pub rules: CssRuleList<'i, R>,
121  /// The location of the rule in the source file.
122  #[cfg_attr(feature = "visitor", skip_visit)]
123  pub loc: Location,
124}
125
126impl<'i, T: Clone> LayerBlockRule<'i, T> {
127  pub(crate) fn minify(
128    &mut self,
129    context: &mut MinifyContext<'_, 'i>,
130    parent_is_unused: bool,
131  ) -> Result<bool, MinifyError> {
132    self.rules.minify(context, parent_is_unused)?;
133
134    Ok(self.rules.0.is_empty())
135  }
136}
137
138impl<'a, 'i, T: ToCss> ToCss for LayerBlockRule<'i, T> {
139  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
140    #[cfg(feature = "custom_sourcemap")]
141    dest.add_mapping(self.loc);
142    dest.write_str("@layer")?;
143    if let Some(name) = &self.name {
144      dest.write_char(' ')?;
145      name.to_css(dest)?;
146    }
147
148    dest.whitespace()?;
149    dest.write_char('{')?;
150    dest.indent();
151    dest.newline()?;
152    self.rules.to_css(dest)?;
153    dest.dedent();
154    dest.newline()?;
155    dest.write_char('}')?;
156    Ok(())
157  }
158}