dioxus_style_macro 0.4.2

Procedural macros for dioxus_style with SCSS/SASS compilation support - internal use only
Documentation
//! Procedural macro implementations for scoped styling with SCSS support.
//! PRODUCTION-READY: Handles all path edge cases correctly

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr};
use std::path::{Path, PathBuf};
use std::env;

use crate::hash::generate_hash;
use crate::style_parser::parse_and_scope;
use crate::scss_compiler::{compile_scss_to_css, is_scss_file};

/// Converts path to a format safe for include_str!
/// Handles Windows paths, spaces, and non-UTF8 correctly
fn path_to_include_str_format(path: &Path) -> Result<String, String> {
    // Canonicalize to get absolute path and resolve symlinks
    let canonical = path.canonicalize()
        .map_err(|e| format!("Failed to canonicalize path '{}': {}", path.display(), e))?;
    
    // Convert to string, handling non-UTF8
    let path_str = canonical.to_str()
        .ok_or_else(|| format!("Path contains invalid UTF-8: {}", canonical.display()))?;
    
    // Fix Windows backslashes: C:\path\to\file -> C:/path/to/file
    // include_str! accepts both, but forward slashes are universal
    let normalized = if cfg!(windows) {
        path_str.replace('\\', "/")
    } else {
        path_str.to_string()
    };
    
    Ok(normalized)
}

/// Simple file resolution using CARGO_MANIFEST_DIR
/// Returns (absolute_canonical_path, file_content)
fn find_style_file(file_path: &str) -> Result<(PathBuf, String), String> {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR")
        .map_err(|_| "CARGO_MANIFEST_DIR not set (not running in cargo context)".to_string())?;
    
    let base = PathBuf::from(&manifest_dir);
    
    // Search locations in priority order
    let candidates = vec![
        base.join(file_path),                    // project_root/button.scss
        base.join("src").join(file_path),        // project_root/src/button.scss
        base.join("styles").join(file_path),     // project_root/styles/button.scss
        base.join("assets").join(file_path),     // project_root/assets/button.scss
        base.join("src/styles").join(file_path), // project_root/src/styles/button.scss
        base.join("src/assets").join(file_path), // project_root/src/assets/button.scss
    ];
    
    // Try each candidate
    for path in &candidates {
        if path.exists() && path.is_file() {
            let content = std::fs::read_to_string(path)
                .map_err(|e| format!("Failed to read '{}': {}", path.display(), e))?;
            
            // Return canonicalized absolute path
            return Ok((path.clone(), content));
        }
    }
    
    // Generate helpful error message
    let tried_paths = candidates.iter()
        .map(|p| format!("  ✗ {}", p.display()))
        .collect::<Vec<_>>()
        .join("\n");
    
    Err(format!(
        "Style file '{}' not found.\n\nSearched in:\n{}\n\n\
        💡 Tip: Place your style files in:\n\
        - src/{}  (recommended)\n\
        - styles/{}\n\
        - {}\n\n\
        Current directory: {}",
        file_path,
        tried_paths,
        file_path,
        file_path,
        file_path,
        manifest_dir
    ))
}

