Animation
CSS transitions and keyframe animations, which properties are cheap to animate, animation events, enter and exit animations, and per-frame animation from Rust with request_frame.
You declare animations in CSS, as transitions and keyframe animations, and zgui runs them without
any Rust code. For values only Rust can compute, use request_frame.
Transitions
A transition animates a property from its old computed value to its new one. The view does not mention it.
use zgui::prelude::*;
const SHEET: &str = css!(
".swap {
padding: 8px 16px;
background-color: #1b1e24;
transition: background-color 180ms ease-out;
}
.swap:hover { background-color: #2b3040 }"
);
#[component]
fn Swap() -> impl IntoView {
view! {
control(class = "swap") {"Hover me"}
}
}When :hover starts matching, the cascade produces a new background-color. The element declares a
transition for that property, so the engine starts one.
| Longhand | Takes | Initial |
|---|---|---|
transition-property | a property, a comma-separated list, all or none | all |
transition-duration | a <time> | 0s |
transition-timing-function | a timing function | ease |
transition-delay | a <time> | 0s |
transition-behavior | normal or allow-discrete | normal |
In the transition shorthand, the first time is the duration and the second is the delay. Commas
separate transitions for different properties:
transition: opacity 180ms ease-out 40ms, transform 180ms ease-out 40ms;transition-behavior: allow-discrete lets a discrete property (such as align-items) transition;
without it, discrete properties change immediately.
Timing functions
All CSS timing functions are accepted: linear, ease, ease-in, ease-out, ease-in-out,
cubic-bezier(x1, y1, x2, y2) (with x1 and x2 between 0 and 1), steps(n),
steps(n, <position>), step-start, step-end, and linear(<stop>#).
What starts a transition
| Situation | Result |
|---|---|
| a declared property gets a different computed value | a transition starts |
| the element was just created (no previous style) | no transition |
| the target changes while a transition runs | it restarts from the current value toward the new target |
the property leaves transition-property | the running transition is cancelled |
the element becomes display: none | all its transitions are cancelled |
Anything that changes a computed value can trigger one: a class: binding, a style: declaration, a
var: custom property, an attribute a selector matches, or a pseudo-class such as :hover or
:focus-visible. This includes writes made in response to a geometry
observation; such a transition starts in the same frame and keeps
animating.
A transition compares two computed styles, and a new element has only one. Nothing transitions on the frame an element appears. Write entrances as keyframe animations.
Keyframe animations
A keyframe animation plays a named sequence of styles. It needs no previous value, so it runs from the frame the element is created.
@keyframes pulse {
from { opacity: 1 }
to { opacity: 0.4 }
}
.cell { animation: pulse 2s linear infinite }Percentage stops work, and each stop may set its own animation-timing-function.
| Longhand | Takes |
|---|---|
animation-name | a @keyframes name, or none |
animation-duration | a <time> per iteration |
animation-timing-function | any timing function |
animation-delay | a <time> before the first iteration; negative starts part-way through |
animation-iteration-count | a number, or infinite |
animation-direction | normal, reverse, alternate, alternate-reverse |
animation-fill-mode | none, forwards, backwards, both |
animation-play-state | running or paused |
A paused animation holds its current value, and the window stops rendering frames for it.
Fill mode
Without a fill mode, the element returns to its own style when the animation ends. With forwards
or both, the last keyframe stays in effect:
.panel { animation: fade 200ms linear forwards } /* the faded value stays */A forwards fill survives later restyles of the element, such as a theme change or an unrelated class
toggle. If a restyle sets animation-play-state: paused on a finished fill, it stays finished and
does not fire a second animation_end. If a restyle removes the animation from animation-name, the
fill is dropped without an animation_cancel event, because the animation had already ended.
Which properties are cheap to animate
Each frame, every animating element takes one of three paths, chosen from the properties it is currently animating.
| Properties | Path | Per-frame work |
|---|---|---|
opacity, background-color, border-*-color, outline-color | repaint | the value is applied when painting; no style recomputation |
transform, translate, rotate, scale, transform-origin | placement | the element's matrix changes; no style, size or box rebuild |
anything else: lengths, filters, color and other inherited values, custom properties | cascade | the element's style is recomputed, which can also relayout |
- One cascade property moves the whole element to the cascade path. Animating
opacityandwidthtogether costs a cascade per frame. transformplusopacitystays cheap, so a slide-and-fade is the cheapest useful animation.- Animating a value on one element does not affect siblings that share its style.
An animation that gives an element its first transform, or removes its last, takes the cascade path. Whether an element has a transform decides whether it creates a stacking context and contains positioned descendants. Declare a resting transform so the animation only changes an existing one:
.bar {
transform: translateX(0px); /* without this, every frame cascades */
animation: slide 1000ms linear infinite;
}
@keyframes slide {
from { transform: translateX(0px) }
to { transform: translateX(300px) }
}Frame rate
While any element is animating, the window renders at the display's refresh rate. Frames are paced to the display, so input and timers do not shift or speed up an animation. When the last animation ends, the window stops rendering until something changes.
Running animations do not write signals or wake the reactive graph. Their cost per frame grows with the number of animating elements, not with the size of the document. The cost model shows what each kind of frame costs.
Animation events
Eight events report animation progress. Each targets the element the animation runs on and bubbles, so an ancestor can listen.
| Listener | Payload | Fires when |
|---|---|---|
on:animation_start | AnimationEvent | the animation begins, after its delay |
on:animation_iteration | AnimationEvent | one iteration ends and the next begins |
on:animation_end | AnimationEvent | it finishes |
on:animation_cancel | AnimationEvent | it is stopped before finishing |
on:transition_run | TransitionEvent | the transition is created (before its delay) |
on:transition_start | TransitionEvent | the delay is over and the value starts moving |
on:transition_end | TransitionEvent | the value arrives |
on:transition_cancel | TransitionEvent | it is stopped before arriving |
box(
class = "toast",
on:animation_end = move |ev| {
if ev.name.as_str() == "toast-out" {
gone.set(true);
}
}
)| Field | Meaning |
|---|---|
name (AnimationEvent) | the @keyframes name |
property (TransitionEvent) | the property being transitioned |
elapsed | active time, excluding a positive delay; a negative delay reports its start offset |
phase | which of the four events this is |
pseudo | Some(Pseudo::Before) or Some(Pseudo::After) for generated content; the event is dispatched at the owning element |
is_final() is true for the end and cancel phases. With no delay, transition_run and
transition_start arrive in that order in the same frame.
Count running animations
NodeRef::running_animations() -> usize counts the animations and transitions still running on a
node. It is already up to date inside lifecycle handlers: in on:transition_end, a value of 0
means nothing else is still moving.
Enter and exit animations
- Enter: a new element cannot transition. Use a keyframe animation on its class.
- Exit:
if move || open.get() { … }removes the element immediately when the condition turns false. Keep it mounted until its exit animation ends.
An exit needs two signals: mounted (is the element in the document) and closing (is it on its
way out, read by the style sheet through a class).
use zgui::prelude::*;
use zgui::reactive::RenderEffect;
const SHEET: &str = css!(
"@keyframes panel-in {
from { opacity: 0; transform: translateX(24px) }
to { opacity: 1; transform: translateX(0px) }
}
.panel {
width: 280px;
padding: 16px;
background-color: #1b1e24;
opacity: 1;
transform: translateX(0px);
animation: panel-in 180ms cubic-bezier(0, 0, 0.2, 1);
transition: opacity 180ms cubic-bezier(0.4, 0, 1, 1),
transform 180ms cubic-bezier(0.4, 0, 1, 1);
}
.panel.closing { opacity: 0; transform: translateX(24px) }"
);
#[component]
fn SlidePanel(
/// Whether the panel should be shown.
open: Signal<bool>,
/// Its content, rebuilt each time it opens.
children: ChildrenFn,
) -> impl IntoView {
install_stylesheet("slide-panel", SHEET);
let mounted = RwSignal::new(false);
let closing = RwSignal::new(false);
let panel = NodeRef::new();
// Reacts to the edges of `open`: true mounts, a change to false starts closing.
let watching = RenderEffect::new(move |was: Option<bool>| {
let now = open.get();
if now {
closing.set(false);
mounted.set(true);
} else if was == Some(true) {
closing.set(true);
}
now
});
on_cleanup_local(move || drop(watching));
view! {
if move || mounted.get() {
box(
class = "panel",
class:closing = move || closing.get(),
node_ref = panel,
on:transition_end = move |_| {
// Two properties transition; unmount after the last one.
if closing.get_untracked() && panel.running_animations() == 0 {
mounted.set(false);
}
}
) {
{children.view()}
}
}
}
}- The keyframe animation runs the entrance on the frame the panel is created.
- The resting
transform: translateX(0px)keeps both entrance and exit on the placement path. class:closingchanges two computed values, so two transitions start.on:transition_endfires twice; the first timerunning_animations()is still 1.- Reopening during the exit sets
closingback to false. The transitions reverse from where they are, and the element is never unmounted. - The duration is defined only in the style sheet.
If the class change starts no transition (the sheet failed to install, the duration is zero, the
property is not declared), transition_end never fires and the invisible element stays mounted.
Arm a fallback timeout when you set closing:
let pending = StoredValue::new_local(None::<TimeoutHandle>);
let clock = Timers::current().expect("a component body is inside a window");
// in the effect, where `closing` is set
pending.set_value(Some(clock.set_timeout(Duration::from_secs(1), move || mounted.set(false))));Overwriting or dropping pending cancels the timeout.
Animate from Rust
There is no imperative animation object. For a value that CSS cannot express, drive a signal from
request_frame. The callback runs once, early in the next frame (before animations are sampled and
before the restyle), and receives that frame's Timestamp. While a request is pending, the window
renders at the display's refresh rate. Request again from the callback to run every frame.
use zgui::view::FrameHandle;
fn spin(timers: Timers, angle: RwSignal<f32>, pending: StoredValue<Option<FrameHandle>, LocalStorage>) {
let next = timers.clone();
pending.set_value(Some(timers.request_frame(move |now| {
// Derive the value from the timestamp, so a slow frame is one bigger step.
angle.set((now.since_origin().as_secs_f32() * 90.0) % 360.0);
spin(next, angle, pending);
})));
}
#[component]
fn Sweep() -> impl IntoView {
let angle = RwSignal::new(0.0f32);
// Dropped with the component, which cancels the pending request.
let pending = StoredValue::new_local(None::<FrameHandle>);
spin(Timers::current().expect("a component body is inside a window"), angle, pending);
view! {
box(
class = "sweep",
style:transform = move || Some(format!("rotate({}deg)", angle.get()))
)
}
}Each write replaces an inline declaration, so the element takes the cascade path every frame. The
same rotation written as @keyframes takes the placement path. See
UI tasks and timers for the full
request_frame API.
Not supported
| Feature | State |
|---|---|
animation-timeline, animation-range-start, animation-range-end, animation-composition | parsed and ignored; there are no scroll-driven animations |
prefers-reduced-motion | not a supported media feature, and an @media rule using it is dropped. Detect the preference yourself and set an attribute or class on the root, for example [reduced-motion] .toast { animation: none } |