Skip to main content

gpui/elements/
animation.rs

1use scheduler::Instant;
2use std::{num::NonZeroUsize, rc::Rc, time::Duration};
3
4use crate::{
5    AnyElement, App, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement,
6    ParentElement, SpringAnimation, SpringConfig, SpringPlayback, SpringState, SpringTarget, Task,
7    Window,
8};
9
10pub use easing::*;
11use smallvec::SmallVec;
12
13/// An animation that can be applied to an element.
14#[derive(Clone)]
15pub struct Animation {
16    /// The amount of time for which this animation should run
17    pub duration: Duration,
18    /// Whether to repeat this animation when it finishes
19    pub oneshot: bool,
20    /// Whether to derive the phase from a shared clock. See [`Animation::repeat_synced`].
21    pub synced: bool,
22    /// A function that maps normalized time to an animated value.
23    /// The result may exceed 0..1 for easing functions that overshoot.
24    pub easing: Rc<dyn Fn(f32) -> f32>,
25    /// The maximum number of times per second this animation re-renders.
26    /// When `None`, the animation re-renders on every frame.
27    pub max_fps: Option<f32>,
28    /// The number of equal steps this animation advances in. See [`Animation::with_steps`].
29    /// When `None`, the animation advances continuously.
30    pub steps: Option<NonZeroUsize>,
31}
32
33impl Animation {
34    /// Create a new animation with the given duration.
35    /// By default the animation will only run once and will use a linear easing function.
36    pub fn new(duration: Duration) -> Self {
37        Self {
38            duration,
39            oneshot: true,
40            synced: false,
41            easing: Rc::new(linear),
42            max_fps: None,
43            steps: None,
44        }
45    }
46
47    /// Set the animation to loop when it finishes.
48    pub fn repeat(mut self) -> Self {
49        self.oneshot = false;
50        self
51    }
52
53    /// Set the animation to loop when it finishes, phase-locked to a clock shared by the whole [`App`].
54    pub fn repeat_synced(mut self) -> Self {
55        self.oneshot = false;
56        self.synced = true;
57        self
58    }
59
60    /// Sets the easing function used to map normalized time to an animated value.
61    ///
62    /// The output is not clamped, allowing physical easing functions such as
63    /// springs to overshoot.
64    pub fn with_easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
65        self.easing = Rc::new(easing);
66        self
67    }
68
69    /// Limit how often this animation re-renders. Instead of re-rendering on
70    /// every frame, the animation schedules its next render `1 / max_fps`
71    /// seconds after the current one. Values that are not finite and positive
72    /// are ignored.
73    pub fn with_max_fps(mut self, max_fps: f32) -> Self {
74        self.max_fps = Some(max_fps);
75        self
76    }
77
78    /// Advance time in `steps` equal steps instead of continuously, like CSS
79    /// `steps()`. Normalized time is `0`, then `1 / steps`, and so on, and the
80    /// animator receives the eased value of each step. The animation re-renders
81    /// only when it steps, so [`Self::with_max_fps`] has no effect. A `steps` of
82    /// zero is ignored.
83    pub fn with_steps(mut self, steps: usize) -> Self {
84        self.steps = NonZeroUsize::new(steps);
85        self
86    }
87}
88
89/// An extension trait for adding the animation wrapper to both Elements and Components
90///
91/// Animations rendered through this trait automatically respect
92/// [`App::reduce_motion`](crate::App::reduce_motion): when it is set,
93/// the element is rendered in a static state (the end state for oneshot
94/// animations, the start state for repeating ones) and no animation frames are
95/// scheduled.
96pub trait AnimationExt {
97    /// Render this component or element with an animation
98    fn with_animation(
99        self,
100        id: impl Into<ElementId>,
101        animation: Animation,
102        animator: impl Fn(Self, f32) -> Self + 'static,
103    ) -> AnimationElement<Self>
104    where
105        Self: Sized,
106    {
107        AnimationElement {
108            id: id.into(),
109            element: Some(self),
110            animator: Box::new(move |this, _, value| animator(this, value)),
111            animations: smallvec::smallvec![animation],
112        }
113    }
114
115    /// Render this component or element with a chain of animations
116    fn with_animations(
117        self,
118        id: impl Into<ElementId>,
119        animations: Vec<Animation>,
120        animator: impl Fn(Self, usize, f32) -> Self + 'static,
121    ) -> AnimationElement<Self>
122    where
123        Self: Sized,
124    {
125        AnimationElement {
126            id: id.into(),
127            element: Some(self),
128            animator: Box::new(animator),
129            animations: animations.into(),
130        }
131    }
132
133    /// Renders this component or element at the value produced by a spring.
134    ///
135    /// The element ID preserves position and velocity across target changes.
136    /// A newly mounted spring starts at its target unless configured with
137    /// [`SpringAnimation::from`].
138    fn with_spring<T>(
139        self,
140        id: impl Into<ElementId>,
141        animation: SpringAnimation<T>,
142        animator: impl FnOnce(Self, T::Output) -> Self + 'static,
143    ) -> SpringAnimationElement<Self>
144    where
145        Self: Sized,
146        T: SpringTarget,
147        T::Output: 'static,
148    {
149        let SpringAnimation {
150            config,
151            target,
152            epsilon,
153            initial,
154            playback,
155        } = animation;
156        let scalar_target = target.target();
157        SpringAnimationElement {
158            id: id.into(),
159            element: Some(self),
160            config,
161            target: scalar_target,
162            epsilon,
163            initial,
164            playback,
165            animator: Some(Box::new(move |this, value| {
166                animator(this, target.resolve(value))
167            })),
168        }
169    }
170}
171
172impl<E: IntoElement + 'static> AnimationExt for E {}
173
174/// A GPUI element that applies an animation to another element
175pub struct AnimationElement<E> {
176    id: ElementId,
177    element: Option<E>,
178    animations: SmallVec<[Animation; 1]>,
179    animator: Box<dyn Fn(E, usize, f32) -> E + 'static>,
180}
181
182/// A GPUI element driven by a stateful spring.
183pub struct SpringAnimationElement<E> {
184    id: ElementId,
185    element: Option<E>,
186    config: SpringConfig,
187    target: f32,
188    epsilon: f32,
189    initial: Option<f32>,
190    playback: SpringPlayback,
191    animator: Option<Box<dyn FnOnce(E, f32) -> E + 'static>>,
192}
193
194impl<E: ParentElement> ParentElement for SpringAnimationElement<E> {
195    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
196        let Some(element) = &mut self.element else {
197            return;
198        };
199
200        element.extend(elements);
201    }
202}
203
204impl<E> SpringAnimationElement<E> {
205    /// Returns a new [`SpringAnimationElement<E>`] after applying the given function
206    /// to the element being animated.
207    pub fn map_element(mut self, f: impl FnOnce(E) -> E) -> SpringAnimationElement<E> {
208        self.element = self.element.map(f);
209        self
210    }
211}
212
213impl<E: ParentElement> ParentElement for AnimationElement<E> {
214    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
215        let Some(element) = &mut self.element else {
216            return;
217        };
218
219        element.extend(elements);
220    }
221}
222
223impl<E> AnimationElement<E> {
224    /// Returns a new [`AnimationElement<E>`] after applying the given function
225    /// to the element being animated.
226    pub fn map_element(mut self, f: impl FnOnce(E) -> E) -> AnimationElement<E> {
227        self.element = self.element.map(f);
228        self
229    }
230}
231
232struct AnimationState {
233    start: Instant,
234    animation_ix: usize,
235    /// The re-render scheduled for the next step (see [`Animation::with_steps`])
236    /// or capped frame (see [`Animation::with_max_fps`]), and when it is due.
237    wake: Option<(Instant, Task<()>)>,
238}
239
240impl AnimationState {
241    /// Re-renders the current view at `instant`, unless a re-render is already due by then.
242    fn render_at(&mut self, instant: Instant, window: &Window, cx: &App) {
243        let now = cx.background_executor().now();
244        if let Some((due, _)) = &self.wake
245            && now < *due
246            && *due <= instant
247        {
248            return;
249        }
250        let view = window.current_view();
251        let wake = window.spawn(cx, async move |cx| {
252            // A timer can fire early, and a render before `instant` would repeat the last one.
253            loop {
254                let delay = instant.saturating_duration_since(cx.background_executor().now());
255                if delay.is_zero() {
256                    break;
257                }
258                cx.background_executor().timer(delay).await;
259            }
260            cx.update(move |_, cx| cx.notify(view)).ok();
261        });
262        // Replacing a wake that was due later drops it, which cancels its timer.
263        self.wake = Some((instant, wake));
264    }
265}
266
267struct SpringElementState {
268    spring: SpringState,
269    target: f32,
270    config: SpringConfig,
271    initial: f32,
272    playback: SpringPlayback,
273    updated_at: Instant,
274}
275
276impl<E: IntoElement + 'static> Element for SpringAnimationElement<E> {
277    type RequestLayoutState = AnyElement;
278    type PrepaintState = ();
279
280    fn id(&self) -> Option<ElementId> {
281        Some(self.id.clone())
282    }
283
284    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
285        None
286    }
287
288    fn request_layout(
289        &mut self,
290        global_id: Option<&GlobalElementId>,
291        _inspector_id: Option<&InspectorElementId>,
292        window: &mut Window,
293        cx: &mut App,
294    ) -> (crate::LayoutId, Self::RequestLayoutState) {
295        window.with_element_state(global_id.unwrap(), |state, window| {
296            let now = cx.background_executor().now();
297            let initial = self.initial.unwrap_or(self.target);
298            let mut state = state.unwrap_or_else(|| SpringElementState {
299                spring: SpringState {
300                    position: initial,
301                    velocity: 0.0,
302                },
303                target: self.target,
304                config: self.config,
305                initial,
306                playback: self.playback,
307                updated_at: now,
308            });
309
310            let elapsed = now.duration_since(state.updated_at).as_secs_f32();
311            match state.playback {
312                SpringPlayback::Running => {
313                    state.spring = state.config.step(state.spring, state.target, elapsed);
314                }
315                SpringPlayback::Paused
316                | SpringPlayback::Stopped
317                | SpringPlayback::Completed
318                | SpringPlayback::Cancelled => {}
319            }
320
321            state.config = self.config;
322            state.target = self.target;
323
324            let done = match self.playback {
325                SpringPlayback::Running => {
326                    if cx.reduce_motion() {
327                        state.spring = SpringState {
328                            position: state.target,
329                            velocity: 0.0,
330                        };
331                        true
332                    } else {
333                        let done =
334                            state
335                                .config
336                                .is_settled(state.spring, state.target, self.epsilon);
337                        if done {
338                            state.spring = SpringState {
339                                position: state.target,
340                                velocity: 0.0,
341                            };
342                        }
343                        done
344                    }
345                }
346                SpringPlayback::Paused => true,
347                SpringPlayback::Stopped => {
348                    state.spring.velocity = 0.0;
349                    true
350                }
351                SpringPlayback::Completed => {
352                    state.spring = SpringState {
353                        position: state.target,
354                        velocity: 0.0,
355                    };
356                    true
357                }
358                SpringPlayback::Cancelled => {
359                    state.spring = SpringState {
360                        position: state.initial,
361                        velocity: 0.0,
362                    };
363                    true
364                }
365            };
366            state.playback = self.playback;
367            state.updated_at = now;
368
369            let element = self.element.take().expect("should only be called once");
370            let animator = self.animator.take().expect("should only be called once");
371            let mut element = animator(element, state.spring.position).into_any_element();
372
373            if !done {
374                window.request_animation_frame();
375            }
376
377            ((element.request_layout(window, cx), element), state)
378        })
379    }
380
381    fn prepaint(
382        &mut self,
383        _id: Option<&GlobalElementId>,
384        _inspector_id: Option<&InspectorElementId>,
385        _bounds: crate::Bounds<crate::Pixels>,
386        element: &mut Self::RequestLayoutState,
387        window: &mut Window,
388        cx: &mut App,
389    ) -> Self::PrepaintState {
390        element.prepaint(window, cx);
391    }
392
393    fn paint(
394        &mut self,
395        _id: Option<&GlobalElementId>,
396        _inspector_id: Option<&InspectorElementId>,
397        _bounds: crate::Bounds<crate::Pixels>,
398        element: &mut Self::RequestLayoutState,
399        _: &mut Self::PrepaintState,
400        window: &mut Window,
401        cx: &mut App,
402    ) {
403        element.paint(window, cx);
404    }
405}
406
407impl<E: IntoElement + 'static> Element for AnimationElement<E> {
408    type RequestLayoutState = AnyElement;
409    type PrepaintState = ();
410
411    fn id(&self) -> Option<ElementId> {
412        Some(self.id.clone())
413    }
414
415    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
416        None
417    }
418
419    fn request_layout(
420        &mut self,
421        global_id: Option<&GlobalElementId>,
422        _inspector_id: Option<&InspectorElementId>,
423        window: &mut Window,
424        cx: &mut App,
425    ) -> (crate::LayoutId, Self::RequestLayoutState) {
426        window.with_element_state(global_id.unwrap(), |state, window| {
427            let now = cx.background_executor().now();
428            let mut state = state.unwrap_or_else(|| AnimationState {
429                start: now,
430                animation_ix: 0,
431                wake: None,
432            });
433            let (animation_ix, delta, done, next_step) = if cx.reduce_motion() {
434                let animation_ix = self.animations.len() - 1;
435                let delta = if self.animations[animation_ix].oneshot {
436                    1.0
437                } else {
438                    0.0
439                };
440                (animation_ix, delta, true, None)
441            } else {
442                // The chain can be shorter than on the render that handed off to this index.
443                state.animation_ix = state.animation_ix.min(self.animations.len() - 1);
444                let animation_ix = state.animation_ix;
445                let duration = self.animations[animation_ix].duration;
446
447                let elapsed = if self.animations[animation_ix].synced && !duration.is_zero() {
448                    let elapsed = now - cx.synced_animation_epoch;
449                    // Reduce modulo the duration before f32 conversion, which loses sub-second precision at scale.
450                    Duration::from_nanos((elapsed.as_nanos() % duration.as_nanos()) as u64)
451                } else {
452                    now - state.start
453                };
454                let mut delta = elapsed.as_secs_f32() / duration.as_secs_f32();
455                let mut finished = delta > 1.0;
456                let mut next_step = None;
457                if let Some(steps) = self.animations[animation_ix].steps
458                    && !duration.is_zero()
459                {
460                    // Steps rarely start on a whole nanosecond, so count them in integers.
461                    let (elapsed, duration) = (elapsed.as_nanos(), duration.as_nanos());
462                    let steps = steps.get() as u128;
463                    let step = elapsed * steps / duration;
464                    delta = (step % steps) as f32 / steps as f32;
465                    finished = self.animations[animation_ix].oneshot && step >= steps;
466                    if !finished {
467                        let starts_in = ((step + 1) * duration).div_ceil(steps) - elapsed;
468                        next_step = Some(now + Duration::from_nanos(starts_in as u64));
469                    }
470                }
471
472                let mut done = false;
473                if finished {
474                    if self.animations[animation_ix].oneshot {
475                        if animation_ix >= self.animations.len() - 1 {
476                            done = true;
477                        } else {
478                            state.start = now;
479                            state.animation_ix += 1;
480                            state.wake = None;
481                        }
482                        delta = 1.0;
483                    } else {
484                        delta %= 1.0;
485                    }
486                }
487                (animation_ix, delta, done, next_step)
488            };
489            let delta = (self.animations[animation_ix].easing)(delta);
490
491            debug_assert!(delta.is_finite(), "animated value should be finite");
492
493            let element = self.element.take().expect("should only be called once");
494            let mut element = (self.animator)(element, animation_ix, delta).into_any_element();
495
496            if let Some(next_step) = next_step {
497                state.render_at(next_step, window, cx);
498            } else if !done {
499                // A hand-off requests the next frame, so the next animation's cap counts from its
500                // first render, as it does after mounting. A stepped animation has no cap.
501                let animation = &self.animations[animation_ix];
502                let handed_off = state.animation_ix != animation_ix;
503                match animation.max_fps.filter(|_| animation.steps.is_none()) {
504                    Some(max_fps) if max_fps.is_finite() && max_fps > 0.0 && !handed_off => {
505                        state.render_at(now + Duration::from_secs_f32(1.0 / max_fps), window, cx)
506                    }
507                    _ => window.request_animation_frame(),
508                }
509            }
510
511            ((element.request_layout(window, cx), element), state)
512        })
513    }
514
515    fn prepaint(
516        &mut self,
517        _id: Option<&GlobalElementId>,
518        _inspector_id: Option<&InspectorElementId>,
519        _bounds: crate::Bounds<crate::Pixels>,
520        element: &mut Self::RequestLayoutState,
521        window: &mut Window,
522        cx: &mut App,
523    ) -> Self::PrepaintState {
524        element.prepaint(window, cx);
525    }
526
527    fn paint(
528        &mut self,
529        _id: Option<&GlobalElementId>,
530        _inspector_id: Option<&InspectorElementId>,
531        _bounds: crate::Bounds<crate::Pixels>,
532        element: &mut Self::RequestLayoutState,
533        _: &mut Self::PrepaintState,
534        window: &mut Window,
535        cx: &mut App,
536    ) {
537        element.paint(window, cx);
538    }
539}
540
541mod easing {
542    use std::f32::consts::PI;
543
544    /// The linear easing function, or delta itself
545    pub fn linear(delta: f32) -> f32 {
546        delta
547    }
548
549    /// The quadratic easing function, delta * delta
550    pub fn quadratic(delta: f32) -> f32 {
551        delta * delta
552    }
553
554    /// The quadratic ease-in-out function, which starts and ends slowly but speeds up in the middle
555    pub fn ease_in_out(delta: f32) -> f32 {
556        if delta < 0.5 {
557            2.0 * delta * delta
558        } else {
559            let x = -2.0 * delta + 2.0;
560            1.0 - x * x / 2.0
561        }
562    }
563
564    /// The Quint ease-out function, which starts quickly and decelerates to a stop
565    pub fn ease_out_quint() -> impl Fn(f32) -> f32 {
566        move |delta| 1.0 - (1.0 - delta).powi(5)
567    }
568
569    /// A heartbeat: a strong beat, a weaker one, then a rest. Starts and ends at 0 and peaks at 1.
570    pub fn heartbeat(delta: f32) -> f32 {
571        let beat = |center: f32, width: f32, height: f32| {
572            let x = (delta - center) / width;
573            height * (-x * x).exp()
574        };
575        beat(0.2, 0.06, 1.0) + beat(0.4, 0.05, 0.58)
576    }
577
578    /// Apply the given easing function, first in the forward direction and then in the reverse direction
579    pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
580        move |delta| {
581            if delta < 0.5 {
582                easing(delta * 2.0)
583            } else {
584                easing((1.0 - delta) * 2.0)
585            }
586        }
587    }
588
589    /// A custom easing function for pulsating alpha that slows down as it approaches 0.1
590    pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
591        let range = max - min;
592
593        move |delta| {
594            // Use a combination of sine and cubic functions for a more natural breathing rhythm
595            let t = (delta * 2.0 * PI).sin();
596            let breath = (t * t * t + t) / 2.0;
597
598            // Map the breath to our desired alpha range
599            let normalized_alpha = (breath + 1.0) / 2.0;
600
601            min + (normalized_alpha * range)
602        }
603    }
604}
605
606#[cfg(test)]
607mod tests {
608    use std::{cell::RefCell, rc::Rc, time::Duration};
609
610    use crate::{
611        Animation, Context, InteractiveElement, Pixels, Render, SpringAnimation, SpringConfig,
612        TestAppContext, WindowHandle, div, prelude::*, px, size,
613    };
614
615    use super::*;
616
617    struct AnimationTestView {
618        rendered_deltas: Rc<RefCell<Vec<f32>>>,
619        animations: Vec<Animation>,
620    }
621
622    struct SyncedAnimationTestView {
623        show_second: bool,
624        first_deltas: Rc<RefCell<Vec<f32>>>,
625        second_deltas: Rc<RefCell<Vec<f32>>>,
626    }
627
628    struct SpringAnimationTestView {
629        target: Pixels,
630        initial: Option<Pixels>,
631        playback: SpringPlayback,
632        rendered_values: Rc<RefCell<Vec<Pixels>>>,
633    }
634
635    impl Render for SpringAnimationTestView {
636        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
637            let rendered_values = self.rendered_values.clone();
638            let mut animation = SpringAnimation::new(SpringConfig::new(100.0, 2.0, 1.0))
639                .to(self.target)
640                .with_epsilon(0.01)
641                .playback(self.playback);
642            if let Some(initial) = self.initial {
643                animation = animation.from(initial);
644            }
645            div().with_spring("spring-animation", animation, move |this, value| {
646                rendered_values.borrow_mut().push(value);
647                this.left(value)
648            })
649        }
650    }
651
652    impl Render for SyncedAnimationTestView {
653        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
654            let record_deltas = |deltas: Rc<RefCell<Vec<f32>>>| {
655                move |this, delta| {
656                    deltas.borrow_mut().push(delta);
657                    this
658                }
659            };
660            div()
661                .size_full()
662                .child(div().with_animation(
663                    "first-synced-animation",
664                    Animation::new(Duration::from_secs(1)).repeat_synced(),
665                    record_deltas(self.first_deltas.clone()),
666                ))
667                .when(self.show_second, |this| {
668                    this.child(div().with_animation(
669                        "second-synced-animation",
670                        Animation::new(Duration::from_secs(1)).repeat_synced(),
671                        record_deltas(self.second_deltas.clone()),
672                    ))
673                })
674        }
675    }
676
677    impl Render for AnimationTestView {
678        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
679            let rendered_deltas = self.rendered_deltas.clone();
680            div().size_full().child(div().with_animations(
681                "repeating-animation",
682                self.animations.clone(),
683                move |this, _, delta| {
684                    rendered_deltas.borrow_mut().push(delta);
685                    this
686                },
687            ))
688        }
689    }
690
691    fn open_test_window(
692        cx: &mut TestAppContext,
693    ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
694        open_test_window_with_animations(cx, vec![one_second().repeat()])
695    }
696
697    fn one_second() -> Animation {
698        Animation::new(Duration::from_secs(1))
699    }
700
701    fn open_test_window_with_animations(
702        cx: &mut TestAppContext,
703        animations: Vec<Animation>,
704    ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
705        let rendered_deltas = Rc::new(RefCell::new(Vec::new()));
706        let window = cx.open_window(size(px(100.), px(100.)), {
707            let rendered_deltas = rendered_deltas.clone();
708            move |_, _| AnimationTestView {
709                rendered_deltas,
710                animations,
711            }
712        });
713        cx.run_until_parked();
714        (rendered_deltas, window)
715    }
716
717    fn simulate_next_frame<V: Render>(window: &WindowHandle<V>, cx: &mut TestAppContext) -> usize {
718        let callback_count = window
719            .update(cx, |_, window, cx| window.simulate_next_frame(cx))
720            .unwrap();
721        cx.run_until_parked();
722        callback_count
723    }
724    // Before parent-animation-element, using .with_animation
725    // would not allow chaining .parent after. This is just a
726    // build check that we can call div().id().with_animation().child()
727    #[test]
728    fn test_animation_parent() {
729        div()
730            .id("id")
731            //
732            .with_animation(
733                "animation",
734                Animation::new(Duration::from_secs(1)),
735                |el, _t| {
736                    //
737                    el
738                },
739            )
740            .child(
741                //
742                div(),
743            );
744    }
745
746    #[test]
747    fn test_spring_animation_parent() {
748        div()
749            .id("id")
750            .with_spring(
751                "spring-animation",
752                SpringAnimation::new(SpringConfig::new(100.0, 10.0, 1.0))
753                    .to(px(10.0))
754                    .from(px(0.0)),
755                |element, value| element.left(value),
756            )
757            .child(div());
758    }
759
760    #[gpui::test]
761    fn test_spring_animation_preserves_velocity_when_retargeted(cx: &mut TestAppContext) {
762        let rendered_values = Rc::new(RefCell::new(Vec::new()));
763        let window = cx.open_window(size(px(100.0), px(100.0)), {
764            let rendered_values = rendered_values.clone();
765            move |_, _| SpringAnimationTestView {
766                target: px(0.0),
767                initial: None,
768                playback: SpringPlayback::Running,
769                rendered_values,
770            }
771        });
772        cx.run_until_parked();
773        assert_eq!(*rendered_values.borrow(), vec![px(0.0)]);
774
775        window
776            .update(cx, |view, _, cx| {
777                view.target = px(100.0);
778                cx.notify();
779            })
780            .unwrap();
781        cx.run_until_parked();
782
783        cx.executor().advance_clock(Duration::from_millis(50));
784        assert!(simulate_next_frame(&window, cx) > 0);
785        let value_before_retargeting = *rendered_values.borrow().last().unwrap();
786        assert!(value_before_retargeting > px(0.0));
787        assert!(value_before_retargeting < px(100.0));
788
789        window
790            .update(cx, |view, _, cx| {
791                view.target = px(0.0);
792                cx.notify();
793            })
794            .unwrap();
795        cx.run_until_parked();
796
797        cx.executor().advance_clock(Duration::from_millis(5));
798        assert!(simulate_next_frame(&window, cx) > 0);
799        let value_after_retargeting = *rendered_values.borrow().last().unwrap();
800        assert!(value_after_retargeting > value_before_retargeting);
801    }
802
803    #[gpui::test]
804    fn test_paused_spring_resumes_with_its_velocity(cx: &mut TestAppContext) {
805        let rendered_values = Rc::new(RefCell::new(Vec::new()));
806        let window = cx.open_window(size(px(100.0), px(100.0)), {
807            let rendered_values = rendered_values.clone();
808            move |_, _| SpringAnimationTestView {
809                target: px(0.0),
810                initial: None,
811                playback: SpringPlayback::Running,
812                rendered_values,
813            }
814        });
815        cx.run_until_parked();
816
817        window
818            .update(cx, |view, _, cx| {
819                view.target = px(100.0);
820                cx.notify();
821            })
822            .unwrap();
823        cx.run_until_parked();
824        cx.executor().advance_clock(Duration::from_millis(50));
825        assert!(simulate_next_frame(&window, cx) > 0);
826
827        window
828            .update(cx, |view, _, cx| {
829                view.target = px(0.0);
830                view.playback = SpringPlayback::Paused;
831                cx.notify();
832            })
833            .unwrap();
834        cx.run_until_parked();
835        let paused_value = *rendered_values.borrow().last().unwrap();
836
837        cx.executor().advance_clock(Duration::from_millis(500));
838        assert!(simulate_next_frame(&window, cx) > 0);
839        assert_eq!(*rendered_values.borrow().last().unwrap(), paused_value);
840        assert_eq!(simulate_next_frame(&window, cx), 0);
841
842        window
843            .update(cx, |view, _, cx| {
844                view.playback = SpringPlayback::Running;
845                cx.notify();
846            })
847            .unwrap();
848        cx.run_until_parked();
849        cx.executor().advance_clock(Duration::from_millis(5));
850        assert!(simulate_next_frame(&window, cx) > 0);
851        assert!(*rendered_values.borrow().last().unwrap() > paused_value);
852    }
853
854    #[gpui::test]
855    fn test_stopped_spring_resumes_without_velocity(cx: &mut TestAppContext) {
856        let rendered_values = Rc::new(RefCell::new(Vec::new()));
857        let window = cx.open_window(size(px(100.0), px(100.0)), {
858            let rendered_values = rendered_values.clone();
859            move |_, _| SpringAnimationTestView {
860                target: px(0.0),
861                initial: None,
862                playback: SpringPlayback::Running,
863                rendered_values,
864            }
865        });
866        cx.run_until_parked();
867
868        window
869            .update(cx, |view, _, cx| {
870                view.target = px(1_000_000.0);
871                cx.notify();
872            })
873            .unwrap();
874        cx.run_until_parked();
875        cx.executor().advance_clock(Duration::from_millis(50));
876        assert!(simulate_next_frame(&window, cx) > 0);
877
878        window
879            .update(cx, |view, _, cx| {
880                view.target = px(0.0);
881                view.playback = SpringPlayback::Stopped;
882                cx.notify();
883            })
884            .unwrap();
885        cx.run_until_parked();
886        let stopped_value = *rendered_values.borrow().last().unwrap();
887
888        cx.executor().advance_clock(Duration::from_millis(500));
889        assert!(simulate_next_frame(&window, cx) > 0);
890        assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);
891        assert_eq!(simulate_next_frame(&window, cx), 0);
892
893        window
894            .update(cx, |view, _, cx| {
895                view.target = stopped_value;
896                view.playback = SpringPlayback::Running;
897                cx.notify();
898            })
899            .unwrap();
900        cx.run_until_parked();
901        assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);
902        assert_eq!(simulate_next_frame(&window, cx), 0);
903    }
904
905    #[gpui::test]
906    fn test_cancelled_and_completed_springs_resolve_their_endpoints(cx: &mut TestAppContext) {
907        let rendered_values = Rc::new(RefCell::new(Vec::new()));
908        let window = cx.open_window(size(px(100.0), px(100.0)), {
909            let rendered_values = rendered_values.clone();
910            move |_, _| SpringAnimationTestView {
911                target: px(100.0),
912                initial: Some(px(20.0)),
913                playback: SpringPlayback::Running,
914                rendered_values,
915            }
916        });
917        cx.run_until_parked();
918        assert_eq!(*rendered_values.borrow(), vec![px(20.0)]);
919
920        cx.executor().advance_clock(Duration::from_millis(50));
921        assert!(simulate_next_frame(&window, cx) > 0);
922        assert!(*rendered_values.borrow().last().unwrap() > px(20.0));
923
924        window
925            .update(cx, |view, _, cx| {
926                view.playback = SpringPlayback::Cancelled;
927                cx.notify();
928            })
929            .unwrap();
930        cx.run_until_parked();
931        assert_eq!(*rendered_values.borrow().last().unwrap(), px(20.0));
932        assert!(simulate_next_frame(&window, cx) > 0);
933        assert_eq!(simulate_next_frame(&window, cx), 0);
934
935        window
936            .update(cx, |view, _, cx| {
937                view.playback = SpringPlayback::Completed;
938                cx.notify();
939            })
940            .unwrap();
941        cx.run_until_parked();
942        assert_eq!(*rendered_values.borrow().last().unwrap(), px(100.0));
943        assert_eq!(simulate_next_frame(&window, cx), 0);
944    }
945
946    #[gpui::test]
947    fn test_spring_animation_respects_reduced_motion(cx: &mut TestAppContext) {
948        cx.update(|cx| cx.set_reduce_motion(true));
949        let rendered_values = Rc::new(RefCell::new(Vec::new()));
950        let window = cx.open_window(size(px(100.0), px(100.0)), {
951            let rendered_values = rendered_values.clone();
952            move |_, _| SpringAnimationTestView {
953                target: px(100.0),
954                initial: None,
955                playback: SpringPlayback::Running,
956                rendered_values,
957            }
958        });
959        cx.run_until_parked();
960
961        assert_eq!(*rendered_values.borrow(), vec![px(100.0)]);
962        assert_eq!(simulate_next_frame(&window, cx), 0);
963    }
964
965    #[gpui::test]
966    fn test_repeating_animation_schedules_animation_frames(cx: &mut TestAppContext) {
967        let (rendered_deltas, window) = open_test_window(cx);
968
969        assert_eq!(rendered_deltas.borrow().len(), 1);
970
971        for expected_frames in 2..=3 {
972            assert_eq!(simulate_next_frame(&window, cx), 1);
973            assert_eq!(rendered_deltas.borrow().len(), expected_frames);
974        }
975    }
976
977    #[gpui::test]
978    fn test_max_fps_schedules_timer_driven_frames(cx: &mut TestAppContext) {
979        // Synced, so the deltas follow the test scheduler's clock rather than wall time.
980        let capped = one_second().repeat_synced().with_max_fps(10.0);
981        let (rendered_deltas, window) = open_test_window_with_animations(cx, vec![capped]);
982
983        // The test scheduler's clock jitters forward slightly on each poll,
984        // so compare against expectations loosely.
985        let assert_deltas_approx_eq = |expected: &[f32]| {
986            let actual = rendered_deltas.borrow();
987            assert_eq!(actual.len(), expected.len(), "deltas: {actual:?}");
988            for (actual, expected) in actual.iter().zip(expected) {
989                assert!(
990                    (actual - expected).abs() < 1e-2,
991                    "expected {expected}, got {actual}"
992                );
993            }
994        };
995
996        assert_deltas_approx_eq(&[0.0]);
997
998        // No per-frame callback is scheduled; re-renders are timer-driven.
999        assert_eq!(simulate_next_frame(&window, cx), 0);
1000        assert_deltas_approx_eq(&[0.0]);
1001
1002        cx.executor().advance_clock(Duration::from_millis(105));
1003        cx.run_until_parked();
1004        assert_deltas_approx_eq(&[0.0, 0.105]);
1005
1006        cx.executor().advance_clock(Duration::from_millis(105));
1007        cx.run_until_parked();
1008        assert_deltas_approx_eq(&[0.0, 0.105, 0.21]);
1009    }
1010
1011    #[gpui::test]
1012    fn test_capped_animation_hands_off_without_its_cap(cx: &mut TestAppContext) {
1013        // One render every two seconds, then two a second.
1014        let chain = [0.5, 2.0].map(|max_fps| one_second().with_max_fps(max_fps));
1015        let (deltas, window) = open_test_window_with_animations(cx, chain.to_vec());
1016        // The first animation finishes on a render that its cap didn't schedule.
1017        cx.executor().advance_clock(Duration::from_millis(1750));
1018        window.update(cx, |_, _, cx| cx.notify()).unwrap();
1019        // The second starts on the next frame, and its cap counts from there.
1020        assert_eq!(simulate_next_frame(&window, cx), 1);
1021        cx.executor().advance_clock(Duration::from_millis(500));
1022        cx.run_until_parked();
1023        assert_eq!(*deltas.borrow(), [0.0, 1.0, 0.0, 0.5]);
1024    }
1025
1026    #[gpui::test]
1027    fn test_sooner_cap_replaces_the_pending_one(cx: &mut TestAppContext) {
1028        let capped = |max_fps| vec![one_second().with_max_fps(max_fps)];
1029        let (deltas, window) = open_test_window_with_animations(cx, capped(0.1));
1030
1031        // Four renders a second from 250 ms on must not wait for the ten-second one.
1032        cx.executor().advance_clock(Duration::from_millis(250));
1033        window
1034            .update(cx, |view, _, _| view.animations = capped(4.0))
1035            .unwrap();
1036        window.update(cx, |_, _, cx| cx.notify()).unwrap();
1037        cx.executor().advance_clock(Duration::from_millis(125));
1038        // Rendering again before the next capped render neither moves it nor adds another.
1039        window.update(cx, |_, _, cx| cx.notify()).unwrap();
1040        cx.executor().advance_clock(Duration::from_millis(250));
1041        cx.run_until_parked();
1042        assert_eq!(*deltas.borrow(), [0.0, 0.25, 0.375, 0.5]);
1043    }
1044
1045    #[gpui::test]
1046    fn test_synced_steps_render_once_each(cx: &mut TestAppContext) {
1047        // Mount 30 ms into a step, after months on the shared clock. A seventh of a
1048        // second isn't a whole number of nanoseconds, and floats misplace its steps.
1049        let uptime = Duration::from_secs(300 * 24 * 60 * 60) + Duration::from_millis(30);
1050        cx.executor().advance_clock(uptime);
1051        let sevenths = one_second().repeat_synced().with_steps(7);
1052        let (rendered_deltas, window) = open_test_window_with_animations(cx, vec![sevenths]);
1053        assert_eq!(simulate_next_frame(&window, cx), 0);
1054
1055        // Rendering again within a step doesn't schedule the next step twice.
1056        window.update(cx, |_, _, cx| cx.notify()).unwrap();
1057        cx.executor().advance_clock(Duration::from_secs(1));
1058        cx.run_until_parked();
1059        let steps = [0, 0, 1, 2, 3, 4, 5, 6, 0].map(|step| step as f32 / 7.0);
1060        assert_eq!(*rendered_deltas.borrow(), steps);
1061    }
1062
1063    #[gpui::test]
1064    fn test_steps_finish_and_repeat_on_time(cx: &mut TestAppContext) {
1065        let quarters = one_second().with_steps(4);
1066        // A cap has no effect on a stepped animation, or on when the next one starts.
1067        let capped = one_second().with_max_fps(0.1);
1068        let chain = vec![quarters.clone().with_max_fps(0.1), capped];
1069        let (chained, window) = open_test_window_with_animations(cx, chain);
1070        let (repeating, _window) = open_test_window_with_animations(cx, vec![quarters.repeat()]);
1071
1072        cx.executor().advance_clock(Duration::from_millis(1500));
1073        cx.run_until_parked();
1074        assert_eq!(*chained.borrow(), [0.0, 0.25, 0.5, 0.75, 1.0]);
1075        assert_eq!(*repeating.borrow(), [0.0, 0.25, 0.5, 0.75, 0.0, 0.25, 0.5]);
1076
1077        // The next animation takes over on the next frame, half a second in.
1078        assert_eq!(simulate_next_frame(&window, cx), 1);
1079        assert_eq!(chained.borrow().last(), Some(&0.5));
1080    }
1081
1082    #[gpui::test]
1083    fn test_sooner_step_replaces_the_pending_one(cx: &mut TestAppContext) {
1084        let slow = vec![one_second().repeat().with_steps(1)];
1085        let (rendered_deltas, window) = open_test_window_with_animations(cx, slow);
1086
1087        // Ten steps a second from 100 ms on must not wait for the one-second step.
1088        cx.executor().advance_clock(Duration::from_millis(100));
1089        let fast = vec![one_second().repeat().with_steps(10)];
1090        window
1091            .update(cx, |view, _, cx| {
1092                view.animations = fast;
1093                cx.notify();
1094            })
1095            .unwrap();
1096        cx.executor().advance_clock(Duration::from_millis(100));
1097        // Rendering again within the new step doesn't schedule the next one twice.
1098        window.update(cx, |_, _, cx| cx.notify()).unwrap();
1099        cx.executor().advance_clock(Duration::from_millis(100));
1100        cx.run_until_parked();
1101        assert_eq!(*rendered_deltas.borrow(), [0.0, 0.1, 0.2, 0.2, 0.3]);
1102    }
1103
1104    #[gpui::test]
1105    fn test_chain_can_get_shorter_after_a_hand_off(cx: &mut TestAppContext) {
1106        let chain = vec![one_second(), one_second()];
1107        let (rendered_deltas, window) = open_test_window_with_animations(cx, chain);
1108        cx.executor().advance_clock(Duration::from_millis(1500));
1109        assert_eq!(simulate_next_frame(&window, cx), 1);
1110
1111        cx.executor().advance_clock(Duration::from_millis(250));
1112        window
1113            .update(cx, |view, _, cx| {
1114                view.animations = vec![one_second()];
1115                cx.notify();
1116            })
1117            .unwrap();
1118        cx.run_until_parked();
1119        assert_eq!(rendered_deltas.borrow().last(), Some(&0.25));
1120    }
1121
1122    #[gpui::test]
1123    fn test_synced_animations_share_phase_across_elements(cx: &mut TestAppContext) {
1124        let first_deltas = Rc::new(RefCell::new(Vec::new()));
1125        let second_deltas = Rc::new(RefCell::new(Vec::new()));
1126        let window = cx.open_window(size(px(100.), px(100.)), {
1127            let first_deltas = first_deltas.clone();
1128            let second_deltas = second_deltas.clone();
1129            move |_, _| SyncedAnimationTestView {
1130                show_second: false,
1131                first_deltas,
1132                second_deltas,
1133            }
1134        });
1135        cx.run_until_parked();
1136
1137        assert_eq!(*first_deltas.borrow(), vec![0.0]);
1138
1139        cx.executor().advance_clock(Duration::from_millis(250));
1140        simulate_next_frame(&window, cx);
1141        assert_eq!(*first_deltas.borrow(), vec![0.0, 0.25]);
1142
1143        // The second element mounts a quarter through the cycle, yet renders
1144        // the shared phase rather than starting at zero.
1145        window
1146            .update(cx, |view, _, cx| {
1147                view.show_second = true;
1148                cx.notify();
1149            })
1150            .unwrap();
1151        cx.run_until_parked();
1152        cx.executor().advance_clock(Duration::from_millis(250));
1153        simulate_next_frame(&window, cx);
1154
1155        assert_eq!(*second_deltas.borrow().last().unwrap(), 0.5);
1156        assert_eq!(
1157            *first_deltas.borrow().last().unwrap(),
1158            *second_deltas.borrow().last().unwrap()
1159        );
1160        assert!(second_deltas.borrow().iter().all(|delta| *delta > 0.0));
1161
1162        // The phase wraps around each full cycle.
1163        cx.executor().advance_clock(Duration::from_millis(2250));
1164        simulate_next_frame(&window, cx);
1165        assert_eq!(*first_deltas.borrow().last().unwrap(), 0.75);
1166
1167        // Sub-second precision survives months of uptime: converting the raw
1168        // elapsed time to f32 would round 0.25 away entirely.
1169        cx.executor()
1170            .advance_clock(Duration::from_secs(300 * 24 * 60 * 60) + Duration::from_millis(500));
1171        simulate_next_frame(&window, cx);
1172        assert_eq!(*first_deltas.borrow().last().unwrap(), 0.25);
1173    }
1174
1175    #[gpui::test]
1176    fn test_reduce_motion_renders_single_static_frame(cx: &mut TestAppContext) {
1177        cx.update(|cx| cx.set_reduce_motion(true));
1178        let (rendered_deltas, window) = open_test_window(cx);
1179
1180        assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
1181
1182        assert_eq!(simulate_next_frame(&window, cx), 0);
1183        assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
1184    }
1185}