1mod stylerule;
2use std::hash::{DefaultHasher, Hasher};
3
4pub use stylerule::StyleRule;
5
6use cssparser::{Parser, ParserInput};
7use lightningcss::{
8 declaration::DeclarationBlock, printer::PrinterOptions, properties::Property,
9 stylesheet::ParserOptions,
10};
11
12pub fn parse_css_block(string: &str) -> Vec<(String, Property<'_>)> {
13 let mut parser_input = ParserInput::new(string);
14 let mut parser = Parser::new(&mut parser_input);
15 let parsed_styles =
16 DeclarationBlock::parse(&mut parser, &ParserOptions::default())
17 .expect("Invalid css");
18
19 let mut nice = Vec::default();
20
21 for style in parsed_styles.declarations {
22 let mut hasher = DefaultHasher::default();
23 hasher.write(style.property_id().name().as_bytes());
24 let options = PrinterOptions { minify: true, ..Default::default() };
25 hasher.write(style.value_to_css_string(options).unwrap().as_bytes());
26 let hash = encode_base62(hasher.finish());
27 nice.push((format!("r{hash}"), style));
28 }
29 for style in parsed_styles.important_declarations {
30 let mut hasher = DefaultHasher::default();
31 hasher.write(style.property_id().name().as_bytes());
32 let options = PrinterOptions { minify: true, ..Default::default() };
33 hasher.write(style.value_to_css_string(options).unwrap().as_bytes());
34 let hash = encode_base62(hasher.finish());
35 nice.push((hash, style));
36 }
37
38 nice
39}
40
41const BASE62: &[u8] =
42 b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
43pub fn encode_base62(mut num: u64) -> String {
44 let mut result = String::new();
45 while num > 0 {
46 let remainder = (num % 62) as usize;
47 result.push(BASE62[remainder] as char);
48 num /= 62;
49 }
50 result.chars().rev().collect()
51}