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, Prop, PropKind};
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
335#[derive(Clone, Copy, Debug, PartialEq)]
340pub struct Step<T> {
341 to: Option<T>,
342 transition: Transition,
343}
344
345impl<T> Step<T> {
346 pub const fn to(value: T, transition: Transition) -> Step<T> {
349 Step {
350 to: Some(value),
351 transition,
352 }
353 }
354
355 pub const fn hold(ms: u32) -> Step<T> {
358 Step {
359 to: None,
360 transition: Transition::new(0).delay(ms),
361 }
362 }
363
364 fn times(&self) -> (u64, u64) {
367 let moves = u64::from(self.transition.delay) * 1000;
368 (moves, moves + u64::from(self.transition.ms) * 1000)
369 }
370}
371
372impl<T: Animate> IntoProp<Vec<Step<T>>> for Vec<Step<T>> {
373 fn into_prop(self) -> Prop<Vec<Step<T>>> {
374 Prop(PropKind::Value(self))
375 }
376}
377
378impl<T: Animate, const N: usize> IntoProp<Vec<Step<T>>> for [Step<T>; N] {
380 fn into_prop(self) -> Prop<Vec<Step<T>>> {
381 Prop(PropKind::Value(self.into()))
382 }
383}
384
385enum Spot<T> {
387 Moving(T),
389 Holding(T, u64),
392 Ended(T),
394}
395
396fn spot<T: Animate>(steps: &[Step<T>], from: &T, at: u64) -> Spot<T> {
399 let mut from = from.clone();
400 let mut begins = 0;
401 for (i, step) in steps.iter().enumerate() {
402 let (moves, ends) = step.times();
403 if at < begins + moves {
404 let mut until = begins + moves;
406 if step.to.is_none() {
407 for next in &steps[i + 1..] {
408 until += next.times().0;
409 if next.to.is_some() {
410 break;
411 }
412 }
413 }
414 return Spot::Holding(from, until);
415 }
416 if let Some(to) = &step.to {
417 if at < begins + ends {
418 let t = (at - begins - moves) as f32 / (ends - moves) as f32;
419 return Spot::Moving(from.lerp(to, step.transition.easing.value_at(t)));
420 }
421 from = to.clone();
422 }
423 begins += ends;
424 }
425 Spot::Ended(from)
426}
427
428pub trait Animate: Clone + PartialEq + 'static {
432 fn lerp(&self, to: &Self, t: f32) -> Self;
434}
435
436impl Animate for f32 {
437 fn lerp(&self, to: &f32, t: f32) -> f32 {
438 self + (to - self) * t
439 }
440}
441
442impl Animate for Point {
443 fn lerp(&self, to: &Point, t: f32) -> Point {
444 Point::new(self.x.lerp(&to.x, t), self.y.lerp(&to.y, t))
445 }
446}
447
448impl Animate for Color {
449 fn lerp(&self, to: &Color, t: f32) -> Color {
450 let channel = |a: u8, b: u8| {
451 f32::from(a)
452 .lerp(&f32::from(b), t)
453 .round()
454 .clamp(0.0, 255.0) as u8
455 };
456 Color::rgba(
457 channel(self.r, to.r),
458 channel(self.g, to.g),
459 channel(self.b, to.b),
460 channel(self.a, to.a),
461 )
462 }
463}
464
465type Tick = Box<dyn FnMut(Instant) -> bool>;
468
469type Running = (Rc<str>, Option<Busy>, Tick);
471
472pub(crate) struct Activity {
476 running: Cell<usize>,
477 outer: Option<Rc<Activity>>,
478}
479
480impl Activity {
481 pub(crate) fn new(outer: Option<Rc<Activity>>) -> Rc<Activity> {
482 Rc::new(Activity {
483 running: Cell::new(0),
484 outer,
485 })
486 }
487
488 fn add(&self, by: isize) {
490 let mut at = Some(self);
491 while let Some(activity) = at {
492 activity
493 .running
494 .set(activity.running.get().wrapping_add_signed(by));
495 at = activity.outer.as_deref();
496 }
497 }
498}
499
500pub(crate) struct Busy(Rc<Activity>);
502
503impl Busy {
504 pub(crate) fn new(activity: &Rc<Activity>) -> Busy {
505 activity.add(1);
506 Busy(Rc::clone(activity))
507 }
508}
509
510impl Drop for Busy {
511 fn drop(&mut self) {
512 self.0.add(-1);
513 }
514}
515
516struct Watch {
520 owner: Owner,
521 activity: Rc<Activity>,
522 done: Box<dyn FnOnce()>,
523}
524
525thread_local! {
526 static RUNNING: RefCell<Vec<Running>> = const { RefCell::new(Vec::new()) };
529 static WATCHES: RefCell<Vec<Watch>> = const { RefCell::new(Vec::new()) };
530 static ASLEEP: RefCell<Vec<Sleeper>> = const { RefCell::new(Vec::new()) };
532 static SLEEP: Cell<Option<Nap>> = const { Cell::new(None) };
534 static LAST_TICK: Cell<Option<Instant>> = const { Cell::new(None) };
536}
537
538pub(crate) fn start(label: Rc<str>, busy: Option<Busy>, step: Tick) {
541 RUNNING.with(|running| running.borrow_mut().push((label, busy, step)));
542}
543
544pub(crate) struct Nap {
548 pub(crate) deadline: Instant,
549 pub(crate) owner: Owner,
550 pub(crate) play: (Rc<Cell<u64>>, u64),
551}
552
553struct Sleeper {
555 nap: Nap,
556 running: Running,
557}
558
559impl Nap {
560 fn stale(&self) -> bool {
562 self.owner.is_disposed() || self.play.0.get() != self.play.1
563 }
564}
565
566pub(crate) fn sleep_until(nap: Nap) {
570 SLEEP.with(|sleep| sleep.set(Some(nap)));
571}
572
573fn sweep_asleep() {
576 let gone = ASLEEP.with(|asleep| {
577 let mut asleep = asleep.borrow_mut();
578 let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut *asleep)
579 .into_iter()
580 .partition(|sleeper| sleeper.nap.stale());
581 *asleep = kept;
582 gone
583 });
584 for Sleeper {
585 running: (label, busy, step),
586 ..
587 } in gone
588 {
589 drop(busy);
590 drop_isolated(&label, step);
591 }
592}
593
594pub(crate) fn next_wake() -> Option<Instant> {
596 sweep_asleep();
597 ASLEEP.with(|asleep| {
598 let asleep = asleep.borrow();
599 asleep.iter().map(|sleeper| sleeper.nap.deadline).min()
600 })
601}
602
603pub(crate) fn wake(now: Instant) {
606 sweep_asleep();
607 let due: Vec<Running> = ASLEEP.with(|asleep| {
608 let mut asleep = asleep.borrow_mut();
609 let (due, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut *asleep)
610 .into_iter()
611 .partition(|sleeper| sleeper.nap.deadline <= now);
612 *asleep = kept;
613 due.into_iter().map(|sleeper| sleeper.running).collect()
614 });
615 RUNNING.with(|running| running.borrow_mut().extend(due));
616}
617
618#[cfg(test)]
620pub(crate) fn asleep() -> usize {
621 ASLEEP.with(|asleep| asleep.borrow().len())
622}
623
624pub(crate) fn watch(owner: Owner, activity: Rc<Activity>, done: impl FnOnce() + 'static) {
628 WATCHES.with(|watches| {
629 watches.borrow_mut().push(Watch {
630 owner,
631 activity,
632 done: Box::new(done),
633 });
634 });
635}
636
637fn judge_watches() {
641 let watches = WATCHES.with(|watches| std::mem::take(&mut *watches.borrow_mut()));
642 let mut kept = Vec::with_capacity(watches.len());
643 for watch in watches {
644 if watch.owner.is_disposed() {
645 continue;
646 }
647 if watch.activity.running.get() == 0 {
648 (watch.done)();
649 } else {
650 kept.push(watch);
651 }
652 }
653 WATCHES.with(|watches| {
654 let mut watches = watches.borrow_mut();
655 kept.append(&mut watches);
656 *watches = kept;
657 });
658}
659
660pub(crate) fn start_time() -> Option<Instant> {
664 if animating() {
665 LAST_TICK.with(Cell::get)
666 } else {
667 None
668 }
669}
670
671pub fn animating() -> bool {
674 RUNNING.with(|running| !running.borrow().is_empty())
675 || WATCHES.with(|watches| !watches.borrow().is_empty())
676}
677
678pub fn advance_animations(now: Instant) -> bool {
683 LAST_TICK.with(|last| last.set(Some(now)));
684 judge_watches();
685 let steps = RUNNING.with(|running| std::mem::take(&mut *running.borrow_mut()));
686 let mut kept = Vec::with_capacity(steps.len());
687 for (label, busy, mut step) in steps {
688 let ran = panic::catch_unwind(AssertUnwindSafe(|| step(now)));
689 let sleep = SLEEP.with(Cell::take);
690 match ran {
691 Ok(true) => match sleep {
692 Some(nap) => {
693 let running = (label, busy, step);
694 ASLEEP.with(|asleep| asleep.borrow_mut().push(Sleeper { nap, running }));
695 }
696 None => kept.push((label, busy, step)),
697 },
698 Ok(false) => drop_isolated(&label, step),
699 Err(payload) => {
700 tracing::error!(
701 "animation {label} panicked and stops: {}",
702 panic_message(payload.as_ref())
703 );
704 drop_isolated(&label, step);
705 }
706 }
707 }
708 RUNNING.with(|running| {
709 let mut running = running.borrow_mut();
711 kept.append(&mut running);
712 *running = kept;
713 });
714 let still = animating();
715 if !still {
716 LAST_TICK.with(|last| last.set(None));
719 }
720 still
721}
722
723fn drop_isolated(label: &str, step: Tick) {
725 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(step))) {
726 tracing::error!(
727 "dropping animation {label} panicked: {}",
728 panic_message(payload.as_ref())
729 );
730 }
731}
732
733fn guarded<R>(label: &str, f: impl FnOnce() -> R) -> Option<R> {
736 match panic::catch_unwind(AssertUnwindSafe(f)) {
737 Ok(value) => Some(value),
738 Err(payload) => {
739 tracing::error!(
740 "animation {label} panicked and stops: {}",
741 panic_message(payload.as_ref())
742 );
743 None
744 }
745 }
746}
747
748fn set_changed<T: PartialEq + 'static>(signal: Signal<T>, value: T) {
751 if untrack(|| signal.try_with(|old| *old != value)) == Some(true) {
752 signal.try_set(value);
753 }
754}
755
756pub struct Animation<T: 'static> {
760 value: ReadSignal<T>,
761 running: ReadSignal<bool>,
762}
763
764impl<T> Clone for Animation<T> {
765 fn clone(&self) -> Self {
766 *self
767 }
768}
769
770impl<T> Copy for Animation<T> {}
771
772impl<T> Animation<T> {
773 pub fn value(&self) -> ReadSignal<T> {
775 self.value
776 }
777
778 pub fn running(&self) -> ReadSignal<bool> {
782 self.running
783 }
784}
785
786impl Cx {
787 #[track_caller]
803 pub fn animate<T: Animate>(
804 &self,
805 target: impl FnMut() -> T + 'static,
806 transition: impl IntoProp<Transition>,
807 ) -> ReadSignal<T> {
808 self.follow("cx.animate", target, transition).value
809 }
810
811 #[track_caller]
830 pub fn animation<T: Animate>(
831 &self,
832 target: impl FnMut() -> T + 'static,
833 transition: impl IntoProp<Transition>,
834 ) -> Animation<T> {
835 self.follow("cx.animation", target, transition)
836 }
837
838 #[track_caller]
840 fn follow<T: Animate>(
841 &self,
842 what: &str,
843 mut target: impl FnMut() -> T + 'static,
844 transition: impl IntoProp<Transition>,
845 ) -> Animation<T> {
846 let label: Rc<str> = format!("{what} at {}", std::panic::Location::caller()).into();
847 let transition = transition.into_prop().shared();
848 let activity = self.activity.clone();
849 let first = untrack(&mut target);
850 let value = self.signal(first.clone());
851 let running = self.signal(false);
852 let mut last = first;
853 let generation = Rc::new(Cell::new(0_u64));
855 let mut broken = false;
856 self.effect(move || {
857 if broken {
858 return;
859 }
860 let Some(to) = guarded(&label, &mut target) else {
861 broken = true;
862 generation.set(generation.get() + 1);
863 set_changed(running, false);
864 return;
865 };
866 if to == last {
867 return;
868 }
869 let Some(transition) = guarded(&label, || untrack(&*transition)) else {
871 broken = true;
872 generation.set(generation.get() + 1);
873 set_changed(running, false);
874 return;
875 };
876 last = to.clone();
877 let Some(from) = untrack(|| value.try_get()) else {
878 return;
879 };
880 let current = generation.get() + 1;
881 generation.set(current);
882 if transition.is_instant() {
884 value.try_set(to);
885 set_changed(running, false);
886 return;
887 }
888 set_changed(running, true);
889 let generation = Rc::clone(&generation);
890 let mut started = start_time();
891 let step_label = Rc::clone(&label);
892 start(
893 Rc::clone(&label),
894 activity.as_ref().map(Busy::new),
895 Box::new(move |now| {
896 if generation.get() != current {
897 return false;
898 }
899 let begun = *started.get_or_insert(now);
900 if transition.waiting(begun, now) {
901 return true;
903 }
904 let (t, ended) = transition.progress(begun, now);
905 let Some(next) = guarded(&step_label, || {
908 if ended { to.clone() } else { from.lerp(&to, t) }
909 }) else {
910 running.try_set(false);
911 return false;
912 };
913 let kept = value.try_set(next);
915 if ended {
916 running.try_set(false);
917 }
918 kept && !ended
919 }),
920 );
921 });
922 Animation {
923 value: value.read_only(),
924 running: running.read_only(),
925 }
926 }
927
928 #[track_caller]
950 pub fn cycle(
951 &self,
952 mut running: impl FnMut() -> bool + 'static,
953 transition: Transition,
954 ) -> ReadSignal<f32> {
955 let label: Rc<str> = format!("cx.cycle at {}", std::panic::Location::caller()).into();
956 let activity = self.activity.clone();
957 let value = self.signal(0.0_f32);
958 let wanted = Rc::new(Cell::new(false));
960 let ticking = Rc::new(Cell::new(false));
961 let mut broken = false;
962 self.effect(move || {
963 let on = !broken
964 && guarded(&label, &mut running).unwrap_or_else(|| {
965 broken = true;
966 false
967 });
968 wanted.set(on);
969 if !on || ticking.get() || transition.ms == 0 {
970 return;
971 }
972 ticking.set(true);
973 let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
974 let leg = f64::from(transition.ms);
975 let period = if transition.alternate { 2.0 * leg } else { leg };
976 let mut started = start_time();
977 let mut round = 0_u64;
979 start(
980 Rc::clone(&label),
981 activity.as_ref().map(Busy::new),
982 Box::new(move |now| {
983 let begun = *started.get_or_insert(now);
984 let elapsed = now.saturating_duration_since(begun).as_secs_f64() * 1000.0
985 - f64::from(transition.delay);
986 let now_round = if elapsed < 0.0 {
987 0
988 } else {
989 (elapsed / period) as u64 + 1
990 };
991 let ended = !wanted.get() && (now_round == 0 || now_round > round);
992 round = now_round;
993 if ended {
994 ticking.set(false);
995 value.try_set(0.0);
996 return false;
997 }
998 let phase = elapsed.max(0.0) % period / leg;
999 let t = if phase <= 1.0 { phase } else { 2.0 - phase };
1000 value.try_set(transition.easing.value_at(t as f32))
1001 }),
1002 );
1003 });
1004 value.read_only()
1005 }
1006
1007 #[track_caller]
1023 pub fn frames(&self, mut running: impl FnMut() -> bool + 'static) -> ReadSignal<Duration> {
1024 let label: Rc<str> = format!("cx.frames at {}", std::panic::Location::caller()).into();
1025 let activity = self.activity.clone();
1026 let value = self.signal(Duration::ZERO);
1027 let wanted = Rc::new(Cell::new(false));
1028 let ticking = Rc::new(Cell::new(false));
1029 let mut broken = false;
1030 self.effect(move || {
1031 let on = !broken
1032 && guarded(&label, &mut running).unwrap_or_else(|| {
1033 broken = true;
1034 false
1035 });
1036 wanted.set(on);
1037 if !on || ticking.get() {
1038 return;
1039 }
1040 ticking.set(true);
1041 let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
1042 let mut started = start_time();
1043 start(
1044 Rc::clone(&label),
1045 activity.as_ref().map(Busy::new),
1046 Box::new(move |now| {
1047 if !wanted.get() {
1048 ticking.set(false);
1049 return false;
1050 }
1051 let begun = *started.get_or_insert(now);
1052 value.try_set(now.saturating_duration_since(begun))
1053 }),
1054 );
1055 });
1056 value.read_only()
1057 }
1058
1059 #[track_caller]
1079 pub fn spring(
1080 &self,
1081 mut target: impl FnMut() -> f32 + 'static,
1082 spring: Spring,
1083 ) -> Animation<f32> {
1084 let label: Rc<str> = format!("cx.spring at {}", std::panic::Location::caller()).into();
1085 let activity = self.activity.clone();
1086 let first = untrack(&mut target);
1087 let value = self.signal(first);
1088 let running = self.signal(false);
1089 let mut last = first;
1090 let goal = Rc::new(Cell::new(first));
1093 let ticking = Rc::new(Cell::new(false));
1094 let mut broken = false;
1095 self.effect(move || {
1096 if broken {
1097 return;
1098 }
1099 let Some(to) = guarded(&label, &mut target) else {
1100 broken = true;
1101 goal.set(f32::NAN);
1102 set_changed(running, false);
1103 return;
1104 };
1105 if to == last {
1106 return;
1107 }
1108 last = to;
1109 goal.set(to);
1110 if !to.is_finite() || !spring.is_valid() {
1111 value.try_set(to);
1112 set_changed(running, false);
1114 return;
1115 }
1116 if ticking.get() {
1117 set_changed(running, true);
1119 return;
1120 }
1121 let Some(from) = untrack(|| value.try_get()) else {
1122 return;
1123 };
1124 ticking.set(true);
1125 set_changed(running, true);
1126 let (goal, ticking) = (Rc::clone(&goal), Rc::clone(&ticking));
1127 let (mut x, mut v) = (f64::from(from), 0.0);
1128 let mut previous = start_time();
1129 start(
1130 Rc::clone(&label),
1131 activity.as_ref().map(Busy::new),
1132 Box::new(move |now| {
1133 let to = f64::from(goal.get());
1134 if !to.is_finite() {
1135 ticking.set(false);
1136 set_changed(running, false);
1137 return false;
1138 }
1139 let seconds = previous.map_or(0.0, |previous| {
1140 now
1141 .saturating_duration_since(previous)
1142 .as_secs_f64()
1143 .min(SPRING_MAX_STEP)
1144 });
1145 previous = Some(now);
1146 spring.advance(&mut x, &mut v, to, seconds);
1147 let (near, slow) = SPRING_REST;
1148 let rest = !(x.is_finite() && v.is_finite()) || ((x - to).abs() < near && v.abs() < slow);
1150 if rest {
1151 x = to;
1152 }
1153 let kept = value.try_set(x as f32);
1154 if rest || !kept {
1155 ticking.set(false);
1156 set_changed(running, false);
1157 }
1158 kept && !rest
1159 }),
1160 );
1161 });
1162 Animation {
1163 value: value.read_only(),
1164 running: running.read_only(),
1165 }
1166 }
1167
1168 #[track_caller]
1201 pub fn sequence<T: Animate, K: PartialEq + 'static>(
1202 &self,
1203 initial: T,
1204 mut trigger: impl FnMut() -> K + 'static,
1205 steps: impl IntoProp<Vec<Step<T>>>,
1206 ) -> Animation<T> {
1207 let player = self.player("cx.sequence", initial, steps);
1208 let mut last = None;
1209 let mut broken = false;
1210 let animation = player.animation();
1211 self.effect(move || {
1212 if broken {
1213 return;
1214 }
1215 let Some(now) = guarded(&player.label, &mut trigger) else {
1216 broken = true;
1217 player.stop();
1218 return;
1219 };
1220 if last.as_ref().is_some_and(|last| *last != now) {
1221 player.play(false);
1222 }
1223 last = Some(now);
1224 });
1225 animation
1226 }
1227
1228 #[track_caller]
1251 pub fn sequence_loop<T: Animate>(
1252 &self,
1253 initial: T,
1254 mut running: impl FnMut() -> bool + 'static,
1255 steps: impl IntoProp<Vec<Step<T>>>,
1256 ) -> Animation<T> {
1257 let player = self.player("cx.sequence_loop", initial, steps);
1258 let mut broken = false;
1259 let animation = player.animation();
1260 self.effect(move || {
1261 let on = !broken
1262 && guarded(&player.label, &mut running).unwrap_or_else(|| {
1263 broken = true;
1264 false
1265 });
1266 player.wanted.set(on);
1267 if on && untrack(|| player.running.try_get()) == Some(false) {
1268 player.play(true);
1269 }
1270 });
1271 animation
1272 }
1273
1274 #[track_caller]
1277 fn player<T: Animate>(
1278 &self,
1279 what: &str,
1280 initial: T,
1281 steps: impl IntoProp<Vec<Step<T>>>,
1282 ) -> Rc<Player<T>> {
1283 Rc::new(Player {
1284 label: format!("{what} at {}", std::panic::Location::caller()).into(),
1285 steps: steps.into_prop().shared(),
1286 value: self.signal(initial),
1287 running: self.signal(false),
1288 generation: Rc::new(Cell::new(0)),
1289 wanted: Rc::new(Cell::new(false)),
1290 owner: self.owner(),
1291 activity: self.activity.clone(),
1292 })
1293 }
1294}
1295
1296struct Player<T: 'static> {
1298 label: Rc<str>,
1299 steps: Rc<dyn Fn() -> Vec<Step<T>>>,
1300 value: Signal<T>,
1301 running: Signal<bool>,
1302 generation: Rc<Cell<u64>>,
1304 wanted: Rc<Cell<bool>>,
1306 owner: Owner,
1307 activity: Option<Rc<Activity>>,
1308}
1309
1310impl<T: Animate> Player<T> {
1311 fn animation(&self) -> Animation<T> {
1312 Animation {
1313 value: self.value.read_only(),
1314 running: self.running.read_only(),
1315 }
1316 }
1317
1318 fn stop(&self) {
1320 self.generation.set(self.generation.get() + 1);
1321 set_changed(self.running, false);
1322 }
1323
1324 fn play(&self, looping: bool) {
1327 self.stop();
1328 let label = Rc::clone(&self.label);
1329 let Some((steps, origin, last)) = guarded(&label, || {
1332 let steps = untrack(&*self.steps);
1333 let origin = untrack(|| self.value.try_get())?;
1334 let last = steps.iter().rev().find_map(|step| step.to.clone());
1335 let last = last.unwrap_or_else(|| origin.clone());
1336 Some((steps, origin, last))
1337 })
1338 .flatten() else {
1339 return;
1340 };
1341 if steps.is_empty() {
1342 return;
1343 }
1344 let length: u64 = steps.iter().map(|step| step.times().1).sum();
1345 let looping = looping && length > 0;
1346 set_changed(self.running, true);
1347 let current = self.generation.get();
1348 let (generation, wanted) = (Rc::clone(&self.generation), Rc::clone(&self.wanted));
1349 let (value, running, owner) = (self.value, self.running, self.owner);
1350 let step_label = Rc::clone(&label);
1351 let mut started = start_time();
1352 let mut round = 0;
1353 start(
1354 label,
1355 self.activity.as_ref().map(Busy::new),
1356 Box::new(move |now| {
1357 if generation.get() != current {
1358 return false;
1359 }
1360 let begun = *started.get_or_insert(now);
1361 let at = now.saturating_duration_since(begun).as_micros();
1362 let at = u64::try_from(at).unwrap_or(u64::MAX);
1363 let (now_round, within) = if looping {
1364 (at / length, at % length)
1365 } else {
1366 (0, at)
1367 };
1368 let ended = now_round > round && !wanted.get();
1369 round = now_round;
1370 let spot = guarded(&step_label, || {
1371 if ended {
1372 return Spot::Ended(last.clone());
1373 }
1374 spot(&steps, if round == 0 { &origin } else { &last }, within)
1375 });
1376 let (next, sleep) = match spot {
1377 Some(Spot::Moving(next)) => (next, None),
1378 Some(Spot::Holding(next, until)) => (next, Some(round * length + until)),
1379 Some(Spot::Ended(next)) => {
1380 guarded(&step_label, || set_changed(value, next));
1382 running.try_set(false);
1383 return false;
1384 }
1385 None => {
1388 running.try_set(false);
1389 return false;
1390 }
1391 };
1392 if untrack(|| value.try_with(|_| ())).is_none() {
1394 return false;
1395 }
1396 if guarded(&step_label, || set_changed(value, next)).is_none() {
1397 running.try_set(false);
1398 return false;
1399 }
1400 if let Some(until) = sleep {
1401 sleep_until(Nap {
1402 deadline: begun + Duration::from_micros(until),
1403 owner,
1404 play: (Rc::clone(&generation), current),
1405 });
1406 }
1407 true
1408 }),
1409 );
1410 }
1411}