add pretty printing

This commit is contained in:
annieversary 2022-08-16 22:46:43 +01:00
parent 3241f5570d
commit 11f2819ec8
5 changed files with 54 additions and 22 deletions

View File

@ -1,9 +1,10 @@
use std::borrow::Cow; use std::borrow::Cow;
use crate::{ use crate::{
indent,
media_queries::{wrap_in_query, ReducedMotion, Responsive}, media_queries::{wrap_in_query, ReducedMotion, Responsive},
modifiers::Modifiers, modifiers::Modifiers,
Zephyr, ZephyrError, nl, space, Zephyr, ZephyrError,
}; };
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
@ -83,7 +84,7 @@ impl<'a> Class<'a> {
/// generates the css rule for this class /// generates the css rule for this class
/// does not generate the corresponding media query /// does not generate the corresponding media query
pub(crate) fn generate(&self, z: &Zephyr) -> Result<String, ZephyrError> { pub(crate) fn generate(&self, z: &Zephyr, indent_level: usize) -> Result<String, ZephyrError> {
let property = z let property = z
.properties .properties
.get(self.property) .get(self.property)
@ -91,6 +92,11 @@ impl<'a> Class<'a> {
.unwrap_or(self.property); .unwrap_or(self.property);
let selector = self.selector(z); let selector = self.selector(z);
let space = space(z.pretty_print);
let indent2 = indent(z.pretty_print, indent_level + 1);
let indent = indent(z.pretty_print, indent_level);
let nl = nl(z.pretty_print);
if let Some(val) = self.value { if let Some(val) = self.value {
let val = match self.value_type { let val = match self.value_type {
ValueType::Normal => { ValueType::Normal => {
@ -109,22 +115,24 @@ impl<'a> Class<'a> {
if let Some(fun) = z.specials.get(property) { if let Some(fun) = z.specials.get(property) {
let v = fun(&val); let v = fun(&val);
Ok(format!("{selector}{{{v}}}",)) Ok(format!(
"{indent}{selector}{space}{{{nl}{indent2}{v}{nl}{indent}}}{nl}",
))
} else { } else {
Ok(format!("{selector}{{{property}:{val}}}")) Ok(format!(
"{indent}{selector}{space}{{{nl}{indent2}{property}:{val}{nl}{indent}}}{nl}"
))
} }
} else if let Some(v) = z.declarations.get(property) { } else if let Some(v) = z.declarations.get(property) {
Ok(format!("{selector}{{{v}}}")) Ok(format!(
"{indent}{selector}{space}{{{nl}{indent2}{v}{nl}{indent}}}{nl}"
))
} else { } else {
Err(ZephyrError::ValueMissing) Err(ZephyrError::ValueMissing)
} }
} }
pub fn generate_with_media_query(&self, z: &Zephyr) -> Result<String, ZephyrError> { pub fn generate_with_media_query(&self, z: &Zephyr) -> Result<String, ZephyrError> {
let css = self.generate(z)?;
dbg!(&self.modifiers);
let mut queries: Vec<String> = vec![]; let mut queries: Vec<String> = vec![];
if let Some(r) = &self.modifiers.responsive { if let Some(r) = &self.modifiers.responsive {
queries.extend(r.queries()); queries.extend(r.queries());
@ -133,7 +141,9 @@ impl<'a> Class<'a> {
queries.extend(r.queries().iter().map(ToString::to_string)); queries.extend(r.queries().iter().map(ToString::to_string));
} }
Ok(wrap_in_query(css, &queries)) let css = self.generate(z, queries.is_empty().then_some(0).unwrap_or(1))?;
Ok(wrap_in_query(css, &queries, z.pretty_print))
} }
} }

View File

@ -44,6 +44,7 @@ pub(crate) fn default_properties() -> HashMap<String, String> {
("bgc", "background-color"), ("bgc", "background-color"),
("tt", "text-transform"), ("tt", "text-transform"),
("td", "text-decoration"), ("td", "text-decoration"),
("fw", "font-weight"),
// TODO // TODO
]) ])
} }

View File

@ -42,6 +42,8 @@ pub struct Zephyr {
/// ///
/// property -> [(short, expanded)] /// property -> [(short, expanded)]
pub context_aware_values: HashMap<String, HashMap<String, String>>, pub context_aware_values: HashMap<String, HashMap<String, String>>,
pub pretty_print: bool,
} }
/// value -> declarations /// value -> declarations
@ -97,7 +99,7 @@ impl Zephyr {
let len = classes.len(); let len = classes.len();
tracing::trace!("finished generating {len} classes"); tracing::trace!("finished generating {len} classes");
classes.join("") classes.join(nl(self.pretty_print))
} }
/// this one returns an error if parsing or generating fails /// this one returns an error if parsing or generating fails
@ -116,15 +118,30 @@ impl Zephyr {
pseudos: default_pseudos(), pseudos: default_pseudos(),
specials: default_specials(), specials: default_specials(),
context_aware_values: default_context_aware_values(), context_aware_values: default_context_aware_values(),
pretty_print: false,
} }
} }
pub fn with_css_colors(mut self) -> Self { pub fn with_css_colors(mut self) -> Self {
self.declarations.extend( self.declarations
crate::consts::CSS_COLORS .extend(crate::consts::CSS_COLORS.iter().map(|c| {
.iter() (
.map(|c| (c.to_string(), format!("color:{c}"))), c.to_string(),
); format!("color:{}{c}", space(self.pretty_print)),
)
}));
self self
} }
} }
pub(crate) fn space(b: bool) -> &'static str {
b.then_some(" ").unwrap_or_default()
}
pub(crate) fn indent(b: bool, level: usize) -> String {
b.then_some(" ".repeat(level)).unwrap_or_default()
}
pub(crate) fn nl(b: bool) -> &'static str {
b.then_some("\n").unwrap_or_default()
}

