waft-animation 0.8.2

Animation controllers and curves for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! Flutter counterpart: `animation/animation.dart`.

use std::any::{TypeId, type_name};
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};
use std::rc::{Rc, Weak};

use waft_foundation::{App, Handle, HandleId, ListenableHandle, Listener, Ref, Retained};

use crate::tween::Animatable;

/// The status of an animation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AnimationStatus {
    /// The animation is stopped at the beginning.
    Dismissed,

    /// The animation is running from beginning to end.
    Forward,

    /// The animation is running backwards, from end to beginning.
    Reverse,

    /// The animation is stopped at the end.
    Completed,
}

impl AnimationStatus {
    /// Whether the animation is stopped at the beginning.
    pub fn is_dismissed(self) -> bool {
        self == AnimationStatus::Dismissed
    }

    /// Whether the animation is stopped at the end.
    pub fn is_completed(self) -> bool {
        self == AnimationStatus::Completed
    }

    /// Whether the animation is running in either direction.
    pub fn is_animating(self) -> bool {
        match self {
            AnimationStatus::Forward | AnimationStatus::Reverse => true,
            AnimationStatus::Completed | AnimationStatus::Dismissed => false,
        }
    }

    /// Whether the current aim of the animation is toward completion.
    pub fn is_forward_or_completed(self) -> bool {
        match self {
            AnimationStatus::Forward | AnimationStatus::Completed => true,
            AnimationStatus::Reverse | AnimationStatus::Dismissed => false,
        }
    }
}

/// Signature for listeners attached using [`Animation::add_status_listener`].
///
/// Like [`Listener`], this is a handle matched by identity: a listener over a
/// closure ([`AnimationStatusListener::new`]) is equal only to its own clones,
/// and a listener over an entity's associated function
/// ([`AnimationStatusListener::handle_method`]) is equal to any other built
/// from the same entity and function.
#[derive(Clone)]
pub struct AnimationStatusListener {
    callback: Rc<StatusCallback>,
    identity: StatusListenerIdentity,
}

type StatusCallback = dyn Fn(AnimationStatus, &mut App);

/// See `ListenerIdentity` on [`Listener`] — the same split for the same
/// reason, including the function-`TypeId` half.
#[derive(Clone, Copy)]
enum StatusListenerIdentity {
    Closure,
    HandleMethod(HandleId, TypeId),
}

impl AnimationStatusListener {
    /// Wraps a closure as a status listener.
    pub fn new(callback: impl Fn(AnimationStatus, &mut App) + 'static) -> AnimationStatusListener {
        AnimationStatusListener {
            callback: Rc::new(callback),
            identity: StatusListenerIdentity::Closure,
        }
    }

    /// Wraps an entity's associated function as a status listener.
    ///
    /// The counterpart of Dart passing the `notifyStatusListeners` tear-off;
    /// see [`Listener::handle_method`] for the identity rule. Pass the
    /// function by name — the compile-time assert rejects fn pointers and
    /// capturing closures, which have no canonical identity.
    ///
    /// The function is receiver-first, `(Handle<T>, &mut App, AnimationStatus)`,
    /// so a method on `Handle<T>` can be named directly.
    ///
    /// Like [`Listener::handle_method`], it does not keep its receiver, and is skipped once the
    /// receiver is freed.
    pub fn handle_method<T: 'static, F>(this: Handle<T>, f: F) -> AnimationStatusListener
    where
        F: Fn(Handle<T>, &mut App, AnimationStatus) + 'static,
    {
        const {
            assert!(
                std::mem::size_of::<F>() == 0,
                "pass the function by name: a fn pointer or capturing closure \
                 has no canonical identity to match on removal"
            )
        };
        AnimationStatusListener {
            callback: Rc::new(move |status, app: &mut App| {
                if app.tear_off_receiver_is_live(this) {
                    f(this, app, status);
                }
            }),
            identity: StatusListenerIdentity::HandleMethod(this.id(), TypeId::of::<F>()),
        }
    }

    /// Calls the closure.
    pub fn call(&self, status: AnimationStatus, app: &mut App) {
        (self.callback)(status, app);
    }

