# Overview

Copy this Markdown into an agent prompt or your project's `AGENTS.md`.

<a id="instructions"></a>

## Refract instructions

Use the copy icon to copy the complete guide as Markdown.

# Working with Refract

## Start with a Refract app

Install the CLI from crates.io and create an app with `refract new my-app`, or add the library to an existing project with `cargo add refract`. Start with the generated counter and the documentation for the APIs you use. The repository’s clock and gallery examples provide additional patterns for effects, environment providers, controls, and layout.

## Write views

Import `refract::prelude::*` and compose views with Rust builders such as `view`, `text`, `v_stack`, and `h_stack`. For example, a `v_stack` can add a title and an activatable view through successive `.child(...)` calls. Apply layout and style modifiers to the element they should affect. Use ordinary Rust functions and control flow to assemble the tree, and choose one of the reactive view forms below when a subtree needs to own mounted state or track its own reads.

### Handwritten struct and `View::body`

Store props as struct fields. This example uses the `initial` prop to seed the mounted count and reads the binding inside the counter body.

```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 }
}
```

### Named view with `#[view]`

The macro generates the view constructor from the function signature. Call `counter(5)` to pass a prop. The view context is supplied by Refract.

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

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

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

    view()
        .child(text(format!("Count: {}", cx.read(&count))))
        .padding(16.0)
        .on_press(increment)
}
```

### Reactive closure with `view_fn`

Use this for an inline subtree or a small component that captures owned values. The closure returns `Result` and has its own mounted state and reactive reads.

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

fn closure_counter(initial: u32) -> impl View {
    view_fn(move |cx| {
        let count = cx.state("count", || 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);
            }))
    })
}
```

### Plain Rust composition

Use ordinary functions to assemble views from props or values the caller has already read. If the caller reads a binding and passes its value to `count_label`, the caller subscribes to the binding. To subscribe the child independently, pass the binding into one of the reactive forms and read it in that child's body.

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

fn count_label(count: u32) -> impl View {
    text(format!("Count: {count}"))
}
```

## Building blocks, child order, and modifiers

Primitives provide basic boxes, content, text input, and vector drawing: `view()` creates a generic box, while `text` and `image` display content. Use [Canvas](https://refract.rs/docs/canvas) for `shape`, `canvas`, and `canvas_with`, or [Shaders](https://refract.rs/docs/shaders) for application-owned WGSL with `shader` and `shader_with`. Add `.on_press(...)` to a view for pointer and keyboard activation. Use `text` for a label, `view().child(content).on_press(action)` for an action with child content, `image` for an image with alternative text, and `field` for a bound string. Use `v_stack` and `h_stack` to lay out children vertically or horizontally. Add children in the intended order with `.child(...)`, or use `.children(...)` with an iterator of views. A stack's `.gap(...)` controls spacing between children, while `.padding(...)` adds space around the view. In a reorderable collection, the order you describe controls placement and the key identifies which mounted child moves to that position.

Read a modifier chain from the primitive outward. Structural modifiers such as `padding` and `frame` add wrappers. A paint modifier such as `background` styles the current outer box, so its position in the chain determines what area it paints. Compare these two chains.

```rust
// The background covers the content and its padding.
text("Hello").padding(12.0).background(Color::WHITE)

