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