Skip to main content

rspack_lightningcss/properties/
css_modules.rs

1//! Properties related to CSS modules.
2
3use crate::dependencies::Location;
4use crate::error::{ParserError, PrinterError};
5use crate::traits::{Parse, ToCss};
6use crate::values::ident::{CustomIdent, CustomIdentList};
7use crate::values::string::CowArcStr;
8#[cfg(feature = "visitor")]
9use crate::visitor::Visit;
10use cssparser::*;
11use smallvec::SmallVec;
12
13/// A value for the [composes](https://github.com/css-modules/css-modules/#dependencies) property from CSS modules.
14#[derive(Debug, Clone, PartialEq)]
15#[cfg_attr(feature = "visitor", derive(Visit))]
16#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
19pub struct Composes<'i> {
20  /// A list of class names to compose.
21  #[cfg_attr(feature = "serde", serde(borrow))]
22  pub names: CustomIdentList<'i>,
23  /// Where the class names are composed from.
24  pub from: Option<Specifier<'i>>,
25  /// The source location of the `composes` property.
26  pub loc: Location,
27}
28
29/// Defines where the class names referenced in the `composes` property are located.
30///
31/// See [Composes](Composes).
32#[derive(Debug, Clone, PartialEq)]
33#[cfg_attr(feature = "visitor", derive(Visit))]
34#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
35#[cfg_attr(
36  feature = "serde",
37  derive(serde::Serialize, serde::Deserialize),
38  serde(tag = "type", content = "value", rename_all = "kebab-case")
39)]
40#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
41pub enum Specifier<'i> {
42  /// The referenced name is global.
43  Global,
44  /// The referenced name comes from the specified file.
45  #[cfg_attr(feature = "serde", serde(borrow))]
46  File(CowArcStr<'i>),
47  /// The referenced name comes from a source index (used during bundling).
48  SourceIndex(u32),
49}
50
51impl<'i> Parse<'i> for Composes<'i> {
52  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
53    let loc = input.current_source_location();
54    let mut names = SmallVec::new();
55    while let Ok(name) = input.try_parse(parse_one_ident) {
56      names.push(name);
57    }
58
59    if names.is_empty() {
60      return Err(input.new_custom_error(ParserError::InvalidDeclaration));
61    }
62
63    let from = if input.try_parse(|input| input.expect_ident_matching("from")).is_ok() {
64      Some(Specifier::parse(input)?)
65    } else {
66      None
67    };
68
69    Ok(Composes {
70      names,
71      from,
72      loc: loc.into(),
73    })
74  }
75}
76
77fn parse_one_ident<'i, 't>(
78  input: &mut Parser<'i, 't>,
79) -> Result<CustomIdent<'i>, ParseError<'i, ParserError<'i>>> {
80  let name = CustomIdent::parse(input)?;
81  if name.0.eq_ignore_ascii_case("from") {
82    return Err(input.new_error_for_next_token());
83  }
84
85  Ok(name)
86}
87
88impl ToCss for Composes<'_> {
89  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
90    let mut first = true;
91    for name in &self.names {
92      if first {
93        first = false;
94      } else {
95        dest.write_char(' ')?;
96      }
97      name.to_css(dest)?;
98    }
99
100    if let Some(from) = &self.from {
101      dest.write_str(" from ")?;
102      from.to_css(dest)?;
103    }
104
105    Ok(())
106  }
107}
108
109impl<'i> Parse<'i> for Specifier<'i> {
110  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
111    if let Ok(file) = input.try_parse(|input| input.expect_string_cloned()) {
112      Ok(Specifier::File(file.into()))
113    } else {
114      input.expect_ident_matching("global")?;
115      Ok(Specifier::Global)
116    }
117  }
118}
119
120impl<'i> ToCss for Specifier<'i> {
121  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
122    match self {
123      Specifier::Global => dest.write_str("global")?,
124      Specifier::File(file) => serialize_string(&file, dest)?,
125      Specifier::SourceIndex(..) => {}
126    }
127    Ok(())
128  }
129}