jsx-generator 1.0.0

JSX code generator with formatting, optimization, and minification capabilities
Documentation
use crate::error::{GeneratorError, GeneratorResult};
use log::debug;

/// Configuration for code formatting
#[derive(Debug, Clone)]
pub struct FormatterConfig {
    pub indent_width: usize,
    pub use_tabs: bool,
    pub line_width: usize,
    pub bracket_style: BracketStyle,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BracketStyle {
    AllmanStyle,    // Opening brace on new line
    KandRStyle,     // Opening brace on same line
}

impl Default for FormatterConfig {
    fn default() -> Self {
        FormatterConfig {
            indent_width: 2,
            use_tabs: false,
            line_width: 100,
            bracket_style: BracketStyle::KandRStyle,
        }
    }
}

/// Formats JSX code for readability
pub struct CodeFormatter {
    config: FormatterConfig,
}

impl CodeFormatter {
    /// Create a new code formatter
    pub fn new(config: FormatterConfig) -> Self {
        CodeFormatter { config }
    }

    /// Create with default config
    pub fn default() -> Self {
        Self::new(FormatterConfig::default())
    }

    /// Format code string
    pub fn format(&self, code: &str) -> GeneratorResult<String> {
        debug!("Formatting code ({} chars)", code.len());

        let mut result = String::with_capacity(code.len());
        let mut indent_level = 0;
        let mut in_string = false;
        let mut string_char = '"';
        let mut prev_char = ' ';
        let mut line_length = 0;

        let chars: Vec<char> = code.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            let ch = chars[i];

            // Handle strings
            if (ch == '"' || ch == '\'' || ch == '`') && prev_char != '\\' {
                if !in_string {
                    in_string = true;
                    string_char = ch;
                } else if ch == string_char {
                    in_string = false;
                }
                result.push(ch);
                line_length += 1;
                prev_char = ch;
                i += 1;
                continue;
            }

            if in_string {
                result.push(ch);
                line_length += 1;
                prev_char = ch;
                i += 1;
                continue;
            }

            // Handle whitespace
            if ch.is_whitespace() {
                if ch == '\n' {
                    result.push('\n');
                    result.push_str(&self.indent_str(indent_level));
                    line_length = indent_level * self.config.indent_width;
                    prev_char = '\n';
                    i += 1;
                    continue;
                }

                if prev_char != ' ' && prev_char != '\n' && prev_char != '{' && prev_char != '(' && prev_char != ':' && prev_char != ',' {
                    result.push(' ');
                    line_length += 1;
                }
                prev_char = ' ';
                i += 1;
                continue;
            }

            // Handle braces and brackets
            match ch {
                '{' => {
                    result.push(ch);
                    result.push('\n');
                    indent_level += 1;
                    result.push_str(&self.indent_str(indent_level));
                    line_length = indent_level * self.config.indent_width;
                }

                '}' => {
                    if !result.ends_with('\n') && !result.ends_with(' ') {
                        result.push('\n');
                    }
                    indent_level = indent_level.saturating_sub(1);
                    result.push_str(&self.indent_str(indent_level));
                    result.push(ch);
                    line_length = indent_level * self.config.indent_width + 1;
                }

                ';' => {
                    result.push(ch);
                    result.push('\n');
                    result.push_str(&self.indent_str(indent_level));
                    line_length = indent_level * self.config.indent_width;
                }

                ',' => {
                    result.push(ch);
                    result.push(' ');
                    line_length += 2;
                }

                '(' | '[' => {
                    result.push(ch);
                    line_length += 1;
                }

                ')' | ']' => {
                    result.push(ch);
                    line_length += 1;
                }

                ':' => {
                    result.push(ch);
                    result.push(' ');
                    line_length += 2;
                }

                _ => {
                    result.push(ch);
                    line_length += 1;
                }
            }

            prev_char = ch;
            i += 1;
        }

        // Clean up trailing whitespace
        while result.ends_with('\n') || result.ends_with(' ') {
            if result.ends_with('\n') {
                break;
            }
            result.pop();
        }

        Ok(result)
    }

    /// Minify code (remove whitespace, comments)
    pub fn minify(&self, code: &str) -> GeneratorResult<String> {
        debug!("Minifying code ({} chars)", code.len());

        let mut result = String::new();
        let mut in_string = false;
        let mut string_char = '"';
        let mut prev_was_space = false;

        for (i, ch) in code.chars().enumerate() {
            // Track string boundaries
            if (ch == '"' || ch == '\'' || ch == '`') && (i == 0 || code.chars().nth(i - 1) != Some('\\')) {
                if !in_string {
                    in_string = true;
                    string_char = ch;
                } else if ch == string_char {
                    in_string = false;
                }
            }

            if in_string {
                result.push(ch);
                prev_was_space = false;
                continue;
            }

            // Remove non-essential whitespace
            if ch.is_whitespace() {
                if !prev_was_space
                    && !result.ends_with('(')
                    && !result.ends_with('{')
                    && !result.ends_with('[')
                    && !result.ends_with(',')
                {
                    result.push(' ');
                    prev_was_space = true;
                }
                continue;
            }

            // Remove comments
            if ch == '/' {
                if let Some(next) = code.chars().nth(i + 1) {
                    if next == '/' {
                        // Line comment - skip to end of line
                        break;
                    } else if next == '*' {
                        // Block comment - skip to */
                        let rest = &code[i + 2..];
                        if let Some(end) = rest.find("*/") {
                            // Skip past the comment
                            continue;
                        }
                    }
                }
            }

            result.push(ch);
            prev_was_space = false;
        }

        Ok(result.trim().to_string())
    }

    fn indent_str(&self, level: usize) -> String {
        if self.config.use_tabs {
            "\t".repeat(level)
        } else {
            " ".repeat(level * self.config.indent_width)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_simple() {
        let formatter = CodeFormatter::default();
        let code = "var x = { a: 1, b: 2 };";
        let formatted = formatter.format(code).unwrap();
        assert!(formatted.contains("a: 1"));
    }

    #[test]
    fn test_minify_removes_whitespace() {
        let formatter = CodeFormatter::default();
        let code = "var  x  =  1 ;";
        let minified = formatter.minify(code).unwrap();
        assert_eq!(minified, "var x = 1 ;");
    }

    #[test]
    fn test_preserve_strings() {
        let formatter = CodeFormatter::default();
        let code = r#"var x = "hello world";"#;
        let formatted = formatter.format(code).unwrap();
        assert!(formatted.contains("hello world"));
    }
}