View File

@ -1,3 +1,5 @@
use crate::{nl, space};
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub(crate) struct Responsive { pub(crate) struct Responsive {
breakpoint: Breakpoint, breakpoint: Breakpoint,
@ -118,7 +120,7 @@ impl ReducedMotion {
} }
} }
pub(crate) fn wrap_in_query(css: String, queries: &[String]) -> String { pub(crate) fn wrap_in_query(css: String, queries: &[String], pretty_print: bool) -> String {
if queries.is_empty() { if queries.is_empty() {
return css; return css;
} }
@ -126,8 +128,10 @@ pub(crate) fn wrap_in_query(css: String, queries: &[String]) -> String {
.iter() .iter()
.map(|s| format!("({s})")) .map(|s| format!("({s})"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join("and"); .join(if pretty_print { " and " } else { "and" });
format!("@media{query}{{{css}}}") let space = space(pretty_print);
let nl = nl(pretty_print);
format!("@media{space}{query}{space}{{{nl}{css}}}{nl}")
} }
#[cfg(test)] #[cfg(test)]

View File

@ -13,7 +13,7 @@ fn generate_margin_works() {
original: "m[1rem]", original: "m[1rem]",
value_type: class::ValueType::Normal, value_type: class::ValueType::Normal,
}; };
let css = class.generate(&z).unwrap(); let css = class.generate(&z, 0).unwrap();
assert_eq!(css, r#".m\[1rem\]{margin:1rem}"#); assert_eq!(css, r#".m\[1rem\]{margin:1rem}"#);
let class = Class { let class = Class {
@ -24,7 +24,7 @@ fn generate_margin_works() {
original: "m[1rem]focus", original: "m[1rem]focus",
value_type: class::ValueType::Normal, value_type: class::ValueType::Normal,
}; };
let css = class.generate(&z).unwrap(); let css = class.generate(&z, 0).unwrap();
assert_eq!(css, r#".m\[1rem\]focus:focus{margin:1rem}"#); assert_eq!(css, r#".m\[1rem\]focus:focus{margin:1rem}"#);
let class = Class { let class = Class {
@ -35,7 +35,7 @@ fn generate_margin_works() {
original: "m[1rem]focus,hover,odd", original: "m[1rem]focus,hover,odd",
value_type: class::ValueType::Normal, value_type: class::ValueType::Normal,
}; };
let css = class.generate(&z).unwrap(); let css = class.generate(&z, 0).unwrap();
assert_eq!( assert_eq!(
css, css,
r#".m\[1rem\]focus,hover,odd:focus:hover:nth-child\(odd\){margin:1rem}"# r#".m\[1rem\]focus,hover,odd:focus:hover:nth-child\(odd\){margin:1rem}"#