Skip to main content

fc_ui/capabilities/motion/
animate.rs

1use gpui::*;
2use std::time::Duration;
3
4use crate::capabilities::motion::animations::easings;
5
6#[derive(Clone)]
7pub struct AnimationPreset {
8    duration: Duration,
9    easing: fn(f32) -> f32,
10    delay: Duration,
11}
12
13impl AnimationPreset {
14    pub fn new(duration: Duration, easing: fn(f32) -> f32) -> Self {
15        Self {
16            duration,
17            easing,
18            delay: Duration::ZERO,
19        }
20    }
21
22    pub fn duration(mut self, duration: Duration) -> Self {
23        self.duration = duration;
24        self
25    }
26
27    pub fn easing(mut self, easing: fn(f32) -> f32) -> Self {
28        self.easing = easing;
29        self
30    }
31
32    /// Set a start delay. The animation holds its initial value for the delay
33    /// before starting (see [`AnimationPreset::to_animation`]).
34    pub fn delay(mut self, delay: Duration) -> Self {
35        self.delay = delay;
36        self
37    }
38
39    pub fn with_duration(mut self, duration: Duration) -> Self {
40        self.duration = duration;
41        self
42    }
43
44    pub fn with_easing(mut self, easing: fn(f32) -> f32) -> Self {
45        self.easing = easing;
46        self
47    }
48
49    /// Set a start delay. The animation holds its initial value for the delay
50    /// before starting (see [`AnimationPreset::to_animation`]).
51    pub fn with_delay(mut self, delay: Duration) -> Self {
52        self.delay = delay;
53        self
54    }
55
56    pub fn get_duration(&self) -> Duration {
57        self.duration
58    }
59
60    pub fn get_easing(&self) -> fn(f32) -> f32 {
61        self.easing
62    }
63
64    /// Returns the start delay applied by [`AnimationPreset::to_animation`].
65    pub fn get_delay(&self) -> Duration {
66        self.delay
67    }
68
69    pub fn to_animation(&self) -> Animation {
70        Animation::new(self.duration)
71            .with_easing(self.easing)
72            .with_delay(self.delay)
73    }
74}
75
76pub fn fade_in() -> AnimationPreset {
77    AnimationPreset::new(Duration::from_millis(200), easings::ease_out_cubic)
78}
79
80pub fn fade_out() -> AnimationPreset {
81    AnimationPreset::new(Duration::from_millis(200), easings::ease_in_cubic)
82}
83
84pub fn slide_up() -> AnimationPreset {
85    AnimationPreset::new(Duration::from_millis(250), easings::ease_out_cubic)
86}
87
88pub fn slide_down() -> AnimationPreset {
89    AnimationPreset::new(Duration::from_millis(250), easings::ease_out_cubic)
90}
91
92pub fn scale_in() -> AnimationPreset {
93    AnimationPreset::new(Duration::from_millis(200), easings::ease_out_back)
94}
95
96pub fn bounce_in() -> AnimationPreset {
97    AnimationPreset::new(Duration::from_millis(400), easings::elastic)
98}
99
100pub fn slide_in_left() -> AnimationPreset {
101    AnimationPreset::new(Duration::from_millis(250), easings::ease_out_cubic)
102}
103
104pub fn slide_in_right() -> AnimationPreset {
105    AnimationPreset::new(Duration::from_millis(250), easings::ease_out_cubic)
106}
107
108#[derive(Clone, Debug, PartialEq)]
109pub enum AnimationRepeat {
110    Once,
111    /// Finite repeat count. A count of zero is treated as one pass.
112    Count(u32),
113    Infinite,
114}
115
116pub struct KeyframeAnimation {
117    id: SharedString,
118    keyframes: Vec<(f32, f32)>,
119    duration: Duration,
120    repeat: AnimationRepeat,
121    easing: fn(f32) -> f32,
122}
123
124impl KeyframeAnimation {
125    pub fn new(id: impl Into<SharedString>) -> Self {
126        Self {
127            id: id.into(),
128            keyframes: vec![(0.0, 0.0), (1.0, 1.0)],
129            duration: Duration::from_millis(300),
130            repeat: AnimationRepeat::Once,
131            easing: easings::linear,
132        }
133    }
134
135    /// Add a finite keyframe, ignoring non-finite positions or values.
136    pub fn at(mut self, pct: f32, value: f32) -> Self {
137        if !pct.is_finite() || !value.is_finite() {
138            return self;
139        }
140
141        let pct = pct.clamp(0.0, 1.0);
142        if let Some(pos) = self
143            .keyframes
144            .iter()
145            .position(|(p, _)| (*p - pct).abs() < f32::EPSILON)
146        {
147            self.keyframes[pos] = (pct, value);
148        } else {
149            self.keyframes.push((pct, value));
150            self.keyframes
151                .sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
152        }
153        self
154    }
155
156    pub fn duration(mut self, duration: Duration) -> Self {
157        self.duration = duration;
158        self
159    }
160
161    pub fn repeat(mut self, repeat: AnimationRepeat) -> Self {
162        self.repeat = repeat;
163        self
164    }
165
166    pub fn easing(mut self, easing: fn(f32) -> f32) -> Self {
167        self.easing = easing;
168        self
169    }
170
171    pub fn id(&self) -> &SharedString {
172        &self.id
173    }
174
175    pub fn get_duration(&self) -> Duration {
176        self.duration
177    }
178
179    pub fn get_repeat(&self) -> &AnimationRepeat {
180        &self.repeat
181    }
182
183    pub fn interpolate(&self, progress: f32) -> f32 {
184        let progress = progress.clamp(0.0, 1.0);
185
186        if self.keyframes.len() < 2 {
187            return if self.keyframes.is_empty() {
188                0.0
189            } else {
190                self.keyframes[0].1
191            };
192        }
193
194        let eased = (self.easing)(progress);
195
196        let mut prev = &self.keyframes[0];
197        for kf in &self.keyframes[1..] {
198            if eased <= kf.0 {
199                let range = kf.0 - prev.0;
200                if range <= f32::EPSILON {
201                    return kf.1;
202                }
203                let local_t = (eased - prev.0) / range;
204                return prev.1 + (kf.1 - prev.1) * local_t;
205            }
206            prev = kf;
207        }
208
209        self.keyframes.last().map(|kf| kf.1).unwrap_or(1.0)
210    }
211
212    pub fn to_animation(&self) -> Animation {
213        let anim = Animation::new(self.duration).with_easing(self.easing);
214        match &self.repeat {
215            AnimationRepeat::Once => anim,
216            AnimationRepeat::Infinite => anim.repeat(),
217            AnimationRepeat::Count(n) => anim.repeat_n(*n),
218        }
219    }
220}
221
222#[derive(Clone)]
223pub struct StaggerConfig {
224    delay_per_child: Duration,
225    preset: AnimationPreset,
226}
227
228impl StaggerConfig {
229    pub fn new() -> Self {
230        Self {
231            delay_per_child: Duration::from_millis(50),
232            preset: fade_in(),
233        }
234    }
235
236    pub fn delay_per_child(mut self, delay: Duration) -> Self {
237        self.delay_per_child = delay;
238        self
239    }
240
241    pub fn animation(mut self, preset: AnimationPreset) -> Self {
242        self.preset = preset;
243        self
244    }
245
246    pub fn delay_for_index(&self, index: usize) -> Duration {
247        self.preset.delay + self.delay_per_child * index as u32
248    }
249
250    pub fn preset_for_index(&self, index: usize) -> AnimationPreset {
251        let mut preset = self.preset.clone();
252        preset.delay = self.delay_for_index(index);
253        preset
254    }
255
256    pub fn get_preset(&self) -> &AnimationPreset {
257        &self.preset
258    }
259}
260
261impl Default for StaggerConfig {
262    fn default() -> Self {
263        Self::new()
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::KeyframeAnimation;
270
271    #[test]
272    fn non_finite_keyframes_are_ignored() {
273        let animation = KeyframeAnimation::new("finite-keyframes")
274            .at(f32::NAN, 0.5)
275            .at(0.5, f32::INFINITY);
276
277        assert_eq!(animation.keyframes, vec![(0.0, 0.0), (1.0, 1.0)]);
278    }
279}
280
281#[derive(Clone)]
282pub struct Transition {
283    property: SharedString,
284    duration: Duration,
285    easing: fn(f32) -> f32,
286    delay: Duration,
287}
288
289impl Transition {
290    pub fn new(property: impl Into<SharedString>) -> Self {
291        Self {
292            property: property.into(),
293            duration: Duration::from_millis(200),
294            easing: easings::ease_out_cubic,
295            delay: Duration::ZERO,
296        }
297    }
298
299    pub fn duration(mut self, duration: Duration) -> Self {
300        self.duration = duration;
301        self
302    }
303
304    pub fn easing(mut self, easing: fn(f32) -> f32) -> Self {
305        self.easing = easing;
306        self
307    }
308
309    /// Set a start delay. The animation holds its initial value for the delay
310    /// before starting (see [`Transition::to_animation`]).
311    pub fn delay(mut self, delay: Duration) -> Self {
312        self.delay = delay;
313        self
314    }
315
316    pub fn get_property(&self) -> &SharedString {
317        &self.property
318    }
319
320    pub fn get_duration(&self) -> Duration {
321        self.duration
322    }
323
324    pub fn get_easing(&self) -> fn(f32) -> f32 {
325        self.easing
326    }
327
328    /// Returns the start delay applied by [`Transition::to_animation`].
329    pub fn get_delay(&self) -> Duration {
330        self.delay
331    }
332
333    pub fn to_animation(&self) -> Animation {
334        Animation::new(self.duration)
335            .with_easing(self.easing)
336            .with_delay(self.delay)
337    }
338}