| 104 | } |
| 105 | |
| 106 | fn format_with_options(source_text: &str, options: FormatOptions) -> Result<String, String> { |
| 107 | let allocator = Bump::default(); |
| 108 | let lexer = Lexer::new(&CssAtomSet::ATOMS, source_text); |
| 109 | let result = Parser::new(&allocator, source_text, lexer).parse_entirely::<StyleSheet>(); |
| 110 | if !result.errors.is_empty() { |
| 111 | let first_error = &result.errors[0]; |
| 112 | let DiagnosticMeta { code, message, help, .. } = (first_error.formatter)(first_error, source_text); |
| 113 | return Err(format!("Parse error [{}]: {} (Help: {})", code, message, help)); |
| 114 | } |
| 115 | let mut output_string = String::new(); |
| 116 | if result.output.is_some() { |
| 117 | let indent_width = options.indent_width.unwrap_or(2).clamp(1, 8); |
| 118 | let expand_tab = match options.indent_style.unwrap_or(IndentStyle::Spaces) { |
| 119 | IndentStyle::Spaces => Some(indent_width), |
| 120 | IndentStyle::Tabs => None, |
| 121 | }; |
| 122 | let quote_style = match options.quote_style.unwrap_or(QuoteStyleOption::Double) { |
| 123 | QuoteStyleOption::Double => QuoteStyle::Double, |
| 124 | QuoteStyleOption::Single => QuoteStyle::Single, |
| 125 | }; |
| 126 | let mut stream = CursorPrettyWriteSink::new(source_text, &mut output_string, expand_tab, quote_style); |
| 127 | result.to_cursors(&mut stream); |
| 128 | } |
| 129 | Ok(output_string) |
| 130 | } |
| 131 | |
| 132 | #[wasm_bindgen] |
| 133 | pub fn parse_error_report(source_text: String) -> String { |