Skip to main content

day_core/
motion.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Frame-driven motion (docs/tween.md): values that animate, the animations that move them, and
5//! the math underneath.
6//!
7//! [`with_animation`](crate::with_animation) hands a change to the platform's animator. This
8//! module is the other path: Day steps the numbers itself on the window's
9//! [`FrameClock`] and views or a canvas read them. It has three layers,
10//! each usable without the one above:
11//!
12//! * [`Animated`]: a reactive value with a velocity. A `.opacity(..)`, a `.translation(..)` or
13//!   a canvas reading it follows its motion, and it is the one animated-value type in Day.
14//! * [`Animation`]: what moves values. [`timing`](Animation::timing) along an [`Easing`],
15//!   [`tween`](Animation::tween) under an [`AnimSpec`], [`spring`](Animation::spring) and
16//!   [`decay`](Animation::decay) with the value's own velocity, composed with
17//!   [`sequence`](Animation::sequence), [`parallel`](Animation::parallel),
18//!   [`stagger`](Animation::stagger), [`repeat`](Animation::repeat) and
19//!   [`looped`](Animation::looped). [`start`](Animation::start) answers a [`Playing`] handle
20//!   that stops it, resets it, and can be awaited.
21//! * The math: [`Easing`], [`Spring`] with [`SpringState`], [`Decay`] and [`Interpolation`],
22//!   plain allocation-free values an app can also step itself from a frame callback.
23//!
24//! Reduced motion and scope cleanup are handled here once: a finite animation lands on its end
25//! state when the user asked for less motion, and an animation stops when a value it moves is
26//! disposed with its scope.
27
28use std::any::Any;
29use std::cell::{Cell, RefCell};
30use std::future::Future;
31use std::ops::ControlFlow;
32use std::pin::Pin;
33use std::rc::Rc;
34use std::task::{Context, Poll, Waker};
35
36use day_reactive::Signal;
37use day_spec::{AnimSample, AnimSpec, Curve};
38
39use crate::frame::{FrameClock, FrameHandle};
40use crate::tween::Lerp;
41
42use std::f64::consts::PI;
43
44/// Which end of a curve is shaped: the start, the end, or both.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Ease {
47    /// Slow at the start.
48    In,
49    /// Slow at the end.
50    Out,
51    /// Slow at both ends.
52    InOut,
53}
54
55/// An easing curve: a function from progress (0 to 1) to eased progress. Back and elastic
56/// curves leave that range on purpose, which is the overshoot they exist to show.
57#[derive(Clone, Copy, Debug, PartialEq)]
58pub enum Easing {
59    /// Progress unchanged.
60    Linear,
61    /// A CSS-style cubic Bézier through (0, 0) and (1, 1) with these two control points.
62    Bezier(f64, f64, f64, f64),
63    /// A power curve: 2 is quadratic, 3 cubic.
64    Power(Ease, f64),
65    /// A quarter of a sine wave.
66    Sine(Ease),
67    /// A quarter of a circle.
68    Circle(Ease),
69    /// An exponential curve.
70    Exponential(Ease),
71    /// A curve that backs up past its start or runs past its end by `overshoot`
72    /// (1.70158 overshoots by a tenth).
73    Back(Ease, f64),
74    /// A spring-like wobble around the end, `bounciness` 1 for the classic curve.
75    ElasticOut(f64),
76    /// A ball dropped on the end value.
77    BounceOut,
78}
79
80impl Easing {
81    /// The CSS `ease` curve.
82    pub const EASE: Easing = Easing::Bezier(0.25, 0.1, 0.25, 1.0);
83    /// The CSS `ease-in-out` curve.
84    pub const EASE_IN_OUT: Easing = Easing::Bezier(0.42, 0.0, 0.58, 1.0);
85
86    /// The eased value at progress `t`, which is clamped to 0..=1 first.
87    #[must_use]
88    pub fn value(self, t: f64) -> f64 {
89        let t = t.clamp(0.0, 1.0);
90        match self {
91            Easing::Linear => t,
92            Easing::Bezier(x1, y1, x2, y2) => bezier(t, x1, y1, x2, y2),
93            Easing::Power(ease, power) => shaped(ease, t, |t| t.powf(power)),
94            Easing::Sine(ease) => shaped(ease, t, |t| 1.0 - (t * PI / 2.0).cos()),
95            Easing::Circle(ease) => shaped(ease, t, |t| 1.0 - (1.0 - t * t).max(0.0).sqrt()),
96            Easing::Exponential(ease) => shaped(ease, t, |t| {
97                if t <= 0.0 {
98                    0.0
99                } else {
100                    2f64.powf(10.0 * (t - 1.0))
101                }
102            }),
103            Easing::Back(ease, overshoot) => {
104                shaped(ease, t, |t| t * t * ((overshoot + 1.0) * t - overshoot))
105            }
106            Easing::ElasticOut(bounciness) => {
107                if t <= 0.0 || t >= 1.0 {
108                    t
109                } else {
110                    let p = bounciness.max(0.01) * PI;
111                    1.0 - (t * PI / 2.0).cos().powi(3) * (t * p).cos()
112                }
113            }
114            Easing::BounceOut => bounce(t),
115        }
116    }
117
118    /// The curve sampled at `count` evenly spaced points from 0 to 1, for plotting it.
119    #[must_use]
120    pub fn samples(self, count: usize) -> Vec<f64> {
121        let last = count.saturating_sub(1).max(1) as f64;
122        (0..count).map(|i| self.value(i as f64 / last)).collect()
123    }
124}
125
126/// An ease-in function turned into the asked-for mode.
127fn shaped(ease: Ease, t: f64, ease_in: impl Fn(f64) -> f64) -> f64 {
128    match ease {
129        Ease::In => ease_in(t),
130        Ease::Out => 1.0 - ease_in(1.0 - t),
131        Ease::InOut => {
132            if t < 0.5 {
133                ease_in(t * 2.0) / 2.0
134            } else {
135                1.0 - ease_in((1.0 - t) * 2.0) / 2.0
136            }
137        }
138    }
139}
140
141fn bounce(t: f64) -> f64 {
142    const N: f64 = 7.5625;
143    const D: f64 = 2.75;
144    if t < 1.0 / D {
145        N * t * t
146    } else if t < 2.0 / D {
147        let t = t - 1.5 / D;
148        N * t * t + 0.75
149    } else if t < 2.5 / D {
150        let t = t - 2.25 / D;
151        N * t * t + 0.9375
152    } else {
153        let t = t - 2.625 / D;
154        N * t * t + 0.984_375
155    }
156}
157
158/// The y of a unit cubic Bézier at the x `x`, solved by Newton's method with a bisection
159/// fallback, as browsers evaluate `cubic-bezier()`.
160fn bezier(x: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
161    let axis = |t: f64, a: f64, b: f64| {
162        let u = 1.0 - t;
163        3.0 * u * u * t * a + 3.0 * u * t * t * b + t * t * t
164    };
165    let slope = |t: f64, a: f64, b: f64| {
166        let u = 1.0 - t;
167        3.0 * u * u * a + 6.0 * u * t * (b - a) + 3.0 * t * t * (1.0 - b)
168    };
169    let mut t = x;
170    for _ in 0..8 {
171        let error = axis(t, x1, x2) - x;
172        if error.abs() < 1e-6 {
173            return axis(t, y1, y2);
174        }
175        let d = slope(t, x1, x2);
176        if d.abs() < 1e-6 {
177            break;
178        }
179        t = (t - error / d).clamp(0.0, 1.0);
180    }
181    let (mut lo, mut hi) = (0.0, 1.0);
182    t = x;
183    for _ in 0..24 {
184        let at = axis(t, x1, x2);
185        if (at - x).abs() < 1e-6 {
186            break;
187        }
188        if at < x {
189            lo = t;
190        } else {
191            hi = t;
192        }
193        t = f64::midpoint(lo, hi);
194    }
195    axis(t, y1, y2)
196}
197
198/// A damped spring: what pulls a value toward its target.
199#[derive(Clone, Copy, Debug, PartialEq)]
200pub struct Spring {
201    /// How hard it pulls. Higher is faster.
202    pub stiffness: f64,
203    /// How much it resists motion. Lower overshoots more.
204    pub damping: f64,
205    /// The weight it moves. Higher is slower and overshoots more.
206    pub mass: f64,
207}
208
209impl Default for Spring {
210    /// A spring that settles without visible overshoot: stiffness 170, damping 26, mass 1.
211    fn default() -> Self {
212        Spring::new(170.0, 26.0)
213    }
214}
215
216impl Spring {
217    /// A spring of mass 1 with this stiffness and damping.
218    #[must_use]
219    pub const fn new(stiffness: f64, damping: f64) -> Self {
220        Spring {
221            stiffness,
222            damping,
223            mass: 1.0,
224        }
225    }
226
227    /// The spring with another mass.
228    #[must_use]
229    pub const fn mass(mut self, mass: f64) -> Self {
230        self.mass = mass;
231        self
232    }
233
234    /// The spring an [`AnimSpec::spring`] of this `response` (the period of the undamped
235    /// oscillation, in seconds) and damping `ratio` describes, with a mass of 1: the same
236    /// motion on the frame-driven path as a native spring animation of that spec.
237    #[must_use]
238    pub fn from_response(response: f64, ratio: f64) -> Self {
239        let (stiffness, damping) = Curve::Spring {
240            response,
241            damping: ratio,
242        }
243        .spring_constants()
244        .unwrap_or((170.0, 26.0));
245        Spring::new(stiffness, damping)
246    }
247
248    /// The spring as an animation curve: its response and damping ratio, for
249    /// [`AnimSpec`]. `AnimSpec::spring(response, ratio)` with these two is the native
250    /// animation that matches this spring released at rest.
251    #[must_use]
252    pub fn curve(self) -> Curve {
253        let mass = self.mass.max(1e-6);
254        let omega0 = (self.stiffness.max(0.0) / mass).sqrt().max(1e-6);
255        Curve::Spring {
256            response: std::f64::consts::TAU / omega0,
257            damping: self.damping / (2.0 * mass * omega0),
258        }
259    }
260
261    /// Advances `state` toward `target` by `dt` seconds. A long frame is split into steps of at
262    /// most a millisecond, so a stiff spring stays stable when the display stalls.
263    pub fn step(self, state: &mut SpringState, target: f64, dt: f64) {
264        let mut left = dt.clamp(0.0, 0.25);
265        let mass = self.mass.max(1e-6);
266        while left > 0.0 {
267            let h = left.min(0.001);
268            let force = -self.stiffness * (state.value - target) - self.damping * state.velocity;
269            state.velocity += force / mass * h;
270            state.value += state.velocity * h;
271            left -= h;
272        }
273    }
274
275    /// Whether `state` has come to rest on `target`: both its distance and its speed are below
276    /// what a display can show.
277    #[must_use]
278    pub fn settled(self, state: SpringState, target: f64) -> bool {
279        (state.value - target).abs() < 0.01 && state.velocity.abs() < 0.01
280    }
281
282    /// The spring's answer to a step from 0 to 1, sampled at `count` evenly spaced times over
283    /// `seconds`, for plotting it.
284    #[must_use]
285    pub fn response(self, seconds: f64, count: usize) -> Vec<f64> {
286        let mut state = SpringState::default();
287        let dt = seconds / count.saturating_sub(1).max(1) as f64;
288        (0..count)
289            .map(|i| {
290                if i > 0 {
291                    self.step(&mut state, 1.0, dt);
292                }
293                state.value
294            })
295            .collect()
296    }
297}
298
299/// Where a sprung value is and how fast it is moving, kept between steps.
300#[derive(Clone, Copy, Debug, Default, PartialEq)]
301pub struct SpringState {
302    /// The value now.
303    pub value: f64,
304    /// Its speed, in units per second.
305    pub velocity: f64,
306}
307
308impl SpringState {
309    /// A value at rest.
310    #[must_use]
311    pub const fn at(value: f64) -> Self {
312        SpringState {
313            value,
314            velocity: 0.0,
315        }
316    }
317}
318
319/// A fling that coasts: a velocity that keeps `rate` of itself every millisecond, as a scroll
320/// view decelerates. 0.998 is the platforms' usual scroll rate; lower stops sooner.
321#[derive(Clone, Copy, Debug, PartialEq)]
322pub struct Decay {
323    /// The share of the velocity kept per millisecond, below 1.
324    pub rate: f64,
325}
326
327impl Decay {
328    /// Advances `state` by `dt` seconds: the value moves by the distance covered while the
329    /// velocity fell.
330    pub fn step(self, state: &mut SpringState, dt: f64) {
331        let ms = (dt * 1000.0).clamp(0.0, 250.0);
332        let rate = self.rate.clamp(0.0, 0.999_999);
333        let k = rate.ln();
334        let factor = rate.powf(ms);
335        // The integral of v·rate^t over the step, in seconds.
336        state.value += state.velocity * (factor - 1.0) / k / 1000.0;
337        state.velocity *= factor;
338    }
339
340    /// Whether the fling has stopped: its speed is below a point per second.
341    #[must_use]
342    pub fn stopped(self, state: SpringState) -> bool {
343        state.velocity.abs() < 1.0
344    }
345
346    /// Where a fling from `state` comes to rest: the distance left is the velocity over the
347    /// share lost per second.
348    #[must_use]
349    pub fn rest(self, state: SpringState) -> f64 {
350        let k = self.rate.clamp(0.0, 0.999_999).ln();
351        state.value - state.velocity / k / 1000.0
352    }
353}
354
355// ---------------------------------------------------------------------------
356// Interpolation: one range mapped onto another
357// ---------------------------------------------------------------------------
358
359/// A piecewise-linear map from an input range onto an output range: `[0, 120]` of scroll onto
360/// `[1, 0]` of opacity, or onto two colors.
361///
362/// The output is anything with a [`Lerp`]: numbers, points, rects, and colors, which blend in
363/// OKLab. Outside the input range the map clamps to the nearest end unless
364/// [`extend`](Interpolation::extend) lets the outer segments run on.
365///
366/// ```rust,ignore
367/// let fade = Interpolation::new([0.0, 120.0], [1.0, 0.0]);
368/// assert_eq!(fade.at(60.0), 0.5);
369/// let heat = Interpolation::new([0.0, 0.5, 1.0], [BLUE, WHITE, RED]);
370/// ```
371///
372/// [`Animated::interpolate`] is the reactive form, for a modifier that follows a value.
373#[derive(Clone, Debug, PartialEq)]
374pub struct Interpolation<T: Lerp> {
375    /// The first stop, which every map has.
376    first: (f64, T),
377    /// The stops after it, by ascending input.
378    rest: Vec<(f64, T)>,
379    /// Whether the first segment runs on below the range.
380    extend_start: bool,
381    /// Whether the last segment runs on above the range.
382    extend_end: bool,
383}
384
385impl<T: Lerp> Interpolation<T> {
386    /// The map through `input[i]` → `output[i]`. The inputs ascend; a map of one stop is
387    /// constant. An empty map does not compile.
388    #[must_use]
389    pub fn new<const N: usize>(input: [f64; N], output: [T; N]) -> Self {
390        const { assert!(N >= 1, "an interpolation needs at least one stop") };
391        let mut stops = input.into_iter().zip(output);
392        let Some(first) = stops.next() else {
393            unreachable!("N >= 1 is asserted at compile time")
394        };
395        Interpolation {
396            first,
397            rest: stops.collect(),
398            extend_start: false,
399            extend_end: false,
400        }
401    }
402
403    /// Lets both outer segments run on past the range instead of clamping. A color's channels
404    /// still stay in range.
405    #[must_use]
406    pub fn extend(mut self) -> Self {
407        self.extend_start = true;
408        self.extend_end = true;
409        self
410    }
411
412    /// Lets the first segment run on below the range.
413    #[must_use]
414    pub fn extend_start(mut self) -> Self {
415        self.extend_start = true;
416        self
417    }
418
419    /// Lets the last segment run on above the range.
420    #[must_use]
421    pub fn extend_end(mut self) -> Self {
422        self.extend_end = true;
423        self
424    }
425
426    /// The output at `x`.
427    #[must_use]
428    pub fn at(&self, x: f64) -> T {
429        let mut lo = &self.first;
430        let Some(mut hi) = self.rest.first() else {
431            return lo.1.clone();
432        };
433        if x < lo.0 && !self.extend_start {
434            return lo.1.clone();
435        }
436        // The segment holding `x`: the last one when `x` is past the end.
437        for stop in self.rest.iter().skip(1) {
438            if x <= hi.0 {
439                break;
440            }
441            lo = hi;
442            hi = stop;
443        }
444        if x > hi.0 && !self.extend_end {
445            return hi.1.clone();
446        }
447        let span = hi.0 - lo.0;
448        if span <= 0.0 {
449            return if x < lo.0 { lo.1.clone() } else { hi.1.clone() };
450        }
451        lo.1.lerp(&hi.1, (x - lo.0) / span)
452    }
453}
454
455// ---------------------------------------------------------------------------
456// Animated: a value that moves
457// ---------------------------------------------------------------------------
458
459/// What an [`Animated`] keeps beside its value: bookkeeping no view reads.
460struct Slot<T> {
461    /// Where the value is headed, or the value itself at rest.
462    target: T,
463    /// Counts every animation step and every `set` that took the value over. A step whose
464    /// number is no longer current has been displaced and stops writing.
465    claim: u64,
466    /// The flight `animate_to` started, to stop when the next one begins.
467    flight: Option<Playing>,
468    /// The window whose frames move the value.
469    clock: FrameClock,
470}
471
472/// A reactive value that animations move: a number with its velocity, or anything else with a
473/// [`Lerp`] (a color, a point, a rect, a `Vec` of them).
474///
475/// Reading it is a tracked read, so whatever reads it follows the motion and nothing else
476/// re-runs. It goes straight into any modifier that takes a reactive value:
477///
478/// ```rust,ignore
479/// let fade = Animated::new(1.0);
480/// let lift = Animated::new(0.0);
481/// label(res::str::title())
482///     .opacity(fade)
483///     .translation(0.0, lift);
484/// button(res::str::hide()).action(move || {
485///     Animation::parallel([
486///         Animation::timing(fade, 0.0, 220, Easing::EASE_IN_OUT),
487///         Animation::spring(lift, -24.0, Spring::new(320.0, 22.0)),
488///     ])
489///     .start();
490/// });
491/// ```
492///
493/// The value is `Copy`, like a `Signal`, and lives in the reactive scope it was made in: when
494/// that scope is disposed, animations moving it stop.
495///
496/// One owner at a time: the latest animation step or [`set`](Animated::set) to touch a value
497/// owns it, and an earlier step on the same value ends without moving it further. A spring
498/// that takes over reads the velocity the displaced step left, which is what makes a retarget
499/// bend the motion.
500pub struct Animated<T: Lerp + 'static = f64> {
501    /// The value on screen.
502    value: Signal<T>,
503    /// Its speed in units per second. Kept for numbers; zero for everything else.
504    velocity: Signal<f64>,
505    /// Whether an animation is moving it.
506    moving: Signal<bool>,
507    /// The bookkeeping.
508    slot: Signal<Slot<T>>,
509}
510
511#[expect(
512    clippy::expl_impl_clone_on_copy,
513    reason = "a derive would demand `T: Copy`, and the handle is `Copy` whatever it holds"
514)]
515impl<T: Lerp + 'static> Clone for Animated<T> {
516    fn clone(&self) -> Self {
517        *self
518    }
519}
520impl<T: Lerp + 'static> Copy for Animated<T> {}
521
522impl<T: Lerp + std::fmt::Debug + 'static> std::fmt::Debug for Animated<T> {
523    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
524        f.debug_struct("Animated")
525            .field("value", &self.try_now())
526            .finish_non_exhaustive()
527    }
528}
529
530impl<T: Lerp + 'static> Animated<T> {
531    /// A value at rest on `initial`, animating on the current page's window.
532    #[must_use]
533    pub fn new(initial: T) -> Self {
534        Self::on(FrameClock::current(), initial)
535    }
536
537    /// A value at rest on `initial`, animating on `clock`'s window.
538    #[must_use]
539    pub fn on(clock: FrameClock, initial: T) -> Self {
540        Animated {
541            value: Signal::new(initial.clone()),
542            velocity: Signal::new(0.0),
543            moving: Signal::new(false),
544            slot: Signal::new(Slot {
545                target: initial,
546                claim: 0,
547                flight: None,
548                clock,
549            }),
550        }
551    }
552
553    /// The value on screen now; tracked.
554    #[must_use]
555    pub fn get(self) -> T {
556        self.value.get()
557    }
558
559    /// The value on screen now, without subscribing.
560    #[must_use]
561    pub fn get_untracked(self) -> T {
562        self.value.get_untracked()
563    }
564
565    /// Where the value is headed (the value itself once it has arrived).
566    #[must_use]
567    pub fn target(self) -> T {
568        self.slot.with_untracked(|slot| slot.target.clone())
569    }
570
571    /// Whether an animation is moving the value; tracked, so a control can disable itself
572    /// while it is.
573    #[must_use]
574    pub fn is_animating(self) -> bool {
575        self.moving.get()
576    }
577
578    /// Puts the value at rest on `value`, taking it from any animation moving it.
579    pub fn set(self, value: T) {
580        self.claim(Some(value.clone()));
581        if let Some(flight) = self.take_flight() {
582            flight.stop();
583        }
584        self.value.set(value);
585        self.velocity.set_if_changed(0.0);
586        self.moving.set_if_changed(false);
587    }
588
589    /// Animates from the value on screen to `target` under `spec`: its delay, curve or spring,
590    /// repeats and autoreverse, as [`AnimSpec::sample`] defines them. A call while an earlier
591    /// one is in flight starts from the value on screen, so the motion bends instead of
592    /// jumping. Shorthand for starting [`Animation::tween`].
593    pub fn animate_to(self, target: T, spec: AnimSpec) -> Playing {
594        if let Some(flight) = self.take_flight() {
595            flight.stop();
596        }
597        let playing = Animation::tween(self, target, spec).start();
598        if !playing.is_finished() {
599            let flight = playing.clone();
600            self.slot.update(|slot| slot.flight = Some(flight));
601        }
602        playing
603    }
604
605    /// A reactive read of the value mapped through `input` → `output`
606    /// ([`Interpolation`]), clamped at both ends: a closure for any modifier that takes a
607    /// reactive value. Colors blend in OKLab.
608    ///
609    /// ```rust,ignore
610    /// let scroll = Animated::new(0.0);
611    /// header
612    ///     .opacity(scroll.interpolate([0.0, 120.0], [1.0, 0.0]))
613    ///     .background(scroll.interpolate([0.0, 120.0], [Color::WHITE, accent]));
614    /// ```
615    pub fn interpolate<U: Lerp + 'static, const N: usize>(
616        self,
617        input: [f64; N],
618        output: [U; N],
619    ) -> impl Fn() -> U + Clone + 'static
620    where
621        T: Into<f64>,
622    {
623        self.interpolate_with(Interpolation::new(input, output))
624    }
625
626    /// A reactive read of the value mapped through `map`, for a map that extends past its
627    /// ends or is shared.
628    pub fn interpolate_with<U: Lerp + 'static>(
629        self,
630        map: Interpolation<U>,
631    ) -> impl Fn() -> U + Clone + 'static
632    where
633        T: Into<f64>,
634    {
635        let map = Rc::new(map);
636        move || map.at(self.get().into())
637    }
638
639    /// The value, when its scope is still alive; untracked.
640    fn try_now(self) -> Option<T> {
641        day_reactive::untrack(|| self.value.try_get())
642    }
643
644    /// Takes the value over and answers the new claim number. `target` also records where
645    /// it is now headed.
646    fn claim(self, target: Option<T>) -> u64 {
647        let mut claim = 0;
648        self.slot.update(|slot| {
649            slot.claim += 1;
650            if let Some(target) = target {
651                slot.target = target;
652            }
653            claim = slot.claim;
654        });
655        claim
656    }
657
658    /// The flight `animate_to` last started, taken out of the slot.
659    fn take_flight(self) -> Option<Playing> {
660        let mut flight = None;
661        self.slot.update(|slot| flight = slot.flight.take());
662        flight
663    }
664
665    /// The window whose frames move the value, while its scope is alive.
666    fn clock(self) -> Option<FrameClock> {
667        day_reactive::untrack(|| self.slot.try_with(|slot| slot.clock))
668    }
669}
670
671impl Animated<f64> {
672    /// The value's speed in units per second; tracked. A spring and a decay start from it.
673    #[must_use]
674    pub fn velocity(self) -> f64 {
675        self.velocity.get()
676    }
677
678    /// Gives the value a speed without moving it: the velocity a finger released it with,
679    /// before a [`spring`](Animation::spring) or a [`decay`](Animation::decay) takes it on.
680    pub fn set_velocity(self, velocity: f64) {
681        self.velocity.set(velocity);
682    }
683}
684
685/// One animation step's hold on a value: it writes while its claim is current.
686struct Hold<T: Lerp + 'static> {
687    /// The value held.
688    value: Animated<T>,
689    /// The claim this step made.
690    claim: u64,
691}
692
693impl<T: Lerp + 'static> Hold<T> {
694    /// Takes `value` for a step headed to `target`, starting from where it stands. `None`
695    /// when the value's scope is gone.
696    fn take(value: Animated<T>, target: Option<T>) -> Option<(Self, T)> {
697        let from = value.try_now()?;
698        let claim = value.claim(target);
699        value.moving.set_if_changed(true);
700        Some((Hold { value, claim }, from))
701    }
702
703    /// Whether the step still owns the value: `Some(true)` to write, `Some(false)` when
704    /// displaced, `None` when the value is gone.
705    fn owns(&self) -> Option<bool> {
706        day_reactive::untrack(|| self.value.slot.try_with(|slot| slot.claim == self.claim))
707    }
708
709    /// Writes the value mid-flight, keeping a number's velocity from the change.
710    fn write(&self, next: T, dt: f64) {
711        if dt > 0.0
712            && let Some(next) = (&next as &dyn Any).downcast_ref::<f64>()
713            && let Some(prev) = self
714                .value
715                .try_now()
716                .as_ref()
717                .and_then(|p| (p as &dyn Any).downcast_ref::<f64>().copied())
718        {
719            self.value.velocity.set((next - prev) / dt);
720        }
721        self.value.value.set(next);
722    }
723
724    /// Puts the value at rest on `end` and gives it up.
725    fn land(&self, end: T) {
726        self.value.value.set(end);
727        self.value.velocity.set_if_changed(0.0);
728        self.release();
729    }
730
731    /// Gives the value up where it stands, if the step still owns it.
732    fn release(&self) {
733        if self.owns() == Some(true) {
734            self.value.moving.set_if_changed(false);
735        }
736    }
737}
738
739// ---------------------------------------------------------------------------
740// Animation: steps and their composition
741// ---------------------------------------------------------------------------
742
743/// How a frame left a step.
744#[derive(Clone, Copy, Debug, PartialEq)]
745enum Flow {
746    /// It has more to do.
747    Running,
748    /// It ended, with this many seconds of the frame unused: the step after it starts that
749    /// far in, so a sequence or a loop keeps exact time.
750    Ended(f64),
751    /// A value it moves was disposed with its scope: the whole animation stops.
752    Gone,
753}
754
755/// One step on one value (or one closure): the leaves of an [`Animation`].
756trait Leaf {
757    /// The step, started now. `None` when its value is gone.
758    fn begin(&self) -> Option<Box<dyn LeafRun>>;
759    /// Puts the step's value where the step would leave it.
760    fn finish(&self);
761    /// Whether the step never ends by itself.
762    fn endless(&self) -> bool {
763        false
764    }
765    /// A closure that puts the step's value back where it is now.
766    fn snapshot(&self) -> Option<Box<dyn Fn()>> {
767        None
768    }
769    /// The window whose frames should drive the step.
770    fn clock(&self) -> Option<FrameClock> {
771        None
772    }
773}
774
775/// A [`Leaf`] in flight.
776trait LeafRun {
777    /// Advances by `dt` seconds.
778    fn advance(&mut self, dt: f64) -> Flow;
779    /// Gives up the value where it stands: the animation was stopped.
780    fn release(&self);
781}
782
783/// A snapshot closure for a value: restores it and its velocity.
784fn snapshot_of<T: Lerp + 'static>(value: Animated<T>) -> Option<Box<dyn Fn()>> {
785    let at = value.try_now()?;
786    let velocity = day_reactive::untrack(|| value.velocity.try_get())?;
787    Some(Box::new(move || {
788        value.set(at.clone());
789        value.velocity.set_if_changed(velocity);
790    }))
791}
792
793/// `value` to `to` over `secs` along `easing`.
794struct TimingLeaf<T: Lerp + 'static> {
795    value: Animated<T>,
796    to: T,
797    secs: f64,
798    easing: Easing,
799}
800
801impl<T: Lerp + 'static> Leaf for TimingLeaf<T> {
802    fn begin(&self) -> Option<Box<dyn LeafRun>> {
803        let (hold, from) = Hold::take(self.value, Some(self.to.clone()))?;
804        Some(Box::new(TimingRun {
805            hold,
806            from,
807            to: self.to.clone(),
808            secs: self.secs,
809            easing: self.easing,
810            elapsed: 0.0,
811        }))
812    }
813    fn finish(&self) {
814        self.value.set(self.to.clone());
815    }
816    fn snapshot(&self) -> Option<Box<dyn Fn()>> {
817        snapshot_of(self.value)
818    }
819    fn clock(&self) -> Option<FrameClock> {
820        self.value.clock()
821    }
822}
823
824struct TimingRun<T: Lerp + 'static> {
825    hold: Hold<T>,
826    from: T,
827    to: T,
828    secs: f64,
829    easing: Easing,
830    elapsed: f64,
831}
832
833impl<T: Lerp + 'static> LeafRun for TimingRun<T> {
834    fn advance(&mut self, dt: f64) -> Flow {
835        self.elapsed += dt;
836        let left = self.elapsed - self.secs;
837        match self.hold.owns() {
838            None => Flow::Gone,
839            // Displaced: the step keeps its time, so what follows it is not brought forward.
840            Some(false) if left >= 0.0 => Flow::Ended(left.min(dt)),
841            Some(false) => Flow::Running,
842            Some(true) if left >= 0.0 => {
843                self.hold.land(self.to.clone());
844                Flow::Ended(left.min(dt))
845            }
846            Some(true) => {
847                let t = self.easing.value(self.elapsed / self.secs);
848                self.hold.write(self.from.lerp(&self.to, t), dt);
849                Flow::Running
850            }
851        }
852    }
853    fn release(&self) {
854        self.hold.release();
855    }
856}
857
858/// `value` to `to` under an [`AnimSpec`]'s whole timeline.
859struct TweenLeaf<T: Lerp + 'static> {
860    value: Animated<T>,
861    to: T,
862    spec: AnimSpec,
863}
864
865impl<T: Lerp + 'static> Leaf for TweenLeaf<T> {
866    fn begin(&self) -> Option<Box<dyn LeafRun>> {
867        let (hold, from) = Hold::take(self.value, Some(self.to.clone()))?;
868        Some(Box::new(TweenRun {
869            hold,
870            from,
871            to: self.to.clone(),
872            spec: self.spec,
873            elapsed: 0.0,
874        }))
875    }
876    fn finish(&self) {
877        self.value.set(self.to.clone());
878    }
879    fn endless(&self) -> bool {
880        self.spec.repeats_forever()
881    }
882    fn snapshot(&self) -> Option<Box<dyn Fn()>> {
883        snapshot_of(self.value)
884    }
885    fn clock(&self) -> Option<FrameClock> {
886        self.value.clock()
887    }
888}
889
890struct TweenRun<T: Lerp + 'static> {
891    hold: Hold<T>,
892    from: T,
893    to: T,
894    spec: AnimSpec,
895    elapsed: f64,
896}
897
898impl<T: Lerp + 'static> LeafRun for TweenRun<T> {
899    fn advance(&mut self, dt: f64) -> Flow {
900        self.elapsed += dt;
901        let sample = self.spec.sample(self.elapsed);
902        let left = self
903            .spec
904            .total_secs()
905            .map_or(0.0, |total| (self.elapsed - total).clamp(0.0, dt));
906        match self.hold.owns() {
907            None => Flow::Gone,
908            Some(false) if sample.done => Flow::Ended(left),
909            Some(false) => Flow::Running,
910            Some(true) if sample.done => {
911                // The value rests on its target whatever the last cycle did (rule 5 of the
912                // `AnimSpec` contract).
913                self.hold.land(self.to.clone());
914                Flow::Ended(left)
915            }
916            Some(true) => {
917                self.hold
918                    .write(self.from.lerp(&self.to, sample.progress), dt);
919                Flow::Running
920            }
921        }
922    }
923    fn release(&self) {
924        self.hold.release();
925    }
926}
927
928/// `value` sprung to `to` from its own velocity.
929struct SpringLeaf {
930    value: Animated<f64>,
931    to: f64,
932    spring: Spring,
933}
934
935impl Leaf for SpringLeaf {
936    fn begin(&self) -> Option<Box<dyn LeafRun>> {
937        let (hold, from) = Hold::take(self.value, Some(self.to))?;
938        let velocity = day_reactive::untrack(|| self.value.velocity.try_get())?;
939        // The largest excursion the spring can make from here: its distance, or what its
940        // speed carries it to. Rest is a thousandth of that.
941        let mass = self.spring.mass.max(1e-6);
942        let omega0 = (self.spring.stiffness.max(1e-6) / mass).sqrt();
943        let reach = (self.to - from).abs().max(velocity.abs() / omega0);
944        Some(Box::new(SpringRun {
945            hold,
946            to: self.to,
947            spring: self.spring,
948            rest: (reach * 1e-3).max(f64::EPSILON),
949            rest_speed: (reach * omega0 * 1e-3).max(f64::EPSILON),
950        }))
951    }
952    fn finish(&self) {
953        self.value.set(self.to);
954    }
955    fn snapshot(&self) -> Option<Box<dyn Fn()>> {
956        snapshot_of(self.value)
957    }
958    fn clock(&self) -> Option<FrameClock> {
959        self.value.clock()
960    }
961}
962
963struct SpringRun {
964    hold: Hold<f64>,
965    to: f64,
966    spring: Spring,
967    /// How close counts as arrived.
968    rest: f64,
969    /// How slow counts as at rest.
970    rest_speed: f64,
971}
972
973impl LeafRun for SpringRun {
974    fn advance(&mut self, dt: f64) -> Flow {
975        match self.hold.owns() {
976            None => return Flow::Gone,
977            Some(false) => return Flow::Ended(0.0),
978            Some(true) => {}
979        }
980        let value = self.hold.value;
981        let (Some(at), Some(velocity)) = (
982            value.try_now(),
983            day_reactive::untrack(|| value.velocity.try_get()),
984        ) else {
985            return Flow::Gone;
986        };
987        let mut state = SpringState {
988            value: at,
989            velocity,
990        };
991        self.spring.step(&mut state, self.to, dt);
992        if (state.value - self.to).abs() < self.rest && state.velocity.abs() < self.rest_speed {
993            self.hold.land(self.to);
994            return Flow::Ended(0.0);
995        }
996        value.value.set(state.value);
997        value.velocity.set(state.velocity);
998        Flow::Running
999    }
1000    fn release(&self) {
1001        self.hold.release();
1002    }
1003}
1004
1005/// `value` coasting from its own velocity until it stops.
1006struct DecayLeaf {
1007    value: Animated<f64>,
1008    decay: Decay,
1009}
1010
1011impl DecayLeaf {
1012    /// The value and its velocity, while its scope is alive.
1013    fn state(&self) -> Option<SpringState> {
1014        Some(SpringState {
1015            value: self.value.try_now()?,
1016            velocity: day_reactive::untrack(|| self.value.velocity.try_get())?,
1017        })
1018    }
1019}
1020
1021impl Leaf for DecayLeaf {
1022    fn begin(&self) -> Option<Box<dyn LeafRun>> {
1023        let (hold, _) = Hold::take(self.value, self.state().map(|s| self.decay.rest(s)))?;
1024        Some(Box::new(DecayRun {
1025            hold,
1026            decay: self.decay,
1027        }))
1028    }
1029    fn finish(&self) {
1030        if let Some(state) = self.state() {
1031            self.value.set(self.decay.rest(state));
1032        }
1033    }
1034    fn snapshot(&self) -> Option<Box<dyn Fn()>> {
1035        snapshot_of(self.value)
1036    }
1037    fn clock(&self) -> Option<FrameClock> {
1038        self.value.clock()
1039    }
1040}
1041
1042struct DecayRun {
1043    hold: Hold<f64>,
1044    decay: Decay,
1045}
1046
1047impl LeafRun for DecayRun {
1048    fn advance(&mut self, dt: f64) -> Flow {
1049        match self.hold.owns() {
1050            None => return Flow::Gone,
1051            Some(false) => return Flow::Ended(0.0),
1052            Some(true) => {}
1053        }
1054        let value = self.hold.value;
1055        let (Some(at), Some(velocity)) = (
1056            value.try_now(),
1057            day_reactive::untrack(|| value.velocity.try_get()),
1058        ) else {
1059            return Flow::Gone;
1060        };
1061        let mut state = SpringState {
1062            value: at,
1063            velocity,
1064        };
1065        self.decay.step(&mut state, dt);
1066        if self.decay.stopped(state) {
1067            self.hold.land(state.value);
1068            return Flow::Ended(0.0);
1069        }
1070        value.value.set(state.value);
1071        value.velocity.set(state.velocity);
1072        Flow::Running
1073    }
1074    fn release(&self) {
1075        self.hold.release();
1076    }
1077}
1078
1079/// A closure called with each frame's sample of an [`AnimSpec`].
1080struct DriveLeaf {
1081    spec: AnimSpec,
1082    step: Rc<RefCell<dyn FnMut(AnimSample)>>,
1083}
1084
1085impl DriveLeaf {
1086    /// Calls the closure, unless it is already running (a step that restarts its own
1087    /// animation).
1088    fn call(step: &Rc<RefCell<dyn FnMut(AnimSample)>>, sample: AnimSample) {
1089        if let Ok(mut step) = step.try_borrow_mut() {
1090            step(sample);
1091        }
1092    }
1093}
1094
1095impl Leaf for DriveLeaf {
1096    fn begin(&self) -> Option<Box<dyn LeafRun>> {
1097        Some(Box::new(DriveRun {
1098            spec: self.spec,
1099            step: self.step.clone(),
1100            elapsed: 0.0,
1101        }))
1102    }
1103    fn finish(&self) {
1104        let end = self.spec.total_secs().unwrap_or(0.0);
1105        Self::call(
1106            &self.step,
1107            AnimSample {
1108                done: true,
1109                ..self.spec.sample(end)
1110            },
1111        );
1112    }
1113    fn endless(&self) -> bool {
1114        self.spec.repeats_forever()
1115    }
1116}
1117
1118struct DriveRun {
1119    spec: AnimSpec,
1120    step: Rc<RefCell<dyn FnMut(AnimSample)>>,
1121    elapsed: f64,
1122}
1123
1124impl LeafRun for DriveRun {
1125    fn advance(&mut self, dt: f64) -> Flow {
1126        self.elapsed += dt;
1127        let sample = self.spec.sample(self.elapsed);
1128        DriveLeaf::call(&self.step, sample);
1129        if sample.done {
1130            let total = self.spec.total_secs().unwrap_or(self.elapsed);
1131            Flow::Ended((self.elapsed - total).clamp(0.0, dt))
1132        } else {
1133            Flow::Running
1134        }
1135    }
1136    fn release(&self) {}
1137}
1138
1139/// The shape of an [`Animation`].
1140#[derive(Clone)]
1141enum Node {
1142    /// One step.
1143    Leaf(Rc<dyn Leaf>),
1144    /// Nothing, for this many seconds.
1145    Delay(f64),
1146    /// Its parts one after another.
1147    Sequence(Vec<Node>),
1148    /// Its parts together, ending with the last of them.
1149    Parallel(Vec<Node>),
1150    /// Its part again each time it ends: this many times, or without end.
1151    Repeat(Box<Node>, Option<u32>),
1152}
1153
1154impl Node {
1155    /// Whether the animation never ends by itself.
1156    fn endless(&self) -> bool {
1157        match self {
1158            Node::Leaf(leaf) => leaf.endless(),
1159            // Played no times, a repeat ends at once whatever it holds.
1160            Node::Delay(_) | Node::Repeat(_, Some(0)) => false,
1161            Node::Sequence(parts) | Node::Parallel(parts) => parts.iter().any(Node::endless),
1162            Node::Repeat(part, times) => times.is_none() || part.endless(),
1163        }
1164    }
1165
1166    /// Puts every value where the animation would leave it, in the order it would.
1167    fn finish(&self) {
1168        match self {
1169            Node::Leaf(leaf) => leaf.finish(),
1170            // Played no times, a repeat leaves every value where it is.
1171            Node::Delay(_) | Node::Repeat(_, Some(0)) => {}
1172            Node::Sequence(parts) | Node::Parallel(parts) => parts.iter().for_each(Node::finish),
1173            Node::Repeat(part, _) => part.finish(),
1174        }
1175    }
1176
1177    /// Visits every leaf, in order.
1178    fn leaves(&self, visit: &mut dyn FnMut(&dyn Leaf)) {
1179        match self {
1180            Node::Leaf(leaf) => visit(leaf.as_ref()),
1181            Node::Delay(_) => {}
1182            Node::Sequence(parts) | Node::Parallel(parts) => {
1183                for part in parts {
1184                    part.leaves(visit);
1185                }
1186            }
1187            Node::Repeat(part, _) => part.leaves(visit),
1188        }
1189    }
1190
1191    /// The animation, started now. `None` when a value it would move first is gone, and then
1192    /// nothing it holds stays claimed: a group lets go of the parts it had already started.
1193    fn begin(&self) -> Option<Run> {
1194        Some(match self {
1195            Node::Leaf(leaf) => Run::Leaf(leaf.begin()?),
1196            Node::Delay(secs) => Run::Delay(*secs),
1197            Node::Sequence(parts) => Run::Sequence {
1198                parts: parts.clone(),
1199                at: 0,
1200                current: match parts.first() {
1201                    Some(first) => Some(Box::new(first.begin()?)),
1202                    None => None,
1203                },
1204            },
1205            Node::Parallel(parts) => {
1206                let mut runs = Vec::with_capacity(parts.len());
1207                for part in parts {
1208                    let Some(run) = part.begin() else {
1209                        for (run, _) in &runs {
1210                            Run::release(run);
1211                        }
1212                        return None;
1213                    };
1214                    runs.push((run, false));
1215                }
1216                Run::Parallel(runs)
1217            }
1218            // Played no times: a pause of no length, which never touches a value.
1219            Node::Repeat(_, Some(0)) => Run::Delay(0.0),
1220            Node::Repeat(part, times) => Run::Repeat {
1221                part: (**part).clone(),
1222                times: *times,
1223                done: 0,
1224                current: Box::new(part.begin()?),
1225            },
1226        })
1227    }
1228}
1229
1230/// How many passes that take no time an endless repeat plays in one frame before it waits for
1231/// the next.
1232const INSTANT_PASSES_PER_FRAME: u32 = 64;
1233
1234/// A [`Node`] in flight.
1235enum Run {
1236    /// A step on its way.
1237    Leaf(Box<dyn LeafRun>),
1238    /// A pause, with the seconds left of it.
1239    Delay(f64),
1240    /// A sequence at one of its parts. A part starts when the one before it ends, so it reads
1241    /// its value where that one left it.
1242    Sequence {
1243        parts: Vec<Node>,
1244        at: usize,
1245        current: Option<Box<Run>>,
1246    },
1247    /// A group, each part with whether it has ended.
1248    Parallel(Vec<(Run, bool)>),
1249    /// A loop around one part.
1250    Repeat {
1251        part: Node,
1252        times: Option<u32>,
1253        done: u32,
1254        current: Box<Run>,
1255    },
1256}
1257
1258impl Run {
1259    /// Advances by `dt` seconds.
1260    fn advance(&mut self, dt: f64) -> Flow {
1261        match self {
1262            Run::Leaf(run) => run.advance(dt),
1263            Run::Delay(left) => {
1264                *left -= dt;
1265                if *left <= 0.0 {
1266                    Flow::Ended((-*left).min(dt))
1267                } else {
1268                    Flow::Running
1269                }
1270            }
1271            Run::Sequence { parts, at, current } => {
1272                let mut dt = dt;
1273                loop {
1274                    let Some(run) = current else {
1275                        return Flow::Ended(dt);
1276                    };
1277                    match run.advance(dt) {
1278                        Flow::Ended(left) => dt = left,
1279                        flow => return flow,
1280                    }
1281                    *at += 1;
1282                    *current = match parts.get(*at) {
1283                        Some(next) => match next.begin() {
1284                            Some(run) => Some(Box::new(run)),
1285                            None => return Flow::Gone,
1286                        },
1287                        None => None,
1288                    };
1289                }
1290            }
1291            Run::Parallel(runs) => {
1292                let mut left = dt;
1293                for (run, ended) in runs.iter_mut().filter(|(_, ended)| !*ended) {
1294                    match run.advance(dt) {
1295                        Flow::Running => {}
1296                        Flow::Ended(unused) => {
1297                            *ended = true;
1298                            left = left.min(unused);
1299                        }
1300                        Flow::Gone => return Flow::Gone,
1301                    }
1302                }
1303                if runs.iter().all(|(_, ended)| *ended) {
1304                    Flow::Ended(left)
1305                } else {
1306                    Flow::Running
1307                }
1308            }
1309            Run::Repeat {
1310                part,
1311                times,
1312                done,
1313                current,
1314            } => {
1315                let mut dt = dt;
1316                // Every pass that fits in `dt` plays now, so a late frame (a stall, an app
1317                // coming back) catches up instead of losing time. A finite repeat ends however
1318                // short its passes are, and hands what is left of `dt` to what follows it. Only
1319                // an endless repeat of passes that take no time at all could spin here for ever;
1320                // a run of those yields to the next frame (an endless run has no later steps
1321                // to lose the time to).
1322                let mut instant = 0;
1323                loop {
1324                    let before = dt;
1325                    match current.advance(dt) {
1326                        Flow::Ended(left) => {
1327                            *done = done.saturating_add(1);
1328                            if times.is_some_and(|times| *done >= times) {
1329                                return Flow::Ended(left);
1330                            }
1331                            match part.begin() {
1332                                Some(run) => **current = run,
1333                                None => return Flow::Gone,
1334                            }
1335                            if left <= 0.0 {
1336                                return Flow::Running;
1337                            }
1338                            if left < before || times.is_some() {
1339                                instant = 0;
1340                            } else {
1341                                instant += 1;
1342                                if instant >= INSTANT_PASSES_PER_FRAME {
1343                                    return Flow::Running;
1344                                }
1345                            }
1346                            dt = left;
1347                        }
1348                        flow => return flow,
1349                    }
1350                }
1351            }
1352        }
1353    }
1354
1355    /// Gives up every value a running step holds, where it stands.
1356    fn release(&self) {
1357        match self {
1358            Run::Leaf(run) => run.release(),
1359            Run::Delay(_) => {}
1360            Run::Sequence { current, .. } => {
1361                if let Some(run) = current {
1362                    run.release();
1363                }
1364            }
1365            Run::Parallel(runs) => runs
1366                .iter()
1367                .filter(|(_, ended)| !*ended)
1368                .for_each(|(run, _)| run.release()),
1369            Run::Repeat { current, .. } => current.release(),
1370        }
1371    }
1372}
1373
1374/// Motion for [`Animated`] values: one step, or a composition of several. Building one moves
1375/// nothing; [`start`](Animation::start) plays it, and it can be started again.
1376///
1377/// ```rust,ignore
1378/// let lifts: Vec<Animated> = (0..5).map(|_| Animated::new(0.0)).collect();
1379/// let entrance = Animation::stagger(
1380///     70,
1381///     lifts.iter().map(|&lift| {
1382///         Animation::sequence([
1383///             Animation::timing(lift, -46.0, 220, Easing::Power(Ease::Out, 2.0)),
1384///             Animation::spring(lift, 0.0, Spring::new(320.0, 11.0)),
1385///         ])
1386///     }),
1387/// );
1388/// let playing = entrance.start();
1389/// day::task(async move {
1390///     if playing.await == Outcome::Finished {
1391///         status.set(Status::Arrived);
1392///     }
1393/// });
1394/// ```
1395///
1396/// Under reduced motion ([`reduce_motion`](crate::reduce_motion)) a finite animation puts every
1397/// value on its end state at once, also when the setting flips mid-flight; one that never ends
1398/// by itself (a [`looped`](Animation::looped) pulse, the sign that work is going on) keeps
1399/// running. An animation stops when a value it moves is disposed with its scope, so a page
1400/// needs no cleanup of its own.
1401#[derive(Clone)]
1402#[must_use = "an animation does nothing until it is started"]
1403pub struct Animation {
1404    node: Node,
1405}
1406
1407impl Animation {
1408    /// Moves `value` to `to` over `ms` milliseconds along `easing`, from wherever it is when
1409    /// the step starts.
1410    pub fn timing<T: Lerp + 'static>(value: Animated<T>, to: T, ms: u32, easing: Easing) -> Self {
1411        Self::leaf(TimingLeaf {
1412            value,
1413            to,
1414            secs: f64::from(ms) / 1000.0,
1415            easing,
1416        })
1417    }
1418
1419    /// Moves `value` to `to` as `spec` says: its delay, its curve or spring, its repeats and
1420    /// autoreverse ([`AnimSpec::sample`]). The frame-driven twin of
1421    /// [`with_animation`](crate::with_animation): a canvas value moved with the spec a native
1422    /// property is animated with moves in step with it. A spec that repeats forever never ends.
1423    pub fn tween<T: Lerp + 'static>(value: Animated<T>, to: T, spec: AnimSpec) -> Self {
1424        Self::leaf(TweenLeaf { value, to, spec })
1425    }
1426
1427    /// Springs `value` to `to`, starting at the velocity it has, until it comes to rest. A
1428    /// spring that takes over from another step, or follows
1429    /// [`set_velocity`](Animated::set_velocity), carries that speed on.
1430    pub fn spring(value: Animated<f64>, to: f64, spring: Spring) -> Self {
1431        Self::leaf(SpringLeaf { value, to, spring })
1432    }
1433
1434    /// Lets `value` coast from the velocity it has until it stops, as a flung scroll view does.
1435    pub fn decay(value: Animated<f64>, decay: Decay) -> Self {
1436        Self::leaf(DecayLeaf { value, decay })
1437    }
1438
1439    /// Calls `step` with each frame's [`AnimSample`] of `spec`, the last one `done`: for a
1440    /// transition that is more than one value (a chart blending two states). Under reduced
1441    /// motion `step` is called once, with the final sample.
1442    pub fn drive(spec: AnimSpec, step: impl FnMut(AnimSample) + 'static) -> Self {
1443        Self::leaf(DriveLeaf {
1444            spec,
1445            step: Rc::new(RefCell::new(step)),
1446        })
1447    }
1448
1449    /// Does nothing for `ms` milliseconds.
1450    pub fn delay(ms: u32) -> Self {
1451        Animation {
1452            node: Node::Delay(f64::from(ms) / 1000.0),
1453        }
1454    }
1455
1456    /// Runs `steps` one after another. Each starts from where its value stands when its turn
1457    /// comes, and on the frame the step before it ends.
1458    pub fn sequence(steps: impl IntoIterator<Item = Animation>) -> Self {
1459        Animation {
1460            node: Node::Sequence(steps.into_iter().map(|step| step.node).collect()),
1461        }
1462    }
1463
1464    /// Runs `steps` together and ends with the last of them.
1465    pub fn parallel(steps: impl IntoIterator<Item = Animation>) -> Self {
1466        Animation {
1467            node: Node::Parallel(steps.into_iter().map(|step| step.node).collect()),
1468        }
1469    }
1470
1471    /// Runs `steps` together, each starting `gap_ms` milliseconds after the one before it.
1472    pub fn stagger(gap_ms: u32, steps: impl IntoIterator<Item = Animation>) -> Self {
1473        let gap = f64::from(gap_ms) / 1000.0;
1474        Animation {
1475            node: Node::Parallel(
1476                steps
1477                    .into_iter()
1478                    .enumerate()
1479                    .map(|(i, step)| {
1480                        if i == 0 {
1481                            step.node
1482                        } else {
1483                            Node::Sequence(vec![Node::Delay(gap * i as f64), step.node])
1484                        }
1485                    })
1486                    .collect(),
1487            ),
1488        }
1489    }
1490
1491    /// Plays the animation `times` times in a row.
1492    pub fn repeat(self, times: u32) -> Self {
1493        Animation {
1494            node: Node::Repeat(Box::new(self.node), Some(times)),
1495        }
1496    }
1497
1498    /// Plays the animation again each time it ends, until it is stopped.
1499    pub fn looped(self) -> Self {
1500        Animation {
1501            node: Node::Repeat(Box::new(self.node), None),
1502        }
1503    }
1504
1505    /// Whether the animation never ends by itself.
1506    #[must_use]
1507    pub fn is_endless(&self) -> bool {
1508        self.node.endless()
1509    }
1510
1511    /// Puts every value where the animation would leave it, without playing it. An endless
1512    /// animation's values are left where one pass would.
1513    pub fn jump_to_end(&self) {
1514        day_reactive::batch(|| self.node.finish());
1515    }
1516
1517    /// Plays the animation on the window of the first value it moves (the current page's
1518    /// window when it moves none).
1519    pub fn start(&self) -> Playing {
1520        let mut clock = None;
1521        self.node
1522            .leaves(&mut |leaf| clock = clock.or_else(|| leaf.clock()));
1523        self.start_on(clock.unwrap_or_else(FrameClock::current))
1524    }
1525
1526    /// Plays the animation on `clock`'s frames.
1527    pub fn start_on(&self, clock: FrameClock) -> Playing {
1528        let mut restore = Vec::new();
1529        self.node
1530            .leaves(&mut |leaf| restore.extend(leaf.snapshot()));
1531        let shared = Rc::new(Shared {
1532            outcome: Cell::new(None),
1533            handle: RefCell::new(None),
1534            run: RefCell::new(None),
1535            wakers: RefCell::new(Vec::new()),
1536            listeners: RefCell::new(Vec::new()),
1537            restore,
1538        });
1539        let playing = Playing {
1540            shared: shared.clone(),
1541        };
1542        let endless = self.node.endless();
1543        if crate::reduce_motion_now() && !endless {
1544            self.jump_to_end();
1545            shared.end(Outcome::Finished);
1546            return playing;
1547        }
1548        let Some(run) = day_reactive::batch(|| self.node.begin()) else {
1549            shared.end(Outcome::Stopped);
1550            return playing;
1551        };
1552        *shared.run.borrow_mut() = Some(run);
1553        let node = self.node.clone();
1554        let guard = Guard(shared.clone());
1555        let handle = clock.subscribe(move |frame| {
1556            let shared = &guard.0;
1557            if shared.outcome.get().is_some() {
1558                return ControlFlow::Break(());
1559            }
1560            // The setting is read per frame, so one flipped mid-flight lands the animation too.
1561            let flow = if crate::reduce_motion_now() && !endless {
1562                node.finish();
1563                Flow::Ended(0.0)
1564            } else {
1565                shared
1566                    .run
1567                    .try_borrow_mut()
1568                    .ok()
1569                    .and_then(|mut run| {
1570                        run.as_mut()
1571                            .map(|run| run.advance(frame.delta.as_secs_f64()))
1572                    })
1573                    .unwrap_or(Flow::Gone)
1574            };
1575            match flow {
1576                // A step may have stopped the animation it belongs to.
1577                Flow::Running if shared.outcome.get().is_none() => {
1578                    return ControlFlow::Continue(());
1579                }
1580                Flow::Running => shared.cleanup(),
1581                Flow::Ended(_) => shared.end(Outcome::Finished),
1582                Flow::Gone => shared.end(Outcome::Stopped),
1583            }
1584            ControlFlow::Break(())
1585        });
1586        // Ended already only if `subscribe` ran the callback inline, which no clock does.
1587        if shared.outcome.get().is_none() {
1588            *shared.handle.borrow_mut() = Some(handle);
1589        }
1590        playing
1591    }
1592
1593    /// An animation of one step.
1594    fn leaf(leaf: impl Leaf + 'static) -> Self {
1595        Animation {
1596            node: Node::Leaf(Rc::new(leaf)),
1597        }
1598    }
1599}
1600
1601// ---------------------------------------------------------------------------
1602// Playing: an animation in flight
1603// ---------------------------------------------------------------------------
1604
1605/// How an animation's run ended.
1606#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1607pub enum Outcome {
1608    /// It played to its end (or landed there at once under reduced motion).
1609    Finished,
1610    /// It was stopped first: by [`Playing::stop`] or [`Playing::reset`], or because a value
1611    /// it moved or its window went away.
1612    Stopped,
1613}
1614
1615/// A callback for the end of a run.
1616type Listener = Box<dyn FnOnce(Outcome)>;
1617
1618/// What a running animation and its handles share.
1619struct Shared {
1620    /// How the run ended, once it has.
1621    outcome: Cell<Option<Outcome>>,
1622    /// The frame subscription driving it.
1623    handle: RefCell<Option<FrameHandle>>,
1624    /// The steps in flight.
1625    run: RefCell<Option<Run>>,
1626    /// Tasks awaiting the end.
1627    wakers: RefCell<Vec<Waker>>,
1628    /// Callbacks for the end.
1629    listeners: RefCell<Vec<Listener>>,
1630    /// Puts each value back where it was when the run started.
1631    restore: Vec<Box<dyn Fn()>>,
1632}
1633
1634impl Shared {
1635    /// Ends the run, once: releases what it held, wakes what awaited it, calls its listeners.
1636    fn end(&self, outcome: Outcome) {
1637        if self.outcome.get().is_some() {
1638            return;
1639        }
1640        self.outcome.set(Some(outcome));
1641        self.cleanup();
1642    }
1643
1644    /// Lets go of the steps and the frame subscription, then tells everyone waiting. Skipped
1645    /// while a step of this very run is advancing (it stopped its own animation): the frame
1646    /// callback calls it again once the step returns.
1647    fn cleanup(&self) {
1648        let Some(outcome) = self.outcome.get() else {
1649            return;
1650        };
1651        let Ok(mut run) = self.run.try_borrow_mut() else {
1652            return;
1653        };
1654        if let Some(run) = run.take() {
1655            day_reactive::batch(|| run.release());
1656        }
1657        drop(run);
1658        // Dropping the handle cancels the subscription.
1659        let handle = self.handle.borrow_mut().take();
1660        drop(handle);
1661        for waker in std::mem::take(&mut *self.wakers.borrow_mut()) {
1662            waker.wake();
1663        }
1664        for listener in std::mem::take(&mut *self.listeners.borrow_mut()) {
1665            listener(outcome);
1666        }
1667    }
1668}
1669
1670/// Ends a run whose frame subscription was dropped under it (its window closed), so nothing
1671/// awaits it for ever.
1672struct Guard(Rc<Shared>);
1673
1674impl Drop for Guard {
1675    fn drop(&mut self) {
1676        // At thread teardown the reactive runtime may already be gone; nothing is waiting then.
1677        if crate::frame::alive() {
1678            self.0.end(Outcome::Stopped);
1679        }
1680    }
1681}
1682
1683/// A started [`Animation`]: stop it, reset it, ask how it went, or await its end.
1684///
1685/// The animation does not depend on the handle: dropping it leaves the animation running, and
1686/// it stops by itself when a value it moves is disposed. Awaiting the handle answers
1687/// [`Outcome::Finished`] when the animation played to its end and [`Outcome::Stopped`] when
1688/// something ended it first.
1689#[derive(Clone)]
1690pub struct Playing {
1691    shared: Rc<Shared>,
1692}
1693
1694impl Playing {
1695    /// Stops the animation where it stands; its values keep what they show. Answers whether
1696    /// it was still running.
1697    #[expect(
1698        clippy::must_use_candidate,
1699        reason = "stopping is the point; whether it was running is incidental"
1700    )]
1701    pub fn stop(&self) -> bool {
1702        let running = self.is_running();
1703        self.shared.end(Outcome::Stopped);
1704        running
1705    }
1706
1707    /// Stops the animation and puts every value it moves back where it was when it started.
1708    pub fn reset(&self) {
1709        self.stop();
1710        day_reactive::batch(|| self.shared.restore.iter().for_each(|restore| restore()));
1711    }
1712
1713    /// Whether the animation is still playing.
1714    #[must_use]
1715    pub fn is_running(&self) -> bool {
1716        self.shared.outcome.get().is_none()
1717    }
1718
1719    /// Whether the animation played to its end.
1720    #[must_use]
1721    pub fn is_finished(&self) -> bool {
1722        self.shared.outcome.get() == Some(Outcome::Finished)
1723    }
1724
1725    /// How the run ended, or `None` while it plays.
1726    #[must_use]
1727    pub fn outcome(&self) -> Option<Outcome> {
1728        self.shared.outcome.get()
1729    }
1730
1731    /// Calls `f` when the run ends, with how; at once when it already has. The callback form
1732    /// of awaiting the handle.
1733    pub fn on_end(&self, f: impl FnOnce(Outcome) + 'static) {
1734        match self.shared.outcome.get() {
1735            Some(outcome) => f(outcome),
1736            None => self.shared.listeners.borrow_mut().push(Box::new(f)),
1737        }
1738    }
1739}
1740
1741impl std::fmt::Debug for Playing {
1742    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1743        f.debug_struct("Playing")
1744            .field("outcome", &self.shared.outcome.get())
1745            .finish()
1746    }
1747}
1748
1749impl Future for Playing {
1750    type Output = Outcome;
1751
1752    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Outcome> {
1753        if let Some(outcome) = self.shared.outcome.get() {
1754            return Poll::Ready(outcome);
1755        }
1756        self.shared.wakers.borrow_mut().push(cx.waker().clone());
1757        Poll::Pending
1758    }
1759}
1760
1761#[cfg(test)]
1762mod tests {
1763    use super::*;
1764
1765    #[test]
1766    fn every_curve_starts_at_zero_and_ends_at_one() {
1767        let curves = [
1768            Easing::Linear,
1769            Easing::EASE,
1770            Easing::EASE_IN_OUT,
1771            Easing::Power(Ease::Out, 2.0),
1772            Easing::Power(Ease::InOut, 3.0),
1773            Easing::Sine(Ease::In),
1774            Easing::Circle(Ease::Out),
1775            Easing::Exponential(Ease::InOut),
1776            Easing::Back(Ease::Out, 1.70158),
1777            Easing::ElasticOut(1.0),
1778            Easing::BounceOut,
1779        ];
1780        for curve in curves {
1781            assert!(curve.value(0.0).abs() < 1e-3, "{curve:?} at 0");
1782            assert!((curve.value(1.0) - 1.0).abs() < 1e-3, "{curve:?} at 1");
1783        }
1784    }
1785
1786    #[test]
1787    fn back_out_overshoots_and_linear_bezier_is_linear() {
1788        let peak = Easing::Back(Ease::Out, 1.70158)
1789            .samples(101)
1790            .into_iter()
1791            .fold(0.0, f64::max);
1792        assert!(peak > 1.05 && peak < 1.2, "{peak}");
1793        let straight = Easing::Bezier(0.25, 0.25, 0.75, 0.75);
1794        assert!((straight.value(0.3) - 0.3).abs() < 1e-3);
1795    }
1796
1797    #[test]
1798    fn a_spring_settles_on_its_target_and_a_loose_one_overshoots() {
1799        let firm = Spring::new(400.0, 30.0);
1800        let mut state = SpringState::default();
1801        for _ in 0..240 {
1802            firm.step(&mut state, 100.0, 1.0 / 60.0);
1803        }
1804        assert!(firm.settled(state, 100.0), "{state:?}");
1805
1806        let peak = Spring::new(180.0, 8.0)
1807            .response(1.8, 200)
1808            .into_iter()
1809            .fold(0.0, f64::max);
1810        assert!(peak > 1.2, "{peak}");
1811    }
1812
1813    #[test]
1814    fn a_decay_stops_at_a_finite_distance() {
1815        let decay = Decay { rate: 0.992 };
1816        let mut state = SpringState {
1817            value: 0.0,
1818            velocity: 1000.0,
1819        };
1820        for _ in 0..600 {
1821            decay.step(&mut state, 1.0 / 60.0);
1822        }
1823        assert!(decay.stopped(state));
1824        // 1000 pt/s losing 0.8% per ms covers 1000 / (-ln 0.992 · 1000) points.
1825        assert!((state.value - 124.5).abs() < 2.0, "{}", state.value);
1826    }
1827
1828    // --- The driver --------------------------------------------------------------------------
1829
1830    use crate::tree::RNode;
1831    use day_spec::{Color, FrameStamp};
1832    use std::collections::VecDeque;
1833
1834    /// A frame source the test fires by hand, 60 frames a second from a time of its own.
1835    struct Frames {
1836        pending: Rc<RefCell<VecDeque<day_spec::FrameCallback>>>,
1837        now: Cell<f64>,
1838    }
1839
1840    impl Frames {
1841        fn new() -> Self {
1842            let pending: Rc<RefCell<VecDeque<day_spec::FrameCallback>>> = Rc::default();
1843            let q = pending.clone();
1844            crate::frame::install_frame_requester(move |_, cb| {
1845                q.borrow_mut().push_back(cb);
1846                Box::new(|| {})
1847            });
1848            Frames {
1849                pending,
1850                now: Cell::new(10.0),
1851            }
1852        }
1853
1854        fn clock() -> FrameClock {
1855            FrameClock::for_root(RNode::default())
1856        }
1857
1858        /// Delivers one frame `secs` after the last. Answers whether one was wanted.
1859        fn step(&self, secs: f64) -> bool {
1860            self.now.set(self.now.get() + secs);
1861            // Requests of cancelled subscriptions stay queued in this fake; deliver them all.
1862            let due: Vec<_> = self.pending.borrow_mut().drain(..).collect();
1863            let wanted = !due.is_empty();
1864            for cb in due {
1865                cb(FrameStamp::new(self.now.get()));
1866            }
1867            wanted
1868        }
1869
1870        /// Runs frames of a sixtieth until `secs` have passed.
1871        fn run(&self, secs: f64) {
1872            for _ in 0..(secs * 60.0).round() as usize {
1873                self.step(1.0 / 60.0);
1874            }
1875        }
1876
1877        fn idle() -> bool {
1878            crate::frame_consumer_count() == 0
1879        }
1880    }
1881
1882    fn close(a: f64, b: f64) -> bool {
1883        (a - b).abs() < 1e-6
1884    }
1885
1886    #[test]
1887    fn a_timing_moves_its_value_and_releases_the_clock_on_arrival() {
1888        let frames = Frames::new();
1889        let v = Animated::on(Frames::clock(), 0.0);
1890        let playing = Animation::timing(v, 100.0, 100, Easing::Linear).start();
1891        assert!(v.is_animating() && playing.is_running());
1892        assert!(close(v.target(), 100.0));
1893        frames.step(0.0); // the first frame is the start: elapsed 0
1894        assert!(close(v.get_untracked(), 0.0));
1895        frames.step(0.05);
1896        assert!(close(v.get_untracked(), 50.0));
1897        assert!(close(v.velocity.get_untracked(), 1000.0));
1898        frames.step(0.06);
1899        assert!(close(v.get_untracked(), 100.0));
1900        assert_eq!(playing.outcome(), Some(Outcome::Finished));
1901        assert!(!v.is_animating());
1902        assert!(Frames::idle(), "no frames wanted after arrival");
1903    }
1904
1905    #[test]
1906    fn animate_to_retargets_from_the_value_on_screen() {
1907        let frames = Frames::new();
1908        let v = Animated::on(Frames::clock(), 0.0);
1909        let first = v.animate_to(100.0, AnimSpec::linear(100));
1910        frames.step(0.0);
1911        frames.step(0.05);
1912        assert!(close(v.get_untracked(), 50.0));
1913        let second = v.animate_to(0.0, AnimSpec::linear(100));
1914        assert_eq!(first.outcome(), Some(Outcome::Stopped));
1915        frames.step(0.01); // the new flight's first frame
1916        assert!(close(v.get_untracked(), 50.0));
1917        frames.step(0.05);
1918        assert!(close(v.get_untracked(), 25.0));
1919        frames.step(0.06);
1920        assert!(close(v.get_untracked(), 0.0));
1921        assert!(second.is_finished() && !v.is_animating() && Frames::idle());
1922    }
1923
1924    #[test]
1925    fn a_tween_follows_its_spec_and_rests_on_the_target() {
1926        let frames = Frames::new();
1927        let v = Animated::on(Frames::clock(), 0.0);
1928        // Forward and back: the last cycle ends on the start, the value rests on the target.
1929        let spec = AnimSpec::linear(100).delay(100).repeat(1, true);
1930        let playing = Animation::tween(v, 10.0, spec).start();
1931        frames.step(0.0);
1932        frames.step(0.05);
1933        assert!(close(v.get_untracked(), 0.0), "held through the delay");
1934        frames.step(0.1); // 0.15: half way forward
1935        assert!(close(v.get_untracked(), 5.0));
1936        frames.step(0.125); // 0.275: three quarters of the way back
1937        assert!(close(v.get_untracked(), 2.5));
1938        frames.step(0.05);
1939        assert!(close(v.get_untracked(), 10.0));
1940        assert!(playing.is_finished());
1941    }
1942
1943    #[test]
1944    fn a_sequence_runs_in_order_and_carries_time_across_its_steps() {
1945        let frames = Frames::new();
1946        let (a, b) = (
1947            Animated::on(Frames::clock(), 0.0),
1948            Animated::on(Frames::clock(), 0.0),
1949        );
1950        let playing = Animation::sequence([
1951            Animation::timing(a, 1.0, 100, Easing::Linear),
1952            Animation::delay(100),
1953            Animation::timing(b, 1.0, 100, Easing::Linear),
1954        ])
1955        .start();
1956        frames.step(0.0);
1957        frames.step(0.15);
1958        assert!(close(a.get_untracked(), 1.0) && close(b.get_untracked(), 0.0));
1959        assert!(!b.is_animating());
1960        // 0.25 in: the delay ended at 0.2 and the last step is half way, not at its start.
1961        frames.step(0.1);
1962        assert!(close(b.get_untracked(), 0.5), "{}", b.get_untracked());
1963        frames.step(0.06);
1964        assert!(playing.is_finished() && close(b.get_untracked(), 1.0));
1965    }
1966
1967    #[test]
1968    fn a_stagger_starts_each_step_a_gap_after_the_one_before() {
1969        let frames = Frames::new();
1970        let values: Vec<Animated> = (0..3).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
1971        let playing = Animation::stagger(
1972            100,
1973            values
1974                .iter()
1975                .map(|&v| Animation::timing(v, 1.0, 200, Easing::Linear)),
1976        )
1977        .start();
1978        frames.step(0.0);
1979        frames.step(0.2);
1980        let at: Vec<f64> = values.iter().map(|v| v.get_untracked()).collect();
1981        assert!(
1982            close(at[0], 1.0) && close(at[1], 0.5) && close(at[2], 0.0),
1983            "{at:?}"
1984        );
1985        frames.step(0.2);
1986        assert!(playing.is_finished());
1987        assert!(values.iter().all(|v| close(v.get_untracked(), 1.0)));
1988    }
1989
1990    #[test]
1991    fn repeat_plays_a_number_of_times_and_looped_never_ends() {
1992        let frames = Frames::new();
1993        let v = Animated::on(Frames::clock(), 0.0);
1994        let there_and_back = Animation::sequence([
1995            Animation::timing(v, 1.0, 100, Easing::Linear),
1996            Animation::timing(v, 0.0, 100, Easing::Linear),
1997        ]);
1998        assert!(!there_and_back.is_endless());
1999        let twice = there_and_back.clone().repeat(2).start();
2000        frames.step(0.0);
2001        frames.step(0.25); // second pass, a quarter in
2002        assert!(close(v.get_untracked(), 0.5), "{}", v.get_untracked());
2003        assert!(twice.is_running());
2004        frames.step(0.2);
2005        assert!(twice.is_finished() && close(v.get_untracked(), 0.0));
2006
2007        let pulse = there_and_back.looped();
2008        assert!(pulse.is_endless());
2009        let playing = pulse.start();
2010        frames.run(3.0);
2011        assert!(playing.is_running());
2012        assert!(playing.stop());
2013        assert_eq!(playing.outcome(), Some(Outcome::Stopped));
2014        assert!(!v.is_animating() && Frames::idle());
2015        assert!(!playing.stop(), "stopping twice is harmless");
2016    }
2017
2018    #[test]
2019    fn a_spring_settles_carries_velocity_and_a_decay_coasts_to_its_rest() {
2020        let frames = Frames::new();
2021        let v = Animated::on(Frames::clock(), 0.0);
2022        let playing = Animation::spring(v, 100.0, Spring::new(180.0, 8.0)).start();
2023        let mut peak = 0.0_f64;
2024        frames.step(0.0);
2025        for _ in 0..600 {
2026            frames.step(1.0 / 60.0);
2027            peak = peak.max(v.get_untracked());
2028        }
2029        assert!(peak > 110.0, "a loose spring overshoots: {peak}");
2030        assert!(playing.is_finished() && close(v.get_untracked(), 100.0));
2031        assert!(close(v.velocity.get_untracked(), 0.0));
2032
2033        // A release velocity away from the target carries the value past where it stood.
2034        v.set(0.0);
2035        v.set_velocity(-2000.0);
2036        let back = Animation::spring(v, 0.0, Spring::new(180.0, 26.0)).start();
2037        frames.step(0.0);
2038        frames.step(1.0 / 60.0);
2039        assert!(v.get_untracked() < -10.0);
2040        frames.run(5.0);
2041        assert!(back.is_finished() && close(v.get_untracked(), 0.0));
2042
2043        let decay = Decay { rate: 0.992 };
2044        v.set(0.0);
2045        v.set_velocity(1000.0);
2046        let rest = decay.rest(SpringState {
2047            value: 0.0,
2048            velocity: 1000.0,
2049        });
2050        assert!((rest - 124.5).abs() < 0.1, "{rest}");
2051        let fling = Animation::decay(v, decay).start();
2052        assert!(close(v.target(), rest));
2053        frames.run(10.0);
2054        assert!(fling.is_finished());
2055        assert!(
2056            (v.get_untracked() - rest).abs() < 1.0,
2057            "{}",
2058            v.get_untracked()
2059        );
2060    }
2061
2062    #[test]
2063    fn the_latest_step_owns_a_value_and_set_takes_it_from_any() {
2064        let frames = Frames::new();
2065        let v = Animated::on(Frames::clock(), 0.0);
2066        let slow = Animation::timing(v, 100.0, 1000, Easing::Linear).start();
2067        frames.step(0.0);
2068        frames.step(0.1);
2069        let quick = Animation::timing(v, -10.0, 100, Easing::Linear).start();
2070        frames.step(0.0);
2071        frames.step(0.2);
2072        assert!(quick.is_finished() && close(v.get_untracked(), -10.0));
2073        // The displaced step keeps its time and ends without touching the value again.
2074        frames.run(1.0);
2075        assert!(slow.is_finished() && close(v.get_untracked(), -10.0));
2076
2077        let again = Animation::timing(v, 100.0, 1000, Easing::Linear).start();
2078        frames.step(0.0);
2079        frames.step(0.1);
2080        v.set(7.0);
2081        assert!(!v.is_animating());
2082        frames.run(1.5);
2083        assert!(again.is_finished() && close(v.get_untracked(), 7.0));
2084    }
2085
2086    #[test]
2087    fn reset_puts_values_back_and_jump_to_end_lands_them() {
2088        let frames = Frames::new();
2089        let (a, b) = (
2090            Animated::on(Frames::clock(), 1.0),
2091            Animated::on(Frames::clock(), 2.0),
2092        );
2093        let animation = Animation::parallel([
2094            Animation::timing(a, 10.0, 100, Easing::Linear),
2095            Animation::sequence([
2096                Animation::delay(50),
2097                Animation::spring(b, 20.0, Spring::default()),
2098            ]),
2099        ]);
2100        let playing = animation.start();
2101        frames.step(0.0);
2102        frames.step(0.08);
2103        assert!(a.get_untracked() > 1.0 && b.get_untracked() > 2.0);
2104        playing.reset();
2105        assert_eq!(playing.outcome(), Some(Outcome::Stopped));
2106        assert!(close(a.get_untracked(), 1.0) && close(b.get_untracked(), 2.0));
2107        assert!(Frames::idle());
2108        animation.jump_to_end();
2109        assert!(close(a.get_untracked(), 10.0) && close(b.get_untracked(), 20.0));
2110    }
2111
2112    #[test]
2113    fn an_animation_stops_when_a_value_it_moves_is_disposed() {
2114        let frames = Frames::new();
2115        let scope = day_reactive::Scope::root().create_child();
2116        let v = scope.enter(|| Animated::on(Frames::clock(), 0.0));
2117        let kept = Animated::on(Frames::clock(), 0.0);
2118        let playing = Animation::parallel([
2119            Animation::timing(v, 1.0, 1000, Easing::Linear),
2120            Animation::timing(kept, 1.0, 1000, Easing::Linear),
2121        ])
2122        .looped()
2123        .start();
2124        frames.step(0.0);
2125        frames.step(0.1);
2126        scope.dispose();
2127        frames.step(0.1);
2128        assert_eq!(playing.outcome(), Some(Outcome::Stopped));
2129        assert!(!kept.is_animating() && Frames::idle());
2130        // Starting on a value that is already gone ends at once.
2131        let late = Animation::timing(v, 1.0, 100, Easing::Linear).start_on(Frames::clock());
2132        assert_eq!(late.outcome(), Some(Outcome::Stopped));
2133    }
2134
2135    #[test]
2136    fn a_group_that_cannot_start_lets_go_of_what_it_started() {
2137        let _frames = Frames::new();
2138        let scope = day_reactive::Scope::root().create_child();
2139        let gone = scope.enter(|| Animated::on(Frames::clock(), 0.0));
2140        scope.dispose();
2141        let step = |v: Animated<f64>| Animation::timing(v, 1.0, 100, Easing::Linear);
2142        // The value that is gone at each position of a group, and inside a nested one.
2143        for gone_at in 0..3 {
2144            let live: Vec<Animated<f64>> =
2145                (0..2).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
2146            let mut parts: Vec<Animation> = live.iter().map(|v| step(*v)).collect();
2147            parts.insert(gone_at, step(gone));
2148            let nested = Animation::parallel([
2149                Animation::sequence([step(live[0]), step(live[1])]),
2150                Animation::parallel(parts),
2151            ]);
2152            for playing in [
2153                nested.start(),
2154                Animation::parallel([step(live[1]), step(gone)]).start(),
2155            ] {
2156                assert_eq!(playing.outcome(), Some(Outcome::Stopped), "at {gone_at}");
2157                assert!(
2158                    live.iter()
2159                        .all(|v| !v.is_animating() && close(v.get_untracked(), 0.0)),
2160                    "a live value stayed claimed (gone at {gone_at})"
2161                );
2162            }
2163        }
2164        assert!(Frames::idle());
2165    }
2166
2167    #[test]
2168    fn a_repeat_of_zero_plays_nothing_and_a_late_frame_plays_every_pass_it_covers() {
2169        let frames = Frames::new();
2170        let v = Animated::on(Frames::clock(), 0.0);
2171        let none = Animation::timing(v, 10.0, 100, Easing::Linear).repeat(0);
2172        assert!(!none.is_endless());
2173        let playing = none.start();
2174        frames.step(0.0);
2175        frames.step(0.2);
2176        assert_eq!(playing.outcome(), Some(Outcome::Finished));
2177        assert!(close(v.get_untracked(), 0.0) && !v.is_animating());
2178
2179        // Ten passes of 10 ms, all inside one frame that came 200 ms late.
2180        let ten = Animation::delay(10).repeat(10).start_on(Frames::clock());
2181        frames.step(0.0);
2182        frames.step(0.2);
2183        assert_eq!(ten.outcome(), Some(Outcome::Finished));
2184
2185        // A thousand passes of 1 ms fit in one stalled frame of two seconds.
2186        let ticks = Animated::on(Frames::clock(), 0.0);
2187        let counted = Animation::sequence([
2188            Animation::delay(1),
2189            Animation::timing(ticks, 1.0, 0, Easing::Linear),
2190        ])
2191        .repeat(1000)
2192        .start();
2193        frames.step(0.0);
2194        frames.step(2.0);
2195        assert_eq!(counted.outcome(), Some(Outcome::Finished));
2196
2197        // A hundred passes that take no time end within the frame and leave the rest of it to
2198        // the step after them.
2199        let after = Animation::sequence([Animation::delay(0).repeat(100), Animation::delay(100)])
2200            .start_on(Frames::clock());
2201        frames.step(0.0);
2202        frames.step(0.2);
2203        assert_eq!(after.outcome(), Some(Outcome::Finished));
2204
2205        // An endless pass that takes no time at all yields to the next frame instead of spinning.
2206        let forever = Animation::delay(0).looped().start_on(Frames::clock());
2207        frames.step(0.0);
2208        frames.step(0.1);
2209        assert!(forever.is_running());
2210        assert!(forever.stop() && Frames::idle());
2211    }
2212
2213    #[test]
2214    fn the_handle_resolves_for_callbacks_and_for_tasks() {
2215        let frames = Frames::new();
2216        let v = Animated::on(Frames::clock(), 0.0);
2217        let playing = Animation::timing(v, 1.0, 100, Easing::Linear).start();
2218        let heard = Rc::new(Cell::new(None));
2219        let h = heard.clone();
2220        playing.on_end(move |outcome| h.set(Some(outcome)));
2221        let mut task = Box::pin(playing.clone());
2222        let waker = std::task::Waker::noop();
2223        let mut cx = Context::from_waker(waker);
2224        assert!(task.as_mut().poll(&mut cx).is_pending());
2225        frames.run(0.2);
2226        assert_eq!(heard.get(), Some(Outcome::Finished));
2227        assert_eq!(task.as_mut().poll(&mut cx), Poll::Ready(Outcome::Finished));
2228        // A listener added after the end hears at once.
2229        let late = Rc::new(Cell::new(false));
2230        let l = late.clone();
2231        playing.on_end(move |_| l.set(true));
2232        assert!(late.get());
2233    }
2234
2235    #[test]
2236    fn every_write_of_a_frame_reaches_a_binding_in_one_pass() {
2237        let frames = Frames::new();
2238        let values: Vec<Animated> = (0..4).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
2239        let runs = Rc::new(Cell::new(0));
2240        let (r, read) = (runs.clone(), values.clone());
2241        day_reactive::Effect::new(move || {
2242            // One view reading four animated values, as a transform of them would.
2243            let _sum: f64 = read.iter().map(|v| v.get()).sum();
2244            r.set(r.get() + 1);
2245        });
2246        day_reactive::flush_sync();
2247        let before = runs.get();
2248        let playing = Animation::parallel(
2249            values
2250                .iter()
2251                .map(|&v| Animation::timing(v, 1.0, 1000, Easing::Linear)),
2252        )
2253        .start();
2254        frames.step(0.0);
2255        let started = runs.get();
2256        assert!(started <= before + 2);
2257        for _ in 0..10 {
2258            frames.step(1.0 / 60.0);
2259        }
2260        // Ten frames moved four values each; the reader ran once per frame.
2261        assert_eq!(runs.get() - started, 10);
2262        playing.stop();
2263    }
2264
2265    #[test]
2266    fn interpolation_clamps_extends_and_blends_colors() {
2267        let fade = Interpolation::new([0.0, 120.0], [1.0, 0.0]);
2268        assert!(close(fade.at(60.0), 0.5));
2269        assert!(close(fade.at(-30.0), 1.0) && close(fade.at(500.0), 0.0));
2270        let open = fade.clone().extend();
2271        assert!(close(open.at(-60.0), 1.5) && close(open.at(240.0), -1.0));
2272        let one_way = Interpolation::new([0.0, 1.0], [0.0, 10.0]).extend_end();
2273        assert!(close(one_way.at(-1.0), 0.0) && close(one_way.at(2.0), 20.0));
2274
2275        let steps = Interpolation::new([0.0, 1.0, 3.0], [0.0, 10.0, 30.0]);
2276        assert!(close(steps.at(0.5), 5.0) && close(steps.at(2.0), 20.0));
2277        assert!(close(steps.at(1.0), 10.0) && close(steps.at(9.0), 30.0));
2278        assert!(close(Interpolation::new([4.0], [7.0]).at(100.0), 7.0));
2279
2280        let (blue, yellow) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0));
2281        let heat = Interpolation::new([0.0, 1.0], [blue, yellow]);
2282        assert_eq!(heat.at(0.0), blue);
2283        assert_eq!(heat.at(1.0), yellow);
2284        assert_eq!(heat.at(0.5), crate::tween::mix_oklab(blue, yellow, 0.5));
2285        assert_eq!(heat.at(7.0), yellow);
2286
2287        let _frames = Frames::new();
2288        let scroll = Animated::on(Frames::clock(), 60.0);
2289        let opacity = scroll.interpolate([0.0, 120.0], [1.0, 0.0]);
2290        assert!(close(opacity(), 0.5));
2291        scroll.set(120.0);
2292        assert!(close(opacity(), 0.0));
2293    }
2294
2295    #[test]
2296    fn a_spring_and_its_curve_describe_the_same_motion() {
2297        let spring = Spring::from_response(0.5, 0.4);
2298        let Curve::Spring { response, damping } = spring.curve() else {
2299            panic!("a spring's curve is a spring");
2300        };
2301        assert!(close(response, 0.5) && close(damping, 0.4));
2302        // The stepped spring and the closed form agree along the way.
2303        let spec = AnimSpec::spring(0.5, 0.4);
2304        let mut state = SpringState::default();
2305        for i in 1..=60 {
2306            spring.step(&mut state, 1.0, 0.01);
2307            let exact = spec.curve.fraction(f64::from(i) * 0.01, 0.0);
2308            assert!(
2309                (state.value - exact).abs() < 0.01,
2310                "{i}: {} {exact}",
2311                state.value
2312            );
2313        }
2314    }
2315}