Skip to main content

waft_animation/
animation.rs

1//! Flutter counterpart: `animation/animation.dart`.
2
3use std::any::{TypeId, type_name};
4use std::fmt::{self, Debug};
5use std::hash::{Hash, Hasher};
6use std::rc::{Rc, Weak};
7
8use waft_foundation::{
9    App, Handle, HandleId, ListenableHandle, Listener, Ref, Retained, describe_identity,
10};
11
12use crate::tween::Animatable;
13
14/// The status of an animation.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum AnimationStatus {
17    /// The animation is stopped at the beginning.
18    Dismissed,
19
20    /// The animation is running from beginning to end.
21    Forward,
22
23    /// The animation is running backwards, from end to beginning.
24    Reverse,
25
26    /// The animation is stopped at the end.
27    Completed,
28}
29
30impl AnimationStatus {
31    /// Whether the animation is stopped at the beginning.
32    pub fn is_dismissed(self) -> bool {
33        self == AnimationStatus::Dismissed
34    }
35
36    /// Whether the animation is stopped at the end.
37    pub fn is_completed(self) -> bool {
38        self == AnimationStatus::Completed
39    }
40
41    /// Whether the animation is running in either direction.
42    pub fn is_animating(self) -> bool {
43        match self {
44            AnimationStatus::Forward | AnimationStatus::Reverse => true,
45            AnimationStatus::Completed | AnimationStatus::Dismissed => false,
46        }
47    }
48
49    /// Whether the current aim of the animation is toward completion.
50    pub fn is_forward_or_completed(self) -> bool {
51        match self {
52            AnimationStatus::Forward | AnimationStatus::Completed => true,
53            AnimationStatus::Reverse | AnimationStatus::Dismissed => false,
54        }
55    }
56}
57
58/// Signature for listeners attached using [`Animation::add_status_listener`].
59///
60/// Like [`Listener`], this is a handle matched by identity: a listener over a
61/// closure ([`AnimationStatusListener::new`]) is equal only to its own clones,
62/// and a listener over an entity's associated function
63/// ([`AnimationStatusListener::handle_method`]) is equal to any other built
64/// from the same entity and function.
65#[derive(Clone)]
66pub struct AnimationStatusListener {
67    callback: Rc<StatusCallback>,
68    identity: StatusListenerIdentity,
69}
70
71type StatusCallback = dyn Fn(AnimationStatus, &mut App);
72
73/// See `ListenerIdentity` on [`Listener`] — the same split for the same
74/// reason, including the function-`TypeId` half.
75#[derive(Clone, Copy)]
76enum StatusListenerIdentity {
77    Closure,
78    HandleMethod(HandleId, TypeId),
79}
80
81impl AnimationStatusListener {
82    /// Wraps a closure as a status listener.
83    pub fn new(callback: impl Fn(AnimationStatus, &mut App) + 'static) -> AnimationStatusListener {
84        AnimationStatusListener {
85            callback: Rc::new(callback),
86            identity: StatusListenerIdentity::Closure,
87        }
88    }
89
90    /// Wraps an entity's associated function as a status listener.
91    ///
92    /// The counterpart of Dart passing the `notifyStatusListeners` tear-off;
93    /// see [`Listener::handle_method`] for the identity rule. Pass the
94    /// function by name — the compile-time assert rejects fn pointers and
95    /// capturing closures, which have no canonical identity.
96    ///
97    /// The function is receiver-first, `(Handle<T>, &mut App, AnimationStatus)`,
98    /// so a method on `Handle<T>` can be named directly.
99    ///
100    /// Like [`Listener::handle_method`], it does not keep its receiver, and is skipped once the
101    /// receiver is freed.
102    pub fn handle_method<T: 'static, F>(this: Handle<T>, f: F) -> AnimationStatusListener
103    where
104        F: Fn(Handle<T>, &mut App, AnimationStatus) + 'static,
105    {
106        const {
107            assert!(
108                std::mem::size_of::<F>() == 0,
109                "pass the function by name: a fn pointer or capturing closure \
110                 has no canonical identity to match on removal"
111            )
112        };
113        AnimationStatusListener {
114            callback: Rc::new(move |status, app: &mut App| {
115                if app.tear_off_receiver_is_live(this) {
116                    f(this, app, status);
117                }
118            }),
119            identity: StatusListenerIdentity::HandleMethod(this.id(), TypeId::of::<F>()),
120        }
121    }
122
123    /// Calls the closure.
124    pub fn call(&self, status: AnimationStatus, app: &mut App) {
125        (self.callback)(status, app);
126    }
127
128    /// A reference to this listener that does not keep its closure alive, for a closure that
129    /// removes itself: Dart's `late AnimationStatusListener l; l = (status) { ...;
130    /// animation.removeStatusListener(l); };` names itself, and a closure holding its own
131    /// listener strongly would keep itself alive after the animation lets it go.
132    pub fn downgrade(&self) -> WeakAnimationStatusListener {
133        WeakAnimationStatusListener {
134            callback: Rc::downgrade(&self.callback),
135            identity: self.identity,
136        }
137    }
138}
139
140/// An [`AnimationStatusListener`] that does not keep its closure alive; see
141/// [`AnimationStatusListener::downgrade`].
142#[derive(Clone)]
143pub struct WeakAnimationStatusListener {
144    callback: Weak<StatusCallback>,
145    identity: StatusListenerIdentity,
146}
147
148impl WeakAnimationStatusListener {
149    /// The listener, equal to the one it was made from, while something still holds that one.
150    pub fn upgrade(&self) -> Option<AnimationStatusListener> {
151        Some(AnimationStatusListener {
152            callback: self.callback.upgrade()?,
153            identity: self.identity,
154        })
155    }
156}
157
158impl PartialEq for AnimationStatusListener {
159    fn eq(&self, other: &AnimationStatusListener) -> bool {
160        match (self.identity, other.identity) {
161            (StatusListenerIdentity::Closure, StatusListenerIdentity::Closure) => {
162                Rc::ptr_eq(&self.callback, &other.callback)
163            }
164            (
165                StatusListenerIdentity::HandleMethod(entity, function),
166                StatusListenerIdentity::HandleMethod(other_entity, other_function),
167            ) => entity == other_entity && function == other_function,
168            _ => false,
169        }
170    }
171}
172
173impl Eq for AnimationStatusListener {}
174
175impl Hash for AnimationStatusListener {
176    fn hash<H: Hasher>(&self, state: &mut H) {
177        match self.identity {
178            StatusListenerIdentity::Closure => {
179                (Rc::as_ptr(&self.callback) as *const ()).hash(state);
180            }
181            StatusListenerIdentity::HandleMethod(entity, function) => {
182                entity.hash(state);
183                function.hash(state);
184            }
185        }
186    }
187}
188
189impl Debug for AnimationStatusListener {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.write_str("AnimationStatusListener")
192    }
193}
194
195/// A value which might change over time, moving forward or backward.
196///
197/// This is what a concrete animation implements — Dart's
198/// `class X extends Animation<T>`. A field or parameter Dart types as
199/// `Animation<T>` holds the erased [`AnimationRef<T>`] instead; get one from a
200/// [`Ref`] with [`Retained::erase`], and the bare [`AnyAnimation<T>`]
201/// that names it without keeping it from [`as_animation`](Animation::as_animation).
202///
203/// The members take `self: Handle<Self>` rather than `&self`, for the reason
204/// recorded on the `listener_helpers` traits: a `&self` receiver would borrow
205/// this animation's slot for the whole call, and the listener members hand
206/// `&mut App` onward to reach other objects and run listeners.
207pub trait Animation<T: 'static>: Sized + 'static {
208    /// Calls the listener every time the value of the animation changes.
209    ///
210    /// Listeners can be removed with [`remove_listener`].
211    ///
212    /// [`remove_listener`]: Animation::remove_listener
213    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener);
214
215    /// Stop calling the listener every time the value of the animation
216    /// changes.
217    ///
218    /// Listeners can be added with [`add_listener`].
219    ///
220    /// [`add_listener`]: Animation::add_listener
221    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener);
222
223    /// Calls listener every time the status of the animation changes.
224    ///
225    /// Listeners can be removed with [`remove_status_listener`].
226    ///
227    /// [`remove_status_listener`]: Animation::remove_status_listener
228    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener);
229
230    /// Stops calling the listener every time the status of the animation
231    /// changes.
232    ///
233    /// Listeners can be added with [`add_status_listener`].
234    ///
235    /// [`add_status_listener`]: Animation::add_status_listener
236    fn remove_status_listener(
237        self: Handle<Self>,
238        app: &mut App,
239        listener: &AnimationStatusListener,
240    );
241
242    /// The current status of this animation.
243    fn status(self: Handle<Self>, app: &App) -> AnimationStatus;
244
245    /// The current value of the animation.
246    ///
247    /// Returns an owned `T`, not a reference: an animation may compute its
248    /// value from its parent's (Dart's `CurvedAnimation.value` does), so there
249    /// is no stored field for a reference to point at.
250    fn value(self: Handle<Self>, app: &App) -> T;
251
252    /// Whether this animation is stopped at the beginning.
253    fn is_dismissed(self: Handle<Self>, app: &App) -> bool {
254        Self::status(self, app).is_dismissed()
255    }
256
257    /// Whether this animation is stopped at the end.
258    fn is_completed(self: Handle<Self>, app: &App) -> bool {
259        Self::status(self, app).is_completed()
260    }
261
262    /// Whether this animation is running in either direction.
263    fn is_animating(self: Handle<Self>, app: &App) -> bool {
264        Self::status(self, app).is_animating()
265    }
266
267    /// Whether the current aim of this animation is toward completion.
268    fn is_forward_or_completed(self: Handle<Self>, app: &App) -> bool {
269        Self::status(self, app).is_forward_or_completed()
270    }
271
272    /// Dart's `Animation.toStringDetails`: the status as its arrow.
273    fn to_string_details(self: Handle<Self>, app: &App) -> String {
274        animation_status_symbol(Self::status(self, app)).to_string()
275    }
276
277    /// Dart's `Animation.toString`: the identity and `toStringDetails`.
278    fn to_string(self: Handle<Self>, app: &App) -> String {
279        format!(
280            "{}({})",
281            describe_identity(
282                waft_foundation::bare_type_name(std::any::type_name::<Self>()),
283                self.id().identity_hash(),
284            ),
285            self.to_string_details(app)
286        )
287    }
288
289    /// This animation as the erased [`AnyAnimation<T>`] — what to pass where
290    /// a Dart API takes an `Animation<T>`.
291    ///
292    /// The object is untouched; this mints an erased second handle to it, so
293    /// concrete members stay reachable through the typed one while the erased
294    /// handle sits in a field Dart types as `Animation<T>`.
295    fn as_animation(self: Handle<Self>) -> AnyAnimation<T> {
296        AnyAnimation {
297            id: self.id(),
298            vtable: const { &AnimationVTable::of::<Self>() },
299        }
300    }
301}
302
303/// The arrow Dart's `Animation.toStringDetails` prints for `status`.
304pub(crate) fn animation_status_symbol(status: AnimationStatus) -> &'static str {
305    match status {
306        AnimationStatus::Forward => "\u{25B6}",
307        AnimationStatus::Reverse => "\u{25C0}",
308        AnimationStatus::Completed => "\u{23ED}",
309        AnimationStatus::Dismissed => "\u{23EE}",
310    }
311}
312
313/// Erased [`Animation`]: one identity and a static vtable, the fat pointer
314/// rustc cannot build for an arena id. No lease.
315///
316/// Like [`Handle`], it names the animation without keeping it: what a call that
317/// only uses an animation takes. A field or parameter Dart types as
318/// `Animation<T>` keeps it and holds an [`AnimationRef<T>`], which derefs to
319/// this. The concrete animation stays in the [`App`] under its own type; the
320/// handle carries its id plus a static dispatch table, so holding or copying one
321/// borrows nothing, and the same object stays reachable through its typed
322/// [`Handle`] for concrete-only members.
323///
324/// Equality is Dart's `==` on an object reference: two handles are equal
325/// exactly when they address the same object.
326pub struct AnyAnimation<T: 'static> {
327    id: HandleId,
328    vtable: &'static AnimationVTable<T>,
329}
330
331/// The vtable of an erased [`AnyAnimation`]: one `&'static` table per
332/// concrete [`Animation`] type, built by [`AnimationVTable::of`].
333///
334/// It lives outside the arena — `&'static` — because a listener member hands
335/// `&mut App` onward; dispatch read out of the arena would keep the arena
336/// borrowed across that call.
337struct AnimationVTable<T> {
338    add_listener: fn(&mut App, HandleId, Listener),
339    remove_listener: fn(&mut App, HandleId, &Listener),
340    add_status_listener: fn(&mut App, HandleId, AnimationStatusListener),
341    remove_status_listener: fn(&mut App, HandleId, &AnimationStatusListener),
342    status: fn(&App, HandleId) -> AnimationStatus,
343    value: fn(&App, HandleId) -> T,
344    // The four derived getters dispatch through the object rather than
345    // recomputing from `status`, because they are virtual in Dart —
346    // `AnimationController` overrides `isAnimating`
347    // (`animation_controller.dart:449`).
348    is_dismissed: fn(&App, HandleId) -> bool,
349    is_completed: fn(&App, HandleId) -> bool,
350    is_animating: fn(&App, HandleId) -> bool,
351    is_forward_or_completed: fn(&App, HandleId) -> bool,
352    to_string: fn(&App, HandleId) -> String,
353}
354
355/// The typed handle for an erased id. Free: nothing is looked up; `get` checks
356/// the slot.
357fn resolve<A: 'static>(id: HandleId) -> Handle<A> {
358    Handle::from_id(id)
359}
360
361impl<T: 'static> AnimationVTable<T> {
362    /// The table for one concrete animation type.
363    const fn of<A: Animation<T>>() -> AnimationVTable<T> {
364        AnimationVTable {
365            add_listener: |app, id, listener| A::add_listener(resolve(id), app, listener),
366            remove_listener: |app, id, listener| A::remove_listener(resolve(id), app, listener),
367            add_status_listener: |app, id, listener| {
368                A::add_status_listener(resolve(id), app, listener)
369            },
370            remove_status_listener: |app, id, listener| {
371                A::remove_status_listener(resolve(id), app, listener)
372            },
373            status: |app, id| A::status(resolve(id), app),
374            value: |app, id| A::value(resolve(id), app),
375            is_dismissed: |app, id| A::is_dismissed(resolve(id), app),
376            is_completed: |app, id| A::is_completed(resolve(id), app),
377            is_animating: |app, id| A::is_animating(resolve(id), app),
378            is_forward_or_completed: |app, id| A::is_forward_or_completed(resolve(id), app),
379            to_string: |app, id| A::to_string(resolve(id), app),
380        }
381    }
382}
383
384impl<T: 'static> AnyAnimation<T> {
385    /// The arena id behind this handle.
386    pub fn id(self) -> HandleId {
387        self.id
388    }
389
390    /// Dart's `animation as A`: the typed handle when this animation is an `A`, else `None`.
391    pub fn downcast<A: 'static>(self, app: &App) -> Option<Handle<A>> {
392        app.handle::<A>(self.id)
393    }
394
395    /// Calls the listener every time the value of the animation changes.
396    ///
397    /// Listeners can be removed with [`remove_listener`](AnyAnimation::remove_listener).
398    pub fn add_listener(self, app: &mut App, listener: Listener) {
399        (self.vtable.add_listener)(app, self.id, listener)
400    }
401
402    /// Stop calling the listener every time the value of the animation
403    /// changes.
404    ///
405    /// Listeners can be added with [`add_listener`](AnyAnimation::add_listener).
406    pub fn remove_listener(self, app: &mut App, listener: &Listener) {
407        (self.vtable.remove_listener)(app, self.id, listener)
408    }
409
410    /// Calls listener every time the status of the animation changes.
411    ///
412    /// Listeners can be removed with
413    /// [`remove_status_listener`](AnyAnimation::remove_status_listener).
414    pub fn add_status_listener(self, app: &mut App, listener: AnimationStatusListener) {
415        (self.vtable.add_status_listener)(app, self.id, listener)
416    }
417
418    /// Stops calling the listener every time the status of the animation
419    /// changes.
420    ///
421    /// Listeners can be added with
422    /// [`add_status_listener`](AnyAnimation::add_status_listener).
423    pub fn remove_status_listener(self, app: &mut App, listener: &AnimationStatusListener) {
424        (self.vtable.remove_status_listener)(app, self.id, listener)
425    }
426
427    /// The current status of this animation.
428    pub fn status(self, app: &App) -> AnimationStatus {
429        (self.vtable.status)(app, self.id)
430    }
431
432    /// The current value of the animation.
433    pub fn value(self, app: &App) -> T {
434        (self.vtable.value)(app, self.id)
435    }
436
437    /// Whether this animation is stopped at the beginning.
438    pub fn is_dismissed(self, app: &App) -> bool {
439        (self.vtable.is_dismissed)(app, self.id)
440    }
441
442    /// Whether this animation is stopped at the end.
443    pub fn is_completed(self, app: &App) -> bool {
444        (self.vtable.is_completed)(app, self.id)
445    }
446
447    /// Whether this animation is running in either direction.
448    pub fn is_animating(self, app: &App) -> bool {
449        (self.vtable.is_animating)(app, self.id)
450    }
451
452    /// Whether the current aim of this animation is toward completion.
453    pub fn is_forward_or_completed(self, app: &App) -> bool {
454        (self.vtable.is_forward_or_completed)(app, self.id)
455    }
456
457    /// Dart's `Animation.toString`: the identity and `toStringDetails`.
458    pub fn to_string(self, app: &App) -> String {
459        (self.vtable.to_string)(app, self.id)
460    }
461}
462
463/// A field or parameter Dart types as `Animation<T>`: the erased animation, kept. It derefs to
464/// the [`AnyAnimation<T>`], so every member is callable on it, and it is a
465/// [`Listenable`](waft_foundation::Listenable) that keeps what it listens to.
466pub type AnimationRef<T> = Retained<AnyAnimation<T>>;
467
468waft_foundation::erased_handle!(AnyAnimation<T>: Animation => Animation::as_animation);
469
470/// Dart's `Animation<double>.drive`, on a kept animation, since the animation it makes keeps
471/// this one.
472///
473/// Dart's `Animation<U> drive<U>(Animatable<U> child)` is a generic virtual method; no dispatch
474/// table can hold a generic, so ours is a trait over the references and cannot be overridden.
475/// Flutter defines no override either — `animation.dart:325` forwards to `child.animate(this)`,
476/// as this does.
477pub trait Drive {
478    /// Chains a `Tween` (or any [`Animatable`]) to this animation.
479    fn drive<U: 'static>(
480        &self,
481        app: &mut App,
482        child: impl Animatable<U> + Clone + 'static,
483    ) -> AnimationRef<U>;
484}
485
486impl<A: Animation<f64>> Drive for Ref<A> {
487    fn drive<U: 'static>(
488        &self,
489        app: &mut App,
490        child: impl Animatable<U> + Clone + 'static,
491    ) -> AnimationRef<U> {
492        child.animate(app, self.erase())
493    }
494}
495
496impl Drive for AnimationRef<f64> {
497    fn drive<U: 'static>(
498        &self,
499        app: &mut App,
500        child: impl Animatable<U> + Clone + 'static,
501    ) -> AnimationRef<U> {
502        child.animate(app, self.clone())
503    }
504}
505
506impl<T: 'static> ListenableHandle for AnyAnimation<T> {
507    fn add_listener_to(self, app: &mut App, listener: Listener) {
508        AnyAnimation::add_listener(self, app, listener);
509    }
510
511    fn remove_listener_from(self, app: &mut App, listener: &Listener) {
512        AnyAnimation::remove_listener(self, app, listener);
513    }
514}
515
516// Written by hand so that `AnyAnimation<T>: Copy` does not require `T: Copy`,
517// like `Handle<T>`.
518impl<T> Clone for AnyAnimation<T> {
519    fn clone(&self) -> AnyAnimation<T> {
520        *self
521    }
522}
523
524impl<T> Copy for AnyAnimation<T> {}
525
526impl<T> Debug for AnyAnimation<T> {
527    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528        write!(f, "AnyAnimation<{}>({:?})", type_name::<T>(), self.id)
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use std::cell::Cell;
535    use waft_foundation::AppCell;
536
537    use super::*;
538
539    #[test]
540    fn a_weak_status_listener_upgrades_to_an_equal_listener_only_while_one_is_held() {
541        let listener = AnimationStatusListener::new(|_, _| {});
542        let weak = listener.downgrade();
543        assert!(weak.upgrade().is_some_and(|upgraded| upgraded == listener));
544        drop(listener);
545        assert!(weak.upgrade().is_none());
546    }
547
548    #[test]
549    fn the_derived_status_getters_match_flutter() {
550        use AnimationStatus::*;
551
552        assert_eq!(
553            [
554                Dismissed.is_dismissed(),
555                Forward.is_dismissed(),
556                Reverse.is_dismissed(),
557                Completed.is_dismissed()
558            ],
559            [true, false, false, false]
560        );
561        assert_eq!(
562            [
563                Dismissed.is_completed(),
564                Forward.is_completed(),
565                Reverse.is_completed(),
566                Completed.is_completed()
567            ],
568            [false, false, false, true]
569        );
570        assert_eq!(
571            [
572                Dismissed.is_animating(),
573                Forward.is_animating(),
574                Reverse.is_animating(),
575                Completed.is_animating()
576            ],
577            [false, true, true, false]
578        );
579        assert_eq!(
580            [
581                Dismissed.is_forward_or_completed(),
582                Forward.is_forward_or_completed(),
583                Reverse.is_forward_or_completed(),
584                Completed.is_forward_or_completed()
585            ],
586            [false, true, false, true]
587        );
588    }
589
590    #[test]
591    fn only_a_handle_to_the_same_status_closure_compares_equal() {
592        let listener = AnimationStatusListener::new(|_status, _app| {});
593
594        assert_eq!(listener, listener.clone());
595        assert_ne!(listener, AnimationStatusListener::new(|_status, _app| {}));
596    }
597
598    #[test]
599    fn a_rebuilt_handle_method_status_listener_matches_like_a_dart_tear_off() {
600        struct Host;
601        fn hook(_this: Handle<Host>, _app: &mut App, _status: AnimationStatus) {}
602
603        let cell = AppCell::new();
604        let mut app = cell.borrow_mut();
605        let a = app.create(Host);
606        let b = app.create(Host);
607
608        assert_eq!(
609            AnimationStatusListener::handle_method(a.handle(), hook),
610            AnimationStatusListener::handle_method(a.handle(), hook)
611        );
612        assert_ne!(
613            AnimationStatusListener::handle_method(a.handle(), hook),
614            AnimationStatusListener::handle_method(b.handle(), hook)
615        );
616        assert_ne!(
617            AnimationStatusListener::handle_method(a.handle(), hook),
618            AnimationStatusListener::new(|_status, _app| {})
619        );
620    }
621
622    /// A minimal node: the erased handle must reach the overriding impl, not
623    /// the trait defaults — `AnimationController` overrides `isAnimating`
624    /// while stopped (`animation_controller.dart:449`).
625    struct OverridingNode;
626
627    impl Animation<f64> for OverridingNode {
628        fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
629        fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
630        fn add_status_listener(
631            self: Handle<Self>,
632            _app: &mut App,
633            _listener: AnimationStatusListener,
634        ) {
635        }
636        fn remove_status_listener(
637            self: Handle<Self>,
638            _app: &mut App,
639            _listener: &AnimationStatusListener,
640        ) {
641        }
642        fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
643            AnimationStatus::Forward
644        }
645        fn value(self: Handle<Self>, _app: &App) -> f64 {
646            0.25
647        }
648        fn is_animating(self: Handle<Self>, _app: &App) -> bool {
649            // Forward would say true; the override says false.
650            false
651        }
652    }
653
654    #[test]
655    fn the_erased_handle_dispatches_overridden_getters() {
656        let cell = AppCell::new();
657        let mut app = cell.borrow_mut();
658        let node = app.create(OverridingNode);
659        let animation: AnimationRef<f64> = node.erase();
660
661        assert_eq!(animation.status(&app), AnimationStatus::Forward);
662        assert_eq!(animation.value(&app), 0.25);
663        assert!(
664            !animation.is_animating(&app),
665            "the override, not the status"
666        );
667        assert!(animation.is_forward_or_completed(&app), "the default");
668    }
669
670    #[test]
671    fn erased_handles_are_equal_exactly_when_their_entities_are() {
672        let cell = AppCell::new();
673        let mut app = cell.borrow_mut();
674        let first = app.create(OverridingNode);
675        let second = app.create(OverridingNode);
676
677        assert_eq!(first.erase::<AnyAnimation<f64>>(), first.erase());
678        assert_eq!(
679            first.erase::<AnyAnimation<f64>>().handle(),
680            first.as_animation()
681        );
682        assert_ne!(first.erase::<AnyAnimation<f64>>(), second.erase());
683    }
684
685    /// A node whose `value` reads its slot.
686    struct Counter(u32);
687
688    impl Animation<f64> for Counter {
689        fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
690        fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
691        fn add_status_listener(
692            self: Handle<Self>,
693            _app: &mut App,
694            _listener: AnimationStatusListener,
695        ) {
696        }
697        fn remove_status_listener(
698            self: Handle<Self>,
699            _app: &mut App,
700            _listener: &AnimationStatusListener,
701        ) {
702        }
703        fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
704            AnimationStatus::Forward
705        }
706        fn value(self: Handle<Self>, app: &App) -> f64 {
707            f64::from(app.get(self).0)
708        }
709    }
710
711    #[test]
712    fn an_erased_handle_does_not_consume_the_typed_one() {
713        let cell = AppCell::new();
714        let mut app = cell.borrow_mut();
715        let counter = app.create(Counter(1));
716        let erased: AnimationRef<f64> = counter.erase();
717
718        // The concrete member stays reachable after erasing — the failure that
719        // killed the owned `Box<dyn>` shape.
720        app.get_mut(&counter).0 = 2;
721        assert_eq!(erased.value(&app), 2.0);
722    }
723
724    /// The erased handle looks nothing up; the stale check is `App::get`'s,
725    /// at the first member that reads the slot.
726    #[test]
727    #[should_panic(expected = "stale handle")]
728    fn an_erased_handle_to_a_freed_animation_panics_on_slot_access() {
729        let cell = AppCell::new();
730        let animation = cell.borrow_mut().create(Counter(1)).as_animation();
731        cell.checkpoint();
732        animation.value(&cell.borrow());
733    }
734
735    /// An erased kept animation keeps the object as the typed `Ref` does: they share one count.
736    #[test]
737    fn an_animation_ref_keeps_the_object_its_typed_ref_made() {
738        let cell = AppCell::new();
739        let counter = cell.borrow_mut().create(Counter(1));
740        let handle = counter.handle();
741        let erased: AnimationRef<f64> = counter.into_erased();
742        cell.checkpoint();
743        assert!(cell.borrow().contains(handle), "the erased ref keeps it");
744        assert_eq!(
745            handle.as_animation().upgrade(&cell.borrow()),
746            Some(erased.clone())
747        );
748        drop(erased);
749        cell.checkpoint();
750        assert!(!cell.borrow().contains(handle));
751    }
752
753    #[test]
754    fn a_status_listener_receives_the_status_and_the_app() {
755        thread_local! {
756            static RECEIVED: Cell<Option<AnimationStatus>> = const { Cell::new(None) };
757        }
758        let listener = AnimationStatusListener::new(|status, _app| {
759            RECEIVED.with(|received| received.set(Some(status)));
760        });
761        listener.call(AnimationStatus::Reverse, &mut AppCell::new().borrow_mut());
762        assert_eq!(RECEIVED.with(Cell::get), Some(AnimationStatus::Reverse));
763    }
764}