dioxus_motion/animations/
tween.rs

1//! Tween animation module
2//!
3//! Provides time-based animation with customizable easing functions.
4//! Supports duration and interpolation control for smooth animations.
5
6use easer::functions::{Easing, Linear};
7pub use instant::Duration;
8
9/// Configuration for tween-based animations
10///
11/// # Examples
12/// ```rust
13/// use dioxus_motion::Duration;
14/// use dioxus_motion::prelude::Tween;
15/// use easer::functions::Easing;
16/// let tween = Tween::new(Duration::from_secs(1))
17///     .with_easing(easer::functions::Cubic::ease_in_out);
18/// ```
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct Tween {
21    /// Duration of the animation
22    pub duration: Duration,
23    /// Easing function for interpolation
24    pub easing: fn(f32, f32, f32, f32) -> f32,
25}
26
27/// Default tween configuration with 300ms duration and linear easing
28impl Default for Tween {
29    fn default() -> Self {
30        Self {
31            duration: Duration::from_millis(300),
32            easing: Linear::ease_in_out,
33        }
34    }
35}
36
37impl Tween {
38    /// Creates a new tween with specified duration and linear easing
39    pub fn new(duration: Duration) -> Self {
40        Self {
41            duration,
42            easing: Linear::ease_in_out,
43        }
44    }
45
46    /// Sets the easing function for the animation
47    ///
48    /// # Arguments
49    /// * `easing` - Function that takes (t, b, c, d) and returns interpolated value
50    pub fn with_easing(mut self, easing: fn(f32, f32, f32, f32) -> f32) -> Self {
51        self.easing = easing;
52        self
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59    use easer::functions::{Cubic, Easing};
60
61    #[test]
62    fn test_tween_new() {
63        let tween = Tween {
64            duration: Duration::from_secs(1),
65            easing: Cubic::ease_in_out,
66        };
67
68        assert_eq!(tween.duration, Duration::from_secs(1));
69    }
70
71    #[test]
72    fn test_tween_interpolation() {
73        let tween = Tween {
74            duration: Duration::from_secs(1),
75            easing: Linear::ease_in_out,
76        };
77
78        // Test midpoint
79        let progress = 0.5;
80        let result = (tween.easing)(progress, 0.0, 1.0, 1.0);
81        assert!((result - 0.5).abs() < f32::EPSILON);
82
83        // Test start
84        let result = (tween.easing)(0.0, 0.0, 1.0, 1.0);
85        assert!((result - 0.0).abs() < f32::EPSILON);
86
87        // Test end
88        let result = (tween.easing)(1.0, 0.0, 1.0, 1.0);
89        assert!((result - 1.0).abs() < f32::EPSILON);
90    }
91}