Skip to main content

freya_animation/
hook.rs

1use std::{
2    ops::Deref,
3    time::{
4        Duration,
5        Instant,
6    },
7};
8
9use freya_core::prelude::*;
10
11#[derive(Default, PartialEq, Clone, Debug)]
12pub struct AnimConfiguration {
13    on_finish: OnFinish,
14    on_creation: OnCreation,
15    on_change: OnChange,
16}
17
18impl AnimConfiguration {
19    pub fn on_finish(&mut self, on_finish: OnFinish) -> &mut Self {
20        self.on_finish = on_finish;
21        self
22    }
23
24    pub fn on_creation(&mut self, on_creation: OnCreation) -> &mut Self {
25        self.on_creation = on_creation;
26        self
27    }
28
29    pub fn on_change(&mut self, on_change: OnChange) -> &mut Self {
30        self.on_change = on_change;
31        self
32    }
33}
34
35/// Controls the direction of the animation.
36#[derive(Clone, Copy, PartialEq)]
37pub enum AnimDirection {
38    Forward,
39    Reverse,
40}
41
42impl AnimDirection {
43    pub fn toggle(&mut self) {
44        match self {
45            Self::Forward => *self = Self::Reverse,
46            Self::Reverse => *self = Self::Forward,
47        }
48    }
49}
50
51/// What to do once the animation finishes.
52///
53/// By default it is [OnFinish::Nothing].
54#[derive(PartialEq, Clone, Copy, Default, Debug)]
55pub enum OnFinish {
56    /// Does nothing at all.
57    #[default]
58    Nothing,
59    /// Runs the animation in reverse direction.
60    Reverse {
61        /// Delay before reversing.
62        delay: Duration,
63    },
64    /// Runs the animation in the same direction again.
65    Restart {
66        /// Delay before restarting.
67        delay: Duration,
68    },
69}
70
71impl OnFinish {
72    /// Creates a new [OnFinish::Nothing] variant.
73    pub fn nothing() -> Self {
74        Self::Nothing
75    }
76
77    /// Creates a new [OnFinish::Reverse] variant with no delay.
78    pub fn reverse() -> Self {
79        Self::Reverse {
80            delay: Duration::ZERO,
81        }
82    }
83
84    /// Creates a new [OnFinish::Reverse] variant with a delay.
85    pub fn reverse_with_delay(delay: Duration) -> Self {
86        Self::Reverse { delay }
87    }
88
89    /// Creates a new [OnFinish::Restart] variant with no delay.
90    pub fn restart() -> Self {
91        Self::Restart {
92            delay: Duration::ZERO,
93        }
94    }
95
96    /// Creates a new [OnFinish::Restart] variant with a delay.
97    pub fn restart_with_delay(delay: Duration) -> Self {
98        Self::Restart { delay }
99    }
100}
101
102/// What to do once the animation gets created.
103///
104/// By default it is [OnCreation::Nothing]
105#[derive(PartialEq, Clone, Copy, Default, Debug)]
106pub enum OnCreation {
107    /// Does nothing at all.
108    #[default]
109    Nothing,
110    /// Runs the animation.
111    Run,
112    /// Set the values to the end of the animation. As if it had actually run.
113    Finish,
114}
115
116/// What to do once the animation dependencies change.
117///
118/// Defaults to [OnChange::Reset].
119#[derive(PartialEq, Clone, Copy, Default, Debug)]
120pub enum OnChange {
121    /// Reset to the initial state.
122    #[default]
123    Reset,
124    /// Set the values to the end of the animation.
125    Finish,
126    /// Reruns the animation.
127    Rerun,
128    /// Does nothing at all.
129    Nothing,
130}
131
132pub trait ReadAnimatedValue: Clone + 'static {
133    type Output;
134    fn value(&self) -> Self::Output;
135}
136
137pub trait AnimatedValue: Clone + Default + 'static {
138    fn prepare(&mut self, direction: AnimDirection);
139
140    fn is_finished(&self, index: u128, direction: AnimDirection) -> bool;
141
142    fn advance(&mut self, index: u128, direction: AnimDirection);
143
144    fn finish(&mut self, direction: AnimDirection);
145
146    fn into_reversed(self) -> Self;
147}
148
149#[derive(Default, Clone, Copy, PartialEq, Eq)]
150pub enum Ease {
151    In,
152    #[default]
153    Out,
154    InOut,
155}
156
157/// Animate your elements. Use [`use_animation`] to use this.
158#[derive(Clone, PartialEq)]
159pub struct UseAnimation<Animated: AnimatedValue> {
160    pub(crate) animated_value: State<Animated>,
161    pub(crate) config: State<AnimConfiguration>,
162    pub(crate) is_running: State<bool>,
163    pub(crate) has_run_yet: State<bool>,
164    pub(crate) runs: State<usize>,
165    pub(crate) task: State<Option<TaskHandle>>,
166    pub(crate) last_direction: State<AnimDirection>,
167}
168impl<T: AnimatedValue> Copy for UseAnimation<T> {}
169
170impl<Animated: AnimatedValue> Deref for UseAnimation<Animated> {
171    type Target = State<Animated>;
172    fn deref(&self) -> &Self::Target {
173        &self.animated_value
174    }
175}
176
177impl<Animated: AnimatedValue> UseAnimation<Animated> {
178    /// Get the animated value.
179    pub fn get(&self) -> ReadRef<'_, Animated> {
180        self.animated_value.read()
181    }
182
183    /// Get the last configured direction used to animation.
184    pub fn direction(&self) -> ReadRef<'_, AnimDirection> {
185        self.last_direction.read()
186    }
187
188    /// Runs the animation normally.
189    pub fn start(&mut self) {
190        self.run(AnimDirection::Forward)
191    }
192
193    /// Runs the animation in reverse direction.
194    pub fn reverse(&mut self) {
195        self.run(AnimDirection::Reverse)
196    }
197
198    /// Reset the animation with the initial state.
199    pub fn reset(&mut self) {
200        if let Some(task) = self.task.write().take() {
201            task.cancel();
202        }
203
204        self.is_running.set_if_modified(false);
205
206        self.animated_value
207            .write()
208            .prepare(*self.last_direction.peek());
209
210        *self.has_run_yet.write() = true;
211    }
212
213    /// Finish the animation with the final state.
214    pub fn finish(&mut self) {
215        if let Some(task) = self.task.write().take() {
216            task.cancel();
217        }
218
219        self.is_running.set_if_modified(false);
220
221        self.animated_value
222            .write()
223            .finish(*self.last_direction.peek());
224
225        *self.has_run_yet.write() = true;
226    }
227
228    pub fn is_running(&self) -> State<bool> {
229        self.is_running
230    }
231
232    pub fn has_run_yet(&self) -> State<bool> {
233        self.has_run_yet
234    }
235
236    /// How many times the animation has been run.
237    pub fn runs(&self) -> State<usize> {
238        self.runs
239    }
240
241    /// Run the animation with a given [`AnimDirection`]
242    pub fn run(&self, mut direction: AnimDirection) {
243        let mut is_running = self.is_running;
244        let mut has_run_yet = self.has_run_yet;
245        let mut runs = self.runs;
246        let mut task = self.task;
247        let mut last_direction = self.last_direction;
248
249        let on_finish = self.config.peek().on_finish;
250        let mut animated_value = self.animated_value;
251
252        last_direction.set(direction);
253
254        // Cancel previous animations
255        if let Some(task) = task.write().take() {
256            task.cancel();
257        }
258
259        let ticker = RenderingTicker::get();
260        let platform = Platform::get().current_window();
261        let animation_clock = AnimationClock::get();
262
263        // Prepare the animations with the the proper direction
264        animated_value.write().prepare(direction);
265
266        has_run_yet.set_if_modified(true);
267        is_running.set_if_modified(true);
268        *runs.write() += 1;
269
270        let animation_task = spawn(async move {
271            platform.send(UserEvent::RequestRedraw);
272
273            let mut index = 0u128;
274            let mut prev_frame = Instant::now();
275
276            loop {
277                // Wait for the event loop to tick
278                ticker.tick().await;
279
280                let elapsed = animation_clock.correct_elapsed_duration(prev_frame.elapsed());
281
282                index += elapsed.as_millis();
283
284                let is_finished = {
285                    let mut animated_value = animated_value.write();
286                    let is_finished = animated_value.is_finished(index, direction);
287                    // Advance the animations
288                    animated_value.advance(index, direction);
289
290                    is_finished
291                };
292
293                if is_finished {
294                    let delay = match on_finish {
295                        OnFinish::Reverse { delay } => {
296                            // Toggle direction
297                            direction.toggle();
298                            delay
299                        }
300                        OnFinish::Restart { delay } => delay,
301                        OnFinish::Nothing => {
302                            // Stop if all the animations are finished
303                            break;
304                        }
305                    };
306
307                    if !delay.is_zero() {
308                        timer(delay).await;
309                    }
310
311                    index = 0;
312
313                    // Restart/reverse the animation
314                    animated_value.write().prepare(direction);
315                }
316
317                // Request another redraw to move the animation forward
318                platform.send(UserEvent::RequestRedraw);
319
320                prev_frame = Instant::now();
321            }
322
323            is_running.set(false);
324            task.write().take();
325        });
326
327        // Cancel previous animations
328        task.write().replace(animation_task);
329    }
330}
331/// Animate your UI easily.
332///
333/// [`use_animation`] takes a callback to initialize the animated values and related configuration.
334///
335/// To animate a group of values at once you can just return a tuple of them.
336///
337/// Currently supports animating:
338/// - Numeric values (e.g width): [AnimNum](crate::prelude::AnimNum)
339/// - Colors using [AnimColor](crate::prelude::AnimColor)
340/// - Sequential animations: [AnimSequential](crate::prelude::AnimSequential)
341/// - Anything as long as you implement the [AnimatedValue] trait.
342///
343/// For each animated value you will need to specify the duration, optionally an ease function or what type of easing you want.
344///
345/// # Example
346///
347/// Here is an example that animates a value from `0.0` to `100.0` in `50` milliseconds.
348///
349/// ```rust, no_run
350/// # use freya::prelude::*;
351/// # use freya::animation::*;
352/// fn app() -> impl IntoElement {
353///     let animation = use_animation(|conf| {
354///         conf.on_creation(OnCreation::Run);
355///         AnimNum::new(0., 100.).time(50)
356///     });
357///
358///     let width = animation.get().value();
359///
360///     rect()
361///         .width(Size::px(width))
362///         .height(Size::fill())
363///         .background(Color::BLUE)
364/// }
365/// ```
366///
367/// You are not limited to just one animation per call, you can have as many as you want.
368///
369/// ```rust, no_run
370/// # use freya::prelude::*;
371/// # use freya::animation::*;
372/// fn app() -> impl IntoElement {
373///     let animation = use_animation(|conf| {
374///         conf.on_creation(OnCreation::Run);
375///         (
376///             AnimNum::new(0., 100.).time(50),
377///             AnimColor::new(Color::RED, Color::BLUE).time(50),
378///         )
379///     });
380///
381///     let (width, color) = animation.get().value();
382///
383///     rect()
384///         .width(Size::px(width))
385///         .height(Size::fill())
386///         .background(color)
387/// }
388/// ```
389///
390/// You can also tweak what to do once the animation has finished with [`AnimConfiguration::on_finish`].
391///
392/// ```rust, no_run
393/// # use freya::prelude::*;
394/// # use freya::animation::*;
395/// fn app() -> impl IntoElement {
396///     let animation = use_animation(|conf| {
397///         conf.on_finish(OnFinish::restart());
398///         // ...
399///         # AnimNum::new(0., 1.)
400///     });
401///
402///     // ...
403///     # rect()
404/// }
405/// ```
406///
407/// You can subscribe your animation to reactive [state](freya_core::prelude::use_state) values, these are considered dependencies.
408///
409/// ```rust, no_run
410/// # use freya::prelude::*;
411/// # use freya::animation::*;
412/// fn app() -> impl IntoElement {
413///     let value = use_state(|| 100.);
414///
415///     let animation = use_animation(move |conf| {
416///         conf.on_change(OnChange::Rerun);
417///         AnimNum::new(0., value()).time(50)
418///     });
419///
420///     // ...
421///     # rect()
422/// }
423/// ```
424///
425/// You may also use [use_animation_with_dependencies] to pass non-reactive dependencies as well.
426pub fn use_animation<Animated: AnimatedValue>(
427    mut run: impl 'static + FnMut(&mut AnimConfiguration) -> Animated,
428) -> UseAnimation<Animated> {
429    use_hook(|| {
430        let mut config = State::create(AnimConfiguration::default());
431        let mut animated_value = State::create(Animated::default());
432        let is_running = State::create(false);
433        let has_run_yet = State::create(false);
434        let runs = State::create(0);
435        let task = State::create(None);
436        let last_direction = State::create(AnimDirection::Forward);
437
438        let mut animation = UseAnimation {
439            animated_value,
440            config,
441            is_running,
442            has_run_yet,
443            runs,
444            task,
445            last_direction,
446        };
447
448        Effect::create_sync_with_gen(move |current_gen| {
449            let mut anim_conf = AnimConfiguration::default();
450            animated_value.set(run(&mut anim_conf));
451            *config.write() = anim_conf;
452            match config.peek().on_change {
453                OnChange::Finish if current_gen > 0 => {
454                    animation.finish();
455                }
456                OnChange::Rerun if current_gen > 0 => {
457                    let last_direction = *animation.last_direction.peek();
458                    animation.run(last_direction);
459                }
460                OnChange::Reset if current_gen > 0 => {
461                    animation.reset();
462                }
463                _ => {}
464            }
465        });
466
467        match config.peek().on_creation {
468            OnCreation::Run => {
469                animation.run(AnimDirection::Forward);
470            }
471            OnCreation::Finish => {
472                animation.finish();
473            }
474            _ => {}
475        }
476
477        animation
478    })
479}
480
481/// Like [use_animation] but supports passing manual dependencies.
482///
483/// The callback reruns synchronously when the dependencies change. States read
484/// inside the callback do not rerun it, pass them as dependencies instead.
485///
486/// ```rust, no_run
487/// # use freya::prelude::*;
488/// # use freya::animation::*;
489/// fn app() -> impl IntoElement {
490///     # let other_value = 1.;
491///     let animation = use_animation_with_dependencies(&other_value, |conf, other_value| {
492///         conf.on_change(OnChange::Rerun);
493///         AnimNum::new(0., *other_value).time(50)
494///     });
495///
496///     // ...
497///     # rect()
498/// }
499/// ```
500pub fn use_animation_with_dependencies<Animated: AnimatedValue, D: 'static + Clone + PartialEq>(
501    dependencies: &D,
502    mut run: impl 'static + FnMut(&mut AnimConfiguration, &D) -> Animated,
503) -> UseAnimation<Animated> {
504    let mut last_dependencies = use_state(|| None::<D>);
505
506    let mut animation = use_hook(|| UseAnimation {
507        animated_value: State::create(Animated::default()),
508        config: State::create(AnimConfiguration::default()),
509        is_running: State::create(false),
510        has_run_yet: State::create(false),
511        runs: State::create(0),
512        task: State::create(None),
513        last_direction: State::create(AnimDirection::Forward),
514    });
515
516    // Dependency changes are handled synchronously so the updated animation values
517    // are ready in this same render, before the frame is painted
518    if last_dependencies.peek().as_ref() != Some(dependencies) {
519        let is_creation = last_dependencies.peek().is_none();
520        last_dependencies.set(Some(dependencies.clone()));
521
522        let mut anim_conf = AnimConfiguration::default();
523        animation
524            .animated_value
525            .set(run(&mut anim_conf, dependencies));
526        *animation.config.write() = anim_conf;
527
528        if is_creation {
529            let on_creation = animation.config.peek().on_creation;
530            match on_creation {
531                OnCreation::Run => animation.run(AnimDirection::Forward),
532                OnCreation::Finish => animation.finish(),
533                _ => {}
534            }
535        } else {
536            let on_change = animation.config.peek().on_change;
537            match on_change {
538                OnChange::Finish => animation.finish(),
539                OnChange::Rerun => {
540                    let last_direction = *animation.last_direction.peek();
541                    animation.run(last_direction);
542                }
543                OnChange::Reset => animation.reset(),
544                _ => {}
545            }
546        }
547    }
548
549    animation
550}
551
552macro_rules! impl_tuple_call {
553    ($(($($type:ident),*)),*) => {
554        $(
555            impl<$($type,)*> AnimatedValue for ($($type,)*)
556            where
557                $($type: AnimatedValue,)*
558            {
559                fn prepare(&mut self, direction: AnimDirection) {
560                    #[allow(non_snake_case)]
561                    let ($($type,)*) = self;
562                    $(
563                        $type.prepare(direction);
564                    )*
565                }
566
567                fn is_finished(&self, index: u128, direction: AnimDirection) -> bool {
568                    #[allow(non_snake_case)]
569                    let ($($type,)*) = self;
570                    $(
571                        if !$type.is_finished(index, direction) {
572                            return false;
573                        }
574                    )*
575                    true
576                }
577
578                fn advance(&mut self, index: u128, direction: AnimDirection) {
579                    #[allow(non_snake_case)]
580                    let ($($type,)*) = self;
581                    $(
582                        $type.advance(index, direction);
583                    )*
584                }
585
586                fn finish(&mut self, direction: AnimDirection) {
587                    #[allow(non_snake_case)]
588                    let ($($type,)*) = self;
589                    $(
590                        $type.finish(direction);
591                    )*
592                }
593
594               fn into_reversed(self) -> Self {
595                    #[allow(non_snake_case)]
596                    let ($($type,)*) = self;
597                    (
598                        $(
599                            $type.into_reversed(),
600                        )*
601                    )
602                }
603            }
604            impl<$($type,)*> ReadAnimatedValue for  ($($type,)*)
605            where
606                $($type: ReadAnimatedValue,)*
607            {
608                type Output = (
609                    $(
610                        <$type as ReadAnimatedValue>::Output,
611                    )*
612                );
613                fn value(&self) -> Self::Output {
614                    #[allow(non_snake_case)]
615                    let ($($type,)*) = self;
616                    (
617                        $(
618                            $type.value(),
619                        )*
620                    )
621                }
622            }
623        )*
624    };
625}
626
627impl_tuple_call!(
628    (T1),
629    (T1, T2),
630    (T1, T2, T3),
631    (T1, T2, T3, T4),
632    (T1, T2, T3, T4, T5),
633    (T1, T2, T3, T4, T5, T6),
634    (T1, T2, T3, T4, T5, T6, T7),
635    (T1, T2, T3, T4, T5, T6, T7, T8),
636    (T1, T2, T3, T4, T5, T6, T7, T8, T9),
637    (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10),
638    (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11),
639    (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)
640);
641
642/// Create a transition animation that animates from the previous value to the current value.
643///
644/// This hook tracks the previous and current values of a reactive value and creates
645/// an animation that transitions between them when the value changes.
646///
647/// # Example
648///
649/// ```rust, no_run
650/// # use freya::prelude::*;
651/// # use freya::animation::*;
652/// fn app() -> impl IntoElement {
653///     let color = use_state(|| Color::RED);
654///     let animation =
655///         use_animation_transition(color, |from: Color, to| AnimColor::new(from, to).time(500));
656///
657///     rect()
658///         .background(&*animation.read())
659///         .width(Size::px(100.))
660///         .height(Size::px(100.))
661/// }
662/// ```
663pub fn use_animation_transition<Animated: AnimatedValue, T: Clone + PartialEq + 'static>(
664    value: impl IntoReadable<T>,
665    mut run: impl 'static + FnMut(T, T) -> Animated,
666) -> UseAnimation<Animated> {
667    let values = use_previous_and_current(value);
668    use_animation(move |conf| {
669        conf.on_change(OnChange::Rerun);
670        conf.on_creation(OnCreation::Run);
671        let (from, to) = values.read().clone();
672        run(from, to)
673    })
674}