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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use std::time::Duration;

use dioxus_core::prelude::{
    spawn,
    use_hook,
    Task,
};
use dioxus_hooks::{
    use_memo,
    use_reactive,
    use_signal,
    Dependency,
};
use dioxus_signals::{
    Memo,
    ReadOnlySignal,
    Readable,
    Signal,
    Writable,
};
use easer::functions::*;
use freya_engine::prelude::Color;
use freya_node_state::Parse;
use tokio::time::Instant;

use crate::{
    use_platform,
    UsePlatform,
};

pub fn apply_value(
    origin: f32,
    destination: f32,
    index: i32,
    time: Duration,
    ease: Ease,
    function: Function,
) -> f32 {
    let (t, b, c, d) = (
        index as f32,
        origin,
        destination - origin,
        time.as_millis() as f32,
    );
    match function {
        Function::Back => match ease {
            Ease::In => Back::ease_in(t, b, c, d),
            Ease::InOut => Back::ease_in_out(t, b, c, d),
            Ease::Out => Back::ease_out(t, b, c, d),
        },
        Function::Bounce => match ease {
            Ease::In => Bounce::ease_in(t, b, c, d),
            Ease::InOut => Bounce::ease_in_out(t, b, c, d),
            Ease::Out => Bounce::ease_out(t, b, c, d),
        },
        Function::Circ => match ease {
            Ease::In => Circ::ease_in(t, b, c, d),
            Ease::InOut => Circ::ease_in_out(t, b, c, d),
            Ease::Out => Circ::ease_out(t, b, c, d),
        },
        Function::Cubic => match ease {
            Ease::In => Cubic::ease_in(t, b, c, d),
            Ease::InOut => Cubic::ease_in_out(t, b, c, d),
            Ease::Out => Cubic::ease_out(t, b, c, d),
        },
        Function::Elastic => match ease {
            Ease::In => Elastic::ease_in(t, b, c, d),
            Ease::InOut => Elastic::ease_in_out(t, b, c, d),
            Ease::Out => Elastic::ease_out(t, b, c, d),
        },
        Function::Expo => match ease {
            Ease::In => Expo::ease_in(t, b, c, d),
            Ease::InOut => Expo::ease_in_out(t, b, c, d),
            Ease::Out => Expo::ease_out(t, b, c, d),
        },
        Function::Linear => match ease {
            Ease::In => Linear::ease_in(t, b, c, d),
            Ease::InOut => Linear::ease_in_out(t, b, c, d),
            Ease::Out => Linear::ease_out(t, b, c, d),
        },
        Function::Quad => match ease {
            Ease::In => Quad::ease_in(t, b, c, d),
            Ease::InOut => Quad::ease_in_out(t, b, c, d),
            Ease::Out => Quad::ease_out(t, b, c, d),
        },
        Function::Quart => match ease {
            Ease::In => Quart::ease_in(t, b, c, d),
            Ease::InOut => Quart::ease_in_out(t, b, c, d),
            Ease::Out => Quart::ease_out(t, b, c, d),
        },
        Function::Sine => match ease {
            Ease::In => Sine::ease_in(t, b, c, d),
            Ease::InOut => Sine::ease_in_out(t, b, c, d),
            Ease::Out => Sine::ease_out(t, b, c, d),
        },
    }
}

#[derive(Default, Clone, Copy)]
pub enum Function {
    Back,
    Bounce,
    Circ,
    Cubic,
    Elastic,
    Expo,
    #[default]
    Linear,
    Quad,
    Quart,
    Sine,
}

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

/// Animate a color.
pub struct AnimColor {
    origin: Color,
    destination: Color,
    time: Duration,
    ease: Ease,
    function: Function,

    value: Color,
}

impl AnimColor {
    pub fn new(origin: &str, destination: &str) -> Self {
        Self {
            origin: Color::parse(origin).unwrap(),
            destination: Color::parse(destination).unwrap(),
            time: Duration::default(),
            ease: Ease::default(),
            function: Function::default(),

            value: Color::parse(origin).unwrap(),
        }
    }

    /// Set the animation duration using milliseconds. Use `Self::duration` if you want to specify the duration in another form.
    pub fn time(mut self, time: u64) -> Self {
        self.time = Duration::from_millis(time);
        self
    }

