Skip to main content

waft_widgets/widgets/
routes.rs

1//! Flutter counterpart: `widgets/routes.dart`.
2
3use crate::widgets::actions::ActionRef;
4use crate::widgets::navigator::RouteRef;
5use crate::widgets::scroll_controller::ScrollControllerRef;
6use std::any::Any;
7use std::collections::HashMap;
8use std::fmt::{self, Debug};
9use std::rc::Rc;
10use std::time::Duration;
11
12use waft_animation::{
13    Animatable, Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
14    AnimationStatusListener, AnyAnimation, ColorTween, Curve, CurveTween, Curves, Drive,
15    ProxyAnimation, TrainHoppingAnimation, k_always_complete_animation,
16    k_always_dismissed_animation,
17};
18use waft_foundation::{
19    App, Completer, CompleterFuture, DiagnosticPropertiesBuilder, FlagProperty, Handle, HandleId,
20    Listener, MergingListenable, Retained, ValueListenable,
21};
22use waft_painting::Color;
23use waft_physics::Simulation;
24use waft_rendering::OrdinalSortKey;
25use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase, TickerFuture};
26
27use crate::framework::{
28    BuildContext, GlobalKey, InheritedModel, InheritedWidget, IntoWidget, KeyRef, Notification,
29    State, StateData, StatefulWidget, WidgetRef,
30};
31use crate::view::View;
32use crate::widgets::actions::{Action, ActionData, Actions, DismissAction, DismissIntent};
33use crate::widgets::basic::{Builder, IgnorePointer, Offstage, RepaintBoundary, Semantics};
34use crate::widgets::focus_manager::{FocusNodeLeaf, FocusScopeNode, TraversalEdgeBehavior};
35use crate::widgets::focus_scope::FocusScope;
36use crate::widgets::modal_barrier::{AnimatedModalBarrier, ModalBarrier};
37use crate::widgets::navigator::{
38    AnyRoute, NavigationNotification, Navigator, NavigatorObserver, NavigatorObserverData, Route,
39    RouteBase, RoutePopDisposition, RoutePredicate, RouteResult, RouteSettingsRef,
40};
41use crate::widgets::overlay::OverlayEntry;
42use crate::widgets::page_storage::{PageStorage, PageStorageBucket};
43use crate::widgets::primary_scroll_controller::PrimaryScrollController;
44use crate::widgets::restoration::RestorationScope;
45use crate::widgets::scroll_controller::ScrollController;
46use crate::widgets::scroll_controller::ScrollControllerLeaf;
47use crate::widgets::transitions::{AnimatedBuilder, DelegatedTransitionBuilder, ListenableBuilder};
48use waft_foundation::OptionRetained;
49use waft_foundation::Ref;
50
51// ---------------------------------------------------------------------------------------------
52// OverlayRoute
53
54/// The fields Dart's `OverlayRoute` declares; every overlay route carries this bag under the
55/// field `overlay_route`.
56pub struct OverlayRouteData {
57    overlay_entries: Vec<Ref<OverlayEntry>>,
58}
59
60impl OverlayRouteData {
61    /// The bag of a freshly created overlay route.
62    pub fn new() -> OverlayRouteData {
63        OverlayRouteData {
64            overlay_entries: Vec::new(),
65        }
66    }
67}
68
69impl Default for OverlayRouteData {
70    fn default() -> OverlayRouteData {
71        OverlayRouteData::new()
72    }
73}
74
75/// The accessors [`OverlayRoute`] asks for, for a struct whose bag is the field
76/// `overlay_route`.
77#[macro_export]
78macro_rules! overlay_route_accessors {
79    () => {
80        fn overlay_route_data(
81            self: ::waft_foundation::Handle<Self>,
82            app: &::waft_foundation::App,
83        ) -> &$crate::OverlayRouteData {
84            &app.get(self).overlay_route
85        }
86
87        fn overlay_route_data_mut(
88            self: ::waft_foundation::Handle<Self>,
89            app: &mut ::waft_foundation::App,
90        ) -> &mut $crate::OverlayRouteData {
91            &mut app.get_mut(self).overlay_route
92        }
93    };
94}
95
96/// A route that displays widgets in the [`Navigator`]'s `Overlay`.
97///
98/// See also:
99///
100///  * [`Route`], which documents the meaning of Dart's `T` generic type argument.
101pub trait OverlayRoute: Route {
102    /// Dart's `OverlayRoute` fields, held under the field `overlay_route`
103    /// ([`overlay_route_accessors!`](crate::overlay_route_accessors)).
104    fn overlay_route_data(self: Handle<Self>, app: &App) -> &OverlayRouteData;
105
106    /// See [`overlay_route_data`](Self::overlay_route_data).
107    fn overlay_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverlayRouteData;
108
109    /// Subclasses should override this method to return the builders for the overlay.
110    fn create_overlay_entries(self: Handle<Self>, app: &mut App) -> Vec<Ref<OverlayEntry>>;
111
112    /// Dart's `OverlayRoute.overlayEntries`.
113    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<OverlayEntry>> {
114        self.overlay_route_data(app)
115            .overlay_entries
116            .iter()
117            .map(Retained::handle)
118            .collect()
119    }
120
121    /// Dart's `OverlayRoute.install`.
122    fn install(self: Handle<Self>, app: &mut App) {
123        debug_assert!(self.overlay_route_data(app).overlay_entries.is_empty());
124        let entries = OverlayRoute::create_overlay_entries(self, app);
125        self.overlay_route_data_mut(app)
126            .overlay_entries
127            .extend(entries);
128        RouteBase::install(self, app);
129    }
130
131    /// Controls whether [`did_pop`](Self::did_pop) calls [`NavigatorState::finalize_route`](crate::NavigatorState::finalize_route).
132    ///
133    /// If true, this route removes its overlay entries during
134    /// [`did_pop`](Route::did_pop). Subclasses can override this getter if they want to delay
135    /// finalization (for example to animate the route's exit before removing it from the
136    /// overlay).
137    ///
138    /// Subclasses that return false from `finished_when_popped` are responsible for calling
139    /// [`NavigatorState::finalize_route`](crate::NavigatorState::finalize_route) themselves.
140    fn finished_when_popped(self: Handle<Self>, app: &App) -> bool {
141        let _ = app;
142        true
143    }
144
145    /// Dart's `OverlayRoute.didPop`.
146    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
147        let return_value = RouteBase::did_pop(self, app, result);
148        debug_assert!(return_value);
149        if OverlayRoute::finished_when_popped(self, app) {
150            let navigator = self
151                .as_route()
152                .navigator(app)
153                .expect("a popped route is installed");
154            navigator.finalize_route(app, self.as_route());
155        }
156        return_value
157    }
158
159    /// Dart's `OverlayRoute.dispose`.
160    fn dispose(self: Handle<Self>, app: &mut App) {
161        for entry in OverlayRoute::overlay_entries(self, app) {
162            entry.dispose(app);
163        }
164        self.overlay_route_data_mut(app).overlay_entries.clear();
165        RouteBase::dispose(self, app);
166    }
167}
168
169// ---------------------------------------------------------------------------------------------
170// TransitionRoute
171
172/// The fields Dart's `TransitionRoute` declares; every transition route carries this bag under
173/// the field `transition_route`.
174pub struct TransitionRouteData {
175    transition_completer: Completer<RouteResult>,
176    pop_finalized: bool,
177    animation: Option<AnimationRef<f64>>,
178    controller: Option<Ref<AnimationController>>,
179    secondary_animation: Ref<ProxyAnimation>,
180    /// Whether to takeover the [`controller`](TransitionRoute::controller) created by
181    /// [`create_animation_controller`](TransitionRoute::create_animation_controller).
182    ///
183    /// If true, this route will call `AnimationController::dispose` when the controller is no
184    /// longer needed. If false, the controller should be disposed by whoever owned it.
185    ///
186    /// It defaults to `true`.
187    pub will_dispose_animation_controller: bool,
188    result: RouteResult,
189    train_hopping_listener_remover: Option<TrainHoppingListenerRemover>,
190}
191
192/// Dart's `_trainHoppingListenerRemover`: disposes the running train-hopping animation and
193/// removes its listener.
194type TrainHoppingListenerRemover = Rc<dyn Fn(&mut App)>;
195
196impl TransitionRouteData {
197    /// The bag of a freshly created transition route.
198    pub fn new(app: &mut App) -> TransitionRouteData {
199        let dismissed = k_always_dismissed_animation(app);
200        TransitionRouteData {
201            transition_completer: Completer::new(),
202            pop_finalized: false,
203            animation: None,
204            controller: None,
205            secondary_animation: ProxyAnimation::new(app, Some(dismissed)),
206            will_dispose_animation_controller: true,
207            result: None,
208            train_hopping_listener_remover: None,
209        }
210    }
211}
212
213/// The accessors [`TransitionRoute`] asks for, for a struct whose bag is the field
214/// `transition_route`.
215#[macro_export]
216macro_rules! transition_route_accessors {
217    () => {
218        fn transition_route_data(
219            self: ::waft_foundation::Handle<Self>,
220            app: &::waft_foundation::App,
221        ) -> &$crate::TransitionRouteData {
222            &app.get(self).transition_route
223        }
224
225        fn transition_route_data_mut(
226            self: ::waft_foundation::Handle<Self>,
227            app: &mut ::waft_foundation::App,
228        ) -> &mut $crate::TransitionRouteData {
229            &mut app.get_mut(self).transition_route
230        }
231    };
232}
233
234/// An interface for a route that supports predictive back gestures.
235pub trait PredictiveBackRoute: Route {
236    /// Whether a pop gesture can be started by the user for this route.
237    fn pop_gesture_enabled(self: Handle<Self>, app: &mut App) -> bool;
238
239    /// Handles a predictive back gesture starting.
240    ///
241    /// The `progress` parameter indicates the progress of the gesture from 0.0 to 1.0.
242    fn handle_start_back_gesture(self: Handle<Self>, app: &mut App, progress: f64);
243
244    /// Handles a predictive back gesture updating as the user drags across the screen.
245    ///
246    /// The `progress` parameter indicates the progress of the gesture from 0.0 to 1.0.
247    fn handle_update_back_gesture_progress(self: Handle<Self>, app: &mut App, progress: f64);
248
249    /// Handles a predictive back gesture ending successfully.
250    fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App);
251
252    /// Handles a predictive back gesture ending in cancellation.
253    fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App);
254}
255
256/// A route with entrance and exit transitions.
257///
258/// See also:
259///
260///  * [`Route`], which documents the meaning of Dart's `T` generic type argument.
261pub trait TransitionRoute: OverlayRoute + PredictiveBackRoute {
262    /// Dart's `TransitionRoute` fields, held under the field `transition_route`
263    /// ([`transition_route_accessors!`](crate::transition_route_accessors)).
264    fn transition_route_data(self: Handle<Self>, app: &App) -> &TransitionRouteData;
265
266    /// See [`transition_route_data`](Self::transition_route_data).
267    fn transition_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut TransitionRouteData;
268
269    /// This route as the erased [`AnyTransitionRoute`].
270    fn as_transition_route(self: Handle<Self>) -> AnyTransitionRoute {
271        AnyTransitionRoute {
272            id: self.id(),
273            vtable: const { &TransitionRouteVTable::of::<Self>() },
274        }
275    }
276
277    /// This future completes only once the transition itself has finished, after the overlay
278    /// entries have been removed from the navigator's overlay.
279    ///
280    /// This future completes once the animation has been dismissed. That will be after
281    /// [`popped`](Route::popped), because `popped` typically completes before the animation
282    /// even starts, as soon as the route is popped.
283    fn completed(self: Handle<Self>, app: &App) -> CompleterFuture<RouteResult> {
284        self.transition_route_data(app)
285            .transition_completer
286            .future()
287    }
288
289    /// The duration the transition going forwards.
290    ///
291    /// See also:
292    ///
293    ///  * [`reverse_transition_duration`](Self::reverse_transition_duration), which controls
294    ///    the duration of the transition when it is in reverse.
295    fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration;
296
297    /// The duration the transition going in reverse.
298    ///
299    /// By default, the reverse transition duration is set to the value of the forwards
300    /// [`transition_duration`](Self::transition_duration).
301    fn reverse_transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
302        TransitionRoute::transition_duration(self, app)
303    }
304
305    /// Whether the route obscures previous routes when the transition is complete.
306    ///
307    /// When an opaque route's entrance transition is complete, the routes behind the opaque
308    /// route will not be built to save resources.
309    fn opaque(self: Handle<Self>, app: &App) -> bool;
310
311    /// Whether the route transition will prefer to animate a snapshot of the entering and
312    /// exiting routes.
313    fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
314        let _ = app;
315        true
316    }
317
318    /// Dart's `TransitionRoute.finishedWhenPopped`.
319    ///
320    /// This ensures that if we got to the dismissed state while still current, we will still be
321    /// disposed when we are eventually popped.
322    fn finished_when_popped(self: Handle<Self>, app: &App) -> bool {
323        let controller = self
324            .transition_route_data(app)
325            .controller
326            .handle()
327            .expect("an installed route");
328        controller.status(app).is_dismissed() && !self.transition_route_data(app).pop_finalized
329    }
330
331    /// The animation that drives the route's transition and the previous route's forward
332    /// transition.
333    fn animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
334        self.transition_route_data(app).animation.handle()
335    }
336
337    /// The animation controller that the route uses to drive the transitions.
338    ///
339    /// The animation itself is exposed by [`animation`](Self::animation).
340    fn controller(self: Handle<Self>, app: &App) -> Option<Handle<AnimationController>> {
341        self.transition_route_data(app).controller.handle()
342    }
343
344    /// The animation for the route being pushed on top of this route.
345    ///
346    /// This animation lets this route coordinate with the entrance and exit transition of the
347    /// route pushed on top of this route.
348    fn secondary_animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
349        Some(
350            self.transition_route_data(app)
351                .secondary_animation
352                .as_animation(),
353        )
354    }
355
356    /// Returns true if the transition has completed.
357    ///
358    /// It is equivalent to whether the future returned by [`completed`](Self::completed) has
359    /// completed.
360    ///
361    /// This method only works when debug assertions are enabled. Otherwise it always returns
362    /// false.
363    fn debug_transition_completed(self: Handle<Self>, app: &App) -> bool {
364        let mut disposed = false;
365        if cfg!(debug_assertions) {
366            disposed = self
367                .transition_route_data(app)
368                .transition_completer
369                .is_completed();
370        }
371        disposed
372    }
373
374    /// Called to create the animation controller that will drive the transitions to this route
375    /// from the previous one, and back to the previous route from this one.
376    ///
377    /// The returned controller will be disposed by `AnimationController::dispose` if
378    /// [`will_dispose_animation_controller`](TransitionRouteData::will_dispose_animation_controller)
379    /// is true.
380    fn create_animation_controller(self: Handle<Self>, app: &mut App) -> Ref<AnimationController> {
381        debug_assert!(
382            !TransitionRoute::debug_transition_completed(self, app),
383            "cannot reuse a route after disposing it"
384        );
385        let duration = TransitionRoute::transition_duration(self, app);
386        let reverse_duration = TransitionRoute::reverse_transition_duration(self, app);
387        let navigator = self
388            .as_route()
389            .navigator(app)
390            .expect("an installed route has a navigator");
391        AnimationController::new(
392            app,
393            None,
394            Some(duration),
395            Some(reverse_duration),
396            0.0,
397            1.0,
398            AnimationBehavior::Normal,
399            navigator,
400        )
401    }
402
403    /// Called to create the animation that exposes the current progress of the transition
404    /// controlled by the animation controller created by
405    /// [`create_animation_controller`](Self::create_animation_controller).
406    fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
407        TransitionRouteBase::create_animation(self, app)
408    }
409
410    /// Creates the simulation that drives the transition animation for this route.
411    ///
412    /// By default, this method returns `None`, indicating that the route doesn't use
413    /// simulations, but initiates the transition by calling either `AnimationController::forward`
414    /// or `AnimationController::reverse` with
415    /// [`transition_duration`](Self::transition_duration) and the controller's curve.
416    ///
417    /// Subclasses can override this method to return a simulation. In that case the
418    /// [`controller`](Self::controller) will instead use the provided simulation to animate the
419    /// transition using `AnimationController::animate_with` or
420    /// `AnimationController::animate_back_with`, and the simulation's `x` is forwarded to the
421    /// value of [`animation`](Self::animation). The controller's curve and
422    /// [`transition_duration`](Self::transition_duration) are ignored.
423    ///
424    /// This method is invoked each time the navigator pushes or pops this route. The `forward`
425    /// parameter indicates the direction of the transition: true when the route is pushed, and
426    /// false when it is popped.
427    fn create_simulation(
428        self: Handle<Self>,
429        app: &mut App,
430        forward: bool,
431    ) -> Option<Box<dyn Simulation>> {
432        let _ = forward;
433        debug_assert!(
434            TransitionRoute::transition_duration(self, app) >= Duration::ZERO,
435            "the duration must be positive for a non-simulation animation"
436        );
437        None
438    }
439
440    /// Dart's `_createSimulationAndVerify`.
441    fn create_simulation_and_verify(
442        self: Handle<Self>,
443        app: &mut App,
444        forward: bool,
445    ) -> Option<Box<dyn Simulation>> {
446        let simulation = TransitionRoute::create_simulation(self, app, forward);
447        debug_assert!(
448            TransitionRoute::transition_duration(self, app) >= Duration::ZERO,
449            "the duration must be positive for an animation that doesn't use a simulation; \
450             either set transition_duration or set create_simulation"
451        );
452        simulation
453    }
454
455    /// Dart's `_handleStatusChanged`.
456    fn handle_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
457        match status {
458            AnimationStatus::Completed => {
459                let entries = Route::overlay_entries(self, app);
460                if let Some(first) = entries.first().copied() {
461                    let opaque = TransitionRoute::opaque(self, app);
462                    first.set_opaque(app, opaque);
463                }
464            }
465            AnimationStatus::Forward | AnimationStatus::Reverse => {
466                let entries = Route::overlay_entries(self, app);
467                if let Some(first) = entries.first().copied() {
468                    first.set_opaque(app, false);
469                }
470            }
471            AnimationStatus::Dismissed => {
472                // We might still be an active route if a subclass is controlling the
473                // transition and hits the dismissed status. For example, the iOS back gesture
474                // drives this animation to the dismissed status before removing the route and
475                // disposing it.
476                if !self.as_route().is_active(app) {
477                    let navigator = self
478                        .as_route()
479                        .navigator(app)
480                        .expect("an active route has a navigator");
481                    navigator.finalize_route(app, self.as_route());
482                    self.transition_route_data_mut(app).pop_finalized = true;
483                }
484            }
485        }
486    }
487
488    /// Dart's `TransitionRoute.install`.
489    fn install(self: Handle<Self>, app: &mut App) {
490        debug_assert!(
491            !TransitionRoute::debug_transition_completed(self, app),
492            "cannot install a route after disposing it"
493        );
494        let controller = TransitionRoute::create_animation_controller(self, app);
495        self.transition_route_data_mut(app).controller = Some(controller);
496        let animation = TransitionRoute::create_animation(self, app);
497        animation.add_status_listener(
498            app,
499            AnimationStatusListener::handle_method(self, Self::handle_status_changed),
500        );
501        let animation_handle = animation.handle();
502        self.transition_route_data_mut(app).animation = Some(animation);
503        OverlayRoute::install(self, app);
504        let entries = Route::overlay_entries(self, app);
505        if animation_handle.is_completed(app)
506            && let Some(first) = entries.first().copied()
507        {
508            let opaque = TransitionRoute::opaque(self, app);
509            first.set_opaque(app, opaque);
510        }
511    }
512
513    /// Dart's `TransitionRoute.didPush`.
514    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
515        debug_assert!(
516            self.transition_route_data(app).controller.is_some(),
517            "didPush called before install or after dispose"
518        );
519        debug_assert!(
520            !TransitionRoute::debug_transition_completed(self, app),
521            "cannot reuse a route after disposing it"
522        );
523        RouteBase::did_push(self, app);
524        let simulation = TransitionRoute::create_simulation_and_verify(self, app, true);
525        let controller = self
526            .transition_route_data(app)
527            .controller
528            .handle()
529            .expect("installed");
530        match simulation {
531            None => controller.forward(app, None),
532            Some(simulation) => controller.animate_with(app, simulation),
533        }
534    }
535
536    /// Dart's `TransitionRoute.didAdd`.
537    fn did_add(self: Handle<Self>, app: &mut App) {
538        debug_assert!(
539            self.transition_route_data(app).controller.is_some(),
540            "didAdd called before install or after dispose"
541        );
542        debug_assert!(
543            !TransitionRoute::debug_transition_completed(self, app),
544            "cannot reuse a route after disposing it"
545        );
546        RouteBase::did_add(self, app);
547        let controller = self
548            .transition_route_data(app)
549            .controller
550            .handle()
551            .expect("installed");
552        let upper_bound = app.get(controller).upper_bound;
553        controller.set_value(app, upper_bound);
554    }
555
556    /// Dart's `TransitionRoute.didReplace`.
557    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<AnyRoute>) {
558        debug_assert!(
559            self.transition_route_data(app).controller.is_some(),
560            "didReplace called before install or after dispose"
561        );
562        debug_assert!(
563            !TransitionRoute::debug_transition_completed(self, app),
564            "cannot reuse a route after disposing it"
565        );
566        if let Some(old) = old_route.and_then(|route| route.as_transition_route(app)) {
567            let value = old.controller_value(app);
568            let controller = self
569                .transition_route_data(app)
570                .controller
571                .handle()
572                .expect("installed");
573            controller.set_value(app, value);
574        }
575        RouteBase::did_replace(self, app, old_route);
576    }
577
578    /// Dart's `TransitionRoute.didPop`.
579    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
580        debug_assert!(
581            self.transition_route_data(app).controller.is_some(),
582            "didPop called before install or after dispose"
583        );
584        debug_assert!(
585            !self
586                .transition_route_data(app)
587                .transition_completer
588                .is_completed(),
589            "cannot reuse a route after disposing it"
590        );
591        self.transition_route_data_mut(app).result = result.clone();
592        let simulation = TransitionRoute::create_simulation_and_verify(self, app, false);
593        let controller = self
594            .transition_route_data(app)
595            .controller
596            .handle()
597            .expect("installed");
598        match simulation {
599            None => {
600                controller.reverse(app, None);
601            }
602            Some(simulation) => {
603                controller.animate_back_with(app, simulation);
604            }
605        }
606        OverlayRoute::did_pop(self, app, result)
607    }
608
609    /// Dart's `TransitionRoute.didPopNext`.
610    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
611        debug_assert!(
612            self.transition_route_data(app).controller.is_some(),
613            "didPopNext called before install or after dispose"
614        );
615        debug_assert!(
616            !TransitionRoute::debug_transition_completed(self, app),
617            "cannot reuse a route after disposing it"
618        );
619        TransitionRoute::update_secondary_animation(self, app, Some(next_route));
620        RouteBase::did_pop_next(self, app, next_route);
621    }
622
623    /// Dart's `TransitionRoute.didChangeNext`.
624    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
625        debug_assert!(
626            self.transition_route_data(app).controller.is_some(),
627            "didChangeNext called before install or after dispose"
628        );
629        debug_assert!(
630            !TransitionRoute::debug_transition_completed(self, app),
631            "cannot reuse a route after disposing it"
632        );
633        TransitionRoute::update_secondary_animation(self, app, next_route);
634        RouteBase::did_change_next(self, app, next_route);
635    }
636
637    /// Dart's `_updateSecondaryAnimation`.
638    fn update_secondary_animation(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
639        // There is an existing train hopping in progress. Unfortunately, we cannot dispose the
640        // current train hopping animation until we replace it with a new animation.
641        let previous_train_hopping_listener_remover = self
642            .transition_route_data_mut(app)
643            .train_hopping_listener_remover
644            .take();
645
646        let next = next_route.and_then(|route| route.as_transition_route(app));
647        let coordinates = match next {
648            Some(next) => {
649                TransitionRoute::can_transition_to(self, app, next)
650                    && next.can_transition_from(app, TransitionRoute::as_transition_route(self))
651            }
652            None => false,
653        };
654
655        if let (Some(next), true) = (next, coordinates) {
656            let secondary = self.transition_route_data(app).secondary_animation.handle();
657            match secondary.parent(app) {
658                Some(current) => {
659                    let current_train = match current.downcast::<TrainHoppingAnimation>(app) {
660                        Some(hopping) => app.get(hopping).current_train().expect("a running train"),
661                        None => current,
662                    };
663                    let next_train = next.underlying_animation(app).expect("an installed route");
664                    if current_train.value(app) == next_train.value(app)
665                        || !next_train.is_animating(app)
666                    {
667                        let next_train = next_train.keep(app);
668                        TransitionRoute::set_secondary_animation(
669                            self,
670                            app,
671                            Some(next_train),
672                            Some(next.completed(app)),
673                        );
674                    } else {
675                        // Two trains animate at different values. We have to do train hopping.
676                        // There are three possibilities of train hopping:
677                        //  1. We hop on the next train when two trains meet in the middle using
678                        //     `TrainHoppingAnimation`.
679                        //  2. There is no chance to hop on the next train because two trains
680                        //     never cross each other. We have to directly set the animation to
681                        //     the next train once the next train stops animating.
682                        //  3. A new `update_secondary_animation` is called before train hopping
683                        //     finishes. We leave a listener remover for the next call to
684                        //     properly clean up the existing train hopping.
685                        let slot: Rc<std::cell::RefCell<Option<Ref<TrainHoppingAnimation>>>> =
686                            Rc::new(std::cell::RefCell::new(None));
687                        // Registered on the next train, so it names that train and this route
688                        // bare, and does nothing once either is no longer kept.
689                        let jump_on_animation_end =
690                            AnimationStatusListener::new(move |status: AnimationStatus, app| {
691                                if status.is_animating() || self.upgrade(app).is_none() {
692                                    return;
693                                }
694                                // The next train has stopped animating without train hopping.
695                                // Directly sets the secondary animation and disposes the
696                                // `TrainHoppingAnimation`.
697                                let kept_train = next_train.upgrade(app);
698                                TransitionRoute::set_secondary_animation(
699                                    self,
700                                    app,
701                                    kept_train,
702                                    Some(next.completed(app)),
703                                );
704                                if let Some(remover) = self
705                                    .transition_route_data_mut(app)
706                                    .train_hopping_listener_remover
707                                    .take()
708                                {
709                                    remover(app);
710                                }
711                            });
712                        // The remover holds the hopping animation, and lets go of it when it
713                        // runs; the animation's own callback names it only weakly, or the two
714                        // would keep each other.
715                        let remover = {
716                            let listener = jump_on_animation_end.clone();
717                            let slot = Rc::clone(&slot);
718                            Rc::new(move |app: &mut App| {
719                                next_train.remove_status_listener(app, &listener);
720                                let hopping = slot.borrow_mut().take();
721                                if let Some(animation) = hopping {
722                                    animation.dispose(app);
723                                }
724                            })
725                        };
726                        self.transition_route_data_mut(app)
727                            .train_hopping_listener_remover = Some(remover);
728                        next_train.add_status_listener(app, jump_on_animation_end);
729                        let on_switched_train = {
730                            let slot = Rc::downgrade(&slot);
731                            Listener::new(move |app| {
732                                let new_animation = slot
733                                    .upgrade()
734                                    .and_then(|slot| slot.borrow().as_ref().map(Retained::handle))
735                                    .expect("the hopping animation, kept until the remover runs");
736                                debug_assert!(
737                                    self.transition_route_data(app)
738                                        .secondary_animation
739                                        .parent(app)
740                                        == Some(new_animation.as_animation())
741                                );
742                                let current = app.get(new_animation).current_train();
743                                debug_assert!(current == next.underlying_animation(app));
744                                // We can hop on the next train, so we don't need to listen to
745                                // whether the next train has stopped.
746                                let current = current.and_then(|current| current.upgrade(app));
747                                TransitionRoute::set_secondary_animation(
748                                    self,
749                                    app,
750                                    current,
751                                    Some(next.completed(app)),
752                                );
753                                if let Some(remover) = self
754                                    .transition_route_data_mut(app)
755                                    .train_hopping_listener_remover
756                                    .take()
757                                {
758                                    remover(app);
759                                }
760                            })
761                        };
762                        let current_train = current_train.keep(app);
763                        let kept_next_train = next_train.keep(app);
764                        let new_animation = TrainHoppingAnimation::new(
765                            app,
766                            current_train,
767                            Some(kept_next_train),
768                            Some(on_switched_train),
769                        );
770                        let erased: AnimationRef<f64> = new_animation.erase();
771                        *slot.borrow_mut() = Some(new_animation);
772                        self.set_secondary_animation(app, Some(erased), Some(next.completed(app)));
773                    }
774                }
775                None => {
776                    let animation = next
777                        .underlying_animation(app)
778                        .and_then(|animation| animation.upgrade(app));
779                    TransitionRoute::set_secondary_animation(
780                        self,
781                        app,
782                        animation,
783                        Some(next.completed(app)),
784                    );
785                }
786            }
787        } else {
788            let dismissed = k_always_dismissed_animation(app);
789            TransitionRoute::set_secondary_animation(self, app, Some(dismissed), None);
790        }
791        // Finally, we dispose any previous train hopping animation because it has been
792        // successfully updated at this point.
793        if let Some(remover) = previous_train_hopping_listener_remover {
794            remover(app);
795        }
796    }
797
798    /// Dart's `_setSecondaryAnimation`.
799    fn set_secondary_animation(
800        self: Handle<Self>,
801        app: &mut App,
802        animation: Option<AnimationRef<f64>>,
803        disposed: Option<CompleterFuture<RouteResult>>,
804    ) {
805        let secondary = self.transition_route_data(app).secondary_animation.clone();
806        let animation_handle = animation.handle();
807        secondary.set_parent(app, animation);
808        // Releases the reference to the next route's animation when that route is disposed.
809        if let Some(disposed) = disposed {
810            disposed.then(app, move |app, _| {
811                if secondary.parent(app) == animation_handle {
812                    let dismissed = k_always_dismissed_animation(app);
813                    secondary.set_parent(app, Some(dismissed));
814                    if let Some(animation) = animation_handle
815                        && let Some(hopping) = animation.downcast::<TrainHoppingAnimation>(app)
816                    {
817                        hopping.dispose(app);
818                    }
819                }
820            });
821        }
822    }
823
824    /// Returns true if this route supports a transition animation that runs when `next_route`
825    /// is pushed on top of it or when `next_route` is popped off of it.
826    ///
827    /// Subclasses can override this method to restrict the set of routes they need to
828    /// coordinate transitions with.
829    ///
830    /// Returns true by default.
831    fn can_transition_to(self: Handle<Self>, app: &App, next_route: AnyTransitionRoute) -> bool {
832        let _ = (app, next_route);
833        true
834    }
835
836    /// Returns true if `previous_route` should animate when this route is pushed on top of it
837    /// or when this route is popped off of it.
838    ///
839    /// Subclasses can override this method to restrict the set of routes they need to
840    /// coordinate transitions with.
841    ///
842    /// Returns true by default.
843    fn can_transition_from(
844        self: Handle<Self>,
845        app: &App,
846        previous_route: AnyTransitionRoute,
847    ) -> bool {
848        let _ = (app, previous_route);
849        true
850    }
851
852    // ---- PredictiveBackRoute ----
853
854    /// Dart's `TransitionRoute.handleStartBackGesture`.
855    fn handle_start_back_gesture(self: Handle<Self>, app: &mut App, progress: f64) {
856        debug_assert!(self.as_route().is_current(app));
857        if let Some(controller) = self.transition_route_data(app).controller.handle() {
858            controller.set_value(app, progress);
859        }
860        if let Some(navigator) = self.as_route().navigator(app) {
861            navigator.did_start_user_gesture(app);
862        }
863    }
864
865    /// Dart's `TransitionRoute.handleUpdateBackGestureProgress`.
866    fn handle_update_back_gesture_progress(self: Handle<Self>, app: &mut App, progress: f64) {
867        // If some other navigation happened during this gesture, don't mess with the transition
868        // anymore.
869        if !self.as_route().is_current(app) {
870            return;
871        }
872        if let Some(controller) = self.transition_route_data(app).controller.handle() {
873            controller.set_value(app, progress);
874        }
875    }
876
877    /// Dart's `TransitionRoute.handleCancelBackGesture`.
878    fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App) {
879        TransitionRoute::handle_drag_end(self, app, true);
880    }
881
882    /// Dart's `TransitionRoute.handleCommitBackGesture`.
883    fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App) {
884        TransitionRoute::handle_drag_end(self, app, false);
885    }
886
887    /// Dart's `_handleDragEnd`.
888    fn handle_drag_end(self: Handle<Self>, app: &mut App, animate_forward: bool) {
889        if self.as_route().is_current(app) {
890            let controller = self
891                .transition_route_data(app)
892                .controller
893                .handle()
894                .expect("installed");
895            if animate_forward {
896                // Typically, `handle_update_back_gesture_progress` will have already completed
897                // the animation. If not, animate to completion.
898                if !controller.status(app).is_completed() {
899                    controller.forward(app, None);
900                }
901            } else {
902                // This route is destined to pop at this point. Reuse the navigator's pop.
903                if let Some(navigator) = self.as_route().navigator(app) {
904                    navigator.pop(app, None);
905                }
906                // The popping may have finished inline if already at the target destination.
907                if let Some(controller) = self.transition_route_data(app).controller.handle()
908                    && controller.is_animating(app)
909                {
910                    let upper_bound = app.get(controller).upper_bound;
911                    controller.reverse(app, Some(upper_bound));
912                }
913            }
914        }
915
916        let controller = self.transition_route_data(app).controller.handle();
917        let animating = match controller {
918            Some(controller) => controller.is_animating(app),
919            None => false,
920        };
921        if animating {
922            // Keep `user_gesture_in_progress` true, since the Android back-gesture page
923            // transition depends on it.
924            let controller = controller.expect("an animating controller");
925            // The listener removes itself, naming itself weakly: it lives in the controller's
926            // list and goes with it.
927            let me: Rc<std::cell::OnceCell<waft_animation::WeakAnimationStatusListener>> =
928                Rc::default();
929            let listener = {
930                let me = Rc::clone(&me);
931                AnimationStatusListener::new(move |_status, app| {
932                    if let Some(navigator) = self.as_route().navigator(app) {
933                        navigator.did_stop_user_gesture(app);
934                    }
935                    if let Some(registered) = me
936                        .get()
937                        .and_then(waft_animation::WeakAnimationStatusListener::upgrade)
938                    {
939                        controller.remove_status_listener(app, &registered);
940                    }
941                })
942            };
943            let _ = me.set(listener.downgrade());
944            controller.add_status_listener(app, listener);
945        } else if let Some(navigator) = self.as_route().navigator(app) {
946            navigator.did_stop_user_gesture(app);
947        }
948    }
949
950    /// Dart's `TransitionRoute.dispose`.
951    fn dispose(self: Handle<Self>, app: &mut App) {
952        debug_assert!(
953            !self
954                .transition_route_data(app)
955                .transition_completer
956                .is_completed(),
957            "cannot dispose a route twice"
958        );
959        if let Some(animation) = self.transition_route_data(app).animation.handle() {
960            animation.remove_status_listener(
961                app,
962                &AnimationStatusListener::handle_method(self, Self::handle_status_changed),
963            );
964        }
965        if self
966            .transition_route_data(app)
967            .will_dispose_animation_controller
968            && let Some(controller) = self.transition_route_data(app).controller.handle()
969        {
970            controller.dispose(app);
971        }
972        let result = self.transition_route_data(app).result.clone();
973        let transition_completer = self.transition_route_data(app).transition_completer.clone();
974        transition_completer.complete(app, result);
975        OverlayRoute::dispose(self, app);
976    }
977
978    /// A short description of this route useful for debugging.
979    fn debug_label(self: Handle<Self>) -> String {
980        std::any::type_name::<Self>().to_string()
981    }
982}
983
984/// Dart's `TransitionRoute` bodies an override reaches as `super`.
985///
986/// Every [`TransitionRoute`] implements it. An override that must run the inherited body calls
987/// it trait-qualified, `TransitionRouteBase::create_animation(self, app)`, where Dart writes
988/// `super.createAnimation()`; the [`TransitionRoute`] default runs the same body.
989pub trait TransitionRouteBase: TransitionRoute {
990    /// `TransitionRoute.createAnimation`: the controller itself, as an animation.
991    fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
992        debug_assert!(
993            !TransitionRoute::debug_transition_completed(self, app),
994            "cannot reuse a route after disposing it"
995        );
996        // Dart's `controller!.view`: the controller itself, as an animation.
997        self.transition_route_data(app)
998            .controller
999            .as_ref()
1000            .expect("createAnimationController ran first")
1001            .erase()
1002    }
1003}
1004
1005impl<T: TransitionRoute> TransitionRouteBase for T {}
1006
1007/// The vtable of an erased [`AnyTransitionRoute`]: one `&'static` table per route type, built
1008/// by [`TransitionRouteVTable::of`].
1009struct TransitionRouteVTable {
1010    type_name: fn() -> &'static str,
1011    route: fn(HandleId) -> AnyRoute,
1012    animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
1013    underlying_animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
1014    controller: fn(&App, HandleId) -> Option<Handle<AnimationController>>,
1015    controller_value: fn(&App, HandleId) -> f64,
1016    opaque: fn(&App, HandleId) -> bool,
1017    allow_snapshotting: fn(&App, HandleId) -> bool,
1018    transition_duration: fn(&mut App, HandleId) -> Duration,
1019    reverse_transition_duration: fn(&mut App, HandleId) -> Duration,
1020    can_transition_to: fn(&App, HandleId, AnyTransitionRoute) -> bool,
1021    can_transition_from: fn(&App, HandleId, AnyTransitionRoute) -> bool,
1022    completed: fn(&App, HandleId) -> CompleterFuture<RouteResult>,
1023    pop_gesture_enabled: fn(&mut App, HandleId) -> bool,
1024    handle_start_back_gesture: fn(&mut App, HandleId, f64),
1025    handle_update_back_gesture_progress: fn(&mut App, HandleId, f64),
1026    handle_commit_back_gesture: fn(&mut App, HandleId),
1027    handle_cancel_back_gesture: fn(&mut App, HandleId),
1028}
1029
1030impl TransitionRouteVTable {
1031    /// The table for one transition route type.
1032    const fn of<R: TransitionRoute>() -> TransitionRouteVTable {
1033        TransitionRouteVTable {
1034            type_name: std::any::type_name::<R>,
1035            route: |id| Route::as_route(resolve::<R>(id)),
1036            animation: |app, id| R::animation(resolve(id), app),
1037            underlying_animation: |app, id| {
1038                R::transition_route_data(resolve::<R>(id), app)
1039                    .animation
1040                    .handle()
1041            },
1042            controller: |app, id| R::controller(resolve(id), app),
1043            controller_value: |app, id| {
1044                let controller = R::transition_route_data(resolve::<R>(id), app)
1045                    .controller
1046                    .handle()
1047                    .expect("an installed route");
1048                controller.value(app)
1049            },
1050            opaque: |app, id| R::opaque(resolve(id), app),
1051            allow_snapshotting: |app, id| R::allow_snapshotting(resolve(id), app),
1052            transition_duration: |app, id| R::transition_duration(resolve(id), app),
1053            reverse_transition_duration: |app, id| R::reverse_transition_duration(resolve(id), app),
1054            can_transition_to: |app, id, next| R::can_transition_to(resolve(id), app, next),
1055            can_transition_from: |app, id, prev| R::can_transition_from(resolve(id), app, prev),
1056            completed: |app, id| R::completed(resolve(id), app),
1057            pop_gesture_enabled: |app, id| {
1058                PredictiveBackRoute::pop_gesture_enabled(resolve::<R>(id), app)
1059            },
1060            handle_start_back_gesture: |app, id, progress| {
1061                PredictiveBackRoute::handle_start_back_gesture(resolve::<R>(id), app, progress)
1062            },
1063            handle_update_back_gesture_progress: |app, id, progress| {
1064                PredictiveBackRoute::handle_update_back_gesture_progress(
1065                    resolve::<R>(id),
1066                    app,
1067                    progress,
1068                )
1069            },
1070            handle_commit_back_gesture: |app, id| {
1071                PredictiveBackRoute::handle_commit_back_gesture(resolve::<R>(id), app)
1072            },
1073            handle_cancel_back_gesture: |app, id| {
1074                PredictiveBackRoute::handle_cancel_back_gesture(resolve::<R>(id), app)
1075            },
1076        }
1077    }
1078}
1079
1080/// Erased [`TransitionRoute`]: what Dart's `route is TransitionRoute<dynamic>` produces.
1081#[derive(Clone, Copy)]
1082pub struct AnyTransitionRoute {
1083    id: HandleId,
1084    vtable: &'static TransitionRouteVTable,
1085}
1086
1087/// A kept route as a [`RouteRef`], through [`Retained::erase`]: Dart's upcast.
1088impl From<AnyTransitionRoute> for AnyRoute {
1089    fn from(route: AnyTransitionRoute) -> AnyRoute {
1090        route.as_route()
1091    }
1092}
1093
1094/// A field Dart types as the erased object, kept: AnyTransitionRoute with its count.
1095pub type TransitionRouteRef = Retained<AnyTransitionRoute>;
1096
1097waft_foundation::erased_handle!(AnyTransitionRoute: TransitionRoute => TransitionRoute::as_transition_route);
1098
1099impl Debug for AnyTransitionRoute {
1100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1101        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
1102    }
1103}
1104
1105impl AnyTransitionRoute {
1106    /// This transition route as the erased [`AnyRoute`].
1107    pub fn as_route(self) -> AnyRoute {
1108        (self.vtable.route)(self.id)
1109    }
1110
1111    /// See [`TransitionRoute::animation`].
1112    pub fn animation(self, app: &App) -> Option<AnyAnimation<f64>> {
1113        (self.vtable.animation)(app, self.id)
1114    }
1115
1116    /// Dart's `_animation`: the animation a route runs on, under whatever
1117    /// [`animation`](Self::animation) answers with.
1118    ///
1119    /// A [`ModalRoute`] answers with a proxy that reads complete while the route is
1120    /// offstage, which is exactly when the route ahead is put offstage to be measured. A
1121    /// route behind follows this one instead, so it stays where it is until the transition
1122    /// really runs.
1123    pub fn underlying_animation(self, app: &App) -> Option<AnyAnimation<f64>> {
1124        (self.vtable.underlying_animation)(app, self.id)
1125    }
1126
1127    /// See [`TransitionRoute::controller`].
1128    pub fn controller(self, app: &App) -> Option<Handle<AnimationController>> {
1129        (self.vtable.controller)(app, self.id)
1130    }
1131
1132    /// The value of Dart's `_controller`, which `didReplace` copies.
1133    pub fn controller_value(self, app: &App) -> f64 {
1134        (self.vtable.controller_value)(app, self.id)
1135    }
1136
1137    /// See [`TransitionRoute::opaque`].
1138    pub fn opaque(self, app: &App) -> bool {
1139        (self.vtable.opaque)(app, self.id)
1140    }
1141
1142    /// See [`TransitionRoute::allow_snapshotting`].
1143    pub fn allow_snapshotting(self, app: &App) -> bool {
1144        (self.vtable.allow_snapshotting)(app, self.id)
1145    }
1146
1147    /// See [`TransitionRoute::transition_duration`].
1148    pub fn transition_duration(self, app: &mut App) -> Duration {
1149        (self.vtable.transition_duration)(app, self.id)
1150    }
1151
1152    /// See [`TransitionRoute::reverse_transition_duration`].
1153    pub fn reverse_transition_duration(self, app: &mut App) -> Duration {
1154        (self.vtable.reverse_transition_duration)(app, self.id)
1155    }
1156
1157    /// See [`TransitionRoute::can_transition_to`].
1158    pub fn can_transition_to(self, app: &App, next_route: AnyTransitionRoute) -> bool {
1159        (self.vtable.can_transition_to)(app, self.id, next_route)
1160    }
1161
1162    /// See [`TransitionRoute::can_transition_from`].
1163    pub fn can_transition_from(self, app: &App, previous_route: AnyTransitionRoute) -> bool {
1164        (self.vtable.can_transition_from)(app, self.id, previous_route)
1165    }
1166
1167    /// See [`TransitionRoute::completed`].
1168    pub fn completed(self, app: &App) -> CompleterFuture<RouteResult> {
1169        (self.vtable.completed)(app, self.id)
1170    }
1171
1172    /// See [`PredictiveBackRoute::pop_gesture_enabled`].
1173    pub fn pop_gesture_enabled(self, app: &mut App) -> bool {
1174        (self.vtable.pop_gesture_enabled)(app, self.id)
1175    }
1176
1177    /// See [`PredictiveBackRoute::handle_start_back_gesture`].
1178    pub fn handle_start_back_gesture(self, app: &mut App, progress: f64) {
1179        (self.vtable.handle_start_back_gesture)(app, self.id, progress)
1180    }
1181
1182    /// See [`PredictiveBackRoute::handle_update_back_gesture_progress`].
1183    pub fn handle_update_back_gesture_progress(self, app: &mut App, progress: f64) {
1184        (self.vtable.handle_update_back_gesture_progress)(app, self.id, progress)
1185    }
1186
1187    /// See [`PredictiveBackRoute::handle_commit_back_gesture`].
1188    pub fn handle_commit_back_gesture(self, app: &mut App) {
1189        (self.vtable.handle_commit_back_gesture)(app, self.id)
1190    }
1191
1192    /// See [`PredictiveBackRoute::handle_cancel_back_gesture`].
1193    pub fn handle_cancel_back_gesture(self, app: &mut App) {
1194        (self.vtable.handle_cancel_back_gesture)(app, self.id)
1195    }
1196}
1197
1198/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
1199fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
1200    Handle::from_id(id)
1201}
1202
1203// ---------------------------------------------------------------------------------------------
1204// LocalHistoryEntry / LocalHistoryRoute
1205
1206/// An entry in the history of a [`LocalHistoryRoute`].
1207///
1208/// A [`LocalHistoryEntry`] represents a "mini" navigation state within a route. It allows
1209/// widgets or UI components to handle the back button or pop operations locally without
1210/// affecting the main navigator stack.
1211///
1212/// It is typically used for widgets such as dialogs, bottom sheets, or inline expandable panels
1213/// that can be dismissed independently of the surrounding route.
1214///
1215/// When a local history entry is removed (e.g. via the back button), the
1216/// [`on_remove`](Self::on_remove) callback is called first. Only after all local history
1217/// entries have been removed will the route itself be popped.
1218///
1219/// See also:
1220///
1221///  * [`LocalHistoryRoute`], which manages a stack of local history entries.
1222///  * [`LocalHistoryRoute::add_local_history_entry`], which adds an entry to a route.
1223pub struct LocalHistoryEntry {
1224    /// Called when this entry is removed from the history of its associated
1225    /// [`LocalHistoryRoute`].
1226    pub on_remove: Option<Listener>,
1227    owner: Option<AnyRoute>,
1228    /// Whether an app bar in the route this entry belongs to should automatically add a back
1229    /// button or close button.
1230    ///
1231    /// Defaults to true.
1232    pub implies_app_bar_dismissal: bool,
1233}
1234
1235impl LocalHistoryEntry {
1236    /// Creates an entry in the history of a [`LocalHistoryRoute`]; Dart's optional arguments
1237    /// are the setters.
1238    ///
1239    /// [`implies_app_bar_dismissal`](Self::implies_app_bar_dismissal) defaults to true.
1240    pub fn new(app: &mut App) -> Ref<LocalHistoryEntry> {
1241        app.create(LocalHistoryEntry {
1242            on_remove: None,
1243            owner: None,
1244            implies_app_bar_dismissal: true,
1245        })
1246    }
1247
1248    /// Dart `LocalHistoryEntry(onRemove:)`.
1249    pub fn on_remove(self: Ref<Self>, app: &mut App, on_remove: Listener) -> Ref<Self> {
1250        app.get_mut(&self).on_remove = Some(on_remove);
1251        self
1252    }
1253
1254    /// Dart `LocalHistoryEntry(impliesAppBarDismissal:)`.
1255    pub fn implies_app_bar_dismissal(
1256        self: Ref<Self>,
1257        app: &mut App,
1258        implies_app_bar_dismissal: bool,
1259    ) -> Ref<Self> {
1260        app.get_mut(&self).implies_app_bar_dismissal = implies_app_bar_dismissal;
1261        self
1262    }
1263
1264    /// Remove this entry from the history of its associated [`LocalHistoryRoute`].
1265    pub fn remove(self: Handle<Self>, app: &mut App) {
1266        if let Some(owner) = app.get(self).owner {
1267            let modal = owner
1268                .as_modal_route(app)
1269                .expect("a local history entry belongs to a modal route");
1270            modal.remove_local_history_entry(app, self);
1271        }
1272        debug_assert!(app.get(self).owner.is_none());
1273    }
1274
1275    fn notify_removed(self: Handle<Self>, app: &mut App) {
1276        if let Some(on_remove) = app.get(self).on_remove.clone() {
1277            on_remove.call(app);
1278        }
1279    }
1280}
1281
1282impl Debug for LocalHistoryEntry {
1283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1284        f.write_str("LocalHistoryEntry")
1285    }
1286}
1287
1288/// The fields Dart's `LocalHistoryRoute` mixin declares; every route that mixes it in carries
1289/// this bag under the field `local_history`.
1290pub struct LocalHistoryRouteData {
1291    local_history: Option<Vec<Ref<LocalHistoryEntry>>>,
1292    entries_implies_app_bar_dismissal: i64,
1293}
1294
1295impl LocalHistoryRouteData {
1296    /// The bag of a route with no local history.
1297    pub fn new() -> LocalHistoryRouteData {
1298        LocalHistoryRouteData {
1299            local_history: None,
1300            entries_implies_app_bar_dismissal: 0,
1301        }
1302    }
1303}
1304
1305impl Default for LocalHistoryRouteData {
1306    fn default() -> LocalHistoryRouteData {
1307        LocalHistoryRouteData::new()
1308    }
1309}
1310
1311/// The accessors [`LocalHistoryRoute`] asks for, for a struct whose bag is the field
1312/// `local_history`.
1313#[macro_export]
1314macro_rules! local_history_route_accessors {
1315    () => {
1316        fn local_history_route_data(
1317            self: ::waft_foundation::Handle<Self>,
1318            app: &::waft_foundation::App,
1319        ) -> &$crate::LocalHistoryRouteData {
1320            &app.get(self).local_history
1321        }
1322
1323        fn local_history_route_data_mut(
1324            self: ::waft_foundation::Handle<Self>,
1325            app: &mut ::waft_foundation::App,
1326        ) -> &mut $crate::LocalHistoryRouteData {
1327            &mut app.get_mut(self).local_history
1328        }
1329    };
1330}
1331
1332/// A mixin used by routes to handle back navigations internally by popping a list.
1333///
1334/// When a [`Navigator`] is instructed to pop, the current route is given an opportunity to
1335/// handle the pop internally. A [`LocalHistoryRoute`] handles the pop internally if its list of
1336/// local history entries is non-empty. Rather than being removed as the current route, the most
1337/// recent [`LocalHistoryEntry`] is removed from the list and its
1338/// [`LocalHistoryEntry::on_remove`] is called.
1339pub trait LocalHistoryRoute: TransitionRoute {
1340    /// Dart's `LocalHistoryRoute` fields, held under the field `local_history`
1341    /// ([`local_history_route_accessors!`](crate::local_history_route_accessors)).
1342    fn local_history_route_data(self: Handle<Self>, app: &App) -> &LocalHistoryRouteData;
1343
1344    /// See [`local_history_route_data`](Self::local_history_route_data).
1345    fn local_history_route_data_mut(
1346        self: Handle<Self>,
1347        app: &mut App,
1348    ) -> &mut LocalHistoryRouteData;
1349
1350    /// Adds a local history entry to this route.
1351    ///
1352    /// When asked to pop, if this route has any local history entries, this route will handle
1353    /// the pop internally by removing the most recently added local history entry.
1354    ///
1355    /// The given local history entry must not already be part of another local history route.
1356    fn add_local_history_entry(self: Handle<Self>, app: &mut App, entry: Ref<LocalHistoryEntry>) {
1357        debug_assert!(app.get(&entry).owner.is_none());
1358        app.get_mut(&entry).owner = Some(self.as_route());
1359        let implies_app_bar_dismissal = app.get(&entry).implies_app_bar_dismissal;
1360        let data = self.local_history_route_data_mut(app);
1361        let history = data.local_history.get_or_insert_with(Vec::new);
1362        let was_empty = history.is_empty();
1363        history.push(entry);
1364        let mut internal_state_changed = false;
1365        if implies_app_bar_dismissal {
1366            let data = self.local_history_route_data_mut(app);
1367            internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
1368            data.entries_implies_app_bar_dismissal += 1;
1369        }
1370        if was_empty || internal_state_changed {
1371            Route::changed_internal_state(self, app);
1372        }
1373    }
1374
1375    /// Removes a local history entry from this route.
1376    ///
1377    /// The entry's [`LocalHistoryEntry::on_remove`] callback, if any, is called synchronously.
1378    fn remove_local_history_entry(
1379        self: Handle<Self>,
1380        app: &mut App,
1381        entry: Handle<LocalHistoryEntry>,
1382    ) {
1383        debug_assert!(app.get(entry).owner == Some(self.as_route()));
1384        let data = self.local_history_route_data_mut(app);
1385        let history = data.local_history.as_mut().expect("a local history");
1386        debug_assert!(history.iter().any(|held| held == entry));
1387        let position = history.iter().position(|held| held == entry);
1388        let mut internal_state_changed = false;
1389        if let Some(position) = position {
1390            history.remove(position);
1391            if app.get(entry).implies_app_bar_dismissal {
1392                let data = self.local_history_route_data_mut(app);
1393                data.entries_implies_app_bar_dismissal -= 1;
1394                internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
1395            }
1396        }
1397        app.get_mut(entry).owner = None;
1398        entry.notify_removed(app);
1399        let data = self.local_history_route_data(app);
1400        if data.local_history.as_ref().is_some_and(Vec::is_empty) || internal_state_changed {
1401            debug_assert_eq!(
1402                self.local_history_route_data(app)
1403                    .entries_implies_app_bar_dismissal,
1404                0
1405            );
1406            if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PersistentCallbacks {
1407                // The local history might be removed as a result of disposing inactive elements
1408                // during `finalize_tree`. The state is locked at this moment, and we can only
1409                // notify that state has changed in the next frame.
1410                SchedulerBinding::add_post_frame_callback(
1411                    app,
1412                    FrameCallback::new(move |app, _duration| {
1413                        if self.upgrade(app).is_some() && self.as_route().is_active(app) {
1414                            Route::changed_internal_state(self, app);
1415                        }
1416                    }),
1417                    self.as_route()
1418                        .navigator(app)
1419                        .and_then(|navigator| View::maybe_id_of(app, navigator.context(app))),
1420                );
1421            } else {
1422                Route::changed_internal_state(self, app);
1423            }
1424        }
1425    }
1426
1427    /// Dart's `LocalHistoryRoute.willPop`.
1428    fn will_pop(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
1429        if Route::will_handle_pop_internally(self, app) {
1430            return RoutePopDisposition::Pop;
1431        }
1432        RouteBase::will_pop(self, app)
1433    }
1434
1435    /// Dart's `LocalHistoryRoute.popDisposition`.
1436    fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
1437        if Route::will_handle_pop_internally(self, app) {
1438            return RoutePopDisposition::Pop;
1439        }
1440        RouteBase::pop_disposition(self, app)
1441    }
1442
1443    /// Dart's `LocalHistoryRoute.didPop`.
1444    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
1445        let last = self
1446            .local_history_route_data_mut(app)
1447            .local_history
1448            .as_mut()
1449            .and_then(Vec::pop);
1450        if let Some(entry) = last {
1451            debug_assert!(app.get(&entry).owner == Some(self.as_route()));
1452            app.get_mut(&entry).owner = None;
1453            entry.notify_removed(app);
1454            let mut internal_state_changed = false;
1455            if app.get(&entry).implies_app_bar_dismissal {
1456                let data = self.local_history_route_data_mut(app);
1457                data.entries_implies_app_bar_dismissal -= 1;
1458                internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
1459            }
1460            let empty = self
1461                .local_history_route_data(app)
1462                .local_history
1463                .as_ref()
1464                .is_some_and(Vec::is_empty);
1465            if empty || internal_state_changed {
1466                Route::changed_internal_state(self, app);
1467            }
1468            return false;
1469        }
1470        TransitionRoute::did_pop(self, app, result)
1471    }
1472
1473    /// Dart's `LocalHistoryRoute.willHandlePopInternally`.
1474    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
1475        self.local_history_route_data(app)
1476            .local_history
1477            .as_ref()
1478            .is_some_and(|history| !history.is_empty())
1479    }
1480}
1481
1482// ---------------------------------------------------------------------------------------------
1483// _ModalScope
1484
1485/// Dart's `_DismissModalAction`.
1486struct DismissModalAction {
1487    action: ActionData,
1488    context: BuildContext,
1489}
1490
1491impl DismissModalAction {
1492    fn new(app: &mut App, context: BuildContext) -> Ref<DismissModalAction> {
1493        app.create(DismissModalAction {
1494            action: ActionData::new(),
1495            context,
1496        })
1497    }
1498}
1499
1500impl Action for DismissModalAction {
1501    type Intent = DismissIntent;
1502
1503    crate::action_accessors!();
1504
1505    fn is_enabled(self: Handle<Self>, app: &mut App, _intent: &DismissIntent) -> bool {
1506        let context = app.get(self).context;
1507        let route = AnyModalRoute::of(app, context).expect("a dismiss action inside a modal route");
1508        route.barrier_dismissible(app)
1509    }
1510
1511    fn invoke(self: Handle<Self>, app: &mut App, _intent: &DismissIntent) -> Option<Rc<dyn Any>> {
1512        let context = app.get(self).context;
1513        let popped = Navigator::of(app, context, false).maybe_pop(app, None);
1514        Some(Rc::new(popped))
1515    }
1516}
1517
1518impl DismissAction for DismissModalAction {}
1519
1520/// Dart's `_ModalRouteAspect`: the aspects of a [`ModalRoute`] a dependent can depend on.
1521#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1522enum ModalRouteAspect {
1523    /// Specifies the aspect corresponding to [`AnyRoute::is_current`].
1524    IsCurrent,
1525    /// Specifies the aspect corresponding to [`ModalRoute::can_pop`].
1526    CanPop,
1527    /// Specifies the aspect corresponding to [`AnyRoute::settings`].
1528    Settings,
1529    /// Specifies the aspect corresponding to [`AnyRoute::is_active`].
1530    IsActive,
1531    /// Specifies the aspect corresponding to [`AnyRoute::is_first`].
1532    IsFirst,
1533    /// Specifies the aspect corresponding to [`TransitionRoute::opaque`].
1534    Opaque,
1535    /// Specifies the aspect corresponding to [`Route::pop_disposition`].
1536    PopDisposition,
1537}
1538
1539/// Dart's `_ModalScopeStatus`.
1540#[derive(Debug)]
1541struct ModalScopeStatus {
1542    is_current: bool,
1543    can_pop: bool,
1544    implies_app_bar_dismissal: bool,
1545    opaque: bool,
1546    route: ModalRouteRef,
1547    child: WidgetRef,
1548}
1549
1550impl InheritedWidget for ModalScopeStatus {
1551    fn child(&self) -> &WidgetRef {
1552        &self.child
1553    }
1554
1555    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1556        properties.add(
1557            FlagProperty::new("isCurrent", Some(self.is_current))
1558                .if_true("active")
1559                .if_false("inactive"),
1560        );
1561        properties.add(FlagProperty::new("canPop", Some(self.can_pop)).if_true("can pop"));
1562        properties.add(
1563            FlagProperty::new(
1564                "impliesAppBarDismissal",
1565                Some(self.implies_app_bar_dismissal),
1566            )
1567            .if_true("implies app bar dismissal"),
1568        );
1569    }
1570
1571    fn update_should_notify(&self, old: &ModalScopeStatus) -> bool {
1572        self.is_current != old.is_current
1573            || self.can_pop != old.can_pop
1574            || self.implies_app_bar_dismissal != old.implies_app_bar_dismissal
1575            || self.route != old.route
1576            || self.opaque != old.opaque
1577    }
1578}
1579
1580impl ModalScopeStatus {
1581    /// The erased widget: an [`InheritedModel`] has two `IntoWidget` impls, so the kind is
1582    /// named here.
1583    fn into_widget(self) -> WidgetRef {
1584        IntoWidget::<crate::framework::InheritedModelKind>::into_widget(self)
1585    }
1586}
1587
1588impl InheritedModel for ModalScopeStatus {
1589    type Aspect = ModalRouteAspect;
1590
1591    fn update_should_notify_dependent(
1592        &self,
1593        old_widget: &ModalScopeStatus,
1594        dependencies: &std::collections::HashSet<ModalRouteAspect>,
1595    ) -> bool {
1596        // The aspects that read the route need the App; the widget cannot. The route-derived
1597        // aspects are compared through the aspect's own recorded value instead.
1598        dependencies.iter().any(|dependency| match dependency {
1599            ModalRouteAspect::IsCurrent => self.is_current != old_widget.is_current,
1600            ModalRouteAspect::CanPop => self.can_pop != old_widget.can_pop,
1601            ModalRouteAspect::Settings
1602            | ModalRouteAspect::IsActive
1603            | ModalRouteAspect::IsFirst
1604            | ModalRouteAspect::PopDisposition => self.route != old_widget.route,
1605            ModalRouteAspect::Opaque => self.opaque != old_widget.opaque,
1606        })
1607    }
1608}
1609
1610/// Dart's `_ModalScope`.
1611#[derive(Debug)]
1612struct ModalScope {
1613    key: Option<KeyRef>,
1614    route: AnyModalRoute,
1615}
1616
1617impl StatefulWidget for ModalScope {
1618    type State = ModalScopeState;
1619
1620    fn key(&self) -> Option<&KeyRef> {
1621        self.key.as_ref()
1622    }
1623
1624    fn create_state(&self) -> ModalScopeState {
1625        ModalScopeState {
1626            state: StateData::new(),
1627            page: None,
1628            listenable: None,
1629            focus_scope_node: None,
1630            primary_scroll_controller: None,
1631            no_gesture_in_progress: None,
1632        }
1633    }
1634}
1635
1636/// Dart's `_ModalScopeState`.
1637struct ModalScopeState {
1638    state: StateData<ModalScope>,
1639    // We cache the result of calling the route's `build_page`, and clear the cache whenever the
1640    // dependencies change. This implements the contract described in the documentation for
1641    // `build_page`, namely that it gets called once, unless something like a `ModalRoute::of`
1642    // dependency triggers an update.
1643    page: Option<WidgetRef>,
1644    // This is the combination of the two animations for the route.
1645    listenable: Option<Rc<MergingListenable>>,
1646    focus_scope_node: Option<Ref<FocusScopeNode>>,
1647    primary_scroll_controller: Option<Ref<ScrollController>>,
1648    /// The notifier a scope whose route has no navigator listens to, where Dart makes a fresh
1649    /// `ValueNotifier<bool>(false)` in each build.
1650    no_gesture_in_progress: Option<Ref<waft_foundation::ValueNotifier<bool>>>,
1651}
1652
1653impl ModalScopeState {
1654    /// The node this scope uses for its root `FocusScope` widget.
1655    fn focus_scope_node(self: Handle<Self>, app: &App) -> Handle<FocusScopeNode> {
1656        app.get(self)
1657            .focus_scope_node
1658            .handle()
1659            .expect("init_state has run")
1660    }
1661
1662    fn route(self: Handle<Self>, app: &App) -> AnyModalRoute {
1663        self.widget(app).route
1664    }
1665
1666    fn update_focus_scope_node(self: Handle<Self>, app: &mut App) {
1667        let route = self.route(app);
1668        let navigator = route
1669            .as_route()
1670            .navigator(app)
1671            .expect("a mounted scope has a navigator");
1672        let traversal_edge_behavior = match route.traversal_edge_behavior(app) {
1673            Some(behavior) => behavior,
1674            None => navigator.widget(app).route_traversal_edge_behavior,
1675        };
1676        let directional_traversal_edge_behavior =
1677            match route.directional_traversal_edge_behavior(app) {
1678                Some(behavior) => behavior,
1679                None => {
1680                    navigator
1681                        .widget(app)
1682                        .route_directional_traversal_edge_behavior
1683                }
1684            };
1685        let node = self.focus_scope_node(app);
1686        node.set_traversal_edge_behavior(app, traversal_edge_behavior);
1687        node.set_directional_traversal_edge_behavior(app, directional_traversal_edge_behavior);
1688        if route.as_route().is_current(app) && self.should_request_focus(app) {
1689            let focus_node = navigator.focus_node(app);
1690            if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
1691                scope.set_first_focus(app, node);
1692            }
1693        }
1694    }
1695
1696    fn force_rebuild_page(self: Handle<Self>, app: &mut App) {
1697        self.set_state(app, |state| {
1698            state.page = None;
1699        });
1700    }
1701
1702    fn should_ignore_focus_request(self: Handle<Self>, app: &mut App) -> bool {
1703        let route = self.route(app);
1704        let reversing = route
1705            .animation(app)
1706            .is_some_and(|animation| animation.status(app) == AnimationStatus::Reverse);
1707        reversing
1708            || route
1709                .as_route()
1710                .navigator(app)
1711                .is_some_and(|navigator| navigator.user_gesture_in_progress(app))
1712    }
1713
1714    fn should_request_focus(self: Handle<Self>, app: &App) -> bool {
1715        self.route(app).as_route().request_focus(app)
1716    }
1717
1718    /// Dart's `_routeSetState`: wraps any change to the route's `is_current`, `can_pop` or
1719    /// `offstage`.
1720    fn route_set_state(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut App)) {
1721        let route = self.route(app);
1722        if route.as_route().is_current(app)
1723            && !self.should_ignore_focus_request(app)
1724            && self.should_request_focus(app)
1725        {
1726            let navigator = route.as_route().navigator(app).expect("a current route");
1727            let focus_node = navigator.focus_node(app);
1728            let node = self.focus_scope_node(app);
1729            if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
1730                scope.set_first_focus(app, node);
1731            }
1732        }
1733        change(app);
1734        self.set_state(app, |_state| {});
1735    }
1736}
1737
1738impl State for ModalScopeState {
1739    type Widget = ModalScope;
1740    crate::state_accessors!();
1741
1742    fn init_state(self: Handle<Self>, app: &mut App) {
1743        let node = FocusScopeNode::new(app);
1744        node.as_node()
1745            .set_debug_label(app, Some("ModalScopeState Focus Scope".to_string()));
1746        app.get_mut(self).focus_scope_node = Some(node);
1747        app.get_mut(self).primary_scroll_controller =
1748            Some(ScrollController::new(app, 0.0, true, None, None, None));
1749        app.get_mut(self).no_gesture_in_progress =
1750            Some(app.create(waft_foundation::ValueNotifier::new(false)));
1751        let route = self.route(app);
1752        let as_listenable = |animation: AnyAnimation<f64>| {
1753            Rc::new(animation.keep(app)) as Rc<dyn waft_foundation::Listenable>
1754        };
1755        let animations: Vec<Option<Rc<dyn waft_foundation::Listenable>>> = vec![
1756            route.animation(app).map(as_listenable),
1757            route.secondary_animation(app).map(as_listenable),
1758        ];
1759        app.get_mut(self).listenable = Some(Rc::new(MergingListenable::new(animations)));
1760    }
1761
1762    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ModalScope) {
1763        debug_assert!(self.widget(app).route == old_widget.route);
1764        self.update_focus_scope_node(app);
1765    }
1766
1767    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1768        app.get_mut(self).page = None;
1769        self.update_focus_scope_node(app);
1770    }
1771
1772    fn dispose(self: Handle<Self>, app: &mut App) {
1773        let node = self.focus_scope_node(app);
1774        node.dispose(app);
1775        let controller = app
1776            .get(self)
1777            .primary_scroll_controller
1778            .handle()
1779            .expect("init_state");
1780        ScrollController::dispose(controller.as_controller(), app);
1781    }
1782
1783    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1784        // The widgets built here keep the route, as Dart's closures over `widget.route` do.
1785        let route = self.route(app);
1786        let route_kept = route.keep(app);
1787        let node = app
1788            .get(self)
1789            .focus_scope_node
1790            .clone()
1791            .expect("init_state has run");
1792        // Only the top-most route can participate in focus traversal.
1793        let is_current = route.as_route().is_current(app);
1794        node.set_skip_traversal(app, !is_current);
1795
1796        let page = match app.get(self).page.clone() {
1797            Some(page) => page,
1798            None => {
1799                let page_route = route_kept.clone();
1800                let page = RepaintBoundary::new()
1801                    .key(route.subtree_key(app).into())
1802                    .child(Builder::new(move |app, context| {
1803                        let (animation, secondary) = page_route.animations(app);
1804                        page_route.build_page(app, context, animation, secondary)
1805                    }))
1806                    .into_widget();
1807                app.get_mut(self).page = Some(page.clone());
1808                page
1809            }
1810        };
1811
1812        let gesture_notifier: Rc<dyn waft_foundation::Listenable> = match route
1813            .as_route()
1814            .navigator(app)
1815        {
1816            Some(navigator) => Rc::new(navigator.user_gesture_in_progress_notifier(app).keep(app)),
1817            None => Rc::new(
1818                app.get(self)
1819                    .no_gesture_in_progress
1820                    .clone()
1821                    .expect("init_state"),
1822            ),
1823        };
1824        let listenable = app.get(self).listenable.clone().expect("init_state");
1825
1826        let transitions_route = route_kept.clone();
1827        let transitions_node = node.clone();
1828        let transitions = ListenableBuilder::new(listenable, move |app, context, child| {
1829            let route = &transitions_route;
1830            let node = transitions_node.clone();
1831            let child = child.cloned().expect("the cached page");
1832            let (animation, secondary) = route.animations(app);
1833            // This additional builder is included because if the value of the user-gesture
1834            // notifier changes, it is only necessary to rebuild the `IgnorePointer` widget and
1835            // set the focus node's ability to focus.
1836            let ignoring = ListenableBuilder::new(Rc::clone(&gesture_notifier), {
1837                move |app: &mut App, _context: BuildContext, child: Option<&WidgetRef>| {
1838                    let ignore_events = self.should_ignore_focus_request(app);
1839                    node.set_can_request_focus(app, !ignore_events);
1840                    let mut widget = IgnorePointer::new().ignoring(ignore_events);
1841                    if let Some(child) = child {
1842                        widget = widget.child(child.clone());
1843                    }
1844                    widget.into_widget()
1845                }
1846            })
1847            .child(child)
1848            .into_widget();
1849            route.build_flexible_transitions(app, context, animation, secondary, ignoring)
1850        })
1851        .child(page)
1852        .into_widget();
1853
1854        let scope_child = Builder::new(move |app, context| {
1855            let dismiss_action: ActionRef = DismissModalAction::new(app, context).into_erased();
1856            let mut actions = HashMap::new();
1857            actions.insert(
1858                <DismissModalAction as Action>::intent_type(),
1859                dismiss_action,
1860            );
1861            let controller: ScrollControllerRef = app
1862                .get(self)
1863                .primary_scroll_controller
1864                .as_ref()
1865                .expect("init_state")
1866                .erase();
1867            Actions::new(
1868                actions,
1869                PrimaryScrollController::new(
1870                    controller,
1871                    FocusScope::with_external_focus_node(
1872                        RepaintBoundary::new().child(transitions.clone()),
1873                        node.clone(),
1874                    ),
1875                ),
1876            )
1877            .into_widget()
1878        });
1879
1880        let storage_bucket = route.storage_bucket(app).keep(app);
1881        let status = ModalScopeStatus {
1882            route: route_kept,
1883            // `route_set_state` is called if any of these update.
1884            is_current,
1885            can_pop: route.can_pop(app),
1886            opaque: route.opaque(app),
1887            implies_app_bar_dismissal: route.implies_app_bar_dismissal(app),
1888            child: Offstage::new()
1889                .offstage(route.offstage(app))
1890                .child(PageStorage::new(storage_bucket, scope_child))
1891                .into_widget(),
1892        };
1893
1894        let restoration_scope_id = route.as_route().restoration_scope_id(app).keep(app);
1895        AnimatedBuilder::new(
1896            Rc::new(restoration_scope_id.clone()),
1897            move |app, _context, child| {
1898                let child = child.cloned().expect("the modal scope status");
1899                let id = app.get(&restoration_scope_id).value().clone();
1900                RestorationScope::new(id, child).into_widget()
1901            },
1902        )
1903        .child(status.into_widget())
1904        .into_widget()
1905    }
1906}
1907
1908// ---------------------------------------------------------------------------------------------
1909// ModalRoute
1910
1911/// The fields Dart's `ModalRoute` declares; every modal route carries this bag under the field
1912/// `modal_route`.
1913pub struct ModalRouteData {
1914    /// The filter to add to the barrier.
1915    ///
1916    /// If given, this filter is applied to the modal barrier using `BackdropFilter`. This
1917    /// allows blur effects, for example.
1918    pub filter: Option<waft_rendering::ImageFilterConfig>,
1919    /// Controls the transfer of focus beyond the first and the last items of a
1920    /// [`FocusScopeNode`].
1921    ///
1922    /// If `None`, [`Navigator::route_traversal_edge_behavior`] is used.
1923    pub traversal_edge_behavior: Option<TraversalEdgeBehavior>,
1924    /// Controls the directional transfer of focus beyond the first and the last items of a
1925    /// [`FocusScopeNode`].
1926    ///
1927    /// If `None`, [`Navigator::route_directional_traversal_edge_behavior`] is used.
1928    pub directional_traversal_edge_behavior: Option<TraversalEdgeBehavior>,
1929    /// The `DelegatedTransitionBuilder` received from the route above this one in the
1930    /// navigation stack.
1931    ///
1932    /// It uses the above route's [`ModalRoute::delegated_transition`] in order to show the
1933    /// right route transition when the above route either enters or leaves the navigation
1934    /// stack. If not `None`, it wraps the route content.
1935    pub received_transition: Option<DelegatedTransitionBuilder>,
1936    offstage: bool,
1937    animation_proxy: Option<Ref<ProxyAnimation>>,
1938    secondary_animation_proxy: Option<Ref<ProxyAnimation>>,
1939    pop_entries: Vec<Rc<dyn PopEntry>>,
1940    scope_key: GlobalKey,
1941    subtree_key: GlobalKey,
1942    storage_bucket: Ref<PageStorageBucket>,
1943    modal_barrier: Option<Ref<OverlayEntry>>,
1944    modal_scope: Option<Ref<OverlayEntry>>,
1945    modal_scope_cache: Option<WidgetRef>,
1946}
1947
1948impl ModalRouteData {
1949    /// The bag of a freshly created modal route; Dart's constructor defaults.
1950    pub fn new(app: &mut App) -> ModalRouteData {
1951        ModalRouteData {
1952            filter: None,
1953            traversal_edge_behavior: None,
1954            directional_traversal_edge_behavior: None,
1955            received_transition: None,
1956            offstage: false,
1957            animation_proxy: None,
1958            secondary_animation_proxy: None,
1959            pop_entries: Vec::new(),
1960            scope_key: GlobalKey::new(),
1961            subtree_key: GlobalKey::new(),
1962            storage_bucket: PageStorageBucket::new(app),
1963            modal_barrier: None,
1964            modal_scope: None,
1965            modal_scope_cache: None,
1966        }
1967    }
1968}
1969
1970/// The accessors [`ModalRoute`] asks for, for a struct whose bag is the field `modal_route`.
1971#[macro_export]
1972macro_rules! modal_route_accessors {
1973    () => {
1974        fn modal_route_data(
1975            self: ::waft_foundation::Handle<Self>,
1976            app: &::waft_foundation::App,
1977        ) -> &$crate::ModalRouteData {
1978            &app.get(self).modal_route
1979        }
1980
1981        fn modal_route_data_mut(
1982            self: ::waft_foundation::Handle<Self>,
1983            app: &mut ::waft_foundation::App,
1984        ) -> &mut $crate::ModalRouteData {
1985            &mut app.get_mut(self).modal_route
1986        }
1987    };
1988}
1989
1990/// A route that blocks interaction with previous routes.
1991///
1992/// [`ModalRoute`]s cover the entire [`Navigator`]. They are not necessarily
1993/// [`opaque`](TransitionRoute::opaque), however; for example, a pop-up menu uses a
1994/// [`ModalRoute`] but only shows the menu in a small box overlapping the previous route.
1995///
1996/// See also:
1997///
1998///  * [`Route`], which further documents the meaning of Dart's `T` generic type argument.
1999pub trait ModalRoute: LocalHistoryRoute {
2000    /// Dart's `ModalRoute` fields, held under the field `modal_route`
2001    /// ([`modal_route_accessors!`](crate::modal_route_accessors)).
2002    fn modal_route_data(self: Handle<Self>, app: &App) -> &ModalRouteData;
2003
2004    /// See [`modal_route_data`](Self::modal_route_data).
2005    fn modal_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut ModalRouteData;
2006
2007    /// This route as the erased [`AnyModalRoute`].
2008    fn as_modal_route(self: Handle<Self>) -> AnyModalRoute {
2009        AnyModalRoute {
2010            id: self.id(),
2011            vtable: const { &ModalRouteVTable::of::<Self>() },
2012        }
2013    }
2014
2015    /// Schedules a call to [`build_transitions`](Self::build_transitions).
2016    ///
2017    /// Whenever you need to change internal state for a [`ModalRoute`] object, make the change
2018    /// in the closure you pass to `set_state`. If you just change the state directly without
2019    /// calling `set_state`, then the route will not be scheduled for rebuilding, meaning that
2020    /// its rendering will not be updated.
2021    fn set_state(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut App)) {
2022        let key = self.modal_route_data(app).scope_key.clone();
2023        match key.current_state::<ModalScopeState>(app) {
2024            Some(state) => state.route_set_state(app, change),
2025            None => {
2026                // The route isn't currently visible, so we don't have to call its `set_state`
2027                // method, but we do still need to run the change, otherwise the state in the
2028                // route won't be updated.
2029                change(app);
2030            }
2031        }
2032    }
2033
2034    /// Override this method to build the primary content of this route.
2035    ///
2036    /// The arguments have the following meanings:
2037    ///
2038    ///  * `context`: The context in which the route is being built.
2039    ///  * `animation`: The animation for this route's transition. When entering, the animation
2040    ///    runs forward from 0.0 to 1.0. When exiting, it runs backwards from 1.0 to 0.0.
2041    ///  * `secondary_animation`: The animation for the route being pushed on top of this route.
2042    ///
2043    /// This method is only called when the route is first built, and rarely thereafter. In
2044    /// particular, it is not automatically called again when the route's state changes unless
2045    /// it uses [`AnyModalRoute::of`]. For a builder that is called every time the route's state
2046    /// changes, consider [`build_transitions`](Self::build_transitions).
2047    fn build_page(
2048        self: Handle<Self>,
2049        app: &mut App,
2050        context: BuildContext,
2051        animation: AnimationRef<f64>,
2052        secondary_animation: AnimationRef<f64>,
2053    ) -> WidgetRef;
2054
2055    /// Override this method to wrap the `child` with one or more transition widgets that define
2056    /// how the route arrives on and leaves the screen.
2057    ///
2058    /// By default, the child (which contains the widget returned by
2059    /// [`build_page`](Self::build_page)) is not wrapped in any transition widgets.
2060    ///
2061    /// This method, in contrast to [`build_page`](Self::build_page), is called each time the
2062    /// route's state changes while it is visible.
2063    fn build_transitions(
2064        self: Handle<Self>,
2065        app: &mut App,
2066        context: BuildContext,
2067        animation: AnimationRef<f64>,
2068        secondary_animation: AnimationRef<f64>,
2069        child: WidgetRef,
2070    ) -> WidgetRef {
2071        let _ = (app, context, animation, secondary_animation);
2072        child
2073    }
2074
2075    /// The `DelegatedTransitionBuilder` provided to the route below this one in the navigation
2076    /// stack.
2077    ///
2078    /// Used for the purposes of coordinating transitions between two routes with different
2079    /// route transitions. When a route is added to the stack, the original topmost route will
2080    /// look for this transition, and if available, it will use it to animate off the screen.
2081    ///
2082    /// If the builder returns `None`, then by default the original transition of the routes
2083    /// will be used.
2084    ///
2085    /// The [`ModalRoute`] receiving this transition sets it as its
2086    /// [`received_transition`](ModalRouteData::received_transition).
2087    fn delegated_transition(self: Handle<Self>, app: &App) -> Option<DelegatedTransitionBuilder> {
2088        let _ = app;
2089        None
2090    }
2091
2092    /// Dart's `_buildFlexibleTransitions`: wraps the transitions of this route with the
2093    /// [`received_transition`](ModalRouteData::received_transition), when there is one.
2094    fn build_flexible_transitions(
2095        self: Handle<Self>,
2096        app: &mut App,
2097        context: BuildContext,
2098        animation: AnimationRef<f64>,
2099        secondary_animation: AnimationRef<f64>,
2100        child: WidgetRef,
2101    ) -> WidgetRef {
2102        let received = self.modal_route_data(app).received_transition.clone();
2103        let Some(received) = received else {
2104            return ModalRoute::build_transitions(
2105                self,
2106                app,
2107                context,
2108                animation,
2109                secondary_animation,
2110                child,
2111            );
2112        };
2113        if secondary_animation.is_dismissed(app) {
2114            return ModalRoute::build_transitions(
2115                self,
2116                app,
2117                context,
2118                animation,
2119                secondary_animation,
2120                child,
2121            );
2122        }
2123
2124        // Create a static proxy animation to suppress the original secondary transition.
2125        let proxy_animation: AnimationRef<f64> = ProxyAnimation::new(app, None).into_erased();
2126        let proxied_original_transitions = ModalRoute::build_transitions(
2127            self,
2128            app,
2129            context,
2130            animation.clone(),
2131            proxy_animation,
2132            child,
2133        );
2134
2135        // If the received transition returns nothing, then we want the original transitions,
2136        // but with the secondary animation still proxied. This keeps a desynched animation from
2137        // playing.
2138        let allow_snapshotting = TransitionRoute::allow_snapshotting(self, app);
2139        received
2140            .call(
2141                app,
2142                context,
2143                animation,
2144                secondary_animation,
2145                allow_snapshotting,
2146                Some(&proxied_original_transitions),
2147            )
2148            .unwrap_or(proxied_original_transitions)
2149    }
2150
2151    /// Dart's `ModalRoute.install`.
2152    fn install(self: Handle<Self>, app: &mut App) {
2153        TransitionRoute::install(self, app);
2154        let animation = self.transition_route_data(app).animation.clone();
2155        let secondary: AnimationRef<f64> =
2156            self.transition_route_data(app).secondary_animation.erase();
2157        self.modal_route_data_mut(app).animation_proxy = Some(ProxyAnimation::new(app, animation));
2158        self.modal_route_data_mut(app).secondary_animation_proxy =
2159            Some(ProxyAnimation::new(app, Some(secondary)));
2160    }
2161
2162    /// Dart's `ModalRoute.didPush`.
2163    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
2164        let key = self.modal_route_data(app).scope_key.clone();
2165        if let Some(state) = key.current_state::<ModalScopeState>(app) {
2166            let navigator = self.as_route().navigator(app).expect("an installed route");
2167            if navigator.widget(app).request_focus {
2168                let focus_node = navigator.focus_node(app);
2169                let scope_node = state.focus_scope_node(app);
2170                if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
2171                    scope.set_first_focus(app, scope_node);
2172                }
2173            }
2174        }
2175        TransitionRoute::did_push(self, app)
2176    }
2177
2178    /// Dart's `ModalRoute.didAdd`.
2179    fn did_add(self: Handle<Self>, app: &mut App) {
2180        let key = self.modal_route_data(app).scope_key.clone();
2181        if let Some(state) = key.current_state::<ModalScopeState>(app) {
2182            let navigator = self.as_route().navigator(app).expect("an installed route");
2183            if navigator.widget(app).request_focus {
2184                let focus_node = navigator.focus_node(app);
2185                let scope_node = state.focus_scope_node(app);
2186                if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
2187                    scope.set_first_focus(app, scope_node);
2188                }
2189            }
2190        }
2191        TransitionRoute::did_add(self, app);
2192    }
2193
2194    /// Whether you can dismiss this route by tapping the modal barrier.
2195    ///
2196    /// The modal barrier is the scrim that is rendered behind each route, which generally
2197    /// prevents the user from interacting with the route below the current route, and normally
2198    /// partially obscures such routes.
2199    ///
2200    /// If `barrier_dismissible` is true, then tapping this barrier, pressing the escape key on
2201    /// the keyboard, or calling route popping functions such as [`Navigator::pop`] will cause
2202    /// the current route to be popped with no value.
2203    ///
2204    /// If this getter would ever start returning a different value, either
2205    /// [`changed_internal_state`](Route::changed_internal_state) or
2206    /// [`changed_external_state`](Route::changed_external_state) should be invoked so that the
2207    /// change can take effect.
2208    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool;
2209
2210    /// Whether the semantics of the modal barrier are included in the semantics tree.
2211    fn semantics_dismissible(self: Handle<Self>, app: &App) -> bool {
2212        let _ = app;
2213        true
2214    }
2215
2216    /// The color to use for the modal barrier. If this is `None`, the barrier will be
2217    /// transparent.
2218    ///
2219    /// The color is ignored, and the barrier made invisible, when
2220    /// [`offstage`](Self::offstage) is true.
2221    ///
2222    /// While the route is animating into position, the color is animated from transparent to
2223    /// the specified color.
2224    fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color>;
2225
2226    /// The semantic label used for a dismissible barrier.
2227    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String>;
2228
2229    /// The curve that is used for animating the modal barrier in and out.
2230    ///
2231    /// It defaults to [`Curves::ease`].
2232    fn barrier_curve(self: Handle<Self>, app: &App) -> Rc<dyn Curve> {
2233        let _ = app;
2234        Curves::ease()
2235    }
2236
2237    /// Whether the route should remain in memory when it is inactive.
2238    ///
2239    /// If this is true, then the route is maintained, so that any completions it is holding
2240    /// from the next route will properly resolve when the next route pops. If this is not
2241    /// necessary, this can be set to false to allow the framework to entirely discard the
2242    /// route's widget hierarchy when it is not visible.
2243    fn maintain_state(self: Handle<Self>, app: &App) -> bool;
2244
2245    /// True if a back gesture (iOS-style back swipe or Android predictive back) is currently
2246    /// underway for this route.
2247    fn pop_gesture_in_progress(self: Handle<Self>, app: &App) -> bool {
2248        self.as_route()
2249            .navigator(app)
2250            .expect("an installed route")
2251            .user_gesture_in_progress(app)
2252    }
2253
2254    /// Dart's `ModalRoute.popGestureEnabled`.
2255    fn pop_gesture_enabled(self: Handle<Self>, app: &mut App) -> bool {
2256        // If there's nothing to go back to, then obviously we don't support the back gesture.
2257        if self.as_route().is_first(app) {
2258            return false;
2259        }
2260        // If the route wouldn't actually pop if we popped it, then the gesture would be really
2261        // confusing (or would skip internal routes), so disallow it.
2262        if Route::will_handle_pop_internally(self, app) {
2263            return false;
2264        }
2265        // If attempts to dismiss this route might be vetoed, then do not allow the user to
2266        // dismiss the route with a swipe.
2267        if Route::pop_disposition(self, app) == RoutePopDisposition::DoNotPop {
2268            return false;
2269        }
2270        // If we're in an animation already, we cannot be manually swiped.
2271        let animation = TransitionRoute::animation(self, app).expect("an installed route");
2272        if !animation.is_completed(app) {
2273            return false;
2274        }
2275        // Looks like a back gesture would be welcome!
2276        true
2277    }
2278
2279    /// Whether this route is currently offstage.
2280    ///
2281    /// On the first frame of a route's entrance transition, the route is built `Offstage` using
2282    /// an animation progress of 1.0. The route is invisible and non-interactive, but each
2283    /// widget has its final size and position. This mechanism lets the `HeroController`
2284    /// determine the final location of any hero widgets being animated as part of the
2285    /// transition.
2286    ///
2287    /// The modal barrier, if any, is not rendered if `offstage` is true.
2288    ///
2289    /// Whenever this changes value, [`changed_internal_state`](Route::changed_internal_state)
2290    /// is called.
2291    fn offstage(self: Handle<Self>, app: &App) -> bool {
2292        self.modal_route_data(app).offstage
2293    }
2294
2295    /// Sets [`offstage`](Self::offstage).
2296    fn set_offstage(self: Handle<Self>, app: &mut App, value: bool) {
2297        if self.modal_route_data(app).offstage == value {
2298            return;
2299        }
2300        ModalRoute::set_state(self, app, |app| {
2301            self.modal_route_data_mut(app).offstage = value;
2302        });
2303        let offstage = self.modal_route_data(app).offstage;
2304        let animation_proxy = self
2305            .modal_route_data(app)
2306            .animation_proxy
2307            .handle()
2308            .expect("installed");
2309        let parent = if offstage {
2310            Some(k_always_complete_animation(app))
2311        } else {
2312            self.transition_route_data(app).animation.clone()
2313        };
2314        animation_proxy.set_parent(app, parent);
2315        let secondary_proxy = self
2316            .modal_route_data(app)
2317            .secondary_animation_proxy
2318            .handle()
2319            .expect("installed");
2320        let parent = if offstage {
2321            k_always_dismissed_animation(app)
2322        } else {
2323            self.transition_route_data(app).secondary_animation.erase()
2324        };
2325        secondary_proxy.set_parent(app, Some(parent));
2326        Route::changed_internal_state(self, app);
2327    }
2328
2329    /// The build context for the subtree containing the primary content of this route.
2330    fn subtree_context(self: Handle<Self>, app: &mut App) -> Option<BuildContext> {
2331        let key = self.modal_route_data(app).subtree_key.clone();
2332        key.current_context(app)
2333    }
2334
2335    /// Dart's `ModalRoute.animation`.
2336    fn animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
2337        self.modal_route_data(app)
2338            .animation_proxy
2339            .handle()
2340            .map(Animation::as_animation)
2341    }
2342
2343    /// Dart's `ModalRoute.secondaryAnimation`.
2344    fn secondary_animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
2345        self.modal_route_data(app)
2346            .secondary_animation_proxy
2347            .handle()
2348            .map(Animation::as_animation)
2349    }
2350
2351    /// Dart's `ModalRoute.popDisposition`.
2352    ///
2353    /// Returns [`RoutePopDisposition::DoNotPop`] if any of the [`PopEntry`] instances
2354    /// registered with [`register_pop_entry`](Self::register_pop_entry) have their
2355    /// [`PopEntry::can_pop_notifier`] set to false.
2356    fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
2357        for pop_entry in self.modal_route_data(app).pop_entries.clone() {
2358            if !*pop_entry.can_pop_notifier(app).value(app) {
2359                return RoutePopDisposition::DoNotPop;
2360            }
2361        }
2362        LocalHistoryRoute::pop_disposition(self, app)
2363    }
2364
2365    /// Dart's `ModalRoute.onPopInvokedWithResult`.
2366    fn on_pop_invoked_with_result(
2367        self: Handle<Self>,
2368        app: &mut App,
2369        did_pop: bool,
2370        result: RouteResult,
2371    ) {
2372        for pop_entry in self.modal_route_data(app).pop_entries.clone() {
2373            pop_entry.on_pop_invoked_with_result(app, did_pop, result.clone());
2374        }
2375        RouteBase::on_pop_invoked_with_result(self, app, did_pop, result);
2376    }
2377
2378    /// Registers the existence of a [`PopEntry`] in the route.
2379    ///
2380    /// [`PopEntry`] instances registered in this way will have their
2381    /// [`PopEntry::on_pop_invoked_with_result`] callbacks called when a route is popped or a
2382    /// pop is attempted. They will also be able to block pop operations with
2383    /// [`PopEntry::can_pop_notifier`] through this route's
2384    /// [`pop_disposition`](Self::pop_disposition) method.
2385    fn register_pop_entry(self: Handle<Self>, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
2386        if !self
2387            .modal_route_data(app)
2388            .pop_entries
2389            .iter()
2390            .any(|held| Rc::ptr_eq(held, &pop_entry))
2391        {
2392            self.modal_route_data_mut(app)
2393                .pop_entries
2394                .push(Rc::clone(&pop_entry));
2395        }
2396        let notifier = pop_entry.can_pop_notifier(app);
2397        notifier.add_listener(
2398            app,
2399            Listener::handle_method(self, Self::maybe_dispatch_navigation_notification),
2400        );
2401        ModalRoute::maybe_dispatch_navigation_notification(self, app);
2402    }
2403
2404    /// Unregisters a [`PopEntry`] in the route's widget subtree.
2405    fn unregister_pop_entry(self: Handle<Self>, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
2406        self.modal_route_data_mut(app)
2407            .pop_entries
2408            .retain(|held| !Rc::ptr_eq(held, &pop_entry));
2409        let notifier = pop_entry.can_pop_notifier(app);
2410        notifier.remove_listener(
2411            app,
2412            &Listener::handle_method(self, Self::maybe_dispatch_navigation_notification),
2413        );
2414        ModalRoute::maybe_dispatch_navigation_notification(self, app);
2415    }
2416
2417    /// Dart's `_maybeDispatchNavigationNotification`.
2418    fn maybe_dispatch_navigation_notification(self: Handle<Self>, app: &mut App) {
2419        if !self.as_route().is_current(app) {
2420            return;
2421        }
2422        // `can_handle_pop` indicates that the originator of the notification can handle a pop.
2423        // In the case of `PopScope`, it handles pops when `can_pop` is false. Hence the
2424        // seemingly backward logic here.
2425        let notification = NavigationNotification::new(
2426            Route::pop_disposition(self, app) == RoutePopDisposition::DoNotPop,
2427        );
2428        // Avoid dispatching a notification in the middle of a build.
2429        match SchedulerBinding::scheduler_phase(app) {
2430            SchedulerPhase::PostFrameCallbacks => {
2431                let context = ModalRoute::subtree_context(self, app);
2432                notification.dispatch(app, context);
2433            }
2434            SchedulerPhase::Idle
2435            | SchedulerPhase::MidFrameMicrotasks
2436            | SchedulerPhase::PersistentCallbacks
2437            | SchedulerPhase::TransientCallbacks => {
2438                let context = ModalRoute::subtree_context(self, app);
2439                SchedulerBinding::add_post_frame_callback(
2440                    app,
2441                    FrameCallback::new(move |app, _time_stamp| {
2442                        if self.upgrade(app).is_none() {
2443                            return;
2444                        }
2445                        let context = ModalRoute::subtree_context(self, app);
2446                        if !context.is_some_and(|context| context.mounted(app)) {
2447                            return;
2448                        }
2449                        notification.dispatch(app, context);
2450                    }),
2451                    context.and_then(|context| View::maybe_id_of(app, context)),
2452                );
2453            }
2454        }
2455    }
2456
2457    /// Dart's `ModalRoute.didChangePrevious`.
2458    fn did_change_previous(self: Handle<Self>, app: &mut App, previous_route: Option<AnyRoute>) {
2459        RouteBase::did_change_previous(self, app, previous_route);
2460        Route::changed_internal_state(self, app);
2461    }
2462
2463    /// Dart's `ModalRoute.didChangeNext`.
2464    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
2465        self.update_received_transition(app, next_route);
2466        TransitionRoute::did_change_next(self, app, next_route);
2467        Route::changed_internal_state(self, app);
2468    }
2469
2470    /// Dart's `ModalRoute.didPopNext`.
2471    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
2472        self.update_received_transition(app, Some(next_route));
2473        TransitionRoute::did_pop_next(self, app, next_route);
2474        Route::changed_internal_state(self, app);
2475        ModalRoute::maybe_dispatch_navigation_notification(self, app);
2476    }
2477
2478    /// The `nextRoute is ModalRoute && canTransitionTo(nextRoute) && …` branch both
2479    /// [`did_change_next`](Self::did_change_next) and [`did_pop_next`](Self::did_pop_next) run.
2480    fn update_received_transition(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
2481        let next_modal = next_route.and_then(|route| route.as_modal_route(app));
2482        let received = match next_modal {
2483            Some(next) => {
2484                let next_transition = next
2485                    .as_route()
2486                    .as_transition_route(app)
2487                    .expect("a modal route is a transition route");
2488                let mine = ModalRoute::delegated_transition(self, app);
2489                let theirs = next.delegated_transition(app);
2490                let differs = mine != theirs;
2491                if TransitionRoute::can_transition_to(self, app, next_transition) && differs {
2492                    theirs
2493                } else {
2494                    None
2495                }
2496            }
2497            None => None,
2498        };
2499        self.modal_route_data_mut(app).received_transition = received;
2500    }
2501
2502    /// Dart's `ModalRoute.changedInternalState`.
2503    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
2504        RouteBase::changed_internal_state(self, app);
2505        // No need to mark dirty if this method is called during the build phase.
2506        if SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks {
2507            ModalRoute::set_state(self, app, |_app| {
2508                // The internal state already changed.
2509            });
2510            let barrier = self
2511                .modal_route_data(app)
2512                .modal_barrier
2513                .handle()
2514                .expect("installed");
2515            barrier.mark_needs_build(app);
2516        }
2517        let maintain_state = ModalRoute::maintain_state(self, app);
2518        let scope = self
2519            .modal_route_data(app)
2520            .modal_scope
2521            .handle()
2522            .expect("installed");
2523        scope.set_maintain_state(app, maintain_state);
2524    }
2525
2526    /// Dart's `ModalRoute.changedExternalState`.
2527    fn changed_external_state(self: Handle<Self>, app: &mut App) {
2528        RouteBase::changed_external_state(self, app);
2529        let barrier = self
2530            .modal_route_data(app)
2531            .modal_barrier
2532            .handle()
2533            .expect("installed");
2534        barrier.mark_needs_build(app);
2535        let key = self.modal_route_data(app).scope_key.clone();
2536        if let Some(state) = key.current_state::<ModalScopeState>(app) {
2537            state.force_rebuild_page(app);
2538        }
2539    }
2540
2541    /// Whether this route can be popped.
2542    ///
2543    /// A route can be popped if there is at least one active route below it, or if
2544    /// [`will_handle_pop_internally`](Route::will_handle_pop_internally) returns true.
2545    fn can_pop(self: Handle<Self>, app: &mut App) -> bool {
2546        self.as_route().has_active_route_below(app) || Route::will_handle_pop_internally(self, app)
2547    }
2548
2549    /// Whether an app bar in the route should automatically add a back button or close button.
2550    ///
2551    /// This returns true if there is at least one active route below it, or there is at least
2552    /// one [`LocalHistoryEntry`] with
2553    /// [`implies_app_bar_dismissal`](LocalHistoryEntry::implies_app_bar_dismissal) set to true.
2554    fn implies_app_bar_dismissal(self: Handle<Self>, app: &App) -> bool {
2555        self.as_route().has_active_route_below(app)
2556            || self
2557                .local_history_route_data(app)
2558                .entries_implies_app_bar_dismissal
2559                > 0
2560    }
2561
2562    /// Whether this route is a full-screen dialog.
2563    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
2564        let _ = app;
2565        false
2566    }
2567
2568    /// Dart's `_buildModalBarrier`.
2569    fn build_modal_barrier_entry(
2570        self: Handle<Self>,
2571        app: &mut App,
2572        context: BuildContext,
2573    ) -> WidgetRef {
2574        let mut barrier = ModalRoute::build_modal_barrier(self, app, context);
2575        if let Some(filter) = self.modal_route_data(app).filter.clone() {
2576            barrier = crate::widgets::basic::BackdropFilter::new(filter)
2577                .child(barrier)
2578                .into_widget();
2579        }
2580        let animation = TransitionRoute::animation(self, app).expect("an installed route");
2581        // `changed_internal_state` is called when the animation status updates; dismissed is
2582        // possible when doing a manual pop gesture.
2583        barrier = IgnorePointer::new()
2584            .ignoring(!animation.is_forward_or_completed(app))
2585            .child(barrier)
2586            .into_widget();
2587        if ModalRoute::semantics_dismissible(self, app)
2588            && ModalRoute::barrier_dismissible(self, app)
2589        {
2590            // To be sorted after the _modalScope.
2591            barrier = Semantics::new()
2592                .sort_key(Rc::new(OrdinalSortKey::new(1.0)))
2593                .child(barrier)
2594                .into_widget();
2595        }
2596        barrier
2597    }
2598
2599    /// Builds the barrier for this [`ModalRoute`]; subclasses can override this method to
2600    /// create their own barrier with customized features such as color or accessibility focus
2601    /// size, and reach this body through [`ModalRouteBase::build_modal_barrier`].
2602    fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2603        ModalRouteBase::build_modal_barrier(self, app, context)
2604    }
2605
2606    /// Dart's `_buildModalScope`: the part of the modal scope that does not change from frame
2607    /// to frame, cached so that the amount of building is minimized.
2608    fn build_modal_scope(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2609        let _ = context;
2610        match self.modal_route_data(app).modal_scope_cache.clone() {
2611            Some(cache) => cache,
2612            None => {
2613                let key = self.modal_route_data(app).scope_key.clone();
2614                // To be sorted before the _modalBarrier.
2615                let scope = Semantics::new()
2616                    .sort_key(Rc::new(OrdinalSortKey::new(0.0)))
2617                    .child(ModalScope {
2618                        key: Some(key.into()),
2619                        route: ModalRoute::as_modal_route(self),
2620                    })
2621                    .into_widget();
2622                self.modal_route_data_mut(app).modal_scope_cache = Some(scope.clone());
2623                scope
2624            }
2625        }
2626    }
2627
2628    /// Dart's `ModalRoute.createOverlayEntries`.
2629    fn create_overlay_entries(self: Handle<Self>, app: &mut App) -> Vec<Ref<OverlayEntry>> {
2630        let barrier = OverlayEntry::new(
2631            app,
2632            Rc::new(move |app, context| ModalRoute::build_modal_barrier_entry(self, app, context)),
2633            false,
2634            false,
2635            false,
2636        );
2637        self.modal_route_data_mut(app).modal_barrier = Some(barrier.clone());
2638        let maintain_state = ModalRoute::maintain_state(self, app);
2639        let opaque = TransitionRoute::opaque(self, app);
2640        let scope = OverlayEntry::new(
2641            app,
2642            Rc::new(move |app, context| ModalRoute::build_modal_scope(self, app, context)),
2643            false,
2644            maintain_state,
2645            opaque,
2646        );
2647        self.modal_route_data_mut(app).modal_scope = Some(scope.clone());
2648        vec![barrier, scope]
2649    }
2650}
2651
2652/// The bodies of Dart's `ModalRoute` class that a subclass's override runs as `super`.
2653///
2654/// Every [`ModalRoute`] implementor gets these bodies, so an override on the leaf never reaches
2655/// them by accident.
2656pub trait ModalRouteBase: ModalRoute {
2657    /// Dart's `ModalRoute.buildModalBarrier`.
2658    fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2659        let _ = context;
2660        let barrier_color = ModalRoute::barrier_color(self, app);
2661        let dismissible = ModalRoute::barrier_dismissible(self, app);
2662        let semantics_label = ModalRoute::barrier_label(self, app);
2663        let semantics_dismissible = ModalRoute::semantics_dismissible(self, app);
2664        match barrier_color {
2665            Some(barrier_color) if barrier_color.a != 0.0 && !ModalRoute::offstage(self, app) => {
2666                // `changed_internal_state` is called if the barrier color or offstage updates.
2667                let transparent = barrier_color.with_values(Some(0.0), None, None, None, None);
2668                debug_assert!(barrier_color != transparent);
2669                let animation = TransitionRoute::animation(self, app)
2670                    .expect("an installed route keeps its animation")
2671                    .keep(app);
2672                let curve = ModalRoute::barrier_curve(self, app);
2673                let color_tween = ColorTween::new(app, Some(transparent), Some(barrier_color));
2674                let curve_tween = CurveTween::new(app, curve);
2675                let color = animation.drive(app, color_tween.chain(curve_tween));
2676                AnimatedModalBarrier::new(color)
2677                    .dismissible(dismissible)
2678                    .barrier_semantics_dismissible(semantics_dismissible)
2679                    .maybe_semantics_label(semantics_label)
2680                    .into_widget()
2681            }
2682            _ => ModalBarrier::new()
2683                .dismissible(dismissible)
2684                .barrier_semantics_dismissible(semantics_dismissible)
2685                .maybe_semantics_label(semantics_label)
2686                .into_widget(),
2687        }
2688    }
2689}
2690
2691impl<R: ModalRoute> ModalRouteBase for R {}
2692
2693/// The [`ModalRouteVTable`] slot for [`ModalRoute::build_flexible_transitions`].
2694type BuildFlexibleTransitionsSlot = fn(
2695    &mut App,
2696    HandleId,
2697    BuildContext,
2698    AnimationRef<f64>,
2699    AnimationRef<f64>,
2700    WidgetRef,
2701) -> WidgetRef;
2702
2703/// The vtable of an erased [`AnyModalRoute`]: one `&'static` table per route type, built by
2704/// [`ModalRouteVTable::of`].
2705struct ModalRouteVTable {
2706    type_name: fn() -> &'static str,
2707    route: fn(HandleId) -> AnyRoute,
2708    transition_route: fn(HandleId) -> AnyTransitionRoute,
2709    barrier_dismissible: fn(&App, HandleId) -> bool,
2710    barrier_color: fn(&App, HandleId) -> Option<Color>,
2711    barrier_label: fn(&App, HandleId) -> Option<String>,
2712    maintain_state: fn(&App, HandleId) -> bool,
2713    opaque: fn(&App, HandleId) -> bool,
2714    offstage: fn(&App, HandleId) -> bool,
2715    set_offstage: fn(&mut App, HandleId, bool),
2716    animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
2717    secondary_animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
2718    delegated_transition: fn(&App, HandleId) -> Option<DelegatedTransitionBuilder>,
2719    can_pop: fn(&mut App, HandleId) -> bool,
2720    implies_app_bar_dismissal: fn(&App, HandleId) -> bool,
2721    fullscreen_dialog: fn(&App, HandleId) -> bool,
2722    pop_gesture_in_progress: fn(&App, HandleId) -> bool,
2723    traversal_edge_behavior: fn(&App, HandleId) -> Option<TraversalEdgeBehavior>,
2724    directional_traversal_edge_behavior: fn(&App, HandleId) -> Option<TraversalEdgeBehavior>,
2725    storage_bucket: fn(&App, HandleId) -> Handle<PageStorageBucket>,
2726    subtree_key: fn(&App, HandleId) -> GlobalKey,
2727    subtree_context: fn(&mut App, HandleId) -> Option<BuildContext>,
2728    build_page:
2729        fn(&mut App, HandleId, BuildContext, AnimationRef<f64>, AnimationRef<f64>) -> WidgetRef,
2730    build_flexible_transitions: BuildFlexibleTransitionsSlot,
2731    add_local_history_entry: fn(&mut App, HandleId, Ref<LocalHistoryEntry>),
2732    remove_local_history_entry: fn(&mut App, HandleId, Handle<LocalHistoryEntry>),
2733    register_pop_entry: fn(&mut App, HandleId, Rc<dyn PopEntry>),
2734    unregister_pop_entry: fn(&mut App, HandleId, Rc<dyn PopEntry>),
2735}
2736
2737impl ModalRouteVTable {
2738    /// The table for one modal route type.
2739    const fn of<R: ModalRoute>() -> ModalRouteVTable {
2740        ModalRouteVTable {
2741            type_name: std::any::type_name::<R>,
2742            route: |id| Route::as_route(resolve::<R>(id)),
2743            transition_route: |id| TransitionRoute::as_transition_route(resolve::<R>(id)),
2744            barrier_dismissible: |app, id| R::barrier_dismissible(resolve(id), app),
2745            barrier_color: |app, id| R::barrier_color(resolve(id), app),
2746            barrier_label: |app, id| R::barrier_label(resolve(id), app),
2747            maintain_state: |app, id| R::maintain_state(resolve(id), app),
2748            opaque: |app, id| TransitionRoute::opaque(resolve::<R>(id), app),
2749            offstage: |app, id| R::offstage(resolve(id), app),
2750            set_offstage: |app, id, value| R::set_offstage(resolve(id), app, value),
2751            animation: |app, id| ModalRoute::animation(resolve::<R>(id), app),
2752            secondary_animation: |app, id| ModalRoute::secondary_animation(resolve::<R>(id), app),
2753            delegated_transition: |app, id| R::delegated_transition(resolve(id), app),
2754            can_pop: |app, id| R::can_pop(resolve(id), app),
2755            implies_app_bar_dismissal: |app, id| R::implies_app_bar_dismissal(resolve(id), app),
2756            fullscreen_dialog: |app, id| R::fullscreen_dialog(resolve(id), app),
2757            pop_gesture_in_progress: |app, id| R::pop_gesture_in_progress(resolve(id), app),
2758            traversal_edge_behavior: |app, id| {
2759                R::modal_route_data(resolve::<R>(id), app).traversal_edge_behavior
2760            },
2761            directional_traversal_edge_behavior: |app, id| {
2762                R::modal_route_data(resolve::<R>(id), app).directional_traversal_edge_behavior
2763            },
2764            storage_bucket: |app, id| {
2765                R::modal_route_data(resolve::<R>(id), app)
2766                    .storage_bucket
2767                    .handle()
2768            },
2769            subtree_key: |app, id| {
2770                R::modal_route_data(resolve::<R>(id), app)
2771                    .subtree_key
2772                    .clone()
2773            },
2774            subtree_context: |app, id| R::subtree_context(resolve::<R>(id), app),
2775            build_page: |app, id, context, animation, secondary| {
2776                R::build_page(resolve(id), app, context, animation, secondary)
2777            },
2778            build_flexible_transitions: |app, id, context, animation, secondary, child| {
2779                R::build_flexible_transitions(
2780                    resolve(id),
2781                    app,
2782                    context,
2783                    animation,
2784                    secondary,
2785                    child,
2786                )
2787            },
2788            add_local_history_entry: |app, id, entry| {
2789                LocalHistoryRoute::add_local_history_entry(resolve::<R>(id), app, entry)
2790            },
2791            remove_local_history_entry: |app, id, entry| {
2792                LocalHistoryRoute::remove_local_history_entry(resolve::<R>(id), app, entry)
2793            },
2794            register_pop_entry: |app, id, entry| R::register_pop_entry(resolve(id), app, entry),
2795            unregister_pop_entry: |app, id, entry| R::unregister_pop_entry(resolve(id), app, entry),
2796        }
2797    }
2798}
2799
2800/// Erased [`ModalRoute`]: what Dart's `ModalRoute.of(context)` returns and what
2801/// `route is ModalRoute<dynamic>` produces.
2802#[derive(Clone, Copy)]
2803pub struct AnyModalRoute {
2804    id: HandleId,
2805    vtable: &'static ModalRouteVTable,
2806}
2807
2808/// A kept route as a [`RouteRef`], through [`Retained::erase`]: Dart's upcast.
2809impl From<AnyModalRoute> for AnyRoute {
2810    fn from(route: AnyModalRoute) -> AnyRoute {
2811        route.as_route()
2812    }
2813}
2814
2815impl From<AnyModalRoute> for AnyTransitionRoute {
2816    fn from(route: AnyModalRoute) -> AnyTransitionRoute {
2817        route.as_transition_route()
2818    }
2819}
2820
2821/// A field Dart types as the erased object, kept: AnyModalRoute with its count.
2822pub type ModalRouteRef = Retained<AnyModalRoute>;
2823
2824waft_foundation::erased_handle!(AnyModalRoute: ModalRoute => ModalRoute::as_modal_route);
2825
2826impl Debug for AnyModalRoute {
2827    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2828        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
2829    }
2830}
2831
2832impl AnyModalRoute {
2833    /// The route's [`animation`](Self::animation) and
2834    /// [`secondary_animation`](Self::secondary_animation), kept, for the builders that take them.
2835    ///
2836    /// # Panics
2837    ///
2838    /// Before the route is installed.
2839    pub fn animations(self, app: &App) -> (AnimationRef<f64>, AnimationRef<f64>) {
2840        let kept = |animation: Option<AnyAnimation<f64>>| {
2841            animation
2842                .expect("an installed route keeps its animations")
2843                .keep(app)
2844        };
2845        (
2846            kept(self.animation(app)),
2847            kept(self.secondary_animation(app)),
2848        )
2849    }
2850
2851    /// Returns the modal route most closely associated with the given context.
2852    ///
2853    /// Returns `None` if the given context is not associated with a modal route.
2854    ///
2855    /// The given [`BuildContext`] will be rebuilt if the state of the route changes while it is
2856    /// visible (specifically, if [`AnyRoute::is_current`] or [`can_pop`](Self::can_pop) change
2857    /// value).
2858    ///
2859    /// Dart's `ModalRoute.of(context)`.
2860    pub fn of(app: &mut App, context: BuildContext) -> Option<AnyModalRoute> {
2861        AnyModalRoute::of_aspect(app, context, None)
2862    }
2863
2864    /// Dart's `ModalRoute._of`.
2865    fn of_aspect(
2866        app: &mut App,
2867        context: BuildContext,
2868        aspect: Option<ModalRouteAspect>,
2869    ) -> Option<AnyModalRoute> {
2870        ModalScopeStatus::inherit_from(app, context, aspect).map(|status| status.route.handle())
2871    }
2872
2873    /// Returns [`AnyRoute::is_current`] for the modal route most closely associated with the
2874    /// given context, creating a dependency on that aspect.
2875    pub fn is_current_of(app: &mut App, context: BuildContext) -> Option<bool> {
2876        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsCurrent))?;
2877        Some(route.as_route().is_current(app))
2878    }
2879
2880    /// Returns [`can_pop`](Self::can_pop) for the modal route most closely associated with the
2881    /// given context, creating a dependency on that aspect.
2882    pub fn can_pop_of(app: &mut App, context: BuildContext) -> Option<bool> {
2883        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::CanPop))?;
2884        Some(route.can_pop(app))
2885    }
2886
2887    /// Returns [`AnyRoute::settings`] for the modal route most closely associated with the
2888    /// given context, creating a dependency on that aspect.
2889    pub fn settings_of(app: &mut App, context: BuildContext) -> Option<RouteSettingsRef> {
2890        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::Settings))?;
2891        Some(route.as_route().settings(app))
2892    }
2893
2894    /// Returns [`AnyRoute::is_active`] for the modal route most closely associated with the
2895    /// given context, creating a dependency on that aspect.
2896    pub fn is_active_of(app: &mut App, context: BuildContext) -> Option<bool> {
2897        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsActive))?;
2898        Some(route.as_route().is_active(app))
2899    }
2900
2901    /// Returns [`AnyRoute::is_first`] for the modal route most closely associated with the
2902    /// given context, creating a dependency on that aspect.
2903    pub fn is_first_of(app: &mut App, context: BuildContext) -> Option<bool> {
2904        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsFirst))?;
2905        Some(route.as_route().is_first(app))
2906    }
2907
2908    /// Returns [`opaque`](Self::opaque) for the modal route most closely associated with the
2909    /// given context, creating a dependency on that aspect.
2910    pub fn opaque_of(app: &mut App, context: BuildContext) -> Option<bool> {
2911        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::Opaque))?;
2912        Some(route.opaque(app))
2913    }
2914
2915    /// Returns [`AnyRoute::pop_disposition`] for the modal route most closely associated with
2916    /// the given context, creating a dependency on that aspect.
2917    pub fn pop_disposition_of(app: &mut App, context: BuildContext) -> Option<RoutePopDisposition> {
2918        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::PopDisposition))?;
2919        Some(route.as_route().pop_disposition(app))
2920    }
2921
2922    /// Returns a predicate that is true if the route has the specified name and if popping the
2923    /// route will not yield the same route, i.e. if the route's
2924    /// [`Route::will_handle_pop_internally`] is false.
2925    ///
2926    /// This function is typically used with [`NavigatorState::pop_until`](crate::NavigatorState::pop_until).
2927    pub fn with_name(name: &str) -> RoutePredicate {
2928        let name = name.to_string();
2929        Rc::new(move |app, route: AnyRoute| {
2930            !route.will_handle_pop_internally(app)
2931                && route.as_modal_route(app).is_some()
2932                && route.settings(app).name() == Some(name.as_str())
2933        })
2934    }
2935
2936    /// This modal route as the erased [`AnyRoute`].
2937    pub fn as_route(self) -> AnyRoute {
2938        (self.vtable.route)(self.id)
2939    }
2940
2941    /// This modal route as the erased [`AnyTransitionRoute`].
2942    pub fn as_transition_route(self) -> AnyTransitionRoute {
2943        (self.vtable.transition_route)(self.id)
2944    }
2945
2946    /// See [`ModalRoute::barrier_dismissible`].
2947    pub fn barrier_dismissible(self, app: &App) -> bool {
2948        (self.vtable.barrier_dismissible)(app, self.id)
2949    }
2950
2951    /// See [`ModalRoute::barrier_color`].
2952    pub fn barrier_color(self, app: &App) -> Option<Color> {
2953        (self.vtable.barrier_color)(app, self.id)
2954    }
2955
2956    /// See [`ModalRoute::barrier_label`].
2957    pub fn barrier_label(self, app: &App) -> Option<String> {
2958        (self.vtable.barrier_label)(app, self.id)
2959    }
2960
2961    /// See [`ModalRoute::maintain_state`].
2962    pub fn maintain_state(self, app: &App) -> bool {
2963        (self.vtable.maintain_state)(app, self.id)
2964    }
2965
2966    /// See [`TransitionRoute::opaque`].
2967    pub fn opaque(self, app: &App) -> bool {
2968        (self.vtable.opaque)(app, self.id)
2969    }
2970
2971    /// See [`ModalRoute::offstage`].
2972    pub fn offstage(self, app: &App) -> bool {
2973        (self.vtable.offstage)(app, self.id)
2974    }
2975
2976    /// See [`ModalRoute::set_offstage`].
2977    pub fn set_offstage(self, app: &mut App, value: bool) {
2978        (self.vtable.set_offstage)(app, self.id, value)
2979    }
2980
2981    /// See [`ModalRoute::animation`].
2982    pub fn animation(self, app: &App) -> Option<AnyAnimation<f64>> {
2983        (self.vtable.animation)(app, self.id)
2984    }
2985
2986    /// See [`ModalRoute::secondary_animation`].
2987    pub fn secondary_animation(self, app: &App) -> Option<AnyAnimation<f64>> {
2988        (self.vtable.secondary_animation)(app, self.id)
2989    }
2990
2991    /// See [`ModalRoute::delegated_transition`].
2992    pub fn delegated_transition(self, app: &App) -> Option<DelegatedTransitionBuilder> {
2993        (self.vtable.delegated_transition)(app, self.id)
2994    }
2995
2996    /// See [`ModalRoute::can_pop`].
2997    pub fn can_pop(self, app: &mut App) -> bool {
2998        (self.vtable.can_pop)(app, self.id)
2999    }
3000
3001    /// See [`ModalRoute::implies_app_bar_dismissal`].
3002    pub fn implies_app_bar_dismissal(self, app: &App) -> bool {
3003        (self.vtable.implies_app_bar_dismissal)(app, self.id)
3004    }
3005
3006    /// See [`ModalRoute::fullscreen_dialog`].
3007    pub fn fullscreen_dialog(self, app: &App) -> bool {
3008        (self.vtable.fullscreen_dialog)(app, self.id)
3009    }
3010
3011    /// See [`ModalRoute::pop_gesture_in_progress`].
3012    pub fn pop_gesture_in_progress(self, app: &App) -> bool {
3013        (self.vtable.pop_gesture_in_progress)(app, self.id)
3014    }
3015
3016    /// See [`ModalRouteData::traversal_edge_behavior`].
3017    pub fn traversal_edge_behavior(self, app: &App) -> Option<TraversalEdgeBehavior> {
3018        (self.vtable.traversal_edge_behavior)(app, self.id)
3019    }
3020
3021    /// See [`ModalRouteData::directional_traversal_edge_behavior`].
3022    pub fn directional_traversal_edge_behavior(self, app: &App) -> Option<TraversalEdgeBehavior> {
3023        (self.vtable.directional_traversal_edge_behavior)(app, self.id)
3024    }
3025
3026    /// Dart's `ModalRoute._storageBucket`.
3027    pub fn storage_bucket(self, app: &App) -> Handle<PageStorageBucket> {
3028        (self.vtable.storage_bucket)(app, self.id)
3029    }
3030
3031    /// Dart's `ModalRoute._subtreeKey`.
3032    pub fn subtree_key(self, app: &App) -> GlobalKey {
3033        (self.vtable.subtree_key)(app, self.id)
3034    }
3035
3036    /// See [`ModalRoute::subtree_context`].
3037    pub fn subtree_context(self, app: &mut App) -> Option<BuildContext> {
3038        (self.vtable.subtree_context)(app, self.id)
3039    }
3040
3041    /// See [`ModalRoute::build_page`].
3042    pub fn build_page(
3043        self,
3044        app: &mut App,
3045        context: BuildContext,
3046        animation: AnimationRef<f64>,
3047        secondary_animation: AnimationRef<f64>,
3048    ) -> WidgetRef {
3049        (self.vtable.build_page)(app, self.id, context, animation, secondary_animation)
3050    }
3051
3052    /// See [`ModalRoute::build_flexible_transitions`].
3053    pub fn build_flexible_transitions(
3054        self,
3055        app: &mut App,
3056        context: BuildContext,
3057        animation: AnimationRef<f64>,
3058        secondary_animation: AnimationRef<f64>,
3059        child: WidgetRef,
3060    ) -> WidgetRef {
3061        (self.vtable.build_flexible_transitions)(
3062            app,
3063            self.id,
3064            context,
3065            animation,
3066            secondary_animation,
3067            child,
3068        )
3069    }
3070
3071    /// See [`LocalHistoryRoute::add_local_history_entry`].
3072    pub fn add_local_history_entry(self, app: &mut App, entry: Ref<LocalHistoryEntry>) {
3073        (self.vtable.add_local_history_entry)(app, self.id, entry)
3074    }
3075
3076    /// See [`LocalHistoryRoute::remove_local_history_entry`].
3077    pub fn remove_local_history_entry(self, app: &mut App, entry: Handle<LocalHistoryEntry>) {
3078        (self.vtable.remove_local_history_entry)(app, self.id, entry)
3079    }
3080
3081    /// See [`ModalRoute::register_pop_entry`].
3082    pub fn register_pop_entry(self, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
3083        (self.vtable.register_pop_entry)(app, self.id, pop_entry)
3084    }
3085
3086    /// See [`ModalRoute::unregister_pop_entry`].
3087    pub fn unregister_pop_entry(self, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
3088        (self.vtable.unregister_pop_entry)(app, self.id, pop_entry)
3089    }
3090}
3091
3092// ---------------------------------------------------------------------------------------------
3093// PopupRoute
3094
3095/// A modal route that overlays a widget over the current route.
3096///
3097/// See also:
3098///
3099///  * [`ModalRoute`], which is the base of this trait.
3100///  * [`NavigatorState::pop`](crate::NavigatorState::pop), which is used to dismiss the route.
3101pub trait PopupRoute: ModalRoute {
3102    /// Dart's `PopupRoute.opaque`.
3103    fn opaque(self: Handle<Self>, app: &App) -> bool {
3104        let _ = app;
3105        false
3106    }
3107
3108    /// Dart's `PopupRoute.maintainState`.
3109    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
3110        let _ = app;
3111        true
3112    }
3113
3114    /// Dart's `PopupRoute.allowSnapshotting`.
3115    fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
3116        let _ = app;
3117        false
3118    }
3119}
3120
3121// ---------------------------------------------------------------------------------------------
3122// The forwarders a modal-route leaf writes
3123
3124/// The `Route` overrides a [`ModalRoute`] leaf inherits, plus
3125/// [`route_accessors!`](crate::route_accessors). Write it inside `impl Route for MyRoute { .. }`.
3126#[macro_export]
3127macro_rules! modal_route_overrides {
3128    () => {
3129        $crate::route_accessors!();
3130
3131        fn as_transition_route(
3132            self: ::waft_foundation::Handle<Self>,
3133        ) -> ::std::option::Option<$crate::AnyTransitionRoute> {
3134            ::std::option::Option::Some($crate::TransitionRoute::as_transition_route(self))
3135        }
3136
3137        fn as_modal_route(
3138            self: ::waft_foundation::Handle<Self>,
3139        ) -> ::std::option::Option<$crate::AnyModalRoute> {
3140            ::std::option::Option::Some($crate::ModalRoute::as_modal_route(self))
3141        }
3142
3143        fn overlay_entries(
3144            self: ::waft_foundation::Handle<Self>,
3145            app: &::waft_foundation::App,
3146        ) -> ::std::vec::Vec<::waft_foundation::Handle<$crate::OverlayEntry>> {
3147            $crate::OverlayRoute::overlay_entries(self, app)
3148        }
3149
3150        fn install(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
3151            $crate::ModalRoute::install(self, app)
3152        }
3153
3154        fn did_push(
3155            self: ::waft_foundation::Handle<Self>,
3156            app: &mut ::waft_foundation::App,
3157        ) -> ::waft_scheduler::TickerFuture {
3158            $crate::ModalRoute::did_push(self, app)
3159        }
3160
3161        fn did_add(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
3162            $crate::ModalRoute::did_add(self, app)
3163        }
3164
3165        fn did_replace(
3166            self: ::waft_foundation::Handle<Self>,
3167            app: &mut ::waft_foundation::App,
3168            old_route: ::std::option::Option<$crate::AnyRoute>,
3169        ) {
3170            $crate::TransitionRoute::did_replace(self, app, old_route)
3171        }
3172
3173        fn will_pop(
3174            self: ::waft_foundation::Handle<Self>,
3175            app: &mut ::waft_foundation::App,
3176        ) -> $crate::RoutePopDisposition {
3177            $crate::LocalHistoryRoute::will_pop(self, app)
3178        }
3179
3180        fn pop_disposition(
3181            self: ::waft_foundation::Handle<Self>,
3182            app: &mut ::waft_foundation::App,
3183        ) -> $crate::RoutePopDisposition {
3184            $crate::ModalRoute::pop_disposition(self, app)
3185        }
3186
3187        fn on_pop_invoked_with_result(
3188            self: ::waft_foundation::Handle<Self>,
3189            app: &mut ::waft_foundation::App,
3190            did_pop: bool,
3191            result: $crate::RouteResult,
3192        ) {
3193            $crate::ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
3194        }
3195
3196        fn will_handle_pop_internally(
3197            self: ::waft_foundation::Handle<Self>,
3198            app: &::waft_foundation::App,
3199        ) -> bool {
3200            $crate::LocalHistoryRoute::will_handle_pop_internally(self, app)
3201        }
3202
3203        fn did_pop(
3204            self: ::waft_foundation::Handle<Self>,
3205            app: &mut ::waft_foundation::App,
3206            result: $crate::RouteResult,
3207        ) -> bool {
3208            $crate::LocalHistoryRoute::did_pop(self, app, result)
3209        }
3210
3211        fn did_pop_next(
3212            self: ::waft_foundation::Handle<Self>,
3213            app: &mut ::waft_foundation::App,
3214            next_route: $crate::AnyRoute,
3215        ) {
3216            $crate::ModalRoute::did_pop_next(self, app, next_route)
3217        }
3218
3219        fn did_change_next(
3220            self: ::waft_foundation::Handle<Self>,
3221            app: &mut ::waft_foundation::App,
3222            next_route: ::std::option::Option<$crate::AnyRoute>,
3223        ) {
3224            $crate::ModalRoute::did_change_next(self, app, next_route)
3225        }
3226
3227        fn did_change_previous(
3228            self: ::waft_foundation::Handle<Self>,
3229            app: &mut ::waft_foundation::App,
3230            previous_route: ::std::option::Option<$crate::AnyRoute>,
3231        ) {
3232            $crate::ModalRoute::did_change_previous(self, app, previous_route)
3233        }
3234
3235        fn changed_internal_state(
3236            self: ::waft_foundation::Handle<Self>,
3237            app: &mut ::waft_foundation::App,
3238        ) {
3239            $crate::ModalRoute::changed_internal_state(self, app)
3240        }
3241
3242        fn changed_external_state(
3243            self: ::waft_foundation::Handle<Self>,
3244            app: &mut ::waft_foundation::App,
3245        ) {
3246            $crate::ModalRoute::changed_external_state(self, app)
3247        }
3248
3249        fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
3250            $crate::TransitionRoute::dispose(self, app)
3251        }
3252    };
3253}
3254
3255/// The `OverlayRoute` overrides a [`ModalRoute`] leaf inherits, plus
3256/// [`overlay_route_accessors!`](crate::overlay_route_accessors). Write it inside
3257/// `impl OverlayRoute for MyRoute { .. }`.
3258#[macro_export]
3259macro_rules! modal_overlay_route_overrides {
3260    () => {
3261        $crate::overlay_route_accessors!();
3262
3263        fn create_overlay_entries(
3264            self: ::waft_foundation::Handle<Self>,
3265            app: &mut ::waft_foundation::App,
3266        ) -> ::std::vec::Vec<::waft_foundation::Ref<$crate::OverlayEntry>> {
3267            $crate::ModalRoute::create_overlay_entries(self, app)
3268        }
3269
3270        fn finished_when_popped(
3271            self: ::waft_foundation::Handle<Self>,
3272            app: &::waft_foundation::App,
3273        ) -> bool {
3274            $crate::TransitionRoute::finished_when_popped(self, app)
3275        }
3276    };
3277}
3278
3279/// The `PredictiveBackRoute` implementation a [`ModalRoute`] leaf inherits. Write it inside
3280/// `impl PredictiveBackRoute for MyRoute { .. }`.
3281#[macro_export]
3282macro_rules! modal_predictive_back_route_overrides {
3283    ($pop_gesture_enabled:path) => {
3284        fn pop_gesture_enabled(
3285            self: ::waft_foundation::Handle<Self>,
3286            app: &mut ::waft_foundation::App,
3287        ) -> bool {
3288            $pop_gesture_enabled(self, app)
3289        }
3290
3291        fn handle_start_back_gesture(
3292            self: ::waft_foundation::Handle<Self>,
3293            app: &mut ::waft_foundation::App,
3294            progress: f64,
3295        ) {
3296            $crate::TransitionRoute::handle_start_back_gesture(self, app, progress)
3297        }
3298
3299        fn handle_update_back_gesture_progress(
3300            self: ::waft_foundation::Handle<Self>,
3301            app: &mut ::waft_foundation::App,
3302            progress: f64,
3303        ) {
3304            $crate::TransitionRoute::handle_update_back_gesture_progress(self, app, progress)
3305        }
3306
3307        fn handle_commit_back_gesture(
3308            self: ::waft_foundation::Handle<Self>,
3309            app: &mut ::waft_foundation::App,
3310        ) {
3311            $crate::TransitionRoute::handle_commit_back_gesture(self, app)
3312        }
3313
3314        fn handle_cancel_back_gesture(
3315            self: ::waft_foundation::Handle<Self>,
3316            app: &mut ::waft_foundation::App,
3317        ) {
3318            $crate::TransitionRoute::handle_cancel_back_gesture(self, app)
3319        }
3320    };
3321}
3322
3323/// The `TransitionRoute` overrides a [`ModalRoute`] leaf inherits, plus
3324/// [`transition_route_accessors!`](crate::transition_route_accessors). Write it inside
3325/// `impl TransitionRoute for MyRoute { .. }`, next to the leaf's own `opaque`,
3326/// `transition_duration` and `allow_snapshotting`.
3327#[macro_export]
3328macro_rules! modal_transition_route_overrides {
3329    () => {
3330        $crate::transition_route_accessors!();
3331
3332        fn animation(
3333            self: ::waft_foundation::Handle<Self>,
3334            app: &::waft_foundation::App,
3335        ) -> ::std::option::Option<::waft_animation::AnyAnimation<f64>> {
3336            $crate::ModalRoute::animation(self, app)
3337        }
3338
3339        fn secondary_animation(
3340            self: ::waft_foundation::Handle<Self>,
3341            app: &::waft_foundation::App,
3342        ) -> ::std::option::Option<::waft_animation::AnyAnimation<f64>> {
3343            $crate::ModalRoute::secondary_animation(self, app)
3344        }
3345    };
3346}
3347
3348// ---------------------------------------------------------------------------------------------
3349// RouteObserver / RouteAware
3350
3351/// A [`Navigator`] observer that notifies [`RouteAware`]s of changes to the state of their
3352/// [`Route`].
3353///
3354/// [`RouteObserver`] informs subscribers whenever a route the `matches` predicate accepts is
3355/// pushed on top of their own matching route or popped from it. This is for example useful to
3356/// keep track of page transitions: a `RouteObserver` built with `AnyRoute::as_page_route` will
3357/// inform subscribed [`RouteAware`]s whenever the user navigates away from the current page
3358/// route to another page route.
3359///
3360/// See also:
3361///
3362///  * [`RouteAware`], which is used with [`RouteObserver`] to make a widget aware of changes to
3363///    the [`Navigator`]'s session history.
3364pub struct RouteObserver {
3365    navigator_observer: NavigatorObserverData,
3366    matches: RoutePredicate,
3367    listeners: Vec<(RouteRef, Vec<Rc<dyn RouteAware>>)>,
3368}
3369
3370impl RouteObserver {
3371    /// Creates an observer of the routes `matches` accepts; Dart's type argument `R`.
3372    pub fn new(app: &mut App, matches: RoutePredicate) -> Ref<RouteObserver> {
3373        app.create(RouteObserver {
3374            navigator_observer: NavigatorObserverData::new(),
3375            matches,
3376            listeners: Vec::new(),
3377        })
3378    }
3379
3380    /// Whether this observer is managing changes for the specified route.
3381    ///
3382    /// If debug assertions are disabled, this method always returns false.
3383    pub fn debug_observing_route(self: Handle<Self>, app: &App, route: AnyRoute) -> bool {
3384        let mut contained = false;
3385        if cfg!(debug_assertions) {
3386            contained = app
3387                .get(self)
3388                .listeners
3389                .iter()
3390                .any(|(held, _)| held == route);
3391        }
3392        contained
3393    }
3394
3395    /// Subscribes `route_aware` to be informed about changes to `route`.
3396    ///
3397    /// Going forward, `route_aware` will be informed about qualifying changes to `route`, e.g.
3398    /// when `route` is covered by another route or when `route` is popped off the [`Navigator`]
3399    /// stack.
3400    pub fn subscribe(
3401        self: Handle<Self>,
3402        app: &mut App,
3403        route_aware: Rc<dyn RouteAware>,
3404        route: AnyRoute,
3405    ) {
3406        let kept = route.keep(app);
3407        let listeners = &mut app.get_mut(self).listeners;
3408        let subscribers = match listeners.iter_mut().find(|(held, _)| held == route) {
3409            Some((_, subscribers)) => subscribers,
3410            None => {
3411                listeners.push((kept, Vec::new()));
3412                &mut listeners.last_mut().expect("just pushed").1
3413            }
3414        };
3415        if subscribers
3416            .iter()
3417            .any(|held| Rc::ptr_eq(held, &route_aware))
3418        {
3419            return;
3420        }
3421        subscribers.push(Rc::clone(&route_aware));
3422        route_aware.did_push(app);
3423    }
3424
3425    /// Unsubscribes `route_aware`.
3426    ///
3427    /// `route_aware` is no longer informed about changes to its route. If the given argument
3428    /// was subscribed to multiple routes, this unregisters it (once) from each.
3429    pub fn unsubscribe(self: Handle<Self>, app: &mut App, route_aware: Rc<dyn RouteAware>) {
3430        let listeners = &mut app.get_mut(self).listeners;
3431        for (_, subscribers) in listeners.iter_mut() {
3432            subscribers.retain(|held| !Rc::ptr_eq(held, &route_aware));
3433        }
3434        listeners.retain(|(_, subscribers)| !subscribers.is_empty());
3435    }
3436
3437    fn subscribers_of(
3438        self: Handle<Self>,
3439        app: &App,
3440        route: AnyRoute,
3441    ) -> Option<Vec<Rc<dyn RouteAware>>> {
3442        app.get(self)
3443            .listeners
3444            .iter()
3445            .find(|(held, _)| held == route)
3446            .map(|(_, subscribers)| subscribers.clone())
3447    }
3448
3449    fn matches(self: Handle<Self>, app: &mut App, route: Option<AnyRoute>) -> bool {
3450        let Some(route) = route else {
3451            return false;
3452        };
3453        let matches = Rc::clone(&app.get(self).matches);
3454        matches(app, route)
3455    }
3456}
3457
3458impl NavigatorObserver for RouteObserver {
3459    crate::navigator_observer_accessors!();
3460
3461    fn did_pop(
3462        self: Handle<Self>,
3463        app: &mut App,
3464        route: AnyRoute,
3465        previous_route: Option<AnyRoute>,
3466    ) {
3467        if !self.matches(app, Some(route)) || !self.matches(app, previous_route) {
3468            return;
3469        }
3470        let previous_route = previous_route.expect("matched above");
3471        if let Some(previous_subscribers) = self.subscribers_of(app, previous_route) {
3472            for route_aware in previous_subscribers {
3473                route_aware.did_pop_next(app);
3474            }
3475        }
3476        if let Some(subscribers) = self.subscribers_of(app, route) {
3477            for route_aware in subscribers {
3478                route_aware.did_pop(app);
3479            }
3480        }
3481    }
3482
3483    fn did_push(
3484        self: Handle<Self>,
3485        app: &mut App,
3486        route: AnyRoute,
3487        previous_route: Option<AnyRoute>,
3488    ) {
3489        if !self.matches(app, Some(route)) || !self.matches(app, previous_route) {
3490            return;
3491        }
3492        let previous_route = previous_route.expect("matched above");
3493        if let Some(previous_subscribers) = self.subscribers_of(app, previous_route) {
3494            for route_aware in previous_subscribers {
3495                route_aware.did_push_next(app);
3496            }
3497        }
3498    }
3499}
3500
3501/// An interface for objects that are aware of their current [`Route`].
3502///
3503/// This is used with [`RouteObserver`] to make a widget aware of changes to the [`Navigator`]'s
3504/// session history.
3505///
3506/// What Dart types as `RouteAware` becomes an `Rc<dyn RouteAware>`; an arena object implements
3507/// [`RouteAwareObject`], and `Rc::new(handle)` is its erased form. A [`RouteObserver`] compares
3508/// subscribers by identity, so a subscriber keeps the `Rc` it subscribed with to unsubscribe.
3509pub trait RouteAware {
3510    /// Called when the top route has been popped off, and the current route shows up.
3511    fn did_pop_next(&self, app: &mut App);
3512
3513    /// Called when the current route has been pushed.
3514    fn did_push(&self, app: &mut App);
3515
3516    /// Called when the current route has been popped off.
3517    fn did_pop(&self, app: &mut App);
3518
3519    /// Called when a new route has been pushed on top of this route, temporarily obscuring it.
3520    ///
3521    /// This method is called synchronously during the push operation, before the transition
3522    /// animation completes. The current route may still be partially visible as it animates
3523    /// out.
3524    fn did_push_next(&self, app: &mut App);
3525}
3526
3527/// The object side of [`RouteAware`]: an arena object a [`RouteObserver`] informs. Implementing
3528/// it makes `Handle<Self>` a [`RouteAware`]; Dart's empty default bodies are the defaults here.
3529pub trait RouteAwareObject: Sized + 'static {
3530    /// See [`RouteAware::did_pop_next`].
3531    fn did_pop_next(self: Handle<Self>, app: &mut App) {
3532        let _ = app;
3533    }
3534
3535    /// See [`RouteAware::did_push`].
3536    fn did_push(self: Handle<Self>, app: &mut App) {
3537        let _ = app;
3538    }
3539
3540    /// See [`RouteAware::did_pop`].
3541    fn did_pop(self: Handle<Self>, app: &mut App) {
3542        let _ = app;
3543    }
3544
3545    /// See [`RouteAware::did_push_next`].
3546    fn did_push_next(self: Handle<Self>, app: &mut App) {
3547        let _ = app;
3548    }
3549}
3550
3551impl<T: RouteAwareObject> RouteAware for Handle<T> {
3552    fn did_pop_next(&self, app: &mut App) {
3553        T::did_pop_next(*self, app);
3554    }
3555
3556    fn did_push(&self, app: &mut App) {
3557        T::did_push(*self, app);
3558    }
3559
3560    fn did_pop(&self, app: &mut App) {
3561        T::did_pop(*self, app);
3562    }
3563
3564    fn did_push_next(&self, app: &mut App) {
3565        T::did_push_next(*self, app);
3566    }
3567}
3568
3569// ---------------------------------------------------------------------------------------------
3570// RawDialogRoute and its callbacks
3571
3572/// Signature for the function that builds a route's primary contents.
3573///
3574/// Used in `PageRouteBuilder` and [`ShowGeneralDialog`].
3575///
3576/// See [`ModalRoute::build_page`] for the complete definition of the parameters.
3577pub type RoutePageBuilder =
3578    Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>, AnimationRef<f64>) -> WidgetRef>;
3579
3580/// Signature for the function that builds a route's transitions.
3581///
3582/// Used in `PageRouteBuilder` and [`ShowGeneralDialog`].
3583///
3584/// The `animation` argument drives this route's transition when it is pushed onto or popped off
3585/// the [`Navigator`]. The `secondary_animation` argument lets this route coordinate with the
3586/// transition of the route above it: when a new route is pushed on top of this one, this
3587/// route's `secondary_animation` runs from 0.0 to 1.0, and when that route is popped it runs
3588/// from 1.0 to 0.0.
3589///
3590/// A route only receives a running `secondary_animation` when this route's
3591/// [`TransitionRoute::can_transition_to`] and the next route's
3592/// [`TransitionRoute::can_transition_from`] both return true. Otherwise `secondary_animation`
3593/// remains `k_always_dismissed_animation`.
3594///
3595/// See [`ModalRoute::build_transitions`] for the complete definition of the parameters.
3596pub type RouteTransitionsBuilder = Rc<
3597    dyn Fn(&mut App, BuildContext, AnimationRef<f64>, AnimationRef<f64>, WidgetRef) -> WidgetRef,
3598>;
3599
3600/// Configuration details for a custom modal barrier.
3601///
3602/// Passed to a [`RouteBarrierBuilder`] by the routing framework to provide the ambient
3603/// variables associated with the route's modal barrier.
3604#[derive(Clone, Debug)]
3605pub struct RouteBarrierDetails {
3606    /// An animation that drives the route's transition.
3607    ///
3608    /// Typically used to animate the barrier's opacity from 0.0 to 1.0 when the route is
3609    /// pushed.
3610    pub animation: AnimationRef<f64>,
3611    /// The color to paint behind the route.
3612    ///
3613    /// If `None`, the barrier will be transparent.
3614    pub barrier_color: Option<Color>,
3615    /// The semantic label used for the barrier.
3616    pub barrier_label: Option<String>,
3617    /// Whether touching the barrier will pop the current route off the [`Navigator`].
3618    pub barrier_dismissible: bool,
3619}
3620
3621impl RouteBarrierDetails {
3622    /// Creates an object that contains the configuration for a modal barrier; Dart's optional
3623    /// arguments are the setters.
3624    pub fn new(animation: AnimationRef<f64>, barrier_dismissible: bool) -> RouteBarrierDetails {
3625        RouteBarrierDetails {
3626            animation,
3627            barrier_color: None,
3628            barrier_label: None,
3629            barrier_dismissible,
3630        }
3631    }
3632
3633    /// Dart `RouteBarrierDetails(barrierColor:)`.
3634    pub fn barrier_color(mut self, barrier_color: Color) -> RouteBarrierDetails {
3635        self.barrier_color = Some(barrier_color);
3636        self
3637    }
3638
3639    /// Dart `RouteBarrierDetails(barrierLabel:)`.
3640    pub fn barrier_label(mut self, barrier_label: String) -> RouteBarrierDetails {
3641        self.barrier_label = Some(barrier_label);
3642        self
3643    }
3644}
3645
3646/// Signature for the function that builds a custom modal barrier for a route.
3647///
3648/// Used by [`RawDialogRoute::barrier_builder`] and [`ShowGeneralDialog`] to wrap or replace
3649/// the default modal barrier.
3650///
3651/// The `barrier` parameter is the default [`ModalBarrier`] (or [`AnimatedModalBarrier`])
3652/// constructed by the framework. Custom builders should typically return a widget that wraps
3653/// this `barrier`, rather than replacing it entirely, to preserve the built-in semantics and
3654/// gestures.
3655pub type RouteBarrierBuilder =
3656    Rc<dyn Fn(&mut App, BuildContext, &RouteBarrierDetails, WidgetRef) -> WidgetRef>;
3657
3658/// A callback type for informing that a navigation pop has been invoked, whether or not it was
3659/// handled successfully.
3660///
3661/// Accepts a `did_pop` boolean indicating whether or not back navigation succeeded.
3662///
3663/// The `result` contains the pop result.
3664pub type PopInvokedWithResultCallback = Rc<dyn Fn(&mut App, bool, RouteResult)>;
3665
3666/// Allows listening to and preventing pops.
3667///
3668/// Can be registered in a [`ModalRoute`] to listen to pops with
3669/// [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result) or to enable and disable
3670/// them with [`can_pop_notifier`](Self::can_pop_notifier).
3671///
3672/// See also:
3673///
3674///  * `PopScope`, which provides similar functionality in a widget.
3675///  * [`ModalRoute::register_pop_entry`], which registers instances of this.
3676///  * [`ModalRoute::unregister_pop_entry`], which unregisters instances of this.
3677///
3678/// What Dart types as `PopEntry` becomes an `Rc<dyn PopEntry>`; an arena object implements
3679/// [`PopEntryObject`], and `Rc::new(handle)` is its erased form. A [`ModalRoute`] compares
3680/// entries by identity, so an entry keeps the `Rc` it registered to unregister it.
3681pub trait PopEntry {
3682    /// Called after a route pop was handled.
3683    fn on_pop_invoked_with_result(&self, app: &mut App, did_pop: bool, result: RouteResult);
3684
3685    /// When false, blocks the current route from being popped.
3686    fn can_pop_notifier(&self, app: &App) -> Rc<dyn ValueListenable<bool>>;
3687}
3688
3689/// The object side of [`PopEntry`]: an arena object a [`ModalRoute`] registers. Implementing it
3690/// makes `Handle<Self>` a [`PopEntry`].
3691pub trait PopEntryObject: Sized + 'static {
3692    /// See [`PopEntry::on_pop_invoked_with_result`].
3693    fn on_pop_invoked_with_result(
3694        self: Handle<Self>,
3695        app: &mut App,
3696        did_pop: bool,
3697        result: RouteResult,
3698    );
3699
3700    /// See [`PopEntry::can_pop_notifier`].
3701    fn can_pop_notifier(self: Handle<Self>, app: &App) -> Rc<dyn ValueListenable<bool>>;
3702}
3703
3704impl<T: PopEntryObject> PopEntry for Handle<T> {
3705    fn on_pop_invoked_with_result(&self, app: &mut App, did_pop: bool, result: RouteResult) {
3706        T::on_pop_invoked_with_result(*self, app, did_pop, result);
3707    }
3708
3709    fn can_pop_notifier(&self, app: &App) -> Rc<dyn ValueListenable<bool>> {
3710        T::can_pop_notifier(*self, app)
3711    }
3712}
3713
3714/// The fields of Dart's `RawDialogRoute`, which its subclasses carry.
3715pub struct RawDialogRouteData {
3716    /// Used to build the route's primary contents.
3717    pub page_builder: RoutePageBuilder,
3718    /// Whether touching the modal barrier pops the route; see
3719    /// [`ModalRoute::barrier_dismissible`].
3720    pub barrier_dismissible: bool,
3721    /// The semantic label of the modal barrier; see [`ModalRoute::barrier_label`].
3722    pub barrier_label: Option<String>,
3723    /// The color painted behind the dialog; see [`ModalRoute::barrier_color`].
3724    pub barrier_color: Option<Color>,
3725    /// How long the route takes to arrive on and leave off the screen; see
3726    /// [`TransitionRoute::transition_duration`].
3727    pub transition_duration: Duration,
3728    /// Used to define how the route arrives on and leaves off the screen.
3729    ///
3730    /// If `None`, the transition is a linear fade of the page's contents.
3731    pub transition_builder: Option<RouteTransitionsBuilder>,
3732    /// Used to define how the route's modal barrier is built.
3733    ///
3734    /// If not `None`, this builder is used to wrap or replace the default [`ModalBarrier`].
3735    pub barrier_builder: Option<RouteBarrierBuilder>,
3736    /// Whether this route is a full-screen dialog.
3737    ///
3738    /// In Material and Cupertino, being fullscreen has the effects of making the app bars have
3739    /// a close button instead of a back button.
3740    pub fullscreen_dialog: bool,
3741}
3742
3743impl RawDialogRouteData {
3744    /// The bag of a freshly created dialog route; Dart's constructor defaults.
3745    pub fn new(page_builder: RoutePageBuilder) -> RawDialogRouteData {
3746        RawDialogRouteData {
3747            page_builder,
3748            barrier_dismissible: true,
3749            barrier_label: None,
3750            barrier_color: Some(Color::new(0x8000_0000)),
3751            transition_duration: Duration::from_millis(200),
3752            transition_builder: None,
3753            barrier_builder: None,
3754            fullscreen_dialog: false,
3755        }
3756    }
3757}
3758
3759/// The accessors [`RawDialogRouteLeaf`] asks for, for a struct whose bag is the field
3760/// `raw_dialog_route`.
3761#[macro_export]
3762macro_rules! raw_dialog_route_accessors {
3763    () => {
3764        fn raw_dialog_route_data(
3765            self: ::waft_foundation::Handle<Self>,
3766            app: &::waft_foundation::App,
3767        ) -> &$crate::RawDialogRouteData {
3768            &app.get(self).raw_dialog_route
3769        }
3770
3771        fn raw_dialog_route_data_mut(
3772            self: ::waft_foundation::Handle<Self>,
3773            app: &mut ::waft_foundation::App,
3774        ) -> &mut $crate::RawDialogRouteData {
3775            &mut app.get_mut(self).raw_dialog_route
3776        }
3777    };
3778}
3779
3780/// A [`PopupRoute`] with the fields Dart's `RawDialogRoute` declares and the members it
3781/// overrides.
3782///
3783/// The shared bodies are associated functions on [`RawDialogRoute`]; an override calls one
3784/// where Dart writes `super.…`.
3785///
3786/// A leaf writes [`raw_dialog_route_modal_route_overrides!`](crate::raw_dialog_route_modal_route_overrides)
3787/// and [`raw_dialog_route_transition_route_overrides!`](crate::raw_dialog_route_transition_route_overrides)
3788/// to route the `ModalRoute` and `TransitionRoute` virtuals here.
3789pub trait RawDialogRouteLeaf: PopupRoute {
3790    /// Dart's `RawDialogRoute` fields, held under the field `raw_dialog_route`
3791    /// ([`raw_dialog_route_accessors!`](crate::raw_dialog_route_accessors)).
3792    fn raw_dialog_route_data(self: Handle<Self>, app: &App) -> &RawDialogRouteData;
3793
3794    /// See [`raw_dialog_route_data`](Self::raw_dialog_route_data).
3795    fn raw_dialog_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut RawDialogRouteData;
3796
3797    /// Dart's `RawDialogRoute.barrierDismissible`.
3798    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
3799        self.raw_dialog_route_data(app).barrier_dismissible
3800    }
3801
3802    /// Dart's `RawDialogRoute.barrierLabel`.
3803    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
3804        self.raw_dialog_route_data(app).barrier_label.clone()
3805    }
3806
3807    /// Dart's `RawDialogRoute.barrierColor`.
3808    fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color> {
3809        self.raw_dialog_route_data(app).barrier_color
3810    }
3811
3812    /// Dart's `RawDialogRoute.transitionDuration`.
3813    fn transition_duration(self: Handle<Self>, app: &App) -> Duration {
3814        self.raw_dialog_route_data(app).transition_duration
3815    }
3816
3817    /// Dart's `RawDialogRoute.fullscreenDialog`.
3818    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
3819        self.raw_dialog_route_data(app).fullscreen_dialog
3820    }
3821
3822    /// Dart's `RawDialogRoute.buildPage`.
3823    fn build_page(
3824        self: Handle<Self>,
3825        app: &mut App,
3826        context: BuildContext,
3827        animation: AnimationRef<f64>,
3828        secondary_animation: AnimationRef<f64>,
3829    ) -> WidgetRef {
3830        RawDialogRoute::build_page(self, app, context, animation, secondary_animation)
3831    }
3832
3833    /// Dart's `RawDialogRoute.buildTransitions`.
3834    fn build_transitions(
3835        self: Handle<Self>,
3836        app: &mut App,
3837        context: BuildContext,
3838        animation: AnimationRef<f64>,
3839        secondary_animation: AnimationRef<f64>,
3840        child: WidgetRef,
3841    ) -> WidgetRef {
3842        RawDialogRoute::build_transitions(self, app, context, animation, secondary_animation, child)
3843    }
3844
3845    /// Dart's `RawDialogRoute.buildModalBarrier`.
3846    fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3847        RawDialogRoute::build_modal_barrier(self, app, context)
3848    }
3849}
3850
3851/// The `ModalRoute` overrides a [`RawDialogRouteLeaf`] inherits, plus
3852/// [`modal_route_accessors!`](crate::modal_route_accessors). Write it inside
3853/// `impl ModalRoute for MyRoute { .. }`.
3854#[macro_export]
3855macro_rules! raw_dialog_route_modal_route_overrides {
3856    () => {
3857        $crate::modal_route_accessors!();
3858
3859        fn barrier_dismissible(
3860            self: ::waft_foundation::Handle<Self>,
3861            app: &::waft_foundation::App,
3862        ) -> bool {
3863            $crate::RawDialogRouteLeaf::barrier_dismissible(self, app)
3864        }
3865
3866        fn barrier_label(
3867            self: ::waft_foundation::Handle<Self>,
3868            app: &::waft_foundation::App,
3869        ) -> ::std::option::Option<::std::string::String> {
3870            $crate::RawDialogRouteLeaf::barrier_label(self, app)
3871        }
3872
3873        fn barrier_color(
3874            self: ::waft_foundation::Handle<Self>,
3875            app: &::waft_foundation::App,
3876        ) -> ::std::option::Option<::waft_painting::Color> {
3877            $crate::RawDialogRouteLeaf::barrier_color(self, app)
3878        }
3879
3880        fn maintain_state(
3881            self: ::waft_foundation::Handle<Self>,
3882            app: &::waft_foundation::App,
3883        ) -> bool {
3884            $crate::PopupRoute::maintain_state(self, app)
3885        }
3886
3887        fn fullscreen_dialog(
3888            self: ::waft_foundation::Handle<Self>,
3889            app: &::waft_foundation::App,
3890        ) -> bool {
3891            $crate::RawDialogRouteLeaf::fullscreen_dialog(self, app)
3892        }
3893
3894        fn build_page(
3895            self: ::waft_foundation::Handle<Self>,
3896            app: &mut ::waft_foundation::App,
3897            context: $crate::BuildContext,
3898            animation: ::waft_animation::AnimationRef<f64>,
3899            secondary_animation: ::waft_animation::AnimationRef<f64>,
3900        ) -> $crate::WidgetRef {
3901            $crate::RawDialogRouteLeaf::build_page(
3902                self,
3903                app,
3904                context,
3905                animation,
3906                secondary_animation,
3907            )
3908        }
3909
3910        fn build_transitions(
3911            self: ::waft_foundation::Handle<Self>,
3912            app: &mut ::waft_foundation::App,
3913            context: $crate::BuildContext,
3914            animation: ::waft_animation::AnimationRef<f64>,
3915            secondary_animation: ::waft_animation::AnimationRef<f64>,
3916            child: $crate::WidgetRef,
3917        ) -> $crate::WidgetRef {
3918            $crate::RawDialogRouteLeaf::build_transitions(
3919                self,
3920                app,
3921                context,
3922                animation,
3923                secondary_animation,
3924                child,
3925            )
3926        }
3927
3928        fn build_modal_barrier(
3929            self: ::waft_foundation::Handle<Self>,
3930            app: &mut ::waft_foundation::App,
3931            context: $crate::BuildContext,
3932        ) -> $crate::WidgetRef {
3933            $crate::RawDialogRouteLeaf::build_modal_barrier(self, app, context)
3934        }
3935    };
3936}
3937
3938/// The `TransitionRoute` overrides a [`RawDialogRouteLeaf`] inherits, plus
3939/// [`modal_transition_route_overrides!`](crate::modal_transition_route_overrides). Write it
3940/// inside `impl TransitionRoute for MyRoute { .. }`.
3941#[macro_export]
3942macro_rules! raw_dialog_route_transition_route_overrides {
3943    () => {
3944        $crate::modal_transition_route_overrides!();
3945
3946        fn transition_duration(
3947            self: ::waft_foundation::Handle<Self>,
3948            app: &mut ::waft_foundation::App,
3949        ) -> ::std::time::Duration {
3950            $crate::RawDialogRouteLeaf::transition_duration(self, app)
3951        }
3952
3953        fn opaque(self: ::waft_foundation::Handle<Self>, app: &::waft_foundation::App) -> bool {
3954            $crate::PopupRoute::opaque(self, app)
3955        }
3956
3957        fn allow_snapshotting(
3958            self: ::waft_foundation::Handle<Self>,
3959            app: &::waft_foundation::App,
3960        ) -> bool {
3961            $crate::PopupRoute::allow_snapshotting(self, app)
3962        }
3963    };
3964}
3965
3966/// A general dialog route which allows for customization of the dialog popup.
3967///
3968/// It is used internally by [`ShowGeneralDialog`] or can be directly pushed onto the
3969/// [`Navigator`] stack to enable state restoration.
3970///
3971/// This route takes a [`page_builder`](RawDialogRouteData::page_builder), which typically
3972/// builds a dialog. Content below the dialog is dimmed with a [`ModalBarrier`].
3973///
3974/// It is also the base class `CupertinoDialogRoute` extends: its fields are the
3975/// [`RawDialogRouteData`] bag, the members it overrides are [`RawDialogRouteLeaf`]'s, and the
3976/// shared bodies are the associated functions below.
3977pub struct RawDialogRoute {
3978    route: crate::widgets::navigator::RouteData,
3979    overlay_route: OverlayRouteData,
3980    transition_route: TransitionRouteData,
3981    local_history: LocalHistoryRouteData,
3982    modal_route: ModalRouteData,
3983    raw_dialog_route: RawDialogRouteData,
3984}
3985
3986impl RawDialogRoute {
3987    /// A general dialog route which allows for customization of the dialog popup; Dart's
3988    /// optional arguments are the setters.
3989    ///
3990    /// Dart's defaults: `barrier_dismissible` true, `barrier_color` `0x80000000`,
3991    /// `transition_duration` 200 ms, `fullscreen_dialog` false.
3992    pub fn new(app: &mut App, page_builder: RoutePageBuilder) -> Ref<RawDialogRoute> {
3993        let route = crate::widgets::navigator::RouteData::new(app, None, None);
3994        let transition_route = TransitionRouteData::new(app);
3995        let modal_route = ModalRouteData::new(app);
3996        app.create(RawDialogRoute {
3997            route,
3998            overlay_route: OverlayRouteData::new(),
3999            transition_route,
4000            local_history: LocalHistoryRouteData::new(),
4001            modal_route,
4002            raw_dialog_route: RawDialogRouteData::new(page_builder),
4003        })
4004    }
4005
4006    /// Dart `RawDialogRoute(settings:)`.
4007    pub fn settings(self: Ref<Self>, app: &mut App, settings: RouteSettingsRef) -> Ref<Self> {
4008        self.route_data_mut(app).set_settings(settings);
4009        self
4010    }
4011
4012    /// Dart `RawDialogRoute(requestFocus:)`.
4013    pub fn request_focus(self: Ref<Self>, app: &mut App, request_focus: bool) -> Ref<Self> {
4014        self.route_data_mut(app)
4015            .set_request_focus(Some(request_focus));
4016        self
4017    }
4018
4019    /// Dart `RawDialogRoute(barrierDismissible:)`.
4020    pub fn barrier_dismissible(
4021        self: Ref<Self>,
4022        app: &mut App,
4023        barrier_dismissible: bool,
4024    ) -> Ref<Self> {
4025        self.raw_dialog_route_data_mut(app).barrier_dismissible = barrier_dismissible;
4026        self
4027    }
4028
4029    /// Dart `RawDialogRoute(barrierColor:)`.
4030    pub fn barrier_color(
4031        self: Ref<Self>,
4032        app: &mut App,
4033        barrier_color: Option<Color>,
4034    ) -> Ref<Self> {
4035        self.raw_dialog_route_data_mut(app).barrier_color = barrier_color;
4036        self
4037    }
4038
4039    /// Dart `RawDialogRoute(barrierLabel:)`.
4040    pub fn barrier_label(self: Ref<Self>, app: &mut App, barrier_label: String) -> Ref<Self> {
4041        self.raw_dialog_route_data_mut(app).barrier_label = Some(barrier_label);
4042        self
4043    }
4044
4045    /// Dart `RawDialogRoute(transitionDuration:)`.
4046    pub fn transition_duration(
4047        self: Ref<Self>,
4048        app: &mut App,
4049        transition_duration: Duration,
4050    ) -> Ref<Self> {
4051        self.raw_dialog_route_data_mut(app).transition_duration = transition_duration;
4052        self
4053    }
4054
4055    /// Dart `RawDialogRoute(transitionBuilder:)`.
4056    pub fn transition_builder(
4057        self: Ref<Self>,
4058        app: &mut App,
4059        transition_builder: RouteTransitionsBuilder,
4060    ) -> Ref<Self> {
4061        self.raw_dialog_route_data_mut(app).transition_builder = Some(transition_builder);
4062        self
4063    }
4064
4065    /// Dart `RawDialogRoute(barrierBuilder:)`.
4066    pub fn barrier_builder(
4067        self: Ref<Self>,
4068        app: &mut App,
4069        barrier_builder: RouteBarrierBuilder,
4070    ) -> Ref<Self> {
4071        self.raw_dialog_route_data_mut(app).barrier_builder = Some(barrier_builder);
4072        self
4073    }
4074
4075    /// Dart `RawDialogRoute(traversalEdgeBehavior:)`.
4076    pub fn traversal_edge_behavior(
4077        self: Ref<Self>,
4078        app: &mut App,
4079        behavior: TraversalEdgeBehavior,
4080    ) -> Ref<Self> {
4081        self.modal_route_data_mut(app).traversal_edge_behavior = Some(behavior);
4082        self
4083    }
4084
4085    /// Dart `RawDialogRoute(directionalTraversalEdgeBehavior:)`.
4086    pub fn directional_traversal_edge_behavior(
4087        self: Ref<Self>,
4088        app: &mut App,
4089        behavior: TraversalEdgeBehavior,
4090    ) -> Ref<Self> {
4091        self.modal_route_data_mut(app)
4092            .directional_traversal_edge_behavior = Some(behavior);
4093        self
4094    }
4095
4096    /// Dart `RawDialogRoute(fullscreenDialog:)`.
4097    pub fn fullscreen_dialog(self: Ref<Self>, app: &mut App, fullscreen_dialog: bool) -> Ref<Self> {
4098        self.raw_dialog_route_data_mut(app).fullscreen_dialog = fullscreen_dialog;
4099        self
4100    }
4101
4102    /// Dart's `RawDialogRoute.buildPage`, which a leaf's
4103    /// [`RawDialogRouteLeaf::build_page`] calls.
4104    pub fn build_page<R: RawDialogRouteLeaf>(
4105        this: Handle<R>,
4106        app: &mut App,
4107        context: BuildContext,
4108        animation: AnimationRef<f64>,
4109        secondary_animation: AnimationRef<f64>,
4110    ) -> WidgetRef {
4111        let page_builder = Rc::clone(&this.raw_dialog_route_data(app).page_builder);
4112        Semantics::new()
4113            .scopes_route(true)
4114            .explicit_child_nodes(true)
4115            .child(page_builder(app, context, animation, secondary_animation))
4116            .into_widget()
4117    }
4118
4119    /// Dart's `RawDialogRoute.buildTransitions`, which a leaf's
4120    /// [`RawDialogRouteLeaf::build_transitions`] calls.
4121    pub fn build_transitions<R: RawDialogRouteLeaf>(
4122        this: Handle<R>,
4123        app: &mut App,
4124        context: BuildContext,
4125        animation: AnimationRef<f64>,
4126        secondary_animation: AnimationRef<f64>,
4127        child: WidgetRef,
4128    ) -> WidgetRef {
4129        match this.raw_dialog_route_data(app).transition_builder.clone() {
4130            // Some default transition.
4131            None => crate::widgets::transitions::FadeTransition::new(animation)
4132                .child(child)
4133                .into_widget(),
4134            Some(transition_builder) => {
4135                transition_builder(app, context, animation, secondary_animation, child)
4136            }
4137        }
4138    }
4139
4140    /// Dart's `RawDialogRoute.buildModalBarrier`, which a leaf's
4141    /// [`RawDialogRouteLeaf::build_modal_barrier`] calls.
4142    pub fn build_modal_barrier<R: RawDialogRouteLeaf>(
4143        this: Handle<R>,
4144        app: &mut App,
4145        context: BuildContext,
4146    ) -> WidgetRef {
4147        let barrier = ModalRouteBase::build_modal_barrier(this, app, context);
4148        let Some(barrier_builder) = this.raw_dialog_route_data(app).barrier_builder.clone() else {
4149            return barrier;
4150        };
4151        Builder::new(move |app, context| {
4152            let animation = TransitionRoute::animation(this, app)
4153                .expect("an installed route keeps its animation")
4154                .keep(app);
4155            let mut details =
4156                RouteBarrierDetails::new(animation, ModalRoute::barrier_dismissible(this, app));
4157            if let Some(color) = ModalRoute::barrier_color(this, app) {
4158                details = details.barrier_color(color);
4159            }
4160            if let Some(label) = ModalRoute::barrier_label(this, app) {
4161                details = details.barrier_label(label);
4162            }
4163            barrier_builder(app, context, &details, barrier.clone())
4164        })
4165        .into_widget()
4166    }
4167}
4168
4169impl Route for RawDialogRoute {
4170    crate::modal_route_overrides!();
4171}
4172
4173impl OverlayRoute for RawDialogRoute {
4174    crate::modal_overlay_route_overrides!();
4175}
4176
4177impl PredictiveBackRoute for RawDialogRoute {
4178    crate::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
4179}
4180
4181impl TransitionRoute for RawDialogRoute {
4182    crate::raw_dialog_route_transition_route_overrides!();
4183}
4184
4185impl LocalHistoryRoute for RawDialogRoute {
4186    crate::local_history_route_accessors!();
4187}
4188
4189impl ModalRoute for RawDialogRoute {
4190    crate::raw_dialog_route_modal_route_overrides!();
4191}
4192
4193impl PopupRoute for RawDialogRoute {}
4194
4195impl RawDialogRouteLeaf for RawDialogRoute {
4196    crate::raw_dialog_route_accessors!();
4197}
4198
4199/// Displays a dialog above the current contents of the app.
4200///
4201/// This function allows for customization of aspects of the dialog popup.
4202///
4203/// The `context` argument is used to look up the [`Navigator`] for the dialog. It is only used
4204/// when the method is called. Its corresponding widget can be safely removed from the tree
4205/// before the dialog is closed.
4206///
4207/// The `use_root_navigator` argument is used to determine whether to push the dialog to the
4208/// [`Navigator`] furthest from or nearest to the given `context`.
4209///
4210/// Returns a future that resolves to the value (if any) that was passed to [`Navigator::pop`]
4211/// when the dialog was closed.
4212///
4213/// See also:
4214///
4215///  * [`RawDialogRoute`], the route this pushes.
4216pub struct ShowGeneralDialog {
4217    page_builder: RoutePageBuilder,
4218    barrier_dismissible: bool,
4219    barrier_label: Option<String>,
4220    barrier_color: Color,
4221    transition_duration: Duration,
4222    transition_builder: Option<RouteTransitionsBuilder>,
4223    barrier_builder: Option<RouteBarrierBuilder>,
4224    use_root_navigator: bool,
4225    fullscreen_dialog: bool,
4226    route_settings: Option<RouteSettingsRef>,
4227    request_focus: Option<bool>,
4228}
4229
4230impl ShowGeneralDialog {
4231    /// Creates a builder for a general dialog; Dart's `showGeneralDialog` required argument is
4232    /// the page builder, and every other argument is a setter.
4233    pub fn new(page_builder: RoutePageBuilder) -> ShowGeneralDialog {
4234        ShowGeneralDialog {
4235            page_builder,
4236            barrier_dismissible: false,
4237            barrier_label: None,
4238            barrier_color: Color::new(0x8000_0000),
4239            transition_duration: Duration::from_millis(200),
4240            transition_builder: None,
4241            barrier_builder: None,
4242            use_root_navigator: true,
4243            fullscreen_dialog: false,
4244            route_settings: None,
4245            request_focus: None,
4246        }
4247    }
4248
4249    /// Whether tapping the barrier dismisses the dialog. Defaults to `false`.
4250    pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowGeneralDialog {
4251        self.barrier_dismissible = barrier_dismissible;
4252        self
4253    }
4254
4255    /// The semantic label of the dialog's modal barrier.
4256    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowGeneralDialog {
4257        self.barrier_label = Some(barrier_label.into());
4258        self
4259    }
4260
4261    /// The color of the dialog's modal barrier.
4262    pub fn barrier_color(mut self, barrier_color: Color) -> ShowGeneralDialog {
4263        self.barrier_color = barrier_color;
4264        self
4265    }
4266
4267    /// The duration of the dialog's transition.
4268    pub fn transition_duration(mut self, transition_duration: Duration) -> ShowGeneralDialog {
4269        self.transition_duration = transition_duration;
4270        self
4271    }
4272
4273    /// Builds the dialog's transition.
4274    pub fn transition_builder(
4275        mut self,
4276        transition_builder: RouteTransitionsBuilder,
4277    ) -> ShowGeneralDialog {
4278        self.transition_builder = Some(transition_builder);
4279        self
4280    }
4281
4282    /// Builds the dialog's barrier.
4283    pub fn barrier_builder(mut self, barrier_builder: RouteBarrierBuilder) -> ShowGeneralDialog {
4284        self.barrier_builder = Some(barrier_builder);
4285        self
4286    }
4287
4288    /// Whether to push the dialog to the root navigator. Defaults to `true`.
4289    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowGeneralDialog {
4290        self.use_root_navigator = use_root_navigator;
4291        self
4292    }
4293
4294    /// Whether this is a fullscreen dialog. Defaults to `false`.
4295    pub fn fullscreen_dialog(mut self, fullscreen_dialog: bool) -> ShowGeneralDialog {
4296        self.fullscreen_dialog = fullscreen_dialog;
4297        self
4298    }
4299
4300    /// The route settings passed to the dialog's route.
4301    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowGeneralDialog {
4302        self.route_settings = Some(route_settings);
4303        self
4304    }
4305
4306    /// Whether the dialog's route requests focus when it is pushed.
4307    pub fn request_focus(mut self, request_focus: bool) -> ShowGeneralDialog {
4308        self.request_focus = Some(request_focus);
4309        self
4310    }
4311
4312    /// Displays the dialog and returns a future that resolves when it closes.
4313    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
4314        let ShowGeneralDialog {
4315            page_builder,
4316            barrier_dismissible,
4317            barrier_label,
4318            barrier_color,
4319            transition_duration,
4320            transition_builder,
4321            barrier_builder,
4322            use_root_navigator,
4323            fullscreen_dialog,
4324            route_settings,
4325            request_focus,
4326        } = self;
4327
4328        debug_assert!(!barrier_dismissible || barrier_label.is_some());
4329        let mut route = RawDialogRoute::new(app, page_builder)
4330            .barrier_dismissible(app, barrier_dismissible)
4331            .barrier_color(app, Some(barrier_color))
4332            .transition_duration(app, transition_duration)
4333            .fullscreen_dialog(app, fullscreen_dialog);
4334        if let Some(barrier_label) = barrier_label {
4335            route = route.barrier_label(app, barrier_label);
4336        }
4337        if let Some(transition_builder) = transition_builder {
4338            route = route.transition_builder(app, transition_builder);
4339        }
4340        if let Some(barrier_builder) = barrier_builder {
4341            route = route.barrier_builder(app, barrier_builder);
4342        }
4343        if let Some(route_settings) = route_settings {
4344            route = route.settings(app, route_settings);
4345        }
4346        if let Some(request_focus) = request_focus {
4347            route = route.request_focus(app, request_focus);
4348        }
4349        let navigator = Navigator::of(app, context, use_root_navigator);
4350        navigator.push(app, route.into_erased())
4351    }
4352}
4353
4354#[cfg(test)]
4355mod tests {
4356    use std::cell::{Cell, RefCell};
4357
4358    use waft_embedder::{Offset, TextDirection};
4359    use waft_painting::AlignmentGeometry;
4360
4361    use super::*;
4362    use crate::framework::{IntoWidget, StatelessWidget};
4363    use crate::testing::{WidgetTester, test_widgets};
4364    use crate::widgets::basic::{Align, Directionality, SizedBox};
4365    use crate::widgets::navigator::{NavigatorState, RouteSettings};
4366    use crate::widgets::pages::PageRouteBuilder;
4367    use crate::widgets::pop_scope::PopScope;
4368
4369    /// A page whose content is a 10x10 box in the top-left corner, so a tap in the middle of
4370    /// the view falls through to whatever is below it.
4371    fn corner_page(child: Option<WidgetRef>) -> RoutePageBuilder {
4372        Rc::new(move |_app, _context, _animation, _secondary| {
4373            let box_widget = match child.clone() {
4374                Some(child) => SizedBox::new().width(10.0).height(10.0).child(child),
4375                None => SizedBox::new().width(10.0).height(10.0),
4376            };
4377            Align::new()
4378                .alignment(AlignmentGeometry::TOP_LEFT)
4379                .child(box_widget)
4380                .into_widget()
4381        })
4382    }
4383
4384    fn page_route(app: &mut App, child: Option<WidgetRef>, name: &str) -> Ref<PageRouteBuilder> {
4385        PageRouteBuilder::new(app, corner_page(child))
4386            .settings(app, RouteSettings::new().name(name.to_string()).into())
4387    }
4388
4389    /// A navigator whose initial route is a plain page, under a `Directionality` the overlay's
4390    /// theater needs.
4391    fn navigator(
4392        key: &GlobalKey,
4393        on_generate_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
4394    ) -> WidgetRef {
4395        Directionality::new(
4396            TextDirection::Ltr,
4397            Navigator::new()
4398                .key(key.clone().into())
4399                .on_generate_route(on_generate_route),
4400        )
4401        .into_widget()
4402    }
4403
4404    fn state(key: &GlobalKey, tester: &WidgetTester) -> Handle<NavigatorState> {
4405        key.current_state::<NavigatorState>(&tester.cell.borrow())
4406            .expect("a mounted navigator")
4407    }
4408
4409    /// A navigator whose initial route is a plain page named "/", pumped and settled.
4410    fn mount_navigator(tester: &mut WidgetTester, key: &GlobalKey) -> Handle<NavigatorState> {
4411        tester.pump_widget(navigator(key, |app, _settings| {
4412            Some(page_route(app, None, "/").into_erased())
4413        }));
4414        let navigator_state = state(key, tester);
4415        tester.pump_and_settle();
4416        navigator_state
4417    }
4418
4419    /// A stateless widget that runs `read` on every build.
4420    type ProbeRead = Rc<dyn Fn(&mut App, BuildContext)>;
4421
4422    struct Probe {
4423        read: ProbeRead,
4424    }
4425
4426    impl Debug for Probe {
4427        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4428            f.write_str("Probe")
4429        }
4430    }
4431
4432    impl StatelessWidget for Probe {
4433        fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
4434            (self.read)(app, context);
4435            SizedBox::new().into_widget()
4436        }
4437    }
4438
4439    fn probe(read: impl Fn(&mut App, BuildContext) + 'static) -> WidgetRef {
4440        Probe {
4441            read: Rc::new(read),
4442        }
4443        .into_widget()
4444    }
4445
4446    // ---- the tests ----
4447
4448    #[test]
4449    fn pushing_a_page_route_runs_its_transition_to_completion_and_popping_runs_it_back() {
4450        test_widgets(|tester| {
4451            let key = GlobalKey::new();
4452            let navigator_state = mount_navigator(tester, &key);
4453
4454            let pushed: RouteRef =
4455                tester.update(|app| page_route(app, None, "second").into_erased());
4456            tester.update(|app| navigator_state.push(app, pushed.clone()));
4457            tester.pump();
4458            let animation = {
4459                let app = tester.cell.borrow();
4460                let animation = pushed
4461                    .as_transition_route(&app)
4462                    .expect("a page route is a transition route")
4463                    .animation(&app)
4464                    .expect("an installed route");
4465                assert!(animation.value(&app) < 1.0, "the transition starts at 0");
4466                animation
4467            };
4468
4469            tester.pump_and_settle();
4470            {
4471                let app = tester.cell.borrow();
4472                assert_eq!(animation.value(&app), 1.0);
4473                assert!(pushed.is_current(&app));
4474                assert!(!pushed.is_first(&app));
4475            }
4476
4477            let popped = Rc::new(Cell::new(false));
4478            tester.update(|app| {
4479                pushed.popped(app).then(app, {
4480                    let popped = Rc::clone(&popped);
4481                    move |_app, _result| popped.set(true)
4482                });
4483                navigator_state.pop(app, None);
4484                app.drain_microtasks();
4485            });
4486            assert!(popped.get(), "the popped future resolves at once");
4487
4488            tester.pump_and_settle();
4489            assert_eq!(animation.value(&tester.cell.borrow()), 0.0);
4490        });
4491    }
4492
4493    #[test]
4494    fn modal_route_of_reports_is_current_and_is_first() {
4495        test_widgets(|tester| {
4496            let key = GlobalKey::new();
4497            let seen: Rc<RefCell<Vec<(bool, bool)>>> = Rc::new(RefCell::new(Vec::new()));
4498            let watcher = probe({
4499                let seen = Rc::clone(&seen);
4500                move |app, context| {
4501                    let route = AnyModalRoute::of(app, context).expect("a modal route");
4502                    let is_current = route.as_route().is_current(app);
4503                    let is_first = route.as_route().is_first(app);
4504                    seen.borrow_mut().push((is_current, is_first));
4505                }
4506            });
4507            tester.pump_widget(navigator(&key, move |app, _settings| {
4508                Some(page_route(app, Some(watcher.clone()), "/").into_erased())
4509            }));
4510            let navigator_state = state(&key, tester);
4511            tester.pump_and_settle();
4512            assert_eq!(seen.borrow().last().copied(), Some((true, true)));
4513
4514            tester.update(|app| {
4515                let second: RouteRef = page_route(app, None, "second").into_erased();
4516                navigator_state.push(app, second);
4517            });
4518            tester.pump_and_settle();
4519            assert_eq!(
4520                seen.borrow().last().copied(),
4521                Some((false, true)),
4522                "the first route is no longer current once another is pushed"
4523            );
4524        });
4525    }
4526
4527    #[test]
4528    fn a_pop_scope_with_can_pop_false_blocks_maybe_pop() {
4529        test_widgets(|tester| {
4530            let key = GlobalKey::new();
4531            let blocked = Rc::new(Cell::new(false));
4532            let scope = PopScope::new(SizedBox::new())
4533                .can_pop(false)
4534                .on_pop_invoked_with_result({
4535                    let blocked = Rc::clone(&blocked);
4536                    Rc::new(move |_app, did_pop, _result| blocked.set(!did_pop))
4537                })
4538                .into_widget();
4539            let navigator_state = mount_navigator(tester, &key);
4540
4541            let second: RouteRef =
4542                tester.update(|app| page_route(app, Some(scope), "second").into_erased());
4543            tester.update(|app| navigator_state.push(app, second.clone()));
4544            tester.pump_and_settle();
4545            assert!(second.is_current(&tester.cell.borrow()));
4546
4547            assert!(
4548                tester.update(|app| navigator_state.maybe_pop(app, None)),
4549                "the pop is handled — by being refused — rather than bubbling"
4550            );
4551            tester.pump_and_settle();
4552            assert!(
4553                second.is_current(&tester.cell.borrow()),
4554                "the route is still on top"
4555            );
4556            assert!(blocked.get(), "the pop was reported as not having happened");
4557        });
4558    }
4559
4560    #[test]
4561    fn tapping_the_barrier_dismisses_a_dismissible_popup_route() {
4562        test_widgets(|tester| {
4563            let key = GlobalKey::new();
4564            let navigator_state = mount_navigator(tester, &key);
4565
4566            let dialog: RouteRef = tester.update(|app| {
4567                RawDialogRoute::new(app, corner_page(None))
4568                    .barrier_dismissible(app, true)
4569                    .barrier_label(app, "dismiss".to_string())
4570                    .into_erased()
4571            });
4572            tester.update(|app| navigator_state.push(app, dialog.clone()));
4573            tester.pump_and_settle();
4574            assert!(dialog.is_current(&tester.cell.borrow()));
4575
4576            // The dialog's own content is the 10x10 box in the corner, so a tap away from it
4577            // is on the barrier.
4578            tester.tap_at(Offset::new(150.0, 100.0), 1);
4579            tester.pump();
4580            tester.pump_and_settle();
4581            assert!(
4582                !dialog.is_active(&tester.cell.borrow()),
4583                "the barrier popped the dialog"
4584            );
4585        });
4586    }
4587
4588    /// Not a Dart case: Dart's collector frees the tweens and the colour animation each build
4589    /// of a modal barrier replaces; here the route keeps the last ones and frees what they
4590    /// replace.
4591    #[test]
4592    fn rebuilding_a_coloured_barrier_leaves_no_new_arena_objects() {
4593        test_widgets(|tester| {
4594            let key = GlobalKey::new();
4595            let navigator_state = mount_navigator(tester, &key);
4596            let dialog = tester.update(|app| {
4597                RawDialogRoute::new(app, corner_page(None))
4598                    .barrier_color(app, Some(Color::new(0x80000000)))
4599            });
4600            tester.update(|app| navigator_state.push(app, dialog.clone().into_erased()));
4601            tester.pump_and_settle();
4602            tester.assert_leaves_nothing_behind(|tester| {
4603                tester.update(|app| ModalRoute::changed_internal_state(dialog.handle(), app));
4604                tester.pump_by(Duration::from_millis(20));
4605            });
4606        });
4607    }
4608
4609    /// Not a Dart case: Dart's collector frees a popped route, and what its barrier drove, once
4610    /// nothing reaches it; here the checkpoint after its entry goes frees it.
4611    #[test]
4612    fn a_popped_route_is_freed_once_its_entry_goes() {
4613        test_widgets(|tester| {
4614            let key = GlobalKey::new();
4615            let navigator_state = mount_navigator(tester, &key);
4616            let dialog = {
4617                let dialog = tester.update(|app| {
4618                    RawDialogRoute::new(app, corner_page(None))
4619                        .barrier_color(app, Some(Color::new(0x80000000)))
4620                });
4621                let named = dialog.handle();
4622                tester.update(|app| navigator_state.push(app, dialog.clone().into_erased()));
4623                tester.pump_and_settle();
4624                tester.update(|app| navigator_state.pop(app, None));
4625                tester.pump_and_settle();
4626                assert!(
4627                    named
4628                        .transition_route_data(&tester.cell.borrow())
4629                        .transition_completer
4630                        .is_completed(),
4631                    "the route is disposed"
4632                );
4633                named
4634            };
4635            tester.cell.checkpoint();
4636            assert!(
4637                !tester.cell.borrow().contains(dialog),
4638                "the popped route is freed"
4639            );
4640        });
4641    }
4642
4643    /// Dart's 'secondary animation is kDismissed after train hopping finishes and pop', with
4644    /// linear routes: Dart's third route curves its animation (`easeOutExpo`), which a
4645    /// `PageRouteBuilder` here cannot be given, so the trains never meet and the hop ends when
4646    /// the replacing route's push does, through the remover. The hopping animation is freed
4647    /// once it is done with, as Dart's collector would.
4648    #[test]
4649    fn a_finished_train_hop_leaves_the_secondary_animation_on_the_new_route_and_frees_it() {
4650        test_widgets(|tester| {
4651            let key = GlobalKey::new();
4652            let navigator_state = mount_navigator(tester, &key);
4653
4654            let one = tester.update(|app| page_route(app, None, "one"));
4655            let one_route = one.handle();
4656            tester.update(|app| navigator_state.push(app, one.into_erased()));
4657            tester.pump_and_settle();
4658            let secondary_parent = |tester: &WidgetTester| {
4659                let app = tester.cell.borrow();
4660                one_route
4661                    .transition_route_data(&app)
4662                    .secondary_animation
4663                    .parent(&app)
4664            };
4665            let dismissed = tester.update(|app| k_always_dismissed_animation(app).handle());
4666            assert_eq!(secondary_parent(tester), Some(dismissed));
4667
4668            let two: RouteRef = tester.update(|app| page_route(app, None, "two").into_erased());
4669            tester.update(|app| navigator_state.push(app, two.clone()));
4670            tester.pump();
4671            tester.pump_by(Duration::from_millis(100));
4672            let two_animation = {
4673                let app = tester.cell.borrow();
4674                two.as_transition_route(&app)
4675                    .and_then(|route| route.underlying_animation(&app))
4676            };
4677            assert_eq!(secondary_parent(tester), two_animation);
4678
4679            let three: RouteRef = tester.update(|app| page_route(app, None, "three").into_erased());
4680            tester.update(|app| navigator_state.push_replacement(app, three.clone(), None));
4681            tester.pump();
4682            tester.pump_by(Duration::from_millis(1));
4683            let hopper = {
4684                let app = tester.cell.borrow();
4685                let hopper = one_route
4686                    .transition_route_data(&app)
4687                    .secondary_animation
4688                    .parent(&app)
4689                    .and_then(|parent| parent.downcast::<TrainHoppingAnimation>(&app))
4690                    .expect("the secondary animation hops trains");
4691                assert_eq!(app.get(hopper).current_train(), two_animation);
4692                hopper
4693            };
4694
4695            tester.pump_and_settle();
4696            let three_animation = {
4697                let app = tester.cell.borrow();
4698                three
4699                    .as_transition_route(&app)
4700                    .and_then(|route| route.underlying_animation(&app))
4701            };
4702            assert_eq!(secondary_parent(tester), three_animation);
4703            tester.cell.checkpoint();
4704            assert!(
4705                !tester.cell.borrow().contains(hopper),
4706                "the finished hop's animation is freed"
4707            );
4708
4709            tester.update(|app| navigator_state.pop(app, None));
4710            tester.pump_and_settle();
4711            assert_eq!(secondary_parent(tester), Some(dismissed));
4712        });
4713    }
4714
4715    #[test]
4716    fn a_non_dismissible_barrier_keeps_the_route() {
4717        test_widgets(|tester| {
4718            let key = GlobalKey::new();
4719            let navigator_state = mount_navigator(tester, &key);
4720
4721            let dialog: RouteRef = tester.update(|app| {
4722                RawDialogRoute::new(app, corner_page(None))
4723                    .barrier_dismissible(app, false)
4724                    .into_erased()
4725            });
4726            tester.update(|app| navigator_state.push(app, dialog.clone()));
4727            tester.pump_and_settle();
4728
4729            tester.tap_at(Offset::new(150.0, 100.0), 1);
4730            tester.pump();
4731            tester.pump_and_settle();
4732            assert!(
4733                dialog.is_current(&tester.cell.borrow()),
4734                "the tap did nothing"
4735            );
4736        });
4737    }
4738
4739    #[test]
4740    fn local_history_entries_are_popped_before_the_route() {
4741        test_widgets(|tester| {
4742            let key = GlobalKey::new();
4743            let navigator_state = mount_navigator(tester, &key);
4744
4745            let second = tester.update(|app| page_route(app, None, "second"));
4746            tester.update(|app| navigator_state.push(app, second.clone().into_erased()));
4747            tester.pump_and_settle();
4748
4749            let removed = Rc::new(Cell::new(false));
4750            tester.update(|app| {
4751                let entry = LocalHistoryEntry::new(app).on_remove(app, {
4752                    let removed = Rc::clone(&removed);
4753                    Listener::new(move |_app| removed.set(true))
4754                });
4755                LocalHistoryRoute::add_local_history_entry(second.handle(), app, entry);
4756                assert!(Route::will_handle_pop_internally(second.handle(), app));
4757                navigator_state.pop(app, None);
4758            });
4759            tester.pump();
4760            assert!(removed.get(), "the local history entry was removed");
4761            assert!(
4762                second.as_route().is_current(&tester.cell.borrow()),
4763                "the route itself is still on top"
4764            );
4765
4766            tester.update(|app| navigator_state.pop(app, None));
4767            tester.pump_and_settle();
4768            assert!(
4769                !second.as_route().is_active(&tester.cell.borrow()),
4770                "the route popped next"
4771            );
4772        });
4773    }
4774
4775    struct Watcher {
4776        pushed: Cell<usize>,
4777        pushed_next: Cell<usize>,
4778        popped: Cell<usize>,
4779        popped_next: Cell<usize>,
4780    }
4781
4782    impl RouteAwareObject for Watcher {
4783        fn did_push(self: Handle<Self>, app: &mut App) {
4784            let count = app.get(self).pushed.get();
4785            app.get(self).pushed.set(count + 1);
4786        }
4787
4788        fn did_push_next(self: Handle<Self>, app: &mut App) {
4789            let count = app.get(self).pushed_next.get();
4790            app.get(self).pushed_next.set(count + 1);
4791        }
4792
4793        fn did_pop(self: Handle<Self>, app: &mut App) {
4794            let count = app.get(self).popped.get();
4795            app.get(self).popped.set(count + 1);
4796        }
4797
4798        fn did_pop_next(self: Handle<Self>, app: &mut App) {
4799            let count = app.get(self).popped_next.get();
4800            app.get(self).popped_next.set(count + 1);
4801        }
4802    }
4803
4804    #[test]
4805    fn a_route_observer_notifies_its_route_aware() {
4806        test_widgets(|tester| {
4807            let key = GlobalKey::new();
4808            let observer = tester.update(|app| {
4809                RouteObserver::new(
4810                    app,
4811                    Rc::new(|app, route: AnyRoute| route.as_page_route(app).is_some()),
4812                )
4813            });
4814            let initial: Rc<Cell<Option<AnyRoute>>> = Rc::new(Cell::new(None));
4815            tester.pump_widget(Directionality::new(
4816                TextDirection::Ltr,
4817                Navigator::new()
4818                    .key(key.clone().into())
4819                    .on_generate_route({
4820                        let initial = Rc::clone(&initial);
4821                        move |app, _settings| {
4822                            let route: RouteRef = page_route(app, None, "/").into_erased();
4823                            initial.set(Some(route.handle()));
4824                            Some(route)
4825                        }
4826                    })
4827                    .observers(vec![observer.erase()]),
4828            ));
4829            let navigator_state = state(&key, tester);
4830            tester.pump_and_settle();
4831
4832            let first = initial.get().expect("the initial route");
4833            let watcher = tester.update(|app| {
4834                app.create(Watcher {
4835                    pushed: Cell::new(0),
4836                    pushed_next: Cell::new(0),
4837                    popped: Cell::new(0),
4838                    popped_next: Cell::new(0),
4839                })
4840            });
4841            tester.update(|app| observer.subscribe(app, Rc::new(watcher.handle()), first));
4842            assert_eq!(tester.cell.borrow().get(&watcher).pushed.get(), 1);
4843
4844            tester.update(|app| {
4845                let second: RouteRef = page_route(app, None, "second").into_erased();
4846                navigator_state.push(app, second);
4847            });
4848            tester.pump_and_settle();
4849            assert_eq!(tester.cell.borrow().get(&watcher).pushed_next.get(), 1);
4850
4851            tester.update(|app| navigator_state.pop(app, None));
4852            tester.pump_and_settle();
4853            let app = tester.cell.borrow();
4854            assert_eq!(app.get(&watcher).popped_next.get(), 1);
4855            assert_eq!(app.get(&watcher).popped.get(), 0);
4856        });
4857    }
4858}