dioxus_style_macro 0.5.2

Procedural macros for dioxus_style with SCSS/SASS compilation support - internal use only
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Procedural macro implementations for scoped styling with SCSS support.
//! PRODUCTION-READY: Handles all path edge cases correctly and maximizes code reuse.
//! UPDATED: Preserves function attributes (doc comments, etc.) and avoids duplicate #[component].

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr, ItemFn, Ident, Token, parse::{Parse, ParseStream}};
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};
use crate::class_extractor::extract_class_names;
use crate::css_constants::looks_like_scss;
use crate::codegen_utils::{generate_class_constant, generate_namespace_module, generate_include_quote};


/// Result of processing a style (file or inline)
pub struct ProcessedStyle {
    pub scope_hash: String,
    pub scoped_css: String,
    pub class_constants: Vec<proc_macro2::TokenStream>,
    pub include_path: Option<String>,
}

/// Main reusable function to process CSS/SCSS
pub fn resolve_and_process_style(input_str: &str, span: proc_macro2::Span) -> syn::Result<ProcessedStyle> {
    // 1. Resolve content (File or Inline)
    let is_likely_path = is_likely_file_path(input_str);
    
    let (css_content, absolute_path_opt) = if is_likely_path {
        match find_style_file(input_str) {
            Ok((path, content)) => (content, Some(path)),
            Err(e) => return Err(syn::Error::new(span, e)),
        }
    } else {
        (input_str.to_string(), None)
    };

    // 2. Compile SCSS if needed
    let is_scss = if let Some(_) = absolute_path_opt {
        is_scss_file(input_str)
    } else {
        looks_like_scss(&css_content)
    };

    let compiled_css = if is_scss {
        let minify = cfg!(not(debug_assertions));
        let path_arg = if absolute_path_opt.is_some() { Some(input_str) } else { None };
        
        match compile_scss_to_css(&css_content, path_arg, minify) {
            Ok(css) => css,
            Err(e) => return Err(syn::Error::new(span, e)),
        }
    } else {
        css_content
    };

    // 3. Generate Hash & Scope
    let path_arg_for_hash = if absolute_path_opt.is_some() { Some(input_str) } else { None };
    let scope_hash = generate_hash(&compiled_css, path_arg_for_hash);
    
    let minify = cfg!(not(debug_assertions));
    let scoped_css = parse_and_scope(&compiled_css, &scope_hash, minify);

    // 4. Extract Classes and generate constants using shared utility
    let selector_infos = extract_class_names(&compiled_css);
    let class_constants: Vec<_> = selector_infos
        .iter()
        .map(|selector_info| generate_class_constant(selector_info, &scope_hash))
        .collect();

    // 5. Prepare include path
    let include_path = if let Some(path) = absolute_path_opt {
        match path_to_include_str_format(&path) {
            Ok(p) => Some(p),
            Err(e) => return Err(syn::Error::new(span, e)),
        }
    } else {
        None
    };

    Ok(ProcessedStyle {
        scope_hash,
        scoped_css,
        class_constants,
        include_path,
    })
}

// ============================================
// HELPER STRUCTS FOR CODE REUSABILITY
// ============================================

/// Extracted function metadata to avoid duplication across macros
struct FunctionMetadata<'a> {
    name: &'a Ident,
    inputs: &'a syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
    output: &'a syn::ReturnType,
    vis: &'a syn::Visibility,
    body: &'a syn::Block,
    component_args: Option<proc_macro2::TokenStream>,
    other_attrs: Vec<&'a syn::Attribute>,
}

impl<'a> FunctionMetadata<'a> {
    /// Extract metadata from a function, handling #[component] attribute specially
    fn from_item_fn(func: &'a ItemFn) -> Self {
        let mut component_args = None;
        let mut other_attrs = Vec::new();

        for attr in &func.attrs {
            if attr.path().is_ident("component") {
                // Store arguments if present
                component_args = Some(if let syn::Meta::List(meta) = &attr.meta {
                    meta.tokens.clone()
                } else {
                    proc_macro2::TokenStream::new()
                });
            } else {
                other_attrs.push(attr);
            }
        }

        Self {
            name: &func.sig.ident,
            inputs: &func.sig.inputs,
            output: &func.sig.output,
            vis: &func.vis,
            body: &func.block,
            component_args,
            other_attrs,
        }
    }

