1use std::cell::{Cell, RefCell};
6use std::panic::{self, AssertUnwindSafe};
7use std::rc::Rc;
8use std::time::{Duration, Instant};
9
10use crabshell_reactive::{Owner, ReadSignal, Signal, untrack};
11
12use crate::cx::Cx;
13use crate::geometry::Point;
14use crate::input::panic_message;
15use crate::prop::IntoProp;
16use crate::style::Color;
17
18#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub enum Easing {
22 Linear,
24 InQuad,
26 OutQuad,
28 InOutQuad,
30 InCubic,
32 #[default]
35 OutCubic,
36 InOutCubic,
38 InSine,
40 OutSine,
42 InOutSine,
44 InQuart,
46 OutQuart,
48 InOutQuart,
50 InQuint,
52 OutQuint,
54 InOutQuint,
56 InExpo,
58 OutExpo,
60 InOutExpo,
62 InCirc,
64 OutCirc,
66 InOutCirc,
68 InBack,
70 OutBack,
72 InOutBack,
74 Bezier(f32, f32, f32, f32),
78 Spline(&'static [[f32; 6]]),
98}
99
100impl Easing {
101 pub fn value_at(self, t: f32) -> f32 {
105 use std::f32::consts::PI;
106 const C1: f32 = 1.70158;
108 const C2: f32 = C1 * 1.525;
109 let t = if t.is_nan() { 1.0 } else { t.clamp(0.0, 1.0) };
110 match self {
111 Easing::Linear => t,
112 Easing::InQuad => t * t,
113 Easing::OutQuad => 1.0 - (1.0 - t) * (1.0 - t),
114 Easing::InOutQuad if t < 0.5 => 2.0 * t * t,
115 Easing::InOutQuad => 1.0 - (-2.0 * t + 2.0).powi(2) / 2.0,
116 Easing::InCubic => t * t * t,
117 Easing::OutCubic => 1.0 - (1.0 - t).powi(3),
118 Easing::InOutCubic if t < 0.5 => 4.0 * t * t * t,
119 Easing::InOutCubic => 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0,
120 Easing::InSine => 1.0 - (t * PI / 2.0).cos(),
121 Easing::OutSine => (t * PI / 2.0).sin(),
122 Easing::InOutSine => (1.0 - (PI * t).cos()) / 2.0,
123 Easing::InQuart => t.powi(4),
124 Easing::OutQuart => 1.0 - (1.0 - t).powi(4),
125 Easing::InOutQuart if t < 0.5 => 8.0 * t.powi(4),
126 Easing::InOutQuart => 1.0 - (-2.0 * t + 2.0).powi(4) / 2.0,
127 Easing::InQuint => t.powi(5),
128 Easing::OutQuint => 1.0 - (1.0 - t).powi(5),
129 Easing::InOutQuint if t < 0.5 => 16.0 * t.powi(5),
130 Easing::InOutQuint => 1.0 - (-2.0 * t + 2.0).powi(5) / 2.0,
131 Easing::InExpo | Easing::OutExpo | Easing::InOutExpo if t == 0.0 || t == 1.0 => t,
133 Easing::InExpo => 2_f32.powf(10.0 * t - 10.0),
134 Easing::OutExpo => 1.0 - 2_f32.powf(-10.0 * t),
135 Easing::InOutExpo if t < 0.5 => 2_f32.powf(20.0 * t - 10.0) / 2.0,
136 Easing::InOutExpo => (2.0 - 2_f32.powf(-20.0 * t + 10.0)) / 2.0,
137 Easing::InCirc => 1.0 - (1.0 - t * t).sqrt(),
138 Easing::OutCirc => (1.0 - (t - 1.0).powi(2)).sqrt(),
139 Easing::InOutCirc if t < 0.5 => (1.0 - (1.0 - (2.0 * t).powi(2)).sqrt()) / 2.0,
140 Easing::InOutCirc => ((1.0 - (-2.0 * t + 2.0).powi(2)).sqrt() + 1.0) / 2.0,
141 Easing::InBack => (C1 + 1.0) * t.powi(3) - C1 * t * t,
142 Easing::OutBack => 1.0 + (C1 + 1.0) * (t - 1.0).powi(3) + C1 * (t - 1.0).powi(2),
143 Easing::InOutBack if t < 0.5 => (2.0 * t).powi(2) * ((C2 + 1.0) * 2.0 * t - C2) / 2.0,
144 Easing::InOutBack => {
145 ((2.0 * t - 2.0).powi(2) * ((C2 + 1.0) * (2.0 * t - 2.0) + C2) + 2.0) / 2.0
146 }
147 Easing::Bezier(x1, y1, x2, y2) => bezier(t, (0.0, 0.0), [x1, y1, x2, y2, 1.0, 1.0]),
148 Easing::Spline(segments) => spline(t, segments),
149 }
150 }
151}
152
153fn spline(x: f32, segments: &[[f32; 6]]) -> f32 {
156 let mut end = 0.0;
157 let valid = segments.iter().all(|segment| {
158 let forward = segment[4] >= end;
159 end = segment[4];
160 forward && segment.iter().all(|n| n.is_finite())
161 }) && segments
162 .last()
163 .is_some_and(|last| last[4] == 1.0 && last[5] == 1.0);
164 if !valid {
165 return x;
166 }
167 let mut start = (0.0, 0.0);
168 for segment in segments {
169 if x <= segment[4] {
170 return bezier(x, start, *segment);
171 }
172 start = (segment[4], segment[5]);
173 }
174 1.0
175}
176
177fn bezier(x: f32, (x0, y0): (f32, f32), segment: [f32; 6]) -> f32 {
182 let [x1, y1, x2, y2, x3, y3] = segment;
183 let (x1, x2) = (x1.clamp(x0, x3), x2.clamp(x0, x3));
184 let at = |p0: f32, p1: f32, p2: f32, p3: f32, s: f32| {
185 let r = 1.0 - s;
186 r * r * r * p0 + 3.0 * r * r * s * p1 + 3.0 * r * s * s * p2 + s * s * s * p3
187 };
188 let (mut low, mut high) = (0.0_f32, 1.0_f32);
189 for _ in 0..32 {
190 let middle = (low + high) / 2.0;
191 if at(x0, x1, x2, x3, middle) < x {
192 low = middle;
193 } else {
194 high = middle;
195 }
196 }
197 at(y0, y1, y2, y3, (low + high) / 2.0)
198}
199
200#[derive(Clone, Copy, Debug, PartialEq)]
203pub struct Transition {
204 pub ms: u32,
206 pub easing: Easing,
208 pub delay: u32,
210 pub alternate: bool,
213}
214
215impl Transition {
216 pub const fn new(ms: u32) -> Transition {
218 Transition {
219 ms,
220 easing: Easing::OutCubic,
221 delay: 0,
222 alternate: false,
223 }
224 }
225
226 pub const fn easing(self, easing: Easing) -> Transition {
228 Transition { easing, ..self }
229 }
230
231 pub const fn delay(self, ms: u32) -> Transition {
233 Transition { delay: ms, ..self }
234 }
235
236 pub const fn alternate(self) -> Transition {
239 Transition {
240 alternate: true,
241 ..self
242 }
243 }
244
245 pub(crate) fn is_instant(self) -> bool {
247 self.ms == 0 && self.delay == 0
248 }
249
250 pub(crate) fn waiting(self, start: Instant, now: Instant) -> bool {
253 now.saturating_duration_since(start) < Duration::from_millis(self.delay.into())
254 }
255
256 pub(crate) fn progress(self, start: Instant, now: Instant) -> (f32, bool) {
259 let elapsed = now.saturating_duration_since(start).as_secs_f32() * 1000.0 - self.delay as f32;
260 if elapsed < 0.0 {
261 return (0.0, false);
262 }
263 if self.ms == 0 {
264 return (1.0, true);
265 }
266 let t = elapsed / self.ms as f32;
267 if t >= 1.0 {
268 (1.0, true)
269 } else {
270 (self.easing.value_at(t), false)
271 }
272 }
273}
274
275#[derive(Clone, Copy, Debug, PartialEq)]
284pub struct Spring {
285 pub stiffness: f32,
287 pub damping: f32,
289}
290
291impl Spring {
292 pub const fn new(stiffness: f32, damping: f32) -> Spring {
294 Spring { stiffness, damping }
295 }
296
297 fn is_valid(self) -> bool {
300 self.stiffness.is_finite()
301 && self.stiffness > 0.0
302 && self.damping.is_finite()
303 && self.damping >= 0.0
304 }
305
306 pub(crate) fn advance(self, x: &mut f64, v: &mut f64, goal: f64, seconds: f64) {
310 let k = f64::from(self.stiffness);
311 let c = 2.0 * f64::from(self.damping) * k.sqrt();
312 let steps = (seconds * 1000.0).ceil().max(1.0);
313 let dt = seconds / steps;
314 for _ in 0..steps as u32 {
315 *v = (*v - dt * k * (*x - goal)) / (1.0 + dt * c + dt * dt * k);
316 *x += dt * *v;
317 }
318 }
319}
320
321impl Default for Spring {
322 fn default() -> Spring {
323 Spring::new(700.0, 0.9)
324 }
325}
326
327const SPRING_MAX_STEP: f64 = 0.25;
330
331const SPRING_REST: (f64, f64) = (0.001, 0.01);
334
335pub trait Animate: Clone + PartialEq + 'static {
339 fn lerp(&self, to: &Self, t: f32) -> Self;
341}
342
343impl Animate for f32 {
344 fn lerp(&self, to: &f32, t: f32) -> f32 {
345 self + (to - self) * t
346 }
347}
348
349impl Animate for Point {
350 fn lerp(&self, to: &Point, t: f32) -> Point {
351 Point::new(self.x.lerp(&to.x, t), self.y.lerp(&to.y, t))
352 }
353}
354
355impl Animate for Color {
356 fn lerp(&self, to: &Color, t: f32) -> Color {
357 let channel = |a: u8, b: u8| {
358 f32::from(a)
359 .lerp(&f32::from(b), t)
360 .round()
361 .clamp(0.0, 255.0) as u8
362 };
363 Color::rgba(
364 channel(self.r, to.r),
365 channel(self.g, to.g),
366 channel(self.b, to.b),
367 channel(self.a, to.a),
368 )
369 }
370}
371
372type Step = Box<dyn FnMut(Instant) -> bool>;
375
376type Running = (Rc<str>, Option<Busy>, Step);
378
379pub(crate) struct Activity {
383 running: Cell<usize>,
384 outer: Option<Rc<Activity>>,
385}
386
387impl Activity {
388 pub(crate) fn new(outer: Option<Rc<Activity>>) -> Rc<Activity> {
389 Rc::new(Activity {
390 running: Cell::new(0),
391 outer,
392 })
393 }
394
395 fn add(&self, by: isize) {
397 let mut at = Some(self);
398 while let Some(activity) = at {
399 activity
400 .running
401 .set(activity.running.get().wrapping_add_signed(by));
402 at = activity.outer.as_deref();
403 }
404 }
405}
406
407pub(crate) struct Busy(Rc<Activity>);
409
410impl Busy {
411 pub(crate) fn new(activity: &Rc<Activity>) -> Busy {
412 activity.add(1);
413 Busy(Rc::clone(activity))
414 }
415}
416
417impl Drop for Busy {
418 fn drop(&mut self) {
419 self.0.add(-1);
420 }
421}
422
423struct Watch {
427 owner: Owner,
428 activity: Rc<Activity>,
429 done: Box<dyn FnOnce()>,
430}
431
432thread_local! {
433 static RUNNING: RefCell<Vec<Running>> = const { RefCell::new(Vec::new()) };
436 static WATCHES: RefCell<Vec<Watch>> = const { RefCell::new(Vec::new()) };
437 static LAST_TICK: Cell<Option<Instant>> = const { Cell::new(None) };
439}
440
441pub(crate) fn start(label: Rc<str>, busy: Option<Busy>, step: Step) {
444 RUNNING.with(|running| running.borrow_mut().push((label, busy, step)));
445}
446
447pub(crate) fn watch(owner: Owner, activity: Rc<Activity>, done: impl FnOnce() + 'static) {
451 WATCHES.with(|watches| {
452 watches.borrow_mut().push(Watch {
453 owner,
454 activity,
455 done: Box::new(done),
456 });
457 });
458}
459
460fn judge_watches() {
464 let watches = WATCHES.with(|watches| std::mem::take(&mut *watches.borrow_mut()));
465 let mut kept = Vec::with_capacity(watches.len());
466 for watch in watches {
467 if watch.owner.is_disposed() {
468 continue;
469 }
470 if watch.activity.running.get() == 0 {
471 (watch.done)();
472 } else {
473 kept.push(watch);
474 }
475 }
476 WATCHES.with(|watches| {
477 let mut watches = watches.borrow_mut();
478 kept.append(&mut watches);
479 *watches = kept;
480 });
481}
482
483pub(crate) fn start_time() -> Option<Instant> {
487 if animating() {
488 LAST_TICK.with(Cell::get)
489 } else {
490 None
491 }
492}
493
494pub fn animating() -> bool {
497 RUNNING.with(|running| !running.borrow().is_empty())
498 || WATCHES.with(|watches| !watches.borrow().is_empty())
499}
500
501pub fn advance_animations(now: Instant) -> bool {
506 LAST_TICK.with(|last| last.set(Some(now)));
507 judge_watches();
508 let steps = RUNNING.with(|running| std::mem::take(&mut *running.borrow_mut()));
509 let mut kept = Vec::with_capacity(steps.len());
510 for (label, busy, mut step) in steps {
511 match panic::catch_unwind(AssertUnwindSafe(|| step(now))) {
512 Ok(true) => kept.push((label, busy, step)),
513 Ok(false) => drop_isolated(&label, step),
514 Err(payload) => {
515 tracing::error!(
516 "animation {label} panicked and stops: {}",
517 panic_message(payload.as_ref())
518 );
519 drop_isolated(&label, step);
520 }
521 }
522 }
523 RUNNING.with(|running| {
524 let mut running = running.borrow_mut();
526 kept.append(&mut running);
527 *running = kept;
528 });
529 let still = animating();
530 if !still {
531 LAST_TICK.with(|last| last.set(None));
534 }
535 still
536}
537
538fn drop_isolated(label: &str, step: Step) {
540 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(step))) {
541 tracing::error!(
542 "dropping animation {label} panicked: {}",
543 panic_message(payload.as_ref())
544 );
545 }
546}
547
548fn guarded<R>(label: &str, f: impl FnOnce() -> R) -> Option<R> {
551 match panic::catch_unwind(AssertUnwindSafe(f)) {
552 Ok(value) => Some(value),
553 Err(payload) => {
554 tracing::error!(
555 "animation {label} panicked and stops: {}",
556 panic_message(payload.as_ref())
557 );
558 None
559 }
560 }
561}
562
563fn set_changed<T: PartialEq + 'static>(signal: Signal<T>, value: T) {
566 if untrack(|| signal.try_with(|old| *old != value)) == Some(true) {
567 signal.try_set(value);
568 }
569}
570
571pub struct Animation<T: 'static> {
575 value: ReadSignal<T>,
576 running: ReadSignal<bool>,
577}
578
579impl<T> Clone for Animation<T> {
580 fn clone(&self) -> Self {
581 *self
582 }
583}
584
585impl<T> Copy for Animation<T> {}
586
587impl<T> Animation<T> {
588 pub fn value(&self) -> ReadSignal<T> {
590 self.value
591 }
592
593 pub fn running(&self) -> ReadSignal<bool> {
597 self.running
598 }
599}
600
601impl Cx {
602 #[track_caller]
618 pub fn animate<T: Animate>(
619 &self,
620 target: impl FnMut() -> T + 'static,
621 transition: impl IntoProp<Transition>,
622 ) -> ReadSignal<T> {
623 self.follow("cx.animate", target, transition).value
624 }
625
626 #[track_caller]
645 pub fn animation<T: Animate>(
646 &self,
647 target: impl FnMut() -> T + 'static,
648 transition: impl IntoProp<Transition>,
649 ) -> Animation<T> {
650 self.follow("cx.animation", target, transition)
651 }
652
653 #[track_caller]
655 fn follow<T: Animate>(
656 &self,
657 what: &str,
658 mut target: impl FnMut() -> T + 'static,
659 transition: impl IntoProp<Transition>,
660 ) -> Animation<T> {
661 let label: Rc<str> = format!("{what} at {}", std::panic::Location::caller()).into();
662 let transition = transition.into_prop().shared();
663 let activity = self.activity.clone();
664 let first = untrack(&mut target);
665 let value = self.signal(first.clone());
666 let running = self.signal(false);
667 let mut last = first;
668 let generation = Rc::new(Cell::new(0_u64));
670 let mut broken = false;
671 self.effect(move || {
672 if broken {
673 return;
674 }
675 let Some(to) = guarded(&label, &mut target) else {
676 broken = true;
677 generation.set(generation.get() + 1);
678 set_changed(running, false);
679 return;
680 };
681 if to == last {
682 return;
683 }
684 let Some(transition) = guarded(&label, || untrack(&*transition)) else {
686 broken = true;
687 generation.set(generation.get() + 1);
688 set_changed(running, false);
689 return;
690 };
691 last = to.clone();
692 let Some(from) = untrack(|| value.try_get()) else {
693 return;
694 };
695 let current = generation.get() + 1;
696 generation.set(current);
697 if transition.is_instant() {
699 value.try_set(to);
700 set_changed(running, false);
701 return;
702 }
703 set_changed(running, true);
704 let generation = Rc::clone(&generation);
705 let mut started = start_time();
706 let step_label = Rc::clone(&label);
707 start(
708 Rc::clone(&label),
709 activity.as_ref().map(Busy::new),
710 Box::new(move |now| {
711 if generation.get() != current {
712 return false;
713 }
714 let begun = *started.get_or_insert(now);
715 if transition.waiting(begun, now) {
716 return true;
718 }
719 let (t, ended) = transition.progress(begun, now);
720 let Some(next) = guarded(&step_label, || {
723 if ended { to.clone() } else { from.lerp(&to, t) }
724 }) else {
725 running.try_set(false);
726 return false;
727 };
728 let kept = value.try_set(next);
730 if ended {
731 running.try_set(false);
732 }
733 kept && !ended
734 }),
735 );
736 });
737 Animation {
738 value: value.read_only(),
739 running: running.read_only(),
740 }
741 }
742
743 #[track_caller]
765 pub fn cycle(
766 &self,
767 mut running: impl FnMut() -> bool + 'static,
768 transition: Transition,
769 ) -> ReadSignal<f32> {
770 let label: Rc<str> = format!("cx.cycle at {}", std::panic::Location::caller()).into();
771 let activity = self.activity.clone();
772 let value = self.signal(0.0_f32);
773 let wanted = Rc::new(Cell::new(false));
775 let ticking = Rc::new(Cell::new(false));
776 let mut broken = false;
777 self.effect(move || {
778 let on = !broken
779 && guarded(&label, &mut running).unwrap_or_else(|| {
780 broken = true;
781 false
782 });
783 wanted.set(on);
784 if !on || ticking.get() || transition.ms == 0 {
785 return;
786 }
787 ticking.set(true);
788 let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
789 let leg = f64::from(transition.ms);
790 let period = if transition.alternate { 2.0 * leg } else { leg };
791 let mut started = start_time();
792 let mut round = 0_u64;
794 start(
795 Rc::clone(&label),
796 activity.as_ref().map(Busy::new),
797 Box::new(move |now| {
798 let begun = *started.get_or_insert(now);
799 let elapsed = now.saturating_duration_since(begun).as_secs_f64() * 1000.0
800 - f64::from(transition.delay);
801 let now_round = if elapsed < 0.0 {
802 0
803 } else {
804 (elapsed / period) as u64 + 1
805 };
806 let ended = !wanted.get() && (now_round == 0 || now_round > round);
807 round = now_round;
808 if ended {
809 ticking.set(false);
810 value.try_set(0.0);
811 return false;
812 }
813 let phase = elapsed.max(0.0) % period / leg;
814 let t = if phase <= 1.0 { phase } else { 2.0 - phase };
815 value.try_set(transition.easing.value_at(t as f32))
816 }),
817 );
818 });
819 value.read_only()
820 }
821
822 #[track_caller]
838 pub fn frames(&self, mut running: impl FnMut() -> bool + 'static) -> ReadSignal<Duration> {
839 let label: Rc<str> = format!("cx.frames at {}", std::panic::Location::caller()).into();
840 let activity = self.activity.clone();
841 let value = self.signal(Duration::ZERO);
842 let wanted = Rc::new(Cell::new(false));
843 let ticking = Rc::new(Cell::new(false));
844 let mut broken = false;
845 self.effect(move || {
846 let on = !broken
847 && guarded(&label, &mut running).unwrap_or_else(|| {
848 broken = true;
849 false
850 });
851 wanted.set(on);
852 if !on || ticking.get() {
853 return;
854 }
855 ticking.set(true);
856 let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
857 let mut started = start_time();
858 start(
859 Rc::clone(&label),
860 activity.as_ref().map(Busy::new),
861 Box::new(move |now| {
862 if !wanted.get() {
863 ticking.set(false);
864 return false;
865 }
866 let begun = *started.get_or_insert(now);
867 value.try_set(now.saturating_duration_since(begun))
868 }),
869 );
870 });
871 value.read_only()
872 }
873
874 #[track_caller]
894 pub fn spring(
895 &self,
896 mut target: impl FnMut() -> f32 + 'static,
897 spring: Spring,
898 ) -> Animation<f32> {
899 let label: Rc<str> = format!("cx.spring at {}", std::panic::Location::caller()).into();
900 let activity = self.activity.clone();
901 let first = untrack(&mut target);
902 let value = self.signal(first);
903 let running = self.signal(false);
904 let mut last = first;
905 let goal = Rc::new(Cell::new(first));
908 let ticking = Rc::new(Cell::new(false));
909 let mut broken = false;
910 self.effect(move || {
911 if broken {
912 return;
913 }
914 let Some(to) = guarded(&label, &mut target) else {
915 broken = true;
916 goal.set(f32::NAN);
917 set_changed(running, false);
918 return;
919 };
920 if to == last {
921 return;
922 }
923 last = to;
924 goal.set(to);
925 if !to.is_finite() || !spring.is_valid() {
926 value.try_set(to);
927 set_changed(running, false);
929 return;
930 }
931 if ticking.get() {
932 set_changed(running, true);
934 return;
935 }
936 let Some(from) = untrack(|| value.try_get()) else {
937 return;
938 };
939 ticking.set(true);
940 set_changed(running, true);
941 let (goal, ticking) = (Rc::clone(&goal), Rc::clone(&ticking));
942 let (mut x, mut v) = (f64::from(from), 0.0);
943 let mut previous = start_time();
944 start(
945 Rc::clone(&label),
946 activity.as_ref().map(Busy::new),
947 Box::new(move |now| {
948 let to = f64::from(goal.get());
949 if !to.is_finite() {
950 ticking.set(false);
951 set_changed(running, false);
952 return false;
953 }
954 let seconds = previous.map_or(0.0, |previous| {
955 now
956 .saturating_duration_since(previous)
957 .as_secs_f64()
958 .min(SPRING_MAX_STEP)
959 });
960 previous = Some(now);
961 spring.advance(&mut x, &mut v, to, seconds);
962 let (near, slow) = SPRING_REST;
963 let rest = !(x.is_finite() && v.is_finite()) || ((x - to).abs() < near && v.abs() < slow);
965 if rest {
966 x = to;
967 }
968 let kept = value.try_set(x as f32);
969 if rest || !kept {
970 ticking.set(false);
971 set_changed(running, false);
972 }
973 kept && !rest
974 }),
975 );
976 });
977 Animation {
978 value: value.read_only(),
979 running: running.read_only(),
980 }
981 }
982}