Macro dominator::class

source ·
macro_rules! class {
    (#![prefix = $name:literal] $($methods:tt)*) => { ... };
    ($($methods:tt)*) => { ... };
}
Expand description

Creates a locally scoped CSS stylesheet.

Normally CSS is global, which means you can accidentally create name collisions by using the same class name multiple times.

However, if you use the class! macro, then it is impossible to have name collisions, because the CSS is locally scoped.

This makes it a lot easier to create self-contained components, so you should prefer to use class! as much as you can.

The class! macro accepts a block of method calls. Inside of the block you can use ClassBuilder methods:

class! {
    .style("color", "green")
    .style("background-color", "blue")
    .style_signal("width", ...)
}

The block uses the apply_methods! macro, see the docs for apply_methods! for more details.

The class! macro returns a String, which is a unique class name. You can then assign that class name to a DomBuilder:

use once_cell::sync::Lazy;

// This uses a `static` so that it only creates the `class!` a single time.
//
// If it used `let` then it would create the same `class!` multiple times.
static MY_CLASS: Lazy<String> = Lazy::new(|| class! {
    .style("color", "green")
    .style("background-color", "blue")
    .style_signal("width", ...)
});

html!("div", {
    .class(&*MY_CLASS)
})

The class is locally scoped, which means it cannot conflict with any other classes, the only way to access the class is by using the MY_CLASS variable.

Because it is a normal Rust variable, it follows the normal Rust scoping rules. By default the variable can only be acccessed within that module.

But you can use pub to export it so it can be used by other modules:

pub static MY_CLASS: Lazy<String> = Lazy::new(|| class! {
    ...
});

Or you can use pub(crate) so that it can only be accessed within your crate.