Skip to main content

crabshell_ui/
animation.rs

1//! Animations: values that move toward a target over a [`Transition`],
2//! and the clock the platform advances only while one is running, so a
3//! shell where nothing moves wakes for nothing.
4
5use 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/// How an animation moves from its start to its end: what fraction of
19/// the way it has gone at each fraction of its time.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub enum Easing {
22  /// The same speed all the way.
23  Linear,
24  /// Starts slow.
25  InQuad,
26  /// Ends slow.
27  OutQuad,
28  /// Starts and ends slow.
29  InOutQuad,
30  /// Starts slower.
31  InCubic,
32  /// Ends slower. The default: it settles gently, as most interface
33  /// motion should.
34  #[default]
35  OutCubic,
36  /// Starts and ends slower.
37  InOutCubic,
38  /// Starts slow, along a quarter sine wave.
39  InSine,
40  /// Ends slow, along a quarter sine wave.
41  OutSine,
42  /// Starts and ends slow, along half a sine wave.
43  InOutSine,
44  /// Starts slower than a cubic.
45  InQuart,
46  /// Ends slower than a cubic.
47  OutQuart,
48  /// Starts and ends slower than a cubic.
49  InOutQuart,
50  /// Starts slower still.
51  InQuint,
52  /// Ends slower still.
53  OutQuint,
54  /// Starts and ends slower still.
55  InOutQuint,
56  /// Barely moves, then rushes in: each tenth of the time doubles it.
57  InExpo,
58  /// Rushes out, then barely moves.
59  OutExpo,
60  /// Barely moves at both ends.
61  InOutExpo,
62  /// Starts slow along a quarter circle.
63  InCirc,
64  /// Ends slow along a quarter circle.
65  OutCirc,
66  /// Starts and ends slow along quarter circles.
67  InOutCirc,
68  /// Pulls back about 10% behind the start, then goes.
69  InBack,
70  /// Runs about 10% past the end, then settles back.
71  OutBack,
72  /// Pulls back at the start and runs past the end.
73  InOutBack,
74  /// A cubic Bézier from (0, 0) to (1, 1) through the control points
75  /// `(x1, y1)` and `(x2, y2)`, as CSS's `cubic-bezier`. The x values are
76  /// kept within 0 to 1.
77  Bezier(f32, f32, f32, f32),
78  /// Cubic Bézier segments joined end to end, as Qt's
79  /// `Easing.BezierSpline`. Each is `[c1x, c1y, c2x, c2y, end_x, end_y]`:
80  /// two control points and an end, starting from the previous end, the
81  /// first from (0, 0). The last must end at (1, 1), and the ends' x
82  /// values must never go back. A spline that breaks either rule, is
83  /// empty, or holds a number that isn't finite moves linearly instead.
84  /// A control point's x is kept within its segment.
85  ///
86  /// Material 3's emphasized curve:
87  ///
88  /// ```
89  /// use crabshell_ui::{Easing, Transition};
90  ///
91  /// const EMPHASIZED: Easing = Easing::Spline(&[
92  ///     [0.05, 0.0, 0.133333, 0.06, 0.166666, 0.4],
93  ///     [0.208333, 0.82, 0.25, 1.0, 1.0, 1.0],
94  /// ]);
95  /// const ENTER: Transition = Transition::new(500).easing(EMPHASIZED);
96  /// ```
97  Spline(&'static [[f32; 6]]),
98}
99
100impl Easing {
101  /// How far along the animation is, from 0 to 1 (Back, a Bézier or a
102  /// spline may overshoot either end), when `t` of its time has passed.
103  /// `t` is kept within 0 to 1.
104  pub fn value_at(self, t: f32) -> f32 {
105    use std::f32::consts::PI;
106    // Back's overshoot, the usual constant: about 10%.
107    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      // The formulas miss their ends by 2^-10, so the ends are exact.
132      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
153/// A spline's y where its x is `x`, or `x` itself for a spline that
154/// breaks the rules [`Easing::Spline`] gives.
155fn 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
177/// The y of a cubic Bézier from `start` through the control points and
178/// to the end in `segment` (laid out as in [`Easing::Spline`]) at the
179/// point whose x is `x`, found by bisection: x grows with the curve's
180/// parameter once both control x values are kept between the ends.
181fn 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/// How long an animation takes, how it moves, and how long it waits
201/// first. Copy it into styles and constants like a color.
202#[derive(Clone, Copy, Debug, PartialEq)]
203pub struct Transition {
204  /// The time it takes, in milliseconds. 0 jumps straight to the end.
205  pub ms: u32,
206  /// How it moves.
207  pub easing: Easing,
208  /// How long it waits before it moves, in milliseconds.
209  pub delay: u32,
210  /// Whether a [`Cx::cycle`] comes back each round instead of starting
211  /// over. Nothing else reads it.
212  pub alternate: bool,
213}
214
215impl Transition {
216  /// A transition of `ms` milliseconds, easing out, with no delay.
217  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  /// The same transition moving as `easing` says.
227  pub const fn easing(self, easing: Easing) -> Transition {
228    Transition { easing, ..self }
229  }
230
231  /// The same transition waiting `ms` milliseconds before it moves.
232  pub const fn delay(self, ms: u32) -> Transition {
233    Transition { delay: ms, ..self }
234  }
235
236  /// The same transition coming back after each round of a
237  /// [`Cx::cycle`], so it goes 0 to 1 to 0, each way taking `ms`.
238  pub const fn alternate(self) -> Transition {
239    Transition {
240      alternate: true,
241      ..self
242    }
243  }
244
245  /// Whether it takes no time at all, so the new value shows at once.
246  pub(crate) fn is_instant(self) -> bool {
247    self.ms == 0 && self.delay == 0
248  }
249
250  /// Whether an animation that started at `start` is still waiting out
251  /// its delay at `now`, so nothing it moves has changed yet.
252  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  /// How far along an animation that started at `start` is at `now`,
257  /// eased, and whether it has ended. It stays at 0 through the delay.
258  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/// The spring a [`Cx::spring`] value follows its target on, as Qt's
276/// `SpringAnimation`. Time is in seconds and distance in the value's own
277/// units. The target pulls the value with `stiffness` times the distance,
278/// per second squared, and friction slows it as `damping` says, as a
279/// ratio: 1 comes to rest as fast as it can without passing the target,
280/// less overshoots and bounces, more creeps in. The default, 700 and 0.9,
281/// is Material 3's default spatial spring; its expressive one is 380 and
282/// 0.8.
283#[derive(Clone, Copy, Debug, PartialEq)]
284pub struct Spring {
285  /// How hard the target pulls, per second squared: higher is faster.
286  pub stiffness: f32,
287  /// The damping ratio: 1 never passes the target, less bounces.
288  pub damping: f32,
289}
290
291impl Spring {
292  /// A spring of `stiffness` and `damping` ratio.
293  pub const fn new(stiffness: f32, damping: f32) -> Spring {
294    Spring { stiffness, damping }
295  }
296
297  /// Whether it can move anything: a stiffness above 0, a damping of 0
298  /// or more, both finite.
299  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  /// Moves the value `x`, with speed `v`, toward `goal` over `seconds`,
307  /// in implicit Euler steps of at most a millisecond, which stay stable
308  /// whatever the spring and the step.
309  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
327/// The most time one tick moves a spring: a frame that comes late moves
328/// it this far and no more, so a stall can't cost a long run of steps.
329const SPRING_MAX_STEP: f64 = 0.25;
330
331/// The distance from its target a spring counts as at rest within, and the
332/// speed per second below which it counts as still.
333const SPRING_REST: (f64, f64) = (0.001, 0.01);
334
335/// A value an animation can move between two of: `lerp` gives the value
336/// `t` of the way from `self` to `to`, where `t` may stray a little past 0
337/// or 1 for an easing that overshoots.
338pub trait Animate: Clone + PartialEq + 'static {
339  /// The value `t` of the way from `self` to `to`.
340  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
372/// One running animation: advanced to a time, it says whether it still
373/// runs.
374type Step = Box<dyn FnMut(Instant) -> bool>;
375
376/// A step on the clock, named for log lines and counted in its item.
377type Running = (Rc<str>, Option<Busy>, Step);
378
379/// How many animations run inside one item of a list with an exit, and
380/// the item around it, so a leaving item knows when everything in it has
381/// stopped.
382pub(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  /// Adds `by` to this item's count and every item's around it.
396  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
407/// One animation counted as running in its item until it is dropped.
408pub(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
423/// A leaving item waiting for everything in it to stop: `done` runs at
424/// the first tick that finds nothing running there, unless `owner`, its
425/// exit's, went first.
426struct Watch {
427  owner: Owner,
428  activity: Rc<Activity>,
429  done: Box<dyn FnOnce()>,
430}
431
432thread_local! {
433  /// Everything is on one thread, so the clock is too. Each animation is
434  /// named for log lines.
435  static RUNNING: RefCell<Vec<Running>> = const { RefCell::new(Vec::new()) };
436  static WATCHES: RefCell<Vec<Watch>> = const { RefCell::new(Vec::new()) };
437  /// When the clock last ticked.
438  static LAST_TICK: Cell<Option<Instant>> = const { Cell::new(None) };
439}
440
441/// Starts `step`, named `label` for log lines and counted in `busy`'s
442/// item, at the next [`advance_animations`].
443pub(crate) fn start(label: Rc<str>, busy: Option<Busy>, step: Step) {
444  RUNNING.with(|running| running.borrow_mut().push((label, busy, step)));
445}
446
447/// Runs `done` at the first tick that finds nothing running in
448/// `activity`'s item, while `owner` lasts. The clock ticks for it, so an
449/// item with nothing moving is judged at once.
450pub(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
460/// Runs the watches whose items have stopped. Judged before the steps
461/// move, so an animation started in the flush after the last tick, as
462/// one that follows another's end, still counts.
463fn 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
483/// When an animation starting now should count from: the clock's last
484/// tick while it runs, so one that replaces another moves at the very
485/// next tick, or `None` when it is still, so the first tick is time 0.
486pub(crate) fn start_time() -> Option<Instant> {
487  if animating() {
488    LAST_TICK.with(Cell::get)
489  } else {
490    None
491  }
492}
493
494/// Whether an animation is running, so the platform should advance the
495/// clock soon. `false` means nothing moves and nothing needs waking.
496pub fn animating() -> bool {
497  RUNNING.with(|running| !running.borrow().is_empty())
498    || WATCHES.with(|watches| !watches.borrow().is_empty())
499}
500
501/// Advances every running animation to `now`, writing their values, and
502/// returns whether any still runs. Each one starts at the first call after
503/// it began, so `now` there is its time 0. One that panics is logged and
504/// dropped.
505pub 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    // Animations started while these ran go after them.
525    let mut running = running.borrow_mut();
526    kept.append(&mut running);
527    *running = kept;
528  });
529  let still = animating();
530  if !still {
531    // The clock stops, so the next animation counts from its own first
532    // tick, not this one.
533    LAST_TICK.with(|last| last.set(None));
534  }
535  still
536}
537
538/// Drops a finished step, and the user's values it holds, isolated.
539fn 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
548/// Runs `f`, a config's closure for the animation `label`, and logs a
549/// panic as that animation's, giving `None`.
550fn 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
563/// Sets `signal` to `value` only when that changes it, since a set always
564/// tells its readers.
565fn 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
571/// A value moving toward its target, from [`Cx::animation`] or
572/// [`Cx::spring`]: a `Copy`
573/// handle to its value and to whether it moves.
574pub 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  /// The value, as [`Cx::animate`] gives it.
589  pub fn value(&self) -> ReadSignal<T> {
590    self.value
591  }
592
593  /// `true` from the moment a new target starts it, through its delay,
594  /// until it settles there. It turns `false` once per animation, so an
595  /// effect on it is the place for what follows.
596  pub fn running(&self) -> ReadSignal<bool> {
597    self.running
598  }
599}
600
601impl Cx {
602  /// A value that follows `target`, moving to each new one over
603  /// `transition` instead of jumping. It starts at `target`'s first value.
604  /// A new target while it moves starts a new animation from where it is.
605  /// The animation goes when this context's owner does. It is
606  /// [`Cx::animation`]'s value.
607  ///
608  /// ```
609  /// use crabshell_ui::{Cx, Transition};
610  ///
611  /// fn slide(cx: &Cx) {
612  ///     let open = cx.signal(false);
613  ///     let offset = cx.animate(move || if open.get() { 0.0 } else { -200.0 }, Transition::new(200));
614  ///     // Read `offset.get()` in a binding, such as a style's width.
615  /// }
616  /// ```
617  #[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  /// A value that follows `target` as [`Cx::animate`]'s does, and whether
627  /// it moves. A panic in `target` is logged with this call's place, and
628  /// the value stays where it was.
629  ///
630  /// ```
631  /// use crabshell_ui::{Cx, Transition};
632  ///
633  /// fn slide_in_then_focus(cx: &Cx) {
634  ///     let open = cx.signal(false);
635  ///     let ready = cx.signal(false);
636  ///     let slide = cx.animation(move || if open.get() { 0.0 } else { -200.0 }, Transition::new(200));
637  ///     cx.effect(move || {
638  ///         if open.get() && !slide.running().get() {
639  ///             ready.set(true);
640  ///         }
641  ///     });
642  /// }
643  /// ```
644  #[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  /// [`Cx::animation`], logged as `what` at the caller's place.
654  #[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    // Bumped by each new target, so the animation it replaces stops.
669    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      // Read as each move starts, so a binding can pick its curve.
685      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      // No time to take: the new value shows in this flush.
698      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            // The value is still `from`; setting it would rerun its readers.
717            return true;
718          }
719          let (t, ended) = transition.progress(begun, now);
720          // `lerp` and `clone` may be a config's own; a panic ends the
721          // animation with `running` false, so whatever waits on it runs.
722          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          // A value whose owner is gone stops its animation.
729          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  /// Progress from 0 to 1, eased, repeating every `transition.ms` while
744  /// `running` gives `true`, for spinners and pulses. With
745  /// [`Transition::alternate`] it comes back, 0 to 1 to 0, each way taking
746  /// `ms`. It waits out the delay once, at the start. When `running` turns
747  /// `false`, the round it is in runs to its end, then it rests at 0 and
748  /// the clock stops; `true` again before then keeps it going, and after
749  /// it begins at 0. A 0 ms cycle never moves. A panic in `running` is
750  /// logged with this call's place and ends the cycle after its round.
751  ///
752  /// ```
753  /// use crabshell_ui::{Cx, Easing, Transition};
754  ///
755  /// const SPIN: Transition = Transition::new(1000).easing(Easing::Linear);
756  /// const PULSE: Transition = Transition::new(600).easing(Easing::InOutSine).alternate();
757  ///
758  /// fn busy(cx: &Cx) {
759  ///     let loading = cx.signal(true);
760  ///     let turn = cx.cycle(move || loading.get(), SPIN); // turns: turn.get() * 360.0
761  ///     let glow = cx.cycle(move || loading.get(), PULSE); // an opacity: 0.5 + glow.get() / 2.0
762  /// }
763  /// ```
764  #[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    // What `running` last gave, and whether a round is on the clock.
774    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      // Round 0 is the delay, then 1, 2 and on.
793      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  /// The time since `running` turned `true`, updated at each tick of the
823  /// animation clock while it stays true, as Qt's `FrameAnimation` gives.
824  /// Nothing ticks while it is false, and the time stays where it was
825  /// until the next run starts again from 0. A panic in `running` is
826  /// logged with this call's place and stops it.
827  ///
828  /// ```
829  /// use crabshell_ui::Cx;
830  ///
831  /// fn wave(cx: &Cx) {
832  ///     let shown = cx.signal(true);
833  ///     let time = cx.frames(move || shown.get());
834  ///     // A bar's height: 10.0 + 5.0 * (time.get().as_secs_f32() * 6.0).sin()
835  /// }
836  /// ```
837  #[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  /// A value that follows `target` on `spring`, as Qt's
875  /// `SpringAnimation`: a new target while it moves keeps its speed, so a
876  /// value chasing a moving target never stops dead. It starts at
877  /// `target`'s first value and comes to rest exactly on the target, when
878  /// the clock stops. A target that isn't finite, or a spring that isn't
879  /// valid (see [`Spring`]), jumps there at once. A panic in `target` is
880  /// logged with this call's place, and the value stops where it is. The
881  /// [`Animation`]'s `running()` is true from a new target until it comes
882  /// to rest, and never for a jump.
883  ///
884  /// ```
885  /// use crabshell_ui::{Cx, Spring};
886  ///
887  /// fn indicator(cx: &Cx) {
888  ///     let hovered = cx.signal(0_usize);
889  ///     let x = cx.spring(move || hovered.get() as f32 * 40.0, Spring::new(380.0, 0.8));
890  ///     // Read `x.value().get()` in a binding, such as a style's padding.
891  /// }
892  /// ```
893  #[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    // Where the step on the clock heads, and whether there is one. A goal
906    // that isn't finite stops it.
907    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        // One on the clock stops at its next tick.
928        set_changed(running, false);
929        return;
930      }
931      if ticking.get() {
932        // Still on the clock after a jump, it moves again.
933        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          // A value that started out not finite lands at once.
964          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}