    /// A reference to this listener that does not keep its closure alive, for a closure that
    /// removes itself: Dart's `late AnimationStatusListener l; l = (status) { ...;
    /// animation.removeStatusListener(l); };` names itself, and a closure holding its own
    /// listener strongly would keep itself alive after the animation lets it go.
    pub fn downgrade(&self) -> WeakAnimationStatusListener {
        WeakAnimationStatusListener {
            callback: Rc::downgrade(&self.callback),
            identity: self.identity,
        }
    }
}

/// An [`AnimationStatusListener`] that does not keep its closure alive; see
/// [`AnimationStatusListener::downgrade`].
#[derive(Clone)]
pub struct WeakAnimationStatusListener {
    callback: Weak<StatusCallback>,
    identity: StatusListenerIdentity,
}

impl WeakAnimationStatusListener {
    /// The listener, equal to the one it was made from, while something still holds that one.
    pub fn upgrade(&self) -> Option<AnimationStatusListener> {
        Some(AnimationStatusListener {
            callback: self.callback.upgrade()?,
            identity: self.identity,
        })
    }
}

impl PartialEq for AnimationStatusListener {
    fn eq(&self, other: &AnimationStatusListener) -> bool {
        match (self.identity, other.identity) {
            (StatusListenerIdentity::Closure, StatusListenerIdentity::Closure) => {
                Rc::ptr_eq(&self.callback, &other.callback)
            }
            (
                StatusListenerIdentity::HandleMethod(entity, function),
                StatusListenerIdentity::HandleMethod(other_entity, other_function),
            ) => entity == other_entity && function == other_function,
            _ => false,
        }
    }
}

impl Eq for AnimationStatusListener {}

impl Hash for AnimationStatusListener {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self.identity {
            StatusListenerIdentity::Closure => {
                (Rc::as_ptr(&self.callback) as *const ()).hash(state);
            }
            StatusListenerIdentity::HandleMethod(entity, function) => {
                entity.hash(state);
                function.hash(state);
            }
        }
    }
}

impl Debug for AnimationStatusListener {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("AnimationStatusListener")
    }
}

/// A value which might change over time, moving forward or backward.
///
/// This is what a concrete animation implements — Dart's
/// `class X extends Animation<T>`. A field or parameter Dart types as
/// `Animation<T>` holds the erased [`AnimationRef<T>`] instead; get one from a
/// [`Ref`] with [`Retained::erase`], and the bare [`AnyAnimation<T>`]
/// that names it without keeping it from [`as_animation`](Animation::as_animation).
///
/// The members take `self: Handle<Self>` rather than `&self`, for the reason
/// recorded on the `listener_helpers` traits: a `&self` receiver would borrow
/// this animation's slot for the whole call, and the listener members hand
/// `&mut App` onward to reach other objects and run listeners.
pub trait Animation<T: 'static>: Sized + 'static {
    /// Calls the listener every time the value of the animation changes.
    ///
    /// Listeners can be removed with [`remove_listener`].
    ///
    /// [`remove_listener`]: Animation::remove_listener
    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener);

    /// Stop calling the listener every time the value of the animation
    /// changes.
    ///
    /// Listeners can be added with [`add_listener`].
    ///
    /// [`add_listener`]: Animation::add_listener
    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener);

    /// Calls listener every time the status of the animation changes.
    ///
    /// Listeners can be removed with [`remove_status_listener`].
    ///
    /// [`remove_status_listener`]: Animation::remove_status_listener
    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener);

    /// Stops calling the listener every time the status of the animation
    /// changes.
    ///
    /// Listeners can be added with [`add_status_listener`].
    ///
    /// [`add_status_listener`]: Animation::add_status_listener
    fn remove_status_listener(
        self: Handle<Self>,
        app: &mut App,
        listener: &AnimationStatusListener,
    );

    /// The current status of this animation.
    fn status(self: Handle<Self>, app: &App) -> AnimationStatus;

    /// The current value of the animation.
    ///
    /// Returns an owned `T`, not a reference: an animation may compute its
    /// value from its parent's (Dart's `CurvedAnimation.value` does), so there
    /// is no stored field for a reference to point at.
    fn value(self: Handle<Self>, app: &App) -> T;

    /// Whether this animation is stopped at the beginning.
    fn is_dismissed(self: Handle<Self>, app: &App) -> bool {
        Self::status(self, app).is_dismissed()
    }

    /// Whether this animation is stopped at the end.
    fn is_completed(self: Handle<Self>, app: &App) -> bool {
        Self::status(self, app).is_completed()
    }

    /// Whether this animation is running in either direction.
    fn is_animating(self: Handle<Self>, app: &App) -> bool {
        Self::status(self, app).is_animating()
    }

    /// Whether the current aim of this animation is toward completion.
    fn is_forward_or_completed(self: Handle<Self>, app: &App) -> bool {
        Self::status(self, app).is_forward_or_completed()
    }

    /// This animation as the erased [`AnyAnimation<T>`] — what to pass where
    /// a Dart API takes an `Animation<T>`.
    ///
    /// The object is untouched; this mints an erased second handle to it, so
    /// concrete members stay reachable through the typed one while the erased
    /// handle sits in a field Dart types as `Animation<T>`.
    fn as_animation(self: Handle<Self>) -> AnyAnimation<T> {
        AnyAnimation {
            id: self.id(),
            vtable: const { &AnimationVTable::of::<Self>() },
        }
    }
}

