Parse StyleSheet into Css struct and pretty print it

This commit is contained in:
ConnorSkees 2020-01-05 12:37:02 -05:00
parent 3722ca98a0
commit c615c5806c
2 changed files with 107 additions and 0 deletions

9
Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "grass"
version = "0.1.0"
authors = ["ConnorSkees <39542938+ConnorSkees@users.noreply.github.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -211,6 +211,104 @@ impl StyleSheet {
pub fn pretty_print<W: std::io::Write>(&self, buf: W) -> io::Result<()> {
PrettyPrinter::new(buf).pretty_print(self)
}
pub fn pretty_print_selectors<W: std::io::Write>(&self, buf: W) -> io::Result<()> {
PrettyPrinter::new(buf).pretty_print_preserve_super_selectors(self)
}
pub fn print_as_css<W: std::io::Write>(self, buf: &mut W) -> io::Result<()> {
Css::from_stylesheet(self).pretty_print(buf)
}
}
#[derive(Debug, Clone)]
pub struct Block {
selector: Selector,
styles: Vec<Style>,
}
impl Block {
fn new(selector: Selector) -> Self {
Block {
selector,
styles: Vec::new(),
}
}
fn push(&mut self, s: Style) {
self.styles.push(s);
}
}
#[derive(Debug, Clone)]
pub struct Css {
blocks: Vec<Block>,
idx: usize,
}
impl Css {
pub fn new() -> Self {
Css {
blocks: Vec::new(),
idx: 0,
}
}
pub fn from_stylesheet(s: StyleSheet) -> Self {
Css {
blocks: Vec::new(),
idx: 0,
}
.parse_stylesheet(s)
}
fn parse_stmt(&mut self, stmt: Stmt) {
match stmt {
Stmt::Style(s) => self.blocks[self.idx - 1].push(s),
Stmt::RuleSet(RuleSet {
selector,
super_selector,
rules,
}) => {
if self.idx == 0 {
self.idx = self.blocks.len() + 1;
self.blocks.push(Block::new(super_selector.zip(selector)));
for rule in rules {
self.parse_stmt(rule);
}
self.idx = 0;
} else {
self.idx += 1;
self.blocks.push(Block::new(super_selector.zip(selector)));
for rule in rules {
self.parse_stmt(rule);
}
self.idx -= 1;
}
}
}
}
fn parse_stylesheet(mut self, s: StyleSheet) -> Css {
for stmt in s.rules {
self.parse_stmt(stmt);
}
self
}
pub fn pretty_print<W: std::io::Write>(self, buf: &mut W) -> io::Result<()> {
for block in self.blocks {
if block.styles.is_empty() {
continue;
}
writeln!(buf, "{} {{", block.selector)?;
for style in block.styles {
writeln!(buf, " {}", style)?;
}
writeln!(buf, "}}")?;
}
Ok(())
}
}
#[derive(Debug, Clone)]