// The padding sits outside the painted box.
text("Hello").background(Color::WHITE).padding(12.0)
```

Modifiers receive ordinary Rust values. To make a modifier reactive, read a binding inside the body and pass the result into the builder. For example, a body can call `cx.read(&selected)` to choose its background color or `cx.read(&spacing)` to set the gap in a stack. Refract tracks the read at the body boundary. When that value changes, the body builds a new description and reconciliation updates the affected elements. Keep the same tree shape when changing a property such as a color. If a conditional branch adds or removes a structural wrapper, the shape changes and can affect mounted identity and local state.

### Component reference

| Use | Constructors |
| --- | --- |
| Primitives | `view()`, `text(value)`, `image(source)`, `field(Binding<String>)`, `fragment(children)` |
| Layout | `stack()`, `h_stack()`, `v_stack()`, `z_stack()`, `spacer()`, `scroll_view(content)` |
| Drawing | `shape(geometry)`, `canvas(draw)`, `canvas_with(prepare, draw)`, `shader(program)`, `shader_with(prepare)` |

### Modifier reference

| Purpose | `ViewExt` methods |
| --- | --- |
| Box layout | `padding`, `frame`, `width`, `height`, `min_width`, `max_width`, `min_height`, `max_height`, `fill_width`, `fill_height`, `grow` |
| Paint and clipping | `background`, `background_gradient`, `foreground`, `shadow`, `border`, `radius`, `opacity`, `blur`, `backdrop_blur`, `clipped` |
| Activation | `on_press`, `disabled` (current element) |
| Focus | `focused`, `focused_value`, `focusable`, `on_focus_change`, `on_focus_within_change` |
| Focus indicators | `focus_ring`, `focus_within` |
| Scrolling and accessibility | `scrollable()`, `label` |
| Identity, memoization, and environment | `key`, `memo`, `environment_object`, `environment` |

Use `blur(amount)` for the composed view and `backdrop_blur(amount)` for content behind its rounded surface. Amounts are finite, nonnegative logical pixels of Gaussian standard deviation; zero disables the effect. Read [Blur and Backdrop Blur](/docs/layout-style#blur) for examples and clipping behavior.

Each constructor returns a concrete builder implementing `View`. Dimensions, paint, labels, and disabled state preserve that type. Typography belongs to `Text` and `Field`; image fitting belongs to `Image`. For example, `field(value).width(280.0).multiline(true)` configures the editable control directly. Structural modifiers such as `padding` and `frame` return wrappers, so configure the inner element before adding those. Composed views use the `ViewExt` fallback.

| Builder type | Builder methods |
| --- | --- |
| `Container`, `Stack`, `Overlay` | `child`, `children`, `maybe_child` |
| `Stack` layout | `direction`, `gap`, `alignment`, `justify` |
| `Overlay` layout | [`alignment(horizontal, vertical)`](/docs/z-stack#alignment) |
| `Text` and `Field` typography | `font_size`, `font_weight`, `font_family`, `line_height`, `text_align` |
| `Text` semantics and overflow | `status`, `heading`, `truncate` |
| `Image` fitting | `fit` |
| `Field` configuration | `multiline`, `style`, `on_submit`, `label`, `placeholder`, `disabled` |

## Architecture and update flow

The `refract` crate is the public facade and provides the prelude application code uses. The optional `refract-macros` crate translates declarations such as `#[view]` and `#[state]` into the ordinary authoring APIs. All three reactive view forms participate in the same runtime, so a project can use different forms in different parts of the tree.

Refract keeps three kinds of information separate. A view description is a temporary Rust value that says what to show. The graph in `refract-graph` stores reactive values and tracks which bodies depend on them. The mounted tree in `refract-core` retains identity, local state ownership, handlers, and the last accepted semantic elements. A view can compose other views without corresponding to a platform element. When a semantic element persists across updates, the adapter can reuse the platform resources associated with its element ID.

For example, suppose a counter body reads its count binding with `cx.read` and describes a button label using that value. When the button is pressed, the adapter calls `app.dispatch` with the element ID and a semantic event. Core resolves the current mounted handler and executes it in a graph batch. If the handler increments the count, the graph invalidates the bodies that read it. The host's next flush calls `app.prepare()`, which reevaluates affected bodies and reconciles the new descriptions into semantic patches. The adapter applies the patches before calling `app.commit(pending)`. If the button still has the same identity, its label can change while the existing button stays mounted.

The platform adapters decide how semantic elements appear and behave. `refract-web` maps elements to DOM nodes and CSS and translates browser events back into semantic events. `refract-native` receives window events through Winit, computes layout with Taffy, shapes text with Parley, and can render through Vello. Keep platform-specific setup and services at the host boundary so the same view code can run on both targets. `refract-test` provides an in-memory host for inspecting updates and testing interactions without opening a window.

## State, props, and identity

A prop is a value supplied by the parent. In the counter examples, `initial` seeds the count when the view first creates its mounted state. If the parent supplies a new initial value to the same mounted counter, the existing count is still used. Use a binding prop when the parent should control the live value. The parent can own the state and pass the binding down, and the child can read and update it through the view and action contexts.

Declare local state unconditionally and give each slot a stable name and type. State follows mounted identity. When rendering a list that can reorder, use a stable item key with `.key(item.id)`, so each row keeps its own state as it moves. Changing a view's identity remounts it, which creates fresh local state from the initializer.

