Skip to main content

waft_animation/
animation_style.rs

1//! Flutter counterpart: `animation/animation_style.dart`.
2
3use std::fmt::{self, Debug};
4use std::hash::{Hash, Hasher};
5use std::rc::Rc;
6use std::time::Duration;
7
8use crate::curves::{Curve, Curves};
9
10/// Used to override the default parameters of an animation.
11///
12/// If [`duration`] and [`reverse_duration`] are set to [`Duration::ZERO`], the
13/// corresponding animation will be disabled.
14///
15/// All of the parameters are optional. If no parameters are specified, the
16/// default animation will be used.
17///
18/// [`duration`]: AnimationStyle::duration
19/// [`reverse_duration`]: AnimationStyle::reverse_duration
20#[derive(Clone, Default)]
21pub struct AnimationStyle {
22    /// When specified, the animation will use this curve.
23    pub curve: Option<Rc<dyn Curve>>,
24
25    /// When specified, the animation will use this duration.
26    pub duration: Option<Duration>,
27
28    /// When specified, the reverse animation will use this curve.
29    pub reverse_curve: Option<Rc<dyn Curve>>,
30
31    /// When specified, the reverse animation will use this duration.
32    pub reverse_duration: Option<Duration>,
33}
34
35impl AnimationStyle {
36    /// An [`AnimationStyle`] with no animation.
37    ///
38    /// Dart's `AnimationStyle.noAnimation`.
39    pub const NO_ANIMATION: AnimationStyle = AnimationStyle {
40        curve: None,
41        duration: Some(Duration::ZERO),
42        reverse_curve: None,
43        reverse_duration: Some(Duration::ZERO),
44    };
45
46    /// Creates an instance of Animation Style class.
47    pub fn new(
48        curve: Option<Rc<dyn Curve>>,
49        duration: Option<Duration>,
50        reverse_curve: Option<Rc<dyn Curve>>,
51        reverse_duration: Option<Duration>,
52    ) -> AnimationStyle {
53        AnimationStyle {
54            curve,
55            duration,
56            reverse_curve,
57            reverse_duration,
58        }
59    }
60
61    /// Creates a new [`AnimationStyle`] based on the current selection, with
62    /// the provided parameters overridden.
63    pub fn copy_with(
64        &self,
65        curve: Option<Rc<dyn Curve>>,
66        duration: Option<Duration>,
67        reverse_curve: Option<Rc<dyn Curve>>,
68        reverse_duration: Option<Duration>,
69    ) -> AnimationStyle {
70        AnimationStyle {
71            curve: curve.or_else(|| self.curve.clone()),
72            duration: duration.or(self.duration),
73            reverse_curve: reverse_curve.or_else(|| self.reverse_curve.clone()),
74            reverse_duration: reverse_duration.or(self.reverse_duration),
75        }
76    }
77
78    /// Creates a new [`AnimationStyle`] that is a combination of this
79    /// animation style and the given `other` animation style.
80    ///
81    /// If `other` is `Some`, its non-`None` properties are used to override
82    /// the corresponding properties of this style.
83    ///
84    /// Returns this animation style if `other` is `None`.
85    pub fn merge(&self, other: Option<&AnimationStyle>) -> AnimationStyle {
86        let Some(other) = other else {
87            return self.clone();
88        };
89        self.copy_with(
90            other.curve.clone(),
91            other.duration,
92            other.reverse_curve.clone(),
93            other.reverse_duration,
94        )
95    }
96
97    /// Linearly interpolate between two animation styles.
98    pub fn lerp(
99        a: Option<&AnimationStyle>,
100        b: Option<&AnimationStyle>,
101        t: f64,
102    ) -> Option<AnimationStyle> {
103        // Dart: `if (identical(a, b)) return a` — true when both are null or
104        // both are the same object.
105        match (a, b) {
106            (None, None) => return None,
107            (Some(a_ref), Some(b_ref)) if std::ptr::eq(a_ref, b_ref) => {
108                return Some(a_ref.clone());
109            }
110            _ => {}
111        }
112        Some(AnimationStyle {
113            curve: lerp_field(
114                a.and_then(|style| style.curve.clone()),
115                b.and_then(|style| style.curve.clone()),
116                t,
117                curves_identical,
118                lerped_curve,
119            ),
120            duration: lerp_field(
121                a.and_then(|style| style.duration),
122                b.and_then(|style| style.duration),
123                t,
124                |a, b| a == b,
125                lerp_duration,
126            ),
127            reverse_curve: lerp_field(
128                a.and_then(|style| style.reverse_curve.clone()),
129                b.and_then(|style| style.reverse_curve.clone()),
130                t,
131                curves_identical,
132                lerped_curve,
133            ),
134            reverse_duration: lerp_field(
135                a.and_then(|style| style.reverse_duration),
136                b.and_then(|style| style.reverse_duration),
137                t,
138                |a, b| a == b,
139                lerp_duration,
140            ),
141        })
142    }
143}
144
145/// Dart's private generic `AnimationStyle._lerp`, with the equality passed in:
146/// Dart's `a == b` dispatches per type (identity for curves, value for
147/// `Duration`), and Rust needs that spelled out.
148fn lerp_field<T: Clone>(
149    a: Option<T>,
150    b: Option<T>,
151    t: f64,
152    eq: impl Fn(&T, &T) -> bool,
153    lerp: impl Fn(Option<&T>, Option<&T>, f64) -> T,
154) -> Option<T> {
155    let equal = match (&a, &b) {
156        (None, None) => true,
157        (Some(a), Some(b)) => eq(a, b),
158        _ => false,
159    };
160    if equal || t == 0.0 {
161        return a;
162    }
163    if t == 1.0 {
164        return b;
165    }
166    Some(lerp(a.as_ref(), b.as_ref(), t))
167}
168
169fn curves_identical(a: &Rc<dyn Curve>, b: &Rc<dyn Curve>) -> bool {
170    Rc::ptr_eq(a, b)
171}
172
173fn lerped_curve(a: Option<&Rc<dyn Curve>>, b: Option<&Rc<dyn Curve>>, t: f64) -> Rc<dyn Curve> {
174    Rc::new(LerpedCurve::new(a.cloned(), b.cloned(), t))
175}
176
177/// Dart's `AnimationStyle._lerpDuration`.
178fn lerp_duration(a: Option<&Duration>, b: Option<&Duration>, t: f64) -> Duration {
179    let a_micros = a.map_or(0.0, |duration| duration.as_micros() as f64);
180    let b_micros = b.map_or(0.0, |duration| duration.as_micros() as f64);
181    Duration::from_micros((a_micros * (1.0 - t) + b_micros * t).round() as u64)
182}
183
184impl PartialEq for AnimationStyle {
185    fn eq(&self, other: &AnimationStyle) -> bool {
186        // Dart compares the curves with `==`, which no framework curve
187        // overrides — identity — except `_LerpedCurve` below, whose structural
188        // `==` is not reproduced; see PORTING.md.
189        option_curve_eq(&self.curve, &other.curve)
190            && self.duration == other.duration
191            && option_curve_eq(&self.reverse_curve, &other.reverse_curve)
192            && self.reverse_duration == other.reverse_duration
193    }
194}
195
196impl Eq for AnimationStyle {}
197
198fn option_curve_eq(a: &Option<Rc<dyn Curve>>, b: &Option<Rc<dyn Curve>>) -> bool {
199    match (a, b) {
200        (None, None) => true,
201        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
202        _ => false,
203    }
204}
205
206impl Hash for AnimationStyle {
207    fn hash<H: Hasher>(&self, state: &mut H) {
208        for curve in [&self.curve, &self.reverse_curve] {
209            match curve {
210                // The address `Rc::ptr_eq` compares, so equal styles hash
211                // equally.
212                Some(curve) => (Rc::as_ptr(curve) as *const () as usize).hash(state),
213                None => 0usize.hash(state),
214            }
215        }
216        self.duration.hash(state);
217        self.reverse_duration.hash(state);
218    }
219}
220
221impl Debug for AnimationStyle {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        // Dart's debugFillProperties: only non-default (non-null) fields.
224        let mut s = f.debug_struct("AnimationStyle");
225        if let Some(curve) = &self.curve {
226            s.field("curve", curve);
227        }
228        if let Some(duration) = &self.duration {
229            s.field("duration", duration);
230        }
231        if let Some(reverse_curve) = &self.reverse_curve {
232            s.field("reverseCurve", reverse_curve);
233        }
234        if let Some(reverse_duration) = &self.reverse_duration {
235            s.field("reverseDuration", reverse_duration);
236        }
237        s.finish()
238    }
239}
240
241/// Dart's private `_LerpedCurve`.
242struct LerpedCurve {
243    first: Rc<dyn Curve>,
244    second: Rc<dyn Curve>,
245    t: f64,
246}
247
248impl LerpedCurve {
249    fn new(a: Option<Rc<dyn Curve>>, b: Option<Rc<dyn Curve>>, t: f64) -> LerpedCurve {
250        LerpedCurve {
251            first: a.unwrap_or_else(Curves::linear),
252            second: b.unwrap_or_else(Curves::linear),
253            t,
254        }
255    }
256}
257
258impl Curve for LerpedCurve {
259    // Dart overrides `transform` directly, bypassing the 0.0/1.0 shortcut.
260    fn transform(&self, t: f64) -> f64 {
261        let a = self.first.transform(t);
262        let b = self.second.transform(t);
263        a * (1.0 - self.t) + b * self.t
264    }
265}
266
267impl Debug for LerpedCurve {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        write!(
270            f,
271            "LerpedCurve({:?}, {:?}, t: {})",
272            self.first, self.second, self.t
273        )
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    // animation_style_test.dart:17 — 'AnimationStyle.copyWith() overrides all
282    // properties'.
283    #[test]
284    fn copy_with_overrides_all_properties() {
285        let style = AnimationStyle::new(
286            Some(Curves::ease()),
287            Some(Duration::from_secs(1)),
288            Some(Curves::ease()),
289            Some(Duration::from_secs(1)),
290        );
291        let copy = style.copy_with(
292            Some(Curves::linear()),
293            Some(Duration::from_secs(2)),
294            Some(Curves::linear()),
295            Some(Duration::from_secs(2)),
296        );
297
298        assert!(Rc::ptr_eq(copy.curve.as_ref().unwrap(), &Curves::linear()));
299        assert_eq!(copy.duration, Some(Duration::from_secs(2)));
300        assert!(Rc::ptr_eq(
301            copy.reverse_curve.as_ref().unwrap(),
302            &Curves::linear()
303        ));
304        assert_eq!(copy.reverse_duration, Some(Duration::from_secs(2)));
305    }
306
307    // animation_style_test.dart:12 — 'copyWith, ==, hashCode basics'.
308    #[test]
309    fn copy_with_of_the_default_is_equal() {
310        let default = AnimationStyle::default();
311        let copy = default.copy_with(None, None, None, None);
312        assert_eq!(default, copy);
313    }
314
315    // animation_style_test.dart:36 — 'AnimationStyle.merge() fills in null
316    // properties'. The base's first two fields are set, so the merge must
317    // override set fields, not only fill empty ones.
318    #[test]
319    fn merge_fills_in_null_properties() {
320        let base = AnimationStyle::new(
321            Some(Curves::ease()),
322            Some(Duration::from_secs(1)),
323            Some(Curves::ease()),
324            Some(Duration::from_secs(1)),
325        );
326        let overrides = AnimationStyle::new(
327            Some(Curves::linear()),
328            Some(Duration::from_secs(2)),
329            None,
330            None,
331        );
332        let merged = base.merge(Some(&overrides));
333
334        assert!(Rc::ptr_eq(
335            merged.curve.as_ref().unwrap(),
336            &Curves::linear()
337        ));
338        assert_eq!(merged.duration, Some(Duration::from_secs(2)));
339        assert!(Rc::ptr_eq(
340            merged.reverse_curve.as_ref().unwrap(),
341            &Curves::ease()
342        ));
343        assert_eq!(merged.reverse_duration, Some(Duration::from_secs(1)));
344    }
345
346    // animation_style_test.dart:51 — 'AnimationStyle.lerp identical a,b'.
347    #[test]
348    fn lerp_of_identical_styles_returns_the_first() {
349        assert!(AnimationStyle::lerp(None, None, 0.0).is_none());
350        let data = AnimationStyle::default();
351        let lerped = AnimationStyle::lerp(Some(&data), Some(&data), 0.5).unwrap();
352        assert_eq!(lerped, data);
353    }
354
355    // animation_style_test.dart:104 — 'AnimationStyle.lerp with null
356    // property': a null side counts as zero microseconds.
357    #[test]
358    fn lerp_with_a_null_property_counts_it_as_zero() {
359        let a = AnimationStyle::new(None, Some(Duration::from_secs(2)), None, None);
360        let b = AnimationStyle::default();
361
362        assert_eq!(
363            AnimationStyle::lerp(Some(&a), Some(&b), 0.5)
364                .unwrap()
365                .duration,
366            Some(Duration::from_secs(1))
367        );
368        assert_eq!(
369            AnimationStyle::lerp(Some(&a), Some(&b), 0.25)
370                .unwrap()
371                .duration,
372            Some(Duration::from_millis(1500))
373        );
374    }
375
376    // animation_style_test.dart:75 — lerp endpoints return the inputs.
377    #[test]
378    fn lerp_endpoints_return_the_inputs() {
379        let a = AnimationStyle::new(
380            Some(Curves::ease()),
381            Some(Duration::from_secs(1)),
382            None,
383            None,
384        );
385        let b = AnimationStyle::new(
386            Some(Curves::linear()),
387            Some(Duration::from_secs(2)),
388            None,
389            None,
390        );
391
392        assert_eq!(AnimationStyle::lerp(Some(&a), Some(&b), 0.0).unwrap(), a);
393        assert_eq!(AnimationStyle::lerp(Some(&a), Some(&b), 1.0).unwrap(), b);
394    }
395
396    // animation_style_test.dart:57 — the in-between curve blends the two.
397    #[test]
398    fn lerp_blends_the_curves() {
399        let a = AnimationStyle::new(Some(Curves::linear()), None, None, None);
400        let b = AnimationStyle::new(Some(Curves::ease()), None, None, None);
401
402        let half = AnimationStyle::lerp(Some(&a), Some(&b), 0.5).unwrap();
403        let lerped = half.curve.unwrap();
404        let expected =
405            Curves::linear().transform(0.25) * 0.5 + Curves::ease().transform(0.25) * 0.5;
406        assert_eq!(lerped.transform(0.25), expected);
407    }
408}