dioxus_style_macro 0.5.3

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
//! CSS parsing and scoping utilities.
//!
//! Transforms CSS selectors by adding a unique scope prefix to prevent conflicts.

/// Parses and scopes CSS content with a unique prefix.
pub fn parse_and_scope(css: &str, scope: &str, minify: bool) -> String {
    // Pre-allocate with estimate
    let mut scoped_css = String::with_capacity(css.len() + scope.len() * 10);

    let rules = parse_css_rules(css);

    for rule in rules {
        if let Some(scoped_rule) = scope_rule(&rule, scope) {
            scoped_css.push_str(&scoped_rule);
            if !minify {
                scoped_css.push('\n');
            }
        }
    }

    if minify {
        scoped_css = minify_css(&scoped_css);
    }

    scoped_css
}

/// Parses CSS into individual rules using a state machine approach.
#[inline]
fn parse_css_rules(css: &str) -> Vec<String> {
    let mut rules = Vec::with_capacity(16);
    let mut current_rule = String::with_capacity(128);
    let mut brace_count = 0;
    let mut chars = css.chars().peekable();

    while let Some(ch) = chars.next() {
        // Fast path: skip comments
        if ch == '/' && chars.peek() == Some(&'*') {
            chars.next(); // consume '*'
                          // Skip until end of comment
            while let Some(ch) = chars.next() {
                if ch == '*' && chars.peek() == Some(&'/') {
                    chars.next(); // consume '/'
                    break;
                }
            }
            continue;
        }

        current_rule.push(ch);

        match ch {
            '{' => brace_count += 1,
            '}' => {
                brace_count -= 1;

                if brace_count == 0 {
                    let trimmed = current_rule.trim();
                    if !trimmed.is_empty() {
                        rules.push(trimmed.to_string());
                    }
                    current_rule.clear();
                }
            }
            _ => {}
        }
    }

    rules
}

/// Scopes a single CSS rule by prefixing selectors.
/// Handles at-rules (@keyframes, @media, etc.) specially.
#[inline]
fn scope_rule(rule: &str, scope: &str) -> Option<String> {
    let trimmed = rule.trim();
    if trimmed.is_empty() {
        return None;
    }

    // Handle at-rules (they start with @)
    if trimmed.starts_with('@') {
        return handle_at_rule(trimmed, scope);
    }

    // Find the opening brace
    let brace_pos = trimmed.find('{')?;

    let selector = trimmed[..brace_pos].trim();
    let rest = &trimmed[brace_pos + 1..];

    // Remove closing brace
    let declarations = if let Some(pos) = rest.rfind('}') {
        rest[..pos].trim()
    } else {
        rest.trim()
    };

    let scoped_selector = scope_selector(selector, scope);

    Some(format!("{} {{ {} }}", scoped_selector, declarations))
}

/// Handles CSS at-rules like @keyframes, @media, @supports, @font-face.
#[inline]
fn handle_at_rule(rule: &str, scope: &str) -> Option<String> {
    // Extract the at-rule name
    let at_end = rule[1..].find(|c: char| c.is_whitespace() || c == '{')
        .map(|i| i + 1)
        .unwrap_or(rule.len());
    let at_name = &rule[1..at_end].to_lowercase();
    
    match at_name.as_str() {
        // These at-rules should NOT be scoped - pass through unchanged
        "keyframes" | "-webkit-keyframes" | "-moz-keyframes" | "font-face" => {
            Some(rule.to_string())
        }
        
        // These at-rules contain nested rules that SHOULD be scoped
        "media" | "supports" | "layer" | "container" => {
            // Find the opening brace
            if let Some(brace_pos) = rule.find('{') {
                let condition = &rule[..brace_pos + 1]; // Keep "@media (...) {"
                let rest = &rule[brace_pos + 1..];
                
                // Find matching closing brace
                if let Some(close_pos) = rest.rfind('}') {
                    let inner_css = &rest[..close_pos];
                    
                    // Parse and scope the inner CSS rules
                    let inner_rules = parse_css_rules(inner_css);
                    let mut scoped_inner = String::with_capacity(inner_css.len());
                    
                    for inner_rule in inner_rules {
                        if let Some(scoped) = scope_rule(&inner_rule, scope) {
                            scoped_inner.push_str(&scoped);
                            scoped_inner.push(' ');
                        }
                    }
                    
                    return Some(format!("{} {} }}", condition, scoped_inner.trim()));
                }
            }
            Some(rule.to_string()) // Fallback: return unchanged
        }
        
        // Unknown at-rules: pass through unchanged
        _ => Some(rule.to_string())
    }
}

