Skip to main content

waft_widgets/widgets/
heroes.rs

1//! Flutter counterpart: `widgets/heroes.dart`.
2//!
3//! [`Hero`] and the [`HeroController`] that flies matching heroes between two [`PageRoute`]s
4//! in the navigator's overlay.
5//!
6//! [`PageRoute`]: crate::PageRoute
7
8use crate::widgets::pages::PageRouteRef;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11
12use indexmap::IndexMap;
13use waft_animation::{
14    Animatable, Animation, AnimationRef, AnimationStatus, AnimationStatusListener, AnyAnimation,
15    Curve, CurveTween, CurvedAnimation, Curves, Drive, Interval, ProxyAnimation, RectTween,
16    ReverseAnimation, Tween, k_always_complete_animation,
17};
18use waft_embedder::{Offset, Rect, Size};
19use waft_foundation::{
20    AnyEq, App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Handle,
21    ListenableObject, Listener, OptionRetained, Retained,
22};
23use waft_painting::transform_rect;
24use waft_scheduler::{FrameCallback, SchedulerBinding};
25
26use crate::framework::{
27    AnyElement, BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget,
28    StatelessWidget, WidgetRef, downcast_widget,
29};
30use crate::view::View;
31use crate::widgets::basic::{IgnorePointer, KeyedSubtree, Offstage, Positioned, SizedBox};
32use crate::widgets::implicit_animations::EdgeInsetsTween;
33use crate::widgets::media_query::MediaQuery;
34use crate::widgets::navigator::{
35    AnyRoute, Navigator, NavigatorObserver, NavigatorObserverData, NavigatorState,
36};
37use crate::widgets::overlay::{OverlayEntry, OverlayState};
38use crate::widgets::routes::AnyModalRoute;
39use crate::widgets::ticker_provider::TickerMode;
40use crate::widgets::transitions::{AnimatedBuilder, FadeTransition};
41use waft_foundation::Ref;
42
43// ---------------------------------------------------------------------------------------------
44// Tween<Rect?>
45
46/// Dart's `Tween<Rect?>`: the tween a [`CreateRectTween`] returns and a hero flight animates
47/// the hero's bounds with.
48///
49/// Rust has no subtyping, so a flight holds this as `Rc<dyn RectTweenObject>`; waft-animation's
50/// `RectTween` — Dart's default — implements it, and so does any tween a caller supplies.
51pub trait RectTweenObject: 'static {
52    /// The value this variable has at the beginning of the animation.
53    fn begin(&self, app: &App) -> Option<Rect>;
54
55    /// The value this variable has at the end of the animation.
56    fn end(&self, app: &App) -> Option<Rect>;
57
58    /// Returns the value this variable has at the given animation clock value.
59    fn lerp(&self, app: &App, t: f64) -> Option<Rect>;
60
61    /// Returns the value this variable has at the given animation clock value, snapping to
62    /// [`begin`](Self::begin) and [`end`](Self::end) at the ends of the interval.
63    fn transform(&self, app: &App, t: f64) -> Option<Rect> {
64        if t == 0.0 {
65            return self.begin(app);
66        }
67        if t == 1.0 {
68            return self.end(app);
69        }
70        self.lerp(app, t)
71    }
72
73    /// The current value of this object for the given animation.
74    fn evaluate(&self, app: &App, animation: AnyAnimation<f64>) -> Option<Rect> {
75        self.transform(app, animation.value(app))
76    }
77}
78
79impl RectTweenObject for Ref<RectTween> {
80    fn begin(&self, app: &App) -> Option<Rect> {
81        app.get(self).begin
82    }
83
84    fn end(&self, app: &App) -> Option<Rect> {
85        app.get(self).end
86    }
87
88    fn lerp(&self, app: &App, t: f64) -> Option<Rect> {
89        RectTween::lerp(self.handle(), app, t)
90    }
91}
92
93/// Dart's `ReverseTween<Rect?>`: a tween that evaluates its parent in reverse.
94///
95/// waft-animation's `ReverseTween` wraps a concrete `Tween<T>`, which the erased tween a
96/// [`CreateRectTween`] returns is not.
97struct ReverseRectTween {
98    parent: Rc<dyn RectTweenObject>,
99}
100
101impl RectTweenObject for ReverseRectTween {
102    fn begin(&self, app: &App) -> Option<Rect> {
103        self.parent.end(app)
104    }
105
106    fn end(&self, app: &App) -> Option<Rect> {
107        self.parent.begin(app)
108    }
109
110    fn lerp(&self, app: &App, t: f64) -> Option<Rect> {
111        self.parent.lerp(app, 1.0 - t)
112    }
113}
114
115/// Signature for a function that takes two [`Rect`] instances and returns a `RectTween` that
116/// transitions between them.
117///
118/// This is typically used with a [`HeroController`] to provide an animation for [`Hero`]
119/// positions that looks nicer than a linear movement. For example, see `MaterialRectArcTween`.
120pub type CreateRectTween =
121    Rc<dyn Fn(&mut App, Option<Rect>, Option<Rect>) -> Rc<dyn RectTweenObject>>;
122
123/// Signature for a function that builds a [`Hero`] placeholder widget given a child and a
124/// [`Size`].
125///
126/// The child can optionally be part of the returned widget tree. The returned widget should
127/// typically be constrained to `hero_size`, if it doesn't do so implicitly.
128///
129/// See also:
130///
131///  * `TransitionBuilder`, which is similar but only takes a [`BuildContext`] and a child
132///    widget.
133pub type HeroPlaceholderBuilder = Rc<dyn Fn(&mut App, BuildContext, Size, WidgetRef) -> WidgetRef>;
134
135/// A function that lets [`Hero`]es self supply a widget that is shown during the hero's flight
136/// from one route to another instead of default (which is to show the destination route's
137/// instance of the hero).
138pub type HeroFlightShuttleBuilder = Rc<
139    dyn Fn(
140        &mut App,
141        BuildContext,
142        AnimationRef<f64>,
143        HeroFlightDirection,
144        BuildContext,
145        BuildContext,
146    ) -> WidgetRef,
147>;
148
149type OnFlightEnded = Rc<dyn Fn(&mut App, Handle<HeroFlight>)>;
150
151/// Direction of the hero's flight based on the navigation operation.
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub enum HeroFlightDirection {
154    /// A flight triggered by a route push.
155    ///
156    /// The animation goes from 0 to 1.
157    ///
158    /// If no custom [`HeroFlightShuttleBuilder`] is supplied, the top route's [`Hero`] child is
159    /// shown in flight.
160    Push,
161
162    /// A flight triggered by a route pop.
163    ///
164    /// The animation goes from 1 to 0.
165    ///
166    /// If no custom [`HeroFlightShuttleBuilder`] is supplied, the bottom route's [`Hero`] child
167    /// is shown in flight.
168    Pop,
169}
170
171// ---------------------------------------------------------------------------------------------
172// Hero
173
174/// A widget that marks its child as being a candidate for
175/// [hero animations](https://docs.flutter.dev/ui/animations/hero-animations).
176///
177/// When a `PageRoute` is pushed or popped with the [`Navigator`], the entire screen's content is
178/// replaced. An old route disappears and a new route appears. If there's a common visual feature
179/// on both routes then it can be helpful for orienting the user for the feature to physically
180/// move from one page to the other during the routes' transition. Such an animation is called a
181/// *hero animation*. The hero widgets "fly" in the navigator's overlay during the transition and
182/// while they're in-flight they're, by default, not shown in their original locations in the old
183/// and new routes.
184///
185/// To label a widget as such a feature, wrap it in a [`Hero`] widget. When navigation happens,
186/// the [`Hero`] widgets on each route are identified by the [`HeroController`]. For each pair of
187/// [`Hero`] widgets that have the same tag, a hero animation is triggered.
188///
189/// If a [`Hero`] is already in flight when navigation occurs, its flight animation will be
190/// redirected to its new destination. The widget shown in-flight during the transition is, by
191/// default, the destination route's [`Hero`]'s child.
192///
193/// For a hero animation to trigger, the hero has to exist on the very first frame of the new
194/// page's animation.
195///
196/// Routes must not contain more than one [`Hero`] for each [`tag`](Self::tag).
197///
198/// ## Discussion
199///
200/// Heroes and the [`Navigator`]'s `Overlay` `Stack` must be axis-aligned for all this to work.
201/// The top left and bottom right coordinates of each animated hero will be converted to global
202/// coordinates and then from there converted to that `Stack`'s coordinate space, and the entire
203/// hero subtree will, for the duration of the animation, be lifted out of its original place,
204/// and positioned on that stack. If the [`Hero`] isn't axis aligned, this is going to fail in a
205/// rather ugly fashion. Don't rotate your heroes!
206///
207/// To make the animations look good, it's critical that the widget tree for the hero in both
208/// locations be essentially identical. The widget of the *target* is, by default, used to do the
209/// transition: when going from route A to route B, route B's hero's widget is placed over route
210/// A's hero's widget. Additionally, if the [`Hero`] subtree changes appearance based on an
211/// `InheritedWidget` (such as [`MediaQuery`] or `Theme`), then the hero animation may have
212/// discontinuity at the start or the end of the animation because route A and route B provides
213/// different such `InheritedWidget`s. Consider providing a custom
214/// [`flight_shuttle_builder`](Self::flight_shuttle_builder) to ensure smooth transitions. The
215/// default flight shuttle builder interpolates [`MediaQuery`]'s paddings. If your [`Hero`] widget
216/// uses custom `InheritedWidget`s and displays a discontinuity in the animation, try to provide
217/// custom in-flight transition using [`flight_shuttle_builder`](Self::flight_shuttle_builder).
218///
219/// By default, both route A and route B's heroes are hidden while the transitioning widget is
220/// animating in-flight above the 2 routes. [`placeholder_builder`](Self::placeholder_builder) can
221/// be used to show a custom widget in their place instead once the transition has taken flight.
222///
223/// During the transition, the transition widget is animated to route B's hero's position, and
224/// then the widget is inserted into route B. When going back from B to A, route A's hero's widget
225/// is, by default, placed over where route B's hero's widget was, and then the animation goes the
226/// other way.
227///
228/// ### Nested Navigators
229///
230/// If either or both routes contain nested [`Navigator`]s, only [`Hero`]es contained in the
231/// top-most routes (as defined by `Route::is_current`) *of those nested [`Navigator`]s* are
232/// considered for animation. Just like in the non-nested case the top-most routes containing
233/// these [`Hero`]es in the nested [`Navigator`]s have to be `PageRoute`s.
234pub struct Hero {
235    /// See [`Widget::key`](crate::Widget::key).
236    pub key: Option<KeyRef>,
237    /// The identifier for this particular hero. If the tag of this hero matches the tag of a
238    /// hero on a `PageRoute` that we're navigating to or from, then a hero animation will be
239    /// triggered.
240    pub tag: Rc<dyn AnyEq>,
241    /// Defines how the destination hero's bounds change as it flies from the starting route to
242    /// the destination route.
243    ///
244    /// A hero flight begins with the destination hero's [`child`](Self::child) aligned with the
245    /// starting hero's child. The tween returned by this callback is used to compute the hero's
246    /// bounds as the flight animation's value goes from 0.0 to 1.0.
247    ///
248    /// If this property is `None`, the default, then the value of
249    /// [`HeroController::create_rect_tween`] is used.
250    pub create_rect_tween: Option<CreateRectTween>,
251    /// The widget subtree that will "fly" from one route to another during a [`Navigator`] push
252    /// or pop transition.
253    ///
254    /// The appearance of this subtree should be similar to the appearance of the subtrees of any
255    /// other heroes in the application with the same [`tag`](Self::tag). Changes in scale and
256    /// aspect ratio work well in hero animations, changes in layout or composition do not.
257    pub child: WidgetRef,
258    /// Optional override to supply a widget that's shown during the hero's flight.
259    ///
260    /// This in-flight widget can depend on the route transition's animation as well as the
261    /// incoming and outgoing routes' [`Hero`] descendants' widgets and layout.
262    ///
263    /// When both the source and destination [`Hero`]es provide a
264    /// [`flight_shuttle_builder`](Self::flight_shuttle_builder), the destination's takes
265    /// precedence.
266    ///
267    /// If none is provided, the destination route's hero child is shown in-flight by default.
268    ///
269    /// ## Limitations
270    ///
271    /// If a widget built by [`flight_shuttle_builder`](Self::flight_shuttle_builder) takes part
272    /// in a [`Navigator`] push transition, that widget or its descendants must not have any
273    /// `GlobalKey` that is used in the source hero's descendant widgets. That is because both
274    /// subtrees will be included in the widget tree during the hero flight animation, and
275    /// `GlobalKey`s must be unique across the entire widget tree.
276    ///
277    /// If the said `GlobalKey` is essential to your application, consider providing a custom
278    /// [`placeholder_builder`](Self::placeholder_builder) for the source hero, to avoid the
279    /// `GlobalKey` collision, such as a builder that builds an empty [`SizedBox`], keeping the
280    /// hero [`child`](Self::child)'s original size.
281    pub flight_shuttle_builder: Option<HeroFlightShuttleBuilder>,
282    /// Placeholder widget left in place as the hero's [`child`](Self::child) once the flight
283    /// takes off.
284    ///
285    /// By default the placeholder widget is an empty [`SizedBox`] keeping the hero child's
286    /// original size, unless this hero is a source hero of a [`Navigator`] push transition, in
287    /// which case [`child`](Self::child) will be a descendant of the placeholder and will be kept
288    /// [`Offstage`] during the hero's flight.
289    pub placeholder_builder: Option<HeroPlaceholderBuilder>,
290    /// Whether to perform the hero transition if the `PageRoute` transition was triggered by a
291    /// user gesture, such as a back swipe on iOS.
292    ///
293    /// If [`Hero`]es with the same [`tag`](Self::tag) on both the from and the to routes have
294    /// [`transition_on_user_gestures`](Self::transition_on_user_gestures) set to true, a back
295    /// swipe gesture will trigger the same hero animation as a programmatically triggered push or
296    /// pop.
297    ///
298    /// The route being popped to or the bottom route must also have `PageRoute::maintain_state`
299    /// set to true for a gesture triggered hero transition to work.
300    ///
301    /// Defaults to false.
302    pub transition_on_user_gestures: bool,
303    /// The curve to use in the forward direction.
304    ///
305    /// Defaults to `Curves::fast_out_slow_in()`.
306    pub curve: Rc<dyn Curve>,
307    /// The curve to use in the reverse direction.
308    ///
309    /// If this property is `None`, [`Hero::curve`]`.flipped()` is used.
310    pub reverse_curve: Option<Rc<dyn Curve>>,
311}
312
313impl Hero {
314    /// Create a hero; Dart's optional named arguments are the setters.
315    ///
316    /// The `child` parameter and all of its descendants must not be [`Hero`]es.
317    ///
318    /// Dart's defaults: `transition_on_user_gestures` false, `curve` `Curves::fast_out_slow_in()`.
319    #[cfg_attr(debug_assertions, track_caller)]
320    pub fn new<K>(tag: Rc<dyn AnyEq>, child: impl IntoWidget<K>) -> Hero {
321        Hero {
322            key: None,
323            tag,
324            create_rect_tween: None,
325            child: child.into_widget(),
326            flight_shuttle_builder: None,
327            placeholder_builder: None,
328            transition_on_user_gestures: false,
329            curve: Curves::fast_out_slow_in(),
330            reverse_curve: None,
331        }
332    }
333
334    /// Dart `Hero(key:)`.
335    pub fn key(mut self, key: KeyRef) -> Hero {
336        self.key = Some(key);
337        self
338    }
339
340    /// Dart `Hero(createRectTween:)`.
341    pub fn create_rect_tween(mut self, create_rect_tween: CreateRectTween) -> Hero {
342        self.create_rect_tween = Some(create_rect_tween);
343        self
344    }
345
346    /// Dart `Hero(flightShuttleBuilder:)`.
347    pub fn flight_shuttle_builder(
348        mut self,
349        flight_shuttle_builder: HeroFlightShuttleBuilder,
350    ) -> Hero {
351        self.flight_shuttle_builder = Some(flight_shuttle_builder);
352        self
353    }
354
355    /// Dart `Hero(placeholderBuilder:)`.
356    pub fn placeholder_builder(mut self, placeholder_builder: HeroPlaceholderBuilder) -> Hero {
357        self.placeholder_builder = Some(placeholder_builder);
358        self
359    }
360
361    /// Dart `Hero(transitionOnUserGestures:)`.
362    pub fn transition_on_user_gestures(mut self, transition_on_user_gestures: bool) -> Hero {
363        self.transition_on_user_gestures = transition_on_user_gestures;
364        self
365    }
366
367    /// Dart `Hero(curve:)`.
368    pub fn curve(mut self, curve: Rc<dyn Curve>) -> Hero {
369        self.curve = curve;
370        self
371    }
372
373    /// Dart `Hero(reverseCurve:)`.
374    pub fn reverse_curve(mut self, reverse_curve: Rc<dyn Curve>) -> Hero {
375        self.reverse_curve = Some(reverse_curve);
376        self
377    }
378
379    /// Returns a map of all of the heroes in `context` indexed by hero tag that should be
380    /// considered for animation when `navigator` transitions from one `PageRoute` to another.
381    fn all_heroes_for(
382        app: &mut App,
383        context: BuildContext,
384        is_user_gesture_transition: bool,
385        navigator: Handle<NavigatorState>,
386    ) -> IndexMap<Rc<dyn AnyEq>, Handle<HeroState>> {
387        let mut result: IndexMap<Rc<dyn AnyEq>, Handle<HeroState>> = IndexMap::new();
388
389        // Dart's `visitor` decides on each element and recurses; the walk itself only reads the
390        // tree, so it collects the heroes in visit order and `invite_hero`'s `Navigator::of` /
391        // `AnyModalRoute::of` / `end_flight`, which need `&mut App`, run after it.
392        fn visitor(app: &App, element: AnyElement, heroes: &mut Vec<AnyElement>) {
393            let widget = element.widget(app).clone();
394            if downcast_widget::<Hero>(&*widget).is_some() {
395                heroes.push(element);
396            } else if downcast_widget::<HeroMode>(&*widget).is_some_and(|mode| !mode.enabled) {
397                return;
398            }
399            element.visit_children(app, &mut |child| visitor(app, child, heroes));
400        }
401
402        let mut heroes = Vec::new();
403        context.visit_child_elements(app, &mut |child| visitor(app, child, &mut heroes));
404
405        for hero in heroes {
406            let widget = hero.widget(app).clone();
407            let hero_widget =
408                downcast_widget::<Hero>(&*widget).expect("collected from the Hero branch");
409            let tag = Rc::clone(&hero_widget.tag);
410            let transition_on_user_gestures = hero_widget.transition_on_user_gestures;
411            if Navigator::of(app, hero, false) == navigator {
412                invite_hero(
413                    app,
414                    &mut result,
415                    hero,
416                    tag,
417                    transition_on_user_gestures,
418                    is_user_gesture_transition,
419                );
420            } else {
421                // The nearest navigator to the hero is not the navigator that is currently
422                // transitioning from one route to another. This means the hero is inside a nested
423                // navigator and should only be considered for animation if it is part of the
424                // top-most route in that nested navigator and if that route is also a
425                // `PageRoute`.
426                let hero_route = AnyModalRoute::of(app, hero);
427                if let Some(hero_route) = hero_route
428                    && hero_route.as_route().as_page_route(app).is_some()
429                    && hero_route.as_route().is_current(app)
430                {
431                    invite_hero(
432                        app,
433                        &mut result,
434                        hero,
435                        tag,
436                        transition_on_user_gestures,
437                        is_user_gesture_transition,
438                    );
439                }
440            }
441        }
442
443        fn invite_hero(
444            app: &mut App,
445            result: &mut IndexMap<Rc<dyn AnyEq>, Handle<HeroState>>,
446            hero: AnyElement,
447            tag: Rc<dyn AnyEq>,
448            transition_on_user_gestures: bool,
449            is_user_gesture_transition: bool,
450        ) {
451            debug_assert!(
452                !result.contains_key(&tag),
453                "There are multiple heroes that share the same tag within a subtree. Within each \
454                 subtree for which heroes are to be animated (i.e. a PageRoute subtree), each \
455                 Hero must have a unique non-null tag."
456            );
457            let hero_state = hero
458                .state_handle::<HeroState>(app)
459                .expect("a Hero element holds a HeroState");
460            if !is_user_gesture_transition || transition_on_user_gestures {
461                result.insert(tag, hero_state);
462            } else {
463                // If transition is not allowed, we need to make sure hero is not hidden.
464                // A hero can be hidden previously due to hero transition.
465                hero_state.end_flight(app, false);
466            }
467        }
468
469        result
470    }
471}
472
473impl StatefulWidget for Hero {
474    type State = HeroState;
475
476    fn key(&self) -> Option<&KeyRef> {
477        self.key.as_ref()
478    }
479
480    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
481        properties.add(DiagnosticsProperty::<String>::new(
482            "tag",
483            Some(format!("{:?}", self.tag)),
484        ));
485    }
486
487    fn create_state(&self) -> HeroState {
488        HeroState {
489            state: StateData::new(),
490            key: GlobalKey::new(),
491            placeholder_size: None,
492            should_include_child: true,
493        }
494    }
495}
496
497impl Debug for Hero {
498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499        f.debug_struct("Hero")
500            .field("tag", &self.tag)
501            .finish_non_exhaustive()
502    }
503}
504
505/// The [`Hero`] widget displays different content based on whether it is in an animated
506/// transition ("flight"), from/to another [`Hero`] with the same tag:
507///   * When [`start_flight`](Self::start_flight) is called, the real content of this [`Hero`]
508///     will be replaced by a "placeholder" widget.
509///   * When the flight ends, the "toHero"'s [`end_flight`](Self::end_flight) method must be
510///     called by the hero controller, so the real content of that [`Hero`] becomes visible again
511///     when the animation completes.
512///
513/// Dart's `_HeroState`.
514pub struct HeroState {
515    state: StateData<Hero>,
516    key: GlobalKey,
517    placeholder_size: Option<Size>,
518    // Whether the placeholder widget should wrap the hero's child widget as its own child, when
519    // `placeholder_size` is non-null (i.e. the hero is currently in its flight animation). See
520    // `start_flight`.
521    should_include_child: bool,
522}
523
524impl HeroState {
525    /// Replaces this hero's content with a placeholder of its current size.
526    ///
527    /// The `should_included_child_in_placeholder` flag dictates if the child widget of this hero
528    /// should be included in the placeholder widget as a descendant.
529    ///
530    /// When a new hero flight animation takes place, a placeholder widget needs to be built to
531    /// replace the original hero widget. When `should_included_child_in_placeholder` is set to
532    /// true and [`Hero::placeholder_builder`] is `None`, the placeholder widget will include the
533    /// original hero's child widget as a descendant, allowing the original element tree to be
534    /// preserved.
535    ///
536    /// It is typically set to true for the *from* hero in a push transition, and false otherwise.
537    pub fn start_flight(
538        self: Handle<Self>,
539        app: &mut App,
540        should_included_child_in_placeholder: bool,
541    ) {
542        app.get_mut(self).should_include_child = should_included_child_in_placeholder;
543        debug_assert!(self.mounted(app));
544        let render_box = self
545            .context(app)
546            .find_render_object(app)
547            .expect("a mounted Hero has a render object")
548            .as_box()
549            .expect("a Hero's render object is a box");
550        debug_assert!(render_box.has_size(app));
551        let size = render_box.size(app);
552        self.set_state(app, |state| state.placeholder_size = Some(size));
553    }
554
555    /// Restores this hero's content once its flight is over.
556    ///
557    /// When `keep_placeholder` is true, the placeholder will continue to be shown after the
558    /// flight ends. Otherwise the child of the hero will become visible and its [`TickerMode`]
559    /// will be re-enabled.
560    ///
561    /// This method can be safely called even when this [`Hero`] is currently not in a flight.
562    pub fn end_flight(self: Handle<Self>, app: &mut App, keep_placeholder: bool) {
563        if keep_placeholder || app.get(self).placeholder_size.is_none() {
564            return;
565        }
566
567        app.get_mut(self).placeholder_size = None;
568        if self.mounted(app) {
569            // Tell the widget to rebuild if it's mounted. `placeholder_size` has already been
570            // updated.
571            self.set_state(app, |_| {});
572        }
573    }
574}
575
576impl State for HeroState {
577    type Widget = Hero;
578    crate::state_accessors!();
579
580    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
581        debug_assert!(
582            context
583                .find_ancestor_widget_of_exact_type::<Hero>(app)
584                .is_none(),
585            "A Hero widget cannot be the descendant of another Hero widget."
586        );
587
588        let placeholder_size = app.get(self).placeholder_size;
589        let show_placeholder = placeholder_size.is_some();
590
591        if show_placeholder
592            && let Some(placeholder_builder) = self.widget(app).placeholder_builder.clone()
593        {
594            let child = self.widget(app).child.clone();
595            let size = placeholder_size.expect("the placeholder is showing");
596            return placeholder_builder(app, context, size, child);
597        }
598
599        if show_placeholder && !app.get(self).should_include_child {
600            let size = placeholder_size.expect("the placeholder is showing");
601            return SizedBox::new()
602                .width(size.width())
603                .height(size.height())
604                .into_widget();
605        }
606
607        let key = app.get(self).key.clone();
608        let child = self.widget(app).child.clone();
609        let mut sized = SizedBox::new();
610        if let Some(size) = placeholder_size {
611            sized = sized.width(size.width()).height(size.height());
612        }
613        sized
614            .child(
615                Offstage::new()
616                    .offstage(show_placeholder)
617                    .child(TickerMode::new(
618                        !show_placeholder,
619                        KeyedSubtree::new(child).key(key.into()),
620                    )),
621            )
622            .into_widget()
623    }
624}
625
626// ---------------------------------------------------------------------------------------------
627// _HeroFlightManifest
628
629/// Everything known about a hero flight that's to be started or diverted.
630struct HeroFlightManifest {
631    r#type: HeroFlightDirection,
632    overlay: Handle<OverlayState>,
633    from_route: PageRouteRef,
634    to_route: PageRouteRef,
635    from_hero: Ref<HeroState>,
636    to_hero: Ref<HeroState>,
637    create_rect_tween: Option<CreateRectTween>,
638    shuttle_builder: HeroFlightShuttleBuilder,
639    is_user_gesture_transition: bool,
640    is_diverted: bool,
641
642    animation: Option<Ref<CurvedAnimation>>,
643    // Dart's three `late final` fields, computed on first read and cached.
644    from_hero_location: Option<Rect>,
645    to_hero_location: Option<Rect>,
646    is_valid: Option<bool>,
647}
648
649impl HeroFlightManifest {
650    #[expect(clippy::too_many_arguments, reason = "Dart's required named arguments")]
651    fn new(
652        app: &mut App,
653        r#type: HeroFlightDirection,
654        overlay: Handle<OverlayState>,
655        from_route: PageRouteRef,
656        to_route: PageRouteRef,
657        from_hero: Handle<HeroState>,
658        to_hero: Handle<HeroState>,
659        create_rect_tween: Option<CreateRectTween>,
660        shuttle_builder: HeroFlightShuttleBuilder,
661        is_user_gesture_transition: bool,
662        is_diverted: bool,
663    ) -> Ref<HeroFlightManifest> {
664        debug_assert!(*from_hero.widget(app).tag == *to_hero.widget(app).tag);
665        let from_hero = from_hero.keep(app);
666        let to_hero = to_hero.keep(app);
667        app.create(HeroFlightManifest {
668            r#type,
669            overlay,
670            from_route,
671            to_route,
672            from_hero,
673            to_hero,
674            create_rect_tween,
675            shuttle_builder,
676            is_user_gesture_transition,
677            is_diverted,
678            animation: None,
679            from_hero_location: None,
680            to_hero_location: None,
681            is_valid: None,
682        })
683    }
684
685    fn tag(self: Handle<Self>, app: &App) -> Rc<dyn AnyEq> {
686        let from_hero = app.get(self).from_hero.handle();
687        Rc::clone(&from_hero.widget(app).tag)
688    }
689
690    fn animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
691        if let Some(animation) = &app.get(self).animation {
692            return animation.erase();
693        }
694        let (curve, reverse_curve, parent) = match app.get(self).r#type {
695            HeroFlightDirection::Push => {
696                let to_route = app.get(self).to_route.handle();
697                let parent = to_route
698                    .as_modal_route()
699                    .animation(app)
700                    .expect("an installed route has an animation");
701                let to_hero = app.get(self).to_hero.handle();
702                let widget = to_hero.widget(app);
703                let curve = Rc::clone(&widget.curve);
704                let reverse_curve = widget
705                    .reverse_curve
706                    .clone()
707                    .unwrap_or_else(|| Rc::new(Rc::clone(&curve).flipped()));
708                (curve, reverse_curve, parent)
709            }
710            HeroFlightDirection::Pop => {
711                let from_route = app.get(self).from_route.handle();
712                let parent = from_route
713                    .as_modal_route()
714                    .animation(app)
715                    .expect("an installed route has an animation");
716                let from_hero = app.get(self).from_hero.handle();
717                let widget = from_hero.widget(app);
718                let curve = Rc::clone(&widget.curve);
719                let reverse_curve = widget
720                    .reverse_curve
721                    .clone()
722                    .unwrap_or_else(|| Rc::new(Rc::clone(&curve).flipped()));
723                (curve, reverse_curve, parent)
724            }
725        };
726
727        let parent = parent.keep(app);
728        let reverse_curve = (!app.get(self).is_diverted).then_some(reverse_curve);
729        let animation = CurvedAnimation::new(app, parent, curve, reverse_curve);
730        let erased = animation.erase();
731        app.get_mut(self).animation = Some(animation);
732        erased
733    }
734
735    fn create_hero_rect_tween(
736        self: Handle<Self>,
737        app: &mut App,
738        begin: Option<Rect>,
739        end: Option<Rect>,
740    ) -> Rc<dyn RectTweenObject> {
741        let to_hero = app.get(self).to_hero.handle();
742        let create_rect_tween = to_hero
743            .widget(app)
744            .create_rect_tween
745            .clone()
746            .or_else(|| app.get(self).create_rect_tween.clone());
747        match create_rect_tween {
748            Some(create_rect_tween) => create_rect_tween(app, begin, end),
749            None => Rc::new(RectTween::new(app, begin, end)),
750        }
751    }
752
753    /// The bounding box for `context`'s render object, in `ancestor_context`'s render object's
754    /// coordinate space.
755    fn bounding_box_for(
756        app: &App,
757        context: BuildContext,
758        ancestor_context: Option<BuildContext>,
759    ) -> Rect {
760        debug_assert!(ancestor_context.is_some());
761        let render_box = context
762            .find_render_object(app)
763            .expect("a mounted hero has a render object")
764            .as_box()
765            .expect("a hero's render object is a box");
766        debug_assert!(render_box.has_size(app) && render_box.size(app).is_finite());
767        let ancestor = ancestor_context.and_then(|context| context.find_render_object(app));
768        transform_rect(
769            &render_box.as_object().get_transform_to(app, ancestor),
770            Offset::ZERO & render_box.size(app),
771        )
772    }
773
774    /// The bounding box of `from_hero`, in `from_route`'s coordinate space.
775    ///
776    /// This property should only be accessed in [`HeroFlight::start`].
777    fn from_hero_location(self: Handle<Self>, app: &mut App) -> Rect {
778        if let Some(location) = app.get(self).from_hero_location {
779            return location;
780        }
781        let context = app.get(self).from_hero.context(app);
782        let ancestor_context = app
783            .get(self)
784            .from_route
785            .as_modal_route()
786            .subtree_context(app);
787        let location = HeroFlightManifest::bounding_box_for(app, context, ancestor_context);
788        app.get_mut(self).from_hero_location = Some(location);
789        location
790    }
791
792    /// The bounding box of `to_hero`, in `to_route`'s coordinate space.
793    ///
794    /// This property should only be accessed in [`HeroFlight::start`] or [`HeroFlight::divert`].
795    fn to_hero_location(self: Handle<Self>, app: &mut App) -> Rect {
796        if let Some(location) = app.get(self).to_hero_location {
797            return location;
798        }
799        let context = app.get(self).to_hero.context(app);
800        let ancestor_context = app.get(self).to_route.as_modal_route().subtree_context(app);
801        let location = HeroFlightManifest::bounding_box_for(app, context, ancestor_context);
802        app.get_mut(self).to_hero_location = Some(location);
803        location
804    }
805
806    /// Whether this manifest is valid and can be used to start or divert a [`HeroFlight`].
807    ///
808    /// When starting or diverting a flight with a brand new manifest, this flag must be checked
809    /// to ensure the rect tween the manifest produces does not contain coordinates that are
810    /// infinite or NaN.
811    fn is_valid(self: Handle<Self>, app: &mut App) -> bool {
812        if let Some(is_valid) = app.get(self).is_valid {
813            return is_valid;
814        }
815        let is_valid = self.to_hero_location(app).is_finite()
816            && (app.get(self).is_diverted || self.from_hero_location(app).is_finite());
817        app.get_mut(self).is_valid = Some(is_valid);
818        is_valid
819    }
820
821    fn dispose(self: Handle<Self>, app: &mut App) {
822        if let Some(animation) = app.get(self).animation.handle() {
823            animation.dispose(app);
824        }
825    }
826}
827
828// ---------------------------------------------------------------------------------------------
829// _HeroFlight
830
831/// Builds the in-flight hero widget.
832struct HeroFlight {
833    on_flight_ended: OnFlightEnded,
834
835    hero_rect_tween: Option<Rc<dyn RectTweenObject>>,
836    shuttle: Option<WidgetRef>,
837
838    hero_opacity: AnimationRef<f64>,
839    proxy_animation: Ref<ProxyAnimation>,
840    // The manifest will be available once `start` is called, throughout the flight's lifecycle.
841    manifest: Option<Ref<HeroFlightManifest>>,
842
843    overlay_entry: Option<Ref<OverlayEntry>>,
844    aborted: bool,
845
846    // Dart's `static final Animatable<double> _reverseTween`; a tween needs an App to live in,
847    // so each flight mints its own.
848    reverse_tween: Ref<Tween<f64>>,
849
850    scheduled_perform_animation_update: bool,
851    // The `navigator` Dart's local `delayedPerformAnimationUpdate` closure captures.
852    scheduled_gesture_navigator: Option<Handle<NavigatorState>>,
853}
854
855impl HeroFlight {
856    fn new(app: &mut App, on_flight_ended: OnFlightEnded) -> Ref<HeroFlight> {
857        let hero_opacity = k_always_complete_animation(app);
858        let proxy_animation = ProxyAnimation::new(app, None);
859        let proxy = proxy_animation.handle();
860        let reverse_tween = Tween::new(app, Some(1.0), Some(0.0));
861        let this = app.create(HeroFlight {
862            on_flight_ended,
863            hero_rect_tween: None,
864            shuttle: None,
865            hero_opacity,
866            proxy_animation,
867            manifest: None,
868            overlay_entry: None,
869            aborted: false,
870            reverse_tween,
871            scheduled_perform_animation_update: false,
872            scheduled_gesture_navigator: None,
873        });
874        proxy.add_status_listener(
875            app,
876            AnimationStatusListener::handle_method(
877                this.handle(),
878                HeroFlight::handle_animation_update,
879            ),
880        );
881        this
882    }
883
884    fn manifest(self: Handle<Self>, app: &App) -> Handle<HeroFlightManifest> {
885        app.get(self)
886            .manifest
887            .handle()
888            .expect("the flight has started")
889    }
890
891    fn set_manifest(self: Handle<Self>, app: &mut App, value: Ref<HeroFlightManifest>) {
892        if let Some(manifest) = app.get(self).manifest.handle() {
893            manifest.dispose(app);
894        }
895        app.get_mut(self).manifest = Some(value);
896    }
897
898    fn hero_rect_tween(self: Handle<Self>, app: &App) -> Rc<dyn RectTweenObject> {
899        Rc::clone(
900            app.get(self)
901                .hero_rect_tween
902                .as_ref()
903                .expect("the flight has started"),
904        )
905    }
906
907    /// The overlay entry's builder callback for the hero's overlay.
908    fn build_overlay(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
909        if app.get(self).shuttle.is_none() {
910            let manifest = self.manifest(app);
911            let shuttle_builder = Rc::clone(&app.get(manifest).shuttle_builder);
912            let animation = manifest.animation(app);
913            let r#type = app.get(manifest).r#type;
914            let from_hero_context = app.get(manifest).from_hero.context(app);
915            let to_hero_context = app.get(manifest).to_hero.context(app);
916            let shuttle = shuttle_builder(
917                app,
918                context,
919                animation,
920                r#type,
921                from_hero_context,
922                to_hero_context,
923            );
924            app.get_mut(self).shuttle = Some(shuttle);
925        }
926        debug_assert!(app.get(self).shuttle.is_some());
927
928        let proxy_animation: AnimationRef<f64> = app.get(self).proxy_animation.erase();
929        let shuttle = app
930            .get(self)
931            .shuttle
932            .clone()
933            .expect("built just above if it was missing");
934        AnimatedBuilder::new(
935            Rc::new(proxy_animation.clone()),
936            move |app, _context, child| {
937                let rect = self
938                    .hero_rect_tween(app)
939                    .evaluate(app, proxy_animation.handle())
940                    .expect("the hero rect tween has both ends");
941                let mut fade = FadeTransition::new(app.get(self).hero_opacity.clone());
942                if let Some(child) = child {
943                    fade = fade.child(child.clone());
944                }
945                Positioned::from_rect(rect, IgnorePointer::new().child(fade)).into_widget()
946            },
947        )
948        .child(shuttle)
949        .into_widget()
950    }
951
952    fn perform_animation_update(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
953        if !status.is_animating() {
954            let proxy_animation = app.get(self).proxy_animation.handle();
955            proxy_animation.set_parent(app, None);
956
957            debug_assert!(app.get(self).overlay_entry.is_some());
958            let overlay_entry = app
959                .get_mut(self)
960                .overlay_entry
961                .take()
962                .expect("a started flight has an overlay entry");
963            overlay_entry.remove(app);
964            overlay_entry.dispose(app);
965            // We want to keep the hero underneath the current page hidden. If the status is
966            // completed, `to_hero` will be the one on top and we keep `from_hero` hidden. If it
967            // is dismissed, the animation is triggered but canceled before it finishes. In this
968            // case, we keep `to_hero` hidden instead.
969            let manifest = self.manifest(app);
970            let from_hero = app.get(manifest).from_hero.handle();
971            let to_hero = app.get(manifest).to_hero.handle();
972            from_hero.end_flight(app, status.is_completed());
973            to_hero.end_flight(app, status.is_dismissed());
974            let on_flight_ended = Rc::clone(&app.get(self).on_flight_ended);
975            on_flight_ended(app, self);
976            Animation::remove_listener(
977                proxy_animation,
978                app,
979                &Listener::handle_method(self, HeroFlight::on_tick),
980            );
981        }
982    }
983
984    fn handle_animation_update(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
985        // The animation will not finish until the user lifts their finger, so we should suppress
986        // the status update if the gesture is in progress, and delay it until the finger is
987        // lifted.
988        let manifest = self.manifest(app);
989        let navigator = app.get(manifest).from_route.as_route().navigator(app);
990        if navigator.map(|navigator| navigator.user_gesture_in_progress(app)) != Some(true) {
991            self.perform_animation_update(app, status);
992            return;
993        }
994
995        if app.get(self).scheduled_perform_animation_update {
996            return;
997        }
998
999        // The `navigator` must be non-null here, or the first if clause above would have returned
1000        // from this method.
1001        let navigator = navigator.expect("checked by the clause above");
1002
1003        debug_assert!(navigator.user_gesture_in_progress(app));
1004        let flight = app.get_mut(self);
1005        flight.scheduled_perform_animation_update = true;
1006        flight.scheduled_gesture_navigator = Some(navigator);
1007        let notifier = navigator.user_gesture_in_progress_notifier(app);
1008        notifier.add_listener(
1009            app,
1010            Listener::handle_method(self, HeroFlight::delayed_perform_animation_update),
1011        );
1012    }
1013
1014    fn delayed_perform_animation_update(self: Handle<Self>, app: &mut App) {
1015        let navigator = app
1016            .get(self)
1017            .scheduled_gesture_navigator
1018            .expect("set where the listener was registered");
1019        debug_assert!(!navigator.user_gesture_in_progress(app));
1020        debug_assert!(app.get(self).scheduled_perform_animation_update);
1021        let flight = app.get_mut(self);
1022        flight.scheduled_perform_animation_update = false;
1023        flight.scheduled_gesture_navigator = None;
1024        let notifier = navigator.user_gesture_in_progress_notifier(app);
1025        notifier.remove_listener(
1026            app,
1027            &Listener::handle_method(self, HeroFlight::delayed_perform_animation_update),
1028        );
1029        let status = app.get(self).proxy_animation.status(app);
1030        self.perform_animation_update(app, status);
1031    }
1032
1033    /// Releases resources.
1034    fn dispose(self: Handle<Self>, app: &mut App) {
1035        if let Some(overlay_entry) = app.get_mut(self).overlay_entry.take() {
1036            overlay_entry.remove(app);
1037            overlay_entry.dispose(app);
1038            let proxy_animation = app.get(self).proxy_animation.handle();
1039            proxy_animation.set_parent(app, None);
1040            Animation::remove_listener(
1041                proxy_animation,
1042                app,
1043                &Listener::handle_method(self, HeroFlight::on_tick),
1044            );
1045            proxy_animation.remove_status_listener(
1046                app,
1047                &AnimationStatusListener::handle_method(self, HeroFlight::handle_animation_update),
1048            );
1049        }
1050        if let Some(manifest) = app.get(self).manifest.handle() {
1051            manifest.dispose(app);
1052        }
1053    }
1054
1055    fn on_tick(self: Handle<Self>, app: &mut App) {
1056        let manifest = self.manifest(app);
1057        let to_hero = app.get(manifest).to_hero.handle();
1058        let to_hero_box = (!app.get(self).aborted && to_hero.mounted(app))
1059            .then(|| to_hero.context(app).find_render_object(app))
1060            .flatten()
1061            .map(|object| object.as_box().expect("a hero's render object is a box"));
1062        // Try to find the new origin of the `to_hero`, if the flight isn't aborted.
1063        let to_hero_origin = match to_hero_box {
1064            Some(to_hero_box)
1065                if to_hero_box.as_object().attached(app) && to_hero_box.has_size(app) =>
1066            {
1067                let ancestor = app
1068                    .get(manifest)
1069                    .to_route
1070                    .as_modal_route()
1071                    .subtree_context(app)
1072                    .and_then(|context| context.find_render_object(app))
1073                    .map(|object| {
1074                        object
1075                            .as_box()
1076                            .expect("a route's subtree render object is a box")
1077                            .as_object()
1078                    });
1079                Some(to_hero_box.local_to_global(app, Offset::ZERO, ancestor))
1080            }
1081            _ => None,
1082        };
1083
1084        if let Some(to_hero_origin) = to_hero_origin
1085            && to_hero_origin.is_finite()
1086        {
1087            // If the new origin of `to_hero` is available and also paintable, try to update
1088            // `hero_rect_tween` with it.
1089            let hero_rect_tween = self.hero_rect_tween(app);
1090            let end = hero_rect_tween
1091                .end(app)
1092                .expect("the hero rect tween has both ends");
1093            if to_hero_origin != end.top_left() {
1094                let hero_rect_end = to_hero_origin & end.size();
1095                let begin = hero_rect_tween.begin(app);
1096                let hero_rect_tween =
1097                    manifest.create_hero_rect_tween(app, begin, Some(hero_rect_end));
1098                app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1099            }
1100        } else if app.get(self).hero_opacity.status(app).is_completed() {
1101            // The `to_hero` no longer exists or it's no longer the flight's destination.
1102            // Continue flying while fading out.
1103            let proxy_animation = app.get(self).proxy_animation.clone();
1104            let curve = Interval::new(proxy_animation.value(app), 1.0, Curves::linear());
1105            let curve_tween = CurveTween::new(app, Rc::new(curve));
1106            let reverse_tween = app.get(self).reverse_tween.clone();
1107            let hero_opacity = proxy_animation.drive(app, reverse_tween.chain(curve_tween));
1108            app.get_mut(self).hero_opacity = hero_opacity;
1109        }
1110        // Update `aborted` for the next animation tick.
1111        app.get_mut(self).aborted =
1112            to_hero_origin.is_none_or(|to_hero_origin| !to_hero_origin.is_finite());
1113    }
1114
1115    /// The simple case: we're either starting a push or a pop animation.
1116    fn start(self: Handle<Self>, app: &mut App, initial_manifest: Ref<HeroFlightManifest>) {
1117        debug_assert!(!app.get(self).aborted);
1118        if cfg!(debug_assertions) {
1119            let initial = initial_manifest.animation(app);
1120            let r#type = app.get(&initial_manifest).r#type;
1121            assert!(match r#type {
1122                HeroFlightDirection::Pop =>
1123                // During user gesture transitions, the animation controller isn't driving the
1124                // reverse transition, so the status is not important.
1125                    app.get(&initial_manifest).is_user_gesture_transition
1126                        || initial.status(app) == AnimationStatus::Reverse,
1127                HeroFlightDirection::Push =>
1128                    initial.value(app) == 0.0 && initial.status(app) == AnimationStatus::Forward,
1129            });
1130        }
1131
1132        self.set_manifest(app, initial_manifest);
1133
1134        let manifest = self.manifest(app);
1135        let proxy_animation = app.get(self).proxy_animation.handle();
1136        let animation = manifest.animation(app);
1137        let should_include_child_in_placeholder = match app.get(manifest).r#type {
1138            HeroFlightDirection::Pop => {
1139                let parent = ReverseAnimation::new(app, animation).into_erased();
1140                proxy_animation.set_parent(app, Some(parent));
1141                false
1142            }
1143            HeroFlightDirection::Push => {
1144                proxy_animation.set_parent(app, Some(animation));
1145                true
1146            }
1147        };
1148
1149        let begin = manifest.from_hero_location(app);
1150        let end = manifest.to_hero_location(app);
1151        let hero_rect_tween = manifest.create_hero_rect_tween(app, Some(begin), Some(end));
1152        app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1153        let from_hero = app.get(manifest).from_hero.handle();
1154        let to_hero = app.get(manifest).to_hero.handle();
1155        from_hero.start_flight(app, should_include_child_in_placeholder);
1156        to_hero.start_flight(app, false);
1157        let overlay_entry = OverlayEntry::new(
1158            app,
1159            Rc::new(move |app, context| self.build_overlay(app, context)),
1160            false,
1161            false,
1162            false,
1163        );
1164        app.get_mut(self).overlay_entry = Some(overlay_entry.clone());
1165        app.get(manifest)
1166            .overlay
1167            .insert(app, overlay_entry, None, None);
1168        Animation::add_listener(
1169            proxy_animation,
1170            app,
1171            Listener::handle_method(self, HeroFlight::on_tick),
1172        );
1173    }
1174
1175    /// While this flight's hero was in transition a push or a pop occurred for routes with the
1176    /// same hero. Redirect the in-flight hero to the new `to_route`.
1177    fn divert(self: Handle<Self>, app: &mut App, new_manifest: Ref<HeroFlightManifest>) {
1178        let manifest = self.manifest(app);
1179        debug_assert!(*manifest.tag(app) == *new_manifest.tag(app));
1180        let proxy_animation = app.get(self).proxy_animation.handle();
1181        if app.get(manifest).r#type == HeroFlightDirection::Push
1182            && app.get(&new_manifest).r#type == HeroFlightDirection::Pop
1183        {
1184            // A push flight was interrupted by a pop.
1185            let new_animation = new_manifest.animation(app);
1186            debug_assert!(new_animation.status(app) == AnimationStatus::Reverse);
1187            debug_assert!(app.get(manifest).from_hero == app.get(&new_manifest).to_hero);
1188            debug_assert!(app.get(manifest).to_hero == app.get(&new_manifest).from_hero);
1189            debug_assert!(app.get(manifest).from_route == app.get(&new_manifest).to_route);
1190            debug_assert!(app.get(manifest).to_route == app.get(&new_manifest).from_route);
1191
1192            // The same hero rect tween is used in reverse, rather than creating a new one with
1193            // `create_hero_rect_tween(hero_rect.end, hero_rect.begin)`. That's because tweens like
1194            // `MaterialRectArcTween` may create a different path for swapped begin and end
1195            // parameters. We want the pop flight path to be the same (in reverse) as the push
1196            // flight path.
1197            let parent = ReverseAnimation::new(app, new_animation).into_erased();
1198            proxy_animation.set_parent(app, Some(parent));
1199            let parent_tween = self.hero_rect_tween(app);
1200            app.get_mut(self).hero_rect_tween = Some(Rc::new(ReverseRectTween {
1201                parent: parent_tween,
1202            }));
1203        } else if app.get(manifest).r#type == HeroFlightDirection::Pop
1204            && app.get(&new_manifest).r#type == HeroFlightDirection::Push
1205        {
1206            // A pop flight was interrupted by a push.
1207            let new_animation = new_manifest.animation(app);
1208            debug_assert!(new_animation.status(app) == AnimationStatus::Forward);
1209            debug_assert!(app.get(manifest).to_hero == app.get(&new_manifest).from_hero);
1210            debug_assert!(app.get(manifest).to_route == app.get(&new_manifest).from_route);
1211
1212            let value = manifest.animation(app).value(app);
1213            let tween = Tween::new(app, Some(value), Some(1.0));
1214            let parent = new_animation.drive(app, tween);
1215            proxy_animation.set_parent(app, Some(parent));
1216            let from_hero = app.get(manifest).from_hero.handle();
1217            let new_to_hero = app.get(&new_manifest).to_hero.handle();
1218            if from_hero != new_to_hero {
1219                from_hero.end_flight(app, true);
1220                new_to_hero.start_flight(app, false);
1221                let hero_rect_tween = self.hero_rect_tween(app);
1222                let begin = hero_rect_tween.end(app);
1223                let end = new_manifest.to_hero_location(app);
1224                let hero_rect_tween = manifest.create_hero_rect_tween(app, begin, Some(end));
1225                app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1226            } else {
1227                // TODO(hansmuller): Use `ReverseRectTween` here per
1228                // github.com/flutter/flutter/pull/12203.
1229                let hero_rect_tween = self.hero_rect_tween(app);
1230                let begin = hero_rect_tween.end(app);
1231                let end = hero_rect_tween.begin(app);
1232                let hero_rect_tween = manifest.create_hero_rect_tween(app, begin, end);
1233                app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1234            }
1235        } else {
1236            // A push or a pop flight is heading to a new route, i.e.
1237            // manifest.type == push && newManifest.type == push ||
1238            // manifest.type == pop && newManifest.type == pop
1239            debug_assert!(app.get(manifest).from_hero != app.get(&new_manifest).from_hero);
1240            debug_assert!(app.get(manifest).to_hero != app.get(&new_manifest).to_hero);
1241
1242            let hero_rect_tween = self.hero_rect_tween(app);
1243            let begin = hero_rect_tween.evaluate(app, proxy_animation.as_animation());
1244            let end = new_manifest.to_hero_location(app);
1245            let hero_rect_tween = manifest.create_hero_rect_tween(app, begin, Some(end));
1246            app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1247            app.get_mut(self).shuttle = None;
1248
1249            let new_animation = new_manifest.animation(app);
1250            if app.get(&new_manifest).r#type == HeroFlightDirection::Pop {
1251                let parent = ReverseAnimation::new(app, new_animation).into_erased();
1252                proxy_animation.set_parent(app, Some(parent));
1253            } else {
1254                proxy_animation.set_parent(app, Some(new_animation));
1255            }
1256
1257            let from_hero = app.get(manifest).from_hero.handle();
1258            let to_hero = app.get(manifest).to_hero.handle();
1259            from_hero.end_flight(app, true);
1260            to_hero.end_flight(app, true);
1261
1262            // Let the heroes in each of the routes rebuild with their placeholders.
1263            let new_from_hero = app.get(&new_manifest).from_hero.handle();
1264            let new_to_hero = app.get(&new_manifest).to_hero.handle();
1265            let should_include_child_in_placeholder =
1266                app.get(&new_manifest).r#type == HeroFlightDirection::Push;
1267            new_from_hero.start_flight(app, should_include_child_in_placeholder);
1268            new_to_hero.start_flight(app, false);
1269
1270            // Let the transition overlay on top of the routes also rebuild since we cleared the
1271            // old shuttle.
1272            app.get(self)
1273                .overlay_entry
1274                .handle()
1275                .expect("a started flight has an overlay entry")
1276                .mark_needs_build(app);
1277        }
1278
1279        self.set_manifest(app, new_manifest);
1280    }
1281
1282    fn abort(self: Handle<Self>, app: &mut App) {
1283        app.get_mut(self).aborted = true;
1284    }
1285}
1286
1287// ---------------------------------------------------------------------------------------------
1288// HeroController
1289
1290/// A [`Navigator`] observer that manages [`Hero`] transitions.
1291///
1292/// An instance of [`HeroController`] should be used in [`Navigator::observers`].
1293pub struct HeroController {
1294    navigator_observer: NavigatorObserverData,
1295    /// Used to create rect tweens that interpolate the position of heroes in flight.
1296    ///
1297    /// If `None`, the controller uses a linear `RectTween`.
1298    pub create_rect_tween: Option<CreateRectTween>,
1299    // All of the heroes that are currently in the overlay and in motion. Indexed by the hero tag.
1300    flights: IndexMap<Rc<dyn AnyEq>, Ref<HeroFlight>>,
1301}
1302
1303impl HeroController {
1304    /// Creates a hero controller; Dart's optional named argument is the setter.
1305    pub fn new(app: &mut App) -> Ref<HeroController> {
1306        app.create(HeroController {
1307            navigator_observer: NavigatorObserverData::new(),
1308            create_rect_tween: None,
1309            flights: IndexMap::new(),
1310        })
1311    }
1312
1313    /// Dart `HeroController(createRectTween:)`.
1314    pub fn create_rect_tween(
1315        self: Ref<Self>,
1316        app: &mut App,
1317        create_rect_tween: CreateRectTween,
1318    ) -> Ref<Self> {
1319        app.get_mut(&self).create_rect_tween = Some(create_rect_tween);
1320        self
1321    }
1322
1323    /// If we're transitioning between different page routes, start a hero transition after the
1324    /// `to_route` has been laid out with its animation's value at 1.0.
1325    fn maybe_start_hero_transition(
1326        self: Handle<Self>,
1327        app: &mut App,
1328        from_route: Option<AnyRoute>,
1329        to_route: Option<AnyRoute>,
1330        is_user_gesture_transition: bool,
1331    ) {
1332        if to_route == from_route {
1333            return;
1334        }
1335        let (Some(to_route), Some(from_route)) = (
1336            to_route.and_then(|route| route.as_page_route(app)),
1337            from_route.and_then(|route| route.as_page_route(app)),
1338        ) else {
1339            return;
1340        };
1341        let new_route_animation = to_route
1342            .as_modal_route()
1343            .animation(app)
1344            .expect("an installed route has an animation");
1345        let old_route_animation = from_route
1346            .as_modal_route()
1347            .animation(app)
1348            .expect("an installed route has an animation");
1349        let flight_type = match (
1350            is_user_gesture_transition,
1351            old_route_animation.status(app),
1352            new_route_animation.status(app),
1353        ) {
1354            (true, _, _) | (_, AnimationStatus::Reverse, _) => Some(HeroFlightDirection::Pop),
1355            (_, _, AnimationStatus::Forward) => Some(HeroFlightDirection::Push),
1356            _ => None,
1357        };
1358
1359        // A user gesture may have already completed the pop, or we might be the initial route.
1360        if let Some(flight_type) = flight_type {
1361            match flight_type {
1362                HeroFlightDirection::Pop => {
1363                    if old_route_animation.value(app) == 0.0 {
1364                        return;
1365                    }
1366                }
1367                HeroFlightDirection::Push => {
1368                    if new_route_animation.value(app) == 1.0 {
1369                        return;
1370                    }
1371                }
1372            }
1373        }
1374
1375        // For pop transitions driven by a user gesture: if the "to" page has `maintain_state`
1376        // true, then the hero's final dimensions can be measured immediately because their page's
1377        // layout is still valid. Unless due to directly adding routes to the pages stack causing
1378        // the route to never get laid out.
1379        let from_route_render_box = to_route
1380            .as_modal_route()
1381            .subtree_context(app)
1382            .and_then(|context| context.find_render_object(app))
1383            .map(|object| {
1384                object
1385                    .as_box()
1386                    .expect("a route's subtree render object is a box")
1387            });
1388        let has_valid_size = from_route_render_box
1389            .is_some_and(|render_box| render_box.has_size(app) && render_box.size(app).is_finite());
1390        if is_user_gesture_transition
1391            && flight_type == Some(HeroFlightDirection::Pop)
1392            && to_route.as_modal_route().maintain_state(app)
1393            && has_valid_size
1394        {
1395            let from_route = from_route.keep(app);
1396            let to_route = to_route.keep(app);
1397            self.start_hero_transition(
1398                app,
1399                from_route,
1400                to_route,
1401                flight_type,
1402                is_user_gesture_transition,
1403            );
1404        } else {
1405            // Otherwise, delay measuring until the end of the next frame to allow the 'to' route
1406            // to build and layout.
1407
1408            // Putting a route offstage changes its animation value to 1.0. Once this frame
1409            // completes, we'll know where the heroes in the `to` route are going to end up, and
1410            // the `to` route will go back onstage.
1411            let offstage = new_route_animation.value(app) == 0.0;
1412            to_route.as_modal_route().set_offstage(app, offstage);
1413            // The callback keeps both routes and this controller until the frame ends, as
1414            // Dart's closure does.
1415            let from_route = from_route.keep(app);
1416            let to_route = to_route.keep(app);
1417            let this = self.keep(app);
1418            SchedulerBinding::add_post_frame_callback(
1419                app,
1420                FrameCallback::new(move |app, _| {
1421                    if from_route.as_route().navigator(app).is_none()
1422                        || to_route.as_route().navigator(app).is_none()
1423                    {
1424                        return;
1425                    }
1426                    this.start_hero_transition(
1427                        app,
1428                        from_route.clone(),
1429                        to_route.clone(),
1430                        flight_type,
1431                        is_user_gesture_transition,
1432                    );
1433                }),
1434                self.navigator(app)
1435                    .and_then(|navigator| View::maybe_id_of(app, navigator.context(app))),
1436            );
1437        }
1438    }
1439
1440    /// Find the matching pairs of heroes in from and to and either start a new hero flight, or
1441    /// divert an existing one.
1442    fn start_hero_transition(
1443        self: Handle<Self>,
1444        app: &mut App,
1445        from: PageRouteRef,
1446        to: PageRouteRef,
1447        flight_type: Option<HeroFlightDirection>,
1448        is_user_gesture_transition: bool,
1449    ) {
1450        // If the `to` route was offstage, then we're implicitly restoring its animation value back
1451        // to what it was before it was "moved" offstage.
1452        to.as_modal_route().set_offstage(app, false);
1453
1454        let navigator = self.navigator(app);
1455        let overlay = navigator.and_then(|navigator| navigator.overlay(app));
1456        // If the navigator or the overlay was removed before this end-of-frame callback was
1457        // called, then don't actually start a transition, and we don't have to worry about any
1458        // hero widget we might have hidden in a previous flight, or ongoing flights.
1459        let (Some(navigator), Some(overlay)) = (navigator, overlay) else {
1460            return;
1461        };
1462
1463        // At this point, the toHeroes may have been built and laid out for the first time.
1464        //
1465        // If `from_subtree_context` is `None`, call `end_flight` on all toHeroes, for good
1466        // measure. If `to_subtree_context` is `None` abort existing flights.
1467        let from_subtree_context = from.as_modal_route().subtree_context(app);
1468        let from_heroes = match from_subtree_context {
1469            Some(context) => {
1470                Hero::all_heroes_for(app, context, is_user_gesture_transition, navigator)
1471            }
1472            None => IndexMap::new(),
1473        };
1474        let to_subtree_context = to.as_modal_route().subtree_context(app);
1475        let mut to_heroes = match to_subtree_context {
1476            Some(context) => {
1477                Hero::all_heroes_for(app, context, is_user_gesture_transition, navigator)
1478            }
1479            None => IndexMap::new(),
1480        };
1481
1482        for (tag, from_hero) in from_heroes {
1483            let to_hero = to_heroes.get(&tag).copied();
1484            let existing_flight = app.get(self).flights.get(&tag).cloned();
1485            let manifest = match (to_hero, flight_type) {
1486                (Some(to_hero), Some(flight_type)) => {
1487                    let shuttle_builder = to_hero
1488                        .widget(app)
1489                        .flight_shuttle_builder
1490                        .clone()
1491                        .or_else(|| from_hero.widget(app).flight_shuttle_builder.clone())
1492                        .unwrap_or_else(|| {
1493                            Rc::new(HeroController::default_hero_flight_shuttle_builder)
1494                        });
1495                    let create_rect_tween = app.get(self).create_rect_tween.clone();
1496                    Some(HeroFlightManifest::new(
1497                        app,
1498                        flight_type,
1499                        overlay,
1500                        from.clone(),
1501                        to.clone(),
1502                        from_hero,
1503                        to_hero,
1504                        create_rect_tween,
1505                        shuttle_builder,
1506                        is_user_gesture_transition,
1507                        existing_flight.is_some(),
1508                    ))
1509                }
1510                _ => None,
1511            };
1512
1513            // Only proceed with a valid manifest. Otherwise abort the existing flight, and call
1514            // `end_flight` when this for loop finishes.
1515            match manifest {
1516                Some(manifest) if manifest.is_valid(app) => {
1517                    to_heroes.shift_remove(&tag);
1518                    match existing_flight {
1519                        Some(existing_flight) => existing_flight.divert(app, manifest),
1520                        None => {
1521                            // Dart's cascade runs `start` before the map assignment.
1522                            let flight = HeroFlight::new(
1523                                app,
1524                                Rc::new(move |app, flight| self.handle_flight_ended(app, flight)),
1525                            );
1526                            flight.start(app, manifest);
1527                            app.get_mut(self).flights.insert(tag, flight);
1528                        }
1529                    }
1530                }
1531                _ => {
1532                    if let Some(existing_flight) = existing_flight {
1533                        existing_flight.abort(app);
1534                    }
1535                }
1536            }
1537        }
1538
1539        // The remaining entries in `to_heroes` are those that failed to participate in a new
1540        // flight (for not having a valid manifest).
1541        //
1542        // This can happen in a route pop transition when a `from_hero` is no longer mounted, or
1543        // kept alive by the `KeepAlive` mechanism but no longer visible.
1544        for to_hero in to_heroes.into_values() {
1545            to_hero.end_flight(app, false);
1546        }
1547    }
1548
1549    fn handle_flight_ended(self: Handle<Self>, app: &mut App, flight: Handle<HeroFlight>) {
1550        let tag = flight.manifest(app).tag(app);
1551        if let Some(flight) = app.get_mut(self).flights.shift_remove(&tag) {
1552            flight.dispose(app);
1553        }
1554    }
1555
1556    fn default_hero_flight_shuttle_builder(
1557        app: &mut App,
1558        _flight_context: BuildContext,
1559        animation: AnimationRef<f64>,
1560        flight_direction: HeroFlightDirection,
1561        from_hero_context: BuildContext,
1562        to_hero_context: BuildContext,
1563    ) -> WidgetRef {
1564        let to_hero_widget = to_hero_context.widget(app).clone();
1565        let to_hero =
1566            downcast_widget::<Hero>(&*to_hero_widget).expect("a hero context holds a Hero");
1567        let to_hero_child = to_hero.child.clone();
1568
1569        let to_media_query_data = MediaQuery::maybe_of(app, to_hero_context);
1570        let from_media_query_data = MediaQuery::maybe_of(app, from_hero_context);
1571
1572        let (Some(to_media_query_data), Some(from_media_query_data)) =
1573            (to_media_query_data, from_media_query_data)
1574        else {
1575            return to_hero_child;
1576        };
1577
1578        let from_hero_padding = from_media_query_data.padding;
1579        let to_hero_padding = to_media_query_data.padding;
1580
1581        AnimatedBuilder::new(Rc::new(animation.clone()), move |app, _context, _child| {
1582            let padding = match flight_direction {
1583                HeroFlightDirection::Push => {
1584                    EdgeInsetsTween::new(Some(from_hero_padding), Some(to_hero_padding))
1585                        .evaluate(app, animation.handle())
1586                }
1587                HeroFlightDirection::Pop => {
1588                    EdgeInsetsTween::new(Some(to_hero_padding), Some(from_hero_padding))
1589                        .evaluate(app, animation.handle())
1590                }
1591            };
1592            MediaQuery::new(
1593                to_media_query_data.copy_with().padding(padding),
1594                to_hero_child.clone(),
1595            )
1596            .into_widget()
1597        })
1598        .into_widget()
1599    }
1600
1601    /// Releases resources.
1602    pub fn dispose(self: Handle<Self>, app: &mut App) {
1603        let flights: Vec<Handle<HeroFlight>> = app
1604            .get(self)
1605            .flights
1606            .values()
1607            .map(Retained::handle)
1608            .collect();
1609        for flight in flights {
1610            flight.dispose(app);
1611        }
1612    }
1613}
1614
1615impl NavigatorObserver for HeroController {
1616    crate::navigator_observer_accessors!();
1617
1618    fn did_change_top(
1619        self: Handle<Self>,
1620        app: &mut App,
1621        top_route: AnyRoute,
1622        previous_top_route: Option<AnyRoute>,
1623    ) {
1624        debug_assert!(top_route.is_current(app));
1625        debug_assert!(self.navigator(app).is_some());
1626        let Some(previous_top_route) = previous_top_route else {
1627            return;
1628        };
1629        // Don't trigger another flight when a pop is committed as a user gesture back swipe is
1630        // snapped.
1631        let navigator = self.navigator(app).expect("asserted above");
1632        if !navigator.user_gesture_in_progress(app) {
1633            self.maybe_start_hero_transition(app, Some(previous_top_route), Some(top_route), false);
1634        }
1635    }
1636
1637    fn did_start_user_gesture(
1638        self: Handle<Self>,
1639        app: &mut App,
1640        route: AnyRoute,
1641        previous_route: Option<AnyRoute>,
1642    ) {
1643        debug_assert!(self.navigator(app).is_some());
1644        self.maybe_start_hero_transition(app, Some(route), previous_route, true);
1645    }
1646
1647    fn did_stop_user_gesture(self: Handle<Self>, app: &mut App) {
1648        let navigator = self
1649            .navigator(app)
1650            .expect("a gesture is only stopped on an observed navigator");
1651        if navigator.user_gesture_in_progress(app) {
1652            return;
1653        }
1654
1655        // When the user gesture ends, if the user horizontal drag gesture initiated the flight
1656        // (i.e. the back swipe) didn't move towards the pop direction at all, the animation will
1657        // not play and thus the status update callback `handle_animation_update` will never be
1658        // called when the gesture finishes. In this case the initiated flight needs to be manually
1659        // invalidated.
1660        let is_invalid_flight = |app: &App, flight: Handle<HeroFlight>| {
1661            let manifest = flight.manifest(app);
1662            app.get(manifest).is_user_gesture_transition
1663                && app.get(manifest).r#type == HeroFlightDirection::Pop
1664                && app.get(flight).proxy_animation.status(app).is_dismissed()
1665        };
1666
1667        let invalid_flights: Vec<Handle<HeroFlight>> = app
1668            .get(self)
1669            .flights
1670            .values()
1671            .map(Retained::handle)
1672            .filter(|flight| is_invalid_flight(app, *flight))
1673            .collect();
1674
1675        // Treat these invalidated flights as dismissed. Calling `handle_animation_update` will
1676        // also remove the flight from `flights`.
1677        for flight in invalid_flights {
1678            flight.handle_animation_update(app, AnimationStatus::Dismissed);
1679        }
1680    }
1681}
1682
1683// ---------------------------------------------------------------------------------------------
1684// HeroMode
1685
1686/// Enables or disables [`Hero`]es in the widget subtree.
1687///
1688/// When [`enabled`](Self::enabled) is false, all [`Hero`] widgets in this subtree will not be
1689/// involved in hero animations.
1690///
1691/// When [`enabled`](Self::enabled) is true (the default), [`Hero`] widgets may be involved in hero
1692/// animations, as usual.
1693#[derive(Debug)]
1694pub struct HeroMode {
1695    /// See [`Widget::key`](crate::Widget::key).
1696    pub key: Option<KeyRef>,
1697    /// The subtree to place inside the [`HeroMode`].
1698    pub child: WidgetRef,
1699    /// Whether or not [`Hero`]es are enabled in this subtree.
1700    ///
1701    /// If this property is false, the [`Hero`]es in this subtree will not animate on route
1702    /// changes. Otherwise, they will animate as usual.
1703    ///
1704    /// Defaults to true.
1705    pub enabled: bool,
1706}
1707
1708impl HeroMode {
1709    /// Creates a widget that enables or disables [`Hero`]es; Dart's optional named arguments are
1710    /// the setters.
1711    #[cfg_attr(debug_assertions, track_caller)]
1712    pub fn new<K>(child: impl IntoWidget<K>) -> HeroMode {
1713        HeroMode {
1714            key: None,
1715            child: child.into_widget(),
1716            enabled: true,
1717        }
1718    }
1719
1720    /// Dart `HeroMode(key:)`.
1721    pub fn key(mut self, key: KeyRef) -> HeroMode {
1722        self.key = Some(key);
1723        self
1724    }
1725
1726    /// Dart `HeroMode(enabled:)`.
1727    pub fn enabled(mut self, enabled: bool) -> HeroMode {
1728        self.enabled = enabled;
1729        self
1730    }
1731}
1732
1733impl StatelessWidget for HeroMode {
1734    fn key(&self) -> Option<&KeyRef> {
1735        self.key.as_ref()
1736    }
1737
1738    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1739        properties.add(
1740            FlagProperty::new("mode", Some(self.enabled))
1741                .if_true("enabled")
1742                .if_false("disabled")
1743                .with_show_name(true),
1744        );
1745    }
1746
1747    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1748        self.child.clone()
1749    }
1750}
1751
1752#[cfg(test)]
1753mod tests {
1754    use std::time::Duration;
1755    use waft_foundation::AppCell;
1756
1757    use waft_embedder::TextDirection;
1758    use waft_painting::{AlignmentGeometry, EdgeInsets, EdgeInsetsGeometry};
1759    use waft_rendering::AnyRenderBox;
1760
1761    use super::*;
1762    use crate::testing::{WidgetTester, test_widgets};
1763    use crate::widgets::basic::{Align, Directionality, Padding};
1764    use crate::widgets::navigator::{HeroControllerScope, RouteSettings};
1765    use crate::widgets::pages::PageRouteBuilder;
1766    use crate::widgets::routes::RoutePageBuilder;
1767
1768    fn tag() -> Rc<dyn AnyEq> {
1769        Rc::new("photo")
1770    }
1771
1772    /// A page holding one [`Hero`] of `width` x `height` at (`left`, `top`).
1773    fn hero_page(
1774        left: f64,
1775        top: f64,
1776        width: f64,
1777        height: f64,
1778        hero_mode: bool,
1779    ) -> RoutePageBuilder {
1780        Rc::new(move |_app, _context, _animation, _secondary| {
1781            let hero = Hero::new(tag(), SizedBox::new().width(width).height(height));
1782            let child: WidgetRef = if hero_mode {
1783                hero.into_widget()
1784            } else {
1785                HeroMode::new(hero).enabled(false).into_widget()
1786            };
1787            Align::new()
1788                .alignment(AlignmentGeometry::TOP_LEFT)
1789                .child(
1790                    Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, 0.0, 0.0)).child(child),
1791                )
1792                .into_widget()
1793        })
1794    }
1795
1796    fn hero_route(app: &mut App, name: &str, page: RoutePageBuilder) -> Ref<PageRouteBuilder> {
1797        PageRouteBuilder::new(app, page)
1798            .settings(app, RouteSettings::new().name(name.to_string()).into())
1799    }
1800
1801    /// A navigator hosting `controller`, under the `Directionality` the overlay's theater needs.
1802    fn hero_navigator(
1803        key: &GlobalKey,
1804        controller: Ref<HeroController>,
1805        first_page: RoutePageBuilder,
1806    ) -> WidgetRef {
1807        Directionality::new(
1808            TextDirection::Ltr,
1809            HeroControllerScope::new(
1810                controller,
1811                Navigator::new().key(key.clone().into()).on_generate_route(
1812                    move |app, _settings| {
1813                        Some(hero_route(app, "/", first_page.clone()).into_erased())
1814                    },
1815                ),
1816            ),
1817        )
1818        .into_widget()
1819    }
1820
1821    /// Pumps a navigator hosting `controller` whose first page is `first_page`, and settles it.
1822    fn mount_navigator(
1823        tester: &mut WidgetTester,
1824        key: &GlobalKey,
1825        controller: &Ref<HeroController>,
1826        first_page: RoutePageBuilder,
1827    ) -> Handle<NavigatorState> {
1828        tester.pump_widget(hero_navigator(key, controller.clone(), first_page));
1829        let navigator = key
1830            .current_state::<NavigatorState>(&tester.cell.borrow())
1831            .expect("a mounted navigator");
1832        tester.pump_and_settle();
1833        navigator
1834    }
1835
1836    /// Pushes a route named "second" whose page is `page`.
1837    fn push_second(
1838        tester: &mut WidgetTester,
1839        navigator: Handle<NavigatorState>,
1840        page: RoutePageBuilder,
1841    ) {
1842        tester.update(|app| {
1843            let second = hero_route(app, "second", page);
1844            navigator.push(app, second.into_erased());
1845        });
1846    }
1847
1848    fn ms(millis: u64) -> Duration {
1849        Duration::from_millis(millis)
1850    }
1851
1852    /// The theater's children, bottom-most first; the top-most is the entry inserted last.
1853    fn overlay_children(app: &mut App, navigator: Handle<NavigatorState>) -> Vec<AnyRenderBox> {
1854        let overlay = navigator.overlay(app).expect("a mounted overlay");
1855        let theater = overlay
1856            .context(app)
1857            .find_render_object(app)
1858            .expect("the overlay is laid out");
1859        let mut children = Vec::new();
1860        theater.visit_children(app, &mut |child| {
1861            children.push(child.as_box().expect("a theater child is a box"));
1862        });
1863        children
1864    }
1865
1866    /// The bounds of the top-most overlay child — the hero flight's shuttle while one is flying.
1867    fn top_overlay_rect(app: &mut App, navigator: Handle<NavigatorState>) -> Rect {
1868        let top = *overlay_children(app, navigator)
1869            .last()
1870            .expect("the overlay has children");
1871        top.local_to_global(app, Offset::ZERO, None) & top.size(app)
1872    }
1873
1874    fn only_flight(app: &App, controller: Handle<HeroController>) -> Handle<HeroFlight> {
1875        let flights = &app.get(controller).flights;
1876        assert_eq!(flights.len(), 1, "one flight per matching tag");
1877        flights
1878            .values()
1879            .next()
1880            .expect("checked just above")
1881            .handle()
1882    }
1883
1884    // ---- the tests ----
1885
1886    #[test]
1887    fn a_hero_flies_between_two_page_routes() {
1888        test_widgets(|tester| {
1889            let key = GlobalKey::new();
1890            let controller = tester.update(HeroController::new);
1891            let navigator = mount_navigator(
1892                tester,
1893                &key,
1894                &controller,
1895                hero_page(10.0, 20.0, 40.0, 30.0, true),
1896            );
1897            let entries_before = tester.update(|app| overlay_children(app, navigator).len());
1898
1899            push_second(tester, navigator, hero_page(150.0, 100.0, 80.0, 60.0, true));
1900
1901            // The observer's post-frame callback measures the destination and starts the flight.
1902            tester.pump_by(ms(20));
1903            let (from_hero, to_hero) = tester.update(|app| {
1904                let flight = only_flight(app, controller.handle());
1905                let manifest = flight.manifest(app);
1906                let (from_hero, to_hero) = (
1907                    app.get(manifest).from_hero.handle(),
1908                    app.get(manifest).to_hero.handle(),
1909                );
1910                assert_eq!(
1911                    app.get(manifest).r#type,
1912                    HeroFlightDirection::Push,
1913                    "a push flies forwards"
1914                );
1915                assert_eq!(
1916                    (
1917                        app.get(from_hero).placeholder_size,
1918                        app.get(to_hero).placeholder_size
1919                    ),
1920                    (Some(Size::new(40.0, 30.0)), Some(Size::new(80.0, 60.0))),
1921                    "both heroes hand their place to a placeholder of their own size"
1922                );
1923                assert_eq!(
1924                    manifest.from_hero_location(app),
1925                    Rect::from_ltrb(10.0, 20.0, 50.0, 50.0),
1926                    "the source hero is measured in its route's coordinate space"
1927                );
1928                assert_eq!(
1929                    manifest.to_hero_location(app),
1930                    Rect::from_ltrb(150.0, 100.0, 230.0, 160.0),
1931                    "the destination hero is measured after the offstage frame laid it out"
1932                );
1933                let tween = flight.hero_rect_tween(app);
1934                assert_eq!(
1935                    (tween.transform(app, 0.0), tween.transform(app, 1.0)),
1936                    (
1937                        Some(Rect::from_ltrb(10.0, 20.0, 50.0, 50.0)),
1938                        Some(Rect::from_ltrb(150.0, 100.0, 230.0, 160.0))
1939                    ),
1940                    "the flight interpolates from the source bounds to the destination bounds"
1941                );
1942                (from_hero, to_hero)
1943            });
1944
1945            // The shuttle is the entry the flight inserted on top of the navigator's overlay.
1946            tester.pump_by(ms(20));
1947            let children = tester.update(|app| overlay_children(app, navigator));
1948            assert!(
1949                children.len() > entries_before,
1950                "the flight added an overlay entry"
1951            );
1952            let mut rect = tester.update(|app| top_overlay_rect(app, navigator));
1953            assert!(
1954                rect.left < 80.0 && rect.width() < 60.0,
1955                "the shuttle starts at the source hero's bounds, not the destination's: {rect:?}"
1956            );
1957
1958            // ... and it moves towards the destination as the route transition runs.
1959            for _ in 0..4 {
1960                tester.pump_by(ms(40));
1961                let moved = tester.update(|app| top_overlay_rect(app, navigator));
1962                assert!(
1963                    moved.left > rect.left && moved.width() > rect.width(),
1964                    "the shuttle's rect grows towards the destination: {rect:?} then {moved:?}"
1965                );
1966                rect = moved;
1967            }
1968
1969            tester.pump_and_settle();
1970            tester.update(|app| {
1971                assert!(
1972                    app.get(&controller).flights.is_empty(),
1973                    "the finished flight is removed from the controller"
1974                );
1975                assert_eq!(
1976                    overlay_children(app, navigator).len(),
1977                    entries_before + 1,
1978                    "the shuttle's entry is gone; only the pushed route's entry remains"
1979                );
1980                assert!(
1981                    app.get(to_hero).placeholder_size.is_none(),
1982                    "the destination hero is visible again"
1983                );
1984                assert!(
1985                    app.get(from_hero).placeholder_size.is_some(),
1986                    "the source hero stays hidden underneath the route on top"
1987                );
1988            });
1989        });
1990    }
1991
1992    #[test]
1993    fn popping_back_flies_the_hero_home_and_clears_its_placeholder() {
1994        test_widgets(|tester| {
1995            let key = GlobalKey::new();
1996            let controller = tester.update(HeroController::new);
1997            let navigator = mount_navigator(
1998                tester,
1999                &key,
2000                &controller,
2001                hero_page(10.0, 20.0, 40.0, 30.0, true),
2002            );
2003
2004            push_second(tester, navigator, hero_page(150.0, 100.0, 80.0, 60.0, true));
2005            tester.pump_and_settle();
2006            assert!(
2007                tester.cell.borrow().get(&controller).flights.is_empty(),
2008                "the push flight is over"
2009            );
2010
2011            tester.update(|app| navigator.pop(app, None));
2012            tester.pump_by(ms(20));
2013            let to_hero = tester.update(|app| {
2014                let flight = only_flight(app, controller.handle());
2015                let manifest = flight.manifest(app);
2016                assert_eq!(
2017                    app.get(manifest).r#type,
2018                    HeroFlightDirection::Pop,
2019                    "a pop flies backwards"
2020                );
2021                app.get(manifest).to_hero.handle()
2022            });
2023
2024            tester.pump_by(ms(20));
2025            let mut rect = tester.update(|app| top_overlay_rect(app, navigator));
2026            assert!(
2027                rect.left > 80.0,
2028                "the shuttle starts at the popped route's hero: {rect:?}"
2029            );
2030            for _ in 0..4 {
2031                tester.pump_by(ms(40));
2032                let moved = tester.update(|app| top_overlay_rect(app, navigator));
2033                assert!(
2034                    moved.left < rect.left,
2035                    "the shuttle flies back: {rect:?} then {moved:?}"
2036                );
2037                rect = moved;
2038            }
2039
2040            tester.pump_and_settle();
2041            let app = tester.cell.borrow();
2042            assert!(app.get(&controller).flights.is_empty());
2043            assert!(
2044                app.get(to_hero).placeholder_size.is_none(),
2045                "the hero that stays on screen shows its child again"
2046            );
2047        });
2048    }
2049
2050    #[test]
2051    fn a_disabled_hero_mode_keeps_the_hero_out_of_the_flight() {
2052        test_widgets(|tester| {
2053            let key = GlobalKey::new();
2054            let controller = tester.update(HeroController::new);
2055            let navigator = mount_navigator(
2056                tester,
2057                &key,
2058                &controller,
2059                hero_page(10.0, 20.0, 40.0, 30.0, false),
2060            );
2061            let entries_before = tester.update(|app| overlay_children(app, navigator).len());
2062
2063            push_second(tester, navigator, hero_page(150.0, 100.0, 80.0, 60.0, true));
2064            tester.pump_by(ms(20));
2065            assert!(
2066                tester.cell.borrow().get(&controller).flights.is_empty(),
2067                "the source hero is behind a disabled HeroMode, so no pair matches"
2068            );
2069
2070            tester.pump_and_settle();
2071            assert_eq!(
2072                tester.update(|app| overlay_children(app, navigator).len()),
2073                entries_before + 1,
2074                "nothing but the pushed route was added to the overlay"
2075            );
2076        });
2077    }
2078
2079    #[test]
2080    fn a_custom_flight_shuttle_builder_supplies_the_in_flight_widget() {
2081        test_widgets(|tester| {
2082            let key = GlobalKey::new();
2083            let controller = tester.update(HeroController::new);
2084            let built = Rc::new(std::cell::Cell::new(0u32));
2085            let shuttle_builder: HeroFlightShuttleBuilder = {
2086                let built = Rc::clone(&built);
2087                Rc::new(move |_app, _flight, _animation, direction, _from, _to| {
2088                    built.set(built.get() + 1);
2089                    assert_eq!(direction, HeroFlightDirection::Push);
2090                    SizedBox::new().width(11.0).height(13.0).into_widget()
2091                })
2092            };
2093            let navigator = mount_navigator(
2094                tester,
2095                &key,
2096                &controller,
2097                hero_page(10.0, 20.0, 40.0, 30.0, true),
2098            );
2099
2100            let page: RoutePageBuilder = Rc::new(move |_app, _context, _animation, _secondary| {
2101                Align::new()
2102                    .alignment(AlignmentGeometry::TOP_LEFT)
2103                    .child(
2104                        Padding::new(EdgeInsetsGeometry::from_ltrb(150.0, 100.0, 0.0, 0.0)).child(
2105                            Hero::new(tag(), SizedBox::new().width(80.0).height(60.0))
2106                                .flight_shuttle_builder(shuttle_builder.clone()),
2107                        ),
2108                    )
2109                    .into_widget()
2110            });
2111            push_second(tester, navigator, page);
2112            tester.pump_by(ms(20));
2113            tester.pump_by(ms(20));
2114
2115            assert_eq!(built.get(), 1, "the shuttle is built once and then reused");
2116            // `Positioned` sizes the shuttle to the flight's rect, so the shuttle's own 11x13 only
2117            // shows up as the child the overlay entry built.
2118            assert!(!tester.cell.borrow().get(&controller).flights.is_empty());
2119            tester.pump_and_settle();
2120            assert!(tester.cell.borrow().get(&controller).flights.is_empty());
2121        });
2122    }
2123
2124    #[test]
2125    fn hero_tags_match_by_value_and_type() {
2126        let a: Rc<dyn AnyEq> = Rc::new("photo");
2127        let b: Rc<dyn AnyEq> = Rc::new("photo");
2128        let c: Rc<dyn AnyEq> = Rc::new("other");
2129        let number: Rc<dyn AnyEq> = Rc::new(1_i32);
2130        assert!(*a == *b);
2131        assert!(*a != *c);
2132        assert!(*a != *number, "two tags of different types never match");
2133
2134        let mut flights: IndexMap<Rc<dyn AnyEq>, u32> = IndexMap::new();
2135        flights.insert(Rc::clone(&a), 1);
2136        assert_eq!(flights.get(&b).copied(), Some(1));
2137        assert_eq!(flights.get(&number), None);
2138    }
2139
2140    #[test]
2141    fn a_reverse_rect_tween_swaps_its_parent_ends() {
2142        let cell = AppCell::new();
2143        let mut app = cell.borrow_mut();
2144        let begin = Rect::from_ltrb(0.0, 0.0, 10.0, 10.0);
2145        let end = Rect::from_ltrb(20.0, 20.0, 40.0, 40.0);
2146        let parent: Rc<dyn RectTweenObject> =
2147            Rc::new(RectTween::new(&mut app, Some(begin), Some(end)));
2148        let reversed = ReverseRectTween {
2149            parent: Rc::clone(&parent),
2150        };
2151        assert_eq!(reversed.begin(&app), Some(end));
2152        assert_eq!(reversed.end(&app), Some(begin));
2153        assert_eq!(reversed.transform(&app, 0.0), Some(end));
2154        assert_eq!(reversed.transform(&app, 1.0), Some(begin));
2155        assert_eq!(
2156            reversed.lerp(&app, 0.25),
2157            parent.lerp(&app, 0.75),
2158            "the parent is evaluated in reverse"
2159        );
2160    }
2161
2162    #[test]
2163    fn an_edge_insets_tween_interpolates_the_shuttle_padding() {
2164        let cell = AppCell::new();
2165        let app = cell.borrow();
2166        let tween = EdgeInsetsTween::new(
2167            Some(EdgeInsets::from_ltrb(0.0, 0.0, 0.0, 0.0)),
2168            Some(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0)),
2169        );
2170        assert_eq!(
2171            tween.transform(&app, 0.5),
2172            EdgeInsets::from_ltrb(5.0, 10.0, 15.0, 20.0)
2173        );
2174        assert_eq!(
2175            tween.transform(&app, 1.0),
2176            EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0)
2177        );
2178    }
2179}