Module lightningcss::visitor

source ·
Expand description

Visitors for traversing the values in a StyleSheet.

The Visitor trait includes methods for visiting and transforming rules, properties, and values within a StyleSheet. Each value implements the Visit trait, which knows how to visit the value itself, as well as its children. A Visitor is configured to only visit specific types of values using VisitTypes flags. This enables entire branches to be skipped when a type does not contain any relevant values.

Example

This example transforms a stylesheet, adding a prefix to all URLs, and converting pixels to rems.

use lightningcss::{
  stylesheet::{StyleSheet, ParserOptions, PrinterOptions},
  visitor::{Visitor, Visit, VisitTypes},
  visit_types,
  values::length::LengthValue,
  values::url::Url
};

let mut stylesheet = StyleSheet::parse(
  r#"
    .foo {
      background: url(bg.png);
      width: 32px;
    }
  "#,
  ParserOptions::default()
).unwrap();

struct MyVisitor;
impl<'i> Visitor<'i> for MyVisitor {
  const TYPES: VisitTypes = visit_types!(URLS | LENGTHS);

  fn visit_url(&mut self, url: &mut Url<'i>) {
    url.url = format!("https://mywebsite.com/{}", url.url).into()
  }

  fn visit_length(&mut self, length: &mut LengthValue) {
    match length {
      LengthValue::Px(px) => *length = LengthValue::Rem(*px / 16.0),
      _ => {}
    }
  }
}

stylesheet.visit(&mut MyVisitor);

let res = stylesheet.to_css(PrinterOptions { minify: true, ..Default::default() }).unwrap();
assert_eq!(res.code, ".foo{background:url(https://mywebsite.com/bg.png);width:2rem}");

Structs

Describes what a Visitor will visit when traversing a StyleSheet.

Traits

A trait for values that can be visited by a Visitor.
A trait for visiting or transforming rules, properties, and values in a StyleSheet.