iris-cssom 1.1.4

Iris CSS Object Model (CSSOM) implementation: CSS parsing, style computation, CSS Modules, and Web API
Documentation
//! CSS parser: convert CSS string → StyleSheet.
//!
//! Uses simple string-based parsing (no cssparser dependency at parse time)
//! for broad compatibility across cssparser 0.33+ API changes.

use crate::{CssRule, Declaration, StyleSheet};

/// Parse CSS string into StyleSheet (simple string-based parser).
pub fn parse_css(css: &str) -> Result<StyleSheet, String> {
    Ok(parse_css_simple(css))
}

/// Simple CSS parser — splits by `{` / `}` and `:` / `;`.
///
/// Handles:
/// - Multi-selector rules (`h1, h2 { ... }`)
/// - @rules (skipped)
/// - Nested at-rules like @media (skipped)
pub fn parse_css_simple(css: &str) -> StyleSheet {
    let mut sheet = StyleSheet::default();
    let mut remaining = css;

    while let Some(open_pos) = remaining.find('{') {
        let before = remaining[..open_pos].trim();
        remaining = &remaining[open_pos + 1..];

        // Find matching closing brace
        let close_pos = match find_matching_brace(remaining) {
            Some(p) => p,
            None => break,
        };

        let decl_str = remaining[..close_pos].trim();
        remaining = &remaining[close_pos + 1..];

        // Skip @rules
        if before.starts_with('@') {
            continue;
        }

        // Skip empty/whitespace selectors
        if before.is_empty() {
            continue;
        }

        let selectors: Vec<String> = before.split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        let declarations = parse_declarations(decl_str);

        if !selectors.is_empty() {
            sheet.rules.push(CssRule { selectors, declarations });
        }
    }

    sheet
}

/// Find the matching closing brace, handling nested braces.
fn find_matching_brace(s: &str) -> Option<usize> {
    let mut depth = 1i32;
    for (i, c) in s.char_indices() {
        match c {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 { return Some(i); }
            }
            _ => {}
        }
    }
    None
}

/// Parse CSS declarations from a "prop: val; prop: val" string.
fn parse_declarations(s: &str) -> Vec<Declaration> {
    let mut result = Vec::new();
    let mut remaining = s.trim();

    while !remaining.is_empty() {
        // Find next colon (property: value separator)
        let colon_pos = match remaining.find(':') {
            Some(p) => p,
            None => break,
        };

        let property = remaining[..colon_pos].trim().to_lowercase();
        remaining = remaining[colon_pos + 1..].trim_start();

        // Find semicolon or end of string
        let (value, rest) = if let Some(sc_pos) = remaining.find(';') {
            (remaining[..sc_pos].trim().to_string(), remaining[sc_pos + 1..].trim())
        } else {
            (remaining.trim().to_string(), "")
        };

        if !property.is_empty() {
            result.push(Declaration { property, value });
        }

        remaining = rest;
    }

    result
}

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

    #[test]
    fn test_parse_simple() {
        let sheet = parse_css_simple(".foo { color: red; font-size: 16px; } .bar { margin: 10px; }");
        assert_eq!(sheet.rules.len(), 2);
        assert_eq!(sheet.rules[0].selectors[0], ".foo");
        assert_eq!(sheet.rules[0].declarations[0].property, "color");
    }

    #[test]
    fn test_complex_selector() {
        let sheet = parse_css_simple("div.container > p.highlight { color: blue; }");
        assert_eq!(sheet.rules.len(), 1);
        assert_eq!(sheet.rules[0].declarations[0].value, "blue");
    }

    #[test]
    fn test_multiple_selectors() {
        let sheet = parse_css_simple("h1, h2, h3 { font-weight: bold; }");
        assert_eq!(sheet.rules[0].selectors.len(), 3);
    }

    #[test]
    fn test_at_rule_skipped() {
        let sheet = parse_css_simple("@media screen { .a { color: red; } } .b { color: blue; }");
        // @media is skipped as one block, .b should be parsed
        assert_eq!(sheet.rules.len(), 1);
        assert_eq!(sheet.rules[0].selectors[0], ".b");
    }

    #[test]
    fn test_stylesheet_compute() {
        let sheet = parse_css_simple(".btn { color: red; font-size: 14px; } .btn-primary { color: blue; }");
        let map = sheet.compute(&["btn".into(), "btn-primary".into()], "button");
        assert_eq!(map.get("color").unwrap(), "blue");
        assert_eq!(map.get("font-size").unwrap(), "14px");
    }

    #[test]
    fn test_empty_input() {
        let sheet = parse_css_simple("");
        assert_eq!(sheet.rules.len(), 0);
    }

    #[test]
    fn test_nested_braces() {
        let sheet = parse_css_simple(".a { x: 1; } .b { y: 2; }");
        assert_eq!(sheet.rules.len(), 2);
    }
}