Skip to main content

StyleSheet

Struct StyleSheet 

Source
pub struct StyleSheet<'i, T = DefaultAtRule> {
    pub rules: CssRuleList<'i, T>,
    pub sources: Vec<String>,
    pub source_map_urls: Vec<Option<String>>,
    pub license_comments: Vec<CowArcStr<'i>>,
    /* private fields */
}
Expand description

A CSS style sheet, representing a .css file or inline <style> element.

Style sheets can be parsed from a string, constructed from scratch, or created using a Bundler. Then, they can be minified and transformed for a set of target browsers, and serialied to a string.

§Example

use lightningcss::stylesheet::{
  StyleSheet, ParserOptions, MinifyOptions, PrinterOptions
};

// Parse a style sheet from a string.
let mut stylesheet = StyleSheet::parse(
  r#"
  .foo {
    color: red;
  }

  .bar {
    color: red;
  }
  "#,
  ParserOptions::default()
).unwrap();

// Minify the stylesheet.
stylesheet.minify(MinifyOptions::default()).unwrap();

// Serialize it to a string.
let res = stylesheet.to_css(PrinterOptions::default()).unwrap();
assert_eq!(res.code, ".foo, .bar {\n  color: red;\n}\n");

Fields§

§rules: CssRuleList<'i, T>

A list of top-level rules within the style sheet.

§sources: Vec<String>

A list of file names for all source files included within the style sheet. Sources are referenced by index in the loc property of each rule.

§source_map_urls: Vec<Option<String>>

The source map URL extracted from the original style sheet.

§license_comments: Vec<CowArcStr<'i>>

The license comments that appeared at the start of the file.

Implementations§

Source§

impl<'i, 'o> StyleSheet<'i, DefaultAtRule>

Source

pub fn parse( code: &'i str, options: ParserOptions<'i>, ) -> Result<Self, Error<ParserError<'i>>>

Parse a style sheet from a string.

Examples found in repository?
examples/serialize.rs (lines 12-18)
6fn parse() {
7  use lightningcss::stylesheet::{ParserOptions, StyleSheet};
8  use std::{env, fs};
9
10  let args: Vec<String> = env::args().collect();
11  let contents = fs::read_to_string(&args[1]).unwrap();
12  let stylesheet = StyleSheet::parse(
13    &contents,
14    ParserOptions {
15      filename: args[1].clone(),
16      ..ParserOptions::default()
17    },
18  )
19  .unwrap();
20  let json = serde_json::to_string(&stylesheet).unwrap();
21  println!("{}", json);
22}
Source§

impl<'i, T> StyleSheet<'i, T>
where T: ToCss + Clone,

Source

pub fn new( sources: Vec<String>, rules: CssRuleList<'i, T>, options: ParserOptions<'i>, ) -> StyleSheet<'i, T>

Creates a new style sheet with the given source filenames and rules.

Source

pub fn parse_with<P: AtRuleParser<'i, AtRule = T>>( code: &'i str, options: ParserOptions<'i>, at_rule_parser: &mut P, ) -> Result<Self, Error<ParserError<'i>>>

Parse a style sheet from a string.

Examples found in repository?
examples/custom_at_rule.rs (line 31)
23fn main() {
24  let args: Vec<String> = std::env::args().collect();
25  let source = std::fs::read_to_string(&args[1]).unwrap();
26  let opts = ParserOptions {
27    filename: args[1].clone(),
28    ..Default::default()
29  };
30
31  let mut stylesheet = StyleSheet::parse_with(&source, opts, &mut TailwindAtRuleParser).unwrap();
32
33  println!("{:?}", stylesheet);
34
35  let mut style_rules = HashMap::new();
36  stylesheet
37    .visit(&mut StyleRuleCollector {
38      rules: &mut style_rules,
39    })
40    .unwrap();
41  println!("{:?}", style_rules);
42  stylesheet.visit(&mut ApplyVisitor { rules: &style_rules }).unwrap();
43
44  let result = stylesheet
45    .to_css(PrinterOptions {
46      targets: Browsers {
47        chrome: Some(100 << 16),
48        ..Browsers::default()
49      }
50      .into(),
51      ..PrinterOptions::default()
52    })
53    .unwrap();
54  println!("{}", result.code);
55}
Source

pub fn source_map_url(&self, source_index: usize) -> Option<&String>

Returns the source map URL for the source at the given index.

Source

pub fn source_map(&self, source_index: usize) -> Option<SourceMap>

Available on crate feature sourcemap only.

Returns the inline source map associated with the source at the given index.

