tony / oxwm

Branch: 2a70554
Switch branches/tags
master
tonybtw added scrolling layout with animations. 5db5675 2025-12-20
76 lines · 1.7 KB Raw Blame History
1 use std::time::Instant;
2 use super::{AnimationConfig, Easing};
3
4 pub struct ScrollAnimation {
5 start_value: i32,
6 end_value: i32,
7 start_time: Instant,
8 duration_ms: u64,
9 easing: Easing,
10 active: bool,
11 }
12
13 impl ScrollAnimation {
14 pub fn new() -> Self {
15 Self {
16 start_value: 0,
17 end_value: 0,
18 start_time: Instant::now(),
19 duration_ms: 150,
20 easing: Easing::EaseOut,
21 active: false,
22 }
23 }
24
25 pub fn start(&mut self, from: i32, to: i32, config: &AnimationConfig) {
26 if from == to {
27 self.active = false;
28 return;
29 }
30 self.start_value = from;
31 self.end_value = to;
32 self.start_time = Instant::now();
33 self.duration_ms = config.duration.as_millis() as u64;
34 self.easing = config.easing;
35 self.active = true;
36 }
37
38 pub fn update(&mut self) -> Option<i32> {
39 if !self.active {
40 return None;
41 }
42
43 let elapsed = self.start_time.elapsed().as_millis() as u64;
44
45 if elapsed >= self.duration_ms {
46 self.active = false;
47 return Some(self.end_value);
48 }
49
50 let t = elapsed as f64 / self.duration_ms as f64;
51 let eased_t = self.easing.apply(t);
52
53 let delta = (self.end_value - self.start_value) as f64;
54 let current = self.start_value as f64 + delta * eased_t;
55
56 Some(current.round() as i32)
57 }
58
59 pub fn is_active(&self) -> bool {
60 self.active
61 }
62
63 pub fn target(&self) -> i32 {
64 self.end_value
65 }
66
67 pub fn cancel(&mut self) {
68 self.active = false;
69 }
70 }
71
72 impl Default for ScrollAnimation {
73 fn default() -> Self {
74 Self::new()
75 }
76 }