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, Prop, PropKind};
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/// One step of a [`Cx::sequence`]: a move to a value over a
336/// [`Transition`], or a hold that keeps the value for a while. Steps are
337/// built in `const`s, so a config keeps a whole sequence in a `const`
338/// array.
339#[derive(Clone, Copy, Debug, PartialEq)]
340pub struct Step<T> {
341  to: Option<T>,
342  transition: Transition,
343}
344
345impl<T> Step<T> {
346  /// A move from wherever the value is to `value`, over `transition`,
347  /// after its delay.
348  pub const fn to(value: T, transition: Transition) -> Step<T> {
349    Step {
350      to: Some(value),
351      transition,
352    }
353  }
354
355  /// A pause of `ms` milliseconds that keeps the value where it is, as
356  /// Qt's `PauseAnimation`.
357  pub const fn hold(ms: u32) -> Step<T> {
358    Step {
359      to: None,
360      transition: Transition::new(0).delay(ms),
361    }
362  }
363
364  /// When it starts to move and when it ends, in microseconds after it
365  /// begins. A hold never moves, so both are its end.
366  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
378/// A fixed array of steps, such as a `const` sequence.
379impl<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
385/// Where a play of a sequence is at a time.
386enum Spot<T> {
387  /// Moving, here.
388  Moving(T),
389  /// Holding here until the time given, in microseconds, when the value
390  /// next changes.
391  Holding(T, u64),
392  /// Past its last step, here.
393  Ended(T),
394}
395
396/// Where a play of `steps`, begun with the value at `from`, is `at`
397/// microseconds in.
398fn 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      // A pause goes on through the holds and delays right after it.
405      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
428/// A value an animation can move between two of: `lerp` gives the value
429/// `t` of the way from `self` to `to`, where `t` may stray a little past 0
430/// or 1 for an easing that overshoots.
431pub trait Animate: Clone + PartialEq + 'static {
432  /// The value `t` of the way from `self` to `to`.
433  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
465/// One running animation: advanced to a time, it says whether it still
466/// runs.
467type Tick = Box<dyn FnMut(Instant) -> bool>;
468
469/// A step on the clock, named for log lines and counted in its item.
470type Running = (Rc<str>, Option<Busy>, Tick);
471
472/// How many animations run inside one item of a list with an exit, and
473/// the item around it, so a leaving item knows when everything in it has
474/// stopped.
475pub(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  /// Adds `by` to this item's count and every item's around it.
489  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
500/// One animation counted as running in its item until it is dropped.
501pub(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
516/// A leaving item waiting for everything in it to stop: `done` runs at
517/// the first tick that finds nothing running there, unless `owner`, its
518/// exit's, went first.
519struct Watch {
520  owner: Owner,
521  activity: Rc<Activity>,
522  done: Box<dyn FnOnce()>,
523}
524
525thread_local! {
526  /// Everything is on one thread, so the clock is too. Each animation is
527  /// named for log lines.
528  static RUNNING: RefCell<Vec<Running>> = const { RefCell::new(Vec::new()) };
529  static WATCHES: RefCell<Vec<Watch>> = const { RefCell::new(Vec::new()) };
530  /// Steps taken off the clock through a pause. The timers wake them.
531  static ASLEEP: RefCell<Vec<Sleeper>> = const { RefCell::new(Vec::new()) };
532  /// What the step now running asked with [`sleep_until`].
533  static SLEEP: Cell<Option<Nap>> = const { Cell::new(None) };
534  /// When the clock last ticked.
535  static LAST_TICK: Cell<Option<Instant>> = const { Cell::new(None) };
536}
537
538/// Starts `step`, named `label` for log lines and counted in `busy`'s
539/// item, at the next [`advance_animations`].
540pub(crate) fn start(label: Rc<str>, busy: Option<Busy>, step: Tick) {
541  RUNNING.with(|running| running.borrow_mut().push((label, busy, step)));
542}
543
544/// A pause a step asked for: until when, the owner whose going frees it,
545/// and the play it belongs to, as its generation cell and the number it
546/// started at, so a play replaced while asleep is freed too.
547pub(crate) struct Nap {
548  pub(crate) deadline: Instant,
549  pub(crate) owner: Owner,
550  pub(crate) play: (Rc<Cell<u64>>, u64),
551}
552
553/// A step asleep through its pause.
554struct Sleeper {
555  nap: Nap,
556  running: Running,
557}
558
559impl Nap {
560  /// Whether nothing waits for it any more.
561  fn stale(&self) -> bool {
562    self.owner.is_disposed() || self.play.0.get() != self.play.1
563  }
564}
565
566/// Takes the step now running off the clock once it returns `true`, until
567/// the nap's deadline, so a pause wakes the loop once instead of every
568/// frame. It stays counted in its item, and is freed unwoken once stale.
569pub(crate) fn sleep_until(nap: Nap) {
570  SLEEP.with(|sleep| sleep.set(Some(nap)));
571}
572
573/// Frees the sleeping steps whose owner is gone or whose play was
574/// replaced, dropping them with the table released.
575fn 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
594/// When the first sleeping step wakes, having freed the stale ones.
595pub(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
603/// Puts the sleeping steps due at `now` back on the clock, having freed
604/// the stale ones.
605pub(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/// How many steps sleep, for tests.
619#[cfg(test)]
620pub(crate) fn asleep() -> usize {
621  ASLEEP.with(|asleep| asleep.borrow().len())
622}
623
624/// Runs `done` at the first tick that finds nothing running in
625/// `activity`'s item, while `owner` lasts. The clock ticks for it, so an
626/// item with nothing moving is judged at once.
627pub(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
637/// Runs the watches whose items have stopped. Judged before the steps
638/// move, so an animation started in the flush after the last tick, as
639/// one that follows another's end, still counts.
640fn 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
660/// When an animation starting now should count from: the clock's last
661/// tick while it runs, so one that replaces another moves at the very
662/// next tick, or `None` when it is still, so the first tick is time 0.
663pub(crate) fn start_time() -> Option<Instant> {
664  if animating() {
665    LAST_TICK.with(Cell::get)
666  } else {
667    None
668  }
669}
670
671/// Whether an animation is running, so the platform should advance the
672/// clock soon. `false` means nothing moves and nothing needs waking.
673pub fn animating() -> bool {
674  RUNNING.with(|running| !running.borrow().is_empty())
675    || WATCHES.with(|watches| !watches.borrow().is_empty())
676}
677
678/// Advances every running animation to `now`, writing their values, and
679/// returns whether any still runs. Each one starts at the first call after
680/// it began, so `now` there is its time 0. One that panics is logged and
681/// dropped.
682pub 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    // Animations started while these ran go after them.
710    let mut running = running.borrow_mut();
711    kept.append(&mut running);
712    *running = kept;
713  });
714  let still = animating();
715  if !still {
716    // The clock stops, so the next animation counts from its own first
717    // tick, not this one.
718    LAST_TICK.with(|last| last.set(None));
719  }
720  still
721}
722
723/// Drops a finished step, and the user's values it holds, isolated.
724fn 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
733/// Runs `f`, a config's closure for the animation `label`, and logs a
734/// panic as that animation's, giving `None`.
735fn 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
748/// Sets `signal` to `value` only when that changes it, since a set always
749/// tells its readers.
750fn 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
756/// A value moving toward its target, from [`Cx::animation`] or
757/// [`Cx::spring`]: a `Copy`
758/// handle to its value and to whether it moves.
759pub 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  /// The value, as [`Cx::animate`] gives it.
774  pub fn value(&self) -> ReadSignal<T> {
775    self.value
776  }
777
778  /// `true` from the moment a new target starts it, through its delay,
779  /// until it settles there. It turns `false` once per animation, so an
780  /// effect on it is the place for what follows.
781  pub fn running(&self) -> ReadSignal<bool> {
782    self.running
783  }
784}
785
786impl Cx {
787  /// A value that follows `target`, moving to each new one over
788  /// `transition` instead of jumping. It starts at `target`'s first value.
789  /// A new target while it moves starts a new animation from where it is.
790  /// The animation goes when this context's owner does. It is
791  /// [`Cx::animation`]'s value.
792  ///
793  /// ```
794  /// use crabshell_ui::{Cx, Transition};
795  ///
796  /// fn slide(cx: &Cx) {
797  ///     let open = cx.signal(false);
798  ///     let offset = cx.animate(move || if open.get() { 0.0 } else { -200.0 }, Transition::new(200));
799  ///     // Read `offset.get()` in a binding, such as a style's width.
800  /// }
801  /// ```
802  #[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  /// A value that follows `target` as [`Cx::animate`]'s does, and whether
812  /// it moves. A panic in `target` is logged with this call's place, and
813  /// the value stays where it was.
814  ///
815  /// ```
816  /// use crabshell_ui::{Cx, Transition};
817  ///
818  /// fn slide_in_then_focus(cx: &Cx) {
819  ///     let open = cx.signal(false);
820  ///     let ready = cx.signal(false);
821  ///     let slide = cx.animation(move || if open.get() { 0.0 } else { -200.0 }, Transition::new(200));
822  ///     cx.effect(move || {
823  ///         if open.get() && !slide.running().get() {
824  ///             ready.set(true);
825  ///         }
826  ///     });
827  /// }
828  /// ```
829  #[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  /// [`Cx::animation`], logged as `what` at the caller's place.
839  #[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    // Bumped by each new target, so the animation it replaces stops.
854    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      // Read as each move starts, so a binding can pick its curve.
870      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      // No time to take: the new value shows in this flush.
883      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            // The value is still `from`; setting it would rerun its readers.
902            return true;
903          }
904          let (t, ended) = transition.progress(begun, now);
905          // `lerp` and `clone` may be a config's own; a panic ends the
906          // animation with `running` false, so whatever waits on it runs.
907          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          // A value whose owner is gone stops its animation.
914          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  /// Progress from 0 to 1, eased, repeating every `transition.ms` while
929  /// `running` gives `true`, for spinners and pulses. With
930  /// [`Transition::alternate`] it comes back, 0 to 1 to 0, each way taking
931  /// `ms`. It waits out the delay once, at the start. When `running` turns
932  /// `false`, the round it is in runs to its end, then it rests at 0 and
933  /// the clock stops; `true` again before then keeps it going, and after
934  /// it begins at 0. A 0 ms cycle never moves. A panic in `running` is
935  /// logged with this call's place and ends the cycle after its round.
936  ///
937  /// ```
938  /// use crabshell_ui::{Cx, Easing, Transition};
939  ///
940  /// const SPIN: Transition = Transition::new(1000).easing(Easing::Linear);
941  /// const PULSE: Transition = Transition::new(600).easing(Easing::InOutSine).alternate();
942  ///
943  /// fn busy(cx: &Cx) {
944  ///     let loading = cx.signal(true);
945  ///     let turn = cx.cycle(move || loading.get(), SPIN); // turns: turn.get() * 360.0
946  ///     let glow = cx.cycle(move || loading.get(), PULSE); // an opacity: 0.5 + glow.get() / 2.0
947  /// }
948  /// ```
949  #[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    // What `running` last gave, and whether a round is on the clock.
959    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      // Round 0 is the delay, then 1, 2 and on.
978      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  /// The time since `running` turned `true`, updated at each tick of the
1008  /// animation clock while it stays true, as Qt's `FrameAnimation` gives.
1009  /// Nothing ticks while it is false, and the time stays where it was
1010  /// until the next run starts again from 0. A panic in `running` is
1011  /// logged with this call's place and stops it.
1012  ///
1013  /// ```
1014  /// use crabshell_ui::Cx;
1015  ///
1016  /// fn wave(cx: &Cx) {
1017  ///     let shown = cx.signal(true);
1018  ///     let time = cx.frames(move || shown.get());
1019  ///     // A bar's height: 10.0 + 5.0 * (time.get().as_secs_f32() * 6.0).sin()
1020  /// }
1021  /// ```
1022  #[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  /// A value that follows `target` on `spring`, as Qt's
1060  /// `SpringAnimation`: a new target while it moves keeps its speed, so a
1061  /// value chasing a moving target never stops dead. It starts at
1062  /// `target`'s first value and comes to rest exactly on the target, when
1063  /// the clock stops. A target that isn't finite, or a spring that isn't
1064  /// valid (see [`Spring`]), jumps there at once. A panic in `target` is
1065  /// logged with this call's place, and the value stops where it is. The
1066  /// [`Animation`]'s `running()` is true from a new target until it comes
1067  /// to rest, and never for a jump.
1068  ///
1069  /// ```
1070  /// use crabshell_ui::{Cx, Spring};
1071  ///
1072  /// fn indicator(cx: &Cx) {
1073  ///     let hovered = cx.signal(0_usize);
1074  ///     let x = cx.spring(move || hovered.get() as f32 * 40.0, Spring::new(380.0, 0.8));
1075  ///     // Read `x.value().get()` in a binding, such as a style's padding.
1076  /// }
1077  /// ```
1078  #[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    // Where the step on the clock heads, and whether there is one. A goal
1091    // that isn't finite stops it.
1092    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        // One on the clock stops at its next tick.
1113        set_changed(running, false);
1114        return;
1115      }
1116      if ticking.get() {
1117        // Still on the clock after a jump, it moves again.
1118        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          // A value that started out not finite lands at once.
1149          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  /// A value that plays `steps` one after another each time `trigger`'s
1169  /// value changes, as Qt's `SequentialAnimation`: a shake on a wrong
1170  /// password, bumped by a counter, or a pause and then a slide. It starts
1171  /// at `initial`, and `trigger`'s first value plays nothing. Each step
1172  /// moves from wherever the value is, so a new trigger mid-play starts
1173  /// over from there, and once played the value rests at the last step's
1174  /// target. `steps` is a value or a closure, read untracked as each play
1175  /// starts; an empty list plays nothing.
1176  ///
1177  /// The [`Animation`]'s `running()` is true from the trigger until the
1178  /// last step ends, holds included, so an effect on it runs what comes
1179  /// after. A hold, or a delay, takes the value off the animation clock:
1180  /// the loop sleeps until it ends instead of waking each frame. A panic in
1181  /// `trigger` is logged with this call's place and stops the sequence
1182  /// where it is for good; one in `steps` or a config's own `lerp` stops
1183  /// that play.
1184  ///
1185  /// ```
1186  /// use crabshell_ui::{Cx, Easing, Step, Transition};
1187  ///
1188  /// const SHAKE: [Step<f32>; 3] = [
1189  ///     Step::to(-14.0, Transition::new(70).easing(Easing::OutQuad)),
1190  ///     Step::to(12.0, Transition::new(90).easing(Easing::InOutQuad)),
1191  ///     Step::to(0.0, Transition::new(95).easing(Easing::OutQuad)),
1192  /// ];
1193  ///
1194  /// fn pill(cx: &Cx) {
1195  ///     let wrong = cx.signal(0_u32); // bumped on each wrong password
1196  ///     let shake = cx.sequence(0.0, move || wrong.get(), SHAKE);
1197  ///     // Read `shake.value().get()` in a binding, such as a translate.
1198  /// }
1199  /// ```
1200  #[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  /// A value that plays `steps` once, starting as soon as it is made: an
1229  /// entrance that plays each time its widget is built, such as a card
1230  /// that waits its turn with a [`Step::hold`] and then fades in. It
1231  /// starts at `initial`, and once played it rests at the last step's
1232  /// target. `steps` is a value or a closure, read untracked once, now; an
1233  /// empty list plays nothing. Holds sleep off the clock as in
1234  /// [`Cx::sequence`], and the [`Animation`]'s `running()` is true until
1235  /// the last step ends. To play again on a change, use
1236  /// [`Cx::sequence`]. A panic in `steps` or a config's own `lerp` is
1237  /// logged with this call's place and stops the play.
1238  ///
1239  /// ```
1240  /// use crabshell_ui::{Cx, Easing, Step, Transition};
1241  ///
1242  /// const FADE: Transition = Transition::new(200).easing(Easing::OutCubic);
1243  ///
1244  /// fn card(cx: &Cx, index: u32) {
1245  ///     let opacity = cx.sequence_now(0.0, [Step::hold(index * 40), Step::to(1.0, FADE)]);
1246  ///     // Read `opacity.value().get()` in a binding.
1247  /// }
1248  /// ```
1249  #[track_caller]
1250  pub fn sequence_now<T: Animate>(
1251    &self,
1252    initial: T,
1253    steps: impl IntoProp<Vec<Step<T>>>,
1254  ) -> Animation<T> {
1255    let player = self.player("cx.sequence_now", initial, steps);
1256    player.play(false);
1257    player.animation()
1258  }
1259
1260  /// A value that plays `steps` over and over while `running` gives
1261  /// `true`, each round with its holds, as a `SequentialAnimation` with
1262  /// infinite loops: a pulse while something loads. It starts at
1263  /// `initial`; round 0 moves from where the value is, and each later
1264  /// round from the last step's target. When `running` turns `false`, the
1265  /// round it is in runs to its end and the value rests at the last step's
1266  /// target; `true` again before then keeps it going, and after it starts
1267  /// again at round 0. A round of no time plays once. Holds sleep off the
1268  /// clock as in [`Cx::sequence`]. A panic in `running` is logged with
1269  /// this call's place and ends it after its round.
1270  ///
1271  /// ```
1272  /// use crabshell_ui::{Cx, Easing, Step, Transition};
1273  ///
1274  /// const SINE: Transition = Transition::new(1100).easing(Easing::InOutSine);
1275  ///
1276  /// fn tile(cx: &Cx, index: u32) {
1277  ///     let loading = cx.signal(true);
1278  ///     let steps = [Step::hold(index * 140), Step::to(0.4, SINE), Step::to(1.0, SINE)];
1279  ///     let opacity = cx.sequence_loop(1.0, move || loading.get(), steps);
1280  /// }
1281  /// ```
1282  #[track_caller]
1283  pub fn sequence_loop<T: Animate>(
1284    &self,
1285    initial: T,
1286    mut running: impl FnMut() -> bool + 'static,
1287    steps: impl IntoProp<Vec<Step<T>>>,
1288  ) -> Animation<T> {
1289    let player = self.player("cx.sequence_loop", initial, steps);
1290    let mut broken = false;
1291    let animation = player.animation();
1292    self.effect(move || {
1293      let on = !broken
1294        && guarded(&player.label, &mut running).unwrap_or_else(|| {
1295          broken = true;
1296          false
1297        });
1298      player.wanted.set(on);
1299      if on && untrack(|| player.running.try_get()) == Some(false) {
1300        player.play(true);
1301      }
1302    });
1303    animation
1304  }
1305
1306  /// The state [`Cx::sequence`], [`Cx::sequence_now`] and
1307  /// [`Cx::sequence_loop`] share, logged as
1308  /// `what` at the caller's place.
1309  #[track_caller]
1310  fn player<T: Animate>(
1311    &self,
1312    what: &str,
1313    initial: T,
1314    steps: impl IntoProp<Vec<Step<T>>>,
1315  ) -> Rc<Player<T>> {
1316    Rc::new(Player {
1317      label: format!("{what} at {}", std::panic::Location::caller()).into(),
1318      steps: steps.into_prop().shared(),
1319      value: self.signal(initial),
1320      running: self.signal(false),
1321      generation: Rc::new(Cell::new(0)),
1322      wanted: Rc::new(Cell::new(false)),
1323      owner: self.owner(),
1324      activity: self.activity.clone(),
1325    })
1326  }
1327}
1328
1329/// A sequence's value, its steps, and the play on the clock.
1330struct Player<T: 'static> {
1331  label: Rc<str>,
1332  steps: Rc<dyn Fn() -> Vec<Step<T>>>,
1333  value: Signal<T>,
1334  running: Signal<bool>,
1335  /// Bumped by each new play, so the one it replaces stops.
1336  generation: Rc<Cell<u64>>,
1337  /// What a loop's `running` last gave.
1338  wanted: Rc<Cell<bool>>,
1339  owner: Owner,
1340  activity: Option<Rc<Activity>>,
1341}
1342
1343impl<T: Animate> Player<T> {
1344  fn animation(&self) -> Animation<T> {
1345    Animation {
1346      value: self.value.read_only(),
1347      running: self.running.read_only(),
1348    }
1349  }
1350
1351  /// Stops the play on the clock where it is.
1352  fn stop(&self) {
1353    self.generation.set(self.generation.get() + 1);
1354    set_changed(self.running, false);
1355  }
1356
1357  /// Starts a play of the steps from where the value is, looping while
1358  /// `wanted` if `looping`.
1359  fn play(&self, looping: bool) {
1360    self.stop();
1361    let label = Rc::clone(&self.label);
1362    // Read as each play starts, so a binding can pick the steps; the
1363    // clones are a config's own.
1364    let Some((steps, origin, last)) = guarded(&label, || {
1365      let steps = untrack(&*self.steps);
1366      let origin = untrack(|| self.value.try_get())?;
1367      let last = steps.iter().rev().find_map(|step| step.to.clone());
1368      let last = last.unwrap_or_else(|| origin.clone());
1369      Some((steps, origin, last))
1370    })
1371    .flatten() else {
1372      return;
1373    };
1374    if steps.is_empty() {
1375      return;
1376    }
1377    let length: u64 = steps.iter().map(|step| step.times().1).sum();
1378    let looping = looping && length > 0;
1379    set_changed(self.running, true);
1380    let current = self.generation.get();
1381    let (generation, wanted) = (Rc::clone(&self.generation), Rc::clone(&self.wanted));
1382    let (value, running, owner) = (self.value, self.running, self.owner);
1383    let step_label = Rc::clone(&label);
1384    let mut started = start_time();
1385    let mut round = 0;
1386    start(
1387      label,
1388      self.activity.as_ref().map(Busy::new),
1389      Box::new(move |now| {
1390        if generation.get() != current {
1391          return false;
1392        }
1393        let begun = *started.get_or_insert(now);
1394        let at = now.saturating_duration_since(begun).as_micros();
1395        let at = u64::try_from(at).unwrap_or(u64::MAX);
1396        let (now_round, within) = if looping {
1397          (at / length, at % length)
1398        } else {
1399          (0, at)
1400        };
1401        let ended = now_round > round && !wanted.get();
1402        round = now_round;
1403        let spot = guarded(&step_label, || {
1404          if ended {
1405            return Spot::Ended(last.clone());
1406          }
1407          spot(&steps, if round == 0 { &origin } else { &last }, within)
1408        });
1409        let (next, sleep) = match spot {
1410          Some(Spot::Moving(next)) => (next, None),
1411          Some(Spot::Holding(next, until)) => (next, Some(round * length + until)),
1412          Some(Spot::Ended(next)) => {
1413            // A config's own `PartialEq` runs in the write.
1414            guarded(&step_label, || set_changed(value, next));
1415            running.try_set(false);
1416            return false;
1417          }
1418          // A panicking `lerp` ends the play with `running` false, so
1419          // whatever waits on it runs.
1420          None => {
1421            running.try_set(false);
1422            return false;
1423          }
1424        };
1425        // A value whose owner is gone stops its sequence.
1426        if untrack(|| value.try_with(|_| ())).is_none() {
1427          return false;
1428        }
1429        if guarded(&step_label, || set_changed(value, next)).is_none() {
1430          running.try_set(false);
1431          return false;
1432        }
1433        if let Some(until) = sleep {
1434          sleep_until(Nap {
1435            deadline: begun + Duration::from_micros(until),
1436            owner,
1437            play: (Rc::clone(&generation), current),
1438          });
1439        }
1440        true
1441      }),
1442    );
1443  }
1444}