Source

pub fn minify( &mut self, options: MinifyOptions, ) -> Result<(), Error<MinifyErrorKind>>

Minify and transform the style sheet for the provided browser targets.

Examples found in repository?
examples/vize_bundler_before_observer.rs (line 42)
20fn observe(case: &Value, provider: &Provider) -> Value {
21  let mut map = SourceMap::new("/");
22  let options = ParserOptions {
23    css_modules: case["cssModules"].as_bool().unwrap_or(false).then(|| Config {
24      dashed_idents: true,
25      pattern: Pattern::parse("[hash]_[local]").unwrap(),
26      ..Default::default()
27    }),
28    ..Default::default()
29  };
30  let mut bundler = Bundler::new(provider, Some(&mut map), options);
31  let result = match bundler.bundle(Path::new(case["entry"].as_str().unwrap())) {
32    Ok(mut stylesheet) => {
33      // Preserve pre-minification source/map/comment/context metadata too.
34      let bundle = json!({
35        "ast": stylesheet,
36        "sources": stylesheet.sources,
37        "sourceMapUrls": stylesheet.source_map_urls,
38        "licenseComments": stylesheet.license_comments,
39        "privateContentHashesObserved": false,
40      });
41      let minify_error = if case["minify"].as_bool().unwrap_or(false) {
42        stylesheet.minify(MinifyOptions::default()).err()
43      } else {
44        None
45      };
46      if let Some(value) = minify_error {
47        json!({"bundle": bundle, "error": error("minify", value)})
48      } else {
49        match stylesheet.to_css(PrinterOptions {
50          source_map: Some(&mut map),
51          ..Default::default()
52        }) {
53          Ok(result) => json!({
54            "bundle": bundle, "code": result.code, "exports": result.exports,
55            "references": result.references, "dependencies": result.dependencies,
56          }),
57          Err(value) => json!({"bundle": bundle, "error": error("print", value)}),
58        }
59      }
60    }
61    Err(value) => json!({"error": error("bundle", value)}),
62  };
63  let mappings: Vec<Value> = map
64    .get_mappings()
65    .iter()
66    .map(|mapping| {
67      json!({
68        "generatedLine": mapping.generated_line,
69        "generatedColumn": mapping.generated_column,
70        "original": mapping.original.map(|value| json!({
71          "line": value.original_line, "column": value.original_column,
72          "source": value.source, "name": value.name,
73        })),
74      })
75    })
76    .collect();
77  json!({
78    "result": result,
79    "map": {"json": map.to_json(None).unwrap(), "sources": map.get_sources(),
80      "sourcesContent": map.get_sources_content(), "names": map.get_names(), "mappings": mappings},
81  })
82}
Source

