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: IntoElement + 'static> IntoElement for AnimationElement<E> {
 76    type Element = AnimationElement<E>;
 77
 78    fn into_element(self) -> Self::Element {
 79        self
 80    }
 81}
 82
 83struct AnimationState {
 84    start: Instant,
 85}
 86
 87impl<E: IntoElement + 'static> Element for AnimationElement<E> {
 88    type RequestLayoutState = AnyElement;
 89    type PrepaintState = ();
 90
 91    fn id(&self) -> Option<ElementId> {
 92        Some(self.id.clone())
 93    }
 94
 95    fn request_layout(
 96        &mut self,
 97        global_id: Option<&GlobalElementId>,
 98        cx: &mut crate::WindowContext,
 99    ) -> (crate::LayoutId, Self::RequestLayoutState) {
100        cx.with_element_state(global_id.unwrap(), |state, cx| {
101            let state = state.unwrap_or_else(|| AnimationState {
102                start: Instant::now(),
103            });
104            let mut delta =
105                state.start.elapsed().as_secs_f32() / self.animation.duration.as_secs_f32();
106
107            let mut done = false;
108            if delta > 1.0 {
109                if self.animation.oneshot {
110                    done = true;
111                    delta = 1.0;
112                } else {
113                    delta = delta % 1.0;
114                }
115            }
116            let delta = (self.animation.easing)(delta);
117
118            debug_assert!(
119                delta >= 0.0 && delta <= 1.0,
120                "delta should always be between 0 and 1"
121            );
122
123            let element = self.element.take().expect("should only be called once");
124            let mut element = (self.animator)(element, delta).into_any_element();
125
126            if !done {
127                let parent_id = cx.parent_view_id();
128                cx.on_next_frame(move |cx| {
129                    if let Some(parent_id) = parent_id {
130                        cx.notify(parent_id)
131                    } else {
132                        cx.refresh()
133                    }
134                })
135            }
136
137            ((element.request_layout(cx), element), state)
138        })
139    }
140
141    fn prepaint(
142        &mut self,
143        _id: Option<&GlobalElementId>,
144        _bounds: crate::Bounds<crate::Pixels>,
145        element: &mut Self::RequestLayoutState,
146        cx: &mut crate::WindowContext,
147    ) -> Self::PrepaintState {
148        element.prepaint(cx);
149    }
150
151    fn paint(
152        &mut self,
153        _id: Option<&GlobalElementId>,
154        _bounds: crate::Bounds<crate::Pixels>,
155        element: &mut Self::RequestLayoutState,
156        _: &mut Self::PrepaintState,
157        cx: &mut crate::WindowContext,
158    ) {
159        element.paint(cx);
160    }
161}
162
163mod easing {
164    /// The linear easing function, or delta itself
165    pub fn linear(delta: f32) -> f32 {
166        delta
167    }
168
169    /// The quadratic easing function, delta * delta
170    pub fn quadratic(delta: f32) -> f32 {
171        delta * delta
172    }
173
174    /// The quadratic ease-in-out function, which starts and ends slowly but speeds up in the middle
175    pub fn ease_in_out(delta: f32) -> f32 {
176        if delta < 0.5 {
177            2.0 * delta * delta
178        } else {
179            let x = -2.0 * delta + 2.0;
180            1.0 - x * x / 2.0
181        }
182    }
183
184    /// Apply the given easing function, first in the forward direction and then in the reverse direction
185    pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
186        move |delta| {
187            if delta < 0.5 {
188                easing(delta * 2.0)
189            } else {
190                easing((1.0 - delta) * 2.0)
191            }
192        }
193    }
194}