/// Scopes a CSS selector by adding the unique prefix.
#[inline]
fn scope_selector(selector: &str, scope: &str) -> String {
    if !selector.contains(',') {
        // Fast path: single selector
        return scope_single_selector(selector, scope);
    }

    // Handle multiple selectors (comma-separated)
    // Pre-allocate based on comma count for efficiency
    let _estimated_count = selector.matches(',').count() + 1;
    let selectors: Vec<_> = selector
        .split(',')
        .map(|s| scope_single_selector(s.trim(), scope))
        .collect();
    
    selectors.join(", ")
}

/// Scopes a single selector (no commas).
/// Scopes: classes (.class), IDs (#id), and elements (div, span, etc.)
/// Also handles functional pseudo-classes like :not(), :has(), :is(), :where()
#[inline]
fn scope_single_selector(selector: &str, scope: &str) -> String {
    let mut result = String::with_capacity(selector.len() + scope.len() * 4);
    let mut chars = selector.chars().peekable();
    let mut at_start = true; // Track if we're at the start of a selector component

    while let Some(ch) = chars.next() {
        match ch {
            // Handle class selectors: .class → .scope_class
            '.' => {
                let mut class_name = String::with_capacity(16);
                while let Some(&next_ch) = chars.peek() {
                    if next_ch.is_alphanumeric() || next_ch == '-' || next_ch == '_' {
                        class_name.push(next_ch);
                        chars.next();
                    } else {
                        break;
                    }
                }

                if !class_name.is_empty() {
                    result.push('.');
                    result.push_str(scope);
                    result.push('_');
                    result.push_str(&class_name);
                } else {
                    // Bug #1 fix: Preserve malformed empty class selector
                    result.push('.');
                }
                at_start = false;
            }

            // Handle ID selectors: #id → #id (NO SCOPING - IDs are globally unique)
            '#' => {
                let mut id_name = String::with_capacity(16);
                while let Some(&next_ch) = chars.peek() {
                    if next_ch.is_alphanumeric() || next_ch == '-' || next_ch == '_' {
                        id_name.push(next_ch);
                        chars.next();
                    } else {
                        break;
                    }
                }

                if !id_name.is_empty() {
                    // CHANGED: Do NOT scope IDs - keep them as-is
                    result.push('#');
                    result.push_str(&id_name);
                } else {
                    // Preserve malformed empty ID selector
                    result.push('#');
                }
                at_start = false;
            }

            // Handle combinators: reset the "at_start" flag
            ' ' | '>' | '+' | '~' => {
                result.push(ch);
                // Skip extra whitespace
                while let Some(&next_ch) = chars.peek() {
                    if next_ch == ' ' {
                        chars.next();
                    } else {
                        break;
                    }
                }
                at_start = true; // Next token is a new selector component
            }

            // Handle pseudo-classes and pseudo-elements
            ':' => {
                result.push(ch);
                
                // Collect pseudo-class/element name
                let mut pseudo_name = String::new();
                
                // Check for :: (pseudo-element)
                if chars.peek() == Some(&':') {
                    result.push(chars.next().unwrap());
                }
                
                // Collect the pseudo name
                while let Some(&next_ch) = chars.peek() {
                    if next_ch.is_alphanumeric() || next_ch == '-' {
                        pseudo_name.push(next_ch);
                        result.push(next_ch);
                        chars.next();
                    } else {
                        break;
                    }
                }
                
                // Bug #2 fix: Handle functional pseudo-classes that need scoping
                // :not(), :has(), :is(), :where() contain selectors that should be scoped
                // Optimization #2: Use eq_ignore_ascii_case to avoid allocation
                let is_functional = ["not", "has", "is", "where", "matches"]
                    .iter()
                    .any(|&p| pseudo_name.eq_ignore_ascii_case(p));
                if is_functional {
                    if chars.peek() == Some(&'(') {
                        result.push(chars.next().unwrap()); // Push '('
                        
                        // Collect content inside parentheses
                        let mut inner_content = String::new();
                        let mut paren_depth = 1;
                        
                        while let Some(c) = chars.next() {
                            match c {
                                '(' => {
                                    paren_depth += 1;
                                    inner_content.push(c);
                                }
                                ')' => {
                                    paren_depth -= 1;
                                    if paren_depth == 0 {
                                        break;
                                    }
                                    inner_content.push(c);
                                }
                                _ => inner_content.push(c),
                            }
                        }
                        
                        // Recursively scope the inner selector(s)
                        let scoped_inner = scope_selector(&inner_content, scope);
                        result.push_str(&scoped_inner);
                        result.push(')');
                    }
                }
                
                at_start = false;
            }

            // Handle attribute selectors with proper quote handling (Bug #3 fix)
            '[' => {
                result.push(ch);
                let mut in_quote: Option<char> = None;
                
                while let Some(next_ch) = chars.next() {
                    result.push(next_ch);
                    
                    match next_ch {
                        '"' | '\'' => {
                            if let Some(quote_char) = in_quote {
                                if quote_char == next_ch {
                                    in_quote = None; // Closing quote
                                }
                            } else {
                                in_quote = Some(next_ch); // Opening quote
                            }
                        }
                        '\\' => {
                            // Handle escape sequences inside quotes
                            if in_quote.is_some() {
                                if let Some(escaped) = chars.next() {
                                    result.push(escaped);
                                }
                            }
                        }
                        ']' => {
                            if in_quote.is_none() {
                                break; // Only break on ] if not inside quotes
                            }
                        }
                        _ => {}
                    }
                }
                at_start = false;
            }

            // Handle universal selector: * (do NOT scope - it's already global)
            '*' => {
                result.push(ch);
                at_start = false;
            }

            // Handle element selectors: div → div[data-scope="scope"]
            ch if ch.is_alphabetic() && at_start => {
                let mut element_name = String::from(ch);
                
                // Collect full element name
                while let Some(&next_ch) = chars.peek() {
                    if next_ch.is_alphanumeric() || next_ch == '-' {
                        element_name.push(next_ch);
                        chars.next();
                    } else {
                        break;
                    }
                }

                // Bug #4 fix: Don't scope :root or :host elements (they're global)
                // Note: These are pseudo-classes, not elements, but we handle edge cases
                if element_name == "root" || element_name == "host" {
                    result.push_str(&element_name);
                } else {
                    // Scope the element with data attribute
                    result.push_str(&element_name);
                    result.push_str("[data-scope=\"");
                    result.push_str(scope);
                    result.push_str("\"]");
                }
                
                at_start = false;
            }

            // Default: pass through
            _ => {
                result.push(ch);
                at_start = false;
            }
        }
    }

    result
}

/// Minifies CSS by removing whitespace and comments.
#[inline]
fn minify_css(css: &str) -> String {
    let mut result = String::with_capacity(css.len() / 2);
    let mut chars = css.chars().peekable();
    let mut last_was_space = false;

    while let Some(ch) = chars.next() {
        // Skip comments
        if ch == '/' && chars.peek() == Some(&'*') {
            chars.next();
            while let Some(ch) = chars.next() {
                if ch == '*' && chars.peek() == Some(&'/') {
                    chars.next();
                    break;
                }
            }
            continue;
        }

        if ch.is_whitespace() {
            if !last_was_space && !result.is_empty() {
                if let Some(last_ch) = result.chars().last() {
                    if !matches!(last_ch, '{' | '}' | ':' | ';' | ',') {
                        result.push(' ');
                        last_was_space = true;
                    }
                }
            }
        } else {
            result.push(ch);
            last_was_space = false;
        }
    }

    result.shrink_to_fit();
    result
}