Motion and tweening

Day animates in two ways, and they share one vocabulary.

  • The platform animates. A change made inside with_animation or under .animation(..) reaches the toolkit with an AnimSpec, and the toolkit plays it on its own animator. The animation contract says exactly what it plays.
  • Day animates. day::motion steps values on the window’s frame clock, and views or a canvas read them. This is the path for a staggered entrance, a spring that starts at the speed a finger released it with, a value that drives several properties through an interpolation, and anything a canvas draws.
use day::motion::{Animated, Animation, Ease, Easing, Spring};

let fade = Animated::new(1.0);
let lift = Animated::new(0.0);
column((
    label(res::str::title()).opacity(fade).translation(0.0, lift),
    button(res::str::hide()).action(move || {
        Animation::parallel([
            Animation::timing(fade, 0.0, 220, Easing::EASE_IN_OUT),
            Animation::spring(lift, -24.0, Spring::new(320.0, 22.0)),
        ])
        .start();
    }),
))

The UI snippets use generated res::str accessors from an app’s Fluent catalog; see the example messages and catalog setup.

Animated

Animated<T> is a reactive value that animations move. T is a number by default and can be anything with a Lerp: a color, a point, a rect, a Vec of them. It is the one animated-value type in Day.

One owner at a time: the latest animation step or set to touch a value owns it, and an earlier step on the same value ends without moving it further.

Animation

An Animation is one step or a composition of steps. Building one moves nothing, and it can be started any number of times.

StepWhat it does
Animation::timing(value, to, ms, easing)moves value to to over ms milliseconds along an Easing
Animation::tween(value, to, spec)moves value to to as an AnimSpec says: delay, curve or spring, repeats, autoreverse
Animation::spring(value, to, spring)springs a number to to from the velocity it has, until it rests
Animation::decay(value, decay)lets a number coast from the velocity it has until it stops
Animation::drive(spec, step)calls step with each frame’s AnimSample of spec, for a transition that is more than one value
Animation::delay(ms)waits
CompositionWhat it does
Animation::sequence(steps)runs the steps one after another; each starts from where its value stands when its turn comes
Animation::parallel(steps)runs them together and ends with the last
Animation::stagger(gap_ms, steps)runs them together, each starting gap_ms after the one before
.repeat(times)plays the animation times times in a row
.looped()plays it again each time it ends, until it is stopped
let lifts: Vec<Animated> = (0..5).map(|_| Animated::new(0.0)).collect();
let entrance = Animation::stagger(
    70,
    lifts.iter().map(|&lift| {
        Animation::sequence([
            Animation::timing(lift, -46.0, 220, Easing::Power(Ease::Out, 2.0)),
            Animation::spring(lift, 0.0, Spring::new(320.0, 11.0)),
        ])
    }),
);

A step that ends part-way through a frame hands the rest of the frame to the step after it, so a sequence, a stagger and a loop keep exact time however the frames fall.

Playing

start() plays the animation on the window of the first value it moves and answers a Playing handle; start_on(clock) names the window.

  • stop() stops it where it stands.
  • reset() stops it and puts every value back where it was when it started.
  • Awaiting the handle answers an Outcome: Finished when the animation played to its end, Stopped when something ended it first. on_end(f) is the callback form.
  • jump_to_end() on the animation puts every value on its end state without playing.
let playing = entrance.start();
day::task(async move {
    if playing.await == Outcome::Finished {
        status.set(Status::Arrived);
    }
});

The animation does not depend on the handle: dropping it leaves the animation running.

What the framework handles

  • Reduced motion (accessibility: the user’s system setting, or a run that forced it with --fast / DAY_REDUCE_MOTION=1). A finite animation puts every value on its end state at once and reports Finished, also when the setting flips mid-flight. An animation that never ends by itself (a looped() pulse, a spec that repeats forever) keeps running: a spinner is the one sign that work is going on. Check day::reduce_motion() before starting a loop that is decoration only.
  • Scope cleanup. An animation stops, with Stopped, when a value it moves is disposed with its scope or its window closes. A page needs no cleanup of its own.
  • One pass per frame. Every animation of a window advances inside one batch per display frame, so a view bound to several animated values rebuilds its Transform once per frame and the toolkit receives one set_transform, however many values moved. The window requests no frames once nothing is animating.

Interpolation

Interpolation::new(input, output) maps one range onto another through any number of stops: [0, 120] of scroll onto [1, 0] of opacity. The output is anything with a Lerp, so the same call maps onto colors, which blend in OKLab. Outside the input range the map clamps; .extend() lets the outer segments run on (extend_start and extend_end choose a side).

Animated::interpolate(input, output) is the reactive form: a closure for any modifier that takes a reactive value, so one animated number drives several properties.

let scroll = Animated::new(0.0);
header
    .opacity(scroll.interpolate([0.0, 120.0], [1.0, 0.0]))
    .background(scroll.interpolate([0.0, 120.0], [Color::WHITE, accent]));

The animation contract

