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};
fn path_to_include_str_format(path: &Path) -> Result<String, String> {
let canonical = path.canonicalize()
.map_err(|e| format!("Failed to canonicalize path '{}': {}", path.display(), e))?;
let path_str = canonical.to_str()
.ok_or_else(|| format!("Path contains invalid UTF-8: {}", canonical.display()))?;
let normalized = if cfg!(windows) {
path_str.replace('\\', "/")
} else {
path_str.to_string()
};
Ok(normalized)
}
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);
let candidates = vec![
base.join(file_path), base.join("src").join(file_path), base.join("styles").join(file_path), base.join("assets").join(file_path), base.join("src/styles").join(file_path), base.join("src/assets").join(file_path), ];
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 Ok((path.clone(), content));
}
}
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
))
}
pub fn scoped_style_impl(input: TokenStream) -> TokenStream {
let input_str = parse_macro_input!(input as LitStr);
let css_content = input_str.value();
if is_likely_file_path(&css_content) {
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();
}
};
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
};
let scope_lit = generate_hash(&css_content, Some(&css_content));
let minify = cfg!(not(debug_assertions));
let scoped = parse_and_scope(&css_content, &scope_lit, minify);
let scoped_css = scoped.scoped;
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();
}
};
let expanded = quote! {
{
use ::std::sync::OnceLock;
static STYLE_INSTANCE: OnceLock<::dioxus_style::ScopedStyle> = OnceLock::new();
*STYLE_INSTANCE.get_or_init(|| {
let _css_tracker = include_str!(#include_path);
::dioxus_style::ScopedStyle::new(#scope_lit, #scoped_css)
})
}
};
TokenStream::from(expanded)
} else {
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)
}
}
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() {
#[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")); 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; }"));
}
}