dioxus_style 0.3.0

Scoped CSS/SCSS styling system for Dioxus components with compile-time processing and SCSS support
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
# dioxus_style


**Scoped CSS/SCSS styling for Dioxus components** - Write CSS or SCSS that's automatically scoped to your components, preventing style conflicts and maintaining clean, modular code.

[![Crates.io](https://img.shields.io/crates/v/dioxus_style.svg)](https://crates.io/crates/dioxus_style)
[![Documentation](https://docs.rs/dioxus_style/badge.svg)](https://docs.rs/dioxus_style)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](LICENSE)

## ✨ Features


- 🎨 **SCSS/SASS Support** - Variables, nesting, mixins, and all SCSS features (NEW in v0.3.0!)
- 🎯 **Automatic CSS Scoping** - Classes, IDs, and elements are automatically scoped
- 🏷️ **Element Scoping** - Element selectors (`div`, `span`) use data attributes for isolation
- 📦 **File or Inline Styles** - Load from `.css`/`.scss` files or write inline
-**Zero Runtime Overhead** - All processing happens at compile time
- 🔥 **Hot Reload Support** - CSS/SCSS changes are tracked via `include_str!`
- 🎨 **Multiple Macro Options** - Choose the syntax that fits your style
- 🚀 **Performance Optimized** - Fast hashing (xxHash), efficient parsing, and minification in release builds
- 💾 **Global Style Registry** - Automatic deduplication and insertion order preservation

## Quick Start


Add to your `Cargo.toml`:

```toml
[dependencies]
dioxus_style = "0.3.0"  # SCSS enabled by default

# Or explicitly enable SCSS

dioxus_style = { version = "0.3.0", features = ["scss"] }

# Or use without SCSS (smaller dependencies)

dioxus_style = { version = "0.3.0", default-features = false }
```

## 🆕 SCSS Support (v0.3.0+)


Write modern, maintainable styles with SCSS! All compilation happens at build time.

### SCSS Example


**button.scss:**
```scss
$primary-color: #3498db;
$padding: 10px 20px;

.btn {
    background: $primary-color;
    color: white;
    padding: $padding;
    border-radius: 5px;
    
    &:hover {
        background: darken($primary-color, 10%);
        transform: scale(1.05);
    }
    
    &:active {
        transform: scale(0.98);
    }
}
```

**Component:**
```rust
use dioxus::prelude::*;
use dioxus_style::with_css;

#[with_css("button.scss")]

fn Button() -> Element {
    rsx! {
        button { 
            "data-scope": "{css}",
            class: "{css}_btn", 
            "Click me!" 
        }
    }
}
```

### Inline SCSS


```rust
use dioxus_style::scoped_style;

fn Badge() -> Element {
    let css = scoped_style!("
        $danger: #e74c3c;
        
        .badge {
            background: $danger;
            color: white;
            padding: 4px 8px;
            
            &:hover {
                background: darken($danger, 10%);
            }
        }
    ");
    
    rsx! {
        span { 
            "data-scope": "{css}",
            class: "{css}_badge", 
            "New" 
        }
    }
}
```

## Usage Examples


### 1. Attribute Macro with Auto-Injection (Recommended)


The simplest way - styles are automatically injected:

```rust
use dioxus::prelude::*;
use dioxus_style::with_css;

#[with_css("button.css")]  // or "button.scss"

fn Button() -> Element {
    rsx! {
        button { 
            "data-scope": "{css}",
            class: "{css}_btn", 
            "Click me!" 
        }
    }
}
```

**button.css (or button.scss):**
```css
.btn {
    background: blue;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
}

.btn:hover {
    background: darkblue;
}

button {
    cursor: pointer;
    border: none;
}
```

### 2. Manual Style Management


For more control over when styles are injected:

```rust
use dioxus::prelude::*;
use dioxus_style::{scoped_style, inject_styles};

#[component]

fn Card() -> Element {
    let css = scoped_style!("card.scss");  // Supports both .css and .scss
    
    rsx! {
        style { dangerous_inner_html: "{inject_styles()}" }
        div { 
            "data-scope": "{css}",
            class: "{css}_card",
            h2 { 
                "data-scope": "{css}",
                class: "{css}_title", 
                "Hello" 
            }
            p { 
                "data-scope": "{css}",
                class: "{css}_content", 
                "World" 
            }
        }
    }
}
```

### 3. Inline CSS/SCSS


No external file needed:

```rust
use dioxus::prelude::*;
use dioxus_style::css;

#[component]

fn Badge() -> Element {
    // Plain CSS
    let css = css!("background: red; color: white; padding: 4px 8px;");
    
    rsx! {
        span { 
            "data-scope": "{css}",
            class: "{css}", 
            "New" 
        }
    }
}

#[component]

fn ScssCard() -> Element {
    // Inline SCSS
    let css = css!("
        $spacing: 1rem;
        
        background: white;
        padding: $spacing;
        
        &:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
    ");
    
    rsx! {
        div { 
            "data-scope": "{css}",
            class: "{css}", 
            "Hover me" 
        }
    }
}
```

### 4. Function-like Component Macro


Alternative syntax for defining styled components:

```rust
use dioxus::prelude::*;
use dioxus_style::component_with_css;

component_with_css! {
    css: "card.scss",  // Supports both .css and .scss
    fn Card() -> Element {
        rsx! {
            div { 
                "data-scope": "{css}",
                class: "{css}_card", 
                "Content" 
            }
        }
    }
}
```

## How It Works


### Compile-Time Processing


```rust
let css = scoped_style!("button.scss");
// 1. Compiles SCSS to CSS (if .scss file)
// 2. Scopes all selectors
// 3. Generates: "sc_a1b2c3d4"
```

**Input SCSS:**
```scss
$primary: red;

.btn { 
    color: $primary;
    
    &:hover { 
        color: blue; 
    }
}

div { 
    margin: 10px; 
}

#header { 

    font-size: 24px; 
}
```

**After SCSS Compilation:**
```css
.btn { color: red; }
.btn:hover { color: blue; }
div { margin: 10px; }
#header { font-size: 24px; }

```

**After Scoping:**
```css
.sc_a1b2c3d4_btn { color: red; }
.sc_a1b2c3d4_btn:hover { color: blue; }
div[data-scope="sc_a1b2c3d4"] { margin: 10px; }
#sc_a1b2c3d4_header { font-size: 24px; }

```

### Usage in Components


```rust
// Use the scoped class name and data-scope attribute
button { 
    "data-scope": "{css}",
    class: "{css}_btn", 
    "Click" 
}
// Renders: <button data-scope="sc_a1b2c3d4" class="sc_a1b2c3d4_btn">Click</button>
```

## SCSS Features Supported


All standard SCSS features are supported:

- **Variables**: `$primary: #3498db;`
-**Nesting**: Parent-child selector relationships
-**Parent Selector**: `&` for modifiers and pseudo-classes
-**Mixins**: `@mixin` and `@include`
-**Functions**: `darken()`, `lighten()`, `rgba()`, etc.
-**Imports**: `@import` and `@use`
-**Extends**: `@extend`
-**Operators**: `+`, `-`, `*`, `/`, `%`
-**Interpolation**: `#{$variable}`
-**Control Directives**: `@if`, `@for`, `@each`, `@while`
-**Maps and Lists**: Complex data structures
-**Built-in Functions**: All SCSS built-in functions

### SCSS Examples


**Variables and Operations:**
```scss
$base-spacing: 1rem;

.container {
    padding: $base-spacing * 2;
    margin: $base-spacing / 2;
}
```

**Nesting:**
```scss
.card {
    background: white;
    
    .title {
        font-size: 1.5rem;
    }
    
    .content {
        color: #666;
    }
}
```

**Mixins:**
```scss
@mixin flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
}

.container {
    @include flex-center;
}
```

**Parent Selector:**
```scss
.button {
    background: blue;
    
    &:hover {
        background: darkblue;
    }
    
    &--large {
        padding: 1rem 2rem;
    }
}
```

## Scoping Behavior


### What Gets Scoped


| Selector Type | Input | Output | Usage |
|--------------|-------|---------|-------|
| **Class** | `.btn` | `.sc_xxx_btn` | `class: "{css}_btn"` |
| **ID** | `#header` | `#sc_xxx_header` | `id: "{css}_header"` |
| **Element** | `div` | `div[data-scope="sc_xxx"]` | `"data-scope": "{css}"` |
| **Pseudo-class** | `.btn:hover` | `.sc_xxx_btn:hover` | (automatic) |
| **Complex** | `.card > .title` | `.sc_xxx_card > .sc_xxx_title` | (automatic) |

### Element Scoping


Elements are scoped using `data-scope` attributes:

```rust
// SCSS
$spacing: 20px;

div { 
    padding: $spacing; 
}

span.highlight { 
    color: yellow; 
}

// Component
rsx! {
    div { 
        "data-scope": "{css}",
        class: "{css}_container",
        span { 
            "data-scope": "{css}",
            class: "{css}_highlight",
            "Text"
        }
    }
}
```

## Style Injection Strategies


### Auto-Injection (Recommended for Simple Cases)


```rust
#[with_css("styles.scss")]

fn MyComponent() -> Element {
    // Styles automatically injected - no manual inject_styles() needed
    rsx! { 
        div { 
            "data-scope": "{css}",
            /* your content */ 
        } 
    }
}
```

### Manual Injection (Recommended for Root Component)


```rust
#[component]

fn App() -> Element {
    rsx! {
        // Inject ALL registered styles once at the root
        style { dangerous_inner_html: "{inject_styles()}" }
        
        // Your components
        MyComponent {}
        AnotherComponent {}
    }
}
```

## Advanced Features


### CSS File Path Resolution


The library searches for CSS/SCSS files in multiple locations:

```rust
scoped_style!("button.scss")
// Searches:
// 1. ./button.scss
// 2. ../button.scss
// 3. ../../button.scss
// 4. src/button.scss
```

### Automatic File Type Detection


```rust
#[with_css("button.scss")]  // ✅ SCSS file - automatically compiled

#[with_css("button.css")]   // ✅ CSS file - scoped only

```

### Complex Selectors


All complex selectors are fully supported in both CSS and SCSS:

```scss
// SCSS with nesting
.parent {
    > .child { 
        color: blue; 
    }
}

// Compiles to: .sc_xxx_parent > .sc_xxx_child { color: blue; }

// Adjacent sibling
.card + .card { 
    margin-top: 20px; 
}
// Output: .sc_xxx_card + .sc_xxx_card { margin-top: 20px; }

// Mixed selectors with SCSS
div.container {
    > span#label { 
        font-weight: bold; 
    }
}
// Output: div[data-scope="sc_xxx"].sc_xxx_container > span[data-scope="sc_xxx"]#sc_xxx_label
```

### Minification


In release builds, CSS is automatically minified:

```rust
// Debug: Preserves formatting for readability
// Release: Removes whitespace and comments for smaller bundles
```

### Hash Generation


Uses xxHash (XXH3) for fast, collision-resistant hashing:

```rust
// Hash includes file path + content for uniqueness
// Format: "sc_" + base62(hash)
// Example: "sc_3xK9mP2"
```

## Performance Characteristics


- **Compile-time SCSS compilation**: Zero runtime SCSS parsing
- **Compile-time CSS scoping**: Zero runtime CSS transformation
- **O(1) style lookups**: HashMap-based registry
- **Deduplication**: Identical styles registered only once
- **Fast hashing**: xxHash3 is one of the fastest non-cryptographic hashes
- **Efficient scoping**: Single-pass CSS transformation with optimized state machine

## Architecture


```
┌───────────────────────────────────┐
│  Your Component (compile time)    │
│  scoped_style!("button.scss")     │
└──────────────┬────────────────────┘
┌───────────────────────────────────┐
│  SCSS Compiler (if .scss)         │
│  • Compile SCSS to CSS            │
│  • Variables, nesting, mixins     │
│  • Functions and operations       │
└──────────────┬────────────────────┘
┌───────────────────────────────────┐
│  Procedural Macro                 │
│  • Read CSS/SCSS file             │
│  • Generate hash (xxHash3)        │
│  • Scope selectors:               │
│    - .btn → .sc_xxx_btn           │
│    - #id → #sc_xxx_id             │
│    - div → div[data-scope="..."]  │
│  • Minify (release builds)        │
└──────────────┬────────────────────┘
┌───────────────────────────────────┐
│  Runtime Registry (lazy_static)   │
│  • Store scoped CSS               │
│  • Deduplicate by hash            │
│  • Preserve insertion order       │
└──────────────┬────────────────────┘
┌───────────────────────────────────┐
│  inject_styles() → <style> tag    │
│  • Inject into DOM                │
│  • All styles in single tag       │
└───────────────────────────────────┘
```

## Examples


### Complete App Structure with SCSS


```rust
use dioxus::prelude::*;
use dioxus_style::{with_css, inject_styles};

fn main() {
    dioxus::launch(App);
}

#[component]

fn App() -> Element {
    rsx! {
        style { dangerous_inner_html: "{inject_styles()}" }
        Header {}
        Main {}
        Footer {}
    }
}

#[with_css("header.scss")]

fn Header() -> Element {
    rsx! {
        header { 
            "data-scope": "{css}",
            class: "{css}_header",
            h1 { 
                "data-scope": "{css}",
                "My App" 
            }
        }
    }
}

#[with_css("main.scss")]

fn Main() -> Element {
    rsx! {
        main { 
            "data-scope": "{css}",
            class: "{css}_container",
            Card { title: "Welcome" }
        }
    }
}

#[with_css("card.scss")]

fn Card(title: String) -> Element {
    rsx! {
        div { 
            "data-scope": "{css}",
            class: "{css}_card",
            h2 { 
                "data-scope": "{css}",
                class: "{css}_title", 
                "{title}" 
            }
        }
    }
}
```

**header.scss:**
```scss
$header-bg: #2c3e50;

.header {
    background: $header-bg;
    padding: 1rem;
    
    h1 {
        color: white;
        margin: 0;
    }
}
```

## Scoping Rules Summary


### ✅ Automatically Scoped


- **Classes**: `.button``.sc_xxx_button`
- **IDs**: `#header``#sc_xxx_header`
- **Elements**: `div``div[data-scope="sc_xxx"]` (requires `data-scope` attribute)
- **Pseudo-classes**: `:hover`, `:focus`, `:active`, etc.
- **Pseudo-elements**: `::before`, `::after`
- **Attribute selectors**: `[type="text"]` (passed through, element gets scoped)
- **Complex selectors**: All combinators (`>`, `+`, `~`, space)

### ❌ Not Scoped (Global)


- **Universal selector**: `*`
- **:root**: CSS variables at root level
- **@keyframes**: Animation definitions (use unique names)
- **@media, @supports**: Query blocks (contents are scoped)

## Migration Guides


### From v0.2.0 to v0.3.0 (SCSS Support)


**Good News**: This is a NON-BREAKING release! All v0.2.0 code works without changes.

**To Use SCSS:**
1. Rename `.css` files to `.scss` (optional)
2. Start using SCSS features
3. Or keep using plain CSS - both work!

**Cargo.toml:**
```toml
# Before (v0.2.0)

[dependencies]
dioxus_style = "0.2.0"

# After (v0.3.0) - SCSS enabled by default

[dependencies]
dioxus_style = "0.3.0"

# Or without SCSS

dioxus_style = { version = "0.3.0", default-features = false }
```

### From v0.1.0 to v0.2.0+ (Element Scoping)


**Breaking Changes:**

1. **Element selectors now require `data-scope`:**
   ```rust
   // OLD (v0.1.0)
   rsx! { div { class: "{css}_container", "Content" } }
   
   // NEW (v0.2.0+)
   rsx! { 
       div { 
           "data-scope": "{css}",
           class: "{css}_container", 
           "Content" 
       } 
   }
   ```

2. **Class selector output format changed:**
   - Old: `.sc_xxx.button`
   - New: `.sc_xxx_button`

3. **ID selector output format changed:**
   - Old: `#sc_xxx.header`
   - New: `#sc_xxx_header`

## Troubleshooting


### SCSS compilation error


```
error: SCSS compilation error in 'button.scss': Undefined variable
```

**Solution:** Check that all SCSS variables are defined:
```scss
// ❌ Wrong
.button { color: $undefined; }

// ✅ Correct
$primary: blue;
.button { color: $primary; }
```

### SCSS feature not available


```
error: SCSS support is not enabled
```

**Solution:** Enable SCSS in Cargo.toml:
```toml
[dependencies]
dioxus_style = { version = "0.3.0", features = ["scss"] }
```

### CSS/SCSS file not found


```rust
// ❌ Error: Failed to find file 'button.scss'
scoped_style!("button.scss")

// ✅ Solution: Use relative path from Cargo.toml location
scoped_style!("src/components/button.scss")
```

### Styles not appearing


```rust
// ❌ Forgot to inject styles
#[component]

fn App() -> Element {
    rsx! { MyComponent {} }
}

// ✅ Add inject_styles() to root component
#[component]

fn App() -> Element {
    rsx! {
        style { dangerous_inner_html: "{inject_styles()}" }
        MyComponent {}
    }
}
```

### Element styles not working


```rust
// ❌ Missing data-scope attribute
div { class: "{css}_container", "Content" }

// ✅ Add data-scope for element scoping
div { 
    "data-scope": "{css}",
    class: "{css}_container", 
    "Content" 
}
```

## Contributing


Contributions are welcome! Please feel free to submit a Pull Request. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## License


This project is licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT License ([LICENSE-MIT]LICENSE-MIT)

at your option.

## Credits


Built for the [Dioxus](https://dioxuslabs.com/) framework.

SCSS compilation powered by [grass](https://github.com/connorskees/grass).

## Changelog


See [CHANGELOG.md](CHANGELOG.md) for detailed version history.

---

**Made with ❤️ for the Dioxus community**