/// Erased [`Animation`]: one identity and a static vtable, the fat pointer
/// rustc cannot build for an arena id. No lease.
///
/// Like [`Handle`], it names the animation without keeping it: what a call that
/// only uses an animation takes. A field or parameter Dart types as
/// `Animation<T>` keeps it and holds an [`AnimationRef<T>`], which derefs to
/// this. The concrete animation stays in the [`App`] under its own type; the
/// handle carries its id plus a static dispatch table, so holding or copying one
/// borrows nothing, and the same object stays reachable through its typed
/// [`Handle`] for concrete-only members.
///
/// Equality is Dart's `==` on an object reference: two handles are equal
/// exactly when they address the same object.
pub struct AnyAnimation<T: 'static> {
    id: HandleId,
    vtable: &'static AnimationVTable<T>,
}

/// The vtable of an erased [`AnyAnimation`]: one `&'static` table per
/// concrete [`Animation`] type, built by [`AnimationVTable::of`].
///
/// It lives outside the arena — `&'static` — because a listener member hands
/// `&mut App` onward; dispatch read out of the arena would keep the arena
/// borrowed across that call.
struct AnimationVTable<T> {
    add_listener: fn(&mut App, HandleId, Listener),
    remove_listener: fn(&mut App, HandleId, &Listener),
    add_status_listener: fn(&mut App, HandleId, AnimationStatusListener),
    remove_status_listener: fn(&mut App, HandleId, &AnimationStatusListener),
    status: fn(&App, HandleId) -> AnimationStatus,
    value: fn(&App, HandleId) -> T,
    // The four derived getters dispatch through the object rather than
    // recomputing from `status`, because they are virtual in Dart —
    // `AnimationController` overrides `isAnimating`
    // (`animation_controller.dart:449`).
    is_dismissed: fn(&App, HandleId) -> bool,
    is_completed: fn(&App, HandleId) -> bool,
    is_animating: fn(&App, HandleId) -> bool,
    is_forward_or_completed: fn(&App, HandleId) -> bool,
}

/// The typed handle for an erased id. Free: nothing is looked up; `get` checks
/// the slot.
fn resolve<A: 'static>(id: HandleId) -> Handle<A> {
    Handle::from_id(id)
}

impl<T: 'static> AnimationVTable<T> {
    /// The table for one concrete animation type.
    const fn of<A: Animation<T>>() -> AnimationVTable<T> {
        AnimationVTable {
            add_listener: |app, id, listener| A::add_listener(resolve(id), app, listener),
            remove_listener: |app, id, listener| A::remove_listener(resolve(id), app, listener),
            add_status_listener: |app, id, listener| {
                A::add_status_listener(resolve(id), app, listener)
            },
            remove_status_listener: |app, id, listener| {
                A::remove_status_listener(resolve(id), app, listener)
            },
            status: |app, id| A::status(resolve(id), app),
            value: |app, id| A::value(resolve(id), app),
            is_dismissed: |app, id| A::is_dismissed(resolve(id), app),
            is_completed: |app, id| A::is_completed(resolve(id), app),
            is_animating: |app, id| A::is_animating(resolve(id), app),
            is_forward_or_completed: |app, id| A::is_forward_or_completed(resolve(id), app),
        }
    }
}

