1use lightningcss::{
2 stylesheet::{ParserOptions, PrinterOptions, StyleSheet},
3 targets::Browsers,
4};
5
6pub struct CssParser;
8
9impl CssParser {
10 pub fn parse(css: &str) -> Result<String, String> {
12 let stylesheet = StyleSheet::parse(
13 css,
14 ParserOptions {
15 filename: "style.css".to_string(),
16 ..Default::default()
17 },
18 )
19 .map_err(|e| format!("CSS parsing error: {:?}", e))?;
20
21 let targets = Browsers::default();
22 let printer_options = PrinterOptions {
23 minify: false,
24 targets: targets.into(),
25 ..Default::default()
26 };
27
28 let result = stylesheet
29 .to_css(printer_options)
30 .map_err(|e| format!("CSS generation error: {:?}", e))?;
31
32 Ok(result.code)
33 }
34
35 pub fn parse_minified(css: &str) -> Result<String, String> {
37 let stylesheet = StyleSheet::parse(
38 css,
39 ParserOptions {
40 filename: "style.css".to_string(),
41 ..Default::default()
42 },
43 )
44 .map_err(|e| format!("CSS parsing error: {:?}", e))?;
45
46 let targets = Browsers::default();
47 let printer_options = PrinterOptions {
48 minify: true,
49 targets: targets.into(),
50 ..Default::default()
51 };
52
53 let result = stylesheet
54 .to_css(printer_options)
55 .map_err(|e| format!("CSS generation error: {:?}", e))?;
56
57 Ok(result.code)
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn test_parse_simple_css() {
67 let css = ".button { color: red; }";
68 let result = CssParser::parse(css);
69 assert!(result.is_ok());
70 }
71
72 #[test]
73 fn test_parse_nested_css() {
74 let css = r#"
75 .button {
76 color: red;
77 &:hover {
78 color: blue;
79 }
80 }
81 "#;
82 let result = CssParser::parse(css);
83 assert!(result.is_ok());
84 }
85}