# Animation

Animate state changes and view transitions with shared timing on desktop and web.

<a id="presentation"></a>

## State changes immediately

Application state always holds the target value. Animation interpolates the displayed properties toward that target without writing intermediate values into your bindings. Animation frames do not reevaluate views or rerun effects.

The same animation API works on desktop and web. Import `refract::prelude::*` and use `std::time::Duration` for timing. Initial rendering and hydration are immediate; animations apply to subsequent changes.

<a id="value-scoped-animation"></a>

## Animate when a value changes

Attach `.animation(animation, value)` to a view to animate changes when `value` differs from its previously committed value. The value must implement `PartialEq + 'static`; a tuple such as `(selected, enabled)` can observe several inputs together.

This example changes an explicit width when pressed. The binding updates immediately, while the displayed width eases toward its new target.

**Without macros (View trait)**

```rust
use refract::prelude::*;
use std::time::Duration;

struct ExpandingPanel;

impl View for ExpandingPanel {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let expanded = cx.state("expanded", || false);
        let open = cx.read(&expanded);

        Ok(text("Toggle width")
            .padding(16.0)
            .width(if open { 280.0 } else { 160.0 })
            .background(Color::BLUE)
            .foreground(Color::WHITE)
            .radius(12.0)
            .on_press(move |action| {
                expanded.update(action.runtime(), |value| *value = !*value);
            })
            .animation(
                Animation::ease_in_out(Duration::from_millis(250)),
                open,
            ))
    }
}

fn expanding_panel() -> impl View {
    ExpandingPanel
}
```

**With macros**

```rust
use refract::prelude::*;
use std::time::Duration;

#[view]
fn expanding_panel(cx: &mut ViewContext<'_>) -> impl View {
    let expanded = cx.state("expanded", || false);
    let open = cx.read(&expanded);

    text("Toggle width")
        .padding(16.0)
        .width(if open { 280.0 } else { 160.0 })
        .background(Color::BLUE)
        .foreground(Color::WHITE)
        .radius(12.0)
        .on_press(move |action| {
            expanded.update(action.runtime(), |value| *value = !*value);
        })
        .animation(
            Animation::ease_in_out(Duration::from_millis(250)),
            open,
        )
}
```

> The modifier scopes the subtree: all animatable changes in that update can participate. Place style modifiers before the animation boundary. Chaining animation modifiers does not give each preceding property an independent animation track or timing scope.

<a id="animated-actions"></a>

## Animate an action

Use `with_animation` when the animation belongs to a state-changing action. It attaches animation intent to synchronous writes in the closure, so affected views can animate without their own `.animation(...)` modifier.

The context survives deferred view updates. An asynchronous completion needs its own transaction; wrapping the code that starts a request does not animate its eventual result. When several writes affect one view evaluation, the latest relevant mutation supplies its context.

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

fn expand_button(expanded: Binding<bool>) -> impl View {
    text("Toggle panel").on_press(move |action| {
        with_animation(action.runtime(), Animation::spring(), |rt| {
            expanded.update(rt, |value| *value = !*value);
        });
    })
}
```

<a id="timing"></a>

## Choose a timing curve

Timed curves accept a duration. Springs accept a response duration and a positive, finite damping ratio. A ratio below `1.0` oscillates, `1.0` is critically damped, and larger ratios are overdamped. Spring response must be nonzero; it describes the spring rather than a fixed completion deadline.

Retargeting starts from the currently displayed position. Springs also carry their current velocity into the new motion. Timed curves restart their easing from the displayed value. A zero timed duration snaps to the target after any delay.

| Constructor | Behavior |
| --- | --- |
| `Animation::linear(duration)` | Constant-rate interpolation. |
| `Animation::ease_in(duration)` | Starts slowly and accelerates. |
| `Animation::ease_out(duration)` | Starts quickly and decelerates. |
| `Animation::ease_in_out(duration)` | Eases at both ends. |
| `Animation::spring()` | A 500ms response with a damping ratio of 0.85. |
| `Animation::spring_with(response, damping)` | A configurable spring with velocity-preserving retargeting. |
| `Animation::default()` | A 250ms ease-in-out animation. |

```rust
let motion = Animation::spring_with(
    Duration::from_millis(500),
    0.85,
).delay(Duration::from_millis(100));
```

<a id="transforms"></a>

## Move presentation independently of layout

Use `offset(x, y)`, `scale_effect(scale)`, and `rotation_effect(degrees)` to transform a view without changing its layout allocation. Offsets use logical pixels; rotation uses degrees. The default anchor is `UnitPoint::CENTER`.

Transforms compose as translation × rotation × scale around the anchor. Nested views compose outside-in. Drawing, clipping, hit testing, and native IME placement follow the displayed transforms.

```rust
fn selected_label(selected: bool) -> impl View {
    text("Selected")
        .opacity(if selected { 1.0 } else { 0.5 })
        .offset(if selected { 8.0 } else { 0.0 }, 0.0)
        .scale_effect(if selected { 1.05 } else { 1.0 })
        .rotation_effect(if selected { 3.0 } else { 0.0 })
        .transform_anchor(UnitPoint::CENTER)
        .animation(Animation::spring(), selected)
}
```

<a id="transitions"></a>

## Animate insertion and removal

A transition describes how a view appears and disappears. Attach `.transition(...)` to the conditional child, then supply timing through an animated action or a value-scoped animation on a surviving parent. A transition alone does not start an animation.

Use `Transition::opacity()`, `offset(x, y)`, or `scale(factor)`, and compose them with `combined_with`. Insertion starts from the effect and approaches the normal view; removal moves toward the effect.

```rust
fn notice(visible: bool) -> impl View {
    v_stack()
        .child(if visible {
            text("Saved")
                .transition(
                    Transition::opacity()
                        .combined_with(Transition::offset(0.0, 6.0)),
                )
                .into_any()
        } else {
            Empty.into_any()
        })
        .animation(
            Animation::ease_out(Duration::from_millis(180)),
            visible,
        )
}
```

<a id="transition-lifetime"></a>

## Choose separate entrance and exit effects

Use `Transition::asymmetric(insertion, removal)` for different effects in each direction. `Transition::identity()` leaves appearance unchanged, making it useful when only one direction needs an effect.

Removal cleans up effects, handlers, focus, and scoped work immediately. An inert visual snapshot finishes the exit outside layout. Reinserting a removed key creates a fresh logical mount; it does not revive disposed state. An ancestor's exit transition subsumes its exiting descendants.

```rust
text("Saved")
    .transition(Transition::asymmetric(
        Transition::opacity().combined_with(Transition::offset(0.0, 4.0)),
        Transition::identity(),
    ))