impl<T: 'static> AnyAnimation<T> {
    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// Dart's `animation as A`: the typed handle when this animation is an `A`, else `None`.
    pub fn downcast<A: 'static>(self, app: &App) -> Option<Handle<A>> {
        app.handle::<A>(self.id)
    }

    /// Calls the listener every time the value of the animation changes.
    ///
    /// Listeners can be removed with [`remove_listener`](AnyAnimation::remove_listener).
    pub fn add_listener(self, app: &mut App, listener: Listener) {
        (self.vtable.add_listener)(app, self.id, listener)
    }

    /// Stop calling the listener every time the value of the animation
    /// changes.
    ///
    /// Listeners can be added with [`add_listener`](AnyAnimation::add_listener).
    pub fn remove_listener(self, app: &mut App, listener: &Listener) {
        (self.vtable.remove_listener)(app, self.id, listener)
    }

    /// Calls listener every time the status of the animation changes.
    ///
    /// Listeners can be removed with
    /// [`remove_status_listener`](AnyAnimation::remove_status_listener).
    pub fn add_status_listener(self, app: &mut App, listener: AnimationStatusListener) {
        (self.vtable.add_status_listener)(app, self.id, listener)
    }

    /// Stops calling the listener every time the status of the animation
    /// changes.
    ///
    /// Listeners can be added with
    /// [`add_status_listener`](AnyAnimation::add_status_listener).
    pub fn remove_status_listener(self, app: &mut App, listener: &AnimationStatusListener) {
        (self.vtable.remove_status_listener)(app, self.id, listener)
    }

    /// The current status of this animation.
    pub fn status(self, app: &App) -> AnimationStatus {
        (self.vtable.status)(app, self.id)
    }

    /// The current value of the animation.
    pub fn value(self, app: &App) -> T {
        (self.vtable.value)(app, self.id)
    }

    /// Whether this animation is stopped at the beginning.
    pub fn is_dismissed(self, app: &App) -> bool {
        (self.vtable.is_dismissed)(app, self.id)
    }

    /// Whether this animation is stopped at the end.
    pub fn is_completed(self, app: &App) -> bool {
        (self.vtable.is_completed)(app, self.id)
    }

    /// Whether this animation is running in either direction.
    pub fn is_animating(self, app: &App) -> bool {
        (self.vtable.is_animating)(app, self.id)
    }

    /// Whether the current aim of this animation is toward completion.
    pub fn is_forward_or_completed(self, app: &App) -> bool {
        (self.vtable.is_forward_or_completed)(app, self.id)
    }
}

/// A field or parameter Dart types as `Animation<T>`: the erased animation, kept. It derefs to
/// the [`AnyAnimation<T>`], so every member is callable on it, and it is a
/// [`Listenable`](waft_foundation::Listenable) that keeps what it listens to.
pub type AnimationRef<T> = Retained<AnyAnimation<T>>;

waft_foundation::erased_handle!(AnyAnimation<T>: Animation => Animation::as_animation);

/// Dart's `Animation<double>.drive`, on a kept animation, since the animation it makes keeps
/// this one.
///
/// Dart's `Animation<U> drive<U>(Animatable<U> child)` is a generic virtual method; no dispatch
/// table can hold a generic, so ours is a trait over the references and cannot be overridden.
/// Flutter defines no override either — `animation.dart:325` forwards to `child.animate(this)`,
/// as this does.
pub trait Drive {
    /// Chains a `Tween` (or any [`Animatable`]) to this animation.
    fn drive<U: 'static>(
        &self,
        app: &mut App,
        child: impl Animatable<U> + Clone + 'static,
    ) -> AnimationRef<U>;
}

