Skip to main content

dioxus_motion/animations/
spring.rs

1//! Spring physics implementation for animations
2//!
3//! Provides a physical spring model for smooth, natural-looking animations.
4//! Based on Hooke's law with damping for realistic motion.
5
6#[cfg(feature = "dioxus")]
7use dioxus::prelude::Store;
8
9/// Configuration for spring-based animations
10///
11/// Uses a mass-spring-damper system to create natural motion.
12///
13/// # Examples
14/// ```rust
15/// use dioxus_motion::prelude::Spring;
16/// let spring = Spring {
17///     stiffness: 100.0,  // Higher values = faster snap
18///     damping: 10.0,     // Higher values = less bounce
19///     mass: 1.0,         // Higher values = more inertia
20///     velocity: 0.0,     // Initial velocity
21/// };
22/// ```
23#[cfg_attr(feature = "dioxus", derive(Store))]
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct Spring {
26    /// Spring stiffness constant (default: 100.0)
27    /// Higher values make the spring stronger and faster
28    pub stiffness: f32,
29
30    /// Damping coefficient (default: 10.0)
31    /// Higher values reduce oscillation
32    pub damping: f32,
33
34    /// Mass of the object (default: 1.0)
35    /// Higher values increase inertia
36    pub mass: f32,
37
38    /// Initial velocity (default: 0.0)
39    /// Can be set for pre-existing motion
40    pub velocity: f32,
41}
42
43/// Default spring configuration for general-purpose animations
44impl Default for Spring {
45    fn default() -> Self {
46        Self {
47            stiffness: 100.0,
48            damping: 10.0,
49            mass: 1.0,
50            velocity: 0.0,
51        }
52    }
53}
54
55/// Represents the current state of a spring animation
56///
57/// Used to track whether the spring is still moving or has settled
58#[derive(Debug, Copy, Clone, PartialEq)]
59pub enum SpringState {
60    /// Spring is still in motion
61    Active,
62    /// Spring has settled to its target position
63    Completed,
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn test_spring_default() {
72        let spring = Spring::default();
73        assert_eq!(spring.stiffness, 100.0);
74        assert_eq!(spring.damping, 10.0);
75        assert_eq!(spring.mass, 1.0);
76        assert_eq!(spring.velocity, 0.0);
77    }
78
79    #[test]
80    fn test_spring_custom() {
81        let spring = Spring {
82            stiffness: 200.0,
83            damping: 20.0,
84            mass: 2.0,
85            velocity: 5.0,
86        };
87
88        assert_eq!(spring.stiffness, 200.0);
89        assert_eq!(spring.damping, 20.0);
90        assert_eq!(spring.mass, 2.0);
91        assert_eq!(spring.velocity, 5.0);
92    }
93}