    /// Set the animation duration using milliseconds.
    pub fn duration(mut self, duration: Duration) -> Self {
        self.time = duration;
        self
    }

    /// Set the easing type. See `Ease` for all the types.
    pub fn ease(mut self, ease: Ease) -> Self {
        self.ease = ease;
        self
    }

    /// Set the easing function. See `Function` for all the types.
    pub fn function(mut self, function: Function) -> Self {
        self.function = function;
        self
    }
}

impl AnimatedValue for AnimColor {
    fn time(&self) -> Duration {
        self.time
    }

    fn as_f32(&self) -> f32 {
        panic!("This is not a f32.")
    }

    fn as_string(&self) -> String {
        format!(
            "rgb({}, {}, {}, {})",
            self.value.r(),
            self.value.g(),
            self.value.b(),
            self.value.a()
        )
    }

    fn prepare(&mut self, direction: AnimDirection) {
        match direction {
            AnimDirection::Forward => self.value = self.origin,
            AnimDirection::Reverse => {
                self.value = self.destination;
            }
        }
    }

    fn is_finished(&self, index: i32, direction: AnimDirection) -> bool {
        match direction {
            AnimDirection::Forward => {
                index > self.time.as_millis() as i32
                    && self.value.r() == self.destination.r()
                    && self.value.g() == self.destination.g()
                    && self.value.b() == self.destination.b()
                    && self.value.a() == self.destination.a()
            }
            AnimDirection::Reverse => {
                index > self.time.as_millis() as i32
                    && self.value.r() == self.origin.r()
                    && self.value.g() == self.origin.g()
                    && self.value.b() == self.origin.b()
                    && self.value.a() == self.origin.a()
            }
        }
    }

    fn advance(&mut self, index: i32, direction: AnimDirection) {
        if !self.is_finished(index, direction) {
            let (origin, destination) = match direction {
                AnimDirection::Forward => (self.origin, self.destination),
                AnimDirection::Reverse => (self.destination, self.origin),
            };
            let r = apply_value(
                origin.r() as f32,
                destination.r() as f32,
                index.min(self.time.as_millis() as i32),
                self.time,
                self.ease,
                self.function,
            );
            let g = apply_value(
                origin.g() as f32,
                destination.g() as f32,
                index.min(self.time.as_millis() as i32),
                self.time,
                self.ease,
                self.function,
            );
            let b = apply_value(
                origin.b() as f32,
                destination.b() as f32,
                index.min(self.time.as_millis() as i32),
                self.time,
                self.ease,
                self.function,
            );
            let a = apply_value(
                origin.a() as f32,
                destination.a() as f32,
                index.min(self.time.as_millis() as i32),
                self.time,
                self.ease,
                self.function,
            );
            self.value = Color::from_argb(a as u8, r as u8, g as u8, b as u8);
        }
    }
}

/// Animate a numeric value.
pub struct AnimNum {
    origin: f32,
    destination: f32,
    time: Duration,
    ease: Ease,
    function: Function,

    value: f32,
}

impl AnimNum {
    pub fn new(origin: f32, destination: f32) -> Self {
        Self {
            origin,
            destination,
            time: Duration::default(),
            ease: Ease::default(),
            function: Function::default(),

            value: origin,
        }
    }

    /// Set the animation duration using milliseconds. Use `Self::duration` if you want to specify the duration in another form.
    pub fn time(mut self, time: u64) -> Self {
        self.time = Duration::from_millis(time);
        self
    }

    /// Set the animation duration using milliseconds.
    pub fn duration(mut self, duration: Duration) -> Self {
        self.time = duration;
        self
    }

    /// Set the easing type. See `Ease` for all the types.
    pub fn ease(mut self, ease: Ease) -> Self {
        self.ease = ease;
        self
    }

    /// Set the easing function. See `Function` for all the types.
    pub fn function(mut self, function: Function) -> Self {
        self.function = function;
        self
    }
}

impl AnimatedValue for AnimNum {
    fn time(&self) -> Duration {
        self.time
    }

    fn as_f32(&self) -> f32 {
        self.value
    }

    fn as_string(&self) -> String {
        panic!("This is not a String");
    }

    fn prepare(&mut self, direction: AnimDirection) {
        match direction {
            AnimDirection::Forward => self.value = self.origin,
            AnimDirection::Reverse => {
                self.value = self.destination;
            }
        }
    }