```

<a id="transactions"></a>

## Override or disable animation

A `Transaction` carries `animation: Option<Animation>` and `disables_animations: bool`. Use `.transaction(...)` to modify the inherited transaction for a subtree. The closure must be pure and does not introduce a layout or DOM element.

Setting `animation` to `None` clears inherited animation, but a nested value-scoped modifier can enable its own. Setting `disables_animations` to `true` suppresses animation throughout the subtree, including nested value-scoped modifiers.

```rust
let immediate = text("Update immediately")
    .transaction(|tx| tx.disables_animations = true);

let no_inherited_motion = text("Use only local animation")
    .transaction(|tx| tx.animation = None);
```

<a id="transaction-writes"></a>

## Scope a transaction to state writes

Use `with_transaction` for explicit control over a group of synchronous writes. For example, disable animations while restoring a saved state even if affected views have value-scoped animation modifiers.

```rust
fn restore_expanded(rt: &mut Runtime, expanded: &Binding<bool>) {
    with_transaction(
        rt,
        Transaction {
            animation: None,
            disables_animations: true,
        },
        |rt| expanded.set(rt, true),
    );
}
```

<a id="conditional-animation"></a>

## Animate only one direction

The `.animation(...)` modifier accepts either `Animation` or `Option<Animation>`. Choose `None` to make the matching value change immediate. This is useful for selection feedback: fade in the new highlight and clear the old highlight immediately, so two rows do not appear selected during the transition.

```rust
fn conversation_label(selected: bool) -> impl View {
    text("Conversation")
        .background(if selected {
            Color::rgb(220, 232, 251)
        } else {
            Color::rgb(241, 245, 251)
        })
        .animation(
            selected.then(|| Animation::ease_out(Duration::from_millis(140))),
            selected,
        )
}
```

<a id="supported-properties"></a>

## Know what interpolates

Animate opacity, offset, scale, rotation, corner radii, numeric width and height constraints, padding, gap, explicit solid foreground and background colors, and compatible borders and box shadows. Colors interpolate in premultiplied sRGB. Nonnegative geometry and opacity stay within valid presentation bounds.

Changes to intrinsic sizing or inherited colors apply immediately. Gradients, text content, font metrics, and images are not interpolated. Unrelated changes to a property do not restart another property's active animation, so streamed text can update while a message entrance continues.

Canvas inputs opt into custom interpolation with animatable_inputs() and the Animatable trait. Continuous canvas schedules also observe reduced-motion preferences on web and macOS; explicit property and input animations do not yet apply that preference automatically. See [Canvas](/docs/canvas#animated-inputs).

Automatic layout and list-reorder transitions, intrinsic-size interpolation, matched geometry, keyframes, and repeating property-animation curves are not currently supported. Use a canvas schedule for time-driven drawings.

<a id="playground"></a>

## Try the shared playground

From a Refract checkout, run the same animation example on either host. Reverse a spring while it is moving, resize the panel, and toggle the notice to compare property animation and transitions. Both hosts stop requesting animation frames when motion settles.

For deterministic checks, `refract_test::TestHost::advance_time` advances presentation time and `presented(id)` reads the displayed element. `elements` continues to contain the logical targets.

```bash
refract dev -p refract-animation --open
# Or run the native app:
refract dev -p refract-animation --platform desktop
```
