Skip to main content

jsx_generator/
formatter.rs

1use crate::error::{GeneratorError, GeneratorResult};
2use log::debug;
3
4/// Configuration for code formatting
5#[derive(Debug, Clone)]
6pub struct FormatterConfig {
7    pub indent_width: usize,
8    pub use_tabs: bool,
9    pub line_width: usize,
10    pub bracket_style: BracketStyle,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub enum BracketStyle {
15    AllmanStyle,    // Opening brace on new line
16    KandRStyle,     // Opening brace on same line
17}
18
19impl Default for FormatterConfig {
20    fn default() -> Self {
21        FormatterConfig {
22            indent_width: 2,
23            use_tabs: false,
24            line_width: 100,
25            bracket_style: BracketStyle::KandRStyle,
26        }
27    }
28}
29
30/// Formats JSX code for readability
31pub struct CodeFormatter {
32    config: FormatterConfig,
33}
34
35impl CodeFormatter {
36    /// Create a new code formatter
37    pub fn new(config: FormatterConfig) -> Self {
38        CodeFormatter { config }
39    }
40
41    /// Create with default config
42    pub fn default() -> Self {
43        Self::new(FormatterConfig::default())
44    }
45
46    /// Format code string
47    pub fn format(&self, code: &str) -> GeneratorResult<String> {
48        debug!("Formatting code ({} chars)", code.len());
49
50        let mut result = String::with_capacity(code.len());
51        let mut indent_level = 0;
52        let mut in_string = false;
53        let mut string_char = '"';
54        let mut prev_char = ' ';
55        let mut line_length = 0;
56
57        let chars: Vec<char> = code.chars().collect();
58        let mut i = 0;
59
60        while i < chars.len() {
61            let ch = chars[i];
62
63            // Handle strings
64            if (ch == '"' || ch == '\'' || ch == '`') && prev_char != '\\' {
65                if !in_string {
66                    in_string = true;
67                    string_char = ch;
68                } else if ch == string_char {
69                    in_string = false;
70                }
71                result.push(ch);
72                line_length += 1;
73                prev_char = ch;
74                i += 1;
75                continue;
76            }
77
78            if in_string {
79                result.push(ch);
80                line_length += 1;
81                prev_char = ch;
82                i += 1;
83                continue;
84            }
85
86            // Handle whitespace
87            if ch.is_whitespace() {
88                if ch == '\n' {
89                    result.push('\n');
90                    result.push_str(&self.indent_str(indent_level));
91                    line_length = indent_level * self.config.indent_width;
92                    prev_char = '\n';
93                    i += 1;
94                    continue;
95                }
96
97                if prev_char != ' ' && prev_char != '\n' && prev_char != '{' && prev_char != '(' && prev_char != ':' && prev_char != ',' {
98                    result.push(' ');
99                    line_length += 1;
100                }
101                prev_char = ' ';
102                i += 1;
103                continue;
104            }
105
106            // Handle braces and brackets
107            match ch {
108                '{' => {
109                    result.push(ch);
110                    result.push('\n');
111                    indent_level += 1;
112                    result.push_str(&self.indent_str(indent_level));
113                    line_length = indent_level * self.config.indent_width;
114                }
115
116                '}' => {
117                    if !result.ends_with('\n') && !result.ends_with(' ') {
118                        result.push('\n');
119                    }
120                    indent_level = indent_level.saturating_sub(1);
121                    result.push_str(&self.indent_str(indent_level));
122                    result.push(ch);
123                    line_length = indent_level * self.config.indent_width + 1;
124                }
125
126                ';' => {
127                    result.push(ch);
128                    result.push('\n');
129                    result.push_str(&self.indent_str(indent_level));
130                    line_length = indent_level * self.config.indent_width;
131                }
132
133                ',' => {
134                    result.push(ch);
135                    result.push(' ');
136                    line_length += 2;
137                }
138
139                '(' | '[' => {
140                    result.push(ch);
141                    line_length += 1;
142                }
143
144                ')' | ']' => {
145                    result.push(ch);
146                    line_length += 1;
147                }
148
149                ':' => {
150                    result.push(ch);
151                    result.push(' ');
152                    line_length += 2;
153                }
154
155                _ => {
156                    result.push(ch);
157                    line_length += 1;
158                }
159            }
160
161            prev_char = ch;
162            i += 1;
163        }
164
165        // Clean up trailing whitespace
166        while result.ends_with('\n') || result.ends_with(' ') {
167            if result.ends_with('\n') {
168                break;
169            }
170            result.pop();
171        }
172
173        Ok(result)
174    }
175
176    /// Minify code (remove whitespace, comments)
177    pub fn minify(&self, code: &str) -> GeneratorResult<String> {
178        debug!("Minifying code ({} chars)", code.len());
179
180        let mut result = String::new();
181        let mut in_string = false;
182        let mut string_char = '"';
183        let mut prev_was_space = false;
184
185        for (i, ch) in code.chars().enumerate() {
186            // Track string boundaries
187            if (ch == '"' || ch == '\'' || ch == '`') && (i == 0 || code.chars().nth(i - 1) != Some('\\')) {
188                if !in_string {
189                    in_string = true;
190                    string_char = ch;
191                } else if ch == string_char {
192                    in_string = false;
193                }
194            }
195
196            if in_string {
197                result.push(ch);
198                prev_was_space = false;
199                continue;
200            }
201
202            // Remove non-essential whitespace
203            if ch.is_whitespace() {
204                if !prev_was_space
205                    && !result.ends_with('(')
206                    && !result.ends_with('{')
207                    && !result.ends_with('[')
208                    && !result.ends_with(',')
209                {
210                    result.push(' ');
211                    prev_was_space = true;
212                }
213                continue;
214            }
215
216            // Remove comments
217            if ch == '/' {
218                if let Some(next) = code.chars().nth(i + 1) {
219                    if next == '/' {
220                        // Line comment - skip to end of line
221                        break;
222                    } else if next == '*' {
223                        // Block comment - skip to */
224                        let rest = &code[i + 2..];
225                        if let Some(end) = rest.find("*/") {
226                            // Skip past the comment
227                            continue;
228                        }
229                    }
230                }
231            }
232
233            result.push(ch);
234            prev_was_space = false;
235        }
236
237        Ok(result.trim().to_string())
238    }
239
240    fn indent_str(&self, level: usize) -> String {
241        if self.config.use_tabs {
242            "\t".repeat(level)
243        } else {
244            " ".repeat(level * self.config.indent_width)
245        }
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn test_format_simple() {
255        let formatter = CodeFormatter::default();
256        let code = "var x = { a: 1, b: 2 };";
257        let formatted = formatter.format(code).unwrap();
258        assert!(formatted.contains("a: 1"));
259    }
260
261    #[test]
262    fn test_minify_removes_whitespace() {
263        let formatter = CodeFormatter::default();
264        let code = "var  x  =  1 ;";
265        let minified = formatter.minify(code).unwrap();
266        assert_eq!(minified, "var x = 1 ;");
267    }
268
269    #[test]
270    fn test_preserve_strings() {
271        let formatter = CodeFormatter::default();
272        let code = r#"var x = "hello world";"#;
273        let formatted = formatter.format(code).unwrap();
274        assert!(formatted.contains("hello world"));
275    }
276}