# Macros

Declare views, state, actions, effects, and environment reads with Refract’s authoring attributes.

<a id="overview"></a>

## An authoring layer over the runtime

The `macros` feature is enabled by default on the `refract` crate. Import `refract::prelude::*` to bring `#[view]` into scope. If you disable default features, enable `macros` explicitly to use it.

`#[view]` is the procedural macro. The other attributes are declarations it processes inside the view body; they are not standalone macros to import or use in ordinary functions. They expand to the same view, binding, environment, and effect APIs used by handwritten views.

| Attribute | Purpose |
| --- | --- |
| [`#[view]`](#view) | Creates a view constructor from a function with a view context and owned props. |
| [`#[state]`](#state) | Creates or reuses a named state binding for this mounted view. |
| [`#[action(...)]`](#action) | Clones listed captures and prepares an action closure. |
| [`#[environment(Key)]`](#environment) | Reads a typed environment value from the nearest provider or its default. |
| [`#[environment_object]`](#environment-object) | Reads an inherited shared model. |
| [`#[effect(...)]`](#effect) | Registers work and cleanup tied to the mounted view’s lifetime. |

<a id="view"></a>

## `#[view]`

Write a synchronous, safe, non-const function whose first argument is `&mut ViewContext<'_>` and whose return type is `impl View`. The macro supplies the context during evaluation; callers pass only the remaining arguments.

Each remaining argument is an owned prop with a single immutable binding name. Props are captured by the generated view and cloned for each body evaluation, so they must support `Clone` and satisfy the view’s `'static` lifetime. Use owned strings and `Rc<T>` for shared data rather than borrowed props.

The body must end with a view expression. The expansion wraps the body in `view_fn` and supplies the `Ok(...)` result. Fallible operations can use `?` when their errors convert to `ViewError`; do not wrap the final view in `Ok` yourself.

```rust
use refract::prelude::*;

#[view]
fn greeting(cx: &mut ViewContext<'_>, name: String) -> impl View {
    text(format!("Hello, {name}"))
}

fn screen() -> impl View {
    greeting(String::from("Refract"))
}
```

<a id="state"></a>

## `#[state]`

Annotate a local declaration with an initializer. The declared value becomes a `Binding<T>`: `let count: u32 = initial` creates a `Binding<u32>`, not an ordinary mutable integer. The value type must be `Clone + 'static`; the annotation can be omitted when Rust can infer it.

The variable name is the default state ID. Set `id = "name"` to give the slot an explicit identity independent of the local name. IDs must be nonempty and unique among state declarations in the view. Keep the slot’s type stable across evaluations.

The initializer runs when the mounted slot is new. A new prop value does not reset an existing slot; changing mounted identity creates fresh state. Initializers can run in discarded preparations, so use effects for external work. Read with `cx.read(&binding)` to subscribe, and update the binding from an action.

```rust
use refract::prelude::*;

#[view]
fn count_label(cx: &mut ViewContext<'_>, initial: u32) -> impl View {
    #[state(id = "count")]
    let count: u32 = initial;

    text(format!("Count: {}", cx.read(&count)))
}
```

<a id="action"></a>

## `#[action(...)]`

Use a parenthesized list of local identifiers, such as `#[action(count)]`. The macro clones each listed value, makes the closure a `move` closure, and supplies the `&mut ActionContext<'_>` parameter type when it is omitted. `#[action()]` is valid when no explicit clones are needed.

The closure must be synchronous and accept one context argument. Capture lists cannot repeat a name. Values used by the closure but omitted from the list follow ordinary Rust move and borrow rules; the list does not discover captures automatically.

Cloning a binding shares access to its state rather than copying the stored value. Separate actions can clone the same binding, leaving it available to the view. Use `cx.runtime()` in the action to update it. Creating an action does not run it: attach it with `.on_press(...)` or `.on_submit(...)`.

```rust
use refract::prelude::*;

#[view]
fn counter_actions(cx: &mut ViewContext<'_>) -> impl View {
    #[state]
    let count: u32 = 0;

    #[action(count)]
    let increment = |cx| {
        count.update(cx.runtime(), |value| *value += 1);
    };

    #[action(count)]
    let reset = |cx| count.set(cx.runtime(), 0);

    h_stack()
        .gap(12.0)
        .child(text(format!("Count: {}", cx.read(&count))))
        .child(view().child(text("Increment")).on_press(increment))
        .child(view().child(text("Reset")).on_press(reset))
}
```

<a id="environment"></a>

## `#[environment(Key)]`

Declare a typed local without an initializer. The key must implement `EnvironmentKey`, and the local type must match the key’s `Value`. That value must be `Clone + PartialEq + 'static`.

The declaration expands to `cx.environment::<Key>()`. It reads the nearest provider, falls back to the key’s default when no override exists, and establishes a reactive dependency. Supply an override with the `.environment::<Key>(value)` view modifier.

```rust
use refract::prelude::*;

struct Accent;

impl EnvironmentKey for Accent {
    type Value = Color;

    fn default() -> Color {
        Color::BLUE
    }
}

#[view]
fn accent_label(cx: &mut ViewContext<'_>) -> impl View {
    #[environment(Accent)]
    let accent: Color;

    text("A shared accent").foreground(accent)
}

fn themed_screen() -> impl View {
    accent_label().environment::<Accent>(Color::rgb(30, 140, 160))
}
```

<a id="environment-object"></a>

## `#[environment_object]`

Declare a local with an `Rc<Model>` type and no initializer. The macro expands to `cx.object()?`, which reads the model supplied by an `.environment_object(model)` provider. A missing provider produces a view error; there is no default model.

The provider is tracked by pointer identity. Reading the object does not subscribe to every field automatically: read its graph bindings inside the view or pass them to reactive controls to track their values.

```rust
use refract::prelude::*;
use std::rc::Rc;

struct Preferences {
    notifications: Binding<bool>,
}

#[view]
fn preferences_panel(cx: &mut ViewContext<'_>) -> impl View {
    #[environment_object]
    let preferences: Rc<Preferences>;

    let enabled = cx.read(&preferences.notifications);
    let notifications = preferences.notifications.clone();
    view()
        .child(text(if enabled { "☑ Notifications" } else { "☐ Notifications" }))
        .label("Notifications")
        .on_press(move |cx| notifications.update(cx.runtime(), |value| *value = !*value))
        .modify(false, move |element| {
            element.role = Some("checkbox".into());
            element.checked = Some(enabled);
        })
}

fn settings(model: Rc<Preferences>) -> impl View {
    preferences_panel().environment_object(model)
}
```

<a id="effect"></a>

## `#[effect(...)]`

An effect declaration registers setup work through `cx.effect`. Its initializer must be a synchronous closure with one `&mut Runtime` argument; the type can be inferred. Return a `Cleanup`, a boxed `FnOnce()` closure that releases resources or undoes the setup.

Setup runs after a successful commit. When dependencies change, the previous cleanup runs before replacement setup. Committed removal and disposal also clean up the effect. Discarded preparations neither start new effects nor tear down the accepted ones.

The local declaration names the effect but does not bind a usable value, so omit a type annotation. Both the setup closure and action closures are synchronous; start asynchronous work through a service and arrange cleanup for its resources.

| Option | Behavior |
| --- | --- |
| `id = "name"` | Defaults to the local name. Must be nonempty and unique among effects in this view. |
| `deps = expression` | Defaults to `()`. The dependency value must be `PartialEq + 'static`; a changed value restarts the effect at commit. |
| `captures(a, b)` | Clones the listed identifiers before creating the move closure. Names cannot repeat; captures do not become dependencies automatically. |

```rust
use refract::prelude::*;

#[view]
fn status_log(cx: &mut ViewContext<'_>, status: String) -> impl View {
    #[effect(id = "status-log", deps = status.clone(), captures(status))]
    let log_status = |_runtime| {
        println!("Entered: {status}");
        let previous = status.clone();
        Box::new(move || println!("Leaving: {previous}"))
    };

    text(status)
}
```

> Read reactive values during view evaluation and include the inputs that should restart setup in `deps`. Equal dependencies retain the previous setup and captures. With the default `()`, an effect runs once per mounted lifetime even if its captured props change.

<a id="declaration-rules"></a>

## Declaration placement and diagnostics

Place `#[state]`, `#[action]`, `#[effect]`, `#[environment]`, and `#[environment_object]` on unconditional top-level `let` statements inside a `#[view]` function. Each declaration uses one helper attribute and one immutable binding name. Nested blocks, conditionals, loops, closures, destructuring patterns, and `let mut` are not supported declaration positions or forms.

Ordinary Rust control flow is still available for composing the returned view. Keep the declarations unconditional, then choose which children to render. Use child keys to control mounted identity rather than conditionally declaring state.

State requires an initializer. Actions require a closure. Effects require a setup closure without a type annotation. Environment reads require a type and forbid an initializer. The macro reports invalid declarations at compile time; missing model providers and changes to a mounted state slot’s type are runtime view errors.

<a id="crate-path"></a>

## Renamed crate imports

The expansion uses `::refract` by default. Set `crate_path = path` when the crate is imported under another name, including a renamed Cargo dependency. The path is a Rust path rather than a string.

```rust
use refract as ui;

#[ui::view(crate_path = ui)]
fn aliased_view(cx: &mut ui::ViewContext<'_>) -> impl ui::View {
    ui::text("An alternate crate path")
}
```

<a id="without-macros"></a>

## The same runtime without macros

Use `View::body` or `view_fn` when you prefer to write the authoring APIs directly. `#[state]` becomes `cx.state`, environment declarations become `cx.environment` or `cx.object`, and `#[effect]` becomes `cx.effect`. An action is a move closure with any required binding clones.

Macro and handwritten views share state ownership, dependency tracking, identity, reconciliation, and effect lifetimes. See [Views](/docs/views) and [Reactivity](/docs/reactivity) and [Effects](/docs/effects) for those runtime behaviors.

```rust
use refract::prelude::*;

struct Counter {
    initial: u32,
}

impl View for Counter {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let count = cx.state("count", || self.initial);
        let label = text(format!("Count: {}", cx.read(&count)));

        Ok(view()
            .child(label)
            .padding(16.0)
            .on_press(move |cx| {
                count.update(cx.runtime(), |n| *n += 1);
            }))
    }
}

fn counter() -> impl View {
    Counter { initial: 0 }
}
```