The body that calls `cx.read` is the one that subscribes. If a parent reads a binding and passes the resulting value to a plain layout helper, the read belongs to the parent. If the parent instead passes the binding to a reactive child, that child can subscribe in its own body. Update the binding from an action using the action context's runtime. For a button, `count.update(cx.runtime(), |n| *n += 1)` computes the next value from the current state when the event runs.

Use an environment provider for a value shared by descendants, such as a model read by several views. Place the provider around the subtree that needs it and read the value through the view context at the point of use. Use mounted effects for resources with a lifecycle, such as timers and subscriptions, and give those effects cleanup. The clock example shows both patterns together.

## Text input across the host boundary

Build a bound field with `field(binding)`, where the binding contains a `String`. Fields are single-line by default; add `.multiline(true)` to allow line breaks. Single-line fields submit on Enter, while multiline fields insert a newline on Enter and submit on Command/Ctrl+Enter. The field reads the binding during body evaluation, so a model write invalidates the field and produces a patch carrying the desired string. The web adapter compares that string with the live DOM value before setting it. The native adapter syncs it to its retained editor buffer.

When the user edits the field, the host updates its local editor and dispatches `Event::Input` with the full edited string. The mounted field handler writes that string back to the binding if it changed. The next patch carries the accepted value to the host. In the ordinary typing case the editor already contains that value, so the adapter skips rewriting the text and the caret stays under the host's control. During IME composition, provisional text stays in the host editor and incoming model writes are deferred until composition ends.

## Asynchronous Work

Use channels to deliver HTTP results, file reads, subscriptions, and expensive computation results into reactive state. Create the channel during committed effect setup with `rt.channel(callback)`. The callback stays on the UI thread and can capture `State`, `Binding`, or an `Rc` model. Give the `MessageSender<T>` to the operation and keep its `MessageSubscription` alive for the effect's lifetime.

This excerpt belongs inside effect setup. `result_state` is an existing binding and `start_request` is an application-defined service that accepts the sender and launches the operation:

```rust
let result_state = result_state.clone();
let (sender, subscription) = rt.channel(move |rt, result| {
    result_state.set(rt, result);
});
start_request(sender);
subscription.into_cleanup()
```

Return `subscription.into_cleanup()` from setup. It retains the subscription until cleanup runs or is dropped. Replacing the effect's explicit dependencies or unmounting closes the channel and discards undelivered results. Use request inputs such as the query or document ID as effect dependencies so old requests cannot deliver after replacement cleanup. Closing delivery does not cancel the underlying operation; when cancellation is supported, use an explicit cleanup closure that drops the subscription and then cancels the producer.

Send owned messages with `sender.try_send(value)`; `Ok(())` means queued, not applied or painted. Use `Result<Data, Error>` or another explicit result type for operation outcomes. Handle `SendError::Full(value)` with producer throttling, a later retry, or an error policy, and stop sending on `SendError::Closed(value)`. Never block or spin on the UI thread waiting for capacity. The runtime shares a 1,024-message inbox and drains at most 128 messages per batch before preparing views.

Receive callbacks update ordinary graph-backed state. Derived values settle when the mutation batch finishes, and only affected views become dirty. Receiving a message by itself does not trigger a render. A root or provider-level effect can own a channel for an `environment_object`; deeper views react by reading the model's bindings through `cx.read`, without creating their own subscriptions to the channel.

Channels provide delivery, not an HTTP client or executor. Keep platform transport and task spawning in application services. Native senders are `Send + Sync` and can move into threads or async tasks. Browser async completions use the main-thread sender. CPU-heavy browser work requires a Worker or another off-main-thread mechanism; Worker results cross `postMessage` before decoding and channel submission on the main thread. Message types must be `Send + 'static` on both targets. Keep view evaluation, effect setup, and receive callbacks short and synchronous.

Read [Channels](https://refract.rs/docs/channels) for the public API and [Async Work](https://refract.rs/docs/async-work) for the scheduling, batching, and ownership internals.

## Run and verify

Install the CLI with `cargo install refract --features cli --locked`. Run `refract new my-app` and enter that directory. Use `refract dev --open` for the browser or `refract dev --platform desktop` for native. The CLI manages browser tooling, watches sources, and reloads after successful builds. Reloads reset state.

Exercise the behavior you changed in the relevant example. If the change affects reactive behavior, verify both the initial render and an update through the normal action or host event. Use `cargo fmt --all --check` and `cargo test --workspace --all-features --locked` for workspace verification.
