freya-animation 0.4.0-rc.13

Animation APIs for Freya
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
use std::{
    ops::Deref,
    time::{
        Duration,
        Instant,
    },
};

use async_io::Timer;
use freya_core::prelude::*;

#[derive(Default, PartialEq, Clone, Debug)]
pub struct AnimConfiguration {
    on_finish: OnFinish,
    on_creation: OnCreation,
    on_change: OnChange,
}

impl AnimConfiguration {
    pub fn on_finish(&mut self, on_finish: OnFinish) -> &mut Self {
        self.on_finish = on_finish;
        self
    }

    pub fn on_creation(&mut self, on_creation: OnCreation) -> &mut Self {
        self.on_creation = on_creation;
        self
    }

    pub fn on_change(&mut self, on_change: OnChange) -> &mut Self {
        self.on_change = on_change;
        self
    }
}

/// Controls the direction of the animation.
#[derive(Clone, Copy, PartialEq)]
pub enum AnimDirection {
    Forward,
    Reverse,
}

impl AnimDirection {
    pub fn toggle(&mut self) {
        match self {
            Self::Forward => *self = Self::Reverse,
            Self::Reverse => *self = Self::Forward,
        }
    }
}

/// What to do once the animation finishes.
///
/// By default it is [OnFinish::Nothing].
#[derive(PartialEq, Clone, Copy, Default, Debug)]
pub enum OnFinish {
    /// Does nothing at all.
    #[default]
    Nothing,
    /// Runs the animation in reverse direction.
    Reverse {
        /// Delay before reversing.
        delay: Duration,
    },
    /// Runs the animation in the same direction again.
    Restart {
        /// Delay before restarting.
        delay: Duration,
    },
}

impl OnFinish {
    /// Creates a new [OnFinish::Nothing] variant.
    pub fn nothing() -> Self {
        Self::Nothing
    }

    /// Creates a new [OnFinish::Reverse] variant with no delay.
    pub fn reverse() -> Self {
        Self::Reverse {
            delay: Duration::ZERO,
        }
    }

    /// Creates a new [OnFinish::Reverse] variant with a delay.
    pub fn reverse_with_delay(delay: Duration) -> Self {
        Self::Reverse { delay }
    }

    /// Creates a new [OnFinish::Restart] variant with no delay.
    pub fn restart() -> Self {
        Self::Restart {
            delay: Duration::ZERO,
        }
    }

    /// Creates a new [OnFinish::Restart] variant with a delay.
    pub fn restart_with_delay(delay: Duration) -> Self {
        Self::Restart { delay }
    }
}

/// What to do once the animation gets created.
///
/// By default it is [OnCreation::Nothing]
#[derive(PartialEq, Clone, Copy, Default, Debug)]
pub enum OnCreation {
    /// Does nothing at all.
    #[default]
    Nothing,
    /// Runs the animation.
    Run,
    /// Set the values to the end of the animation. As if it had actually run.
    Finish,
}

/// What to do once the animation dependencies change.
///
/// Defaults to [OnChange::Reset].
#[derive(PartialEq, Clone, Copy, Default, Debug)]
pub enum OnChange {
    /// Reset to the initial state.
    #[default]
    Reset,
    /// Set the values to the end of the animation.
    Finish,
    /// Reruns the animation.
    Rerun,
    /// Does nothing at all.
    Nothing,
}

pub trait ReadAnimatedValue: Clone + 'static {
    type Output;
    fn value(&self) -> Self::Output;
}

pub trait AnimatedValue: Clone + Default + 'static {
    fn prepare(&mut self, direction: AnimDirection);

    fn is_finished(&self, index: u128, direction: AnimDirection) -> bool;

    fn advance(&mut self, index: u128, direction: AnimDirection);

    fn finish(&mut self, direction: AnimDirection);

    fn into_reversed(self) -> Self;
}

#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub enum Ease {
    In,
    #[default]
    Out,
    InOut,
}

/// Animate your elements. Use [`use_animation`] to use this.
#[derive(Clone, PartialEq)]
pub struct UseAnimation<Animated: AnimatedValue> {
    pub(crate) animated_value: State<Animated>,
    pub(crate) config: State<AnimConfiguration>,
    pub(crate) is_running: State<bool>,
    pub(crate) has_run_yet: State<bool>,
    pub(crate) task: State<Option<TaskHandle>>,
    pub(crate) last_direction: State<AnimDirection>,
}
impl<T: AnimatedValue> Copy for UseAnimation<T> {}

