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,
208 pub easing: Easing,
210 pub delay: u32,
212 pub alternate: bool,
215}
216
217impl Transition {
218 pub const fn new(ms: u32) -> Transition {
220 Transition {
221 ms,
222 easing: Easing::OutCubic,
223 delay: 0,
224 alternate: false,
225 }
226 }
227
228 pub const fn easing(self, easing: Easing) -> Transition {
230 Transition { easing, ..self }
231 }
232
233 pub const fn delay(self, ms: u32) -> Transition {
235 Transition { delay: ms, ..self }
236 }
237
238 pub const fn alternate(self) -> Transition {
241 Transition {
242 alternate: true,
243 ..self
244 }
245 }
246
247 pub(crate) fn is_instant(self) -> bool {
249 self.ms == 0 && self.delay == 0
250 }
251
252 pub(crate) fn waiting(self, start: Instant, now: Instant) -> bool {
255 now.saturating_duration_since(start) < Duration::from_millis(self.delay.into())
256 }
257
258 pub(crate) fn progress(self, start: Instant, now: Instant) -> (f32, bool) {
261 let elapsed = now.saturating_duration_since(start).as_secs_f32() * 1000.0 - self.delay as f32;
262 if elapsed < 0.0 {
263 return (0.0, false);
264 }
265 if self.ms == 0 {
266 return (1.0, true);
267 }
268 let t = elapsed / self.ms as f32;
269 if t >= 1.0 {
270 (1.0, true)
271 } else {
272 (self.easing.value_at(t), false)
273 }
274 }
275}
276
277#[derive(Clone, Copy, Debug, PartialEq)]
286pub struct Spring {
287 pub stiffness: f32,
289 pub damping: f32,
291}
292
293impl Spring {
294 pub const fn new(stiffness: f32, damping: f32) -> Spring {
296 Spring { stiffness, damping }
297 }
298
299 fn is_valid(self) -> bool {
302 self.stiffness.is_finite()
303 && self.stiffness > 0.0
304 && self.damping.is_finite()
305 && self.damping >= 0.0
306 }
307
308 pub(crate) fn advance(self, x: &mut f64, v: &mut f64, goal: f64, seconds: f64) {
312 let k = f64::from(self.stiffness);
313 let c = 2.0 * f64::from(self.damping) * k.sqrt();
314 let steps = (seconds * 1000.0).ceil().max(1.0);
315 let dt = seconds / steps;
316 for _ in 0..steps as u32 {
317 *v = (*v - dt * k * (*x - goal)) / (1.0 + dt * c + dt * dt * k);
318 *x += dt * *v;
319 }
320 }
321}
322
323impl Default for Spring {
324 fn default() -> Spring {
325 Spring::new(700.0, 0.9)
326 }
327}
328
329const SPRING_MAX_STEP: f64 = 0.25;
332
333const SPRING_REST: (f64, f64) = (0.001, 0.01);
336
337#[derive(Clone, Copy, Debug, PartialEq)]
342pub struct Step<T> {
343 to: Option<T>,
344 transition: Transition,
345}
346
347impl<T> Step<T> {
348 pub const fn to(value: T, transition: Transition) -> Step<T> {
351 Step {
352 to: Some(value),
353 transition,
354 }
355 }
356
357 pub const fn hold(ms: u32) -> Step<T> {
360 Step {
361 to: None,
362 transition: Transition::new(0).delay(ms),
363 }
364 }
365
366 fn times(&self) -> (u64, u64) {
369 let moves = u64::from(self.transition.delay) * 1000;
370 (moves, moves + u64::from(self.transition.ms) * 1000)
371 }
372}
373
374impl<T: Animate> IntoProp<Vec<Step<T>>> for Vec<Step<T>> {
375 fn into_prop(self) -> Prop<Vec<Step<T>>> {
376 Prop(PropKind::Value(self))
377 }
378}
379
380impl<T: Animate, const N: usize> IntoProp<Vec<Step<T>>> for [Step<T>; N] {
382 fn into_prop(self) -> Prop<Vec<Step<T>>> {
383 Prop(PropKind::Value(self.into()))
384 }
385}
386
387enum Spot<T> {
389 Moving(T),
391 Holding(T, u64),
394 Ended(T),
396}
397
398fn spot<T: Animate>(steps: &[Step<T>], from: &T, at: u64) -> Spot<T> {
401 let mut from = from.clone();
402 let mut begins = 0;
403 for (i, step) in steps.iter().enumerate() {
404 let (moves, ends) = step.times();
405 if at < begins + moves {
406 let mut until = begins + moves;
408 if step.to.is_none() {
409 for next in &steps[i + 1..] {
410 until += next.times().0;
411 if next.to.is_some() {
412 break;
413 }
414 }
415 }
416 return Spot::Holding(from, until);
417 }
418 if let Some(to) = &step.to {
419 if at < begins + ends {
420 let t = (at - begins - moves) as f32 / (ends - moves) as f32;
421 return Spot::Moving(from.lerp(to, step.transition.easing.value_at(t)));
422 }
423 from = to.clone();
424 }
425 begins += ends;
426 }
427 Spot::Ended(from)
428}
429
430pub trait Animate: Clone + PartialEq + 'static {
434 fn lerp(&self, to: &Self, t: f32) -> Self;
436}
437
438impl Animate for f32 {
439 fn lerp(&self, to: &f32, t: f32) -> f32 {
440 self + (to - self) * t
441 }
442}
443
444impl Animate for Point {
445 fn lerp(&self, to: &Point, t: f32) -> Point {
446 Point::new(self.x.lerp(&to.x, t), self.y.lerp(&to.y, t))
447 }
448}
449
450impl Animate for Color {
451 fn lerp(&self, to: &Color, t: f32) -> Color {
452 let channel = |a: u8, b: u8| {
453 f32::from(a)
454 .lerp(&f32::from(b), t)
455 .round()
456 .clamp(0.0, 255.0) as u8
457 };
458 Color::rgba(
459 channel(self.r, to.r),
460 channel(self.g, to.g),
461 channel(self.b, to.b),
462 channel(self.a, to.a),
463 )
464 }
465}
466
467type Tick = Box<dyn FnMut(Instant) -> bool>;
470
471type Running = (Rc<str>, Option<Busy>, Tick);
473
474pub(crate) struct Activity {
478 running: Cell<usize>,
479 outer: Option<Rc<Activity>>,
480}
481
482impl Activity {
483 pub(crate) fn new(outer: Option<Rc<Activity>>) -> Rc<Activity> {
484 Rc::new(Activity {
485 running: Cell::new(0),
486 outer,
487 })
488 }
489
490 fn add(&self, by: isize) {
492 let mut at = Some(self);
493 while let Some(activity) = at {
494 activity
495 .running
496 .set(activity.running.get().wrapping_add_signed(by));
497 at = activity.outer.as_deref();
498 }
499 }
500}
501
502pub(crate) struct Busy(Rc<Activity>);
504
505impl Busy {
506 pub(crate) fn new(activity: &Rc<Activity>) -> Busy {
507 activity.add(1);
508 Busy(Rc::clone(activity))
509 }
510}
511
512impl Drop for Busy {
513 fn drop(&mut self) {
514 self.0.add(-1);
515 }
516}
517
518struct Watch {
522 owner: Owner,
523 activity: Rc<Activity>,
524 done: Box<dyn FnOnce()>,
525}
526
527thread_local! {
528 static RUNNING: RefCell<Vec<Running>> = const { RefCell::new(Vec::new()) };
531 static WATCHES: RefCell<Vec<Watch>> = const { RefCell::new(Vec::new()) };
532 static ASLEEP: RefCell<Vec<Sleeper>> = const { RefCell::new(Vec::new()) };
534 static SLEEP: Cell<Option<Nap>> = const { Cell::new(None) };
536 static LAST_TICK: Cell<Option<Instant>> = const { Cell::new(None) };
538}
539
540pub(crate) fn start(label: Rc<str>, busy: Option<Busy>, step: Tick) {
543 RUNNING.with(|running| running.borrow_mut().push((label, busy, step)));
544}
545
546pub(crate) struct Nap {
550 pub(crate) deadline: Instant,
551 pub(crate) owner: Owner,
552 pub(crate) play: (Rc<Cell<u64>>, u64),
553}
554
555struct Sleeper {
557 nap: Nap,
558 running: Running,
559}
560
561impl Nap {
562 fn stale(&self) -> bool {
564 self.owner.is_disposed() || self.play.0.get() != self.play.1
565 }
566}
567
568pub(crate) fn sleep_until(nap: Nap) {
572 SLEEP.with(|sleep| sleep.set(Some(nap)));
573}
574
575fn sweep_asleep() {
578 let gone = ASLEEP.with(|asleep| {
579 let mut asleep = asleep.borrow_mut();
580 let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut *asleep)
581 .into_iter()
582 .partition(|sleeper| sleeper.nap.stale());
583 *asleep = kept;
584 gone
585 });
586 for Sleeper {
587 running: (label, busy, step),
588 ..
589 } in gone
590 {
591 drop(busy);
592 drop_isolated(&label, step);
593 }
594}
595
596pub(crate) fn next_wake() -> Option<Instant> {
598 sweep_asleep();
599 ASLEEP.with(|asleep| {
600 let asleep = asleep.borrow();
601 asleep.iter().map(|sleeper| sleeper.nap.deadline).min()
602 })
603}
604
605pub(crate) fn wake(now: Instant) {
608 sweep_asleep();
609 let due: Vec<Running> = ASLEEP.with(|asleep| {
610 let mut asleep = asleep.borrow_mut();
611 let (due, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut *asleep)
612 .into_iter()
613 .partition(|sleeper| sleeper.nap.deadline <= now);
614 *asleep = kept;
615 due.into_iter().map(|sleeper| sleeper.running).collect()
616 });
617 RUNNING.with(|running| running.borrow_mut().extend(due));
618}
619
620#[cfg(test)]
622pub(crate) fn asleep() -> usize {
623 ASLEEP.with(|asleep| asleep.borrow().len())
624}
625
626pub(crate) fn watch(owner: Owner, activity: Rc<Activity>, done: impl FnOnce() + 'static) {
630 WATCHES.with(|watches| {
631 watches.borrow_mut().push(Watch {
632 owner,
633 activity,
634 done: Box::new(done),
635 });
636 });
637}
638
639fn judge_watches() {
643 let watches = WATCHES.with(|watches| std::mem::take(&mut *watches.borrow_mut()));
644 let mut kept = Vec::with_capacity(watches.len());
645 for watch in watches {
646 if watch.owner.is_disposed() {
647 continue;
648 }
649 if watch.activity.running.get() == 0 {
650 (watch.done)();
651 } else {
652 kept.push(watch);
653 }
654 }
655 WATCHES.with(|watches| {
656 let mut watches = watches.borrow_mut();
657 kept.append(&mut watches);
658 *watches = kept;
659 });
660}
661
662pub(crate) fn start_time() -> Option<Instant> {
666 if animating() {
667 LAST_TICK.with(Cell::get)
668 } else {
669 None
670 }
671}
672
673pub fn animating() -> bool {
676 RUNNING.with(|running| !running.borrow().is_empty())
677 || WATCHES.with(|watches| !watches.borrow().is_empty())
678}
679
680pub fn advance_animations(now: Instant) -> bool {
685 LAST_TICK.with(|last| last.set(Some(now)));
686 judge_watches();
687 let steps = RUNNING.with(|running| std::mem::take(&mut *running.borrow_mut()));
688 let mut kept = Vec::with_capacity(steps.len());
689 for (label, busy, mut step) in steps {
690 let ran = panic::catch_unwind(AssertUnwindSafe(|| step(now)));
691 let sleep = SLEEP.with(Cell::take);
692 match ran {
693 Ok(true) => match sleep {
694 Some(nap) => {
695 let running = (label, busy, step);
696 ASLEEP.with(|asleep| asleep.borrow_mut().push(Sleeper { nap, running }));
697 }
698 None => kept.push((label, busy, step)),
699 },
700 Ok(false) => drop_isolated(&label, step),
701 Err(payload) => {
702 tracing::error!(
703 "animation {label} panicked and stops: {}",
704 panic_message(payload.as_ref())
705 );
706 drop_isolated(&label, step);
707 }
708 }
709 }
710 RUNNING.with(|running| {
711 let mut running = running.borrow_mut();
713 kept.append(&mut running);
714 *running = kept;
715 });
716 let still = animating();
717 if !still {
718 LAST_TICK.with(|last| last.set(None));
721 }
722 still
723}
724
725fn drop_isolated(label: &str, step: Tick) {
727 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(step))) {
728 tracing::error!(
729 "dropping animation {label} panicked: {}",
730 panic_message(payload.as_ref())
731 );
732 }
733}
734
735fn guarded<R>(label: &str, f: impl FnOnce() -> R) -> Option<R> {
738 match panic::catch_unwind(AssertUnwindSafe(f)) {
739 Ok(value) => Some(value),
740 Err(payload) => {
741 tracing::error!(
742 "animation {label} panicked and stops: {}",
743 panic_message(payload.as_ref())
744 );
745 None
746 }
747 }
748}
749
750fn set_changed<T: PartialEq + 'static>(signal: Signal<T>, value: T) {
753 if untrack(|| signal.try_with(|old| *old != value)) == Some(true) {
754 signal.try_set(value);
755 }
756}
757
758pub struct Animation<T: 'static> {
762 value: ReadSignal<T>,
763 running: ReadSignal<bool>,
764}
765
766impl<T> Clone for Animation<T> {
767 fn clone(&self) -> Self {
768 *self
769 }
770}
771
772impl<T> Copy for Animation<T> {}
773
774impl<T> Animation<T> {
775 pub fn value(&self) -> ReadSignal<T> {
777 self.value
778 }
779
780 pub fn running(&self) -> ReadSignal<bool> {
786 self.running
787 }
788}
789
790impl Cx {
791 #[track_caller]
809 pub fn animate<T: Animate>(
810 &self,
811 target: impl FnMut() -> T + 'static,
812 transition: impl IntoProp<Transition>,
813 ) -> ReadSignal<T> {
814 self.follow("cx.animate", target, transition).value
815 }
816
817 #[track_caller]
836 pub fn animation<T: Animate>(
837 &self,
838 target: impl FnMut() -> T + 'static,
839 transition: impl IntoProp<Transition>,
840 ) -> Animation<T> {
841 self.follow("cx.animation", target, transition)
842 }
843
844 #[track_caller]
846 fn follow<T: Animate>(
847 &self,
848 what: &str,
849 mut target: impl FnMut() -> T + 'static,
850 transition: impl IntoProp<Transition>,
851 ) -> Animation<T> {
852 let label: Rc<str> = format!("{what} at {}", std::panic::Location::caller()).into();
853 let transition = transition.into_prop().shared();
854 let activity = self.activity.clone();
855 let first = untrack(&mut target);
856 let value = self.signal(first.clone());
857 let running = self.signal(false);
858 let mut last = first;
859 let generation = Rc::new(Cell::new(0_u64));
861 let mut broken = false;
862 self.effect(move || {
863 if broken {
864 return;
865 }
866 let Some(to) = guarded(&label, &mut target) else {
867 broken = true;
868 generation.set(generation.get() + 1);
869 set_changed(running, false);
870 return;
871 };
872 if to == last {
873 return;
874 }
875 let Some(transition) = guarded(&label, || untrack(&*transition)) else {
877 broken = true;
878 generation.set(generation.get() + 1);
879 set_changed(running, false);
880 return;
881 };
882 last = to.clone();
883 let Some(from) = untrack(|| value.try_get()) else {
884 return;
885 };
886 let current = generation.get() + 1;
887 generation.set(current);
888 if transition.is_instant() {
890 value.try_set(to);
891 set_changed(running, false);
892 return;
893 }
894 set_changed(running, true);
895 let generation = Rc::clone(&generation);
896 let mut started = start_time();
897 let step_label = Rc::clone(&label);
898 start(
899 Rc::clone(&label),
900 activity.as_ref().map(Busy::new),
901 Box::new(move |now| {
902 if generation.get() != current {
903 return false;
904 }
905 let begun = *started.get_or_insert(now);
906 if transition.waiting(begun, now) {
907 return true;
909 }
910 let (t, ended) = transition.progress(begun, now);
911 let Some(next) = guarded(&step_label, || {
914 if ended { to.clone() } else { from.lerp(&to, t) }
915 }) else {
916 running.try_set(false);
917 return false;
918 };
919 let kept = value.try_set(next);
921 if ended {
922 running.try_set(false);
923 }
924 kept && !ended
925 }),
926 );
927 });
928 Animation {
929 value: value.read_only(),
930 running: running.read_only(),
931 }
932 }
933
934 #[track_caller]
956 pub fn cycle(
957 &self,
958 mut running: impl FnMut() -> bool + 'static,
959 transition: Transition,
960 ) -> ReadSignal<f32> {
961 let label: Rc<str> = format!("cx.cycle at {}", std::panic::Location::caller()).into();
962 let activity = self.activity.clone();
963 let value = self.signal(0.0_f32);
964 let wanted = Rc::new(Cell::new(false));
966 let ticking = Rc::new(Cell::new(false));
967 let mut broken = false;
968 self.effect(move || {
969 let on = !broken
970 && guarded(&label, &mut running).unwrap_or_else(|| {
971 broken = true;
972 false
973 });
974 wanted.set(on);
975 if !on || ticking.get() || transition.ms == 0 {
976 return;
977 }
978 ticking.set(true);
979 let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
980 let leg = f64::from(transition.ms);
981 let period = if transition.alternate { 2.0 * leg } else { leg };
982 let mut started = start_time();
983 let mut round = 0_u64;
985 start(
986 Rc::clone(&label),
987 activity.as_ref().map(Busy::new),
988 Box::new(move |now| {
989 let begun = *started.get_or_insert(now);
990 let elapsed = now.saturating_duration_since(begun).as_secs_f64() * 1000.0
991 - f64::from(transition.delay);
992 let now_round = if elapsed < 0.0 {
993 0
994 } else {
995 (elapsed / period) as u64 + 1
996 };
997 let ended = !wanted.get() && (now_round == 0 || now_round > round);
998 round = now_round;
999 if ended {
1000 ticking.set(false);
1001 value.try_set(0.0);
1002 return false;
1003 }
1004 let phase = elapsed.max(0.0) % period / leg;
1005 let t = if phase <= 1.0 { phase } else { 2.0 - phase };
1006 value.try_set(transition.easing.value_at(t as f32))
1007 }),
1008 );
1009 });
1010 value.read_only()
1011 }
1012
1013 #[track_caller]
1029 pub fn frames(&self, mut running: impl FnMut() -> bool + 'static) -> ReadSignal<Duration> {
1030 let label: Rc<str> = format!("cx.frames at {}", std::panic::Location::caller()).into();
1031 let activity = self.activity.clone();
1032 let value = self.signal(Duration::ZERO);
1033 let wanted = Rc::new(Cell::new(false));
1034 let ticking = Rc::new(Cell::new(false));
1035 let mut broken = false;
1036 self.effect(move || {
1037 let on = !broken
1038 && guarded(&label, &mut running).unwrap_or_else(|| {
1039 broken = true;
1040 false
1041 });
1042 wanted.set(on);
1043 if !on || ticking.get() {
1044 return;
1045 }
1046 ticking.set(true);
1047 let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
1048 let mut started = start_time();
1049 start(
1050 Rc::clone(&label),
1051 activity.as_ref().map(Busy::new),
1052 Box::new(move |now| {
1053 if !wanted.get() {
1054 ticking.set(false);
1055 return false;
1056 }
1057 let begun = *started.get_or_insert(now);
1058 value.try_set(now.saturating_duration_since(begun))
1059 }),
1060 );
1061 });
1062 value.read_only()
1063 }
1064
1065 #[track_caller]
1085 pub fn spring(
1086 &self,
1087 mut target: impl FnMut() -> f32 + 'static,
1088 spring: Spring,
1089 ) -> Animation<f32> {
1090 let label: Rc<str> = format!("cx.spring at {}", std::panic::Location::caller()).into();
1091 let activity = self.activity.clone();
1092 let first = untrack(&mut target);
1093 let value = self.signal(first);
1094 let running = self.signal(false);
1095 let mut last = first;
1096 let goal = Rc::new(Cell::new(first));
1099 let ticking = Rc::new(Cell::new(false));
1100 let mut broken = false;
1101 self.effect(move || {
1102 if broken {
1103 return;
1104 }
1105 let Some(to) = guarded(&label, &mut target) else {
1106 broken = true;
1107 goal.set(f32::NAN);
1108 set_changed(running, false);
1109 return;
1110 };
1111 if to == last {
1112 return;
1113 }
1114 last = to;
1115 goal.set(to);
1116 if !to.is_finite() || !spring.is_valid() {
1117 value.try_set(to);
1118 set_changed(running, false);
1120 return;
1121 }
1122 if ticking.get() {
1123 set_changed(running, true);
1125 return;
1126 }
1127 let Some(from) = untrack(|| value.try_get()) else {
1128 return;
1129 };
1130 ticking.set(true);
1131 set_changed(running, true);
1132 let (goal, ticking) = (Rc::clone(&goal), Rc::clone(&ticking));
1133 let (mut x, mut v) = (f64::from(from), 0.0);
1134 let mut previous = start_time();
1135 start(
1136 Rc::clone(&label),
1137 activity.as_ref().map(Busy::new),
1138 Box::new(move |now| {
1139 let to = f64::from(goal.get());
1140 if !to.is_finite() {
1141 ticking.set(false);
1142 set_changed(running, false);
1143 return false;
1144 }
1145 let seconds = previous.map_or(0.0, |previous| {
1146 now
1147 .saturating_duration_since(previous)
1148 .as_secs_f64()
1149 .min(SPRING_MAX_STEP)
1150 });
1151 previous = Some(now);
1152 spring.advance(&mut x, &mut v, to, seconds);
1153 let (near, slow) = SPRING_REST;
1154 let rest = !(x.is_finite() && v.is_finite()) || ((x - to).abs() < near && v.abs() < slow);
1156 if rest {
1157 x = to;
1158 }
1159 let kept = value.try_set(x as f32);
1160 if rest || !kept {
1161 ticking.set(false);
1162 set_changed(running, false);
1163 }
1164 kept && !rest
1165 }),
1166 );
1167 });
1168 Animation {
1169 value: value.read_only(),
1170 running: running.read_only(),
1171 }
1172 }
1173
1174 #[track_caller]
1211 pub fn sequence<T: Animate, K: PartialEq + 'static>(
1212 &self,
1213 initial: T,
1214 mut trigger: impl FnMut() -> K + 'static,
1215 steps: impl IntoProp<Vec<Step<T>>>,
1216 ) -> Animation<T> {
1217 let player = self.player("cx.sequence", initial, steps);
1218 let mut last = None;
1219 let mut broken = false;
1220 let animation = player.animation();
1221 self.effect(move || {
1222 if broken {
1223 return;
1224 }
1225 let Some(now) = guarded(&player.label, &mut trigger) else {
1226 broken = true;
1227 player.stop();
1228 return;
1229 };
1230 if last.as_ref().is_some_and(|last| *last != now) {
1231 player.play(false);
1232 }
1233 last = Some(now);
1234 });
1235 animation
1236 }
1237
1238 #[track_caller]
1261 pub fn sequence_now<T: Animate>(
1262 &self,
1263 initial: T,
1264 steps: impl IntoProp<Vec<Step<T>>>,
1265 ) -> Animation<T> {
1266 let player = self.player("cx.sequence_now", initial, steps);
1267 player.play(false);
1268 player.animation()
1269 }
1270
1271 #[track_caller]
1297 pub fn sequence_loop<T: Animate>(
1298 &self,
1299 initial: T,
1300 mut running: impl FnMut() -> bool + 'static,
1301 steps: impl IntoProp<Vec<Step<T>>>,
1302 ) -> Animation<T> {
1303 let player = self.player("cx.sequence_loop", initial, steps);
1304 let mut broken = false;
1305 let animation = player.animation();
1306 self.effect(move || {
1307 let on = !broken
1308 && guarded(&player.label, &mut running).unwrap_or_else(|| {
1309 broken = true;
1310 false
1311 });
1312 player.wanted.set(on);
1313 if on && untrack(|| player.running.try_get()) == Some(false) {
1314 player.play(true);
1315 }
1316 });
1317 animation
1318 }
1319
1320 #[track_caller]
1324 fn player<T: Animate>(
1325 &self,
1326 what: &str,
1327 initial: T,
1328 steps: impl IntoProp<Vec<Step<T>>>,
1329 ) -> Rc<Player<T>> {
1330 Rc::new(Player {
1331 label: format!("{what} at {}", std::panic::Location::caller()).into(),
1332 steps: steps.into_prop().shared(),
1333 value: self.signal(initial),
1334 running: self.signal(false),
1335 generation: Rc::new(Cell::new(0)),
1336 wanted: Rc::new(Cell::new(false)),
1337 owner: self.owner(),
1338 activity: self.activity.clone(),
1339 })
1340 }
1341}
1342
1343struct Player<T: 'static> {
1345 label: Rc<str>,
1346 steps: Rc<dyn Fn() -> Vec<Step<T>>>,
1347 value: Signal<T>,
1348 running: Signal<bool>,
1349 generation: Rc<Cell<u64>>,
1351 wanted: Rc<Cell<bool>>,
1353 owner: Owner,
1354 activity: Option<Rc<Activity>>,
1355}
1356
1357impl<T: Animate> Player<T> {
1358 fn animation(&self) -> Animation<T> {
1359 Animation {
1360 value: self.value.read_only(),
1361 running: self.running.read_only(),
1362 }
1363 }
1364
1365 fn stop(&self) {
1367 self.generation.set(self.generation.get() + 1);
1368 set_changed(self.running, false);
1369 }
1370
1371 fn play(&self, looping: bool) {
1374 self.stop();
1375 let label = Rc::clone(&self.label);
1376 let Some((steps, origin, last)) = guarded(&label, || {
1379 let steps = untrack(&*self.steps);
1380 let origin = untrack(|| self.value.try_get())?;
1381 let last = steps.iter().rev().find_map(|step| step.to.clone());
1382 let last = last.unwrap_or_else(|| origin.clone());
1383 let leading = steps
1387 .iter()
1388 .take_while(|step| step.transition.is_instant())
1389 .filter_map(|step| step.to.clone())
1390 .last();
1391 if let Some(leading) = leading {
1392 set_changed(self.value, leading);
1393 }
1394 Some((steps, origin, last))
1395 })
1396 .flatten() else {
1397 return;
1398 };
1399 let length: u64 = steps.iter().map(|step| step.times().1).sum();
1400 if length == 0 {
1402 return;
1403 }
1404 set_changed(self.running, true);
1405 let current = self.generation.get();
1406 let (generation, wanted) = (Rc::clone(&self.generation), Rc::clone(&self.wanted));
1407 let (value, running, owner) = (self.value, self.running, self.owner);
1408 let step_label = Rc::clone(&label);
1409 let mut started = start_time();
1410 let mut round = 0;
1411 start(
1412 label,
1413 self.activity.as_ref().map(Busy::new),
1414 Box::new(move |now| {
1415 if generation.get() != current {
1416 return false;
1417 }
1418 let begun = *started.get_or_insert(now);
1419 let at = now.saturating_duration_since(begun).as_micros();
1420 let at = u64::try_from(at).unwrap_or(u64::MAX);
1421 let (now_round, within) = if looping {
1422 (at / length, at % length)
1423 } else {
1424 (0, at)
1425 };
1426 let ended = now_round > round && !wanted.get();
1427 round = now_round;
1428 let spot = guarded(&step_label, || {
1429 if ended {
1430 return Spot::Ended(last.clone());
1431 }
1432 spot(&steps, if round == 0 { &origin } else { &last }, within)
1433 });
1434 let (next, sleep) = match spot {
1435 Some(Spot::Moving(next)) => (next, None),
1436 Some(Spot::Holding(next, until)) => (next, Some(round * length + until)),
1437 Some(Spot::Ended(next)) => {
1438 guarded(&step_label, || set_changed(value, next));
1440 running.try_set(false);
1441 return false;
1442 }
1443 None => {
1446 running.try_set(false);
1447 return false;
1448 }
1449 };
1450 if untrack(|| value.try_with(|_| ())).is_none() {
1452 return false;
1453 }
1454 if guarded(&step_label, || set_changed(value, next)).is_none() {
1455 running.try_set(false);
1456 return false;
1457 }
1458 if let Some(until) = sleep {
1459 sleep_until(Nap {
1460 deadline: begun + Duration::from_micros(until),
1461 owner,
1462 play: (Rc::clone(&generation), current),
1463 });
1464 }
1465 true
1466 }),
1467 );
1468 }
1469}