Module lightningcss::visitor

source ·
Available on crate feature visitor only.
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 std::convert::Infallible;
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 {
  type Error = Infallible;

  const TYPES: VisitTypes = visit_types!(URLS | LENGTHS);

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

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

    Ok(())
  }
}

stylesheet.visit(&mut MyVisitor).unwrap();

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

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.