impl<Animated: AnimatedValue> Deref for UseAnimation<Animated> {
    type Target = State<Animated>;
    fn deref(&self) -> &Self::Target {
        &self.animated_value
    }
}

impl<Animated: AnimatedValue> UseAnimation<Animated> {
    /// Get the animated value.
    pub fn get(&self) -> ReadRef<'static, Animated> {
        self.animated_value.read()
    }

    /// Get the last configured direction used to animation.
    pub fn direction(&self) -> ReadRef<'static, AnimDirection> {
        self.last_direction.read()
    }

    /// Runs the animation normally.
    pub fn start(&mut self) {
        self.run(AnimDirection::Forward)
    }

    /// Runs the animation in reverse direction.
    pub fn reverse(&mut self) {
        self.run(AnimDirection::Reverse)
    }

    /// Reset the animation with the initial state.
    pub fn reset(&mut self) {
        if let Some(task) = self.task.write().take() {
            task.cancel();
        }

        self.animated_value
            .write()
            .prepare(*self.last_direction.peek());

        *self.has_run_yet.write() = true;
    }

    /// Finish the animation with the final state.
    pub fn finish(&mut self) {
        if let Some(task) = self.task.write().take() {
            task.cancel();
        }

        self.animated_value
            .write()
            .finish(*self.last_direction.peek());

        *self.has_run_yet.write() = true;
    }

    pub fn is_running(&self) -> State<bool> {
        self.is_running
    }

    pub fn has_run_yet(&self) -> State<bool> {
        self.has_run_yet
    }

    /// Run the animation with a given [`AnimDirection`]
    pub fn run(&self, mut direction: AnimDirection) {
        let mut is_running = self.is_running;
        let mut has_run_yet = self.has_run_yet;
        let mut task = self.task;
        let mut last_direction = self.last_direction;

        let on_finish = self.config.peek().on_finish;
        let mut animated_value = self.animated_value;

        last_direction.set(direction);

        // Cancel previous animations
        if let Some(task) = task.write().take() {
            task.cancel();
        }

        let peek_has_run_yet = *self.has_run_yet.peek();

        let mut ticker = RenderingTicker::get();
        let platform = Platform::get();
        let animation_clock = AnimationClock::get();

        // Prepare the animations with the the proper direction
        animated_value.write().prepare(direction);

        let animation_task = spawn(async move {
            platform.send(UserEvent::RequestRedraw);

            let mut index = 0u128;
            let mut prev_frame = Instant::now();

            if !peek_has_run_yet {
                *has_run_yet.write() = true;
            }
            is_running.set(true);

            loop {
                // Wait for the event loop to tick
                ticker.tick().await;

                // Request another redraw to move the animation forward
                platform.send(UserEvent::RequestRedraw);

                let elapsed = animation_clock.correct_elapsed_duration(prev_frame.elapsed());

                index += elapsed.as_millis();

                let is_finished = {
                    let mut animated_value = animated_value.write();
                    let is_finished = animated_value.is_finished(index, direction);
                    // Advance the animations
                    animated_value.advance(index, direction);

                    is_finished
                };

                if is_finished {
                    let delay = match on_finish {
                        OnFinish::Reverse { delay } => {
                            // Toggle direction
                            direction.toggle();
                            delay
                        }
                        OnFinish::Restart { delay } => delay,
                        OnFinish::Nothing => {
                            // Stop if all the animations are finished
                            break;
                        }
                    };

                    if !delay.is_zero() {
                        Timer::after(delay).await;
                    }

                    index = 0;

                    // Restart/reverse the animation
                    animated_value.write().prepare(direction);
                }

                prev_frame = Instant::now();
            }

            is_running.set(false);
            task.write().take();
        });

        // Cancel previous animations
        task.write().replace(animation_task);
    }
}
/// Animate your UI easily.
///
/// [`use_animation`] takes a callback to initialize the animated values and related configuration.
///
/// To animate a group of values at once you can just return a tuple of them.
///
/// Currently supports animating:
/// - Numeric values (e.g width): [AnimNum](crate::prelude::AnimNum)
/// - Colors using [AnimColor](crate::prelude::AnimColor)
/// - Sequential animations: [AnimSequential](crate::prelude::AnimSequential)
/// - Anything as long as you implement the [AnimatedValue] trait.
///
/// For each animated value you will need to specify the duration, optionally an ease function or what type of easing you want.
///
/// # Example
///
/// Here is an example that animates a value from `0.0` to `100.0` in `50` milliseconds.
///
/// ```rust, no_run
/// # use freya::prelude::*;
/// # use freya::animation::*;
/// fn app() -> impl IntoElement {
///     let animation = use_animation(|conf| {
///         conf.on_creation(OnCreation::Run);
///         AnimNum::new(0., 100.).time(50)
///     });
///
///     let width = animation.get().value();
///
///     rect()
///         .width(Size::px(width))
///         .height(Size::fill())
///         .background(Color::BLUE)
/// }
/// ```
///
/// You are not limited to just one animation per call, you can have as many as you want.
///
/// ```rust, no_run
/// # use freya::prelude::*;
/// # use freya::animation::*;
/// fn app() -> impl IntoElement {
///     let animation = use_animation(|conf| {
///         conf.on_creation(OnCreation::Run);
///         (
///             AnimNum::new(0., 100.).time(50),
///             AnimColor::new(Color::RED, Color::BLUE).time(50),
///         )
///     });
///
///     let (width, color) = animation.get().value();
///
///     rect()
///         .width(Size::px(width))
///         .height(Size::fill())
///         .background(color)
/// }
/// ```
///
/// You can also tweak what to do once the animation has finished with [`AnimConfiguration::on_finish`].
///
/// ```rust, no_run
/// # use freya::prelude::*;
/// # use freya::animation::*;
/// fn app() -> impl IntoElement {
///     let animation = use_animation(|conf| {
///         conf.on_finish(OnFinish::restart());
///         // ...
///         # AnimNum::new(0., 1.)
///     });
///
///     // ...
///     # rect()
/// }
/// ```
///
/// You can subscribe your animation to reactive [state](freya_core::prelude::use_state) values, these are considered dependencies.
///
/// ```rust, no_run
/// # use freya::prelude::*;
/// # use freya::animation::*;
/// fn app() -> impl IntoElement {
///     let value = use_state(|| 100.);
///
///     let animation = use_animation(move |conf| {
///         conf.on_change(OnChange::Rerun);
///         AnimNum::new(0., value()).time(50)
///     });
///
///     // ...
///     # rect()
/// }
/// ```
///
/// You may also use [use_animation_with_dependencies] to pass non-reactive dependencies as well.
pub fn use_animation<Animated: AnimatedValue>(
    mut run: impl 'static + FnMut(&mut AnimConfiguration) -> Animated,
) -> UseAnimation<Animated> {
    use_hook(|| {
        let mut config = State::create(AnimConfiguration::default());
        let mut animated_value = State::create(Animated::default());
        let is_running = State::create(false);
        let has_run_yet = State::create(false);
        let task = State::create(None);
        let last_direction = State::create(AnimDirection::Forward);

        let mut animation = UseAnimation {
            animated_value,
            config,
            is_running,
            has_run_yet,
            task,
            last_direction,
        };

        Effect::create_sync_with_gen(move |current_gen| {
            let mut anim_conf = AnimConfiguration::default();
            animated_value.set(run(&mut anim_conf));
            *config.write() = anim_conf;
            match config.peek().on_change {
                OnChange::Finish if current_gen > 0 => {
                    animation.finish();
                }
                OnChange::Rerun if current_gen > 0 => {
                    let last_direction = *animation.last_direction.peek();
                    animation.run(last_direction);
                }
                OnChange::Reset if current_gen > 0 => {
                    animation.reset();
                }
                _ => {}
            }
        });

        match config.peek().on_creation {
            OnCreation::Run => {
                animation.run(AnimDirection::Forward);
            }
            OnCreation::Finish => {
                animation.finish();
            }
            _ => {}
        }

        animation
    })
}