impl<A: Animation<f64>> Drive for Ref<A> {
    fn drive<U: 'static>(
        &self,
        app: &mut App,
        child: impl Animatable<U> + Clone + 'static,
    ) -> AnimationRef<U> {
        child.animate(app, self.erase())
    }
}

impl Drive for AnimationRef<f64> {
    fn drive<U: 'static>(
        &self,
        app: &mut App,
        child: impl Animatable<U> + Clone + 'static,
    ) -> AnimationRef<U> {
        child.animate(app, self.clone())
    }
}

impl<T: 'static> ListenableHandle for AnyAnimation<T> {
    fn add_listener_to(self, app: &mut App, listener: Listener) {
        AnyAnimation::add_listener(self, app, listener);
    }

    fn remove_listener_from(self, app: &mut App, listener: &Listener) {
        AnyAnimation::remove_listener(self, app, listener);
    }
}

// Written by hand so that `AnyAnimation<T>: Copy` does not require `T: Copy`,
// like `Handle<T>`.
impl<T> Clone for AnyAnimation<T> {
    fn clone(&self) -> AnyAnimation<T> {
        *self
    }
}

impl<T> Copy for AnyAnimation<T> {}

impl<T> Debug for AnyAnimation<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AnyAnimation<{}>({:?})", type_name::<T>(), self.id)
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use waft_foundation::AppCell;

    use super::*;

    #[test]
    fn a_weak_status_listener_upgrades_to_an_equal_listener_only_while_one_is_held() {
        let listener = AnimationStatusListener::new(|_, _| {});
        let weak = listener.downgrade();
        assert!(weak.upgrade().is_some_and(|upgraded| upgraded == listener));
        drop(listener);
        assert!(weak.upgrade().is_none());
    }

    #[test]
    fn the_derived_status_getters_match_flutter() {
        use AnimationStatus::*;

        assert_eq!(
            [
                Dismissed.is_dismissed(),
                Forward.is_dismissed(),
                Reverse.is_dismissed(),
                Completed.is_dismissed()
            ],
            [true, false, false, false]
        );
        assert_eq!(
            [
                Dismissed.is_completed(),
                Forward.is_completed(),
                Reverse.is_completed(),
                Completed.is_completed()
            ],
            [false, false, false, true]
        );
        assert_eq!(
            [
                Dismissed.is_animating(),
                Forward.is_animating(),
                Reverse.is_animating(),
                Completed.is_animating()
            ],
            [false, true, true, false]
        );
        assert_eq!(
            [
                Dismissed.is_forward_or_completed(),
                Forward.is_forward_or_completed(),
                Reverse.is_forward_or_completed(),
                Completed.is_forward_or_completed()
            ],
            [false, true, false, true]
        );
    }

    #[test]
    fn only_a_handle_to_the_same_status_closure_compares_equal() {
        let listener = AnimationStatusListener::new(|_status, _app| {});

        assert_eq!(listener, listener.clone());
        assert_ne!(listener, AnimationStatusListener::new(|_status, _app| {}));
    }

    #[test]
    fn a_rebuilt_handle_method_status_listener_matches_like_a_dart_tear_off() {
        struct Host;
        fn hook(_this: Handle<Host>, _app: &mut App, _status: AnimationStatus) {}

        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let a = app.create(Host);
        let b = app.create(Host);

        assert_eq!(
            AnimationStatusListener::handle_method(a.handle(), hook),
            AnimationStatusListener::handle_method(a.handle(), hook)
        );
        assert_ne!(
            AnimationStatusListener::handle_method(a.handle(), hook),
            AnimationStatusListener::handle_method(b.handle(), hook)
        );
        assert_ne!(
            AnimationStatusListener::handle_method(a.handle(), hook),
            AnimationStatusListener::new(|_status, _app| {})
        );
    }

    /// A minimal node: the erased handle must reach the overriding impl, not
    /// the trait defaults — `AnimationController` overrides `isAnimating`
    /// while stopped (`animation_controller.dart:449`).
    struct OverridingNode;

    impl Animation<f64> for OverridingNode {
        fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
        fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
        fn add_status_listener(
            self: Handle<Self>,
            _app: &mut App,
            _listener: AnimationStatusListener,
        ) {
        }
        fn remove_status_listener(
            self: Handle<Self>,
            _app: &mut App,
            _listener: &AnimationStatusListener,
        ) {
        }
        fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
            AnimationStatus::Forward
        }
        fn value(self: Handle<Self>, _app: &App) -> f64 {
            0.25
        }
        fn is_animating(self: Handle<Self>, _app: &App) -> bool {
            // Forward would say true; the override says false.
            false
        }
    }

    #[test]
    fn the_erased_handle_dispatches_overridden_getters() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let node = app.create(OverridingNode);
        let animation: AnimationRef<f64> = node.erase();

        assert_eq!(animation.status(&app), AnimationStatus::Forward);
        assert_eq!(animation.value(&app), 0.25);
        assert!(
            !animation.is_animating(&app),
            "the override, not the status"
        );
        assert!(animation.is_forward_or_completed(&app), "the default");
    }

    #[test]
    fn erased_handles_are_equal_exactly_when_their_entities_are() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let first = app.create(OverridingNode);
        let second = app.create(OverridingNode);

        assert_eq!(first.erase::<AnyAnimation<f64>>(), first.erase());
        assert_eq!(
            first.erase::<AnyAnimation<f64>>().handle(),
            first.as_animation()
        );
        assert_ne!(first.erase::<AnyAnimation<f64>>(), second.erase());
    }

    /// A node whose `value` reads its slot.
    struct Counter(u32);

    impl Animation<f64> for Counter {
        fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
        fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
        fn add_status_listener(
            self: Handle<Self>,
            _app: &mut App,
            _listener: AnimationStatusListener,
        ) {
        }
        fn remove_status_listener(
            self: Handle<Self>,
            _app: &mut App,
            _listener: &AnimationStatusListener,
        ) {
        }
        fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
            AnimationStatus::Forward
        }
        fn value(self: Handle<Self>, app: &App) -> f64 {
            f64::from(app.get(self).0)
        }
    }

    #[test]
    fn an_erased_handle_does_not_consume_the_typed_one() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(1));
        let erased: AnimationRef<f64> = counter.erase();

        // The concrete member stays reachable after erasing — the failure that
        // killed the owned `Box<dyn>` shape.
        app.get_mut(&counter).0 = 2;
        assert_eq!(erased.value(&app), 2.0);
    }

    /// The erased handle looks nothing up; the stale check is `App::get`'s,
    /// at the first member that reads the slot.
    #[test]
    #[should_panic(expected = "stale handle")]
    fn an_erased_handle_to_a_freed_animation_panics_on_slot_access() {
        let cell = AppCell::new();
        let animation = cell.borrow_mut().create(Counter(1)).as_animation();
        cell.checkpoint();
        animation.value(&cell.borrow());
    }

    /// An erased kept animation keeps the object as the typed `Ref` does: they share one count.
    #[test]
    fn an_animation_ref_keeps_the_object_its_typed_ref_made() {
        let cell = AppCell::new();
        let counter = cell.borrow_mut().create(Counter(1));
        let handle = counter.handle();
        let erased: AnimationRef<f64> = counter.into_erased();
        cell.checkpoint();
        assert!(cell.borrow().contains(handle), "the erased ref keeps it");
        assert_eq!(
            handle.as_animation().upgrade(&cell.borrow()),
            Some(erased.clone())
        );
        drop(erased);
        cell.checkpoint();
        assert!(!cell.borrow().contains(handle));
    }

    #[test]
    fn a_status_listener_receives_the_status_and_the_app() {
        thread_local! {
            static RECEIVED: Cell<Option<AnimationStatus>> = const { Cell::new(None) };
        }
        let listener = AnimationStatusListener::new(|status, _app| {
            RECEIVED.with(|received| received.set(Some(status)));
        });
        listener.call(AnimationStatus::Reverse, &mut AppCell::new().borrow_mut());
        assert_eq!(RECEIVED.with(Cell::get), Some(AnimationStatus::Reverse));
    }
}