pub fn to_css( &self, options: PrinterOptions<'_>, ) -> Result<ToCssResult, Error<PrinterErrorKind>>

Serialize the style sheet to a CSS string.

Examples found in repository?
examples/custom_at_rule.rs (lines 45-52)
23fn main() {
24  let args: Vec<String> = std::env::args().collect();
25  let source = std::fs::read_to_string(&args[1]).unwrap();
26  let opts = ParserOptions {
27    filename: args[1].clone(),
28    ..Default::default()
29  };
30
31  let mut stylesheet = StyleSheet::parse_with(&source, opts, &mut TailwindAtRuleParser).unwrap();
32
33  println!("{:?}", stylesheet);
34
35  let mut style_rules = HashMap::new();
36  stylesheet
37    .visit(&mut StyleRuleCollector {
38      rules: &mut style_rules,
39    })
40    .unwrap();
41  println!("{:?}", style_rules);
42  stylesheet.visit(&mut ApplyVisitor { rules: &style_rules }).unwrap();
43
44  let result = stylesheet
45    .to_css(PrinterOptions {
46      targets: Browsers {
47        chrome: Some(100 << 16),
48        ..Browsers::default()
49      }
50      .into(),
51      ..PrinterOptions::default()
52    })
53    .unwrap();
54  println!("{}", result.code);
55}
More examples
Hide additional examples
examples/vize_bundler_before_observer.rs (lines 49-52)
20fn observe(case: &Value, provider: &Provider) -> Value {
21  let mut map = SourceMap::new("/");
22  let options = ParserOptions {
23    css_modules: case["cssModules"].as_bool().unwrap_or(false).then(|| Config {
24      dashed_idents: true,
25      pattern: Pattern::parse("[hash]_[local]").unwrap(),
26      ..Default::default()
27    }),
28    ..Default::default()
29  };
30  let mut bundler = Bundler::new(provider, Some(&mut map), options);
31  let result = match bundler.bundle(Path::new(case["entry"].as_str().unwrap())) {
32    Ok(mut stylesheet) => {
33      // Preserve pre-minification source/map/comment/context metadata too.
34      let bundle = json!({
35        "ast": stylesheet,
36        "sources": stylesheet.sources,
37        "sourceMapUrls": stylesheet.source_map_urls,
38        "licenseComments": stylesheet.license_comments,
39        "privateContentHashesObserved": false,
40      });
41      let minify_error = if case["minify"].as_bool().unwrap_or(false) {
42        stylesheet.minify(MinifyOptions::default()).err()
43      } else {
44        None
45      };
46      if let Some(value) = minify_error {
47        json!({"bundle": bundle, "error": error("minify", value)})
48      } else {
49        match stylesheet.to_css(PrinterOptions {
50          source_map: Some(&mut map),
51          ..Default::default()
52        }) {
53          Ok(result) => json!({
54            "bundle": bundle, "code": result.code, "exports": result.exports,
55            "references": result.references, "dependencies": result.dependencies,
56          }),
57          Err(value) => json!({"bundle": bundle, "error": error("print", value)}),
58        }
59      }
60    }
61    Err(value) => json!({"error": error("bundle", value)}),
62  };
63  let mappings: Vec<Value> = map
64    .get_mappings()
65    .iter()
66    .map(|mapping| {
67      json!({
68        "generatedLine": mapping.generated_line,
69        "generatedColumn": mapping.generated_column,
70        "original": mapping.original.map(|value| json!({
71          "line": value.original_line, "column": value.original_column,
72          "source": value.source, "name": value.name,
73        })),
74      })
75    })
76    .collect();
77  json!({
78    "result": result,
79    "map": {"json": map.to_json(None).unwrap(), "sources": map.get_sources(),
80      "sourcesContent": map.get_sources_content(), "names": map.get_names(), "mappings": mappings},
81  })
82}

Trait Implementations§

Source§

impl<'i, T: Clone> Clone for StyleSheet<'i, T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'i, T: Debug> Debug for StyleSheet<'i, T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de: 'i, 'i, T> Deserialize<'de> for StyleSheet<'i, T>
where T: Deserialize<'de>,

Available on crate feature serde only.
Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<'any, 'i, T> IntoOwned<'any> for StyleSheet<'i, T>
where T: IntoOwned<'any>,

Available on crate feature into_owned only.
Source§

fn into_owned(self) -> Self::Owned

Consumes the value and returns an owned clone.

Source§

type Owned = StyleSheet<'any, <T as IntoOwned<'any>>::Owned>

A variant of Self with a new lifetime.
Source§

impl<'i, T> JsonSchema for StyleSheet<'i, T>
where T: JsonSchema,

Available on crate feature jsonschema only.
Source§

fn schema_name() -> String

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn is_referenceable() -> bool

Whether JSON Schemas generated for this type should be re-used where possible using the $ref keyword. Read more
Source§

impl<'i, T> Serialize for StyleSheet<'i, T>
where T: Serialize,

Available on crate feature serde only.
Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<'i, T, V> Visit<'i, T, V> for StyleSheet<'i, T>
where T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>,

Available on crate feature visitor only.
Source§

const CHILD_TYPES: VisitTypes

The types of values contained within this value and its children. This is used to skip branches that don’t have any values requested by the Visitor.
Source§

fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error>

Visits the value by calling an appropriate method on the Visitor. If no corresponding visitor method exists, then the children are visited.
Source§

fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error>

Visit the children of this value.

Auto Trait Implementations§

§

impl<'i, T> Freeze for StyleSheet<'i, T>
where CssRuleList<'i, T>: Freeze,

§

impl<'i, T> RefUnwindSafe for StyleSheet<'i, T>
where CssRuleList<'i, T>: RefUnwindSafe,

§

impl<'i, T> Send for StyleSheet<'i, T>
where CssRuleList<'i, T>: Send,

§

impl<'i, T> Sync for StyleSheet<'i, T>
where CssRuleList<'i, T>: Sync,

§

impl<'i, T> Unpin for StyleSheet<'i, T>
where CssRuleList<'i, T>: Unpin,

§

impl<'i, T> UnsafeUnpin for StyleSheet<'i, T>
where CssRuleList<'i, T>: UnsafeUnpin,

§

impl<'i, T> UnwindSafe for StyleSheet<'i, T>
where CssRuleList<'i, T>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.