An AnimSpec means the same thing on every toolkit and on the frame-driven path. A change from the value on screen (the start) to the new value (the target) plays as follows.

FieldMeaning
delay_msThe start value is held this long before the first cycle. Served once, never between repeats.
duration_msThe length of one cycle. Zero applies the target at once (after the delay).
curveThe shape of one cycle: Linear is t, EaseIn is t², EaseOut is 1 - (1 - t)², EaseInOut is t²(3 - 2t), and Spring is a physical spring.
repeatCycles beyond the first. u32::MAX repeats until the property is next changed.
autoreverseEvery second cycle plays backwards, from the target to the start.
  • Rest. When a finite run ends the property rests on the target, whatever the last cycle did. A run that ends on a backward cycle (autoreverse with an odd repeat) is followed by a jump to the target; use an even repeat to end on a forward one.
  • Spring. Curve::Spring { response, damping } is the spring of SwiftUI’s .spring(response:dampingFraction:): response is the period of its undamped oscillation in seconds and damping its damping ratio (1 is critically damped, below 1 overshoots). Its position is the closed-form response Curve::fraction evaluates. AnimSpec::spring sets duration_ms to the spring’s settle time (Curve::settle_secs: the time after which it stays within a thousandth of its travel), and the cycle ends exactly on its end value. A spring is therefore longer than its response: spring(0.4, 0.8) settles in about 0.59 s.
  • Retarget. A new change to a property in flight starts from the value on screen. A change with no animation cancels the run and applies at once.
  • What animates. Frame, opacity, transform, and a container’s background color, whose in-between colors lie between the two ends in every channel.

AnimSpec::sample(elapsed) is this timeline as a function: the progress elapsed seconds after the change and whether the run is over. total_secs() is the run’s length, or None for a spec that repeats forever. Animation::tween and Animated::animate_to run on it, so a canvas value moved with the spec a native property is animated with moves in step with it.

A toolkit plays the contract on its own animator. Where the platform has a spring animator it takes Curve::spring_constants (stiffness and damping for a mass of 1); everywhere else it plays AnimSpec::keyframes(), one forward cycle sampled sixty times a second, through a keyframe animation or a custom interpolator, so every toolkit draws the same spring. day::motion::Spring::from_response(response, damping) is the same spring for the frame-driven path, and spring.curve() converts back.

Toolkit support

Cap::Animation says whether the toolkit animates at all; where it is Unsupported an animated change applies at once. The conformance cases animation-delay-holds-the-start, animation-repeat-plays-every-cycle, animation-autoreverse-plays-back, animation-repeats-forever-until-set, animation-retargets-from-the-value-shown, animation-spring-overshoots-and-settles, animation-frame-passes-between and animation-background-passes-between read each property mid-flight through assert_displayed and compare it with AnimSpec::sample.

ToolkitDelayRepeat and autoreverseSpringBackground colorMid-flight read-backLimitations
AppKityesyesCASpringAnimation from macOS 14; Day’s keyframes for an over-damped spring on macOS 13 and for a spring that scales or turnsyes, on the view’s layer for the runopacity, frame, translation, backgroundA gradient fill, and a change to or from no fill, apply at once.
UIKityesyesCASpringAnimation; Day’s keyframes for a background coloryesopacity, frame, translation, backgroundA change to or from no color applies at once.
GTKyesyesthe physical spring, sampled each frameyes, blended per sRGB channelopacity, frame, translation, backgroundDay steps every animated property on the frame clock, since GTK has no property animator, so animations run on the main thread and stall with it. A spring’s opacity overshoot is clipped to 0 to 1. A fill animation rewrites the surface’s CSS each frame. An unmapped widget, a list row’s content and a stacked navigation host take a new frame at once. A transform interpolates translation, scale and rotation one component at a time, in a straight line.
QtyesyesDay’s keyframesyesopacity, frame, translation, backgroundA host whose frame Qt owns (navigation, suite, split, inspector, list) takes a new frame at once. A transform that draws outside the widget is clipped to the parent widget’s rect.
WinUIyesyesDay’s keyframes in a storyboardyesopacity, frame, translation, background
AndroidyesyesDay’s keyframes through an interpolatoryesopacity, frame, translation, backgroundA view’s first placement applies at once.
ArkUIyesyes; a finite run plays as one curve over all its cyclesDay’s spring as a custom curveyesnone: the C API reads back the values set, not the values shownA change to or from no background applies at once.
WebyesyesDay’s keyframes in a Web Animationyesopacity, frame, translation, backgroundA background from no fill applies at once.

Lerp

Lerp is how a value moves between two states: a.lerp(&b, t) is a at t = 0 and b at t = 1. It is implemented for f64, f32, Point, Size, Rect, Color, Ink, Angle, tuples of two and three, arrays and Vecs (element-wise over the common prefix, the target’s tail taken as is), and Option (interpolated when both are present, switched at the midpoint otherwise). t may leave 0..=1: an under-damped spring overshoots, and a number follows it past the target and back.

