Skip to main content

nsh_core/animation/
motion.rs

1//! Keyframes, staggering and motions: what is played on animated values
2//! described as data, turned into [`Composite`] trees the graph runs like
3//! any other (so every platform plays them, with no code of its own).
4//!
5//! - [`keyframes`]: one value through keyframes, as CSS `@keyframes` and
6//!   the Web Animations API mean them: offsets (missing ones spread
7//!   evenly), an easing per segment, iterations, a direction, a delay.
8//! - [`stagger_delay`]: the delay of each item of a staggered group,
9//!   counted from the first, the last, the center or any item.
10//! - [`MotionSpec`]: several channels of a view ([`MotionChannel`]: opacity and
11//!   the parts of its transform) through keyframes with one timing, or each
12//!   on one spring to where its keyframes end, and the ready-made ones
13//!   ([`MotionPreset`]: entrances, exits, attention seekers and loops). The
14//!   values are the app's: a motion has no look, it only moves what the app
15//!   styled.
16
17use super::ops::{Composite, Driver, Easing, NodeId};
18use crate::{TransformKind, element::Spring};
19
20/// One keyframe of a value: where it is at `offset` (0..=1 of an
21/// iteration) and the easing of the segment that starts there.
22#[derive(Debug, Clone, Copy, PartialEq)]
23#[non_exhaustive]
24pub struct Keyframe {
25    /// Where it is in the iteration, 0..=1; `None` spreads it evenly
26    /// between its neighbors (the first is 0 and the last 1 by default).
27    pub offset: Option<f32>,
28    /// The value there.
29    pub value: f32,
30    /// The curve to the next keyframe (`None`: the timing's).
31    pub easing: Option<Easing>,
32}
33
34impl Default for Keyframe {
35    fn default() -> Self {
36        Self {
37            offset: None,
38            value: 0.0,
39            easing: None,
40        }
41    }
42}
43
44impl Keyframe {
45    /// `value`, spread evenly with the keyframes around it.
46    pub const fn new(value: f32) -> Self {
47        Self {
48            offset: None,
49            value,
50            easing: None,
51        }
52    }
53
54    /// `value` at `offset` (0..=1).
55    pub const fn at(offset: f32, value: f32) -> Self {
56        Self {
57            offset: Some(offset),
58            value,
59            easing: None,
60        }
61    }
62
63    /// With `easing` for the segment that starts here.
64    pub const fn ease(mut self, easing: Easing) -> Self {
65        self.easing = Some(easing);
66        self
67    }
68}
69
70/// Which way the iterations of keyframes play (CSS `animation-direction`).
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub enum PlaybackDirection {
73    /// From the first keyframe to the last, each iteration.
74    #[default]
75    Normal,
76    /// From the last to the first.
77    Reverse,
78    /// Forwards, then backwards, and so on.
79    Alternate,
80    /// Backwards, then forwards, and so on.
81    AlternateReverse,
82}
83
84impl PlaybackDirection {
85    /// Parses a CSS `animation-direction`.
86    pub fn parse(name: &str) -> Option<PlaybackDirection> {
87        Some(match name {
88            "normal" => PlaybackDirection::Normal,
89            "reverse" => PlaybackDirection::Reverse,
90            "alternate" => PlaybackDirection::Alternate,
91            "alternate-reverse" => PlaybackDirection::AlternateReverse,
92            _ => return None,
93        })
94    }
95
96    /// Its CSS name.
97    pub fn name(self) -> &'static str {
98        match self {
99            PlaybackDirection::Normal => "normal",
100            PlaybackDirection::Reverse => "reverse",
101            PlaybackDirection::Alternate => "alternate",
102            PlaybackDirection::AlternateReverse => "alternate-reverse",
103        }
104    }
105
106    /// Whether iteration `index` (from 0) plays backwards.
107    fn reversed(self, index: u32) -> bool {
108        match self {
109            PlaybackDirection::Normal => false,
110            PlaybackDirection::Reverse => true,
111            PlaybackDirection::Alternate => !index.is_multiple_of(2),
112            PlaybackDirection::AlternateReverse => index.is_multiple_of(2),
113        }
114    }
115
116    fn alternates(self) -> bool {
117        matches!(
118            self,
119            PlaybackDirection::Alternate | PlaybackDirection::AlternateReverse
120        )
121    }
122}
123
124/// How keyframes play (CSS `animation-duration`, `-delay`,
125/// `-timing-function`, `-iteration-count` and `-direction`).
126#[derive(Debug, Clone, Copy, PartialEq)]
127#[non_exhaustive]
128pub struct KeyframeTiming {
129    /// One iteration, in milliseconds.
130    pub duration_ms: f32,
131    /// Before the first iteration, in milliseconds.
132    pub delay_ms: f32,
133    /// The curve of each segment without one of its own (CSS `ease` by
134    /// default; as in CSS it shapes every segment, not the whole).
135    pub easing: Easing,
136    /// How many iterations; `None` repeats until stopped.
137    pub iterations: Option<u32>,
138    /// Which way the iterations play.
139    pub direction: PlaybackDirection,
140    /// The highest frame rate it needs, in Hz ([`super::Driver::frame_rate`]);
141    /// `None`: the screen's highest.
142    pub frame_rate: Option<f32>,
143}
144
145impl Default for KeyframeTiming {
146    fn default() -> Self {
147        Self {
148            duration_ms: 300.0,
149            delay_ms: 0.0,
150            easing: Easing::EASE,
151            iterations: Some(1),
152            direction: PlaybackDirection::Normal,
153            frame_rate: None,
154        }
155    }
156}
157
158impl KeyframeTiming {
159    /// One iteration of `duration_ms` with the defaults otherwise.
160    pub fn new(duration_ms: f32) -> Self {
161        Self {
162            duration_ms,
163            ..Self::default()
164        }
165    }
166
167    /// With `easing` for segments without one.
168    pub fn easing(mut self, easing: Easing) -> Self {
169        self.easing = easing;
170        self
171    }
172
173    /// Waiting `delay_ms` before the first iteration.
174    pub fn delay(mut self, delay_ms: f32) -> Self {
175        self.delay_ms = delay_ms;
176        self
177    }
178
179    /// `iterations` times (`None`: until stopped).
180    pub fn iterations(mut self, iterations: Option<u32>) -> Self {
181        self.iterations = iterations;
182        self
183    }
184
185    /// Repeating until stopped.
186    pub fn infinite(self) -> Self {
187        self.iterations(None)
188    }
189
190    /// Playing in `direction`.
191    pub fn direction(mut self, direction: PlaybackDirection) -> Self {
192        self.direction = direction;
193        self
194    }
195
196    /// Needing at most `hz` frames per second.
197    pub fn frame_rate(mut self, hz: f32) -> Self {
198        self.frame_rate = Some(hz);
199        self
200    }
201}
202
203/// Keyframes with their offsets resolved (increasing, within 0..=1), as
204/// the Web Animations API spaces them: the first defaults to 0 and the
205/// last to 1 (a single one is the end), the ones between spread evenly
206/// between their neighbors with an offset.
207fn resolve(frames: &[Keyframe]) -> Vec<(f32, f32, Option<Easing>)> {
208    let n = frames.len();
209    let mut offsets: Vec<Option<f32>> = frames
210        .iter()
211        .map(|f| {
212            f.offset
213                .filter(|o| o.is_finite())
214                .map(|o| o.clamp(0.0, 1.0))
215        })
216        .collect();
217    if n == 1 {
218        offsets[0].get_or_insert(1.0);
219    } else if n > 1 {
220        offsets[0].get_or_insert(0.0);
221        offsets[n - 1].get_or_insert(1.0);
222    }
223    let mut i = 0;
224    while i < n {
225        if offsets[i].is_some() {
226            i += 1;
227            continue;
228        }
229        let start = i - 1;
230        let mut end = i;
231        while offsets[end].is_none() {
232            end += 1;
233        }
234        let (a, b) = (offsets[start].unwrap_or(0.0), offsets[end].unwrap_or(1.0));
235        for (k, slot) in offsets.iter_mut().enumerate().take(end).skip(i) {
236            *slot = Some(a + (b - a) * (k - start) as f32 / (end - start) as f32);
237        }
238        i = end;
239    }
240    // Offsets go up: one below the one before it is held there.
241    let mut last = 0.0f32;
242    frames
243        .iter()
244        .zip(offsets)
245        .map(|(f, o)| {
246            let o = o.unwrap_or(1.0).max(last);
247            last = o;
248            (o, f.value, f.easing)
249        })
250        .collect()
251}
252
253/// One iteration over `frames` (resolved), forwards or backwards.
254fn iteration(
255    node: NodeId,
256    frames: &[(f32, f32, Option<Easing>)],
257    timing: &KeyframeTiming,
258    backwards: bool,
259) -> Composite {
260    let duration = timing.duration_ms.max(0.0);
261    // Backwards, offsets mirror and each segment runs its curve reversed.
262    let oriented: Vec<(f32, f32, Easing)> = if backwards {
263        let mut out = Vec::with_capacity(frames.len());
264        for i in (0..frames.len()).rev() {
265            let easing = match i {
266                0 => timing.easing,
267                _ => frames[i - 1].2.unwrap_or(timing.easing).reversed(),
268            };
269            out.push((1.0 - frames[i].0, frames[i].1, easing));
270        }
271        out
272    } else {
273        frames
274            .iter()
275            .map(|&(o, v, e)| (o, v, e.unwrap_or(timing.easing)))
276            .collect()
277    };
278    let timing_to = |to: f32, ms: f32, easing: Easing| Composite::Run {
279        node,
280        driver: Driver::Timing {
281            to,
282            duration_ms: ms,
283            easing,
284            delay_ms: 0.0,
285            frame_rate: timing.frame_rate,
286        },
287    };
288    let mut steps = Vec::with_capacity(oriented.len() + 1);
289    let Some(&(first_offset, first_value, _)) = oriented.first() else {
290        return Composite::Sequence(steps);
291    };
292    // Without a keyframe at 0 the value goes from where it is, as CSS
293    // goes from the underlying value.
294    steps.push(timing_to(
295        first_value,
296        first_offset * duration,
297        timing.easing,
298    ));
299    for pair in oriented.windows(2) {
300        let ((a, _, easing), (b, value, _)) = (pair[0], pair[1]);
301        steps.push(timing_to(value, (b - a) * duration, easing));
302    }
303    let last = oriented.last().map_or(1.0, |f| f.0);
304    if last < 1.0 {
305        steps.push(Composite::Delay((1.0 - last) * duration));
306    }
307    Composite::Sequence(steps)
308}
309
310/// The value `node` through `frames` as `timing` says: a tree of timing
311/// steps the graph runs natively, each starting at the exact end of the
312/// one before. Each iteration starts at its first keyframe (a jump, as in
313/// CSS), so a loop of keyframes that end where they start never jumps;
314/// a delay holds that first keyframe (CSS `animation-fill-mode:
315/// backwards`). The value stays where the last iteration leaves it.
316pub fn keyframes(node: NodeId, frames: &[Keyframe], timing: &KeyframeTiming) -> Composite {
317    let frames = resolve(frames);
318    let pass = |index| iteration(node, &frames, timing, timing.direction.reversed(index));
319    let body = match (timing.iterations, timing.direction.alternates()) {
320        (Some(0), _) => Composite::Sequence(Vec::new()),
321        (Some(1), _) => pass(0),
322        (iterations, false) => Composite::Loop {
323            child: Box::new(pass(0)),
324            iterations,
325            reset: false,
326        },
327        (None, true) => Composite::Loop {
328            child: Box::new(Composite::Sequence(vec![pass(0), pass(1)])),
329            iterations: None,
330            reset: false,
331        },
332        (Some(n), true) => {
333            let pairs = Composite::Loop {
334                child: Box::new(Composite::Sequence(vec![pass(0), pass(1)])),
335                iterations: Some(n / 2),
336                reset: false,
337            };
338            match n % 2 {
339                0 => pairs,
340                _ => Composite::Sequence(vec![pairs, pass(0)]),
341            }
342        }
343    };
344    if timing.delay_ms <= 0.0 {
345        return body;
346    }
347    // During the delay the value already holds the first keyframe (CSS
348    // `animation-fill-mode: backwards`), so a delayed entrance does not
349    // show its view at rest first.
350    let mut steps = Vec::with_capacity(3);
351    let first = if timing.direction.reversed(0) {
352        frames.last().map(|f| (1.0 - f.0, f.1))
353    } else {
354        frames.first().map(|f| (f.0, f.1))
355    };
356    if let Some((0.0, value)) = first {
357        steps.push(Composite::Run {
358            node,
359            driver: Driver::Timing {
360                to: value,
361                duration_ms: 0.0,
362                easing: Easing::Linear,
363                delay_ms: 0.0,
364                frame_rate: timing.frame_rate,
365            },
366        });
367    }
368    steps.push(Composite::Delay(timing.delay_ms));
369    steps.push(body);
370    Composite::Sequence(steps)
371}
372
373/// Where the value of `frames` is when keyframes played as `timing` says
374/// begin and when they end: `(start, end)`. `None` without keyframes.
375pub fn keyframe_ends(frames: &[Keyframe], timing: &KeyframeTiming) -> Option<(f32, f32)> {
376    let (first, last) = (frames.first()?.value, frames.last()?.value);
377    let at = |backwards| if backwards { last } else { first };
378    let start = at(timing.direction.reversed(0));
379    let end = match timing.iterations {
380        Some(0) => start,
381        Some(n) => {
382            if timing.direction.reversed(n - 1) {
383                first
384            } else {
385                last
386            }
387        }
388        // Stopped at some point; where a single iteration ends.
389        None => {
390            if timing.direction.reversed(0) {
391                first
392            } else {
393                last
394            }
395        }
396    };
397    Some((start, end))
398}
399
400/// Where the items of a staggered group start counting from.
401#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
402pub enum StaggerFrom {
403    /// The first item starts at once, the others one interval after the
404    /// one before.
405    #[default]
406    First,
407    /// The last item starts at once.
408    Last,
409    /// The middle item starts at once, the others spread out from it.
410    Center,
411    /// The item at this index starts at once.
412    Index(usize),
413}
414
415/// How many intervals item `index` of `count` waits, counted from `from`.
416pub fn stagger_delay(index: usize, count: usize, from: StaggerFrom) -> f32 {
417    if count == 0 {
418        return 0.0;
419    }
420    let index = index.min(count - 1);
421    match from {
422        StaggerFrom::First => index as f32,
423        StaggerFrom::Last => (count - 1 - index) as f32,
424        // Even counts have two middle items; both start at once.
425        StaggerFrom::Center => (index as f32 - (count - 1) as f32 / 2.0).abs().floor(),
426        StaggerFrom::Index(origin) => index.abs_diff(origin.min(count - 1)) as f32,
427    }
428}
429
430/// What a motion moves: the opacity of a view and the parts of its
431/// transform, applied in this order (translations first, then rotations,
432/// then scales, about the view's transform origin).
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
434pub enum MotionChannel {
435    /// `opacity` (multiplies the view's), 0..1.
436    Opacity,
437    /// `translateX`, points.
438    TranslateX,
439    /// `translateY`, points.
440    TranslateY,
441    /// `rotate`, degrees clockwise.
442    Rotate,
443    /// `rotateX`, degrees.
444    RotateX,
445    /// `rotateY`, degrees.
446    RotateY,
447    /// `scale`.
448    Scale,
449    /// `scaleX`.
450    ScaleX,
451    /// `scaleY`.
452    ScaleY,
453}
454
455impl MotionChannel {
456    /// Every channel, in the order a motion applies them.
457    pub const ALL: [MotionChannel; 9] = [
458        MotionChannel::Opacity,
459        MotionChannel::TranslateX,
460        MotionChannel::TranslateY,
461        MotionChannel::Rotate,
462        MotionChannel::RotateX,
463        MotionChannel::RotateY,
464        MotionChannel::Scale,
465        MotionChannel::ScaleX,
466        MotionChannel::ScaleY,
467    ];
468
469    /// Its position in [`Self::ALL`].
470    pub fn index(self) -> usize {
471        self as usize
472    }
473
474    /// Its name in styles (`opacity`, `translateX`, ...).
475    pub fn name(self) -> &'static str {
476        match self {
477            MotionChannel::Opacity => "opacity",
478            MotionChannel::TranslateX => "translateX",
479            MotionChannel::TranslateY => "translateY",
480            MotionChannel::Rotate => "rotate",
481            MotionChannel::RotateX => "rotateX",
482            MotionChannel::RotateY => "rotateY",
483            MotionChannel::Scale => "scale",
484            MotionChannel::ScaleX => "scaleX",
485            MotionChannel::ScaleY => "scaleY",
486        }
487    }
488
489    /// The channel named `name`.
490    pub fn parse(name: &str) -> Option<MotionChannel> {
491        MotionChannel::ALL.into_iter().find(|c| c.name() == name)
492    }
493
494    /// Its value at rest (what changes nothing).
495    pub fn identity(self) -> f32 {
496        match self {
497            MotionChannel::Opacity
498            | MotionChannel::Scale
499            | MotionChannel::ScaleX
500            | MotionChannel::ScaleY => 1.0,
501            _ => 0.0,
502        }
503    }
504
505    /// The transform part it binds to (`None`: the opacity).
506    pub fn transform(self) -> Option<TransformKind> {
507        Some(match self {
508            MotionChannel::Opacity => return None,
509            MotionChannel::TranslateX => TransformKind::TranslateX,
510            MotionChannel::TranslateY => TransformKind::TranslateY,
511            MotionChannel::Rotate => TransformKind::Rotate,
512            MotionChannel::RotateX => TransformKind::RotateX,
513            MotionChannel::RotateY => TransformKind::RotateY,
514            MotionChannel::Scale => TransformKind::Scale,
515            MotionChannel::ScaleX => TransformKind::ScaleX,
516            MotionChannel::ScaleY => TransformKind::ScaleY,
517        })
518    }
519}
520
521/// Several channels of a view through keyframes, played with one timing
522/// or one spring: a preset ([`MotionPreset`]) or the app's own.
523#[derive(Debug, Clone, PartialEq, Default)]
524#[non_exhaustive]
525pub struct MotionSpec {
526    /// The keyframes of each channel it moves.
527    pub tracks: Vec<(MotionChannel, Vec<Keyframe>)>,
528    /// How they play.
529    pub timing: KeyframeTiming,
530    /// Plays each channel on this spring instead of through its keyframes:
531    /// from where the value is, keeping its velocity, to where the
532    /// keyframes end ([`keyframe_ends`] of one iteration), after the
533    /// timing's delay. The first keyframe is where the motion starts a
534    /// view that enters ([`MotionSpec::start_values`]); the keyframes
535    /// between, the duration, easings and iterations are not used, nor the
536    /// spring's own velocity (each channel keeps its own).
537    pub spring: Option<Spring>,
538}
539
540impl MotionSpec {
541    /// A motion over `timing` with no tracks yet.
542    pub fn new(timing: KeyframeTiming) -> Self {
543        Self {
544            tracks: Vec::new(),
545            timing,
546            spring: None,
547        }
548    }
549
550    /// With `channel` through `frames` (replacing its track, if any).
551    pub fn track(
552        mut self,
553        channel: MotionChannel,
554        frames: impl IntoIterator<Item = Keyframe>,
555    ) -> Self {
556        let frames: Vec<Keyframe> = frames.into_iter().collect();
557        match self.tracks.iter_mut().find(|(c, _)| *c == channel) {
558            Some((_, f)) => *f = frames,
559            None => self.tracks.push((channel, frames)),
560        }
561        self
562    }
563
564    /// With `channel` through `values`, spread evenly.
565    pub fn values(self, channel: MotionChannel, values: impl IntoIterator<Item = f32>) -> Self {
566        self.track(channel, values.into_iter().map(Keyframe::new))
567    }
568
569    /// With its timing changed by `f`.
570    pub fn timing(mut self, f: impl FnOnce(KeyframeTiming) -> KeyframeTiming) -> Self {
571        self.timing = f(self.timing);
572        self
573    }
574
575    /// Playing each channel on `spring` ([`MotionSpec::spring`]).
576    pub fn spring(mut self, spring: Spring) -> Self {
577        self.spring = Some(spring);
578        self
579    }
580
581    /// Where a channel through `frames` lands.
582    fn end(&self, frames: &[Keyframe]) -> Option<f32> {
583        let timing = match self.spring {
584            Some(_) => KeyframeTiming {
585                iterations: Some(1),
586                ..self.timing
587            },
588            None => self.timing,
589        };
590        keyframe_ends(frames, &timing).map(|(_, end)| end)
591    }
592
593    /// The tree that plays it on the channels' value nodes (`nodes`, by
594    /// [`MotionChannel::index`]). `reduced`: the user asked for less motion,
595    /// so it lands where it ends at once, without moving.
596    pub fn composite(&self, nodes: &[NodeId; 9], reduced: bool) -> Composite {
597        let mut children = Vec::with_capacity(self.tracks.len());
598        for (channel, frames) in &self.tracks {
599            let node = nodes[channel.index()];
600            if reduced {
601                let Some(end) = self.end(frames) else {
602                    continue;
603                };
604                children.push(Composite::Run {
605                    node,
606                    driver: Driver::Timing {
607                        to: end,
608                        duration_ms: 0.0,
609                        easing: Easing::Linear,
610                        delay_ms: 0.0,
611                        frame_rate: self.timing.frame_rate,
612                    },
613                });
614            } else if let Some(spring) = self.spring {
615                let Some(to) = self.end(frames) else {
616                    continue;
617                };
618                children.push(Composite::Run {
619                    node,
620                    driver: Driver::Spring {
621                        to,
622                        stiffness: spring.stiffness,
623                        damping: spring.damping,
624                        mass: spring.mass,
625                        velocity: None,
626                        frame_rate: spring.frame_rate.or(self.timing.frame_rate),
627                    },
628                });
629            } else {
630                children.push(keyframes(node, frames, &self.timing));
631            }
632        }
633        let all = Composite::Parallel {
634            children,
635            stop_together: true,
636        };
637        // The delay of keyframes is theirs (it holds their first frame); a
638        // spring waits with the values left where they are.
639        match self.spring {
640            Some(_) if !reduced && self.timing.delay_ms > 0.0 => {
641                Composite::Sequence(vec![Composite::Delay(self.timing.delay_ms), all])
642            }
643            _ => all,
644        }
645    }
646
647    /// Where each channel it moves starts: a motion that brings a view in
648    /// starts from there, set before its first frame shows.
649    pub fn start_values(&self) -> impl Iterator<Item = (MotionChannel, f32)> + '_ {
650        self.tracks.iter().filter_map(|(channel, frames)| {
651            Some((*channel, keyframe_ends(frames, &self.timing)?.0))
652        })
653    }
654}
655
656/// What a preset is for.
657#[derive(Debug, Clone, Copy, PartialEq, Eq)]
658pub enum MotionKind {
659    /// Brings a view in: it starts hidden or away and ends at rest.
660    Enter,
661    /// Takes a view out: it starts at rest and ends hidden or away.
662    Exit,
663    /// Draws the eye: it starts and ends at rest.
664    Attention,
665    /// Repeats until stopped.
666    Loop,
667}
668
669impl MotionKind {
670    /// Its name (`enter`, `exit`, `attention`, `loop`).
671    pub fn name(self) -> &'static str {
672        match self {
673            MotionKind::Enter => "enter",
674            MotionKind::Exit => "exit",
675            MotionKind::Attention => "attention",
676            MotionKind::Loop => "loop",
677        }
678    }
679}
680
681/// Keyframes of a preset's track: `(offset, value)`.
682type Track = (MotionChannel, &'static [(f32, f32)]);
683
684/// A ready-made motion, as data.
685#[derive(Debug)]
686pub struct PresetDef {
687    /// Its name in JS (`fadeIn`, `shake`, ...).
688    pub name: &'static str,
689    /// What it is for.
690    pub kind: MotionKind,
691    /// One line about it.
692    pub doc: &'static str,
693    duration_ms: f32,
694    easing: Easing,
695    iterations: Option<u32>,
696    direction: PlaybackDirection,
697    tracks: &'static [Track],
698}
699
700impl PresetDef {
701    /// The motion.
702    pub fn spec(&self) -> MotionSpec {
703        let timing = KeyframeTiming {
704            duration_ms: self.duration_ms,
705            easing: self.easing,
706            iterations: self.iterations,
707            direction: self.direction,
708            ..KeyframeTiming::default()
709        };
710        let mut spec = MotionSpec::new(timing);
711        for (channel, frames) in self.tracks {
712            spec = spec.track(*channel, frames.iter().map(|&(o, v)| Keyframe::at(o, v)));
713        }
714        spec
715    }
716}
717
718use MotionChannel::{
719    Opacity as O, Rotate as R, RotateX as RX, RotateY as RY, Scale as S, ScaleX as SX,
720    ScaleY as SY, TranslateX as X, TranslateY as Y,
721};
722
723/// Strong deceleration: things that arrive.
724const OUT_EXPO: Easing = Easing::Bezier(0.16, 1.0, 0.3, 1.0);
725/// Things that leave.
726const IN_QUART: Easing = Easing::Bezier(0.5, 0.0, 0.75, 0.0);
727/// A slight overshoot.
728const OUT_BACK: Easing = Easing::Bezier(0.34, 1.56, 0.64, 1.0);
729const IN_OUT_SINE: Easing = Easing::Bezier(0.37, 0.0, 0.63, 1.0);
730
731macro_rules! presets {
732    ($(
733        $(#[doc = $doc:literal])+
734        $variant:ident $name:literal $kind:ident $ms:literal $easing:expr, $iterations:expr, $direction:ident
735            [$($channel:ident: [$(($o:literal, $v:literal)),* $(,)?]),* $(,)?]
736    )*) => {
737        /// The ready-made motions: entrances, exits, attention seekers and
738        /// loops, as data ([`PresetDef`]). Distances are in points, sized
739        /// for controls and cards; scale a motion's values for larger
740        /// views, or write your own keyframes.
741        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
742        #[non_exhaustive]
743        pub enum MotionPreset {
744            $($(#[doc = $doc])+ $variant,)*
745        }
746
747        /// Every preset, in [`MotionPreset`]'s order.
748        pub const PRESETS: &[PresetDef] = &[$(
749            PresetDef {
750                name: $name,
751                kind: MotionKind::$kind,
752                doc: concat!($($doc),+),
753                duration_ms: $ms,
754                easing: $easing,
755                iterations: $iterations,
756                direction: PlaybackDirection::$direction,
757                tracks: &[$(($channel, &[$(($o, $v)),*])),*],
758            },
759        )*];
760
761        impl MotionPreset {
762            /// Every preset.
763            pub const ALL: &[MotionPreset] = &[$(MotionPreset::$variant),*];
764        }
765    };
766}
767
768presets! {
769    /// Fades in.
770    FadeIn "fadeIn" Enter 300.0 Easing::EaseOut, Some(1), Normal [O: [(0.0, 0.0), (1.0, 1.0)]]
771    /// Fades in, rising into place.
772    FadeInUp "fadeInUp" Enter 450.0 OUT_EXPO, Some(1), Normal
773        [O: [(0.0, 0.0), (1.0, 1.0)], Y: [(0.0, 24.0), (1.0, 0.0)]]
774    /// Fades in, dropping into place.
775    FadeInDown "fadeInDown" Enter 450.0 OUT_EXPO, Some(1), Normal
776        [O: [(0.0, 0.0), (1.0, 1.0)], Y: [(0.0, -24.0), (1.0, 0.0)]]
777    /// Fades in, coming from the left.
778    FadeInLeft "fadeInLeft" Enter 450.0 OUT_EXPO, Some(1), Normal
779        [O: [(0.0, 0.0), (1.0, 1.0)], X: [(0.0, -24.0), (1.0, 0.0)]]
780    /// Fades in, coming from the right.
781    FadeInRight "fadeInRight" Enter 450.0 OUT_EXPO, Some(1), Normal
782        [O: [(0.0, 0.0), (1.0, 1.0)], X: [(0.0, 24.0), (1.0, 0.0)]]
783    /// Fades in, growing from 90 %.
784    ZoomIn "zoomIn" Enter 350.0 OUT_EXPO, Some(1), Normal
785        [O: [(0.0, 0.0), (1.0, 1.0)], S: [(0.0, 0.9), (1.0, 1.0)]]
786    /// Pops in: grows from half its size past its own and settles.
787    PopIn "popIn" Enter 450.0 OUT_BACK, Some(1), Normal
788        [O: [(0.0, 0.0), (0.4, 1.0), (1.0, 1.0)], S: [(0.0, 0.5), (1.0, 1.0)]]
789    /// Bounces in, overshooting twice.
790    BounceIn "bounceIn" Enter 650.0 Easing::Bezier(0.215, 0.61, 0.355, 1.0), Some(1), Normal
791        [O: [(0.0, 0.0), (0.6, 1.0), (1.0, 1.0)],
792         S: [(0.0, 0.3), (0.2, 1.1), (0.4, 0.9), (0.6, 1.03), (0.8, 0.97), (1.0, 1.0)]]
793    /// Slides up from below, unfaded (sheets, toasts).
794    SlideInUp "slideInUp" Enter 400.0 OUT_EXPO, Some(1), Normal [Y: [(0.0, 64.0), (1.0, 0.0)]]
795    /// Slides down from above, unfaded.
796    SlideInDown "slideInDown" Enter 400.0 OUT_EXPO, Some(1), Normal [Y: [(0.0, -64.0), (1.0, 0.0)]]
797    /// Flips in about its horizontal axis.
798    FlipInX "flipInX" Enter 600.0 Easing::EaseOut, Some(1), Normal
799        [O: [(0.0, 0.0), (0.6, 1.0), (1.0, 1.0)], RX: [(0.0, 90.0), (0.4, -20.0), (0.6, 10.0), (0.8, -5.0), (1.0, 0.0)]]
800    /// Flips in about its vertical axis.
801    FlipInY "flipInY" Enter 600.0 Easing::EaseOut, Some(1), Normal
802        [O: [(0.0, 0.0), (0.6, 1.0), (1.0, 1.0)], RY: [(0.0, 90.0), (0.4, -20.0), (0.6, 10.0), (0.8, -5.0), (1.0, 0.0)]]
803    /// Fades out.
804    FadeOut "fadeOut" Exit 250.0 Easing::EaseIn, Some(1), Normal [O: [(0.0, 1.0), (1.0, 0.0)]]
805    /// Fades out, rising away.
806    FadeOutUp "fadeOutUp" Exit 300.0 IN_QUART, Some(1), Normal
807        [O: [(0.0, 1.0), (1.0, 0.0)], Y: [(0.0, 0.0), (1.0, -24.0)]]
808    /// Fades out, dropping away.
809    FadeOutDown "fadeOutDown" Exit 300.0 IN_QUART, Some(1), Normal
810        [O: [(0.0, 1.0), (1.0, 0.0)], Y: [(0.0, 0.0), (1.0, 24.0)]]
811    /// Fades out to the left.
812    FadeOutLeft "fadeOutLeft" Exit 300.0 IN_QUART, Some(1), Normal
813        [O: [(0.0, 1.0), (1.0, 0.0)], X: [(0.0, 0.0), (1.0, -24.0)]]
814    /// Fades out to the right.
815    FadeOutRight "fadeOutRight" Exit 300.0 IN_QUART, Some(1), Normal
816        [O: [(0.0, 1.0), (1.0, 0.0)], X: [(0.0, 0.0), (1.0, 24.0)]]
817    /// Fades out, shrinking to 90 %.
818    ZoomOut "zoomOut" Exit 250.0 IN_QUART, Some(1), Normal
819        [O: [(0.0, 1.0), (1.0, 0.0)], S: [(0.0, 1.0), (1.0, 0.9)]]
820    /// Pops out: swells a little, then shrinks away.
821    PopOut "popOut" Exit 300.0 Easing::EaseIn, Some(1), Normal
822        [O: [(0.0, 1.0), (0.3, 1.0), (1.0, 0.0)], S: [(0.0, 1.0), (0.3, 1.08), (1.0, 0.5)]]
823    /// Slides down out of view, unfaded.
824    SlideOutDown "slideOutDown" Exit 300.0 IN_QUART, Some(1), Normal [Y: [(0.0, 0.0), (1.0, 64.0)]]
825    /// Slides up out of view, unfaded.
826    SlideOutUp "slideOutUp" Exit 300.0 IN_QUART, Some(1), Normal [Y: [(0.0, 0.0), (1.0, -64.0)]]
827    /// Shakes sideways: a wrong password, an invalid field.
828    Shake "shake" Attention 500.0 Easing::EaseInOut, Some(1), Normal
829        [X: [(0.0, 0.0), (0.1, -8.0), (0.3, 8.0), (0.5, -8.0), (0.7, 8.0), (0.9, -4.0), (1.0, 0.0)]]
830    /// Shakes its head: a gentler no.
831    HeadShake "headShake" Attention 800.0 Easing::EaseInOut, Some(1), Normal
832        [X: [(0.0, 0.0), (0.065, -6.0), (0.185, 5.0), (0.315, -3.0), (0.435, 2.0), (0.5, 0.0), (1.0, 0.0)],
833         RY: [(0.0, 0.0), (0.065, -9.0), (0.185, 7.0), (0.315, -5.0), (0.435, 3.0), (0.5, 0.0), (1.0, 0.0)]]
834    /// Wiggles about its center: something to notice.
835    Wiggle "wiggle" Attention 600.0 Easing::EaseInOut, Some(1), Normal
836        [R: [(0.0, 0.0), (0.15, -6.0), (0.3, 6.0), (0.45, -4.0), (0.6, 4.0), (0.75, -2.0), (1.0, 0.0)]]
837    /// Swings side to side like a hanging sign (hang it from its top edge
838    /// with a top transform origin).
839    Swing "swing" Attention 900.0 Easing::EaseInOut, Some(1), Normal
840        [R: [(0.0, 0.0), (0.2, 15.0), (0.4, -10.0), (0.6, 5.0), (0.8, -5.0), (1.0, 0.0)]]
841    /// Grows a little and back: a soft emphasis.
842    Pulse "pulse" Attention 500.0 Easing::EaseInOut, Some(1), Normal
843        [S: [(0.0, 1.0), (0.5, 1.06), (1.0, 1.0)]]
844    /// Beats twice, like a heart: a like, a favorite.
845    Heartbeat "heartbeat" Attention 900.0 Easing::EaseInOut, Some(1), Normal
846        [S: [(0.0, 1.0), (0.14, 1.25), (0.28, 1.0), (0.42, 1.25), (0.7, 1.0), (1.0, 1.0)]]
847    /// Squashes and stretches like rubber.
848    RubberBand "rubberBand" Attention 800.0 Easing::EaseInOut, Some(1), Normal
849        [SX: [(0.0, 1.0), (0.3, 1.25), (0.4, 0.75), (0.5, 1.15), (0.65, 0.95), (0.75, 1.05), (1.0, 1.0)],
850         SY: [(0.0, 1.0), (0.3, 0.75), (0.4, 1.25), (0.5, 0.85), (0.65, 1.05), (0.75, 0.95), (1.0, 1.0)]]
851    /// Wobbles like jelly.
852    Jello "jello" Attention 800.0 Easing::EaseInOut, Some(1), Normal
853        [SX: [(0.0, 1.0), (0.2, 1.12), (0.4, 0.92), (0.6, 1.05), (0.8, 0.98), (1.0, 1.0)],
854         SY: [(0.0, 1.0), (0.2, 0.88), (0.4, 1.08), (0.6, 0.95), (0.8, 1.02), (1.0, 1.0)]]
855    /// Shrinks, then grows with a wiggle: a reward.
856    Tada "tada" Attention 900.0 Easing::EaseInOut, Some(1), Normal
857        [S: [(0.0, 1.0), (0.1, 0.9), (0.2, 0.9), (0.3, 1.1), (0.9, 1.1), (1.0, 1.0)],
858         R: [(0.0, 0.0), (0.1, -3.0), (0.2, -3.0), (0.3, 3.0), (0.4, -3.0), (0.5, 3.0), (0.6, -3.0), (0.7, 3.0), (0.8, -3.0), (0.9, 3.0), (1.0, 0.0)]]
859    /// Jumps and lands with a squash.
860    Jump "jump" Attention 700.0 Easing::EaseInOut, Some(1), Normal
861        [Y: [(0.0, 0.0), (0.4, -18.0), (0.55, -18.0), (0.8, 0.0), (1.0, 0.0)],
862         SY: [(0.0, 1.0), (0.15, 0.9), (0.4, 1.05), (0.8, 0.92), (1.0, 1.0)]]
863    /// Blinks out and in twice.
864    Flash "flash" Attention 800.0 Easing::Linear, Some(1), Normal
865        [O: [(0.0, 1.0), (0.25, 0.0), (0.5, 1.0), (0.75, 0.0), (1.0, 1.0)]]
866    /// Turns once, forever (CSS `animate-spin`'s turn on a motion).
867    Spin "spin" Loop 1000.0 Easing::Linear, None, Normal [R: [(0.0, 0.0), (1.0, 360.0)]]
868    /// Floats up and down, forever.
869    Float "float" Loop 1500.0 IN_OUT_SINE, None, Alternate [Y: [(0.0, 0.0), (1.0, -8.0)]]
870    /// Breathes: grows and fades a little, forever.
871    Breathe "breathe" Loop 1800.0 IN_OUT_SINE, None, Alternate
872        [S: [(0.0, 1.0), (1.0, 1.05)], O: [(0.0, 1.0), (1.0, 0.8)]]
873    /// Sways about its center, forever.
874    Sway "sway" Loop 1600.0 IN_OUT_SINE, None, Alternate [R: [(0.0, -4.0), (1.0, 4.0)]]
875    /// Bobs like a bouncing ball, forever (Tailwind's `animate-bounce`).
876    Bob "bob" Loop 1000.0 Easing::Linear, None, Normal
877        [Y: [(0.0, 0.0), (0.5, -12.0), (1.0, 0.0)]]
878    /// Glows in and out, forever (Tailwind's `animate-pulse` on a motion).
879    Glow "glow" Loop 2000.0 Easing::Bezier(0.4, 0.0, 0.6, 1.0), None, Normal
880        [O: [(0.0, 1.0), (0.5, 0.5), (1.0, 1.0)]]
881}
882
883impl MotionPreset {
884    /// Its definition.
885    pub fn def(self) -> &'static PresetDef {
886        &PRESETS[self as usize]
887    }
888
889    /// Its name in JS.
890    pub fn name(self) -> &'static str {
891        self.def().name
892    }
893
894    /// The preset named `name`.
895    pub fn parse(name: &str) -> Option<MotionPreset> {
896        MotionPreset::ALL.iter().copied().find(|p| p.name() == name)
897    }
898
899    /// The motion.
900    pub fn spec(self) -> MotionSpec {
901        self.def().spec()
902    }
903}
904
905impl From<MotionPreset> for MotionSpec {
906    fn from(preset: MotionPreset) -> Self {
907        preset.spec()
908    }
909}
910
911#[cfg(test)]
912mod tests {
913    use super::*;
914    use crate::animation::{AnimationOp, Finished, Graph};
915
916    fn value(g: &mut Graph, node: NodeId, start: f32) {
917        g.apply(
918            AnimationOp::CreateValue { node, value: start },
919            &mut Vec::new(),
920        );
921    }
922
923    /// Runs `spec` on node 2 from `start`, sampled at `times` (ms).
924    fn run(spec: Composite, start: f32, times: &[f64]) -> (Vec<f32>, Vec<Finished>) {
925        let mut g = Graph::default();
926        value(&mut g, 2, start);
927        let mut f = Vec::new();
928        g.apply(
929            AnimationOp::StartComposite {
930                animation: 10,
931                key: 12,
932                spec,
933            },
934            &mut f,
935        );
936        // Frames every 10 ms up to each sample (a composite starts at most a
937        // few steps per frame).
938        let mut out = Vec::new();
939        let mut now = 0.0;
940        for &t in times {
941            while now + 10.0 < t {
942                now += 10.0;
943                g.tick(now / 1000.0, &mut f);
944            }
945            now = t;
946            g.tick(t / 1000.0, &mut f);
947            out.push((g.value(2).unwrap() * 1000.0).round() / 1000.0);
948        }
949        (out, f)
950    }
951
952    fn linear(ms: f32) -> KeyframeTiming {
953        KeyframeTiming::new(ms).easing(Easing::Linear)
954    }
955
956    #[test]
957    fn offsets_spread_as_the_web_animations_api_spreads_them() {
958        let frames = [
959            Keyframe::new(0.0),
960            Keyframe::new(1.0),
961            Keyframe::at(0.8, 2.0),
962            Keyframe::new(3.0),
963        ];
964        let resolved: Vec<f32> = resolve(&frames).iter().map(|f| f.0).collect();
965        assert_eq!(resolved, [0.0, 0.4, 0.8, 1.0]);
966        assert_eq!(resolve(&[Keyframe::new(5.0)])[0].0, 1.0);
967        // Out of order: held at the one before.
968        let held: Vec<f32> = resolve(&[Keyframe::at(0.5, 0.0), Keyframe::at(0.2, 1.0)])
969            .iter()
970            .map(|f| f.0)
971            .collect();
972        assert_eq!(held, [0.5, 0.5]);
973    }
974
975    #[test]
976    fn keyframes_play_their_segments_on_time() {
977        let frames = [
978            Keyframe::new(0.0),
979            Keyframe::at(0.25, 10.0),
980            Keyframe::new(0.0),
981        ];
982        let spec = keyframes(2, &frames, &linear(400.0));
983        // The jump to the first keyframe happens on the first frame.
984        let (values, f) = run(spec, 7.0, &[0.0, 50.0, 100.0, 250.0, 400.0, 450.0]);
985        assert_eq!(values, [0.0, 5.0, 10.0, 5.0, 0.0, 0.0]);
986        assert!(f.iter().any(|f| f.animation == 10 && f.finished), "{f:?}");
987    }
988
989    #[test]
990    fn directions_iterations_and_delays() {
991        let frames = [Keyframe::new(0.0), Keyframe::new(10.0)];
992        let alternate = linear(100.0)
993            .direction(PlaybackDirection::Alternate)
994            .iterations(Some(3));
995        let (values, _) = run(
996            keyframes(2, &frames, &alternate),
997            0.0,
998            &[0.0, 50.0, 150.0, 250.0, 300.0, 400.0],
999        );
1000        assert_eq!(values, [0.0, 5.0, 5.0, 5.0, 10.0, 10.0]);
1001        let reverse = linear(100.0)
1002            .direction(PlaybackDirection::Reverse)
1003            .delay(100.0);
1004        let (values, _) = run(
1005            keyframes(2, &frames, &reverse),
1006            3.0,
1007            &[0.0, 50.0, 150.0, 200.0],
1008        );
1009        // The delay holds the first keyframe (the last, backwards).
1010        assert_eq!(values, [10.0, 10.0, 5.0, 0.0]);
1011        // Endless: still going long after.
1012        let (values, f) = run(
1013            keyframes(2, &frames, &linear(100.0).infinite()),
1014            0.0,
1015            &[0.0, 10_050.0],
1016        );
1017        assert_eq!(values[1], 5.0);
1018        assert!(!f.iter().any(|f| f.animation == 10), "{f:?}");
1019        assert_eq!(
1020            keyframe_ends(&frames, &alternate.iterations(Some(2))),
1021            Some((0.0, 0.0))
1022        );
1023    }
1024
1025    #[test]
1026    fn a_reversed_segment_runs_its_curve_backwards() {
1027        let ease = Easing::Bezier(0.42, 0.0, 1.0, 1.0);
1028        let frames = [Keyframe::new(0.0).ease(ease), Keyframe::new(1.0)];
1029        let timing = KeyframeTiming::new(100.0).direction(PlaybackDirection::Reverse);
1030        let (backwards, _) = run(keyframes(2, &frames, &timing), 0.0, &[0.0, 25.0]);
1031        let (forwards, _) = run(
1032            keyframes(2, &frames, &KeyframeTiming::new(100.0)),
1033            0.0,
1034            &[0.0, 75.0],
1035        );
1036        assert!(
1037            (backwards[1] - forwards[1]).abs() < 1e-3,
1038            "{backwards:?} {forwards:?}"
1039        );
1040    }
1041
1042    #[test]
1043    fn steps_jump_as_in_css() {
1044        use super::super::sample_easing;
1045        use crate::animation::StepPosition::*;
1046        let at = |e| sample_easing(Easing::Steps(4, e), 5);
1047        assert_eq!(at(JumpEnd), [0.0, 0.25, 0.5, 0.75, 1.0]);
1048        assert_eq!(at(JumpStart), [0.25, 0.5, 0.75, 1.0, 1.0]);
1049        let none = sample_easing(Easing::Steps(3, JumpNone), 4);
1050        assert_eq!(none, [0.0, 0.5, 1.0, 1.0]);
1051        let both = sample_easing(Easing::Steps(1, JumpBoth), 3);
1052        assert_eq!(both, [0.5, 0.5, 1.0]);
1053        assert_eq!(
1054            Easing::Steps(2, JumpStart).reversed(),
1055            Easing::Steps(2, JumpEnd)
1056        );
1057    }
1058
1059    #[test]
1060    fn staggering_counts_from_its_origin() {
1061        let delays = |from| {
1062            (0..5)
1063                .map(|i| stagger_delay(i, 5, from))
1064                .collect::<Vec<_>>()
1065        };
1066        assert_eq!(delays(StaggerFrom::First), [0.0, 1.0, 2.0, 3.0, 4.0]);
1067        assert_eq!(delays(StaggerFrom::Last), [4.0, 3.0, 2.0, 1.0, 0.0]);
1068        assert_eq!(delays(StaggerFrom::Center), [2.0, 1.0, 0.0, 1.0, 2.0]);
1069        assert_eq!(delays(StaggerFrom::Index(1)), [1.0, 0.0, 1.0, 2.0, 3.0]);
1070        let even: Vec<f32> = (0..4)
1071            .map(|i| stagger_delay(i, 4, StaggerFrom::Center))
1072            .collect();
1073        assert_eq!(even, [1.0, 0.0, 0.0, 1.0]);
1074    }
1075
1076    #[test]
1077    fn presets_are_well_formed() {
1078        assert_eq!(PRESETS.len(), MotionPreset::ALL.len());
1079        for (i, preset) in MotionPreset::ALL.iter().enumerate() {
1080            let def = preset.def();
1081            assert_eq!(def.name, PRESETS[i].name);
1082            assert_eq!(MotionPreset::parse(def.name), Some(*preset));
1083            let spec = preset.spec();
1084            assert!(!spec.tracks.is_empty(), "{}", def.name);
1085            for (channel, frames) in &spec.tracks {
1086                let resolved = resolve(frames);
1087                assert_eq!(resolved.first().map(|f| f.0), Some(0.0), "{}", def.name);
1088                assert_eq!(resolved.last().map(|f| f.0), Some(1.0), "{}", def.name);
1089                assert!(
1090                    resolved.windows(2).all(|w| w[0].0 <= w[1].0),
1091                    "{}",
1092                    def.name
1093                );
1094                let (start, end) = keyframe_ends(frames, &spec.timing).unwrap();
1095                let rest = channel.identity();
1096                match def.kind {
1097                    MotionKind::Enter => assert_eq!(end, rest, "{} ends at rest", def.name),
1098                    MotionKind::Exit => assert_eq!(start, rest, "{} starts at rest", def.name),
1099                    MotionKind::Attention => {
1100                        assert_eq!((start, end), (rest, rest), "{}", def.name)
1101                    }
1102                    MotionKind::Loop => assert!(spec.timing.iterations.is_none(), "{}", def.name),
1103                }
1104            }
1105        }
1106    }
1107
1108    /// The spring of csp's motions: about 380 ms to settle, 2.8 % over.
1109    fn csp_spring() -> Spring {
1110        Spring {
1111            stiffness: 620.0,
1112            damping: 36.0,
1113            ..Spring::default()
1114        }
1115    }
1116
1117    #[test]
1118    fn a_spring_motion_springs_each_channel_to_where_it_ends() {
1119        let spec = MotionPreset::FadeInUp.spec().spring(csp_spring());
1120        let nodes = [2, 4, 6, 8, 10, 12, 14, 16, 18];
1121        let Composite::Parallel { children, .. } = spec.composite(&nodes, false) else {
1122            panic!()
1123        };
1124        let targets: Vec<_> = children
1125            .iter()
1126            .map(|child| match child {
1127                Composite::Run {
1128                    node,
1129                    driver:
1130                        Driver::Spring {
1131                            to,
1132                            stiffness,
1133                            velocity: None,
1134                            ..
1135                        },
1136                } => (*node, *to, *stiffness),
1137                other => panic!("{other:?}"),
1138            })
1139            .collect();
1140        assert_eq!(targets, [(2, 1.0, 620.0), (6, 0.0, 620.0)]);
1141        // Starts from where the value is (no jump to the first keyframe),
1142        // passes its end a little and settles there.
1143        let track = MotionSpec::default()
1144            .values(MotionChannel::Opacity, [0.0, 10.0])
1145            .spring(csp_spring());
1146        let mut nodes = [0; 9];
1147        nodes[MotionChannel::Opacity.index()] = 2;
1148        let (values, f) = run(
1149            track.composite(&nodes, false),
1150            5.0,
1151            &[0.0, 120.0, 200.0, 1000.0],
1152        );
1153        assert_eq!(values[0], 5.0);
1154        assert!(values[1] > 5.0 && values[1] < 10.0, "{values:?}");
1155        assert!(values[2] > 10.0, "{values:?}");
1156        assert_eq!(values[3], 10.0);
1157        assert!(f.iter().any(|f| f.animation == 10 && f.finished), "{f:?}");
1158        // Its delay leaves the value where it is.
1159        let delayed = track.clone().timing(|t| t.delay(100.0));
1160        let (values, _) = run(delayed.composite(&nodes, false), 5.0, &[0.0, 90.0, 200.0]);
1161        assert_eq!(values[..2], [5.0, 5.0]);
1162        assert!(values[2] > 5.0, "{values:?}");
1163        // Less motion: it lands at once, as keyframes do.
1164        let (values, _) = run(track.composite(&nodes, true), 5.0, &[0.0]);
1165        assert_eq!(values, [10.0]);
1166    }
1167
1168    #[test]
1169    fn an_interrupted_spring_motion_goes_on_from_its_value_and_velocity() {
1170        let mut nodes = [0; 9];
1171        nodes[MotionChannel::TranslateY.index()] = 2;
1172        let to = |end: f32| {
1173            MotionSpec::default()
1174                .values(MotionChannel::TranslateY, [100.0, end])
1175                .spring(csp_spring())
1176                .composite(&nodes, false)
1177        };
1178        let mut g = Graph::default();
1179        value(&mut g, 2, 100.0);
1180        let mut f = Vec::new();
1181        let start = |g: &mut Graph, animation, spec, f: &mut Vec<Finished>| {
1182            g.apply(
1183                AnimationOp::StartComposite {
1184                    animation,
1185                    key: 12,
1186                    spec,
1187                },
1188                f,
1189            )
1190        };
1191        start(&mut g, 10, to(0.0), &mut f);
1192        let mut now = 0.0;
1193        while now < 80.0 {
1194            g.tick(now / 1000.0, &mut f);
1195            now += 10.0;
1196        }
1197        let before = g.value(2).unwrap();
1198        assert!(before < 100.0 && before > 0.0, "{before}");
1199        // Sent back while it falls: it goes on from there, still falling
1200        // for a moment, rather than jumping to its first keyframe.
1201        start(&mut g, 11, to(100.0), &mut f);
1202        g.tick(now / 1000.0, &mut f);
1203        let at_once = g.value(2).unwrap();
1204        g.tick((now + 10.0) / 1000.0, &mut f);
1205        let next = g.value(2).unwrap();
1206        assert!((at_once - before).abs() < 15.0, "{before} {at_once}");
1207        assert!(next < before, "{before} {at_once} {next}");
1208        assert!(f.iter().any(|f| f.animation == 10 && !f.finished), "{f:?}");
1209        for _ in 0..100 {
1210            now += 10.0;
1211            g.tick(now / 1000.0, &mut f);
1212        }
1213        assert_eq!(g.value(2), Some(100.0));
1214        assert!(f.iter().any(|f| f.animation == 11 && f.finished), "{f:?}");
1215    }
1216
1217    #[test]
1218    fn a_reduced_motion_lands_at_its_end() {
1219        let spec = MotionPreset::FadeInUp.spec();
1220        let nodes = [2, 4, 6, 8, 10, 12, 14, 16, 18];
1221        let Composite::Parallel { children, .. } = spec.composite(&nodes, true) else {
1222            panic!()
1223        };
1224        assert_eq!(children.len(), 2);
1225        for child in &children {
1226            assert!(matches!(
1227                child,
1228                Composite::Run {
1229                    driver: Driver::Timing {
1230                        duration_ms: 0.0,
1231                        ..
1232                    },
1233                    ..
1234                }
1235            ));
1236        }
1237        let starts: Vec<_> = spec.start_values().collect();
1238        assert_eq!(
1239            starts,
1240            [
1241                (MotionChannel::Opacity, 0.0),
1242                (MotionChannel::TranslateY, 24.0)
1243            ]
1244        );
1245    }
1246}