/// Like [use_animation] but supports passing manual dependencies.
///
/// ```rust, no_run
/// # use freya::prelude::*;
/// # use freya::animation::*;
/// fn app() -> impl IntoElement {
///     # let other_value = 1.;
///     let animation = use_animation_with_dependencies(&other_value, |conf, other_value| {
///         conf.on_change(OnChange::Rerun);
///         AnimNum::new(0., *other_value).time(50)
///     });
///
///     // ...
///     # rect()
/// }
/// ```
pub fn use_animation_with_dependencies<Animated: AnimatedValue, D: 'static + Clone + PartialEq>(
    dependencies: &D,
    mut run: impl 'static + FnMut(&mut AnimConfiguration, &D) -> Animated,
) -> UseAnimation<Animated> {
    let dependencies = use_reactive(dependencies);
    use_hook(|| {
        let mut config = State::create(AnimConfiguration::default());
        let mut animated_value = State::create(Animated::default());
        let is_running = State::create(false);
        let has_run_yet = State::create(false);
        let task = State::create(None);
        let last_direction = State::create(AnimDirection::Forward);

        let mut animation = UseAnimation {
            animated_value,
            config,
            is_running,
            has_run_yet,
            task,
            last_direction,
        };

        Effect::create_sync_with_gen(move |current_gen| {
            let dependencies = dependencies.read();
            let mut anim_conf = AnimConfiguration::default();
            animated_value.set(run(&mut anim_conf, &dependencies));
            *config.write() = anim_conf;

            match config.peek().on_change {
                OnChange::Finish if current_gen > 0 => {
                    animation.finish();
                }
                OnChange::Rerun if current_gen > 0 => {
                    let last_direction = *animation.last_direction.peek();
                    animation.run(last_direction);
                }
                OnChange::Reset if current_gen > 0 => {
                    animation.reset();
                }
                _ => {}
            }
        });

        match config.peek().on_creation {
            OnCreation::Run => {
                animation.run(AnimDirection::Forward);
            }
            OnCreation::Finish => {
                animation.finish();
            }
            _ => {}
        }

        animation
    })
}

