Skip to main content

day_core/
tween.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Tweening for self-drawn content (docs/tween.md): the pieces a canvas animation needs that
5//! native widgets get from their toolkit.
6//!
7//! [`with_animation`](crate::with_animation) hands native widgets *intent* and lets each toolkit
8//! animate on its own compositor. A canvas has no compositor to hand anything to: it re-records a
9//! display list, so something has to decide, frame by frame, what the in-between picture is. That
10//! something is built from four parts, each usable on its own:
11//!
12//! * [`Lerp`]: how a value moves between two states. Numbers, points, rects, tuples, arrays,
13//!   vectors, and colors (blended in OKLab, so a heat map's mid-transition cells are the colors in
14//!   between rather than a muddy detour through gray).
15//! * [`Timing`]: an [`AnimSpec`] sampled over elapsed seconds: delay, easing curve or spring,
16//!   repeats and autoreverse, and a definite end, so a driver knows when to stop asking for frames.
17//! * [`animate`]: a driver on the window's [`FrameClock`], calling a step
18//!   closure once per display frame until the timing completes, then releasing the clock.
19//! * [`Tweened`]: a reactive value that glides to each new target, starting from wherever it is when
20//!   retargeted, so an interrupted transition bends instead of jumping.
21//!
22//! [`stagger`] offsets one spec per item, for sequences (bars rising left to right).
23//!
24//! [`Pairs`] is the step before any of them when what changed is a *collection*: it matches the
25//! items of two states by key, gives the ones only one side has somewhere to come from or go to,
26//! and interpolates the lot, so bars that trade places slide and a new one grows out of its
27//! neighbor instead of the whole picture cross-fading.
28
29use std::cell::{Cell, RefCell};
30use std::collections::{HashMap, VecDeque};
31use std::hash::Hash;
32use std::ops::ControlFlow;
33use std::rc::Rc;
34use std::time::Duration;
35
36use day_spec::{AnimSpec, Color, Point, Rect, Size};
37
38use crate::frame::{FrameClock, FrameHandle};
39
40/// A value that can be interpolated: `a.lerp(&b, 0.0)` is `a`, `a.lerp(&b, 1.0)` is `b`.
41///
42/// `t` may leave `0..=1`: an under-damped spring overshoots, and a numeric value follows it past
43/// the target and back. Implementations that cannot extrapolate (a color's alpha, a count) clamp
44/// the parts that must stay in range.
45pub trait Lerp: Clone {
46    #[must_use]
47    fn lerp(&self, to: &Self, t: f64) -> Self;
48}
49
50/// `a + (b - a) * t`, the scalar every other implementation is built from.
51#[inline]
52#[must_use]
53pub fn lerp(a: f64, b: f64, t: f64) -> f64 {
54    a + (b - a) * t
55}
56
57impl Lerp for f64 {
58    fn lerp(&self, to: &Self, t: f64) -> Self {
59        lerp(*self, *to, t)
60    }
61}
62
63impl Lerp for f32 {
64    fn lerp(&self, to: &Self, t: f64) -> Self {
65        lerp(f64::from(*self), f64::from(*to), t) as f32
66    }
67}
68
69impl Lerp for Point {
70    fn lerp(&self, to: &Self, t: f64) -> Self {
71        Point::new(lerp(self.x, to.x, t), lerp(self.y, to.y, t))
72    }
73}
74
75impl Lerp for Size {
76    fn lerp(&self, to: &Self, t: f64) -> Self {
77        Size::new(
78            lerp(self.width, to.width, t).max(0.0),
79            lerp(self.height, to.height, t).max(0.0),
80        )
81    }
82}
83
84impl Lerp for Rect {
85    fn lerp(&self, to: &Self, t: f64) -> Self {
86        Rect {
87            origin: self.origin.lerp(&to.origin, t),
88            size: self.size.lerp(&to.size, t),
89        }
90    }
91}
92
93/// Colors blend in OKLab (Björn Ottosson's perceptual space), alpha linearly: the midpoint of blue
94/// and yellow is a clean mid-lightness color rather than sRGB's dim gray, and a sequential scale's
95/// in-between cells read as in-between values. The endpoints are exact.
96impl Lerp for Color {
97    fn lerp(&self, to: &Self, t: f64) -> Self {
98        mix_oklab(*self, *to, t)
99    }
100}
101
102impl<A: Lerp, B: Lerp> Lerp for (A, B) {
103    fn lerp(&self, to: &Self, t: f64) -> Self {
104        (self.0.lerp(&to.0, t), self.1.lerp(&to.1, t))
105    }
106}
107
108impl<A: Lerp, B: Lerp, C: Lerp> Lerp for (A, B, C) {
109    fn lerp(&self, to: &Self, t: f64) -> Self {
110        (
111            self.0.lerp(&to.0, t),
112            self.1.lerp(&to.1, t),
113            self.2.lerp(&to.2, t),
114        )
115    }
116}
117
118impl<T: Lerp, const N: usize> Lerp for [T; N] {
119    fn lerp(&self, to: &Self, t: f64) -> Self {
120        std::array::from_fn(|i| self[i].lerp(&to[i], t))
121    }
122}
123
124/// Element-wise over the common prefix; the target's extra elements (or the source's missing ones)
125/// take the target's values, so a series that grew draws its new tail where it is headed. A caller
126/// that wants entering elements to grow in matches them up first; `Vec` has no idea what they mean.
127impl<T: Lerp> Lerp for Vec<T> {
128    fn lerp(&self, to: &Self, t: f64) -> Self {
129        to.iter()
130            .enumerate()
131            .map(|(i, b)| match self.get(i) {
132                Some(a) => a.lerp(b, t),
133                None => b.clone(),
134            })
135            .collect()
136    }
137}
138
139/// Both present: interpolate. Otherwise there is nothing to move between, so the value switches at
140/// the midpoint.
141impl<T: Lerp> Lerp for Option<T> {
142    fn lerp(&self, to: &Self, t: f64) -> Self {
143        match (self, to) {
144            (Some(a), Some(b)) => Some(a.lerp(b, t)),
145            _ if t < 0.5 => self.clone(),
146            _ => to.clone(),
147        }
148    }
149}
150
151// --- OKLab ------------------------------------------------------------------------------------
152
153fn to_linear(c: f64) -> f64 {
154    if c <= 0.04045 {
155        c / 12.92
156    } else {
157        ((c + 0.055) / 1.055).powf(2.4)
158    }
159}
160
161fn to_srgb(c: f64) -> f64 {
162    if c <= 0.003_130_8 {
163        c * 12.92
164    } else {
165        1.055 * c.powf(1.0 / 2.4) - 0.055
166    }
167}
168
169fn oklab(c: Color) -> [f64; 3] {
170    let (r, g, b) = (to_linear(c.r), to_linear(c.g), to_linear(c.b));
171    let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
172    let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
173    let s = (0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b).cbrt();
174    [
175        0.210_454_255_3 * l + 0.793_617_785_0 * m - 0.004_072_046_8 * s,
176        1.977_998_495_1 * l - 2.428_592_205_0 * m + 0.450_593_709_9 * s,
177        0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766_0 * s,
178    ]
179}
180
181fn from_oklab([l, a, b]: [f64; 3], alpha: f64) -> Color {
182    let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
183    let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
184    let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
185    let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
186    let r = 4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3;
187    let g = -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3;
188    let bl = -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3;
189    let ch = |v: f64| to_srgb(v.max(0.0)).clamp(0.0, 1.0);
190    Color::rgba(ch(r), ch(g), ch(bl), alpha.clamp(0.0, 1.0))
191}
192
193/// Blend two colors in OKLab by `t`, alpha linearly. `t` outside `0..=1` extrapolates the
194/// lightness and hue axes and clamps the result into gamut.
195#[expect(
196    clippy::float_cmp,
197    reason = "exactly 0.0 and 1.0 select the endpoints unchanged"
198)]
199pub fn mix_oklab(a: Color, b: Color, t: f64) -> Color {
200    // The endpoints are the endpoints, not a round trip through two color spaces.
201    if t == 0.0 {
202        return a;
203    }
204    if t == 1.0 {
205        return b;
206    }
207    let (p, q) = (oklab(a), oklab(b));
208    from_oklab(
209        [
210            lerp(p[0], q[0], t),
211            lerp(p[1], q[1], t),
212            lerp(p[2], q[2], t),
213        ],
214        lerp(a.a, b.a, t),
215    )
216}
217
218// --- Timing -----------------------------------------------------------------------------------
219
220/// One sample of a [`Timing`]: how far the value has come, and whether it has arrived.
221#[derive(Clone, Copy, Debug, PartialEq)]
222pub struct Sample {
223    /// `0` at the start, `1` at the end. A spring may overshoot on the way; the final sample is
224    /// exactly the end value (`1`, or `0` for an autoreversed cycle count that ends where it began).
225    pub progress: f64,
226    /// Whether this sample is the last one. A driver stops requesting frames after it.
227    pub done: bool,
228}
229
230/// An [`AnimSpec`] as a function of elapsed seconds.
231///
232/// Easing curves run for `duration_ms`. A spring runs its analytic step response and ends at
233/// `duration_ms`, which `AnimSpec::spring` sets to the spring's `response`: that is how every Day
234/// backend times a spring, so a canvas transition and a native one started together land together.
235#[derive(Clone, Copy, Debug, PartialEq)]
236pub struct Timing {
237    pub spec: AnimSpec,
238}
239
240impl Timing {
241    #[must_use]
242    pub fn new(spec: AnimSpec) -> Self {
243        Timing { spec }
244    }
245
246    /// One cycle, in seconds.
247    fn cycle(&self) -> f64 {
248        (f64::from(self.spec.duration_ms) / 1000.0).max(0.0)
249    }
250
251    /// The whole run including the delay, or `None` for a spec that repeats forever.
252    #[must_use]
253    pub fn total(&self) -> Option<f64> {
254        if self.spec.repeat == u32::MAX {
255            return None;
256        }
257        Some(
258            f64::from(self.spec.delay_ms) / 1000.0
259                + self.cycle() * (f64::from(self.spec.repeat) + 1.0),
260        )
261    }
262
263    /// Where the transition is `elapsed` seconds after it was started.
264    #[must_use]
265    pub fn sample(&self, elapsed: f64) -> Sample {
266        let t = elapsed - f64::from(self.spec.delay_ms) / 1000.0;
267        if t < 0.0 || !t.is_finite() {
268            return Sample {
269                progress: 0.0,
270                done: false,
271            };
272        }
273        let one = self.cycle();
274        let reverses = self.spec.autoreverse;
275        let cycles = self.spec.repeat.saturating_add(1);
276        let forever = self.spec.repeat == u32::MAX;
277        if one <= 0.0 {
278            return Sample {
279                progress: 1.0,
280                done: true,
281            };
282        }
283        let index = (t / one).floor();
284        if !forever && index >= f64::from(cycles) {
285            // Arrived. An autoreversed run of an even number of cycles ends back at the start.
286            let back = reverses && cycles.is_multiple_of(2);
287            return Sample {
288                progress: if back { 0.0 } else { 1.0 },
289                done: true,
290            };
291        }
292        let mut local = t - index * one;
293        if reverses && (index as u64) % 2 == 1 {
294            local = one - local;
295        }
296        // A spring evaluates its own step response, which may overshoot; an easing curve its
297        // shape over the cycle. `Curve::fraction` is both.
298        Sample {
299            progress: self.spec.curve.fraction(local, one),
300            done: false,
301        }
302    }
303}
304
305/// `spec`, delayed for item `index` of `count` so the items start `spread_ms` apart in total:
306/// the first starts on time, the last `spread_ms` later. Bars rising left to right, points popping
307/// in along a line: a sequence is one spec per item, and this is the arithmetic.
308pub fn stagger(spec: AnimSpec, index: usize, count: usize, spread_ms: u32) -> AnimSpec {
309    let step = if count > 1 {
310        f64::from(spread_ms) / (count - 1) as f64
311    } else {
312        0.0
313    };
314    AnimSpec {
315        delay_ms: spec.delay_ms + (step * index as f64).round() as u32,
316        ..spec
317    }
318}
319
320// --- Drivers ----------------------------------------------------------------------------------
321
322/// Call `step(sample)` once per display frame of `clock` until `timing` is done, then stop.
323///
324/// Elapsed time is measured from the first frame delivered, not from this call, so a transition
325/// started while the app is busy begins on screen rather than part-way through. The final call has
326/// `sample.done == true` and the exact end value; after it the subscription ends and the window
327/// requests no more frames on this transition's behalf. Keep the handle, or call
328/// [`FrameHandle::in_scope`]: dropping it cancels the transition where it stands.
329pub fn animate(
330    clock: FrameClock,
331    timing: Timing,
332    mut step: impl FnMut(Sample) + 'static,
333) -> FrameHandle {
334    // Under reduced motion, finish finite decorative tweens on their first frame. Keep
335    // continuous animations and simulations running; they have no meaningful final state. The
336    // check is per frame, not per start, so a setting flipped mid-flight lands the tween too.
337    let finish = |timing: &Timing| {
338        (crate::reduce_motion_now() && timing.total().is_some()).then_some(Sample {
339            progress: if timing.spec.duration_ms > 0
340                && timing.spec.autoreverse
341                && timing.spec.repeat % 2 == 1
342            {
343                0.0
344            } else {
345                1.0
346            },
347            done: true,
348        })
349    };
350    let mut start: Option<Duration> = None;
351    clock.subscribe(move |frame| {
352        let t0 = *start.get_or_insert(frame.timestamp);
353        let elapsed = frame.timestamp.saturating_sub(t0).as_secs_f64();
354        let sample = finish(&timing).unwrap_or_else(|| timing.sample(elapsed));
355        step(sample);
356        if sample.done {
357            ControlFlow::Break(())
358        } else {
359            ControlFlow::Continue(())
360        }
361    })
362}
363
364struct Flight<T> {
365    from: T,
366    to: T,
367    handle: Option<FrameHandle>,
368}
369
370/// A value that animates toward whatever it is told to become.
371///
372/// Reads are reactive, so a canvas that reads a `Tweened` re-records every frame of its
373/// transition and not otherwise. Retargeting mid-flight starts the new transition from the value
374/// on screen, which keeps the motion continuous: a slider dragged back and forth bends the path
375/// instead of snapping it.
376///
377/// ```rust,ignore
378/// let height = Tweened::new(0.0);
379/// button("Grow").action(move || height.animate_to(120.0, AnimSpec::spring(0.4, 0.8)));
380/// canvas(move |d, _| d.fill(Shape::Rect(Rect::new(0.0, 0.0, 40.0, height.get())), BLUE));
381/// ```
382pub struct Tweened<T: Lerp + 'static> {
383    shown: day_reactive::Signal<T>,
384    flight: Rc<RefCell<Flight<T>>>,
385    clock: FrameClock,
386    moving: Rc<Cell<bool>>,
387}
388
389impl<T: Lerp + 'static> Clone for Tweened<T> {
390    fn clone(&self) -> Self {
391        Tweened {
392            shown: self.shown,
393            flight: self.flight.clone(),
394            clock: self.clock,
395            moving: self.moving.clone(),
396        }
397    }
398}
399
400impl<T: Lerp + 'static> Tweened<T> {
401    /// A value at `initial`, animating on the current page's window.
402    pub fn new(initial: T) -> Self {
403        Self::on(FrameClock::current(), initial)
404    }
405
406    /// A value at `initial`, animating on `clock`.
407    pub fn on(clock: FrameClock, initial: T) -> Self {
408        Tweened {
409            shown: day_reactive::Signal::new(initial.clone()),
410            flight: Rc::new(RefCell::new(Flight {
411                from: initial.clone(),
412                to: initial,
413                handle: None,
414            })),
415            clock,
416            moving: Rc::new(Cell::new(false)),
417        }
418    }
419
420    /// The value on screen now; tracked.
421    #[must_use]
422    pub fn get(&self) -> T {
423        self.shown.get()
424    }
425
426    /// The value on screen now, without subscribing.
427    #[must_use]
428    pub fn get_untracked(&self) -> T {
429        self.shown.get_untracked()
430    }
431
432    /// Where the value is headed (the value itself once it has arrived).
433    #[must_use]
434    pub fn target(&self) -> T {
435        self.flight.borrow().to.clone()
436    }
437
438    /// Whether a transition is in flight.
439    #[must_use]
440    pub fn is_animating(&self) -> bool {
441        self.moving.get()
442    }
443
444    /// Jump to `value`, cancelling any transition.
445    pub fn set(&self, value: T) {
446        let mut f = self.flight.borrow_mut();
447        if let Some(h) = f.handle.take() {
448            h.cancel();
449        }
450        f.from = value.clone();
451        f.to = value.clone();
452        drop(f);
453        self.moving.set(false);
454        self.shown.set(value);
455    }
456
457    /// Animate from the value on screen to `target` under `spec`.
458    pub fn animate_to(&self, target: T, spec: AnimSpec) {
459        // Reduced motion (docs/accessibility.md): a finite transition lands at once; an
460        // endless one (a spinner, a pulse that is the only sign of work) keeps going.
461        if crate::reduce_motion_now() && spec.repeat != u32::MAX {
462            self.set(target);
463            return;
464        }
465        let from = self.shown.get_untracked();
466        {
467            let mut f = self.flight.borrow_mut();
468            if let Some(h) = f.handle.take() {
469                h.cancel();
470            }
471            f.from = from;
472            f.to = target;
473        }
474        self.moving.set(true);
475        let (flight, shown, moving) = (self.flight.clone(), self.shown, self.moving.clone());
476        let handle = animate(self.clock, Timing::new(spec), move |s| {
477            let v = {
478                let f = flight.borrow();
479                if s.done {
480                    f.to.clone()
481                } else {
482                    f.from.lerp(&f.to, s.progress)
483                }
484            };
485            shown.set(v);
486            if s.done {
487                moving.set(false);
488            }
489        });
490        self.flight.borrow_mut().handle = Some(handle);
491    }
492}
493
494// ---------------------------------------------------------------------------
495// Pairs: matching two collections
496// ---------------------------------------------------------------------------
497
498/// Which side of a change an item of a [`Pairs`] is on.
499#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
500pub enum Change {
501    /// In both states: it moves from where it was to where it is.
502    Kept,
503    /// Only in the new state: it arrives from a stand-in the caller chose.
504    Entering,
505    /// Only in the old state: it departs toward a stand-in the caller chose, and is gone once the
506    /// transition ends.
507    Leaving,
508}
509
510/// One item of a transition between two collections: where it starts, where it ends, and why.
511#[derive(Clone, Debug, PartialEq)]
512pub struct Pair<T> {
513    pub from: T,
514    pub to: T,
515    pub change: Change,
516}
517
518impl<T: Lerp> Pair<T> {
519    /// The item `t` of the way along.
520    pub fn at(&self, t: f64) -> T {
521        self.from.lerp(&self.to, t)
522    }
523}
524
525/// Two states of a collection, matched item by item, ready to be sampled at any `t`.
526///
527/// Built once per change, sampled once per frame: matching is the part that costs something and
528/// it does not depend on `t`. [`Pairs::by_key`] matches by an identity the caller derives; a
529/// caller whose own rules already know what moved where (a sliding-tile game knows which tiles
530/// merged) collects its [`Pair`]s directly (`Pairs: FromIterator`).
531///
532/// ```
533/// use day_core::tween::{Change, Lerp, Pairs, lerp};
534///
535/// #[derive(Clone, Debug, PartialEq)]
536/// struct Bar { name: &'static str, height: f64 }
537///
538/// impl Lerp for Bar {
539///     fn lerp(&self, to: &Self, t: f64) -> Self {
540///         Bar { name: to.name, height: lerp(self.height, to.height, t) }
541///     }
542/// }
543///
544/// let bar = |name, height| Bar { name, height };
545/// // "b" shrinks, "c" grows out of nothing, "a" collapses away.
546/// let before = [bar("a", 3.0), bar("b", 5.0)];
547/// let after = [bar("b", 1.0), bar("c", 4.0)];
548/// let pairs = Pairs::by_key(&before, &after, |b| b.name, |b, _| bar(b.name, 0.0));
549/// assert_eq!(pairs.at(0.5), vec![bar("b", 3.0), bar("c", 2.0), bar("a", 1.5)]);
550/// assert_eq!(pairs[2].change, Change::Leaving);
551/// ```
552#[derive(Clone, Debug, PartialEq)]
553pub struct Pairs<T> {
554    items: Vec<Pair<T>>,
555}
556
557impl<T> Default for Pairs<T> {
558    fn default() -> Self {
559        Pairs { items: Vec::new() }
560    }
561}
562
563impl<T: Clone> Pairs<T> {
564    /// Match `from` with `to` by `key`.
565    ///
566    /// * An item whose key is on both sides is [`Change::Kept`]. Keys may repeat: the *n*th item
567    ///   with a key on one side matches the *n*th with that key on the other, so identical tokens
568    ///   (three red gems in a column) pair up in order rather than all with the first.
569    /// * An item only in `to` is [`Change::Entering`]; `absent(item, Change::Entering)` says where
570    ///   it starts. An item only in `from` is [`Change::Leaving`]; `absent(item, Change::Leaving)`
571    ///   says where it ends. That stand-in is the whole of what entering and leaving mean: grown
572    ///   from a baseline, faded out, slid in from a neighbor. The caller decides; the match does
573    ///   not.
574    ///
575    /// The result is in `to`'s order, then the leaving items in `from`'s order, so a renderer
576    /// drawing in sequence draws the arriving picture's order, with what is departing on top.
577    pub fn by_key<K: Eq + Hash>(
578        from: &[T],
579        to: &[T],
580        mut key: impl FnMut(&T) -> K,
581        mut absent: impl FnMut(&T, Change) -> T,
582    ) -> Self {
583        let mut waiting: HashMap<K, VecDeque<usize>> = HashMap::with_capacity(from.len());
584        for (i, item) in from.iter().enumerate() {
585            waiting.entry(key(item)).or_default().push_back(i);
586        }
587        let mut matched = vec![false; from.len()];
588        let mut items = Vec::with_capacity(from.len().max(to.len()));
589        for item in to {
590            let found = waiting.get_mut(&key(item)).and_then(VecDeque::pop_front);
591            items.push(match found {
592                Some(i) => {
593                    matched[i] = true;
594                    Pair {
595                        from: from[i].clone(),
596                        to: item.clone(),
597                        change: Change::Kept,
598                    }
599                }
600                None => Pair {
601                    from: absent(item, Change::Entering),
602                    to: item.clone(),
603                    change: Change::Entering,
604                },
605            });
606        }
607        for (item, _) in from.iter().zip(&matched).filter(|(_, m)| !**m) {
608            items.push(Pair {
609                from: item.clone(),
610                to: absent(item, Change::Leaving),
611                change: Change::Leaving,
612            });
613        }
614        Pairs { items }
615    }
616}
617
618impl<T> Pairs<T> {
619    /// Every item `t` of the way along, in order, through `f`: for items whose in-between depends
620    /// on more than the two ends (a chart mark needs both charts' scales to place itself).
621    pub fn at_with<U>(&self, t: f64, mut f: impl FnMut(&Pair<T>, f64) -> U) -> Vec<U> {
622        self.items.iter().map(|p| f(p, t)).collect()
623    }
624
625    /// Each item at its own progress: `progress(index, pair)` gives the `t` for that item, for
626    /// sequences that do not move in lockstep (cards dealt one after another, see [`stagger`]).
627    pub fn at_each<U>(
628        &self,
629        mut progress: impl FnMut(usize, &Pair<T>) -> f64,
630        mut f: impl FnMut(&Pair<T>, f64) -> U,
631    ) -> Vec<U> {
632        self.items
633            .iter()
634            .enumerate()
635            .map(|(i, p)| f(p, progress(i, p)))
636            .collect()
637    }
638
639    /// The arriving state: every item that is not leaving, at its end. What to draw once the
640    /// transition is over.
641    pub fn settled(&self) -> impl Iterator<Item = &T> {
642        self.items
643            .iter()
644            .filter(|p| p.change != Change::Leaving)
645            .map(|p| &p.to)
646    }
647
648    /// How many items of each kind of [`Change`] there are: `(kept, entering, leaving)`.
649    #[must_use]
650    pub fn counts(&self) -> (usize, usize, usize) {
651        self.items
652            .iter()
653            .fold((0, 0, 0), |(k, e, l), p| match p.change {
654                Change::Kept => (k + 1, e, l),
655                Change::Entering => (k, e + 1, l),
656                Change::Leaving => (k, e, l + 1),
657            })
658    }
659
660    pub fn iter(&self) -> std::slice::Iter<'_, Pair<T>> {
661        self.items.iter()
662    }
663
664    #[must_use]
665    pub fn len(&self) -> usize {
666        self.items.len()
667    }
668
669    #[must_use]
670    pub fn is_empty(&self) -> bool {
671        self.items.is_empty()
672    }
673}
674
675impl<T: Lerp> Pairs<T> {
676    /// Every item `t` of the way along, in order. Leaving items are included until the caller
677    /// stops sampling: at `t = 1` they sit at their stand-ins.
678    #[must_use]
679    pub fn at(&self, t: f64) -> Vec<T> {
680        self.items.iter().map(|p| p.at(t)).collect()
681    }
682}
683
684impl<T> std::ops::Index<usize> for Pairs<T> {
685    type Output = Pair<T>;
686    fn index(&self, i: usize) -> &Pair<T> {
687        &self.items[i]
688    }
689}
690
691impl<T> FromIterator<Pair<T>> for Pairs<T> {
692    fn from_iter<I: IntoIterator<Item = Pair<T>>>(iter: I) -> Self {
693        Pairs {
694            items: iter.into_iter().collect(),
695        }
696    }
697}
698
699impl<T> IntoIterator for Pairs<T> {
700    type Item = Pair<T>;
701    type IntoIter = std::vec::IntoIter<Pair<T>>;
702    fn into_iter(self) -> Self::IntoIter {
703        self.items.into_iter()
704    }
705}
706
707impl<'a, T> IntoIterator for &'a Pairs<T> {
708    type Item = &'a Pair<T>;
709    type IntoIter = std::slice::Iter<'a, Pair<T>>;
710    fn into_iter(self) -> Self::IntoIter {
711        self.items.iter()
712    }
713}
714
715#[cfg(test)]
716mod tests {
717    use super::*;
718
719    fn near(a: f64, b: f64) -> bool {
720        (a - b).abs() < 1e-9
721    }
722
723    #[test]
724    #[expect(
725        clippy::float_cmp,
726        reason = "a finished tween reports a progress of exactly 1.0"
727    )]
728    fn linear_timing_runs_its_duration_then_stops() {
729        let t = Timing::new(AnimSpec::linear(200));
730        assert_eq!(t.sample(0.0).progress, 0.0);
731        assert!(near(t.sample(0.1).progress, 0.5));
732        assert!(!t.sample(0.199).done);
733        let end = t.sample(0.2);
734        assert!(end.done && end.progress == 1.0);
735        assert_eq!(t.total(), Some(0.2));
736    }
737
738    #[test]
739    fn delay_holds_the_start_and_repeat_autoreverse_ends_where_it_began() {
740        let t = Timing::new(AnimSpec {
741            delay_ms: 100,
742            repeat: 1,
743            autoreverse: true,
744            ..AnimSpec::linear(100)
745        });
746        assert_eq!(t.sample(0.05).progress, 0.0);
747        assert!(near(t.sample(0.15).progress, 0.5)); // forward
748        assert!(near(t.sample(0.275).progress, 0.25)); // back
749        let end = t.sample(0.31);
750        assert!(end.done && end.progress == 0.0);
751        assert!(near(t.total().unwrap(), 0.3));
752        let forever = Timing::new(AnimSpec {
753            repeat: u32::MAX,
754            ..AnimSpec::linear(100)
755        });
756        assert!(!forever.sample(1000.0).done);
757        assert_eq!(forever.total(), None);
758    }
759
760    #[test]
761    #[expect(
762        clippy::float_cmp,
763        reason = "a finished tween reports a progress of exactly 1.0"
764    )]
765    fn a_bouncy_spring_overshoots_and_ends_exactly_on_target() {
766        let t = Timing::new(AnimSpec::spring(0.5, 0.4));
767        let peak = (1..50)
768            .map(|i| t.sample(f64::from(i) * 0.01).progress)
769            .fold(0.0, f64::max);
770        assert!(peak > 1.0, "an under-damped spring overshoots: peak {peak}");
771        let end = t.sample(0.5);
772        assert!(end.done && end.progress == 1.0);
773    }
774
775    #[test]
776    fn stagger_spreads_delays_across_the_items() {
777        let s = AnimSpec::linear(300);
778        assert_eq!(stagger(s, 0, 5, 400).delay_ms, 0);
779        assert_eq!(stagger(s, 2, 5, 400).delay_ms, 200);
780        assert_eq!(stagger(s, 4, 5, 400).delay_ms, 400);
781        assert_eq!(stagger(s, 0, 1, 400).delay_ms, 0);
782    }
783
784    #[test]
785    fn tweened_values_ride_the_frame_clock_and_release_it_on_arrival() {
786        use crate::tree::RNode;
787        use day_spec::FrameStamp;
788        use std::collections::VecDeque;
789        let pending: Rc<RefCell<VecDeque<day_spec::FrameCallback>>> = Rc::default();
790        let q = pending.clone();
791        crate::frame::install_frame_requester(move |_, cb| {
792            q.borrow_mut().push_back(cb);
793            Box::new(|| {})
794        });
795        let fire = |ts: f64| {
796            let cb = pending
797                .borrow_mut()
798                .pop_front()
799                .expect("a frame was requested");
800            cb(FrameStamp {
801                timestamp: ts,
802                target_timestamp: None,
803            });
804        };
805        let v = Tweened::on(FrameClock::for_root(RNode::default()), 0.0);
806        v.animate_to(100.0, AnimSpec::linear(100));
807        assert!(v.is_animating());
808        fire(5.0); // the first frame is the start: elapsed 0
809        assert_eq!(v.get_untracked(), 0.0);
810        fire(5.05);
811        assert!(near(v.get_untracked(), 50.0));
812        // Retargeted mid-flight: the new transition starts from the value on screen. The cancelled
813        // transition's request is still queued in this fake (a native source would drop it); the
814        // frame service ignores its delivery.
815        v.animate_to(0.0, AnimSpec::linear(100));
816        fire(5.06);
817        fire(5.07); // the new transition's first frame
818        assert!(near(v.get_untracked(), 50.0));
819        fire(5.12);
820        assert!(near(v.get_untracked(), 25.0));
821        fire(5.18);
822        assert_eq!(v.get_untracked(), 0.0);
823        assert!(!v.is_animating());
824        assert!(
825            pending.borrow().is_empty(),
826            "no frames requested after arrival"
827        );
828    }
829
830    #[test]
831    fn values_interpolate_and_colors_keep_their_endpoints() {
832        assert!(near(10.0.lerp(&20.0, 0.25), 12.5));
833        let r = Rect::new(0.0, 0.0, 10.0, 10.0).lerp(&Rect::new(10.0, 10.0, 30.0, 10.0), 0.5);
834        assert_eq!(r, Rect::new(5.0, 5.0, 20.0, 10.0));
835        let (blue, yellow) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0));
836        let a = blue.lerp(&yellow, 0.0);
837        let b = blue.lerp(&yellow, 1.0);
838        assert_eq!(a, blue);
839        assert_eq!(b, yellow);
840        // The OKLab midpoint of blue and yellow is lighter than sRGB's gray (0.5, 0.5, 0.5).
841        let mid = blue.lerp(&yellow, 0.5);
842        assert!(mid.r + mid.g + mid.b > 1.6, "{mid:?}");
843        assert_eq!(
844            vec![0.0, 1.0].lerp(&vec![2.0, 3.0, 9.0], 0.5),
845            vec![1.0, 2.0, 9.0]
846        );
847        assert_eq!(Some(1.0).lerp(&None, 0.4), Some(1.0));
848        assert_eq!(Some(1.0).lerp(&None, 0.6), None);
849    }
850
851    // --- Pairs -----------------------------------------------------------------------------
852
853    /// A keyed value, the shape most callers pair: an identity and something that moves.
854    #[derive(Clone, Debug, PartialEq)]
855    struct Item {
856        key: &'static str,
857        at: f64,
858    }
859
860    impl Lerp for Item {
861        fn lerp(&self, to: &Self, t: f64) -> Self {
862            Item {
863                key: to.key,
864                at: lerp(self.at, to.at, t),
865            }
866        }
867    }
868
869    fn item(key: &'static str, at: f64) -> Item {
870        Item { key, at }
871    }
872
873    /// Stand-ins at zero, the way a bar grows from its baseline.
874    fn from_zero(i: &Item, _: Change) -> Item {
875        item(i.key, 0.0)
876    }
877
878    fn by_key(from: &[Item], to: &[Item]) -> Pairs<Item> {
879        Pairs::by_key(from, to, |i| i.key, from_zero)
880    }
881
882    fn changes(p: &Pairs<Item>) -> Vec<(&'static str, Change)> {
883        p.iter().map(|p| (p.to.key, p.change)).collect()
884    }
885
886    #[test]
887    fn items_are_kept_entering_or_leaving_in_arriving_order_then_leaving() {
888        let p = by_key(
889            &[item("a", 1.0), item("b", 2.0), item("c", 3.0)],
890            &[item("c", 30.0), item("d", 40.0), item("a", 10.0)],
891        );
892        assert_eq!(
893            changes(&p),
894            vec![
895                ("c", Change::Kept),
896                ("d", Change::Entering),
897                ("a", Change::Kept),
898                ("b", Change::Leaving),
899            ]
900        );
901        assert_eq!(p.counts(), (2, 1, 1));
902        // A kept item starts where it was, an entering one at its stand-in, a leaving one where
903        // it was and ends at its stand-in.
904        assert_eq!((p[0].from.at, p[0].to.at), (3.0, 30.0));
905        assert_eq!((p[1].from.at, p[1].to.at), (0.0, 40.0));
906        assert_eq!((p[2].from.at, p[2].to.at), (1.0, 10.0));
907        assert_eq!((p[3].from.at, p[3].to.at), (2.0, 0.0));
908    }
909
910    #[test]
911    fn the_stand_in_is_asked_for_with_the_item_and_its_side() {
912        let mut asked = Vec::new();
913        let p = Pairs::by_key(
914            &[item("gone", 5.0), item("stays", 1.0)],
915            &[item("stays", 2.0), item("new", 7.0)],
916            |i| i.key,
917            |i, change| {
918                asked.push((i.key, i.at, change));
919                // Entering items come from below their target, leaving ones go above.
920                match change {
921                    Change::Entering => item(i.key, i.at - 100.0),
922                    Change::Leaving => item(i.key, i.at + 100.0),
923                    Change::Kept => unreachable!("a kept item has both ends"),
924                }
925            },
926        );
927        assert_eq!(
928            asked,
929            vec![
930                ("new", 7.0, Change::Entering),
931                ("gone", 5.0, Change::Leaving)
932            ]
933        );
934        assert_eq!(p[1].from.at, -93.0);
935        assert_eq!(p[2].to.at, 105.0);
936    }
937
938    #[test]
939    fn repeated_keys_pair_in_order_and_the_surplus_enters_or_leaves() {
940        // Three red gems become two: the first two pair with the first two, the third leaves.
941        let p = by_key(
942            &[item("red", 1.0), item("red", 2.0), item("red", 3.0)],
943            &[item("red", 10.0), item("red", 20.0)],
944        );
945        assert_eq!(p.counts(), (2, 0, 1));
946        assert_eq!((p[0].from.at, p[1].from.at), (1.0, 2.0));
947        assert_eq!((p[2].from.at, p[2].change), (3.0, Change::Leaving));
948        // And the other way: the extra one enters.
949        let p = by_key(&[item("red", 1.0)], &[item("red", 10.0), item("red", 20.0)]);
950        assert_eq!(p.counts(), (1, 1, 0));
951        assert_eq!((p[0].from.at, p[1].change), (1.0, Change::Entering));
952    }
953
954    #[test]
955    fn an_empty_side_makes_everything_enter_or_leave() {
956        let some = [item("a", 1.0), item("b", 2.0)];
957        let arriving = by_key(&[], &some);
958        assert_eq!(arriving.counts(), (0, 2, 0));
959        assert_eq!(arriving.at(0.0), vec![item("a", 0.0), item("b", 0.0)]);
960        let departing = by_key(&some, &[]);
961        assert_eq!(departing.counts(), (0, 0, 2));
962        assert_eq!(departing.at(1.0), vec![item("a", 0.0), item("b", 0.0)]);
963        assert!(by_key(&[], &[]).is_empty());
964        assert!(Pairs::<Item>::default().is_empty());
965    }
966
967    #[test]
968    fn a_permutation_keeps_everything_and_follows_the_new_order() {
969        let from = [item("a", 0.0), item("b", 1.0), item("c", 2.0)];
970        let to = [item("c", 0.0), item("a", 1.0), item("b", 2.0)];
971        let p = by_key(&from, &to);
972        assert_eq!(p.counts(), (3, 0, 0));
973        assert_eq!(
974            p.at(0.0),
975            vec![item("c", 2.0), item("a", 0.0), item("b", 1.0)]
976        );
977        assert_eq!(p.at(1.0), to.to_vec());
978    }
979
980    #[test]
981    fn sampling_runs_from_the_old_state_to_the_new_one_and_past_it() {
982        let p = by_key(&[item("a", 0.0), item("b", 8.0)], &[item("a", 10.0)]);
983        assert_eq!(p.at(0.0), vec![item("a", 0.0), item("b", 8.0)]);
984        assert_eq!(p.at(0.25), vec![item("a", 2.5), item("b", 6.0)]);
985        // At the end the leaving item sits at its stand-in; the caller drops it when done.
986        assert_eq!(p.at(1.0), vec![item("a", 10.0), item("b", 0.0)]);
987        // A spring's overshoot carries the values past their targets.
988        assert_eq!(p.at(1.1)[0].at, 11.0);
989        assert_eq!(
990            p.settled().cloned().collect::<Vec<_>>(),
991            vec![item("a", 10.0)]
992        );
993    }
994
995    #[test]
996    fn at_with_hands_each_pair_and_t_to_the_caller() {
997        let p = by_key(&[item("a", 0.0)], &[item("a", 4.0), item("b", 2.0)]);
998        let got = p.at_with(0.5, |pair, t| (pair.change, pair.at(t).at));
999        assert_eq!(got, vec![(Change::Kept, 2.0), (Change::Entering, 1.0)]);
1000    }
1001
1002    #[test]
1003    fn at_each_gives_every_item_its_own_progress() {
1004        // Dealt one after another: item i starts i quarters later.
1005        let to: Vec<Item> = ["a", "b", "c"].iter().map(|k| item(k, 10.0)).collect();
1006        let p = by_key(&[], &to);
1007        let elapsed = 0.5;
1008        let got = p.at_each(
1009            |i, _| ((elapsed - i as f64 * 0.25) / 0.5).clamp(0.0, 1.0),
1010            |pair, t| pair.at(t).at,
1011        );
1012        assert_eq!(got, vec![10.0, 5.0, 0.0]);
1013    }
1014
1015    #[test]
1016    fn pairs_collected_directly_may_share_a_destination() {
1017        // Two tiles merging into one cell: the rules know it, and a key match could not say it.
1018        let p: Pairs<Point> = [
1019            (Point::new(0.0, 0.0), Point::new(3.0, 0.0)),
1020            (Point::new(1.0, 0.0), Point::new(3.0, 0.0)),
1021        ]
1022        .into_iter()
1023        .map(|(from, to)| Pair {
1024            from,
1025            to,
1026            change: Change::Kept,
1027        })
1028        .collect();
1029        assert_eq!(p.len(), 2);
1030        let mid = p.at(0.5);
1031        assert_eq!(mid, vec![Point::new(1.5, 0.0), Point::new(2.0, 0.0)]);
1032        assert_eq!(p.at(1.0), vec![Point::new(3.0, 0.0); 2]);
1033    }
1034
1035    #[test]
1036    fn pairs_of_library_types_interpolate_with_their_own_lerp() {
1037        let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
1038        let from = [(1u8, Rect::new(0.0, 0.0, 10.0, 10.0), red)];
1039        let to = [(1u8, Rect::new(20.0, 0.0, 10.0, 30.0), blue)];
1040        let p = Pairs::by_key(
1041            &from.map(|(_, r, c)| (r, c)),
1042            &to.map(|(_, r, c)| (r, c)),
1043            |_| 1u8,
1044            |x, _| *x,
1045        );
1046        let (rect, color) = p.at(0.5)[0];
1047        assert_eq!(rect, Rect::new(10.0, 0.0, 10.0, 20.0));
1048        assert!(color != red && color != blue);
1049        assert_eq!(p.at(1.0)[0].1, blue);
1050    }
1051
1052    #[test]
1053    fn keys_are_derived_once_per_item() {
1054        let calls = Cell::new(0);
1055        let from = [item("a", 0.0), item("b", 0.0), item("c", 0.0)];
1056        let to = [item("b", 0.0), item("d", 0.0)];
1057        let _ = Pairs::by_key(
1058            &from,
1059            &to,
1060            |i| {
1061                calls.set(calls.get() + 1);
1062                i.key
1063            },
1064            from_zero,
1065        );
1066        assert_eq!(calls.get(), from.len() + to.len());
1067    }
1068
1069    #[test]
1070    fn iteration_and_indexing_see_the_same_pairs() {
1071        let p = by_key(&[item("a", 1.0)], &[item("a", 2.0), item("b", 3.0)]);
1072        let by_ref: Vec<_> = (&p).into_iter().map(|p| p.to.key).collect();
1073        let by_iter: Vec<_> = p.iter().map(|p| p.to.key).collect();
1074        assert_eq!(by_ref, by_iter);
1075        assert_eq!(p[1].to.key, "b");
1076        let owned: Vec<Pair<Item>> = p.clone().into_iter().collect();
1077        assert_eq!(owned.len(), p.len());
1078        assert_eq!(owned[0], p[0]);
1079    }
1080
1081    /// For random collections with repeated keys, the match accounts for every item exactly
1082    /// once: each arriving item is the end of exactly one non-leaving pair (in its order), each
1083    /// departing item the start of exactly one kept or leaving pair, and the number kept is the
1084    /// size of the keys' multiset intersection.
1085    #[test]
1086    fn every_item_is_accounted_for_exactly_once() {
1087        const KEYS: [&str; 5] = ["a", "b", "c", "d", "e"];
1088        let mut seed = 0x9E37_79B9_7F4A_7C15u64;
1089        let mut next = move |n: usize| {
1090            seed ^= seed << 13;
1091            seed ^= seed >> 7;
1092            seed ^= seed << 17;
1093            (seed % n as u64) as usize
1094        };
1095        for round in 0..200 {
1096            let len_a = next(9);
1097            let len_b = next(9);
1098            // Distinct positions so each item can be recognized after matching.
1099            let from: Vec<Item> = (0..len_a)
1100                .map(|i| item(KEYS[next(KEYS.len())], i as f64))
1101                .collect();
1102            let to: Vec<Item> = (0..len_b)
1103                .map(|i| item(KEYS[next(KEYS.len())], 100.0 + i as f64))
1104                .collect();
1105            let p = Pairs::by_key(
1106                &from,
1107                &to,
1108                |i| i.key,
1109                |i, c| match c {
1110                    Change::Entering => item(i.key, -1.0),
1111                    _ => item(i.key, -2.0),
1112                },
1113            );
1114            let arriving: Vec<&Item> = p.settled().collect();
1115            assert_eq!(arriving, to.iter().collect::<Vec<_>>(), "round {round}");
1116            let mut starts: Vec<f64> = p
1117                .iter()
1118                .filter(|p| p.change != Change::Entering)
1119                .map(|p| p.from.at)
1120                .collect();
1121            starts.sort_by(f64::total_cmp);
1122            let all: Vec<f64> = from.iter().map(|i| i.at).collect();
1123            assert_eq!(starts, all, "round {round}");
1124            let kept = KEYS
1125                .iter()
1126                .map(|k| {
1127                    let a = from.iter().filter(|i| i.key == *k).count();
1128                    let b = to.iter().filter(|i| i.key == *k).count();
1129                    a.min(b)
1130                })
1131                .sum::<usize>();
1132            let (k, e, l) = p.counts();
1133            assert_eq!(
1134                (k, e, l),
1135                (kept, len_b - kept, len_a - kept),
1136                "round {round}"
1137            );
1138            for pair in &p {
1139                match pair.change {
1140                    Change::Kept => assert_eq!(pair.from.key, pair.to.key),
1141                    Change::Entering => assert_eq!(pair.from.at, -1.0),
1142                    Change::Leaving => assert_eq!(pair.to.at, -2.0),
1143                }
1144            }
1145        }
1146    }
1147}