    /// Validate that function returns Element
    fn validate_element_return(&self) -> Result<(), proc_macro2::TokenStream> {
        let has_element_return = match self.output {
            syn::ReturnType::Type(_, ty) => {
                if let syn::Type::Path(type_path) = ty.as_ref() {
                    type_path.path.segments.last()
                        .map(|seg| seg.ident == "Element")
                        .unwrap_or(false)
                } else {
                    false
                }
            }
            _ => false,
        };

        if !has_element_return {
            return Err(syn::Error::new_spanned(
                self.output,
                "Functions with CSS must return Element"
            ).to_compile_error());
        }

        Ok(())
    }

    /// Generate #[component] attribute with preserved arguments
    fn component_attribute(&self) -> proc_macro2::TokenStream {
        if let Some(ref args) = self.component_args {
            if args.is_empty() {
                quote! { #[::dioxus::prelude::component] }
            } else {
                quote! { #[::dioxus::prelude::component(#args)] }
            }
        } else {
            quote! { #[::dioxus::prelude::component] }
        }
    }
}

// Helper functions moved to codegen_utils module for better reusability

// ============================================
// MACRO IMPLEMENTATIONS
// ============================================

pub struct WithCssArgs {
    pub namespace: Ident,
    pub _comma: Token![,],
    pub css_file: LitStr,
}

impl Parse for WithCssArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(WithCssArgs {
            namespace: input.parse()?,
            _comma: input.parse()?,
            css_file: input.parse()?,
        })
    }
}

pub fn with_css_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as WithCssArgs);
    let namespace_name = args.namespace;
    let css_file_lit = args.css_file;
    
    let func = parse_macro_input!(item as ItemFn);
    let meta = FunctionMetadata::from_item_fn(&func);
    
    // Validate return type
    if let Err(e) = meta.validate_element_return() {
        return e.into();
    }

    // Process style
    let processed = match resolve_and_process_style(&css_file_lit.value(), css_file_lit.span()) {
        Ok(p) => p,
        Err(e) => return e.to_compile_error().into()
    };
    
    let scope_hash = processed.scope_hash;
    let scoped_css = processed.scoped_css;
    let class_constants = processed.class_constants;
    let include_quote = generate_include_quote(processed.include_path);

    // Generate namespace module
    let namespace_module = generate_namespace_module(
        &namespace_name,
        &scope_hash,
        &scoped_css,
        &class_constants,
        &include_quote,
    );

    let component_attr = meta.component_attribute();
    let other_attrs = &meta.other_attrs;
    let fn_name = meta.name;
    let fn_inputs = meta.inputs;
    let fn_output = meta.output;
    let fn_vis = meta.vis;
    let fn_body = meta.body;

    let expanded = quote! {
        #component_attr
        #(#other_attrs)*
        #fn_vis fn #fn_name(#fn_inputs) #fn_output {
            use ::dioxus::prelude::*;

            #namespace_module

            let _ = #namespace_name::get_scope();
            let user_element = { #fn_body };

            rsx! {
                style { dangerous_inner_html: "{::dioxus_style::inject_styles()}" }
                {user_element}
            }
        }
    };

    TokenStream::from(expanded)
}

/// Input for component_with_css! macro
/// Now supports multiple CSS/SCSS files with different namespaces
pub struct ComponentInput {
    pub style_files: Vec<(Ident, LitStr)>, // Vector of (namespace, file_path) pairs
    pub func: ItemFn,
}

impl Parse for ComponentInput {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut style_files = Vec::new();
        
        // Parse multiple namespace: "path" pairs
        while !input.peek(Token![fn]) {
            let namespace: Ident = input.parse()?;
            let _: Token![:] = input.parse()?;
            let css_path: LitStr = input.parse()?;
            
            style_files.push((namespace, css_path));
            
            // Consume optional comma
            if input.peek(Token![,]) {
                let _: Token![,] = input.parse()?;
            } else {
                break; // No comma means next should be function
            }
        }
        
        // Parse the function definition
        let func: ItemFn = input.parse()?;
        
        if style_files.is_empty() {
            return Err(syn::Error::new(input.span(), "Expected at least one namespace:path pair before function"));
        }
        
        Ok(ComponentInput { style_files, func })
    }
}

