Skip to main content

rspack_lightningcss/
stylesheet.rs

1//! CSS style sheets and style attributes.
2//!
3//! A [StyleSheet](StyleSheet) represents a `.css` file or `<style>` element in HTML.
4//! A [StyleAttribute](StyleAttribute) represents an inline `style` attribute in HTML.
5
6#![deny(unsafe_code)]
7
8use crate::context::{DeclarationContext, PropertyHandlerContext};
9use crate::css_modules::{hash, CssModule, CssModuleExports, CssModuleReferences};
10use crate::declaration::{DeclarationBlock, DeclarationHandler};
11use crate::dependencies::Dependency;
12use crate::error::{Error, ErrorLocation, MinifyErrorKind, ParserError, PrinterError, PrinterErrorKind};
13use crate::parser::{DefaultAtRule, DefaultAtRuleParser, TopLevelRuleParser};
14use crate::printer::Printer;
15#[cfg(feature = "custom_sourcemap")]
16use crate::printer::SourceMap;
17use crate::rules::{CssRule, CssRuleList, MinifyContext};
18use crate::targets::{should_compile, Targets, TargetsWithSupportsScope};
19use crate::traits::{AtRuleParser, ToCss};
20use crate::values::string::CowArcStr;
21#[cfg(feature = "visitor")]
22use crate::visitor::{Visit, VisitTypes, Visitor};
23use cssparser::{Parser, ParserInput, StyleSheetParser};
24use std::collections::{HashMap, HashSet};
25use std::fmt::Write;
26
27pub use crate::parser::{ParserFlags, ParserOptions};
28pub use crate::printer::PrinterOptions;
29pub use crate::printer::PseudoClasses;
30
31/// A CSS style sheet, representing a `.css` file or inline `<style>` element.
32///
33/// Style sheets can be parsed from a string, constructed from scratch,
34/// or created using a [Bundler](super::bundler::Bundler). Then, they can be
35/// minified and transformed for a set of target browsers, and serialied to a string.
36///
37/// # Example
38///
39/// ```
40/// use rspack_lightningcss::stylesheet::{
41///   StyleSheet, ParserOptions, MinifyOptions, PrinterOptions
42/// };
43/// // Parse a style sheet from a string.
44/// let mut stylesheet = StyleSheet::parse(
45///   r#"
46///   .foo {
47///     color: red;
48///   }
49///
50///   .bar {
51///     color: red;
52///   }
53///   "#,
54///   ParserOptions::default()
55/// ).unwrap();
56///
57/// // Minify the stylesheet.
58/// stylesheet.minify(MinifyOptions::default()).unwrap();
59///
60/// // Serialize it to a string.
61/// let res = stylesheet.to_css(PrinterOptions::default()).unwrap();
62/// assert_eq!(res.code, ".foo, .bar {\n  color: red;\n}\n");
63/// ```
64#[derive(Debug, Clone)]
65#[cfg_attr(
66  feature = "serde",
67  derive(serde::Serialize, serde::Deserialize),
68  serde(rename_all = "camelCase")
69)]
70#[cfg_attr(
71  feature = "jsonschema",
72  derive(schemars::JsonSchema),
73  schemars(rename = "StyleSheet", bound = "T: schemars::JsonSchema")
74)]
75#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
76pub struct StyleSheet<'i, T = DefaultAtRule> {
77  /// A list of top-level rules within the style sheet.
78  #[cfg_attr(feature = "serde", serde(borrow))]
79  pub rules: CssRuleList<'i, T>,
80  /// A list of file names for all source files included within the style sheet.
81  /// Sources are referenced by index in the `loc` property of each rule.
82  pub sources: Vec<String>,
83  /// The source map URL extracted from the original style sheet.
84  pub source_map_urls: Vec<Option<String>>,
85  /// Output source map indices corresponding to the bundler's source indices.
86  #[cfg(feature = "custom_sourcemap")]
87  #[cfg_attr(feature = "serde", serde(skip))]
88  pub(crate) source_map_source_indices: Vec<Option<u32>>,
89  /// The license comments that appeared at the start of the file.
90  pub license_comments: Vec<CowArcStr<'i>>,
91  /// A list of content hashes for all source files included within the style sheet.
92  /// This is only set if CSS modules are enabled and the pattern includes [content-hash].
93  #[cfg_attr(feature = "serde", serde(skip))]
94  pub(crate) content_hashes: Option<Vec<String>>,
95  #[cfg_attr(feature = "serde", serde(skip))]
96  /// The options the style sheet was originally parsed with.
97  options: ParserOptions<'i>,
98}
99
100/// Options for the `minify` function of a [StyleSheet](StyleSheet)
101/// or [StyleAttribute](StyleAttribute).
102#[derive(Default)]
103pub struct MinifyOptions {
104  /// Targets to compile the CSS for.
105  pub targets: Targets,
106  /// A list of known unused symbols, including CSS class names,
107  /// ids, and `@keyframe` names. The declarations of these will be removed.
108  pub unused_symbols: HashSet<String>,
109}
110
111/// A result returned from `to_css`, including the serialize CSS
112/// and other metadata depending on the input options.
113#[derive(Debug)]
114pub struct ToCssResult {
115  /// Serialized CSS code.
116  pub code: String,
117  /// A map of CSS module exports, if the `css_modules` option was
118  /// enabled during parsing.
119  pub exports: Option<CssModuleExports>,
120  /// A map of CSS module references, if the `css_modules` config
121  /// had `dashed_idents` enabled.
122  pub references: Option<CssModuleReferences>,
123  /// A list of dependencies (e.g. `@import` or `url()`) found in
124  /// the style sheet, if the `analyze_dependencies` option is enabled.
125  pub dependencies: Option<Vec<Dependency>>,
126}
127
128impl<'i, 'o> StyleSheet<'i, DefaultAtRule> {
129  /// Parse a style sheet from a string.
130  pub fn parse(code: &'i str, options: ParserOptions<'i>) -> Result<Self, Error<ParserError<'i>>> {
131    Self::parse_with(code, options, &mut DefaultAtRuleParser)
132  }
133}
134
135impl<'i, T> StyleSheet<'i, T>
136where
137  T: ToCss + Clone,
138{
139  /// Creates a new style sheet with the given source filenames and rules.
140  pub fn new(sources: Vec<String>, rules: CssRuleList<'i, T>, options: ParserOptions<'i>) -> StyleSheet<'i, T> {
141    StyleSheet {
142      sources,
143      source_map_urls: Vec::new(),
144      #[cfg(feature = "custom_sourcemap")]
145      source_map_source_indices: Vec::new(),
146      license_comments: Vec::new(),
147      content_hashes: None,
148      rules,
149      options,
150    }
151  }
152
153  /// Parse a style sheet from a string.
154  pub fn parse_with<P: AtRuleParser<'i, AtRule = T>>(
155    code: &'i str,
156    mut options: ParserOptions<'i>,
157    at_rule_parser: &mut P,
158  ) -> Result<Self, Error<ParserError<'i>>> {
159    let mut input = ParserInput::new(&code);
160    let mut parser = Parser::new(&mut input);
161    let mut license_comments = Vec::new();
162
163    let mut content_hashes = None;
164    if let Some(config) = &options.css_modules {
165      if config.pattern.has_content_hash() {
166        content_hashes = Some(vec![hash(
167          &code,
168          matches!(config.pattern.segments[0], crate::css_modules::Segment::ContentHash),
169        )]);
170      }
171    }
172
173    let mut state = parser.state();
174    while let Ok(token) = parser.next_including_whitespace_and_comments() {
175      match token {
176        cssparser::Token::WhiteSpace(..) => {}
177        cssparser::Token::Comment(comment) if comment.starts_with('!') => {
178          license_comments.push((*comment).into());
179        }
180        cssparser::Token::Comment(comment) if comment.contains("cssmodules-pure-no-check") => {
181          if let Some(css_modules) = &mut options.css_modules {
182            css_modules.pure = false;
183          }
184        }
185        _ => break,
186      }
187      state = parser.state();
188    }
189    parser.reset(&state);
190
191    let mut rules = CssRuleList(vec![]);
192    let mut rule_parser = TopLevelRuleParser::new(&mut options, at_rule_parser, &mut rules);
193    let mut rule_list_parser = StyleSheetParser::new(&mut parser, &mut rule_parser);
194
195    while let Some(rule) = rule_list_parser.next() {
196      match rule {
197        Ok(()) => {}
198        Err((e, _)) => {
199          let options = &mut rule_list_parser.parser.options;
200          if options.error_recovery {
201            options.warn(e);
202            continue;
203          }
204
205          return Err(Error::from(e, options.filename.clone()));
206        }
207      }
208    }
209
210    Ok(StyleSheet {
211      sources: vec![options.filename.clone()],
212      source_map_urls: vec![parser.current_source_map_url().map(|s| s.to_owned())],
213      #[cfg(feature = "custom_sourcemap")]
214      source_map_source_indices: Vec::new(),
215      content_hashes,
216      rules,
217      license_comments,
218      options,
219    })
220  }
221
222  /// Returns the source map URL for the source at the given index.
223  pub fn source_map_url(&self, source_index: usize) -> Option<&String> {
224    self.source_map_urls.get(source_index)?.as_ref()
225  }
226
227  /// Returns the inline source map associated with the source at the given index.
228  #[cfg(feature = "custom_sourcemap")]
229  pub fn source_map<S: SourceMap>(&self, source_index: usize) -> Option<S> {
230    S::from_data_url("/", self.source_map_url(source_index)?)
231  }
232
233  /// Minify and transform the style sheet for the provided browser targets.
234  pub fn minify(&mut self, options: MinifyOptions) -> Result<(), Error<MinifyErrorKind>> {
235    let context = PropertyHandlerContext::new(options.targets, &options.unused_symbols);
236    let mut handler = DeclarationHandler::default();
237    let mut important_handler = DeclarationHandler::default();
238
239    // @custom-media rules may be defined after they are referenced, but may only be defined at the top level
240    // of a stylesheet. Do a pre-scan here and create a lookup table by name.
241    let custom_media = if self.options.flags.contains(ParserFlags::CUSTOM_MEDIA)
242      && should_compile!(options.targets, CustomMediaQueries)
243    {
244      let mut custom_media = HashMap::new();
245      for rule in &self.rules.0 {
246        if let CssRule::CustomMedia(rule) = rule {
247          custom_media.insert(rule.name.0.clone(), rule.clone());
248        }
249      }
250      Some(custom_media)
251    } else {
252      None
253    };
254
255    let mut ctx = MinifyContext {
256      targets: TargetsWithSupportsScope::new(options.targets),
257      handler: &mut handler,
258      important_handler: &mut important_handler,
259      handler_context: context,
260      unused_symbols: &options.unused_symbols,
261      custom_media,
262      css_modules: self.options.css_modules.is_some(),
263      pure_css_modules: self.options.css_modules.as_ref().map(|c| c.pure).unwrap_or_default(),
264    };
265
266    self.rules.minify(&mut ctx, false).map_err(|e| Error {
267      kind: e.kind,
268      loc: Some(ErrorLocation::new(
269        e.loc,
270        self.sources[e.loc.source_index as usize].clone(),
271      )),
272    })?;
273
274    Ok(())
275  }
276
277  /// Serialize the style sheet to a CSS string.
278  pub fn to_css<'a, #[cfg(feature = "custom_sourcemap")] S: SourceMap>(
279    &self,
280    #[cfg(feature = "custom_sourcemap")] options: PrinterOptions<'a, S>,
281    #[cfg(not(feature = "custom_sourcemap"))] options: PrinterOptions<'a>,
282  ) -> Result<ToCssResult, Error<PrinterErrorKind>> {
283    // Make sure we always have capacity > 0: https://github.com/napi-rs/napi-rs/issues/1124.
284    let mut dest = String::with_capacity(1);
285    let project_root = options.project_root.clone();
286    let mut printer = Printer::new(&mut dest, options);
287    printer.sources = Some(&self.sources);
288
289    #[cfg(feature = "custom_sourcemap")]
290    if printer.source_map.is_some() {
291      printer.source_maps = self.sources.iter().enumerate().map(|(i, _)| self.source_map::<S>(i)).collect();
292      printer.source_map_source_indices = &self.source_map_source_indices;
293    }
294
295    for comment in &self.license_comments {
296      printer.write_str("/*")?;
297      printer.write_str(comment)?;
298      printer.write_str("*/\n")?;
299    }
300
301    if let Some(config) = &self.options.css_modules {
302      let mut references = CssModuleReferences::new();
303      printer.state.css_module = Some(CssModule::new(
304        config,
305        &self.sources,
306        project_root,
307        &mut references,
308        &self.content_hashes,
309      ));
310
311      self.rules.to_css(&mut printer)?;
312      printer.newline()?;
313
314      Ok(ToCssResult {
315        dependencies: printer.state.dependencies,
316        exports: Some(std::mem::take(
317          &mut printer.state.css_module.unwrap().exports_by_source_index[0],
318        )),
319        code: dest,
320        references: Some(references),
321      })
322    } else {
323      self.rules.to_css(&mut printer)?;
324      printer.newline()?;
325
326      Ok(ToCssResult {
327        dependencies: printer.state.dependencies,
328        code: dest,
329        exports: None,
330        references: None,
331      })
332    }
333  }
334}
335
336#[cfg(feature = "visitor")]
337#[cfg_attr(docsrs, doc(cfg(feature = "visitor")))]
338impl<'i, T, V> Visit<'i, T, V> for StyleSheet<'i, T>
339where
340  T: Visit<'i, T, V>,
341  V: ?Sized + Visitor<'i, T>,
342{
343  const CHILD_TYPES: VisitTypes = VisitTypes::all();
344
345  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
346    visitor.visit_stylesheet(self)
347  }
348
349  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
350    self.rules.visit(visitor)
351  }
352}
353
354/// An inline style attribute, as in HTML or SVG.
355///
356/// Style attributes can be parsed from a string, minified and transformed
357/// for a set of target browsers, and serialied to a string.
358///
359/// # Example
360///
361/// ```
362/// use rspack_lightningcss::stylesheet::{
363///   StyleAttribute, ParserOptions, MinifyOptions, PrinterOptions
364/// };
365///
366/// // Parse a style sheet from a string.
367/// let mut style = StyleAttribute::parse(
368///   "color: yellow; font-family: 'Helvetica';",
369///   ParserOptions::default()
370/// ).unwrap();
371///
372/// // Minify the stylesheet.
373/// style.minify(MinifyOptions::default());
374///
375/// // Serialize it to a string.
376/// let res = style.to_css(PrinterOptions::default()).unwrap();
377/// assert_eq!(res.code, "color: #ff0; font-family: Helvetica");
378/// ```
379#[cfg_attr(feature = "visitor", derive(Visit))]
380#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
381pub struct StyleAttribute<'i> {
382  /// The declarations in the style attribute.
383  pub declarations: DeclarationBlock<'i>,
384  #[cfg_attr(feature = "visitor", skip_visit)]
385  sources: Vec<String>,
386}
387
388impl<'i> StyleAttribute<'i> {
389  /// Parses a style attribute from a string.
390  pub fn parse(code: &'i str, options: ParserOptions<'i>) -> Result<StyleAttribute<'i>, Error<ParserError<'i>>> {
391    let mut input = ParserInput::new(&code);
392    let mut parser = Parser::new(&mut input);
393    Ok(StyleAttribute {
394      declarations: DeclarationBlock::parse(&mut parser, &options).map_err(|e| Error::from(e, "".into()))?,
395      sources: vec![options.filename],
396    })
397  }
398
399  /// Minify and transform the style attribute for the provided browser targets.
400  pub fn minify(&mut self, options: MinifyOptions) {
401    let mut context = PropertyHandlerContext::new(options.targets, &options.unused_symbols);
402    let mut handler = DeclarationHandler::default();
403    let mut important_handler = DeclarationHandler::default();
404    context.context = DeclarationContext::StyleAttribute;
405    self.declarations.minify(&mut handler, &mut important_handler, &mut context);
406  }
407
408  /// Serializes the style attribute to a CSS string.
409  pub fn to_css(&self, options: PrinterOptions) -> Result<ToCssResult, PrinterError> {
410    // Make sure we always have capacity > 0: https://github.com/napi-rs/napi-rs/issues/1124.
411    let mut dest = String::with_capacity(1);
412    let mut printer = Printer::new(&mut dest, options);
413    printer.sources = Some(&self.sources);
414
415    self.declarations.to_css(&mut printer)?;
416
417    Ok(ToCssResult {
418      dependencies: printer.take_dependencies(),
419      code: dest,
420      exports: None,
421      references: None,
422    })
423  }
424}