animation.rs

  1use std::time::{Duration, Instant};
  2
  3use crate::{AnyElement, Element, ElementId, GlobalElementId, IntoElement, WindowContext};
  4
  5pub use easing::*;
  6
  7/// An animation that can be applied to an element.
  8pub struct Animation {
  9    /// The amount of time for which this animation should run
 10    pub duration: Duration,
 11    /// Whether to repeat this animation when it finishes
 12    pub oneshot: bool,
 13    /// A function that takes a delta between 0 and 1 and returns a new delta
 14    /// between 0 and 1 based on the given easing function.
 15    pub easing: Box<dyn Fn(f32) -> f32>,
 16}
 17
 18impl Animation {
 19    /// Create a new animation with the given duration.
 20    /// By default the animation will only run once and will use a linear easing function.
 21    pub fn new(duration: Duration) -> Self {
 22        Self {
 23            duration,
 24            oneshot: true,
 25            easing: Box::new(linear),
 26        }
 27    }
 28
 29    /// Set the animation to loop when it finishes.
 30    pub fn repeat(mut self) -> Self {
 31        self.oneshot = false;
 32        self
 33    }
 34
 35    /// Set the easing function to use for this animation.
 36    /// The easing function will take a time delta between 0 and 1 and return a new delta
 37    /// between 0 and 1
 38    pub fn with_easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
 39        self.easing = Box::new(easing);
 40        self
 41    }
 42}
 43
 44/// An extension trait for adding the animation wrapper to both Elements and Components
 45pub trait AnimationExt {
 46    /// Render this component or element with an animation
 47    fn with_animation(
 48        self,
 49        id: impl Into<ElementId>,
 50        animation: Animation,
 51        animator: impl Fn(Self, f32) -> Self + 'static,
 52    ) -> AnimationElement<Self>
 53    where
 54        Self: Sized,
 55    {
 56        AnimationElement {
 57            id: id.into(),
 58            element: Some(self),
 59            animator: Box::new(animator),
 60            animation,
 61        }
 62    }
 63}
 64
 65impl<E> AnimationExt for E {}
 66
 67/// A GPUI element that applies an animation to another element
 68pub struct AnimationElement<E> {
 69    id: ElementId,
 70    element: Option<E>,
 71    animation: Animation,
 72    animator: Box<dyn Fn(E, f32) -> E + 'static>,
 73}
 74
 75impl<E> AnimationElement<E> {
 76    /// Returns a new [`AnimationElement<E>`] after applying the given function
 77    /// to the element being animated.
 78    pub fn map_element(mut self, f: impl FnOnce(E) -> E) -> AnimationElement<E> {
 79        self.element = self.element.map(f);
 80        self
 81    }
 82}
 83
 84impl<E: IntoElement + 'static> IntoElement for AnimationElement<E> {
 85    type Element = AnimationElement<E>;
 86
 87    fn into_element(self) -> Self::Element {
 88        self
 89    }
 90}
 91
 92struct AnimationState {
 93    start: Instant,
 94}
 95
 96impl<E: IntoElement + 'static> Element for AnimationElement<E> {
 97    type RequestLayoutState = AnyElement;
 98    type PrepaintState = ();
 99
100    fn id(&self) -> Option<ElementId> {
101        Some(self.id.clone())
102    }
103
104    fn request_layout(
105        &mut self,
106        global_id: Option<&GlobalElementId>,
107        cx: &mut WindowContext,
108    ) -> (crate::LayoutId, Self::RequestLayoutState) {
109        cx.with_element_state(global_id.unwrap(), |state, cx| {
110            let state = state.unwrap_or_else(|| AnimationState {
111                start: Instant::now(),
112            });
113            let mut delta =
114                state.start.elapsed().as_secs_f32() / self.animation.duration.as_secs_f32();
115
116            let mut done = false;
117            if delta > 1.0 {
118                if self.animation.oneshot {
119                    done = true;
120                    delta = 1.0;
121                } else {
122                    delta %= 1.0;
123                }
124            }
125            let delta = (self.animation.easing)(delta);
126
127            debug_assert!(
128                (0.0..=1.0).contains(&delta),
129                "delta should always be between 0 and 1"
130            );
131
132            let element = self.element.take().expect("should only be called once");
133            let mut element = (self.animator)(element, delta).into_any_element();
134
135            if !done {
136                cx.request_animation_frame();
137            }
138
139            ((element.request_layout(cx), element), state)
140        })
141    }
142
143    fn prepaint(
144        &mut self,
145        _id: Option<&GlobalElementId>,
146        _bounds: crate::Bounds<crate::Pixels>,
147        element: &mut Self::RequestLayoutState,
148        cx: &mut WindowContext,
149    ) -> Self::PrepaintState {
150        element.prepaint(cx);
151    }
152
153    fn paint(
154        &mut self,
155        _id: Option<&GlobalElementId>,
156        _bounds: crate::Bounds<crate::Pixels>,
157        element: &mut Self::RequestLayoutState,
158        _: &mut Self::PrepaintState,
159        cx: &mut WindowContext,
160    ) {
161        element.paint(cx);
162    }
163}
164
165mod easing {
166    use std::f32::consts::PI;
167
168    /// The linear easing function, or delta itself
169    pub fn linear(delta: f32) -> f32 {
170        delta
171    }
172
173    /// The quadratic easing function, delta * delta
174    pub fn quadratic(delta: f32) -> f32 {
175        delta * delta
176    }
177
178    /// The quadratic ease-in-out function, which starts and ends slowly but speeds up in the middle
179    pub fn ease_in_out(delta: f32) -> f32 {
180        if delta < 0.5 {
181            2.0 * delta * delta
182        } else {
183            let x = -2.0 * delta + 2.0;
184            1.0 - x * x / 2.0
185        }
186    }
187
188    /// Apply the given easing function, first in the forward direction and then in the reverse direction
189    pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
190        move |delta| {
191            if delta < 0.5 {
192                easing(delta * 2.0)
193            } else {
194                easing((1.0 - delta) * 2.0)
195            }
196        }
197    }
198
199    /// A custom easing function for pulsating alpha that slows down as it approaches 0.1
200    pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
201        let range = max - min;
202
203        move |delta| {
204            // Use a combination of sine and cubic functions for a more natural breathing rhythm
205            let t = (delta * 2.0 * PI).sin();
206            let breath = (t * t * t + t) / 2.0;
207
208            // Map the breath to our desired alpha range
209            let normalized_alpha = (breath + 1.0) / 2.0;
210
211            min + (normalized_alpha * range)
212        }
213    }
214}