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