macro_rules! impl_tuple_call {
    ($(($($type:ident),*)),*) => {
        $(
            impl<$($type,)*> AnimatedValue for ($($type,)*)
            where
                $($type: AnimatedValue,)*
            {
                fn prepare(&mut self, direction: AnimDirection) {
                    #[allow(non_snake_case)]
                    let ($($type,)*) = self;
                    $(
                        $type.prepare(direction);
                    )*
                }

                fn is_finished(&self, index: u128, direction: AnimDirection) -> bool {
                    #[allow(non_snake_case)]
                    let ($($type,)*) = self;
                    $(
                        if !$type.is_finished(index, direction) {
                            return false;
                        }
                    )*
                    true
                }

                fn advance(&mut self, index: u128, direction: AnimDirection) {
                    #[allow(non_snake_case)]
                    let ($($type,)*) = self;
                    $(
                        $type.advance(index, direction);
                    )*
                }

                fn finish(&mut self, direction: AnimDirection) {
                    #[allow(non_snake_case)]
                    let ($($type,)*) = self;
                    $(
                        $type.finish(direction);
                    )*
                }

               fn into_reversed(self) -> Self {
                    #[allow(non_snake_case)]
                    let ($($type,)*) = self;
                    (
                        $(
                            $type.into_reversed(),
                        )*
                    )
                }
            }
            impl<$($type,)*> ReadAnimatedValue for  ($($type,)*)
            where
                $($type: ReadAnimatedValue,)*
            {
                type Output = (
                    $(
                        <$type as ReadAnimatedValue>::Output,
                    )*
                );
                fn value(&self) -> Self::Output {
                    #[allow(non_snake_case)]
                    let ($($type,)*) = self;
                    (
                        $(
                            $type.value(),
                        )*
                    )
                }
            }
        )*
    };
}

impl_tuple_call!(
    (T1),
    (T1, T2),
    (T1, T2, T3),
    (T1, T2, T3, T4),
    (T1, T2, T3, T4, T5),
    (T1, T2, T3, T4, T5, T6),
    (T1, T2, T3, T4, T5, T6, T7),
    (T1, T2, T3, T4, T5, T6, T7, T8),
    (T1, T2, T3, T4, T5, T6, T7, T8, T9),
    (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10),
    (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11),
    (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)
);

/// Create a transition animation that animates from the previous value to the current value.
///
/// This hook tracks the previous and current values of a reactive value and creates
/// an animation that transitions between them when the value changes.
///
/// # Example
///
/// ```rust, no_run
/// # use freya::prelude::*;
/// # use freya::animation::*;
/// fn app() -> impl IntoElement {
///     let color = use_state(|| Color::RED);
///     let animation =
///         use_animation_transition(color, |from: Color, to| AnimColor::new(from, to).time(500));
///
///     rect()
///         .background(&*animation.read())
///         .width(Size::px(100.))
///         .height(Size::px(100.))
/// }
/// ```
pub fn use_animation_transition<Animated: AnimatedValue, T: Clone + PartialEq + 'static>(
    value: impl IntoReadable<T>,
    mut run: impl 'static + FnMut(T, T) -> Animated,
) -> UseAnimation<Animated> {
    let values = use_previous_and_current(value);
    use_animation(move |conf| {
        conf.on_change(OnChange::Rerun);
        conf.on_creation(OnCreation::Run);
        let (from, to) = values.read().clone();
        run(from, to)
    })
}