animation.rs

  1use std::time::{Duration, Instant};
  2
  3use crate::{AnyElement, Element, ElementId, GlobalElementId, IntoElement};
  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 crate::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                let parent_id = cx.parent_view_id();
137                cx.on_next_frame(move |cx| {
138                    if let Some(parent_id) = parent_id {
139                        cx.notify(parent_id)
140                    } else {
141                        cx.refresh()
142                    }
143                })
144            }
145
146            ((element.request_layout(cx), element), state)
147        })
148    }
149
150    fn prepaint(
151        &mut self,
152        _id: Option<&GlobalElementId>,
153        _bounds: crate::Bounds<crate::Pixels>,
154        element: &mut Self::RequestLayoutState,
155        cx: &mut crate::WindowContext,
156    ) -> Self::PrepaintState {
157        element.prepaint(cx);
158    }
159
160    fn paint(
161        &mut self,
162        _id: Option<&GlobalElementId>,
163        _bounds: crate::Bounds<crate::Pixels>,
164        element: &mut Self::RequestLayoutState,
165        _: &mut Self::PrepaintState,
166        cx: &mut crate::WindowContext,
167    ) {
168        element.paint(cx);
169    }
170}
171
172mod easing {
173    use std::f32::consts::PI;
174
175    /// The linear easing function, or delta itself
176    pub fn linear(delta: f32) -> f32 {
177        delta
178    }
179
180    /// The quadratic easing function, delta * delta
181    pub fn quadratic(delta: f32) -> f32 {
182        delta * delta
183    }
184
185    /// The quadratic ease-in-out function, which starts and ends slowly but speeds up in the middle
186    pub fn ease_in_out(delta: f32) -> f32 {
187        if delta < 0.5 {
188            2.0 * delta * delta
189        } else {
190            let x = -2.0 * delta + 2.0;
191            1.0 - x * x / 2.0
192        }
193    }
194
195    /// Apply the given easing function, first in the forward direction and then in the reverse direction
196    pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
197        move |delta| {
198            if delta < 0.5 {
199                easing(delta * 2.0)
200            } else {
201                easing((1.0 - delta) * 2.0)
202            }
203        }
204    }
205
206    /// A custom easing function for pulsating alpha that slows down as it approaches 0.1
207    pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
208        let range = max - min;
209
210        move |delta| {
211            // Use a combination of sine and cubic functions for a more natural breathing rhythm
212            let t = (delta * 2.0 * PI).sin();
213            let breath = (t * t * t + t) / 2.0;
214
215            // Map the breath to our desired alpha range
216            let normalized_alpha = (breath + 1.0) / 2.0;
217
218            min + (normalized_alpha * range)
219        }
220    }
221}