Colors blend in OKLab, alpha linearly. The midpoint of blue and yellow is a clean mid-lightness color rather than sRGB’s dim gray, and a sequential scale’s in-between colors read as in-between values. The endpoints are returned exactly. An Ink blends each appearance separately, so a pair mid-flight still follows an appearance switch, and a role is resolved against both appearances first; the endpoints are the inks themselves (color.md “Inks in motion”). An Angle moves along the number line, not the short way round: normalize first for the short arc. mix_oklab(a, b, t) is the same blend as a function.

stagger(spec, index, count, spread_ms) delays an AnimSpec for item index of count so the first starts on time and the last spread_ms later: one spec per bar of a chart, for a with_animation or a tween each.

Pairs

When what changed is a collection (the bars of a chart, the cards on a table, the tiles of a board), the first question is which item became which. Pairs::by_key(from, to, key, absent) answers it once per change:

use day::tween::{Change, Pairs};

let pairs = Pairs::by_key(&before, &after, |bar| bar.name.clone(), |bar, change| match change {
    Change::Entering => bar.at_baseline(), // grows from zero
    _ => bar.at_baseline().faded(),        // shrinks away
});
// Each frame:
let bars = pairs.at(progress);
  • An item whose key is on both sides is Kept and moves from where it was to where it is. Keys may repeat: the nth item with a key on one side matches the nth on the other, so identical tokens pair up in order.
  • An item only in to is Entering, and absent(item, Change::Entering) says where it starts. One only in from is Leaving, and absent(item, Change::Leaving) says where it goes. That stand-in is the whole meaning of arriving and departing (grown from a baseline, slid in beside a neighbor, faded) and it is the caller’s to choose.
  • The result is in to’s order, then the leaving items in from’s order.

at(t) interpolates every item with its Lerp. at_with(t, f) hands each Pair and t to a closure, for items whose in-between needs more context than their two ends. at_each(progress, f) gives each item its own t, for sequences that do not move in lockstep. settled() is the arriving state without the leaving items: what to draw once the transition is over.

When the caller’s own rules already know what moved where (a sliding-tile game knows which two tiles merged into which cell, which no key match could say), it collects its Pairs directly: Pairs implements FromIterator<Pair<T>>.

Composite transitions

A chart, a graph or a map changes many values at once, and what they mean decides how they should move. day-piece-charts is the worked example: its animate.rs pairs marks and axis ticks across two resolved charts with Pairs::by_key, keyed by what they encode, interpolates values in data space while the scales’ domains move, re-stacks stacked marks every frame, and gives entering and leaving marks a meaning (a bar grows from its baseline, a line’s new samples unfold along the old line). It drives the whole blend with one Animation::drive per change and reads current_anim() so that a change made inside with_animation animates with the caller’s spec, the same contract native widgets keep.

Easing, springs and decay

Animation steps are built from three small values, and an app can also step them itself:

  • A curve the native animators do not carry. Easing maps progress to eased progress for linear, a CSS cubic Bézier, power, sine, circle, exponential, back, elastic and bounce curves, in, out or both ways where that applies. Easing::Back(Ease::Out, 1.70158).value(t) overshoots by a tenth before it settles; samples(n) gives the curve as points for plotting it.
  • A spring that keeps its velocity. Spring has a stiffness, a damping and a mass, and spring.step(&mut state, target, dt) advances a SpringState (a value and its velocity) by one frame. Because the velocity lives in the state, a spring started with the speed a finger released a view at carries that speed on, and a new target bends the motion instead of restarting it. settled says when to stop asking for frames.
  • A fling that coasts. Decay loses a fixed share of the velocity per millisecond, as a scroll view decelerates.

They are plain numbers: nothing in them touches a view or a clock. Animation::timing, Animation::spring and Animation::decay are the usual way to run them. A simulation with rules of its own (a drag that springs back only past a threshold, bodies that collide) steps them from a FrameClock subscription with the frame’s delta and writes the result into an Animated or a signal:

use day::motion::{Spring, SpringState};

let spring = Spring::new(180.0, 11.0);
let mut x = SpringState { value: start, velocity: release_velocity };
FrameClock::current().subscribe(move |frame| {
    spring.step(&mut x, 0.0, frame.delta.as_secs_f64());
    offset.set(x.value);
    if spring.settled(x, 0.0) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
});

Motion stepped this way is the app’s own: read day::reduce_motion() and write the target at once instead of starting the subscription.

Tests live in day-core/src/motion.rs (the driver on a manual frame source: timing, sequences that carry time across steps, stagger, repeat and loop, springs and decay with velocity, ownership of a value, reset, scope disposal, the awaitable handle, one binding pass per frame, interpolation), day-spec (anim_tests: the timeline across delay, repeat, autoreverse and springs, settle time, keyframes) and day-core/src/tween.rs (interpolation and OKLab endpoints, staggering, and Pairs: classification and order, the stand-in callback, repeated keys, empty sides, permutations, sampling past the end, per-item progress, many-to-one pairs collected directly, and a randomized check that every item of either side is accounted for exactly once).