webizen_studio/render/
motion.rs1#[derive(Debug, Clone, Copy)]
8pub struct Timeline {
9 pub current_time: f64,
10 pub delta_t: f64,
11 pub reduced_motion: bool,
12}
13
14#[derive(Clone, Copy, Debug)]
16pub struct Spring {
17 pub value: f64,
18 pub velocity: f64,
19 pub target: f64,
20 stiffness: f64,
21 damping: f64,
22}
23
24impl Spring {
25 pub fn new(initial: f64) -> Self {
27 Self {
28 value: initial,
29 velocity: 0.0,
30 target: initial,
31 stiffness: 100.0,
33 damping: 20.0,
34 }
35 }
36
37 pub fn set_target(&mut self, target: f64) {
39 self.target = target;
40 }
41
42 pub fn step(&mut self, timeline: &Timeline) -> f64 {
45 if timeline.reduced_motion {
46 self.value = self.target;
47 self.velocity = 0.0;
48 return self.value;
49 }
50
51 let displacement = self.target - self.value;
53 let spring_force = displacement * self.stiffness;
54 let damping_force = -self.velocity * self.damping;
55 let acceleration = spring_force + damping_force;
56
57 self.velocity += acceleration * timeline.delta_t;
58 self.value += self.velocity * timeline.delta_t;
59
60 self.value
61 }
62
63 pub fn is_at_target(&self, tolerance: f64) -> bool {
65 (self.value - self.target).abs() < tolerance && self.velocity.abs() < tolerance
66 }
67}
68
69#[cfg(target_arch = "wasm32")]
71pub fn prefers_reduced_motion() -> bool {
72 web_sys::window()
73 .and_then(|window| window.match_media("(prefers-reduced-motion: reduce)").ok())
74 .flatten()
75 .map(|query| query.matches())
76 .unwrap_or(false)
77}
78
79#[cfg(not(target_arch = "wasm32"))]
80pub fn prefers_reduced_motion() -> bool {
82 false
83}
84
85pub fn timeline_from_theme(current_time: f64, delta_t: f64, theme_class: Option<&str>) -> Timeline {
87 let sanctuary = theme_class
88 .map(|c| c.contains("sanctuary"))
89 .unwrap_or(false);
90 Timeline {
91 current_time,
92 delta_t,
93 reduced_motion: sanctuary || prefers_reduced_motion(),
94 }
95}