/// Implementation of the `scoped_style!` macro with SCSS support.
pub fn scoped_style_impl(input: TokenStream) -> TokenStream {
    let input_str = parse_macro_input!(input as LitStr);
    let css_content = input_str.value();

    // Check if it's a file path
    if is_likely_file_path(&css_content) {
        // Find the file and get absolute path
        let (absolute_path, raw_content) = match find_style_file(&css_content) {
            Ok(result) => result,
            Err(e) => {
                return syn::Error::new(input_str.span(), e)
                    .to_compile_error()
                    .into();
            }
        };

        // Compile SCSS if needed
        let css_content = if is_scss_file(&css_content) {
            let minify = cfg!(not(debug_assertions));
            match compile_scss_to_css(&raw_content, Some(&css_content), minify) {
                Ok(css) => css,
                Err(e) => {
                    return syn::Error::new(input_str.span(), e)
                        .to_compile_error()
                        .into();
                }
            }
        } else {
            raw_content
        };

        // Generate hash
        let scope_lit = generate_hash(&css_content, Some(&css_content));
        
        // Scope the CSS
        let minify = cfg!(not(debug_assertions));
        let scoped = parse_and_scope(&css_content, &scope_lit, minify);
        let scoped_css = scoped.scoped;

        // FIXED: Convert path to include_str! safe format
        let include_path = match path_to_include_str_format(&absolute_path) {
            Ok(p) => p,
            Err(e) => {
                return syn::Error::new(input_str.span(), e)
                    .to_compile_error()
                    .into();
            }
        };

        // Generate code with properly formatted path
        let expanded = quote! {
            {
                use ::std::sync::OnceLock;
                static STYLE_INSTANCE: OnceLock<::dioxus_style::ScopedStyle> = OnceLock::new();
                
                *STYLE_INSTANCE.get_or_init(|| {
                    // Use normalized absolute path - works on Windows and Unix
                    let _css_tracker = include_str!(#include_path);
                    ::dioxus_style::ScopedStyle::new(#scope_lit, #scoped_css)
                })
            }
        };

        TokenStream::from(expanded)
    } else {
        // Inline CSS/SCSS
        let css_content = if looks_like_scss(&css_content) {
            let minify = cfg!(not(debug_assertions));
            match compile_scss_to_css(&css_content, None, minify) {
                Ok(css) => css,
                Err(e) => {
                    return syn::Error::new(input_str.span(), e)
                        .to_compile_error()
                        .into();
                }
            }
        } else {
            css_content
        };

        let scope = generate_hash(&css_content, None);
        let minify = cfg!(not(debug_assertions));
        let scoped = parse_and_scope(&css_content, &scope, minify);
        let scoped_css = scoped.scoped;

        let expanded = quote! {
            {
                use ::std::sync::OnceLock;
                static STYLE_INSTANCE: OnceLock<::dioxus_style::ScopedStyle> = OnceLock::new();
                
                *STYLE_INSTANCE.get_or_init(|| {
                    ::dioxus_style::ScopedStyle::new(#scope, #scoped_css)
                })
            }
        };

        TokenStream::from(expanded)
    }
}

/// Implementation of the `css!` macro for inline styles.
pub fn css_impl(input: TokenStream) -> TokenStream {
    let input_str = parse_macro_input!(input as LitStr);
    let css_content = input_str.value();

    let scope = generate_hash(&css_content, None);
    let class_name = format!("{}_inline", scope);
    let wrapped_css = format!(".{} {{ {} }}", class_name, css_content);

    let minify = cfg!(not(debug_assertions));
    let scoped = crate::style_parser::parse_and_scope(&wrapped_css, &scope, minify);
    let final_css = scoped.scoped;

    let expanded = quote! {
        {
            use ::std::sync::OnceLock;
            static STYLE_INSTANCE: OnceLock<::dioxus_style::ScopedStyle> = OnceLock::new();
            
            *STYLE_INSTANCE.get_or_init(|| {
                ::dioxus_style::ScopedStyle::new(#scope, #final_css)
            })
        }
    };

    TokenStream::from(expanded)
}

fn is_likely_file_path(s: &str) -> bool {
    s.ends_with(".css") || s.ends_with(".scss") || s.ends_with(".sass") 
        || s.contains('/') || s.contains('\\')
}

fn looks_like_scss(content: &str) -> bool {
    content.contains('$') || content.contains("@mixin") || 
    content.contains("@include") || content.contains("@import") ||
    content.contains("@use") || content.contains("@extend") ||
    content.contains('&') || has_nesting(content)
}

fn has_nesting(content: &str) -> bool {
    let mut brace_depth: u32 = 0;
    let mut chars = content.chars().peekable();
    
    while let Some(ch) = chars.next() {
        match ch {
            '{' => {
                brace_depth += 1;
                if brace_depth > 1 { return true; }
            }
            '}' => brace_depth = brace_depth.saturating_sub(1),
            '"' | '\'' => {
                let quote = ch;
                while let Some(c) = chars.next() {
                    if c == quote { break; }
                    if c == '\\' { chars.next(); }
                }
            }
            '/' if chars.peek() == Some(&'*') => {
                chars.next();
                while let Some(c) = chars.next() {
                    if c == '*' && chars.peek() == Some(&'/') {
                        chars.next();
                        break;
                    }
                }
            }
            _ => {}
        }
    }
    false
}

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

    #[test]
    fn test_path_normalization() {
        // Test Windows path conversion
        #[cfg(windows)]
        {
            let path = PathBuf::from(r"C:\Users\Test\project\button.scss");
            if let Ok(normalized) = path_to_include_str_format(&path) {
                assert!(!normalized.contains('\\'));
                assert!(normalized.contains('/'));
            }
        }
    }

    #[test]
    fn test_is_likely_file_path() {
        assert!(is_likely_file_path("button.css"));
        assert!(is_likely_file_path("button.scss"));
        assert!(is_likely_file_path("styles/button.css"));
        assert!(is_likely_file_path("src\\button.scss")); // Windows path
        assert!(!is_likely_file_path(".button { color: red; }"));
    }

    #[test]
    fn test_looks_like_scss() {
        assert!(looks_like_scss("$primary: blue;"));
        assert!(looks_like_scss("@mixin flex { }"));
        assert!(looks_like_scss(".parent { .child { } }"));
        assert!(!looks_like_scss(".button { color: red; }"));
    }
}