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#[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#[derive(PartialEq, Clone, Copy, Default, Debug)]
55pub enum OnFinish {
56 #[default]
58 Nothing,
59 Reverse {
61 delay: Duration,
63 },
64 Restart {
66 delay: Duration,
68 },
69}
70
71impl OnFinish {
72 pub fn nothing() -> Self {
74 Self::Nothing
75 }
76
77 pub fn reverse() -> Self {
79 Self::Reverse {
80 delay: Duration::ZERO,
81 }
82 }
83
84 pub fn reverse_with_delay(delay: Duration) -> Self {
86 Self::Reverse { delay }
87 }
88
89 pub fn restart() -> Self {
91 Self::Restart {
92 delay: Duration::ZERO,
93 }
94 }
95
96 pub fn restart_with_delay(delay: Duration) -> Self {
98 Self::Restart { delay }
99 }
100}
101
102#[derive(PartialEq, Clone, Copy, Default, Debug)]
106pub enum OnCreation {
107 #[default]
109 Nothing,
110 Run,
112 Finish,
114}
115
116#[derive(PartialEq, Clone, Copy, Default, Debug)]
120pub enum OnChange {
121 #[default]
123 Reset,
124 Finish,
126 Rerun,
128 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#[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 pub fn get(&self) -> ReadRef<'_, Animated> {
180 self.animated_value.read()
181 }
182
183 pub fn direction(&self) -> ReadRef<'_, AnimDirection> {
185 self.last_direction.read()
186 }
187
188 pub fn start(&mut self) {
190 self.run(AnimDirection::Forward)
191 }
192
193 pub fn reverse(&mut self) {
195 self.run(AnimDirection::Reverse)
196 }
197
198 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 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 pub fn runs(&self) -> State<usize> {
238 self.runs
239 }
240
241 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 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 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 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 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 direction.toggle();
298 delay
299 }
300 OnFinish::Restart { delay } => delay,
301 OnFinish::Nothing => {
302 break;
304 }
305 };
306
307 if !delay.is_zero() {
308 timer(delay).await;
309 }
310
311 index = 0;
312
313 animated_value.write().prepare(direction);
315 }
316
317 platform.send(UserEvent::RequestRedraw);
319
320 prev_frame = Instant::now();
321 }
322
323 is_running.set(false);
324 task.write().take();
325 });
326
327 task.write().replace(animation_task);
329 }
330}
331pub 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
481pub 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 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
642pub 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}