    fn is_finished(&self, index: i32, direction: AnimDirection) -> bool {
        match direction {
            AnimDirection::Forward => {
                index > self.time.as_millis() as i32 && self.value >= self.destination
            }
            AnimDirection::Reverse => {
                index > self.time.as_millis() as i32 && self.value <= self.origin
            }
        }
    }

    fn advance(&mut self, index: i32, direction: AnimDirection) {
        if !self.is_finished(index, direction) {
            let (origin, destination) = match direction {
                AnimDirection::Forward => (self.origin, self.destination),
                AnimDirection::Reverse => (self.destination, self.origin),
            };
            self.value = apply_value(
                origin,
                destination,
                index.min(self.time.as_millis() as i32),
                self.time,
                self.ease,
                self.function,
            )
        }
    }
}

pub trait AnimatedValue {
    fn time(&self) -> Duration;

    fn as_f32(&self) -> f32;

    fn as_string(&self) -> String;

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

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

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

pub type ReadAnimatedValue = ReadOnlySignal<Box<dyn AnimatedValue>>;

#[derive(Default, PartialEq, Clone)]
pub struct AnimationContext {
    animated_values: Vec<Signal<Box<dyn AnimatedValue>>>,
    on_finish: OnFinish,
    auto_start: bool,
}

impl AnimationContext {
    pub fn with(&mut self, animated_value: impl AnimatedValue + 'static) -> ReadAnimatedValue {
        let val: Box<dyn AnimatedValue> = Box::new(animated_value);
        let signal = Signal::new(val);
        self.animated_values.push(signal);
        ReadOnlySignal::new(signal)
    }

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

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

/// Controls the direction of the animation.
#[derive(Clone, Copy)]
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 [`Stop`](OnFinish::Stop)
#[derive(PartialEq, Clone, Copy, Default)]
pub enum OnFinish {
    #[default]
    Stop,
    Reverse,
    Restart,
}

/// Animate your elements. Use [`use_animation`] to use this.
#[derive(PartialEq, Clone)]
pub struct UseAnimator<Animated: PartialEq + Clone + 'static> {
    pub(crate) value_and_ctx: Memo<(Animated, AnimationContext)>,
    pub(crate) platform: UsePlatform,
    pub(crate) is_running: Signal<bool>,
    pub(crate) has_run_yet: Signal<bool>,
    pub(crate) task: Signal<Option<Task>>,
}

impl<T: PartialEq + Clone + 'static> Copy for UseAnimator<T> {}

impl<Animated: PartialEq + Clone + 'static> UseAnimator<Animated> {
    /// Get the animated value.
    pub fn get(&self) -> Animated {
        self.value_and_ctx.read().0.clone()
    }

    /// Reset the animation to the default state.
    pub fn reset(&self) {
        let mut task = self.task;

        if let Some(task) = task.write().take() {
            task.cancel();
        }

        for value in &self.value_and_ctx.read().1.animated_values {
            let mut value = *value;
            value.write().prepare(AnimDirection::Forward);
        }
    }

    /// Checks if there is any animation running.
    pub fn is_running(&self) -> bool {
        *self.is_running.read()
    }

    /// Checks if it has run yet, by subscribing.
    pub fn has_run_yet(&self) -> bool {
        *self.has_run_yet.read()
    }

    /// Checks if it has run yet, doesn't subscribe. Useful for when you just mounted your component.
    pub fn peek_has_run_yet(&self) -> bool {
        *self.has_run_yet.peek()
    }

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

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