pub fn component_with_css_impl(input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(input as ComponentInput);
    let style_files = args.style_files;
    let func = args.func;

    let meta = FunctionMetadata::from_item_fn(&func);
    
    // Validate return type
    if let Err(e) = meta.validate_element_return() {
        return e.into();
    }

    // Process each style file and generate namespace modules
    let mut namespace_modules = Vec::new();
    let mut namespace_inits = Vec::new();
    
    for (namespace_name, css_file_lit) in style_files {
        let processed = match resolve_and_process_style(&css_file_lit.value(), css_file_lit.span()) {
            Ok(p) => p,
            Err(e) => return e.to_compile_error().into()
        };
        
        let include_quote = generate_include_quote(processed.include_path);

        // Generate namespace module for this CSS file
        let namespace_module = generate_namespace_module(
            &namespace_name,
            &processed.scope_hash,
            &processed.scoped_css,
            &processed.class_constants,
            &include_quote,
        );
        
        namespace_modules.push(namespace_module);
        
        // Generate initialization call for runtime style injection
        namespace_inits.push(quote! {
            let _ = #namespace_name::get_scope();
        });
    }

    let component_attr = meta.component_attribute();
    let other_attrs = &meta.other_attrs;
    let fn_name = meta.name;
    let fn_inputs = meta.inputs;
    let fn_output = meta.output;
    let fn_vis = meta.vis;
    let fn_body = meta.body;

    let expanded = quote! {
        #component_attr
        #(#other_attrs)*
        #fn_vis fn #fn_name(#fn_inputs) #fn_output {
            use ::dioxus::prelude::*;

            // Generate all namespace modules
            #(#namespace_modules)*

            // Initialize all styles for runtime injection
            #(#namespace_inits)*
            
            let user_element = { #fn_body };

            rsx! {
                style { dangerous_inner_html: "{::dioxus_style::inject_styles()}" }
                {user_element}
            }
        }
    };

    TokenStream::from(expanded)
}

pub fn scoped_style_impl(input: TokenStream) -> TokenStream {
    enum StyleInput {
        Anonymous(LitStr),
        Named(Ident, LitStr),
    }

    impl Parse for StyleInput {
        fn parse(input: ParseStream) -> syn::Result<Self> {
            if input.peek(Ident) && input.peek2(Token![,]) {
                let name: Ident = input.parse()?;
                let _: Token![,] = input.parse()?;
                let path: LitStr = input.parse()?;
                Ok(StyleInput::Named(name, path))
            } else {
                Ok(StyleInput::Anonymous(input.parse()?))
            }
        }
    }

    let parsed_input = parse_macro_input!(input as StyleInput);
    
    let (namespace, css_lit) = match parsed_input {
        StyleInput::Anonymous(lit) => (None, lit),
        StyleInput::Named(ident, lit) => (Some(ident), lit),
    };

    let processed = match resolve_and_process_style(&css_lit.value(), css_lit.span()) {
        Ok(p) => p,
        Err(e) => return e.to_compile_error().into()
    };

    let scope_hash = processed.scope_hash;
    let scoped_css = processed.scoped_css;
    let class_constants = processed.class_constants;
    let include_quote = generate_include_quote(processed.include_path);

    if let Some(mod_name) = namespace {
        // Named: Generate Module
        let namespace_module = generate_namespace_module(
            &mod_name,
            &scope_hash,
            &scoped_css,
            &class_constants,
            &include_quote,
        );
        
        let expanded = quote! {
            #namespace_module
            // Ensure style is registered
            let _ = #mod_name::get_scope();
        };
        TokenStream::from(expanded)
    } else {
        // Anonymous: Return ScopedStyle expression
        let expanded = quote! {
            {
                use ::std::sync::OnceLock;
                static STYLE_INSTANCE: OnceLock<::dioxus_style::ScopedStyle> = OnceLock::new();
                
                *STYLE_INSTANCE.get_or_init(|| {
                    #include_quote
                    ::dioxus_style::ScopedStyle::new(#scope_hash, #scoped_css)
                })
            }
        };
        TokenStream::from(expanded)
    }
}

// ============================================
// HELPER FUNCTIONS (Preserved/Moved)
// ============================================

pub 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)
}

pub 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.\nSearched in:\n{}\n",
        file_path, tried_paths
    ))
}

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

// looks_like_scss and has_nesting have been moved to shared utility modules