Skip to main content

bhoo/
timing.rs

1//! Duration curves adapted from Material Web internal/motion/animation.ts,
2//! Copyright 2021 Google LLC, Apache-2.0. Independently implemented CSS sampling.
3#[derive(Clone, Copy, Debug, Default)]
4pub enum Easing {
5    #[default]
6    Linear,
7    Standard,
8    Emphasized,
9    EmphasizedAccelerate,
10    EmphasizedDecelerate,
11    StandardDecelerate,
12    Backdrop,
13    Cubic([f32; 4]),
14}
15impl Easing {
16    pub fn sample(self, x: f32) -> f32 {
17        let (x1, y1, x2, y2) = match self {
18            Self::Linear => return x.clamp(0.0, 1.0),
19            Self::Standard => (0.2, 0.0, 0.0, 1.0),
20            Self::Emphasized => (0.3, 0.0, 0.0, 1.0),
21            Self::EmphasizedAccelerate => (0.3, 0.0, 0.8, 0.15),
22            Self::EmphasizedDecelerate => (0.05, 0.7, 0.1, 1.0),
23            Self::StandardDecelerate => (0.0, 0.0, 0.2, 1.0),
24            Self::Backdrop => (0.25, 0.8, 0.25, 1.0),
25            Self::Cubic([x1, y1, x2, y2]) => (x1, y1, x2, y2),
26        };
27        let x = x.clamp(0.0, 1.0);
28        if x == 0.0 || x == 1.0 {
29            return x;
30        }
31        let (mut lo, mut hi) = (0.0, 1.0);
32        for _ in 0..20 {
33            let t = (lo + hi) * 0.5;
34            let u = 1.0 - t;
35            let bx = 3.0 * u * u * t * x1 + 3.0 * u * t * t * x2 + t * t * t;
36            if bx < x {
37                lo = t;
38            } else {
39                hi = t;
40            }
41        }
42        let t = (lo + hi) * 0.5;
43        let u = 1.0 - t;
44        3.0 * u * u * t * y1 + 3.0 * u * t * t * y2 + t * t * t
45    }
46}
47#[derive(Clone, Copy, Debug)]
48pub struct TweenSpec {
49    pub delay: f64,
50    pub duration: f64,
51    pub easing: Easing,
52}
53impl TweenSpec {
54    pub const fn new(duration: f64, easing: Easing) -> Self {
55        Self {
56            delay: 0.0,
57            duration,
58            easing,
59        }
60    }
61}
62#[derive(Clone, Copy, Debug, Default)]
63/// Interruptible duration-based animation using the Material easing curves.
64pub struct Tween {
65    value: f32,
66    from: f32,
67    target: f32,
68    start: f64,
69    delay: f64,
70    duration: f64,
71    easing: Easing,
72    reverse_start: f32,
73    reverse_factor: f64,
74}
75impl Tween {
76    pub fn at(value: f32) -> Self {
77        Self {
78            value,
79            from: value,
80            target: value,
81            reverse_start: value,
82            reverse_factor: 1.0,
83            ..Self::default()
84        }
85    }
86    pub fn sample(
87        &mut self,
88        time: f64,
89        target: f32,
90        enter: TweenSpec,
91        exit: TweenSpec,
92        reduced: bool,
93    ) -> f32 {
94        let time = if time.is_finite() {
95            time.max(self.start)
96        } else {
97            self.start
98        };
99        self.advance(time);
100        if target != self.target {
101            let spec = if target > self.target { enter } else { exit };
102            self.from = self.value;
103            self.target = target;
104            self.start = time;
105            self.delay = spec.delay.max(0.0);
106            self.duration = spec.duration.max(0.0);
107            self.easing = spec.easing;
108        }
109        if reduced {
110            self.value = target;
111            self.from = target;
112            self.target = target;
113            self.duration = 0.0;
114            self.delay = 0.0;
115        }
116        self.advance(time);
117        self.value
118    }
119    /// CSS transition reversal shortening, preserving the current presentation.
120    pub fn sample_css(
121        &mut self,
122        time: f64,
123        target: f32,
124        mut enter: TweenSpec,
125        mut exit: TweenSpec,
126        reduced: bool,
127    ) -> f32 {
128        let time = if time.is_finite() {
129            time.max(self.start)
130        } else {
131            self.start
132        };
133        self.advance(time);
134        if target != self.target {
135            let reversing = self.moving() && target == self.reverse_start;
136            let factor = if reversing {
137                let progress = ((self.value - self.from) / (self.target - self.from)) as f64;
138                (progress * self.reverse_factor + 1.0 - self.reverse_factor)
139                    .abs()
140                    .clamp(0.0, 1.0)
141            } else {
142                1.0
143            };
144            self.reverse_start = if reversing { self.target } else { self.value };
145            self.reverse_factor = factor;
146            enter.duration *= factor;
147            exit.duration *= factor;
148        }
149        self.sample(time, target, enter, exit, reduced)
150    }
151    fn advance(&mut self, time: f64) {
152        let elapsed = (time - self.start - self.delay).max(0.0);
153        if time >= self.start + self.delay {
154            let progress = if self.duration > 0.0 {
155                (elapsed / self.duration).min(1.0) as f32
156            } else {
157                1.0
158            };
159            self.value = self.from + (self.target - self.from) * self.easing.sample(progress);
160        }
161    }
162    pub fn moving(&self) -> bool {
163        self.value != self.target
164    }
165}
166#[cfg(test)]
167mod tests {
168    use super::*;
169    #[test]
170    fn reversal_samples_old_presentation_before_retarget() {
171        let mut t = Tween::default();
172        let spec = TweenSpec::new(0.5, Easing::Emphasized);
173        t.sample(0.0, 1.0, spec, spec, false);
174        let mid = t.sample(0.1, 1.0, spec, spec, false);
175        assert!(mid > 0.0 && mid < 1.0);
176        assert_eq!(mid, t.sample(0.1, 0.0, spec, spec, false));
177        assert_eq!(t.sample(1.0, 0.0, spec, spec, false), 0.0);
178        assert!(!t.moving());
179    }
180    #[test]
181    fn delay_zero_duration_and_reduced_motion_are_exact() {
182        let mut t = Tween::default();
183        let s = TweenSpec {
184            delay: 0.1,
185            duration: 0.0,
186            easing: Easing::Linear,
187        };
188        assert_eq!(t.sample(0.0, 1.0, s, s, false), 0.0);
189        assert_eq!(t.sample(0.1, 1.0, s, s, false), 1.0);
190        assert_eq!(t.sample(0.1, 0.0, s, s, true), 0.0);
191        assert!(!t.moving());
192    }
193}