    /// Run the animation with a given [`AnimDirection`]
    pub fn run(&self, mut direction: AnimDirection) {
        let ctx = &self.value_and_ctx.peek().1;
        let platform = self.platform;
        let mut is_running = self.is_running;
        let mut ticker = platform.new_ticker();
        let mut values = ctx.animated_values.clone();
        let mut has_run_yet = self.has_run_yet;
        let on_finish = ctx.on_finish;
        let mut task = self.task;

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

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

        let animation_task = spawn(async move {
            platform.request_animation_frame();

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

            // Prepare the animations with the the proper direction
            for value in values.iter_mut() {
                value.write().prepare(direction);
            }

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

                index += prev_frame.elapsed().as_millis() as i32;

                let is_finished = values
                    .iter()
                    .all(|value| value.peek().is_finished(index, direction));

                // Advance the animations
                for value in values.iter_mut() {
                    value.write().advance(index, direction);
                }

                prev_frame = Instant::now();

                if is_finished {
                    if OnFinish::Reverse == on_finish {
                        // Toggle direction
                        direction.toggle();
                    }
                    match on_finish {
                        OnFinish::Restart | OnFinish::Reverse => {
                            index = 0;

                            // Restart the animation
                            for value in values.iter_mut() {
                                value.write().prepare(direction);
                            }
                        }
                        OnFinish::Stop => {
                            // Stop if all the animations are finished
                            break;
                        }
                    }
                }
            }

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

        // Cancel previous animations
        task.write().replace(animation_task);
    }
}

/// Animate your elements easily.
///
/// [`use_animation`] takes an 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, padding, rotation, offsets) or also colors, you need specify the duration,
/// and optionally an ease function or what type of easing you want as well.
///
/// # Example
///
/// Here is an example that animates a value from `0.0` to `100.0` in `50` milliseconds.
///
/// ```rust, no_run
/// # use freya::prelude::*;
/// fn main() {
///     launch(app);
/// }
///
/// fn app() -> Element {
///     let animation = use_animation(|ctx| {
///         ctx.auto_start(true);
///         ctx.with(AnimNum::new(0., 100.).time(50))
///     });
///
///     let width = animation.get().read().as_f32();
///
///     rsx!(rect {
///         width: "{width}",
///         height: "100%",
///         background: "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::*;
/// fn app() -> Element {
///     let animation = use_animation(|ctx| {
///         ctx.auto_start(true);
///         (
///             ctx.with(AnimNum::new(0., 100.).time(50)),
///             ctx.with(AnimColor::new("red", "blue").time(50)),
///         )
///     });
///
///     let (width, color) = animation.get();
///
///     rsx!(rect {
///         width: "{width.read().as_f32()}",
///         height: "100%",
///         background: "{color.read().as_string()}"
///     })
/// }
/// ```
///
/// You can also tweak what to do once the animation has finished with [`Context::on_finish`].
///
/// ```rust,no_run
/// # use freya::prelude::*;
/// fn app() -> Element {
///     let animation = use_animation(|ctx| {
///         ctx.on_finish(OnFinish::Restart);
///         (
///             ctx.with(AnimNum::new(0., 100.).time(50)),
///             ctx.with(AnimColor::new("red", "blue").time(50)),
///         )
///     });
///
///     let (width, color) = animation.get();
///
///     rsx!(rect {
///         width: "{width.read().as_f32()}",
///         height: "100%",
///         background: "{color.read().as_string()}"
///     })
/// }
/// ```
pub fn use_animation<Animated: PartialEq + Clone + 'static>(
    run: impl Fn(&mut AnimationContext) -> Animated + Clone + 'static,
) -> UseAnimator<Animated> {
    let platform = use_platform();
    let is_running = use_signal(|| false);
    let has_run_yet = use_signal(|| false);
    let task = use_signal(|| None);

    let value_and_ctx = use_memo(move || {
        let mut ctx = AnimationContext::default();
        (run(&mut ctx), ctx)
    });

    let animator = UseAnimator {
        value_and_ctx,
        platform,
        is_running,
        has_run_yet,
        task,
    };

    use_hook(move || {
        if animator.value_and_ctx.read().1.auto_start {
            animator.run(AnimDirection::Forward);
        }
    });

    animator
}

pub fn use_animation_with_dependencies<Animated: PartialEq + Clone + 'static, D: Dependency>(
    deps: D,
    run: impl Fn(&mut AnimationContext, D::Out) -> Animated + 'static,
) -> UseAnimator<Animated>
where
    D::Out: 'static + Clone,
{
    let platform = use_platform();
    let is_running = use_signal(|| false);
    let has_run_yet = use_signal(|| false);
    let task = use_signal(|| None);

    let value_and_ctx = use_memo(use_reactive(deps, move |vals| {
        let mut ctx = AnimationContext::default();
        (run(&mut ctx, vals), ctx)
    }));

    let animator = UseAnimator {
        value_and_ctx,
        platform,
        is_running,
        has_run_yet,
        task,
    };

    use_hook(move || {
        if animator.value_and_ctx.read().1.auto_start {
            animator.run(AnimDirection::Forward);
        }
    });

    animator
}