Skip to main content

waft_widgets/widgets/
navigator.rs

1//! Flutter counterpart: `widgets/navigator.dart`.
2//!
3//! `Route` and its type-erased handle [`AnyRoute`], the [`Navigator`] widget and [`NavigatorState`],
4//! the pages API with its [`TransitionDelegate`], the observers, and the restoration of the
5//! history.
6
7use std::any::{Any, TypeId};
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11use std::time::Duration;
12
13use waft_embedder::{Clip, RestorationData, RestorationMap};
14use waft_foundation::{
15    App, ChangeNotifierData, Completer, CompleterFuture, Handle, HandleId, ListenableObject,
16    Listener, OptionRetained, Retained, ValueNotifier, WeakListener,
17};
18use waft_gestures::GestureBinding;
19use waft_rendering::RenderAbsorbPointer;
20use waft_scheduler::{
21    FrameCallback, SchedulerBinding, SchedulerPhase, Ticker, TickerCallback, TickerFuture,
22    TickerProviderObject,
23};
24use waft_services::RestorationBucket;
25
26use crate::framework::{
27    BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, Notification, State, StateData,
28    StatefulWidget, WidgetRef, keys_equal,
29};
30use crate::view::View;
31use crate::widgets::basic::AbsorbPointer;
32use crate::widgets::focus_manager::{
33    FocusNode, FocusNodeLeaf, FocusNodeRef, TraversalEdgeBehavior,
34};
35use crate::widgets::focus_scope::Focus;
36use crate::widgets::focus_traversal::FocusTraversalGroup;
37use crate::widgets::heroes::HeroController;
38use crate::widgets::notification_listener::NotificationListener;
39use crate::widgets::overlay::{Overlay, OverlayEntry, OverlayState};
40use crate::widgets::restoration::{
41    RestorableProperty, RestorablePropertyData, RestorationMixin, RestorationMixinData,
42    UnmanagedRestorationScope,
43};
44use crate::widgets::restoration_properties::{RestorableInt, RestorableValue};
45use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
46use waft_foundation::Ref;
47
48/// Duration for delay before refocusing in android so that the focus won't be interrupted.
49#[expect(dead_code, reason = "read by the accessibility refocus, which waits")]
50const K_ANDROID_REFOCUSING_DELAY_DURATION: Duration = Duration::from_millis(300);
51
52/// A route's result: what `Navigator::pop` hands back to the code that pushed the route.
53///
54/// Dart's `T?` on `Route<T>`; erased here because a `Route` is reached through [`AnyRoute`].
55pub type RouteResult = Option<Rc<dyn Any>>;
56
57/// Creates a route for the given route settings.
58///
59/// Used by [`Navigator::on_generate_route`].
60pub type RouteFactory = Rc<dyn Fn(&mut App, &RouteSettings) -> Option<RouteRef>>;
61
62/// Creates a series of one or more routes.
63///
64/// Used by [`Navigator::on_generate_initial_routes`].
65pub type RouteListFactory = Rc<dyn Fn(&mut App, Handle<NavigatorState>, &str) -> Vec<RouteRef>>;
66
67/// Creates a [`Route`] that is to be added to a [`Navigator`].
68///
69/// The route can be configured with the provided `arguments`. The provided `context` is the
70/// [`BuildContext`] of the [`Navigator`] to which the route is added.
71///
72/// Used by the restorable methods of the [`Navigator`] that add anonymous routes (e.g.
73/// [`NavigatorState::restorable_push`]).
74pub type RestorableRouteBuilder =
75    Rc<dyn Fn(&mut App, BuildContext, Option<Rc<dyn Any>>) -> RouteRef>;
76
77/// Signature for the [`NavigatorState::pop_until`] predicate argument.
78pub type RoutePredicate = Rc<dyn Fn(&mut App, AnyRoute) -> bool>;
79
80/// Signature for the [`Navigator::on_pop_page`] callback.
81///
82/// This callback must call [`AnyRoute::did_pop`] on the specified route and must properly
83/// update the pages list the next time it is passed into [`Navigator::pages`] so that it no
84/// longer includes the corresponding [`Page`].
85pub type PopPageCallback = Rc<dyn Fn(&mut App, AnyRoute, RouteResult) -> bool>;
86
87/// Signature for the [`Navigator::on_did_remove_page`] callback.
88///
89/// This must properly update the pages list the next time it is passed into
90/// [`Navigator::pages`] so that it no longer includes the input `page`.
91pub type DidRemovePageCallback = Rc<dyn Fn(&mut App, PageRef)>;
92
93/// Indicates whether the current route should be popped.
94///
95/// Used as the return value for [`AnyRoute::will_pop`].
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum RoutePopDisposition {
98    /// Pop the route.
99    ///
100    /// If [`AnyRoute::will_pop`] or [`AnyRoute::pop_disposition`] return
101    /// [`Pop`](Self::Pop) then the back button will actually pop the current route.
102    Pop,
103
104    /// Do not pop the route.
105    ///
106    /// If [`AnyRoute::will_pop`] or [`AnyRoute::pop_disposition`] return
107    /// [`DoNotPop`](Self::DoNotPop) then the back button will be ignored.
108    DoNotPop,
109
110    /// Delegate this to the next level of navigation.
111    ///
112    /// If [`AnyRoute::will_pop`] or [`AnyRoute::pop_disposition`] return
113    /// [`Bubble`](Self::Bubble) then the back button will be handled by the platform's
114    /// navigator, which will usually close the application.
115    Bubble,
116}
117
118// ---------------------------------------------------------------------------------------------
119// RouteSettings and Page
120
121/// Data that might be useful in constructing a [`Route`].
122#[derive(Clone, Default)]
123pub struct RouteSettings {
124    /// The name of the route (e.g., "/settings").
125    ///
126    /// If `None`, the route is anonymous.
127    pub name: Option<String>,
128    /// The arguments passed to this route.
129    ///
130    /// May be used when building the route, e.g. in [`Navigator::on_generate_route`].
131    pub arguments: Option<Rc<dyn Any>>,
132}
133
134impl RouteSettings {
135    /// Creates data used to construct routes; Dart's named arguments are the setters.
136    pub fn new() -> RouteSettings {
137        RouteSettings::default()
138    }
139
140    /// Dart `RouteSettings(name:)`.
141    pub fn name(mut self, name: impl Into<String>) -> RouteSettings {
142        self.name = Some(name.into());
143        self
144    }
145
146    /// Dart `RouteSettings(arguments:)`.
147    pub fn arguments(mut self, arguments: Rc<dyn Any>) -> RouteSettings {
148        self.arguments = Some(arguments);
149        self
150    }
151}
152
153impl Debug for RouteSettings {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        match &self.name {
156            None => write!(f, "RouteSettings(none)"),
157            Some(name) => write!(f, "RouteSettings(\"{name}\")"),
158        }
159    }
160}
161
162/// A shared [`Page`] (Dart's `Page<T>` reference).
163pub type PageRef = Rc<dyn Page>;
164
165/// Describes the configuration of a [`Route`].
166///
167/// [`can_pop`](Self::can_pop) and [`on_pop_invoked`](Self::on_pop_invoked) are used for
168/// intercepting pops.
169///
170/// A page is also the [`RouteSettings`] of the route it creates: [`name`](Self::name) and
171/// [`arguments`](Self::arguments) are Dart's inherited `RouteSettings` fields.
172///
173/// See also:
174///
175///  * [`Navigator::pages`], which accepts a list of [`Page`]s and updates its routes history.
176pub trait Page: Debug + 'static {
177    /// The concrete page, for Dart's `runtimeType` in [`can_update`](Self::can_update).
178    fn as_any(&self) -> &dyn Any;
179
180    /// The key associated with this page.
181    ///
182    /// This key will be used for comparing pages in [`can_update`](Self::can_update).
183    fn key(&self) -> Option<&KeyRef> {
184        None
185    }
186
187    /// See [`RouteSettings::name`].
188    fn name(&self) -> Option<&str> {
189        None
190    }
191
192    /// See [`RouteSettings::arguments`].
193    fn arguments(&self) -> Option<&Rc<dyn Any>> {
194        None
195    }
196
197    /// Restoration ID to save and restore the state of the [`Route`] configured by this page.
198    ///
199    /// If no restoration ID is provided, the [`Route`] will not restore its state.
200    fn restoration_id(&self) -> Option<&str> {
201        None
202    }
203
204    /// When false, blocks the associated route from being popped.
205    ///
206    /// If this is set to false for the first page in the [`Navigator`] it prevents the
207    /// application from exiting.
208    ///
209    /// If there are any `PopScope` widgets in a route's widget subtree, each of their `can_pop`
210    /// must be `true`, in addition to this `can_pop`, in order for the route to be able to pop.
211    fn can_pop(&self) -> bool {
212        true
213    }
214
215    /// Called after a pop on the associated route was handled.
216    ///
217    /// It's not possible to prevent the pop from happening at the time that this method is
218    /// called; the pop has already happened. Use [`can_pop`](Self::can_pop) to disable pops in
219    /// advance.
220    ///
221    /// This will still be called even when the pop is canceled.
222    fn on_pop_invoked(&self, app: &mut App, did_pop: bool, result: RouteResult) {
223        let _ = (app, did_pop, result);
224    }
225
226    /// Whether this page can be updated with the `other` page.
227    ///
228    /// Two pages are considered updatable if they have the same `runtimeType` and
229    /// [`key`](Self::key).
230    fn can_update(&self, other: &dyn Page) -> bool {
231        other.as_any().type_id() == self.as_any().type_id() && keys_equal(other.key(), self.key())
232    }
233
234    /// Creates the [`Route`] that corresponds to this page.
235    ///
236    /// The created route must have its settings set to this page: `this` is the shared
237    /// reference the navigator holds, which Dart writes as `this`.
238    fn create_route(&self, app: &mut App, context: BuildContext, this: &PageRef) -> RouteRef;
239}
240
241/// What a [`Route`]'s settings hold: plain [`RouteSettings`], or the [`Page`] that created the
242/// route.
243///
244/// Dart's `Page<T> extends RouteSettings`, so `Route.settings` is either; `settings is Page` is
245/// [`as_page`](Self::as_page).
246#[derive(Clone)]
247pub enum RouteSettingsRef {
248    /// A pageless route's settings.
249    Settings(RouteSettings),
250    /// A page-based route's settings: the page itself.
251    Page(PageRef),
252}
253
254impl RouteSettingsRef {
255    /// See [`RouteSettings::name`].
256    pub fn name(&self) -> Option<&str> {
257        match self {
258            RouteSettingsRef::Settings(settings) => settings.name.as_deref(),
259            RouteSettingsRef::Page(page) => page.name(),
260        }
261    }
262
263    /// See [`RouteSettings::arguments`].
264    pub fn arguments(&self) -> Option<&Rc<dyn Any>> {
265        match self {
266            RouteSettingsRef::Settings(settings) => settings.arguments.as_ref(),
267            RouteSettingsRef::Page(page) => page.arguments(),
268        }
269    }
270
271    /// Dart's `settings is Page<Object?>`.
272    pub fn as_page(&self) -> Option<&PageRef> {
273        match self {
274            RouteSettingsRef::Settings(_) => None,
275            RouteSettingsRef::Page(page) => Some(page),
276        }
277    }
278}
279
280impl PartialEq for RouteSettingsRef {
281    fn eq(&self, other: &RouteSettingsRef) -> bool {
282        match (self, other) {
283            (RouteSettingsRef::Page(a), RouteSettingsRef::Page(b)) => Rc::ptr_eq(a, b),
284            (RouteSettingsRef::Settings(a), RouteSettingsRef::Settings(b)) => {
285                a.name == b.name
286                    && match (&a.arguments, &b.arguments) {
287                        (None, None) => true,
288                        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
289                        _ => false,
290                    }
291            }
292            _ => false,
293        }
294    }
295}
296
297impl Debug for RouteSettingsRef {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        match self {
300            RouteSettingsRef::Settings(settings) => Debug::fmt(settings, f),
301            RouteSettingsRef::Page(page) => Debug::fmt(page, f),
302        }
303    }
304}
305
306impl From<RouteSettings> for RouteSettingsRef {
307    fn from(settings: RouteSettings) -> RouteSettingsRef {
308        RouteSettingsRef::Settings(settings)
309    }
310}
311
312impl From<PageRef> for RouteSettingsRef {
313    fn from(page: PageRef) -> RouteSettingsRef {
314        RouteSettingsRef::Page(page)
315    }
316}
317
318// ---------------------------------------------------------------------------------------------
319// Route
320
321/// The fields Dart's `Route` declares; every route carries this bag under the field `route`.
322pub struct RouteData {
323    request_focus: Option<bool>,
324    navigator: Option<Handle<NavigatorState>>,
325    settings: RouteSettingsRef,
326    restoration_scope_id: Ref<ValueNotifier<Option<String>>>,
327    pop_completer: Completer<RouteResult>,
328    dispose_completer: Completer<RouteResult>,
329}
330
331impl RouteData {
332    /// The bag of a freshly created route: Dart's constructor defaults.
333    ///
334    /// `settings` is Dart's `settings ?? const RouteSettings()`, `request_focus` its
335    /// `requestFocus`.
336    pub fn new(
337        app: &mut App,
338        settings: Option<RouteSettingsRef>,
339        request_focus: Option<bool>,
340    ) -> RouteData {
341        RouteData {
342            request_focus,
343            navigator: None,
344            settings: settings
345                .unwrap_or_else(|| RouteSettingsRef::Settings(RouteSettings::default())),
346            restoration_scope_id: app.create(ValueNotifier::new(None)),
347            pop_completer: Completer::new(),
348            dispose_completer: Completer::new(),
349        }
350    }
351}
352
353impl RouteData {
354    /// Dart's `Route(settings:)`, for a leaf whose constructor takes it as a fluent setter.
355    pub fn set_settings(&mut self, settings: RouteSettingsRef) {
356        self.settings = settings;
357    }
358
359    /// Dart's `Route(requestFocus:)`, for a leaf whose constructor takes it as a fluent setter.
360    pub fn set_request_focus(&mut self, request_focus: Option<bool>) {
361        self.request_focus = request_focus;
362    }
363}
364
365/// The accessors [`Route`] asks for, for a struct whose bag is the field `route`.
366#[macro_export]
367macro_rules! route_accessors {
368    () => {
369        fn route_data(
370            self: ::waft_foundation::Handle<Self>,
371            app: &::waft_foundation::App,
372        ) -> &$crate::RouteData {
373            &app.get(self).route
374        }
375
376        fn route_data_mut(
377            self: ::waft_foundation::Handle<Self>,
378            app: &mut ::waft_foundation::App,
379        ) -> &mut $crate::RouteData {
380            &mut app.get_mut(self).route
381        }
382    };
383}
384
385/// An abstraction for an entry managed by a [`Navigator`].
386///
387/// This trait defines an abstract interface between the navigator and the "routes" that are
388/// pushed on and popped off the navigator. Most routes have visual affordances, which they
389/// place in the navigator's [`Overlay`] using one or more [`OverlayEntry`] objects.
390///
391/// A route can belong to a page if its settings are a [`Page`]. A page-based route, as opposed
392/// to a pageless route, is created from [`Page::create_route`] during [`Navigator::pages`]
393/// updates. The page associated with this route may change during the lifetime of the route. If
394/// the [`Navigator`] updates the page of this route, it calls
395/// [`changed_internal_state`](Self::changed_internal_state) to notify the route that the page
396/// has been updated.
397///
398/// Dart's type argument `T` — the route's return type — is erased as [`RouteResult`]; a
399/// concrete route keeps a typed accessor where one is possible.
400///
401/// The trait holds the virtuals and one-line forwarders for the shared members, which live on
402/// [`AnyRoute`] because a route reaches its navigator and its neighbours through that handle.
403pub trait Route: Sized + 'static {
404    /// Dart's `Route` fields, held under the field `route` ([`route_accessors!`](crate::route_accessors)).
405    fn route_data(self: Handle<Self>, app: &App) -> &RouteData;
406
407    /// See [`route_data`](Self::route_data).
408    fn route_data_mut(self: Handle<Self>, app: &mut App) -> &mut RouteData;
409
410    /// This route as the erased [`AnyRoute`] — what to pass where a Dart API takes a `Route`.
411    ///
412    /// The object is untouched; this mints an erased second handle to it, so concrete members
413    /// stay reachable through the typed one.
414    fn as_route(self: Handle<Self>) -> AnyRoute {
415        AnyRoute {
416            id: self.id(),
417            vtable: const { &RouteVTable::of::<Self>() },
418        }
419    }
420
421    /// This route as the erased [`AnyTransitionRoute`](crate::AnyTransitionRoute), when it is
422    /// a `TransitionRoute`.
423    ///
424    /// Dart's `route is TransitionRoute<dynamic>`; a `TransitionRoute` implementor overrides
425    /// this to `Some(self.as_transition_route())`.
426    fn as_transition_route(self: Handle<Self>) -> Option<crate::AnyTransitionRoute> {
427        let _ = self;
428        None
429    }
430
431    /// This route as the erased [`AnyModalRoute`](crate::AnyModalRoute), when it is a
432    /// `ModalRoute`.
433    ///
434    /// Dart's `route is ModalRoute<dynamic>`; a `ModalRoute` implementor overrides this to
435    /// `Some(self.as_modal_route())`.
436    fn as_modal_route(self: Handle<Self>) -> Option<crate::AnyModalRoute> {
437        let _ = self;
438        None
439    }
440
441    /// This route as the erased [`AnyPageRoute`](crate::AnyPageRoute), when it is a
442    /// `PageRoute`.
443    ///
444    /// Dart's `route is PageRoute<dynamic>`; a `PageRoute` implementor overrides this to
445    /// `Some(self.as_page_route())`.
446    fn as_page_route(self: Handle<Self>) -> Option<crate::AnyPageRoute> {
447        let _ = self;
448        None
449    }
450
451    /// Dart's `route is SomeMixin` for a mixin defined outside this crate: the erased handle of
452    /// the interface `id` names, if this type implements it.
453    ///
454    /// An implementor answers each interface it implements with that interface's erased
455    /// handle, boxed; [`AnyRoute::interface`] unboxes it. The default implements none.
456    fn interface(self: Handle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
457        let _ = (self, id);
458        None
459    }
460
461    /// The overlay entries of this route.
462    ///
463    /// These are typically populated by [`install`](Self::install). The [`Navigator`] is in
464    /// charge of adding them to and removing them from the [`Overlay`].
465    ///
466    /// There must be at least one entry in this list after `install` has been invoked.
467    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<OverlayEntry>> {
468        RouteBase::overlay_entries(self, app)
469    }
470
471    /// Called when the route is inserted into the navigator.
472    ///
473    /// Use this to populate [`overlay_entries`](Self::overlay_entries).
474    fn install(self: Handle<Self>, app: &mut App) {
475        RouteBase::install(self, app)
476    }
477
478    /// Called after [`install`](Self::install) when the route is pushed onto the navigator.
479    ///
480    /// The returned value resolves when the push transition is complete.
481    ///
482    /// [`did_add`](Self::did_add) will be called instead of this when the route immediately
483    /// appears on screen without any push transition.
484    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
485        RouteBase::did_push(self, app)
486    }
487
488    /// Called after [`install`](Self::install) when the route is added to the navigator.
489    ///
490    /// This method is called instead of [`did_push`](Self::did_push) when the route immediately
491    /// appears on screen without any push transition.
492    fn did_add(self: Handle<Self>, app: &mut App) {
493        RouteBase::did_add(self, app)
494    }
495
496    /// Called after [`install`](Self::install) when the route replaced another in the navigator.
497    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<AnyRoute>) {
498        RouteBase::did_replace(self, app, old_route)
499    }
500
501    /// Returns whether calling [`NavigatorState::maybe_pop`] when this route is current should
502    /// do anything.
503    ///
504    /// Dart's deprecated `willPop`; [`pop_disposition`](Self::pop_disposition) is its
505    /// replacement.
506    fn will_pop(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
507        RouteBase::will_pop(self, app)
508    }
509
510    /// Returns whether calling [`NavigatorState::maybe_pop`] when this route is current
511    /// ([`is_current`](AnyRoute::is_current)) should do anything.
512    ///
513    /// By default, if a route is the first route in the history (i.e., if
514    /// [`is_first`](AnyRoute::is_first)), it reports that pops should be bubbled
515    /// ([`RoutePopDisposition::Bubble`]). This behavior prevents the user from popping the
516    /// first route off the history and being stranded at a blank screen; instead, the larger
517    /// scope is popped.
518    ///
519    /// In other cases, the default behavior is to accept the pop ([`RoutePopDisposition::Pop`]).
520    fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
521        RouteBase::pop_disposition(self, app)
522    }
523
524    /// Called after a route pop was handled.
525    ///
526    /// Even when the pop is canceled, for example by a `PopScope` widget, this will still be
527    /// called. The `did_pop` parameter indicates whether or not the back navigation actually
528    /// happened successfully.
529    fn on_pop_invoked_with_result(
530        self: Handle<Self>,
531        app: &mut App,
532        did_pop: bool,
533        result: RouteResult,
534    ) {
535        RouteBase::on_pop_invoked_with_result(self, app, did_pop, result)
536    }
537
538    /// Whether calling [`did_pop`](Self::did_pop) would return false.
539    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
540        RouteBase::will_handle_pop_internally(self, app)
541    }
542
543    /// When this route is popped (see [`NavigatorState::pop`]) if the result isn't specified or
544    /// if it is `None`, this value will be used instead.
545    ///
546    /// This fallback is implemented by [`did_complete`](Self::did_complete).
547    fn current_result(self: Handle<Self>, app: &App) -> RouteResult {
548        RouteBase::current_result(self, app)
549    }
550
551    /// A request was made to pop this route. If the route can handle it internally (e.g.
552    /// because it has its own stack of internal state) then return false, otherwise return true
553    /// (by returning the value of calling `Route::did_pop`). Returning false will prevent the
554    /// default behavior of [`NavigatorState::pop`].
555    ///
556    /// When this function returns true, the navigator removes this route from the history but
557    /// does not yet call [`dispose`](Self::dispose). Instead, it is the route's responsibility
558    /// to call [`NavigatorState::finalize_route`], which will in turn call `dispose` on the
559    /// route.
560    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
561        RouteBase::did_pop(self, app, result)
562    }
563
564    /// The route was popped or is otherwise being removed somewhat gracefully.
565    ///
566    /// This is called by [`did_pop`](Self::did_pop) and in response to
567    /// [`NavigatorState::push_replacement`]. If `did_pop` was not called, then
568    /// [`NavigatorState::finalize_route`] must be called immediately, and no exit animation
569    /// will run.
570    ///
571    /// The `popped` completion is resolved by this method.
572    fn did_complete(self: Handle<Self>, app: &mut App, result: RouteResult) {
573        RouteBase::did_complete(self, app, result)
574    }
575
576    /// The given route, which was above this one, has been popped off the navigator.
577    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
578        RouteBase::did_pop_next(self, app, next_route)
579    }
580
581    /// This route's next route has changed to the given new route.
582    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
583        RouteBase::did_change_next(self, app, next_route)
584    }
585
586    /// This route's previous route has changed to the given new route.
587    fn did_change_previous(self: Handle<Self>, app: &mut App, previous_route: Option<AnyRoute>) {
588        RouteBase::did_change_previous(self, app, previous_route)
589    }
590
591    /// Called whenever the internal state of the route has changed.
592    ///
593    /// This should be called whenever [`will_handle_pop_internally`](Self::will_handle_pop_internally),
594    /// [`did_pop`](Self::did_pop), `ModalRoute::offstage`, or other internal state of the route
595    /// changes value.
596    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
597        RouteBase::changed_internal_state(self, app)
598    }
599
600    /// Called whenever the [`Navigator`] has updated in some manner that might affect routes,
601    /// to indicate that the route may wish to rebuild as well.
602    fn changed_external_state(self: Handle<Self>, app: &mut App) {
603        RouteBase::changed_external_state(self, app)
604    }
605
606    /// Discards any resources used by the object.
607    ///
608    /// This method should not remove its [`overlay_entries`](Self::overlay_entries) from the
609    /// [`Overlay`]. The object's owner is in charge of doing that.
610    fn dispose(self: Handle<Self>, app: &mut App) {
611        RouteBase::dispose(self, app)
612    }
613
614    // ---- one-line forwarders to the type-erased handle ----
615
616    /// See [`AnyRoute::navigator`].
617    fn navigator(self: Handle<Self>, app: &App) -> Option<Handle<NavigatorState>> {
618        self.as_route().navigator(app)
619    }
620
621    /// See [`AnyRoute::settings`].
622    fn settings(self: Handle<Self>, app: &App) -> RouteSettingsRef {
623        self.as_route().settings(app)
624    }
625
626    /// See [`AnyRoute::is_page_based`].
627    fn is_page_based(self: Handle<Self>, app: &App) -> bool {
628        self.as_route().is_page_based(app)
629    }
630
631    /// See [`AnyRoute::request_focus`].
632    fn request_focus(self: Handle<Self>, app: &App) -> bool {
633        self.as_route().request_focus(app)
634    }
635
636    /// See [`AnyRoute::restoration_scope_id`].
637    fn restoration_scope_id(
638        self: Handle<Self>,
639        app: &App,
640    ) -> Handle<ValueNotifier<Option<String>>> {
641        self.as_route().restoration_scope_id(app)
642    }
643
644    /// See [`AnyRoute::is_current`].
645    fn is_current(self: Handle<Self>, app: &App) -> bool {
646        self.as_route().is_current(app)
647    }
648
649    /// See [`AnyRoute::is_first`].
650    fn is_first(self: Handle<Self>, app: &App) -> bool {
651        self.as_route().is_first(app)
652    }
653
654    /// See [`AnyRoute::is_active`].
655    fn is_active(self: Handle<Self>, app: &App) -> bool {
656        self.as_route().is_active(app)
657    }
658
659    /// See [`AnyRoute::has_active_route_below`].
660    fn has_active_route_below(self: Handle<Self>, app: &App) -> bool {
661        self.as_route().has_active_route_below(app)
662    }
663
664    /// See [`AnyRoute::popped`].
665    fn popped(self: Handle<Self>, app: &App) -> CompleterFuture<RouteResult> {
666        self.as_route().popped(app)
667    }
668}
669
670/// The bodies of Dart's `Route` class.
671///
672/// A subclass whose override runs Dart's `super.install()` calls [`RouteBase::install`]; a
673/// [`Route`] default is one line that does the same. Every [`Route`] implementor gets these
674/// bodies, so an override on the leaf never reaches them by accident.
675pub trait RouteBase: Route {
676    /// Dart's `Route.overlayEntries`.
677    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<OverlayEntry>> {
678        let _ = app;
679        Vec::new()
680    }
681
682    /// Dart's `Route.install`.
683    fn install(self: Handle<Self>, app: &mut App) {
684        let _ = app;
685    }
686
687    /// Dart's `Route.didPush`.
688    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
689        let future = TickerFuture::complete();
690        // The completion keeps the route, as Dart's closure over `this` does.
691        let route: RouteRef = self.keep(app).into_erased();
692        future.when_complete(
693            app,
694            Listener::new(move |app| {
695                if route.request_focus(app)
696                    && let Some(navigator) = route.navigator(app)
697                {
698                    let focus_node = navigator.focus_node(app);
699                    if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
700                        scope.request_focus(app, None);
701                    }
702                }
703            }),
704        );
705        future
706    }
707
708    /// Dart's `Route.didAdd`.
709    fn did_add(self: Handle<Self>, app: &mut App) {
710        if !self.as_route().request_focus(app) {
711            return;
712        }
713        // This completion serves two purposes. First, we want to make sure that animations
714        // triggered by other operations will finish before focusing the navigator. Second,
715        // `navigator.focus_node` might acquire more focused children in `install`
716        // asynchronously.
717        let route: RouteRef = self.keep(app).into_erased();
718        let future = TickerFuture::complete();
719        future.when_complete(
720            app,
721            Listener::new(move |app| {
722                // The route can be disposed before the completion runs.
723                if let Some(navigator) = route.navigator(app) {
724                    let focus_node = navigator.focus_node(app);
725                    if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
726                        scope.request_focus(app, None);
727                    }
728                }
729            }),
730        );
731    }
732
733    /// Dart's `Route.didReplace`.
734    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<AnyRoute>) {
735        let _ = (app, old_route);
736    }
737
738    /// Dart's `Route.willPop`.
739    fn will_pop(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
740        if self.as_route().is_first(app) {
741            RoutePopDisposition::Bubble
742        } else {
743            RoutePopDisposition::Pop
744        }
745    }
746
747    /// Dart's `Route.popDisposition`.
748    fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
749        if let Some(page) = self.route_data(app).settings.as_page()
750            && !page.can_pop()
751        {
752            return RoutePopDisposition::DoNotPop;
753        }
754        if self.as_route().is_first(app) {
755            RoutePopDisposition::Bubble
756        } else {
757            RoutePopDisposition::Pop
758        }
759    }
760
761    /// Dart's `Route.onPopInvokedWithResult`.
762    fn on_pop_invoked_with_result(
763        self: Handle<Self>,
764        app: &mut App,
765        did_pop: bool,
766        result: RouteResult,
767    ) {
768        if let Some(page) = self.route_data(app).settings.as_page().cloned() {
769            page.on_pop_invoked(app, did_pop, result);
770        }
771    }
772
773    /// Dart's `Route.willHandlePopInternally`.
774    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
775        let _ = app;
776        false
777    }
778
779    /// Dart's `Route.currentResult`.
780    fn current_result(self: Handle<Self>, app: &App) -> RouteResult {
781        let _ = app;
782        None
783    }
784
785    /// Dart's `Route.didPop`.
786    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
787        Route::did_complete(self, app, result);
788        true
789    }
790
791    /// Dart's `Route.didComplete`.
792    fn did_complete(self: Handle<Self>, app: &mut App, result: RouteResult) {
793        let result = result.or_else(|| Route::current_result(self, app));
794        let pop_completer = self.route_data(app).pop_completer.clone();
795        pop_completer.complete(app, result);
796    }
797
798    /// Dart's `Route.didPopNext`.
799    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
800        let _ = (app, next_route);
801    }
802
803    /// Dart's `Route.didChangeNext`.
804    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
805        let _ = (app, next_route);
806    }
807
808    /// Dart's `Route.didChangePrevious`.
809    fn did_change_previous(self: Handle<Self>, app: &mut App, previous_route: Option<AnyRoute>) {
810        let _ = (app, previous_route);
811    }
812
813    /// Dart's `Route.changedInternalState`.
814    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
815        let _ = app;
816    }
817
818    /// Dart's `Route.changedExternalState`.
819    fn changed_external_state(self: Handle<Self>, app: &mut App) {
820        let _ = app;
821    }
822
823    /// Dart's `Route.dispose`.
824    fn dispose(self: Handle<Self>, app: &mut App) {
825        self.route_data_mut(app).navigator = None;
826        let notifier = self.route_data(app).restoration_scope_id.handle();
827        notifier.dispose(app);
828        let dispose_completer = self.route_data(app).dispose_completer.clone();
829        dispose_completer.complete(app, None);
830    }
831}
832
833impl<R: Route> RouteBase for R {}
834
835/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
836fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
837    Handle::from_id(id)
838}
839
840/// The vtable of an erased [`AnyRoute`]: one `&'static` table per route type, built by
841/// [`RouteVTable::of`].
842struct RouteVTable {
843    type_name: fn() -> &'static str,
844    data: fn(&App, HandleId) -> &RouteData,
845    data_mut: fn(&mut App, HandleId) -> &mut RouteData,
846    overlay_entries: fn(&App, HandleId) -> Vec<Handle<OverlayEntry>>,
847    install: fn(&mut App, HandleId),
848    did_push: fn(&mut App, HandleId) -> TickerFuture,
849    did_add: fn(&mut App, HandleId),
850    did_replace: fn(&mut App, HandleId, Option<AnyRoute>),
851    will_pop: fn(&mut App, HandleId) -> RoutePopDisposition,
852    pop_disposition: fn(&mut App, HandleId) -> RoutePopDisposition,
853    on_pop_invoked_with_result: fn(&mut App, HandleId, bool, RouteResult),
854    will_handle_pop_internally: fn(&App, HandleId) -> bool,
855    current_result: fn(&App, HandleId) -> RouteResult,
856    did_pop: fn(&mut App, HandleId, RouteResult) -> bool,
857    did_complete: fn(&mut App, HandleId, RouteResult),
858    did_pop_next: fn(&mut App, HandleId, AnyRoute),
859    did_change_next: fn(&mut App, HandleId, Option<AnyRoute>),
860    did_change_previous: fn(&mut App, HandleId, Option<AnyRoute>),
861    changed_internal_state: fn(&mut App, HandleId),
862    changed_external_state: fn(&mut App, HandleId),
863    dispose: fn(&mut App, HandleId),
864    as_transition_route: fn(HandleId) -> Option<crate::AnyTransitionRoute>,
865    as_modal_route: fn(HandleId) -> Option<crate::AnyModalRoute>,
866    as_page_route: fn(HandleId) -> Option<crate::AnyPageRoute>,
867    interface: fn(HandleId, TypeId) -> Option<Box<dyn Any>>,
868}
869
870impl RouteVTable {
871    /// The table for one route type.
872    const fn of<R: Route>() -> RouteVTable {
873        RouteVTable {
874            type_name: std::any::type_name::<R>,
875            data: |app, id| R::route_data(resolve(id), app),
876            data_mut: |app, id| R::route_data_mut(resolve(id), app),
877            overlay_entries: |app, id| R::overlay_entries(resolve(id), app),
878            install: |app, id| R::install(resolve(id), app),
879            did_push: |app, id| R::did_push(resolve(id), app),
880            did_add: |app, id| R::did_add(resolve(id), app),
881            did_replace: |app, id, old| R::did_replace(resolve(id), app, old),
882            will_pop: |app, id| R::will_pop(resolve(id), app),
883            pop_disposition: |app, id| R::pop_disposition(resolve(id), app),
884            on_pop_invoked_with_result: |app, id, did_pop, result| {
885                R::on_pop_invoked_with_result(resolve(id), app, did_pop, result)
886            },
887            will_handle_pop_internally: |app, id| R::will_handle_pop_internally(resolve(id), app),
888            current_result: |app, id| R::current_result(resolve(id), app),
889            did_pop: |app, id, result| R::did_pop(resolve(id), app, result),
890            did_complete: |app, id, result| R::did_complete(resolve(id), app, result),
891            did_pop_next: |app, id, next| R::did_pop_next(resolve(id), app, next),
892            did_change_next: |app, id, next| R::did_change_next(resolve(id), app, next),
893            did_change_previous: |app, id, prev| R::did_change_previous(resolve(id), app, prev),
894            changed_internal_state: |app, id| R::changed_internal_state(resolve(id), app),
895            changed_external_state: |app, id| R::changed_external_state(resolve(id), app),
896            dispose: |app, id| R::dispose(resolve(id), app),
897            as_transition_route: |id| R::as_transition_route(resolve::<R>(id)),
898            as_modal_route: |id| R::as_modal_route(resolve::<R>(id)),
899            as_page_route: |id| R::as_page_route(resolve::<R>(id)),
900            interface: |id, interface| R::interface(resolve::<R>(id), interface),
901        }
902    }
903}
904
905/// Erased [`Route`]: one identity and a static vtable, the fat pointer rustc cannot build for
906/// an arena id. No lease.
907///
908/// This is what a field or parameter Dart types as `Route<dynamic>` becomes; the route stays in
909/// the [`App`] under its own type, and [`downcast`](Self::downcast) gets the typed handle back.
910///
911/// Equality is Dart's `==` on an object reference: two handles are equal exactly when they address
912/// the same route.
913#[derive(Clone, Copy)]
914pub struct AnyRoute {
915    id: HandleId,
916    vtable: &'static RouteVTable,
917}
918
919/// A field Dart types as the erased object, kept: AnyRoute with its count.
920pub type RouteRef = Retained<AnyRoute>;
921
922waft_foundation::erased_handle!(AnyRoute: Route => Route::as_route);
923
924impl Debug for AnyRoute {
925    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
926        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
927    }
928}
929
930impl AnyRoute {
931    /// The arena id behind this handle.
932    pub fn id(self) -> HandleId {
933        self.id
934    }
935
936    /// Dart's `route as T`: the typed handle when this route is a `T`, else `None`.
937    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
938        app.handle::<T>(self.id)
939    }
940
941    /// Dart's `route is TransitionRoute<dynamic>`.
942    pub fn as_transition_route(self, app: &App) -> Option<crate::AnyTransitionRoute> {
943        let _ = app;
944        (self.vtable.as_transition_route)(self.id)
945    }
946
947    /// Dart's `route is ModalRoute<dynamic>`.
948    pub fn as_modal_route(self, app: &App) -> Option<crate::AnyModalRoute> {
949        let _ = app;
950        (self.vtable.as_modal_route)(self.id)
951    }
952
953    /// Dart's `route is PageRoute<dynamic>`.
954    pub fn as_page_route(self, app: &App) -> Option<crate::AnyPageRoute> {
955        let _ = app;
956        (self.vtable.as_page_route)(self.id)
957    }
958
959    /// See [`Route::interface`]: Dart's `route is SomeMixin`, as
960    /// `interface::<Rc<dyn SomeMixin>>()`.
961    pub fn interface<I: 'static>(self) -> Option<I> {
962        (self.vtable.interface)(self.id, TypeId::of::<I>())?
963            .downcast()
964            .ok()
965            .map(|interface| *interface)
966    }
967
968    fn data(self, app: &App) -> &RouteData {
969        (self.vtable.data)(app, self.id)
970    }
971
972    fn data_mut(self, app: &mut App) -> &mut RouteData {
973        (self.vtable.data_mut)(app, self.id)
974    }
975
976    /// When the route state is updated, request focus if the current route is at the top.
977    ///
978    /// If not provided in the constructor, [`Navigator::request_focus`] is used instead.
979    pub fn request_focus(self, app: &App) -> bool {
980        if let Some(value) = self.data(app).request_focus {
981            return value;
982        }
983        match self.navigator(app) {
984            None => false,
985            Some(navigator) => navigator.widget(app).request_focus,
986        }
987    }
988
989    /// The navigator that the route is in, if any.
990    pub fn navigator(self, app: &App) -> Option<Handle<NavigatorState>> {
991        self.data(app).navigator
992    }
993
994    pub(crate) fn set_navigator(self, app: &mut App, navigator: Option<Handle<NavigatorState>>) {
995        self.data_mut(app).navigator = navigator;
996    }
997
998    /// Dart's `Route._installed`.
999    pub(crate) fn installed(self, app: &App) -> bool {
1000        self.data(app).navigator.is_some()
1001    }
1002
1003    pub(crate) fn is_installed_in(self, app: &App, state: Handle<NavigatorState>) -> bool {
1004        self.data(app).navigator == Some(state)
1005    }
1006
1007    /// The settings for this route.
1008    ///
1009    /// The settings can change during the route's lifetime. If the settings change, the route's
1010    /// overlays will be marked dirty (see [`changed_internal_state`](Self::changed_internal_state)).
1011    ///
1012    /// If the route is created from a [`Page`] in the [`Navigator::pages`] list, then this will
1013    /// be a page, and it will be updated each time its corresponding page has changed.
1014    pub fn settings(self, app: &App) -> RouteSettingsRef {
1015        self.data(app).settings.clone()
1016    }
1017
1018    /// Dart's `Route._isPageBased`.
1019    pub fn is_page_based(self, app: &App) -> bool {
1020        matches!(self.data(app).settings, RouteSettingsRef::Page(_))
1021    }
1022
1023    /// The restoration scope ID to be used for the `RestorationScope` surrounding this route.
1024    ///
1025    /// The restoration scope ID is `None` if restoration is currently disabled for this route.
1026    ///
1027    /// If the restoration scope ID changes (e.g. because restoration is enabled or disabled)
1028    /// during the life of the route, the notifier notifies its listeners.
1029    pub fn restoration_scope_id(self, app: &App) -> Handle<ValueNotifier<Option<String>>> {
1030        self.data(app).restoration_scope_id.handle()
1031    }
1032
1033    fn update_settings(self, app: &mut App, new_settings: RouteSettingsRef) {
1034        if self.data(app).settings != new_settings {
1035            self.data_mut(app).settings = new_settings;
1036            if self.installed(app) {
1037                self.changed_internal_state(app);
1038            }
1039        }
1040    }
1041
1042    fn update_restoration_id(self, app: &mut App, restoration_id: Option<String>) {
1043        let notifier = self.data(app).restoration_scope_id.handle();
1044        notifier.set_value(app, restoration_id);
1045    }
1046
1047    /// A future that completes when this route is popped off the navigator.
1048    ///
1049    /// The future completes with the value given to [`NavigatorState::pop`], if any, or else
1050    /// the value of [`current_result`](Self::current_result). See
1051    /// [`did_complete`](Self::did_complete) for more discussion on this topic.
1052    pub fn popped(self, app: &App) -> CompleterFuture<RouteResult> {
1053        self.data(app).pop_completer.future()
1054    }
1055
1056    // ---- the virtuals ----
1057
1058    /// See [`Route::overlay_entries`].
1059    pub fn overlay_entries(self, app: &App) -> Vec<Handle<OverlayEntry>> {
1060        (self.vtable.overlay_entries)(app, self.id)
1061    }
1062
1063    /// See [`Route::install`].
1064    pub fn install(self, app: &mut App) {
1065        (self.vtable.install)(app, self.id)
1066    }
1067
1068    /// See [`Route::did_push`].
1069    pub fn did_push(self, app: &mut App) -> TickerFuture {
1070        (self.vtable.did_push)(app, self.id)
1071    }
1072
1073    /// See [`Route::did_add`].
1074    pub fn did_add(self, app: &mut App) {
1075        (self.vtable.did_add)(app, self.id)
1076    }
1077
1078    /// See [`Route::did_replace`].
1079    pub fn did_replace(self, app: &mut App, old_route: Option<AnyRoute>) {
1080        (self.vtable.did_replace)(app, self.id, old_route)
1081    }
1082
1083    /// See [`Route::will_pop`].
1084    pub fn will_pop(self, app: &mut App) -> RoutePopDisposition {
1085        (self.vtable.will_pop)(app, self.id)
1086    }
1087
1088    /// See [`Route::pop_disposition`].
1089    pub fn pop_disposition(self, app: &mut App) -> RoutePopDisposition {
1090        (self.vtable.pop_disposition)(app, self.id)
1091    }
1092
1093    /// See [`Route::on_pop_invoked_with_result`].
1094    pub fn on_pop_invoked_with_result(self, app: &mut App, did_pop: bool, result: RouteResult) {
1095        (self.vtable.on_pop_invoked_with_result)(app, self.id, did_pop, result)
1096    }
1097
1098    /// See [`Route::will_handle_pop_internally`].
1099    pub fn will_handle_pop_internally(self, app: &App) -> bool {
1100        (self.vtable.will_handle_pop_internally)(app, self.id)
1101    }
1102
1103    /// See [`Route::current_result`].
1104    pub fn current_result(self, app: &App) -> RouteResult {
1105        (self.vtable.current_result)(app, self.id)
1106    }
1107
1108    /// See [`Route::did_pop`].
1109    pub fn did_pop(self, app: &mut App, result: RouteResult) -> bool {
1110        (self.vtable.did_pop)(app, self.id, result)
1111    }
1112
1113    /// See [`Route::did_complete`].
1114    pub fn did_complete(self, app: &mut App, result: RouteResult) {
1115        (self.vtable.did_complete)(app, self.id, result)
1116    }
1117
1118    /// See [`Route::did_pop_next`].
1119    pub fn did_pop_next(self, app: &mut App, next_route: AnyRoute) {
1120        (self.vtable.did_pop_next)(app, self.id, next_route)
1121    }
1122
1123    /// See [`Route::did_change_next`].
1124    pub fn did_change_next(self, app: &mut App, next_route: Option<AnyRoute>) {
1125        (self.vtable.did_change_next)(app, self.id, next_route)
1126    }
1127
1128    /// See [`Route::did_change_previous`].
1129    pub fn did_change_previous(self, app: &mut App, previous_route: Option<AnyRoute>) {
1130        (self.vtable.did_change_previous)(app, self.id, previous_route)
1131    }
1132
1133    /// See [`Route::changed_internal_state`].
1134    pub fn changed_internal_state(self, app: &mut App) {
1135        (self.vtable.changed_internal_state)(app, self.id)
1136    }
1137
1138    /// See [`Route::changed_external_state`].
1139    pub fn changed_external_state(self, app: &mut App) {
1140        (self.vtable.changed_external_state)(app, self.id)
1141    }
1142
1143    /// See [`Route::dispose`].
1144    pub fn dispose(self, app: &mut App) {
1145        (self.vtable.dispose)(app, self.id)
1146    }
1147
1148    // ---- the position of this route in its navigator's history ----
1149
1150    /// Whether this route is the top-most route on the navigator.
1151    ///
1152    /// If this is true, then [`is_active`](Self::is_active) is also true.
1153    pub fn is_current(self, app: &App) -> bool {
1154        let Some(navigator) = self.navigator(app) else {
1155            return false;
1156        };
1157        match navigator.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate) {
1158            None => false,
1159            Some(entry) => app.get(entry).route == self,
1160        }
1161    }
1162
1163    /// Whether this route is the bottom-most active route on the navigator.
1164    ///
1165    /// If [`is_first`](Self::is_first) and [`is_current`](Self::is_current) are both true then
1166    /// this is the only route on the navigator.
1167    pub fn is_first(self, app: &App) -> bool {
1168        let Some(navigator) = self.navigator(app) else {
1169            return false;
1170        };
1171        match navigator.first_route_entry_where_or_null(app, RouteEntry::is_present_predicate) {
1172            None => false,
1173            Some(entry) => app.get(entry).route == self,
1174        }
1175    }
1176
1177    /// Whether there is at least one active route underneath this route.
1178    pub fn has_active_route_below(self, app: &App) -> bool {
1179        let Some(navigator) = self.navigator(app) else {
1180            return false;
1181        };
1182        for entry in navigator.history_entries(app) {
1183            if app.get(entry).route == self {
1184                return false;
1185            }
1186            if RouteEntry::is_present_predicate(app, entry) {
1187                return true;
1188            }
1189        }
1190        false
1191    }
1192
1193    /// Whether this route is on the navigator.
1194    ///
1195    /// If the route is not only active, but also the current route (the top-most route), then
1196    /// [`is_current`](Self::is_current) will also be true. If it is the first route (the
1197    /// bottom-most route), then [`is_first`](Self::is_first) will also be true.
1198    pub fn is_active(self, app: &App) -> bool {
1199        let Some(navigator) = self.navigator(app) else {
1200            return false;
1201        };
1202        navigator
1203            .first_route_entry_where_or_null(app, move |app, entry| app.get(entry).route == self)
1204            .is_some_and(|entry| RouteEntry::is_present_predicate(app, entry))
1205    }
1206}
1207
1208// ---------------------------------------------------------------------------------------------
1209// NavigatorObserver
1210
1211/// The fields Dart's `NavigatorObserver` keeps in its `Expando`; every observer carries this
1212/// bag under the field `navigator_observer`.
1213#[derive(Default)]
1214pub struct NavigatorObserverData {
1215    navigator: Option<Handle<NavigatorState>>,
1216}
1217
1218impl NavigatorObserverData {
1219    /// An observer that is not observing a navigator yet.
1220    pub fn new() -> NavigatorObserverData {
1221        NavigatorObserverData::default()
1222    }
1223}
1224
1225/// The accessors [`NavigatorObserver`] asks for, for a struct whose bag is the field
1226/// `navigator_observer`.
1227#[macro_export]
1228macro_rules! navigator_observer_accessors {
1229    () => {
1230        fn navigator_observer_data(
1231            self: ::waft_foundation::Handle<Self>,
1232            app: &::waft_foundation::App,
1233        ) -> &$crate::NavigatorObserverData {
1234            &app.get(self).navigator_observer
1235        }
1236
1237        fn navigator_observer_data_mut(
1238            self: ::waft_foundation::Handle<Self>,
1239            app: &mut ::waft_foundation::App,
1240        ) -> &mut $crate::NavigatorObserverData {
1241            &mut app.get_mut(self).navigator_observer
1242        }
1243    };
1244}
1245
1246/// An interface for observing the behavior of a [`Navigator`].
1247pub trait NavigatorObserver: Sized + 'static {
1248    /// Dart's `NavigatorObserver._navigators` entry, held under the field `navigator_observer`
1249    /// ([`navigator_observer_accessors!`](crate::navigator_observer_accessors)).
1250    fn navigator_observer_data(self: Handle<Self>, app: &App) -> &NavigatorObserverData;
1251
1252    /// See [`navigator_observer_data`](Self::navigator_observer_data).
1253    fn navigator_observer_data_mut(self: Handle<Self>, app: &mut App)
1254    -> &mut NavigatorObserverData;
1255
1256    /// This observer as the erased [`AnyNavigatorObserver`].
1257    fn as_observer(self: Handle<Self>) -> AnyNavigatorObserver {
1258        AnyNavigatorObserver {
1259            id: self.id(),
1260            vtable: const { &NavigatorObserverVTable::of::<Self>() },
1261        }
1262    }
1263
1264    /// The navigator that the observer is observing, if any.
1265    fn navigator(self: Handle<Self>, app: &App) -> Option<Handle<NavigatorState>> {
1266        self.navigator_observer_data(app).navigator
1267    }
1268
1269    /// The [`Navigator`] pushed `route`.
1270    ///
1271    /// The route immediately below that one, and thus the previously active route, is
1272    /// `previous_route`.
1273    fn did_push(
1274        self: Handle<Self>,
1275        app: &mut App,
1276        route: AnyRoute,
1277        previous_route: Option<AnyRoute>,
1278    ) {
1279        let _ = (app, route, previous_route);
1280    }
1281
1282    /// The [`Navigator`] popped `route`.
1283    ///
1284    /// The route immediately below that one, and thus the newly active route, is
1285    /// `previous_route`.
1286    fn did_pop(
1287        self: Handle<Self>,
1288        app: &mut App,
1289        route: AnyRoute,
1290        previous_route: Option<AnyRoute>,
1291    ) {
1292        let _ = (app, route, previous_route);
1293    }
1294
1295    /// The [`Navigator`] removed `route`.
1296    ///
1297    /// If only one route is being removed, then the route immediately below that one, if any,
1298    /// is `previous_route`.
1299    ///
1300    /// If multiple routes are being removed, then the route below the bottommost route being
1301    /// removed, if any, is `previous_route`, and this method will be called once for each
1302    /// removed route, from the topmost route to the bottommost route.
1303    fn did_remove(
1304        self: Handle<Self>,
1305        app: &mut App,
1306        route: AnyRoute,
1307        previous_route: Option<AnyRoute>,
1308    ) {
1309        let _ = (app, route, previous_route);
1310    }
1311
1312    /// The [`Navigator`] replaced `old_route` with `new_route`.
1313    fn did_replace(
1314        self: Handle<Self>,
1315        app: &mut App,
1316        new_route: Option<AnyRoute>,
1317        old_route: Option<AnyRoute>,
1318    ) {
1319        let _ = (app, new_route, old_route);
1320    }
1321
1322    /// The top most route has changed.
1323    ///
1324    /// The `top_route` is the new top most route. This can be a new route pushed on top of the
1325    /// screen, or an existing route that becomes the new top-most route because the previous
1326    /// top-most route has been popped.
1327    ///
1328    /// The `previous_top_route` was the top most route before the change.
1329    fn did_change_top(
1330        self: Handle<Self>,
1331        app: &mut App,
1332        top_route: AnyRoute,
1333        previous_top_route: Option<AnyRoute>,
1334    ) {
1335        let _ = (app, top_route, previous_top_route);
1336    }
1337
1338    /// The [`Navigator`]'s routes are being moved by a user gesture.
1339    ///
1340    /// For example, this is called when an iOS back gesture starts, and is used to disable hero
1341    /// animations during such interactions.
1342    fn did_start_user_gesture(
1343        self: Handle<Self>,
1344        app: &mut App,
1345        route: AnyRoute,
1346        previous_route: Option<AnyRoute>,
1347    ) {
1348        let _ = (app, route, previous_route);
1349    }
1350
1351    /// User gesture is no longer controlling the [`Navigator`].
1352    ///
1353    /// Paired with an earlier call to [`did_start_user_gesture`](Self::did_start_user_gesture).
1354    fn did_stop_user_gesture(self: Handle<Self>, app: &mut App) {
1355        let _ = app;
1356    }
1357}
1358
1359/// The vtable of an erased [`AnyNavigatorObserver`].
1360struct NavigatorObserverVTable {
1361    type_name: fn() -> &'static str,
1362    data: fn(&App, HandleId) -> &NavigatorObserverData,
1363    data_mut: fn(&mut App, HandleId) -> &mut NavigatorObserverData,
1364    did_push: fn(&mut App, HandleId, AnyRoute, Option<AnyRoute>),
1365    did_pop: fn(&mut App, HandleId, AnyRoute, Option<AnyRoute>),
1366    did_remove: fn(&mut App, HandleId, AnyRoute, Option<AnyRoute>),
1367    did_replace: fn(&mut App, HandleId, Option<AnyRoute>, Option<AnyRoute>),
1368    did_change_top: fn(&mut App, HandleId, AnyRoute, Option<AnyRoute>),
1369    did_start_user_gesture: fn(&mut App, HandleId, AnyRoute, Option<AnyRoute>),
1370    did_stop_user_gesture: fn(&mut App, HandleId),
1371}
1372
1373impl NavigatorObserverVTable {
1374    const fn of<O: NavigatorObserver>() -> NavigatorObserverVTable {
1375        NavigatorObserverVTable {
1376            type_name: std::any::type_name::<O>,
1377            data: |app, id| O::navigator_observer_data(resolve(id), app),
1378            data_mut: |app, id| O::navigator_observer_data_mut(resolve(id), app),
1379            did_push: |app, id, route, previous| O::did_push(resolve(id), app, route, previous),
1380            did_pop: |app, id, route, previous| O::did_pop(resolve(id), app, route, previous),
1381            did_remove: |app, id, route, previous| O::did_remove(resolve(id), app, route, previous),
1382            did_replace: |app, id, new_route, old_route| {
1383                O::did_replace(resolve(id), app, new_route, old_route)
1384            },
1385            did_change_top: |app, id, top, previous_top| {
1386                O::did_change_top(resolve(id), app, top, previous_top)
1387            },
1388            did_start_user_gesture: |app, id, route, previous| {
1389                O::did_start_user_gesture(resolve(id), app, route, previous)
1390            },
1391            did_stop_user_gesture: |app, id| O::did_stop_user_gesture(resolve(id), app),
1392        }
1393    }
1394}
1395
1396/// Erased [`NavigatorObserver`]: what [`Navigator::observers`] holds.
1397#[derive(Clone, Copy)]
1398pub struct AnyNavigatorObserver {
1399    id: HandleId,
1400    vtable: &'static NavigatorObserverVTable,
1401}
1402
1403/// A field Dart types as the erased object, kept: AnyNavigatorObserver with its count.
1404pub type NavigatorObserverRef = Retained<AnyNavigatorObserver>;
1405
1406waft_foundation::erased_handle!(AnyNavigatorObserver: NavigatorObserver => NavigatorObserver::as_observer);
1407
1408impl Debug for AnyNavigatorObserver {
1409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
1411    }
1412}
1413
1414impl AnyNavigatorObserver {
1415    /// The arena id behind this handle.
1416    pub fn id(self) -> HandleId {
1417        self.id
1418    }
1419
1420    /// Dart's `observer as T`: the typed handle when this observer is a `T`, else `None`.
1421    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
1422        app.handle::<T>(self.id)
1423    }
1424
1425    /// See [`NavigatorObserver::navigator`].
1426    pub fn navigator(self, app: &App) -> Option<Handle<NavigatorState>> {
1427        (self.vtable.data)(app, self.id).navigator
1428    }
1429
1430    fn set_navigator(self, app: &mut App, navigator: Option<Handle<NavigatorState>>) {
1431        (self.vtable.data_mut)(app, self.id).navigator = navigator;
1432    }
1433
1434    /// See [`NavigatorObserver::did_push`].
1435    pub fn did_push(self, app: &mut App, route: AnyRoute, previous_route: Option<AnyRoute>) {
1436        (self.vtable.did_push)(app, self.id, route, previous_route)
1437    }
1438
1439    /// See [`NavigatorObserver::did_pop`].
1440    pub fn did_pop(self, app: &mut App, route: AnyRoute, previous_route: Option<AnyRoute>) {
1441        (self.vtable.did_pop)(app, self.id, route, previous_route)
1442    }
1443
1444    /// See [`NavigatorObserver::did_remove`].
1445    pub fn did_remove(self, app: &mut App, route: AnyRoute, previous_route: Option<AnyRoute>) {
1446        (self.vtable.did_remove)(app, self.id, route, previous_route)
1447    }
1448
1449    /// See [`NavigatorObserver::did_replace`].
1450    pub fn did_replace(
1451        self,
1452        app: &mut App,
1453        new_route: Option<AnyRoute>,
1454        old_route: Option<AnyRoute>,
1455    ) {
1456        (self.vtable.did_replace)(app, self.id, new_route, old_route)
1457    }
1458
1459    /// See [`NavigatorObserver::did_change_top`].
1460    pub fn did_change_top(
1461        self,
1462        app: &mut App,
1463        top_route: AnyRoute,
1464        previous_top_route: Option<AnyRoute>,
1465    ) {
1466        (self.vtable.did_change_top)(app, self.id, top_route, previous_top_route)
1467    }
1468
1469    /// See [`NavigatorObserver::did_start_user_gesture`].
1470    pub fn did_start_user_gesture(
1471        self,
1472        app: &mut App,
1473        route: AnyRoute,
1474        previous_route: Option<AnyRoute>,
1475    ) {
1476        (self.vtable.did_start_user_gesture)(app, self.id, route, previous_route)
1477    }
1478
1479    /// See [`NavigatorObserver::did_stop_user_gesture`].
1480    pub fn did_stop_user_gesture(self, app: &mut App) {
1481        (self.vtable.did_stop_user_gesture)(app, self.id)
1482    }
1483}
1484
1485// ---------------------------------------------------------------------------------------------
1486// HeroControllerScope
1487
1488/// An inherited widget to host a hero controller.
1489///
1490/// The hosted hero controller will be picked up by the navigator in the [`child`](Self::child)
1491/// subtree. Once a navigator picks up this controller, the navigator will bar any navigator
1492/// below its subtree from receiving this controller.
1493///
1494/// The hero controller inside the [`HeroControllerScope`] can only subscribe to one navigator at
1495/// a time.
1496#[derive(Debug)]
1497pub struct HeroControllerScope {
1498    /// See [`Widget::key`](crate::Widget::key).
1499    pub key: Option<KeyRef>,
1500    /// The hero controller that is hosted inside this widget.
1501    pub controller: Option<Ref<HeroController>>,
1502    /// The widget below this widget in the tree.
1503    pub child: WidgetRef,
1504}
1505
1506impl HeroControllerScope {
1507    /// Creates a widget to host the input `controller`.
1508    #[cfg_attr(debug_assertions, track_caller)]
1509    pub fn new<K>(
1510        controller: Ref<HeroController>,
1511        child: impl IntoWidget<K>,
1512    ) -> HeroControllerScope {
1513        HeroControllerScope {
1514            key: None,
1515            controller: Some(controller),
1516            child: child.into_widget(),
1517        }
1518    }
1519
1520    /// Creates a widget to prevent the subtree from receiving the hero controller above.
1521    #[cfg_attr(debug_assertions, track_caller)]
1522    pub fn none<K>(child: impl IntoWidget<K>) -> HeroControllerScope {
1523        HeroControllerScope {
1524            key: None,
1525            controller: None,
1526            child: child.into_widget(),
1527        }
1528    }
1529
1530    /// Dart `HeroControllerScope(key:)`.
1531    pub fn key(mut self, key: KeyRef) -> HeroControllerScope {
1532        self.key = Some(key);
1533        self
1534    }
1535
1536    /// Retrieves the [`HeroController`] from the closest [`HeroControllerScope`] ancestor, or
1537    /// `None` if none exists.
1538    ///
1539    /// Calling this method will create a dependency on the closest [`HeroControllerScope`] in
1540    /// the `context`, if there is one.
1541    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<HeroController>> {
1542        context
1543            .depend_on_inherited_widget_of_exact_type::<HeroControllerScope>(app)
1544            .and_then(|host| host.controller.handle())
1545    }
1546
1547    /// Retrieves the [`HeroController`] from the closest [`HeroControllerScope`] ancestor.
1548    ///
1549    /// Panics if no ancestor is found.
1550    pub fn of(app: &mut App, context: BuildContext) -> Handle<HeroController> {
1551        HeroControllerScope::maybe_of(app, context).expect(
1552            "HeroControllerScope.of() was called with a context that does not contain a \
1553             HeroControllerScope widget.",
1554        )
1555    }
1556}
1557
1558impl InheritedWidget for HeroControllerScope {
1559    fn key(&self) -> Option<&KeyRef> {
1560        self.key.as_ref()
1561    }
1562
1563    fn child(&self) -> &WidgetRef {
1564        &self.child
1565    }
1566
1567    fn update_should_notify(&self, old_widget: &HeroControllerScope) -> bool {
1568        old_widget.controller != self.controller
1569    }
1570}
1571
1572// ---------------------------------------------------------------------------------------------
1573// RouteTransitionRecord and TransitionDelegate
1574
1575/// A [`Route`] wrapper interface that can be staged for [`TransitionDelegate`] to decide how its
1576/// underlying route should transition on or off screen.
1577///
1578/// Dart's `abstract class RouteTransitionRecord`; the record is the [`RouteEntry`] the navigator
1579/// keeps, so this is the trait that entry implements.
1580pub trait RouteTransitionRecord {
1581    /// Retrieves the wrapped [`Route`].
1582    fn route(self: Handle<Self>, app: &App) -> AnyRoute
1583    where
1584        Self: Sized;
1585
1586    /// Whether this route is waiting for the decision on how to enter the screen.
1587    ///
1588    /// If this property is true, this route requires an explicit decision on how to transition
1589    /// into the screen. Such a decision should be made in [`TransitionDelegate::resolve`].
1590    fn is_waiting_for_entering_decision(self: Handle<Self>, app: &App) -> bool
1591    where
1592        Self: Sized;
1593
1594    /// Whether this route is waiting for the decision on how to exit the screen.
1595    ///
1596    /// If this property is true, this route requires an explicit decision on how to transition
1597    /// off the screen. Such a decision should be made in [`TransitionDelegate::resolve`].
1598    fn is_waiting_for_exiting_decision(self: Handle<Self>, app: &App) -> bool
1599    where
1600        Self: Sized;
1601
1602    /// Marks the route to be pushed with transition.
1603    fn mark_for_push(self: Handle<Self>, app: &mut App)
1604    where
1605        Self: Sized;
1606
1607    /// Marks the route to be added without transition.
1608    fn mark_for_add(self: Handle<Self>, app: &mut App)
1609    where
1610        Self: Sized;
1611
1612    /// Marks the route to be popped with transition.
1613    fn mark_for_pop(self: Handle<Self>, app: &mut App, result: RouteResult)
1614    where
1615        Self: Sized;
1616
1617    /// Marks the route to be completed without transition.
1618    fn mark_for_complete(self: Handle<Self>, app: &mut App, result: RouteResult)
1619    where
1620        Self: Sized;
1621}
1622
1623/// A shared [`TransitionDelegate`].
1624pub type TransitionDelegateRef = Rc<dyn TransitionDelegate>;
1625
1626/// The delegate that decides how pages added and removed from [`Navigator::pages`] transition in
1627/// or out of the screen.
1628///
1629/// This trait implements the API to be called by [`Navigator`] when it requires explicit
1630/// decisions on how the routes transition on or off the screen.
1631///
1632/// To make route transition decisions, an implementor implements [`resolve`](Self::resolve).
1633///
1634/// See also:
1635///
1636///  * [`Navigator::transition_delegate`], which uses this trait to make route transition
1637///    decisions.
1638///  * [`DefaultTransitionDelegate`], which implements the default way to decide how routes
1639///    transition in or out of the screen.
1640pub trait TransitionDelegate: 'static {
1641    /// A method that will be called by the [`Navigator`] to decide how routes transition in or
1642    /// out of the screen when [`Navigator::pages`] is updated.
1643    ///
1644    /// The `new_page_route_history` list contains all page-based routes in the order that will
1645    /// be on the navigator's history stack after this update completes. If a route in it has
1646    /// [`RouteTransitionRecord::is_waiting_for_entering_decision`] set to true, this route
1647    /// requires an explicit decision on how it should transition onto the navigator. To make a
1648    /// decision, call [`RouteTransitionRecord::mark_for_push`] or
1649    /// [`RouteTransitionRecord::mark_for_add`].
1650    ///
1651    /// `location_to_exiting_page_route` contains the page-based routes that are removed from the
1652    /// routes history after the page update. This map records page-based routes to be removed
1653    /// with the location of the route in the original route history before the update. The keys
1654    /// are the locations represented by the page-based routes that are directly below the
1655    /// removed routes, and the values are the page-based routes to be removed. The location is
1656    /// `None` if the route to be removed is the bottom-most route.
1657    ///
1658    /// `page_route_to_pageless_routes` records the page-based routes and their associated
1659    /// pageless routes.
1660    ///
1661    /// Once all the decisions have been made, this method must merge the removed routes (whether
1662    /// or not they require decisions) and `new_page_route_history` and return the merged result.
1663    /// The return list must preserve the same order of routes in `new_page_route_history`; the
1664    /// removed routes can be inserted into the return list freely as long as all of them are
1665    /// included.
1666    fn resolve(
1667        &self,
1668        app: &mut App,
1669        new_page_route_history: &[Handle<RouteEntry>],
1670        location_to_exiting_page_route: &HashMap<Option<Handle<RouteEntry>>, Handle<RouteEntry>>,
1671        page_route_to_pageless_routes: &HashMap<
1672            Option<Handle<RouteEntry>>,
1673            Vec<Handle<RouteEntry>>,
1674        >,
1675    ) -> Vec<Handle<RouteEntry>>;
1676}
1677
1678/// Dart's `TransitionDelegate._transition`: [`resolve`](TransitionDelegate::resolve) plus the
1679/// integrity check of the decisions that were made.
1680fn transition(
1681    delegate: &dyn TransitionDelegate,
1682    app: &mut App,
1683    new_page_route_history: &[Handle<RouteEntry>],
1684    location_to_exiting_page_route: &HashMap<Option<Handle<RouteEntry>>, Handle<RouteEntry>>,
1685    page_route_to_pageless_routes: &HashMap<Option<Handle<RouteEntry>>, Vec<Handle<RouteEntry>>>,
1686) -> Vec<Handle<RouteEntry>> {
1687    let results = delegate.resolve(
1688        app,
1689        new_page_route_history,
1690        location_to_exiting_page_route,
1691        page_route_to_pageless_routes,
1692    );
1693    // Verifies the integrity after the decisions have been made.
1694    //
1695    // Here are the rules:
1696    // - All the entering routes in new_page_route_history must either be pushed or added.
1697    // - All the exiting routes in location_to_exiting_page_route must either be popped,
1698    //   completed or removed.
1699    // - All the pageless routes that belong to exiting routes must either be popped, completed
1700    //   or removed.
1701    // - All the entering routes in the result must preserve the same order as the entering
1702    //   routes in new_page_route_history, and the result must contain all exiting routes.
1703    if cfg!(debug_assertions) {
1704        let mut exiting_page_routes: HashSet<Handle<RouteEntry>> =
1705            location_to_exiting_page_route.values().copied().collect();
1706        // Firstly, verifies all exiting routes have been marked.
1707        for exiting_page_route in &exiting_page_routes {
1708            assert!(!app.get(*exiting_page_route).is_waiting_for_exiting_decision);
1709            if let Some(pageless) = page_route_to_pageless_routes.get(&Some(*exiting_page_route)) {
1710                for pageless_route in pageless {
1711                    assert!(!app.get(*pageless_route).is_waiting_for_exiting_decision);
1712                }
1713            }
1714        }
1715        // Secondly, verifies the order of results matches new_page_route_history and contains
1716        // all the exiting routes.
1717        let mut index_of_next_route_in_new_history = 0;
1718        for route_entry in &results {
1719            let entry = app.get(*route_entry);
1720            assert!(
1721                entry.current_state != RouteLifecycle::Staging
1722                    && !entry.is_waiting_for_exiting_decision
1723            );
1724            if index_of_next_route_in_new_history >= new_page_route_history.len()
1725                || *route_entry != new_page_route_history[index_of_next_route_in_new_history]
1726            {
1727                assert!(exiting_page_routes.contains(route_entry));
1728                exiting_page_routes.remove(route_entry);
1729            } else {
1730                index_of_next_route_in_new_history += 1;
1731            }
1732        }
1733        assert!(
1734            index_of_next_route_in_new_history == new_page_route_history.len()
1735                && exiting_page_routes.is_empty(),
1736            "The merged result from the transition delegate's resolve does not include all \
1737             required routes. Do you remember to merge all exiting routes?"
1738        );
1739    }
1740    results
1741}
1742
1743/// The default implementation of [`TransitionDelegate`] that the [`Navigator`] will use if its
1744/// [`Navigator::transition_delegate`] is not specified.
1745///
1746/// This transition delegate follows two rules. Firstly, all the entering routes are placed on
1747/// top of the exiting routes if they are at the same location. Secondly, the top most route will
1748/// always transition with an animated transition. All the other routes below will either be
1749/// completed with [`AnyRoute::current_result`] or added without an animated transition.
1750#[derive(Debug, Default)]
1751pub struct DefaultTransitionDelegate;
1752
1753impl DefaultTransitionDelegate {
1754    /// Creates a default transition delegate.
1755    pub fn new() -> DefaultTransitionDelegate {
1756        DefaultTransitionDelegate
1757    }
1758}
1759
1760impl TransitionDelegate for DefaultTransitionDelegate {
1761    fn resolve(
1762        &self,
1763        app: &mut App,
1764        new_page_route_history: &[Handle<RouteEntry>],
1765        location_to_exiting_page_route: &HashMap<Option<Handle<RouteEntry>>, Handle<RouteEntry>>,
1766        page_route_to_pageless_routes: &HashMap<
1767            Option<Handle<RouteEntry>>,
1768            Vec<Handle<RouteEntry>>,
1769        >,
1770    ) -> Vec<Handle<RouteEntry>> {
1771        let mut results: Vec<Handle<RouteEntry>> = Vec::new();
1772
1773        // Handles the exiting route and its corresponding pageless routes at this location, then
1774        // recursively checks whether there is any other exiting route above it.
1775        fn handle_exiting_route(
1776            app: &mut App,
1777            results: &mut Vec<Handle<RouteEntry>>,
1778            location_to_exiting_page_route: &HashMap<
1779                Option<Handle<RouteEntry>>,
1780                Handle<RouteEntry>,
1781            >,
1782            page_route_to_pageless_routes: &HashMap<
1783                Option<Handle<RouteEntry>>,
1784                Vec<Handle<RouteEntry>>,
1785            >,
1786            location: Option<Handle<RouteEntry>>,
1787            is_last: bool,
1788        ) {
1789            let Some(exiting_page_route) = location_to_exiting_page_route.get(&location).copied()
1790            else {
1791                return;
1792            };
1793            if app.get(exiting_page_route).is_waiting_for_exiting_decision {
1794                let has_pageless_route =
1795                    page_route_to_pageless_routes.contains_key(&Some(exiting_page_route));
1796                let is_last_exiting_page_route = is_last
1797                    && !location_to_exiting_page_route.contains_key(&Some(exiting_page_route));
1798                let result = app.get(exiting_page_route).route.current_result(app);
1799                if is_last_exiting_page_route && !has_pageless_route {
1800                    exiting_page_route.mark_for_pop(app, result);
1801                } else {
1802                    exiting_page_route.mark_for_complete(app, result);
1803                }
1804                if has_pageless_route {
1805                    let pageless_routes =
1806                        page_route_to_pageless_routes[&Some(exiting_page_route)].clone();
1807                    let last = pageless_routes.last().copied();
1808                    for pageless_route in pageless_routes {
1809                        // It is possible that a pageless route that belongs to an exiting
1810                        // page-based route does not require an exiting decision. This can happen
1811                        // if the page list is updated right after a pop.
1812                        if app.get(pageless_route).is_waiting_for_exiting_decision {
1813                            let result = app.get(pageless_route).route.current_result(app);
1814                            if is_last_exiting_page_route && Some(pageless_route) == last {
1815                                pageless_route.mark_for_pop(app, result);
1816                            } else {
1817                                pageless_route.mark_for_complete(app, result);
1818                            }
1819                        }
1820                    }
1821                }
1822            }
1823            results.push(exiting_page_route);
1824
1825            // It is possible there is another exiting route above this one.
1826            handle_exiting_route(
1827                app,
1828                results,
1829                location_to_exiting_page_route,
1830                page_route_to_pageless_routes,
1831                Some(exiting_page_route),
1832                is_last,
1833            );
1834        }
1835
1836        // Handles exiting route in the beginning of list.
1837        handle_exiting_route(
1838            app,
1839            &mut results,
1840            location_to_exiting_page_route,
1841            page_route_to_pageless_routes,
1842            None,
1843            new_page_route_history.is_empty(),
1844        );
1845
1846        for page_route in new_page_route_history.iter().copied() {
1847            let is_last_iteration = new_page_route_history.last() == Some(&page_route);
1848            if app.get(page_route).current_state == RouteLifecycle::Staging {
1849                if !location_to_exiting_page_route.contains_key(&Some(page_route))
1850                    && is_last_iteration
1851                {
1852                    page_route.mark_for_push(app);
1853                } else {
1854                    page_route.mark_for_add(app);
1855                }
1856            }
1857            results.push(page_route);
1858            handle_exiting_route(
1859                app,
1860                &mut results,
1861                location_to_exiting_page_route,
1862                page_route_to_pageless_routes,
1863                Some(page_route),
1864                is_last_iteration,
1865            );
1866        }
1867        results
1868    }
1869}
1870
1871/// The default value of [`Navigator::route_traversal_edge_behavior`].
1872pub const K_DEFAULT_ROUTE_TRAVERSAL_EDGE_BEHAVIOR: TraversalEdgeBehavior =
1873    TraversalEdgeBehavior::ParentScope;
1874
1875/// The default value of [`Navigator::route_directional_traversal_edge_behavior`].
1876pub const K_DEFAULT_ROUTE_DIRECTIONAL_TRAVERSAL_EDGE_BEHAVIOR: TraversalEdgeBehavior =
1877    TraversalEdgeBehavior::Stop;
1878
1879// ---------------------------------------------------------------------------------------------
1880// Navigator
1881
1882/// A widget that manages a set of child widgets with a stack discipline.
1883///
1884/// Many apps have a navigator near the top of their widget hierarchy in order to display their
1885/// logical history using an [`Overlay`] with the most recently visited pages visually on top of
1886/// the older pages. Using this pattern lets the navigator visually transition from one page to
1887/// another by moving the widgets around in the overlay. Similarly, the navigator can be used to
1888/// show a dialog by positioning the dialog widget above the current page.
1889///
1890/// ## Using the Pages API
1891///
1892/// The [`Navigator`] will convert its [`pages`](Self::pages) into a stack of [`Route`]s if it is
1893/// provided. A change in `pages` will trigger an update to the stack of routes. To use this API,
1894/// implement [`Page`] and define a list of pages for `pages`. An
1895/// [`on_did_remove_page`](Self::on_did_remove_page) callback is also required to properly clean
1896/// up the input pages in case of a pop.
1897///
1898/// By default, the [`Navigator`] will use [`DefaultTransitionDelegate`] to decide how routes
1899/// transition in or out of the screen.
1900///
1901/// ## Using the Navigator API
1902///
1903/// The navigator manages a stack of [`Route`] objects and provides two ways for managing the
1904/// stack, the declarative API [`pages`](Self::pages) or the imperative API
1905/// [`push`](Navigator::push) and [`pop`](Navigator::pop).
1906pub struct Navigator {
1907    /// See [`Widget::key`](crate::Widget::key).
1908    pub key: Option<KeyRef>,
1909    /// The list of pages with which to populate the history.
1910    ///
1911    /// Pages are turned into routes using [`Page::create_route`] in a manner analogous to how
1912    /// [`on_generate_route`](Self::on_generate_route) turns [`RouteSettings`] into [`Route`]s.
1913    ///
1914    /// When this list is updated, the new list is compared to the previous list and the set of
1915    /// routes is updated accordingly.
1916    pub pages: Vec<PageRef>,
1917    /// Called when [`pop`](Navigator::pop) is invoked but the current [`Route`] corresponds to a
1918    /// [`Page`] found in the [`pages`](Self::pages) list.
1919    ///
1920    /// Dart's deprecated `onPopPage`; [`on_did_remove_page`](Self::on_did_remove_page) is its
1921    /// replacement.
1922    pub on_pop_page: Option<PopPageCallback>,
1923    /// Called when a [`Route`] created from a [`Page`] in [`pages`](Self::pages) is removed.
1924    ///
1925    /// This must update the pages list the next time it is passed into [`pages`](Self::pages) so
1926    /// that it no longer includes the input page.
1927    pub on_did_remove_page: Option<DidRemovePageCallback>,
1928    /// The delegate used for deciding how routes transition in or off the screen during the
1929    /// [`pages`](Self::pages) updates.
1930    pub transition_delegate: TransitionDelegateRef,
1931    /// The name of the first route to show.
1932    ///
1933    /// Defaults to [`Navigator::DEFAULT_ROUTE_NAME`].
1934    ///
1935    /// If this string contains any `/` characters, then the string is split on those characters
1936    /// and substrings from the start of the string up to each such character are, in turn, used
1937    /// as routes to push.
1938    pub initial_route: Option<String>,
1939    /// Called to generate a route for a given [`RouteSettings`].
1940    pub on_generate_route: Option<RouteFactory>,
1941    /// Called when [`on_generate_route`](Self::on_generate_route) fails to generate a route.
1942    ///
1943    /// This callback is typically used for error handling. It receives the [`RouteSettings`] and
1944    /// must return a non-`None` [`Route`].
1945    pub on_unknown_route: Option<RouteFactory>,
1946    /// A list of observers for this navigator.
1947    pub observers: Vec<NavigatorObserverRef>,
1948    /// Restoration ID to save and restore the state of the navigator, including its history.
1949    ///
1950    /// If a restoration ID is provided, the navigator will persist its internal state (including
1951    /// the route history) to the surrounding `RestorationScope` and restore it during state
1952    /// restoration.
1953    pub restoration_scope_id: Option<String>,
1954    /// Controls the transfer of focus beyond the first and the last items of a focus scope that
1955    /// defines focus traversal of widgets within a route.
1956    pub route_traversal_edge_behavior: TraversalEdgeBehavior,
1957    /// Controls the transfer of focus beyond the first and the last items of a focus scope that
1958    /// defines focus traversal of widgets within a route, in a directional traversal.
1959    pub route_directional_traversal_edge_behavior: TraversalEdgeBehavior,
1960    /// Called when the widget is created to generate the initial list of [`Route`] objects if
1961    /// [`initial_route`](Self::initial_route) is not `None`.
1962    ///
1963    /// Defaults to [`Navigator::default_generate_initial_routes`].
1964    pub on_generate_initial_routes: RouteListFactory,
1965    /// Whether this navigator should report route update message back to the engine when the
1966    /// top-most route changes.
1967    pub reports_route_update_to_engine: bool,
1968    /// The content will be clipped (or not) according to this option.
1969    ///
1970    /// Defaults to [`Clip::HardEdge`].
1971    pub clip_behavior: Clip,
1972    /// Whether or not the navigator and it's new topmost route should request focus when the new
1973    /// route is pushed onto the navigator.
1974    ///
1975    /// Defaults to true.
1976    pub request_focus: bool,
1977}
1978
1979impl Navigator {
1980    /// The default name for the [`initial_route`](Self::initial_route).
1981    ///
1982    /// See also:
1983    ///
1984    ///  * `dart:ui.PlatformDispatcher.defaultRouteName`, which reflects the route that the
1985    ///    application was started with.
1986    pub const DEFAULT_ROUTE_NAME: &'static str = "/";
1987
1988    /// Creates a widget that maintains a stack-based history of child widgets; Dart's named
1989    /// arguments are the setters.
1990    pub fn new() -> Navigator {
1991        Navigator::default()
1992    }
1993
1994    /// Dart `Navigator(key:)`.
1995    pub fn key(mut self, key: KeyRef) -> Navigator {
1996        self.key = Some(key);
1997        self
1998    }
1999
2000    /// Dart `Navigator(pages:)`.
2001    pub fn pages(mut self, pages: impl IntoIterator<Item = PageRef>) -> Navigator {
2002        self.pages = pages.into_iter().collect();
2003        self
2004    }
2005
2006    /// Dart `Navigator(onPopPage:)`.
2007    pub fn on_pop_page(
2008        mut self,
2009        on_pop_page: impl Fn(&mut App, AnyRoute, RouteResult) -> bool + 'static,
2010    ) -> Navigator {
2011        self.on_pop_page = Some(Rc::new(on_pop_page));
2012        self
2013    }
2014
2015    /// Dart `Navigator(onDidRemovePage:)`.
2016    pub fn on_did_remove_page(
2017        mut self,
2018        on_did_remove_page: impl Fn(&mut App, PageRef) + 'static,
2019    ) -> Navigator {
2020        self.on_did_remove_page = Some(Rc::new(on_did_remove_page));
2021        self
2022    }
2023
2024    /// Dart `Navigator(transitionDelegate:)`.
2025    pub fn transition_delegate(mut self, delegate: TransitionDelegateRef) -> Navigator {
2026        self.transition_delegate = delegate;
2027        self
2028    }
2029
2030    /// Dart `Navigator(initialRoute:)`.
2031    pub fn initial_route(mut self, initial_route: impl Into<String>) -> Navigator {
2032        self.initial_route = Some(initial_route.into());
2033        self
2034    }
2035
2036    /// Dart `Navigator(onGenerateRoute:)`.
2037    pub fn on_generate_route(
2038        mut self,
2039        on_generate_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
2040    ) -> Navigator {
2041        self.on_generate_route = Some(Rc::new(on_generate_route));
2042        self
2043    }
2044
2045    /// Dart `Navigator(onUnknownRoute:)`.
2046    pub fn on_unknown_route(
2047        mut self,
2048        on_unknown_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
2049    ) -> Navigator {
2050        self.on_unknown_route = Some(Rc::new(on_unknown_route));
2051        self
2052    }
2053
2054    /// Dart `Navigator(observers:)`.
2055    pub fn observers(
2056        mut self,
2057        observers: impl IntoIterator<Item = NavigatorObserverRef>,
2058    ) -> Navigator {
2059        self.observers = observers.into_iter().collect();
2060        self
2061    }
2062
2063    /// Dart `Navigator(restorationScopeId:)`.
2064    pub fn restoration_scope_id(mut self, restoration_scope_id: impl Into<String>) -> Navigator {
2065        self.restoration_scope_id = Some(restoration_scope_id.into());
2066        self
2067    }
2068
2069    /// Dart `Navigator(routeTraversalEdgeBehavior:)`.
2070    pub fn route_traversal_edge_behavior(mut self, behavior: TraversalEdgeBehavior) -> Navigator {
2071        self.route_traversal_edge_behavior = behavior;
2072        self
2073    }
2074
2075    /// Dart `Navigator(routeDirectionalTraversalEdgeBehavior:)`.
2076    pub fn route_directional_traversal_edge_behavior(
2077        mut self,
2078        behavior: TraversalEdgeBehavior,
2079    ) -> Navigator {
2080        self.route_directional_traversal_edge_behavior = behavior;
2081        self
2082    }
2083
2084    /// Dart `Navigator(onGenerateInitialRoutes:)`.
2085    pub fn on_generate_initial_routes(
2086        mut self,
2087        on_generate_initial_routes: impl Fn(&mut App, Handle<NavigatorState>, &str) -> Vec<RouteRef>
2088        + 'static,
2089    ) -> Navigator {
2090        self.on_generate_initial_routes = Rc::new(on_generate_initial_routes);
2091        self
2092    }
2093
2094    /// Dart `Navigator(reportsRouteUpdateToEngine:)`.
2095    pub fn reports_route_update_to_engine(mut self, value: bool) -> Navigator {
2096        self.reports_route_update_to_engine = value;
2097        self
2098    }
2099
2100    /// Dart `Navigator(clipBehavior:)`.
2101    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Navigator {
2102        self.clip_behavior = clip_behavior;
2103        self
2104    }
2105
2106    /// Dart `Navigator(requestFocus:)`.
2107    pub fn request_focus(mut self, request_focus: bool) -> Navigator {
2108        self.request_focus = request_focus;
2109        self
2110    }
2111
2112    /// Dart's `Navigator._usingPagesAPI`.
2113    fn using_pages_api(&self) -> bool {
2114        !self.pages.is_empty()
2115    }
2116
2117    // ---- the static helpers ----
2118
2119    /// The state from the closest instance of this class that encloses the given context.
2120    ///
2121    /// If `root_navigator` is set to true, the state from the furthest instance of this class is
2122    /// given instead. Useful for pushing contents above all subsequent instances of
2123    /// [`Navigator`].
2124    ///
2125    /// Panics if there is no [`Navigator`] in the given context.
2126    pub fn of(
2127        app: &mut App,
2128        context: BuildContext,
2129        root_navigator: bool,
2130    ) -> Handle<NavigatorState> {
2131        Navigator::maybe_of(app, context, root_navigator).expect(
2132            "Navigator operation requested with a context that does not include a Navigator. The \
2133             context used to push or pop routes from the Navigator must be that of a widget that \
2134             is a descendant of a Navigator widget.",
2135        )
2136    }
2137
2138    /// The state from the closest instance of this class that encloses the given context, if any.
2139    ///
2140    /// If `root_navigator` is set to true, the state from the furthest instance of this class is
2141    /// given instead.
2142    pub fn maybe_of(
2143        app: &mut App,
2144        context: BuildContext,
2145        root_navigator: bool,
2146    ) -> Option<Handle<NavigatorState>> {
2147        let navigator = context.state_handle::<NavigatorState>(app);
2148        if root_navigator {
2149            context
2150                .find_root_ancestor_state_of_type::<NavigatorState>(app)
2151                .or(navigator)
2152        } else {
2153            navigator.or_else(|| context.find_ancestor_state_of_type::<NavigatorState>(app))
2154        }
2155    }
2156
2157    /// Push a named route onto the navigator that most tightly encloses the given context.
2158    ///
2159    /// Returns a future that completes to the `result` value passed to [`pop`](Self::pop) when
2160    /// the pushed route is popped off the navigator.
2161    pub fn push_named(
2162        app: &mut App,
2163        context: BuildContext,
2164        route_name: &str,
2165        arguments: Option<Rc<dyn Any>>,
2166    ) -> CompleterFuture<RouteResult> {
2167        Navigator::of(app, context, false).push_named(app, route_name, arguments)
2168    }
2169
2170    /// Push a named route onto the navigator that most tightly encloses the given context, and
2171    /// return its restoration ID.
2172    pub fn restorable_push_named(
2173        app: &mut App,
2174        context: BuildContext,
2175        route_name: &str,
2176        arguments: Option<RestorationData>,
2177    ) -> String {
2178        Navigator::of(app, context, false).restorable_push_named(app, route_name, arguments)
2179    }
2180
2181    /// Replace the current route of the navigator that most tightly encloses the given context by
2182    /// pushing the route named `route_name` and then disposing the previous route once the
2183    /// animation has completed.
2184    pub fn push_replacement_named(
2185        app: &mut App,
2186        context: BuildContext,
2187        route_name: &str,
2188        result: RouteResult,
2189        arguments: Option<Rc<dyn Any>>,
2190    ) -> CompleterFuture<RouteResult> {
2191        Navigator::of(app, context, false)
2192            .push_replacement_named(app, route_name, result, arguments)
2193    }
2194
2195    /// The restorable version of [`push_replacement_named`](Self::push_replacement_named).
2196    pub fn restorable_push_replacement_named(
2197        app: &mut App,
2198        context: BuildContext,
2199        route_name: &str,
2200        result: RouteResult,
2201        arguments: Option<RestorationData>,
2202    ) -> String {
2203        Navigator::of(app, context, false)
2204            .restorable_push_replacement_named(app, route_name, result, arguments)
2205    }
2206
2207    /// Pop the current route off the navigator that most tightly encloses the given context and
2208    /// push a named route in its place.
2209    pub fn pop_and_push_named(
2210        app: &mut App,
2211        context: BuildContext,
2212        route_name: &str,
2213        result: RouteResult,
2214        arguments: Option<Rc<dyn Any>>,
2215    ) -> CompleterFuture<RouteResult> {
2216        Navigator::of(app, context, false).pop_and_push_named(app, route_name, result, arguments)
2217    }
2218
2219    /// The restorable version of [`pop_and_push_named`](Self::pop_and_push_named).
2220    pub fn restorable_pop_and_push_named(
2221        app: &mut App,
2222        context: BuildContext,
2223        route_name: &str,
2224        result: RouteResult,
2225        arguments: Option<RestorationData>,
2226    ) -> String {
2227        Navigator::of(app, context, false)
2228            .restorable_pop_and_push_named(app, route_name, result, arguments)
2229    }
2230
2231    /// Push the route with the given name onto the navigator that most tightly encloses the
2232    /// given context, and then remove all the previous routes until the `predicate` returns true.
2233    pub fn push_named_and_remove_until(
2234        app: &mut App,
2235        context: BuildContext,
2236        new_route_name: &str,
2237        predicate: RoutePredicate,
2238        arguments: Option<Rc<dyn Any>>,
2239    ) -> CompleterFuture<RouteResult> {
2240        Navigator::of(app, context, false).push_named_and_remove_until(
2241            app,
2242            new_route_name,
2243            predicate,
2244            arguments,
2245        )
2246    }
2247
2248    /// The restorable version of
2249    /// [`push_named_and_remove_until`](Self::push_named_and_remove_until).
2250    pub fn restorable_push_named_and_remove_until(
2251        app: &mut App,
2252        context: BuildContext,
2253        new_route_name: &str,
2254        predicate: RoutePredicate,
2255        arguments: Option<RestorationData>,
2256    ) -> String {
2257        Navigator::of(app, context, false).restorable_push_named_and_remove_until(
2258            app,
2259            new_route_name,
2260            predicate,
2261            arguments,
2262        )
2263    }
2264
2265    /// Push the given route onto the navigator that most tightly encloses the given context.
2266    ///
2267    /// Returns a future that completes to the `result` value passed to [`pop`](Self::pop) when
2268    /// the pushed route is popped off the navigator.
2269    pub fn push(
2270        app: &mut App,
2271        context: BuildContext,
2272        route: RouteRef,
2273    ) -> CompleterFuture<RouteResult> {
2274        Navigator::of(app, context, false).push(app, route)
2275    }
2276
2277    /// Push a new route onto the navigator that most tightly encloses the given context, and
2278    /// return its restoration ID.
2279    pub fn restorable_push(
2280        app: &mut App,
2281        context: BuildContext,
2282        route_builder: RestorableRouteBuilder,
2283        arguments: Option<RestorationData>,
2284    ) -> String {
2285        Navigator::of(app, context, false).restorable_push(app, route_builder, arguments)
2286    }
2287
2288    /// Replace the current route of the navigator that most tightly encloses the given context by
2289    /// pushing the given route and then disposing the previous route.
2290    pub fn push_replacement(
2291        app: &mut App,
2292        context: BuildContext,
2293        new_route: RouteRef,
2294        result: RouteResult,
2295    ) -> CompleterFuture<RouteResult> {
2296        Navigator::of(app, context, false).push_replacement(app, new_route, result)
2297    }
2298
2299    /// The restorable version of [`push_replacement`](Self::push_replacement).
2300    pub fn restorable_push_replacement(
2301        app: &mut App,
2302        context: BuildContext,
2303        route_builder: RestorableRouteBuilder,
2304        result: RouteResult,
2305        arguments: Option<RestorationData>,
2306    ) -> String {
2307        Navigator::of(app, context, false).restorable_push_replacement(
2308            app,
2309            route_builder,
2310            result,
2311            arguments,
2312        )
2313    }
2314
2315    /// Push the given route onto the navigator that most tightly encloses the given context, and
2316    /// then remove all the previous routes until the `predicate` returns true.
2317    pub fn push_and_remove_until(
2318        app: &mut App,
2319        context: BuildContext,
2320        new_route: RouteRef,
2321        predicate: RoutePredicate,
2322    ) -> CompleterFuture<RouteResult> {
2323        Navigator::of(app, context, false).push_and_remove_until(app, new_route, predicate)
2324    }
2325
2326    /// The restorable version of [`push_and_remove_until`](Self::push_and_remove_until).
2327    pub fn restorable_push_and_remove_until(
2328        app: &mut App,
2329        context: BuildContext,
2330        new_route_builder: RestorableRouteBuilder,
2331        predicate: RoutePredicate,
2332        arguments: Option<RestorationData>,
2333    ) -> String {
2334        Navigator::of(app, context, false).restorable_push_and_remove_until(
2335            app,
2336            new_route_builder,
2337            predicate,
2338            arguments,
2339        )
2340    }
2341
2342    /// Replaces a route on the navigator that most tightly encloses the given context with a new
2343    /// route.
2344    pub fn replace(app: &mut App, context: BuildContext, old_route: AnyRoute, new_route: RouteRef) {
2345        Navigator::of(app, context, false).replace(app, old_route, new_route);
2346    }
2347
2348    /// The restorable version of [`replace`](Self::replace).
2349    pub fn restorable_replace(
2350        app: &mut App,
2351        context: BuildContext,
2352        old_route: AnyRoute,
2353        new_route_builder: RestorableRouteBuilder,
2354        arguments: Option<RestorationData>,
2355    ) -> String {
2356        Navigator::of(app, context, false).restorable_replace(
2357            app,
2358            old_route,
2359            new_route_builder,
2360            arguments,
2361        )
2362    }
2363
2364    /// Replaces a route on the navigator that most tightly encloses the given context with a new
2365    /// route. The route to be replaced is the one below the given `anchor_route`.
2366    pub fn replace_route_below(
2367        app: &mut App,
2368        context: BuildContext,
2369        anchor_route: AnyRoute,
2370        new_route: RouteRef,
2371    ) {
2372        Navigator::of(app, context, false).replace_route_below(app, anchor_route, new_route);
2373    }
2374
2375    /// The restorable version of [`replace_route_below`](Self::replace_route_below).
2376    pub fn restorable_replace_route_below(
2377        app: &mut App,
2378        context: BuildContext,
2379        anchor_route: AnyRoute,
2380        new_route_builder: RestorableRouteBuilder,
2381        arguments: Option<RestorationData>,
2382    ) -> String {
2383        Navigator::of(app, context, false).restorable_replace_route_below(
2384            app,
2385            anchor_route,
2386            new_route_builder,
2387            arguments,
2388        )
2389    }
2390
2391    /// Whether the navigator that most tightly encloses the given context can be popped.
2392    ///
2393    /// The initial route cannot be popped off the navigator, which implies that this function
2394    /// returns true only if popping the navigator would not remove the initial route.
2395    pub fn can_pop(app: &mut App, context: BuildContext) -> bool {
2396        match Navigator::maybe_of(app, context, false) {
2397            None => false,
2398            Some(navigator) => navigator.can_pop(app),
2399        }
2400    }
2401
2402    /// Consults the current route's [`AnyRoute::pop_disposition`] method, and acts accordingly,
2403    /// potentially popping the route as a result; returns whether the pop request should be
2404    /// considered handled.
2405    pub fn maybe_pop(app: &mut App, context: BuildContext, result: RouteResult) -> bool {
2406        Navigator::of(app, context, false).maybe_pop(app, result)
2407    }
2408
2409    /// Pop the top-most route off the navigator that most tightly encloses the given context.
2410    pub fn pop(app: &mut App, context: BuildContext, result: RouteResult) {
2411        Navigator::of(app, context, false).pop(app, result);
2412    }
2413
2414    /// Calls [`pop`](Self::pop) repeatedly on the navigator that most tightly encloses the given
2415    /// context until the predicate returns true.
2416    pub fn pop_until(app: &mut App, context: BuildContext, predicate: RoutePredicate) {
2417        Navigator::of(app, context, false).pop_until(app, predicate);
2418    }
2419
2420    /// Calls [`pop`](Self::pop) repeatedly until the predicate returns true, passing `result` to
2421    /// the last popped route.
2422    pub fn pop_until_with_result(
2423        app: &mut App,
2424        context: BuildContext,
2425        predicate: RoutePredicate,
2426        result: RouteResult,
2427    ) {
2428        Navigator::of(app, context, false).pop_until_with_result(app, predicate, result);
2429    }
2430
2431    /// Immediately remove `route` from the navigator that most tightly encloses the given
2432    /// context, and dispose of it.
2433    pub fn remove_route(
2434        app: &mut App,
2435        context: BuildContext,
2436        route: AnyRoute,
2437        result: RouteResult,
2438    ) {
2439        Navigator::of(app, context, false).remove_route(app, route, result);
2440    }
2441
2442    /// Immediately remove a route from the navigator that most tightly encloses the given
2443    /// context, and dispose of it. The route to be replaced is the one below the given
2444    /// `anchor_route`.
2445    pub fn remove_route_below(
2446        app: &mut App,
2447        context: BuildContext,
2448        anchor_route: AnyRoute,
2449        result: RouteResult,
2450    ) {
2451        Navigator::of(app, context, false).remove_route_below(app, anchor_route, result);
2452    }
2453
2454    /// Turn a route name into a set of [`Route`] objects.
2455    ///
2456    /// This is the default value of [`on_generate_initial_routes`](Self::on_generate_initial_routes),
2457    /// which is used if that value is not supplied.
2458    ///
2459    /// If the route name starts with `/` and is longer than one character, the name is split on
2460    /// `/` characters and each prefix is pushed in turn.
2461    pub fn default_generate_initial_routes(
2462        app: &mut App,
2463        navigator: Handle<NavigatorState>,
2464        initial_route_name: &str,
2465    ) -> Vec<RouteRef> {
2466        let mut result: Vec<Option<RouteRef>> = Vec::new();
2467        if initial_route_name.starts_with('/') && initial_route_name.len() > 1 {
2468            let initial_route_name = &initial_route_name[1..]; // strip leading '/'
2469            debug_assert_eq!(Navigator::DEFAULT_ROUTE_NAME, "/");
2470            result.push(navigator.route_named(app, Navigator::DEFAULT_ROUTE_NAME, None, true));
2471            if !initial_route_name.is_empty() {
2472                let mut route_name = String::new();
2473                for part in initial_route_name.split('/') {
2474                    route_name.push('/');
2475                    route_name.push_str(part);
2476                    result.push(navigator.route_named(app, &route_name, None, true));
2477                }
2478            }
2479            if result.last() == Some(&None) {
2480                for route in result.iter().flatten() {
2481                    route.dispose(app);
2482                }
2483                result.clear();
2484            }
2485        } else if initial_route_name != Navigator::DEFAULT_ROUTE_NAME {
2486            // If initialRouteName wasn't '/', then we try to get it with allowNull:true, so that
2487            // if that fails, we fall back to '/' (without allowNull:true, see below).
2488            result.push(navigator.route_named(app, initial_route_name, None, true));
2489        }
2490        // Null route might be a result of gap in initialRouteName.
2491        result.retain(Option::is_some);
2492        if result.is_empty() {
2493            result.push(navigator.route_named(app, Navigator::DEFAULT_ROUTE_NAME, None, false));
2494        }
2495        result.into_iter().flatten().collect()
2496    }
2497}
2498
2499impl Debug for Navigator {
2500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2501        f.debug_struct("Navigator")
2502            .field("pages", &self.pages)
2503            .field("initial_route", &self.initial_route)
2504            .field("restoration_scope_id", &self.restoration_scope_id)
2505            .finish_non_exhaustive()
2506    }
2507}
2508
2509impl Default for Navigator {
2510    fn default() -> Navigator {
2511        Navigator {
2512            key: None,
2513            pages: Vec::new(),
2514            on_pop_page: None,
2515            on_did_remove_page: None,
2516            transition_delegate: Rc::new(DefaultTransitionDelegate),
2517            initial_route: None,
2518            on_generate_route: None,
2519            on_unknown_route: None,
2520            observers: Vec::new(),
2521            restoration_scope_id: None,
2522            route_traversal_edge_behavior: K_DEFAULT_ROUTE_TRAVERSAL_EDGE_BEHAVIOR,
2523            route_directional_traversal_edge_behavior:
2524                K_DEFAULT_ROUTE_DIRECTIONAL_TRAVERSAL_EDGE_BEHAVIOR,
2525            on_generate_initial_routes: Rc::new(Navigator::default_generate_initial_routes),
2526            reports_route_update_to_engine: false,
2527            clip_behavior: Clip::HardEdge,
2528            request_focus: true,
2529        }
2530    }
2531}
2532
2533impl StatefulWidget for Navigator {
2534    type State = NavigatorState;
2535
2536    fn key(&self) -> Option<&KeyRef> {
2537        self.key.as_ref()
2538    }
2539
2540    fn create_state(&self) -> NavigatorState {
2541        NavigatorState::new()
2542    }
2543}
2544
2545// ---------------------------------------------------------------------------------------------
2546// _RouteEntry
2547
2548/// The lifecycle of a [`RouteEntry`]. The variants are declared in Dart's order: the
2549/// comparisons the navigator makes on `currentState.index` are `PartialOrd` here.
2550#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2551pub enum RouteLifecycle {
2552    /// We will wait for the transition delegate to decide what to do with this route.
2553    Staging,
2554    /// We'll want to run install, did_add, etc; a route created by
2555    /// [`Navigator::on_generate_initial_routes`] or by the initial [`Navigator::pages`].
2556    Add,
2557    /// We're waiting for the completion of the top-most route's `did_push`.
2558    Adding,
2559    /// We'll want to run install, did_push, etc; a route added via `push` and friends.
2560    Push,
2561    /// We'll want to run install, did_push, etc; a route added via `push_replacement` and
2562    /// friends.
2563    PushReplace,
2564    /// We're waiting for the completion of `did_push`.
2565    Pushing,
2566    /// We'll want to run install, did_replace, etc; a route added via `replace` and friends.
2567    Replace,
2568    /// The route is being harmless.
2569    Idle,
2570    /// We'll want to call `did_pop`.
2571    Pop,
2572    /// We'll want to call `did_complete`.
2573    Complete,
2574    /// We'll want to run did_replace / did_remove etc.
2575    Remove,
2576    /// We're waiting for the route to call `finalize_route` to switch to dispose.
2577    Popping,
2578    /// We are waiting for subsequent routes to be done animating, then will switch to dispose.
2579    Removing,
2580    /// We will dispose the route momentarily.
2581    Dispose,
2582    /// The entry is waiting for its widget subtree to be disposed.
2583    Disposing,
2584    /// We have disposed the route.
2585    Disposed,
2586}
2587
2588/// Dart's `_RouteEntry`: one [`Route`] and its place in a [`NavigatorState`]'s history.
2589///
2590/// This is also the [`RouteTransitionRecord`] a [`TransitionDelegate`] receives.
2591pub struct RouteEntry {
2592    route: RouteRef,
2593    restoration_information: Option<Rc<RestorationInformation>>,
2594    page_based: bool,
2595    current_state: RouteLifecycle,
2596    /// Last argument to `Route::did_change_previous`; `None` is Dart's `notAnnounced`.
2597    last_announced_previous_route: Option<Option<RouteRef>>,
2598    /// Last argument to `Route::did_pop_next`; `None` is Dart's `notAnnounced`. Named without
2599    /// keeping it, as Dart's `WeakReference`.
2600    last_announced_popped_next_route: Option<Option<AnyRoute>>,
2601    /// Last argument to `Route::did_change_next`; `None` is Dart's `notAnnounced`.
2602    last_announced_next_route: Option<Option<RouteRef>>,
2603    /// Whether the route is being removed by an imperative API call.
2604    imperative_removal: bool,
2605    pending_result: RouteResult,
2606    report_removal_to_observer: bool,
2607    is_waiting_for_exiting_decision: bool,
2608}
2609
2610impl RouteEntry {
2611    fn last_announced_previous_route(&self) -> Option<Option<AnyRoute>> {
2612        self.last_announced_previous_route
2613            .as_ref()
2614            .map(OptionRetained::handle)
2615    }
2616
2617    /// Dart's `lastAnnouncedPoppedNextRoute.target`: a freed route reads as `null`.
2618    fn last_announced_popped_next_route(&self, app: &App) -> Option<Option<AnyRoute>> {
2619        self.last_announced_popped_next_route
2620            .map(|route| route.filter(|route| app.contains(*route)))
2621    }
2622
2623    fn last_announced_next_route(&self) -> Option<Option<AnyRoute>> {
2624        self.last_announced_next_route
2625            .as_ref()
2626            .map(OptionRetained::handle)
2627    }
2628
2629    /// The maximum number of `did_pop` attempts a `mark_for_pop` makes on a route that handles
2630    /// pops internally.
2631    pub const K_DEBUG_POP_ATTEMPT_LIMIT: usize = 100;
2632
2633    /// Creates an entry for `route`; `initial_state` must be one of [`RouteLifecycle::Staging`],
2634    /// [`Add`](RouteLifecycle::Add), [`Push`](RouteLifecycle::Push),
2635    /// [`PushReplace`](RouteLifecycle::PushReplace) or [`Replace`](RouteLifecycle::Replace).
2636    fn new(
2637        app: &mut App,
2638        route: RouteRef,
2639        initial_state: RouteLifecycle,
2640        page_based: bool,
2641        restoration_information: Option<Rc<RestorationInformation>>,
2642    ) -> Ref<RouteEntry> {
2643        debug_assert!(!page_based || route.is_page_based(app));
2644        debug_assert!(matches!(
2645            initial_state,
2646            RouteLifecycle::Staging
2647                | RouteLifecycle::Add
2648                | RouteLifecycle::Push
2649                | RouteLifecycle::PushReplace
2650                | RouteLifecycle::Replace
2651        ));
2652        app.create(RouteEntry {
2653            route,
2654            restoration_information,
2655            page_based,
2656            current_state: initial_state,
2657            last_announced_previous_route: None,
2658            last_announced_popped_next_route: None,
2659            last_announced_next_route: None,
2660            imperative_removal: false,
2661            pending_result: None,
2662            report_removal_to_observer: true,
2663            is_waiting_for_exiting_decision: false,
2664        })
2665    }
2666
2667    /// Whether this entry was created from a [`Page`] in [`Navigator::pages`].
2668    pub fn page_based(self: Handle<Self>, app: &App) -> bool {
2669        app.get(self).page_based
2670    }
2671
2672    /// The lifecycle state this entry is in.
2673    pub fn current_state(self: Handle<Self>, app: &App) -> RouteLifecycle {
2674        app.get(self).current_state
2675    }
2676
2677    /// The restoration ID under which this entry's route is serialized, if any.
2678    pub fn restoration_id(self: Handle<Self>, app: &App) -> Option<String> {
2679        // User-provided restoration ids of Pages are prefixed with 'p+'. Generated ids for
2680        // pageless routes are prefixed with 'r+' to avoid clashes.
2681        if app.get(self).page_based {
2682            let settings = app.get(self).route.settings(app);
2683            let page = settings.as_page().expect("a page-based route has a page");
2684            return page.restoration_id().map(|id| format!("p+{id}"));
2685        }
2686        app.get(self)
2687            .restoration_information
2688            .as_ref()
2689            .map(|information| format!("r+{}", information.restoration_scope_id()))
2690    }
2691
2692    fn can_update_from(self: Handle<Self>, app: &App, page: &PageRef) -> bool {
2693        if !self.will_be_present(app) {
2694            return false;
2695        }
2696        if !app.get(self).page_based {
2697            return false;
2698        }
2699        let settings = app.get(self).route.settings(app);
2700        let route_page = settings.as_page().expect("a page-based route has a page");
2701        page.can_update(&**route_page)
2702    }
2703
2704    fn handle_add(
2705        self: Handle<Self>,
2706        app: &mut App,
2707        navigator: Handle<NavigatorState>,
2708        previous_present: Option<RouteRef>,
2709    ) {
2710        debug_assert!(app.get(self).current_state == RouteLifecycle::Add);
2711        app.get_mut(self).current_state = RouteLifecycle::Adding;
2712        let route = app.get(self).route.clone();
2713        app.get_mut(navigator)
2714            .observed_route_additions
2715            .push_back(NavigatorObservation::Push {
2716                primary_route: route,
2717                secondary_route: previous_present,
2718            });
2719    }
2720
2721    fn handle_push(
2722        self: Handle<Self>,
2723        app: &mut App,
2724        navigator: Handle<NavigatorState>,
2725        is_new_first: bool,
2726        previous: Option<AnyRoute>,
2727        previous_present: Option<RouteRef>,
2728    ) {
2729        let previous_state = app.get(self).current_state;
2730        debug_assert!(matches!(
2731            previous_state,
2732            RouteLifecycle::Push | RouteLifecycle::PushReplace | RouteLifecycle::Replace
2733        ));
2734        let route = app.get(self).route.handle();
2735        debug_assert!(
2736            !route.installed(app),
2737            "The pushed route has already been used. When pushing a route, a new Route object \
2738             must be provided."
2739        );
2740        route.set_navigator(app, Some(navigator));
2741        route.install(app);
2742        debug_assert!(!route.overlay_entries(app).is_empty());
2743        if matches!(
2744            previous_state,
2745            RouteLifecycle::Push | RouteLifecycle::PushReplace
2746        ) {
2747            let route_future = route.did_push(app);
2748            app.get_mut(self).current_state = RouteLifecycle::Pushing;
2749            route_future.when_complete_or_cancel(
2750                app,
2751                Listener::new(move |app| {
2752                    if app.contains(self) && app.get(self).current_state == RouteLifecycle::Pushing
2753                    {
2754                        app.get_mut(self).current_state = RouteLifecycle::Idle;
2755                        navigator.flush_history_updates(app, true);
2756                    }
2757                }),
2758            );
2759        } else {
2760            debug_assert!(previous_state == RouteLifecycle::Replace);
2761            route.did_replace(app, previous);
2762            app.get_mut(self).current_state = RouteLifecycle::Idle;
2763        }
2764        if is_new_first {
2765            route.did_change_next(app, None);
2766        }
2767
2768        if matches!(
2769            previous_state,
2770            RouteLifecycle::Replace | RouteLifecycle::PushReplace
2771        ) {
2772            let primary_route = app.get(self).route.clone();
2773            app.get_mut(navigator).observed_route_additions.push_back(
2774                NavigatorObservation::Replace {
2775                    primary_route,
2776                    secondary_route: previous_present.clone(),
2777                },
2778            );
2779            if let Some(previous_present) = previous_present
2780                && let Some(page) = previous_present.settings(app).as_page().cloned()
2781                && let Some(callback) = navigator.widget(app).on_did_remove_page.clone()
2782            {
2783                callback(app, page);
2784            }
2785        } else {
2786            debug_assert!(previous_state == RouteLifecycle::Push);
2787            let primary_route = app.get(self).route.clone();
2788            app.get_mut(navigator)
2789                .observed_route_additions
2790                .push_back(NavigatorObservation::Push {
2791                    primary_route,
2792                    secondary_route: previous_present,
2793                });
2794        }
2795    }
2796
2797    fn handle_did_pop_next(self: Handle<Self>, app: &mut App, popped_route: AnyRoute) {
2798        let route = app.get(self).route.handle();
2799        route.did_pop_next(app, popped_route);
2800        app.get_mut(self).last_announced_popped_next_route = Some(Some(popped_route));
2801    }
2802
2803    /// Returns whether the entry has been marked for pop.
2804    fn handle_pop(
2805        self: Handle<Self>,
2806        app: &mut App,
2807        navigator: Handle<NavigatorState>,
2808        _previous_present: Option<AnyRoute>,
2809    ) -> bool {
2810        let route = app.get(self).route.handle();
2811        debug_assert!(route.is_installed_in(app, navigator));
2812        app.get_mut(self).current_state = RouteLifecycle::Popping;
2813        if route.data(app).pop_completer.is_completed() {
2814            // This is a page-based route popped through the Navigator.pop. The didPop should
2815            // have been called. No further action is needed.
2816            debug_assert!(app.get(self).page_based);
2817            debug_assert!(app.get(self).pending_result.is_none());
2818            return true;
2819        }
2820        let pending_result = app.get(self).pending_result.clone();
2821        if !route.did_pop(app, pending_result.clone()) {
2822            app.get_mut(self).current_state = RouteLifecycle::Idle;
2823            return false;
2824        }
2825        route.on_pop_invoked_with_result(app, true, pending_result);
2826        if app.get(self).page_based
2827            && app.get(self).imperative_removal
2828            && let Some(page) = route.settings(app).as_page().cloned()
2829            && let Some(callback) = navigator.widget(app).on_did_remove_page.clone()
2830        {
2831            callback(app, page);
2832        }
2833        app.get_mut(self).pending_result = None;
2834        true
2835    }
2836
2837    fn handle_complete(self: Handle<Self>, app: &mut App) {
2838        let route = app.get(self).route.handle();
2839        let pending_result = app.get(self).pending_result.clone();
2840        route.did_complete(app, pending_result);
2841        app.get_mut(self).pending_result = None;
2842        // did_complete implies the popped completion resolved.
2843        debug_assert!(route.data(app).pop_completer.is_completed());
2844        app.get_mut(self).current_state = RouteLifecycle::Remove;
2845    }
2846
2847    fn handle_removal(
2848        self: Handle<Self>,
2849        app: &mut App,
2850        navigator: Handle<NavigatorState>,
2851        previous_present: Option<RouteRef>,
2852    ) {
2853        let route = app.get(self).route.handle();
2854        if route.is_installed_in(app, navigator) {
2855            app.get_mut(self).current_state = RouteLifecycle::Removing;
2856        } else {
2857            // The route was never installed (e.g. it was created for a page that was removed
2858            // before the route was ever pushed), so there is nothing to animate away.
2859            app.get_mut(self).current_state = RouteLifecycle::Dispose;
2860        }
2861        if app.get(self).report_removal_to_observer {
2862            let primary_route = app.get(self).route.clone();
2863            app.get_mut(navigator).observed_route_deletions.push_back(
2864                NavigatorObservation::Remove {
2865                    primary_route,
2866                    secondary_route: previous_present,
2867                },
2868            );
2869        }
2870    }
2871
2872    fn did_add(
2873        self: Handle<Self>,
2874        app: &mut App,
2875        navigator: Handle<NavigatorState>,
2876        is_new_first: bool,
2877    ) {
2878        let route = app.get(self).route.handle();
2879        debug_assert!(!route.installed(app));
2880        route.set_navigator(app, Some(navigator));
2881        route.install(app);
2882        debug_assert!(!route.overlay_entries(app).is_empty());
2883        route.did_add(app);
2884        app.get_mut(self).current_state = RouteLifecycle::Idle;
2885        if is_new_first {
2886            route.did_change_next(app, None);
2887        }
2888    }
2889
2890    fn pop(self: Handle<Self>, app: &mut App, result: RouteResult, imperative_removal: bool) {
2891        debug_assert!(self.is_present(app));
2892        let entry = app.get_mut(self);
2893        entry.pending_result = result;
2894        entry.current_state = RouteLifecycle::Pop;
2895        entry.imperative_removal = imperative_removal;
2896    }
2897
2898    fn complete(
2899        self: Handle<Self>,
2900        app: &mut App,
2901        result: RouteResult,
2902        is_replaced: bool,
2903        imperative_removal: bool,
2904    ) {
2905        if app.get(self).current_state >= RouteLifecycle::Remove {
2906            return;
2907        }
2908        debug_assert!(self.is_present(app));
2909        let entry = app.get_mut(self);
2910        entry.report_removal_to_observer = !is_replaced;
2911        entry.pending_result = result;
2912        entry.current_state = RouteLifecycle::Complete;
2913        entry.imperative_removal = imperative_removal;
2914    }
2915
2916    fn finalize(self: Handle<Self>, app: &mut App) {
2917        debug_assert!(app.get(self).current_state < RouteLifecycle::Dispose);
2918        app.get_mut(self).current_state = RouteLifecycle::Dispose;
2919    }
2920
2921    /// Disposes the route immediately, without waiting for its widget subtree to be unmounted.
2922    fn forced_dispose(self: Handle<Self>, app: &mut App) {
2923        debug_assert!(app.get(self).current_state < RouteLifecycle::Disposed);
2924        app.get_mut(self).current_state = RouteLifecycle::Disposed;
2925        let route = app.get(self).route.handle();
2926        route.dispose(app);
2927    }
2928
2929    /// Disposes the route after the widget subtree the route's overlay entries built has been
2930    /// unmounted.
2931    fn dispose(self: Handle<Self>, app: &mut App) {
2932        debug_assert!(app.get(self).current_state < RouteLifecycle::Disposing);
2933        app.get_mut(self).current_state = RouteLifecycle::Disposing;
2934
2935        let route = app.get(self).route.handle();
2936        let mounted_entries: Vec<Handle<OverlayEntry>> = route
2937            .overlay_entries(app)
2938            .into_iter()
2939            .filter(|entry| entry.mounted(app))
2940            .collect();
2941
2942        if mounted_entries.is_empty() {
2943            self.forced_dispose(app);
2944            return;
2945        }
2946
2947        // Dart's closure holds `final NavigatorState navigator` strongly, so the state outlives
2948        // the subtree whose unmounting runs the microtask.
2949        let navigator = route.navigator(app).expect("an installed route").keep(app);
2950        let kept = self.keep(app);
2951        app.get_mut(navigator.handle())
2952            .entry_waiting_for_subtree_disposal
2953            .insert(kept);
2954        let remaining = Rc::new(std::cell::Cell::new(mounted_entries.len()));
2955        for overlay_entry in mounted_entries {
2956            let navigator = navigator.clone();
2957            // Dart's `late VoidCallback listener`: the closure names itself weakly, so it does
2958            // not keep itself once the entry lets it go.
2959            let itself: Rc<std::cell::OnceCell<WeakListener>> = Rc::default();
2960            let listener = {
2961                let itself = Rc::clone(&itself);
2962                let remaining = Rc::clone(&remaining);
2963                Listener::new(move |app| {
2964                    debug_assert!(remaining.get() > 0);
2965                    debug_assert!(!overlay_entry.mounted(app));
2966                    remaining.set(remaining.get() - 1);
2967                    if let Some(listener) = itself.get().and_then(WeakListener::upgrade) {
2968                        overlay_entry.remove_listener(app, &listener);
2969                    }
2970                    if remaining.get() == 0 {
2971                        let navigator = navigator.clone();
2972                        app.schedule_microtask(Listener::new(move |app| {
2973                            if !app
2974                                .get_mut(navigator.handle())
2975                                .entry_waiting_for_subtree_disposal
2976                                .remove(&self)
2977                            {
2978                                // This route entry was disposed by the navigator's dispose.
2979                                return;
2980                            }
2981                            debug_assert!(app.get(self).current_state == RouteLifecycle::Disposing);
2982                            self.forced_dispose(app);
2983                        }));
2984                    }
2985                })
2986            };
2987            let _ = itself.set(listener.downgrade());
2988            overlay_entry.add_listener(app, listener);
2989        }
2990    }
2991
2992    fn will_be_present(self: Handle<Self>, app: &App) -> bool {
2993        let state = app.get(self).current_state;
2994        state <= RouteLifecycle::Idle && state >= RouteLifecycle::Add
2995    }
2996
2997    fn is_present(self: Handle<Self>, app: &App) -> bool {
2998        let state = app.get(self).current_state;
2999        state <= RouteLifecycle::Remove && state >= RouteLifecycle::Add
3000    }
3001
3002    fn is_present_for_restoration(self: Handle<Self>, app: &App) -> bool {
3003        app.get(self).current_state <= RouteLifecycle::Idle
3004    }
3005
3006    fn suitable_for_announcement(self: Handle<Self>, app: &App) -> bool {
3007        let state = app.get(self).current_state;
3008        state <= RouteLifecycle::Removing && state >= RouteLifecycle::Push
3009    }
3010
3011    fn suitable_for_transition_animation(self: Handle<Self>, app: &App) -> bool {
3012        let state = app.get(self).current_state;
3013        state <= RouteLifecycle::Remove && state >= RouteLifecycle::Push
3014    }
3015
3016    fn should_announce_change_to_next(
3017        self: Handle<Self>,
3018        app: &App,
3019        next_route: Option<AnyRoute>,
3020    ) -> bool {
3021        let entry = app.get(self);
3022        debug_assert!(entry.last_announced_next_route() != Some(next_route));
3023        // We do not announce when `next_route` is null and the last announced popped next route
3024        // is the same as the last announced next route: the route was already told that it is
3025        // the topmost by `did_pop_next`.
3026        !(next_route.is_none()
3027            && entry.last_announced_popped_next_route(app) == entry.last_announced_next_route())
3028    }
3029
3030    fn is_present_predicate(app: &App, entry: Handle<RouteEntry>) -> bool {
3031        entry.is_present(app)
3032    }
3033
3034    fn suitable_for_transition_animation_predicate(app: &App, entry: Handle<RouteEntry>) -> bool {
3035        entry.suitable_for_transition_animation(app)
3036    }
3037
3038    fn will_be_present_predicate(app: &App, entry: Handle<RouteEntry>) -> bool {
3039        entry.will_be_present(app)
3040    }
3041
3042    #[expect(
3043        dead_code,
3044        reason = "Dart's `_RouteEntry.restorationEnabled` getter; only its setter is read"
3045    )]
3046    fn restoration_enabled(self: Handle<Self>, app: &App) -> bool {
3047        let notifier = app.get(self).route.restoration_scope_id(app);
3048        app.get(notifier).value().is_some()
3049    }
3050
3051    fn set_restoration_enabled(self: Handle<Self>, app: &mut App, value: bool) {
3052        debug_assert!(!value || self.restoration_id(app).is_some());
3053        let id = value.then(|| self.restoration_id(app)).flatten();
3054        let route = app.get(self).route.handle();
3055        route.update_restoration_id(app, id);
3056    }
3057
3058    fn mark_needs_exiting_decision(self: Handle<Self>, app: &mut App) {
3059        app.get_mut(self).is_waiting_for_exiting_decision = true;
3060    }
3061}
3062
3063impl RouteTransitionRecord for RouteEntry {
3064    fn route(self: Handle<Self>, app: &App) -> AnyRoute {
3065        app.get(self).route.handle()
3066    }
3067
3068    fn is_waiting_for_entering_decision(self: Handle<Self>, app: &App) -> bool {
3069        app.get(self).current_state == RouteLifecycle::Staging
3070    }
3071
3072    fn is_waiting_for_exiting_decision(self: Handle<Self>, app: &App) -> bool {
3073        app.get(self).is_waiting_for_exiting_decision
3074    }
3075
3076    fn mark_for_push(self: Handle<Self>, app: &mut App) {
3077        debug_assert!(
3078            self.is_waiting_for_entering_decision(app)
3079                && !self.is_waiting_for_exiting_decision(app),
3080            "This route cannot be marked for push. Either a decision has already been made or it \
3081             does not require an explicit decision on how to transition in."
3082        );
3083        app.get_mut(self).current_state = RouteLifecycle::Push;
3084    }
3085
3086    fn mark_for_add(self: Handle<Self>, app: &mut App) {
3087        debug_assert!(
3088            self.is_waiting_for_entering_decision(app)
3089                && !self.is_waiting_for_exiting_decision(app),
3090            "This route cannot be marked for add. Either a decision has already been made or it \
3091             does not require an explicit decision on how to transition in."
3092        );
3093        app.get_mut(self).current_state = RouteLifecycle::Add;
3094    }
3095
3096    fn mark_for_pop(self: Handle<Self>, app: &mut App, result: RouteResult) {
3097        debug_assert!(
3098            !self.is_waiting_for_entering_decision(app)
3099                && self.is_waiting_for_exiting_decision(app)
3100                && self.is_present(app),
3101            "This route cannot be marked for pop. Either a decision has already been made or it \
3102             does not require an explicit decision on how to transition out."
3103        );
3104        // Remove state that prevents a pop, e.g. LocalHistoryEntry.
3105        let route = app.get(self).route.handle();
3106        let mut attempt = 0;
3107        while route.will_handle_pop_internally(app) {
3108            if cfg!(debug_assertions) {
3109                attempt += 1;
3110                assert!(
3111                    attempt < RouteEntry::K_DEBUG_POP_ATTEMPT_LIMIT,
3112                    "Attempted to pop {route:?} {} times, but still failed",
3113                    RouteEntry::K_DEBUG_POP_ATTEMPT_LIMIT
3114                );
3115            }
3116            let pop_result = route.did_pop(app, result.clone());
3117            debug_assert!(!pop_result);
3118        }
3119        self.pop(app, result, false);
3120        app.get_mut(self).is_waiting_for_exiting_decision = false;
3121    }
3122
3123    fn mark_for_complete(self: Handle<Self>, app: &mut App, result: RouteResult) {
3124        debug_assert!(
3125            !self.is_waiting_for_entering_decision(app)
3126                && self.is_waiting_for_exiting_decision(app)
3127                && self.is_present(app),
3128            "This route cannot be marked for complete. Either a decision has already been made or \
3129             it does not require an explicit decision on how to transition out."
3130        );
3131        self.complete(app, result, false, false);
3132        app.get_mut(self).is_waiting_for_exiting_decision = false;
3133    }
3134}
3135
3136/// Dart's `_NavigatorObservation` family: what an observer is told once the history has settled.
3137enum NavigatorObservation {
3138    Push {
3139        primary_route: RouteRef,
3140        secondary_route: Option<RouteRef>,
3141    },
3142    Pop {
3143        primary_route: RouteRef,
3144        secondary_route: Option<RouteRef>,
3145    },
3146    Remove {
3147        primary_route: RouteRef,
3148        secondary_route: Option<RouteRef>,
3149    },
3150    Replace {
3151        primary_route: RouteRef,
3152        secondary_route: Option<RouteRef>,
3153    },
3154}
3155
3156impl NavigatorObservation {
3157    fn notify(&self, app: &mut App, observer: AnyNavigatorObserver) {
3158        match self {
3159            NavigatorObservation::Push {
3160                primary_route,
3161                secondary_route,
3162            } => observer.did_push(app, primary_route.handle(), secondary_route.handle()),
3163            NavigatorObservation::Pop {
3164                primary_route,
3165                secondary_route,
3166            } => observer.did_pop(app, primary_route.handle(), secondary_route.handle()),
3167            NavigatorObservation::Remove {
3168                primary_route,
3169                secondary_route,
3170            } => observer.did_remove(app, primary_route.handle(), secondary_route.handle()),
3171            NavigatorObservation::Replace {
3172                primary_route,
3173                secondary_route,
3174            } => observer.did_replace(app, Some(primary_route.handle()), secondary_route.handle()),
3175        }
3176    }
3177}
3178
3179/// Dart's `_History`: the navigator's route entries, as a `ChangeNotifier`.
3180pub struct History {
3181    change_notifier: waft_foundation::ChangeNotifierData,
3182    value: Vec<Ref<RouteEntry>>,
3183}
3184
3185impl History {
3186    fn new(app: &mut App) -> Ref<History> {
3187        app.create(History {
3188            change_notifier: waft_foundation::ChangeNotifierData::new(),
3189            value: Vec::new(),
3190        })
3191    }
3192
3193    fn entries(self: Handle<Self>, app: &App) -> Vec<Handle<RouteEntry>> {
3194        app.get(self).value.iter().map(Retained::handle).collect()
3195    }
3196
3197    fn len(self: Handle<Self>, app: &App) -> usize {
3198        app.get(self).value.len()
3199    }
3200
3201    fn is_empty(self: Handle<Self>, app: &App) -> bool {
3202        app.get(self).value.is_empty()
3203    }
3204
3205    fn at(self: Handle<Self>, app: &App, index: usize) -> Handle<RouteEntry> {
3206        app.get(self).value[index].handle()
3207    }
3208
3209    fn index_where(
3210        self: Handle<Self>,
3211        app: &App,
3212        test: impl Fn(&App, Handle<RouteEntry>) -> bool,
3213    ) -> Option<usize> {
3214        app.get(self)
3215            .value
3216            .iter()
3217            .position(|entry| test(app, entry.handle()))
3218    }
3219
3220    fn add(self: Handle<Self>, app: &mut App, element: Ref<RouteEntry>) {
3221        app.get_mut(self).value.push(element);
3222        self.notify_listeners(app);
3223    }
3224
3225    fn add_all(self: Handle<Self>, app: &mut App, elements: Vec<Ref<RouteEntry>>) {
3226        if elements.is_empty() {
3227            return;
3228        }
3229        app.get_mut(self).value.extend(elements);
3230        self.notify_listeners(app);
3231    }
3232
3233    fn clear(self: Handle<Self>, app: &mut App) {
3234        let value_was_empty = app.get(self).value.is_empty();
3235        app.get_mut(self).value.clear();
3236        if !value_was_empty {
3237            self.notify_listeners(app);
3238        }
3239    }
3240
3241    fn insert(self: Handle<Self>, app: &mut App, index: usize, element: Ref<RouteEntry>) {
3242        app.get_mut(self).value.insert(index, element);
3243        self.notify_listeners(app);
3244    }
3245
3246    fn remove_at(self: Handle<Self>, app: &mut App, index: usize) -> Ref<RouteEntry> {
3247        let entry = app.get_mut(self).value.remove(index);
3248        self.notify_listeners(app);
3249        entry
3250    }
3251
3252    fn remove_last(self: Handle<Self>, app: &mut App) -> Ref<RouteEntry> {
3253        let entry = app.get_mut(self).value.pop().expect("a non-empty history");
3254        self.notify_listeners(app);
3255        entry
3256    }
3257}
3258
3259impl waft_foundation::ChangeNotifier for History {
3260    fn change_notifier_data(&self) -> &waft_foundation::ChangeNotifierData {
3261        &self.change_notifier
3262    }
3263
3264    fn change_notifier_data_mut(&mut self) -> &mut waft_foundation::ChangeNotifierData {
3265        &mut self.change_notifier
3266    }
3267}
3268
3269impl Debug for History {
3270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3271        Debug::fmt(&self.value, f)
3272    }
3273}
3274
3275// ---------------------------------------------------------------------------------------------
3276// NavigatorState
3277
3278/// The state for a [`Navigator`] widget.
3279///
3280/// A reference to this class can be obtained by calling [`Navigator::of`].
3281pub struct NavigatorState {
3282    state: StateData<Navigator>,
3283    ticker_provider: TickerProviderStateMixinData,
3284    restoration: RestorationMixinData,
3285    overlay_key: Option<GlobalKey>,
3286    history: Option<Ref<History>>,
3287    /// The [`RouteEntry`]s that are waiting for their subtrees to be disposed.
3288    entry_waiting_for_subtree_disposal: HashSet<Ref<RouteEntry>>,
3289    serializable_history: Option<Ref<HistoryProperty>>,
3290    observed_route_additions: VecDeque<NavigatorObservation>,
3291    observed_route_deletions: VecDeque<NavigatorObservation>,
3292    focus_node: Option<Ref<FocusNode>>,
3293    /// Used to prevent re-entrant calls to push, pop, and friends.
3294    debug_locked: bool,
3295    hero_controller_from_scope: Option<Ref<HeroController>>,
3296    effective_observers: Vec<NavigatorObserverRef>,
3297    raw_next_pageless_restoration_scope_id: Option<Ref<RestorableInt>>,
3298    last_topmost_route: Option<Ref<RouteEntry>>,
3299    last_announced_route_name: Option<String>,
3300    debug_updating_page: bool,
3301    flushing_history: bool,
3302    user_gestures_in_progress_count: i64,
3303    user_gesture_in_progress_notifier: Option<Ref<ValueNotifier<bool>>>,
3304    active_pointers: HashSet<i64>,
3305}
3306
3307impl NavigatorState {
3308    fn new() -> NavigatorState {
3309        NavigatorState {
3310            state: StateData::new(),
3311            ticker_provider: TickerProviderStateMixinData::new(),
3312            restoration: RestorationMixinData::new(),
3313            overlay_key: None,
3314            history: None,
3315            entry_waiting_for_subtree_disposal: HashSet::new(),
3316            serializable_history: None,
3317            observed_route_additions: VecDeque::new(),
3318            observed_route_deletions: VecDeque::new(),
3319            focus_node: None,
3320            debug_locked: false,
3321            hero_controller_from_scope: None,
3322            effective_observers: Vec::new(),
3323            raw_next_pageless_restoration_scope_id: None,
3324            last_topmost_route: None,
3325            last_announced_route_name: None,
3326            debug_updating_page: false,
3327            flushing_history: false,
3328            user_gestures_in_progress_count: 0,
3329            user_gesture_in_progress_notifier: None,
3330            active_pointers: HashSet::new(),
3331        }
3332    }
3333
3334    /// The focus node for this navigator.
3335    ///
3336    /// The navigator will attempt to focus this node when the top-most route changes.
3337    pub fn focus_node(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
3338        app.get(self)
3339            .focus_node
3340            .handle()
3341            .expect("init_state has run")
3342    }
3343
3344    /// True if the state's [`user_gesture_in_progress_notifier`](Self::user_gesture_in_progress_notifier)
3345    /// value is true, meaning a route is being moved by a user gesture.
3346    pub fn user_gesture_in_progress(self: Handle<Self>, app: &App) -> bool {
3347        *app.get(self.user_gesture_in_progress_notifier(app)).value()
3348    }
3349
3350    /// Notifies its listeners if the value of [`user_gesture_in_progress`](Self::user_gesture_in_progress)
3351    /// changes.
3352    pub fn user_gesture_in_progress_notifier(
3353        self: Handle<Self>,
3354        app: &App,
3355    ) -> Handle<ValueNotifier<bool>> {
3356        app.get(self)
3357            .user_gesture_in_progress_notifier
3358            .handle()
3359            .expect("init_state has run")
3360    }
3361
3362    fn history(self: Handle<Self>, app: &App) -> Handle<History> {
3363        app.get(self).history.handle().expect("init_state has run")
3364    }
3365
3366    fn serializable_history(self: Handle<Self>, app: &App) -> Handle<HistoryProperty> {
3367        app.get(self)
3368            .serializable_history
3369            .handle()
3370            .expect("init_state has run")
3371    }
3372
3373    pub(crate) fn history_entries(self: Handle<Self>, app: &App) -> Vec<Handle<RouteEntry>> {
3374        self.history(app).entries(app)
3375    }
3376
3377    /// Dart's `_handleHistoryChanged`.
3378    fn handle_history_changed(self: Handle<Self>, app: &mut App) {
3379        let can_handle_pop = self.get_navigator_can_handle_pop(app);
3380        match SchedulerBinding::scheduler_phase(app) {
3381            SchedulerPhase::PostFrameCallbacks => {
3382                let context = self.context(app);
3383                NavigationNotification { can_handle_pop }.dispatch(app, Some(context));
3384            }
3385            _ => {
3386                SchedulerBinding::add_post_frame_callback(
3387                    app,
3388                    FrameCallback::handle_method(self, NavigatorState::dispatch_navigation_state),
3389                    View::maybe_id_of(app, self.context(app)),
3390                );
3391            }
3392        }
3393    }
3394
3395    fn dispatch_navigation_state(self: Handle<Self>, app: &mut App, _time_stamp: Duration) {
3396        if !self.mounted(app) {
3397            return;
3398        }
3399        let can_handle_pop = self.get_navigator_can_handle_pop(app);
3400        let context = self.context(app);
3401        NavigationNotification { can_handle_pop }.dispatch(app, Some(context));
3402    }
3403
3404    fn get_navigator_can_handle_pop(self: Handle<Self>, app: &mut App) -> bool {
3405        if self.can_pop(app) {
3406            return true;
3407        }
3408        let last_entry = self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
3409        match last_entry {
3410            None => false,
3411            Some(entry) => {
3412                let route = app.get(entry).route.handle();
3413                route.pop_disposition(app) == RoutePopDisposition::DoNotPop
3414            }
3415        }
3416    }
3417
3418    fn debug_check_page_api_parameters(self: Handle<Self>, app: &App) -> bool {
3419        let widget = self.widget(app);
3420        if !widget.using_pages_api() {
3421            return true;
3422        }
3423        assert!(
3424            (widget.on_did_remove_page.is_none()) != (widget.on_pop_page.is_none()),
3425            "Either on_did_remove_page or on_pop_page must be provided to use the \
3426             Navigator.pages API but not both."
3427        );
3428        true
3429    }
3430
3431    fn next_pageless_restoration_scope_id(self: Handle<Self>, app: &mut App) -> i64 {
3432        let property = app
3433            .get(self)
3434            .raw_next_pageless_restoration_scope_id
3435            .handle()
3436            .expect("init_state has run");
3437        let value = *property.value(app);
3438        property.set_value(app, value + 1);
3439        value
3440    }
3441
3442    fn forced_dispose_all_route_entries(self: Handle<Self>, app: &mut App) {
3443        let waiting: Vec<Ref<RouteEntry>> = app
3444            .get_mut(self)
3445            .entry_waiting_for_subtree_disposal
3446            .drain()
3447            .collect();
3448        for entry in waiting {
3449            entry.forced_dispose(app);
3450        }
3451        let history = self.history(app);
3452        while !history.is_empty(app) {
3453            let entry = history.remove_last(app);
3454            NavigatorState::dispose_route_entry(app, entry.handle(), false);
3455        }
3456    }
3457
3458    fn dispose_route_entry(app: &mut App, entry: Handle<RouteEntry>, graceful: bool) {
3459        let route = app.get(entry).route.handle();
3460        for overlay_entry in route.overlay_entries(app) {
3461            overlay_entry.remove(app);
3462        }
3463        if graceful {
3464            entry.dispose(app);
3465        } else {
3466            entry.forced_dispose(app);
3467        }
3468    }
3469
3470    fn update_hero_controller(
3471        self: Handle<Self>,
3472        app: &mut App,
3473        new_hero_controller: Option<Handle<HeroController>>,
3474    ) {
3475        if app.get(self).hero_controller_from_scope.handle() == new_hero_controller {
3476            return;
3477        }
3478        if let Some(controller) = new_hero_controller {
3479            controller.as_observer().set_navigator(app, Some(self));
3480        }
3481        if let Some(previous) = app.get(self).hero_controller_from_scope.handle()
3482            && previous.as_observer().navigator(app) == Some(self)
3483        {
3484            previous.as_observer().set_navigator(app, None);
3485        }
3486        let kept = new_hero_controller.map(|controller| controller.keep(app));
3487        app.get_mut(self).hero_controller_from_scope = kept;
3488        self.update_effective_observers(app);
3489    }
3490
3491    fn update_effective_observers(self: Handle<Self>, app: &mut App) {
3492        let mut observers = self.widget(app).observers.clone();
3493        if let Some(controller) = &app.get(self).hero_controller_from_scope {
3494            observers.push(controller.erase());
3495        }
3496        app.get_mut(self).effective_observers = observers;
3497    }
3498
3499    fn debug_check_duplicated_page_keys(self: Handle<Self>, app: &App) {
3500        if !cfg!(debug_assertions) {
3501            return;
3502        }
3503        let mut key_reservation: Vec<KeyRef> = Vec::new();
3504        for page in &self.widget(app).pages {
3505            if let Some(key) = page.key() {
3506                assert!(
3507                    !key_reservation.iter().any(|other| other == key),
3508                    "The Navigator.pages must not contain two pages with the same key."
3509                );
3510                key_reservation.push(key.clone());
3511            }
3512        }
3513    }
3514
3515    /// The [`OverlayState`] of the [`Overlay`] this navigator builds, once it is mounted.
3516    pub fn overlay(self: Handle<Self>, app: &mut App) -> Option<Handle<OverlayState>> {
3517        let key = app.get(self).overlay_key.clone()?;
3518        key.current_state::<OverlayState>(app)
3519    }
3520
3521    fn all_route_overlay_entries(self: Handle<Self>, app: &App) -> Vec<Ref<OverlayEntry>> {
3522        let mut entries = Vec::new();
3523        for entry in self.history_entries(app) {
3524            let route = app.get(entry).route.handle();
3525            entries.extend(
3526                route
3527                    .overlay_entries(app)
3528                    .into_iter()
3529                    .map(|overlay_entry| overlay_entry.keep(app)),
3530            );
3531        }
3532        entries
3533    }
3534
3535    // ---- the history walkers ----
3536
3537    fn get_route_before(
3538        self: Handle<Self>,
3539        app: &App,
3540        index: i64,
3541        predicate: fn(&App, Handle<RouteEntry>) -> bool,
3542    ) -> Option<Handle<RouteEntry>> {
3543        let index = self.get_index_before(app, index, predicate);
3544        (index >= 0).then(|| self.history(app).at(app, index as usize))
3545    }
3546
3547    fn get_index_before(
3548        self: Handle<Self>,
3549        app: &App,
3550        mut index: i64,
3551        predicate: fn(&App, Handle<RouteEntry>) -> bool,
3552    ) -> i64 {
3553        let history = self.history(app);
3554        while index >= 0 && !predicate(app, history.at(app, index as usize)) {
3555            index -= 1;
3556        }
3557        index
3558    }
3559
3560    fn get_route_after(
3561        self: Handle<Self>,
3562        app: &App,
3563        mut index: i64,
3564        predicate: fn(&App, Handle<RouteEntry>) -> bool,
3565    ) -> Option<Handle<RouteEntry>> {
3566        let history = self.history(app);
3567        let length = history.len(app) as i64;
3568        while index < length && !predicate(app, history.at(app, index as usize)) {
3569            index += 1;
3570        }
3571        (index < length).then(|| history.at(app, index as usize))
3572    }
3573
3574    pub(crate) fn first_route_entry_where_or_null(
3575        self: Handle<Self>,
3576        app: &App,
3577        test: impl Fn(&App, Handle<RouteEntry>) -> bool,
3578    ) -> Option<Handle<RouteEntry>> {
3579        self.history_entries(app)
3580            .into_iter()
3581            .find(|entry| test(app, *entry))
3582    }
3583
3584    pub(crate) fn last_route_entry_where_or_null(
3585        self: Handle<Self>,
3586        app: &App,
3587        test: impl Fn(&App, Handle<RouteEntry>) -> bool,
3588    ) -> Option<Handle<RouteEntry>> {
3589        let mut result = None;
3590        for entry in self.history_entries(app) {
3591            if test(app, entry) {
3592                result = Some(entry);
3593            }
3594        }
3595        result
3596    }
3597}
3598
3599impl NavigatorState {
3600    /// Dart's `_updatePages`: the diff between the old history and the new [`Navigator::pages`].
3601    fn update_pages(self: Handle<Self>, app: &mut App) {
3602        debug_assert!(!app.get(self).debug_updating_page);
3603        self.debug_check_duplicated_page_keys(app);
3604        app.get_mut(self).debug_updating_page = true;
3605
3606        // This attempts to diff the new pages list (widget.pages) with the old
3607        // _RouteEntry history (_history).
3608        //
3609        // In the case of a newly added page or an unmatched page, the new page is
3610        // added to the newHistory list with a staging state, and the transition
3611        // delegate decides how it enters the screen.
3612        let history = self.history(app);
3613        let mut needs_explicit_decision = false;
3614        let mut new_pages_bottom: i64 = 0;
3615        let mut old_entries_bottom: i64 = 0;
3616        let mut new_pages_top: i64 = self.widget(app).pages.len() as i64 - 1;
3617        let mut old_entries_top: i64 = history.len(app) as i64 - 1;
3618
3619        // The diff names entries bare; these keep the entries it makes until the history is
3620        // rebuilt from its result.
3621        let mut created: Vec<Ref<RouteEntry>> = Vec::new();
3622        let mut new_history: Vec<Handle<RouteEntry>> = Vec::new();
3623        let mut page_route_to_pageless_routes: HashMap<
3624            Option<Handle<RouteEntry>>,
3625            Vec<Handle<RouteEntry>>,
3626        > = HashMap::new();
3627
3628        // Scans the top of the list until we found a page that does not exist in the new list.
3629        let mut previous_old_page_route_entry: Option<Handle<RouteEntry>> = None;
3630        while old_entries_bottom <= old_entries_top {
3631            let old_entry = history.at(app, old_entries_bottom as usize);
3632            debug_assert!(app.get(old_entry).current_state != RouteLifecycle::Disposed);
3633            // Records pageless route. The bottom most pageless routes will be added to the
3634            // most recently scanned page-based route.
3635            if !app.get(old_entry).page_based {
3636                page_route_to_pageless_routes
3637                    .entry(previous_old_page_route_entry)
3638                    .or_default()
3639                    .push(old_entry);
3640                old_entries_bottom += 1;
3641                continue;
3642            }
3643            if new_pages_bottom > new_pages_top {
3644                break;
3645            }
3646            let new_page = self.widget(app).pages[new_pages_bottom as usize].clone();
3647            if !old_entry.can_update_from(app, &new_page) {
3648                break;
3649            }
3650            previous_old_page_route_entry = Some(old_entry);
3651            let route = app.get(old_entry).route.handle();
3652            route.update_settings(app, RouteSettingsRef::Page(new_page));
3653            new_history.push(old_entry);
3654            new_pages_bottom += 1;
3655            old_entries_bottom += 1;
3656        }
3657
3658        let mut unattached_pageless_routes: Vec<Handle<RouteEntry>> = Vec::new();
3659        // Scans the bottom of the list until we found a page that does not exist in the new
3660        // list.
3661        while (old_entries_bottom <= old_entries_top) && (new_pages_bottom <= new_pages_top) {
3662            let old_entry = history.at(app, old_entries_top as usize);
3663            debug_assert!(app.get(old_entry).current_state != RouteLifecycle::Disposed);
3664            if !app.get(old_entry).page_based {
3665                unattached_pageless_routes.push(old_entry);
3666                old_entries_top -= 1;
3667                continue;
3668            }
3669            let new_page = self.widget(app).pages[new_pages_top as usize].clone();
3670            if !old_entry.can_update_from(app, &new_page) {
3671                break;
3672            }
3673
3674            // We found the page for all the consecutive pageless routes below. Attach these
3675            // pageless routes to the page.
3676            if !unattached_pageless_routes.is_empty() {
3677                page_route_to_pageless_routes
3678                    .entry(Some(old_entry))
3679                    .or_insert_with(|| unattached_pageless_routes.clone());
3680                unattached_pageless_routes.clear();
3681            }
3682
3683            old_entries_top -= 1;
3684            new_pages_top -= 1;
3685        }
3686        // Reverts the pageless routes that cannot be updated.
3687        old_entries_top += unattached_pageless_routes.len() as i64;
3688
3689        // Scans the remaining routes and records the page keys.
3690        let mut old_entries_bottom_to_scan = old_entries_bottom;
3691        let mut page_key_to_old_entry: Vec<(KeyRef, Handle<RouteEntry>)> = Vec::new();
3692        // This set contains entries that are transitioning out but are still in the widget's
3693        // pages list; they should not be reused during the diff.
3694        let mut phantom_entries: HashSet<Handle<RouteEntry>> = HashSet::new();
3695        while old_entries_bottom_to_scan <= old_entries_top {
3696            let old_entry = history.at(app, old_entries_bottom_to_scan as usize);
3697            old_entries_bottom_to_scan += 1;
3698            debug_assert!(app.get(old_entry).current_state != RouteLifecycle::Disposed);
3699            // Pageless routes will be recorded when we update the middle of the old list.
3700            if !app.get(old_entry).page_based {
3701                continue;
3702            }
3703
3704            let settings = app.get(old_entry).route.settings(app);
3705            let page = settings.as_page().expect("a page-based route has a page");
3706            let Some(key) = page.key().cloned() else {
3707                continue;
3708            };
3709
3710            if !old_entry.will_be_present(app) {
3711                phantom_entries.insert(old_entry);
3712                continue;
3713            }
3714            debug_assert!(!page_key_to_old_entry.iter().any(|(k, _)| *k == key));
3715            page_key_to_old_entry.push((key, old_entry));
3716        }
3717
3718        // Updates the middle of the list.
3719        while new_pages_bottom <= new_pages_top {
3720            let next_page = self.widget(app).pages[new_pages_bottom as usize].clone();
3721            new_pages_bottom += 1;
3722            let matching = next_page.key().and_then(|key| {
3723                page_key_to_old_entry
3724                    .iter()
3725                    .position(|(other, _)| other == key)
3726            });
3727            let matching = matching.filter(|index| {
3728                let entry = page_key_to_old_entry[*index].1;
3729                entry.can_update_from(app, &next_page)
3730            });
3731            match matching {
3732                None => {
3733                    // There is no matching key in the old history, we need to create a new
3734                    // route and wait for the transition delegate to decide how to add it into
3735                    // the history.
3736                    let context = self.context(app);
3737                    let route = next_page.create_route(app, context, &next_page);
3738                    debug_assert!(
3739                        route.settings(app) == RouteSettingsRef::Page(Rc::clone(&next_page)),
3740                        "The settings of a page-based Route must be the Page object. Please set \
3741                         the settings to the Page in the Page::create_route method."
3742                    );
3743                    let new_entry =
3744                        RouteEntry::new(app, route, RouteLifecycle::Staging, true, None);
3745                    needs_explicit_decision = true;
3746                    new_history.push(new_entry.handle());
3747                    created.push(new_entry);
3748                }
3749                Some(index) => {
3750                    // Removes the key from the keyToOldEntry map so it will not be reused.
3751                    let (_, matching_entry) = page_key_to_old_entry.remove(index);
3752                    debug_assert!(matching_entry.can_update_from(app, &next_page));
3753                    let route = app.get(matching_entry).route.handle();
3754                    route.update_settings(app, RouteSettingsRef::Page(next_page));
3755                    new_history.push(matching_entry);
3756                }
3757            }
3758        }
3759
3760        // Any remaining old routes that do not have a match will need to be removed.
3761        let mut location_to_exiting_page_route: HashMap<
3762            Option<Handle<RouteEntry>>,
3763            Handle<RouteEntry>,
3764        > = HashMap::new();
3765        while old_entries_bottom <= old_entries_top {
3766            let potential_entry_to_remove = history.at(app, old_entries_bottom as usize);
3767            old_entries_bottom += 1;
3768
3769            if !app.get(potential_entry_to_remove).page_based {
3770                debug_assert!(previous_old_page_route_entry.is_some());
3771                page_route_to_pageless_routes
3772                    .entry(previous_old_page_route_entry)
3773                    .or_default()
3774                    .push(potential_entry_to_remove);
3775                let previous = previous_old_page_route_entry.expect("asserted above");
3776                if previous.is_waiting_for_exiting_decision(app)
3777                    && potential_entry_to_remove.will_be_present(app)
3778                {
3779                    potential_entry_to_remove.mark_needs_exiting_decision(app);
3780                }
3781                continue;
3782            }
3783
3784            let settings = app.get(potential_entry_to_remove).route.settings(app);
3785            let potential_page_to_remove = settings
3786                .as_page()
3787                .expect("a page-based route has a page")
3788                .clone();
3789
3790            // Marks for transition delegate to remove if this old page does not have a key,
3791            // was not taken during updating the middle of new page, or is a phantom entry.
3792            let key_is_free = match potential_page_to_remove.key() {
3793                None => true,
3794                Some(key) => page_key_to_old_entry.iter().any(|(other, _)| other == key),
3795            };
3796            if key_is_free || phantom_entries.contains(&potential_entry_to_remove) {
3797                location_to_exiting_page_route
3798                    .insert(previous_old_page_route_entry, potential_entry_to_remove);
3799                // We only need a decision if it has not already been popped.
3800                if potential_entry_to_remove.will_be_present(app) {
3801                    potential_entry_to_remove.mark_needs_exiting_decision(app);
3802                }
3803            }
3804            previous_old_page_route_entry = Some(potential_entry_to_remove);
3805        }
3806
3807        // We've scanned the whole list.
3808        debug_assert!(old_entries_bottom == old_entries_top + 1);
3809        debug_assert!(new_pages_bottom == new_pages_top + 1);
3810        new_pages_top = self.widget(app).pages.len() as i64 - 1;
3811        old_entries_top = history.len(app) as i64 - 1;
3812        // Verifies we either reach the bottom or the oldEntriesBottom must be updatable by
3813        // newPagesBottom.
3814        debug_assert!(if old_entries_bottom <= old_entries_top {
3815            let entry = history.at(app, old_entries_bottom as usize);
3816            let page = self.widget(app).pages[new_pages_bottom as usize].clone();
3817            new_pages_bottom <= new_pages_top
3818                && app.get(entry).page_based
3819                && entry.can_update_from(app, &page)
3820        } else {
3821            new_pages_bottom > new_pages_top
3822        });
3823
3824        // Updates the top of the list.
3825        while (old_entries_bottom <= old_entries_top) && (new_pages_bottom <= new_pages_top) {
3826            let old_entry = history.at(app, old_entries_bottom as usize);
3827            debug_assert!(app.get(old_entry).current_state != RouteLifecycle::Disposed);
3828            if !app.get(old_entry).page_based {
3829                debug_assert!(previous_old_page_route_entry.is_some());
3830                page_route_to_pageless_routes
3831                    .entry(previous_old_page_route_entry)
3832                    .or_default()
3833                    .push(old_entry);
3834                old_entries_bottom += 1;
3835                continue;
3836            }
3837            previous_old_page_route_entry = Some(old_entry);
3838            let new_page = self.widget(app).pages[new_pages_bottom as usize].clone();
3839            debug_assert!(old_entry.can_update_from(app, &new_page));
3840            let route = app.get(old_entry).route.handle();
3841            route.update_settings(app, RouteSettingsRef::Page(new_page));
3842            new_history.push(old_entry);
3843            old_entries_bottom += 1;
3844            new_pages_bottom += 1;
3845        }
3846
3847        // Finally, uses transition delegate to make explicit decision if needed.
3848        needs_explicit_decision =
3849            needs_explicit_decision || !location_to_exiting_page_route.is_empty();
3850        let results = if needs_explicit_decision {
3851            let delegate = Rc::clone(&self.widget(app).transition_delegate);
3852            transition(
3853                &*delegate,
3854                app,
3855                &new_history,
3856                &location_to_exiting_page_route,
3857                &page_route_to_pageless_routes,
3858            )
3859        } else {
3860            new_history
3861        };
3862        // The old entries stay kept while the history is rebuilt.
3863        let previous: Vec<Ref<RouteEntry>> = app.get(history).value.clone();
3864        history.clear(app);
3865        let kept = |app: &App, entries: Vec<Handle<RouteEntry>>| -> Vec<Ref<RouteEntry>> {
3866            entries.into_iter().map(|entry| entry.keep(app)).collect()
3867        };
3868        // Adds the leading pageless routes if there is any.
3869        if let Some(pageless) = page_route_to_pageless_routes.get(&None).cloned() {
3870            let pageless = kept(app, pageless);
3871            history.add_all(app, pageless);
3872        }
3873        for result in results {
3874            let entry = kept(app, vec![result]);
3875            history.add_all(app, entry);
3876            if let Some(pageless) = page_route_to_pageless_routes.get(&Some(result)).cloned() {
3877                let pageless = kept(app, pageless);
3878                history.add_all(app, pageless);
3879            }
3880        }
3881        drop((previous, created));
3882        app.get_mut(self).debug_updating_page = false;
3883        app.get_mut(self).debug_locked = true;
3884        self.flush_history_updates(app, true);
3885        app.get_mut(self).debug_locked = false;
3886    }
3887
3888    /// Dart's `_flushHistoryUpdates`: runs the pending lifecycle transitions of every entry.
3889    pub(crate) fn flush_history_updates(
3890        self: Handle<Self>,
3891        app: &mut App,
3892        rearrange_overlay: bool,
3893    ) {
3894        debug_assert!(!app.get(self).debug_updating_page);
3895        app.get_mut(self).flushing_history = true;
3896        let history = self.history(app);
3897
3898        // Clean up the list, sending updates to the routes that changed. Notably, we don't send
3899        // the didChangePrevious/didChangeNext updates to those that did not change at this
3900        // point, because we're not yet sure exactly what the routes will be at the end of the
3901        // day (some might get disposed).
3902        let mut index: i64 = history.len(app) as i64 - 1;
3903        let mut next: Option<Handle<RouteEntry>> = None;
3904        let mut entry: Option<Handle<RouteEntry>> = Some(history.at(app, index as usize));
3905        let mut previous: Option<Handle<RouteEntry>> =
3906            (index > 0).then(|| history.at(app, (index - 1) as usize));
3907        // Whether there is a fully opaque route on top to silently remove or add a route
3908        // underneath.
3909        let mut can_remove_or_add = false;
3910        // The route that should trigger did_pop_next on the top active route.
3911        let mut popped_route: Option<AnyRoute> = None;
3912        // Whether we've seen the route that would get did_pop_next.
3913        let mut seen_top_active_route = false;
3914        let mut to_be_disposed: Vec<Ref<RouteEntry>> = Vec::new();
3915        while index >= 0 {
3916            loop {
3917                let current = entry.expect("the history has an entry at this index");
3918                match app.get(current).current_state {
3919                    RouteLifecycle::Add => {
3920                        debug_assert!(rearrange_overlay);
3921                        let previous_present = self
3922                            .get_route_before(app, index - 1, RouteEntry::is_present_predicate)
3923                            .map(|entry| app.get(entry).route.clone());
3924                        current.handle_add(app, self, previous_present);
3925                        debug_assert!(app.get(current).current_state == RouteLifecycle::Adding);
3926                        continue;
3927                    }
3928                    RouteLifecycle::Adding => {
3929                        if can_remove_or_add || next.is_none() {
3930                            current.did_add(app, self, next.is_none());
3931                            debug_assert!(app.get(current).current_state == RouteLifecycle::Idle);
3932                            continue;
3933                        }
3934                    }
3935                    RouteLifecycle::Push
3936                    | RouteLifecycle::PushReplace
3937                    | RouteLifecycle::Replace => {
3938                        debug_assert!(rearrange_overlay);
3939                        let previous_route = previous.map(|entry| app.get(entry).route.handle());
3940                        let previous_present = self
3941                            .get_route_before(app, index - 1, RouteEntry::is_present_predicate)
3942                            .map(|entry| app.get(entry).route.clone());
3943                        current.handle_push(
3944                            app,
3945                            self,
3946                            next.is_none(),
3947                            previous_route,
3948                            previous_present,
3949                        );
3950                        debug_assert!(!matches!(
3951                            app.get(current).current_state,
3952                            RouteLifecycle::Push
3953                                | RouteLifecycle::PushReplace
3954                                | RouteLifecycle::Replace
3955                        ));
3956                        if app.get(current).current_state == RouteLifecycle::Idle {
3957                            continue;
3958                        }
3959                    }
3960                    RouteLifecycle::Pushing => {
3961                        // Will exit this state when the animation completes.
3962                        if !seen_top_active_route && let Some(popped) = popped_route {
3963                            current.handle_did_pop_next(app, popped);
3964                        }
3965                        seen_top_active_route = true;
3966                    }
3967                    RouteLifecycle::Idle => {
3968                        if !seen_top_active_route && let Some(popped) = popped_route {
3969                            current.handle_did_pop_next(app, popped);
3970                        }
3971                        seen_top_active_route = true;
3972                        // This route is idle, so we can remove or add routes underneath it
3973                        // without an animation.
3974                        can_remove_or_add = true;
3975                    }
3976                    RouteLifecycle::Pop => {
3977                        let previous_present = self
3978                            .get_route_before(app, index, RouteEntry::will_be_present_predicate)
3979                            .map(|entry| app.get(entry).route.handle());
3980                        if !current.handle_pop(app, self, previous_present) {
3981                            debug_assert!(app.get(current).current_state == RouteLifecycle::Idle);
3982                            continue;
3983                        }
3984                        if !seen_top_active_route {
3985                            if let Some(popped) = popped_route {
3986                                current.handle_did_pop_next(app, popped);
3987                            }
3988                            popped_route = Some(app.get(current).route.handle());
3989                        }
3990                        let route = app.get(current).route.clone();
3991                        let previous_present = self
3992                            .get_route_before(app, index, RouteEntry::will_be_present_predicate)
3993                            .map(|entry| app.get(entry).route.clone());
3994                        app.get_mut(self).observed_route_deletions.push_back(
3995                            NavigatorObservation::Pop {
3996                                primary_route: route,
3997                                secondary_route: previous_present,
3998                            },
3999                        );
4000                        if app.get(current).current_state == RouteLifecycle::Dispose {
4001                            // A route that doesn't animate through its exit will be disposed
4002                            // right away.
4003                            continue;
4004                        }
4005                        debug_assert!(app.get(current).current_state == RouteLifecycle::Popping);
4006                        can_remove_or_add = true;
4007                    }
4008                    RouteLifecycle::Popping => {
4009                        // Will exit this state when the route calls finalize_route.
4010                    }
4011                    RouteLifecycle::Complete => {
4012                        current.handle_complete(app);
4013                        debug_assert!(app.get(current).current_state == RouteLifecycle::Remove);
4014                        continue;
4015                    }
4016                    RouteLifecycle::Remove => {
4017                        if !seen_top_active_route && app.get(current).route.installed(app) {
4018                            if let Some(popped) = popped_route {
4019                                current.handle_did_pop_next(app, popped);
4020                            }
4021                            popped_route = None;
4022                        }
4023                        let previous_present = self
4024                            .get_route_before(app, index, RouteEntry::will_be_present_predicate)
4025                            .map(|entry| app.get(entry).route.clone());
4026                        current.handle_removal(app, self, previous_present);
4027                        debug_assert!(app.get(current).current_state >= RouteLifecycle::Removing);
4028                        continue;
4029                    }
4030                    RouteLifecycle::Removing => {
4031                        if !can_remove_or_add && next.is_some() {
4032                            // We aren't allowed to remove this route yet.
4033                            break;
4034                        }
4035                        app.get_mut(current).current_state = RouteLifecycle::Dispose;
4036                        continue;
4037                    }
4038                    RouteLifecycle::Dispose => {
4039                        // Delay disposal until didChangeNext/didChangePrevious have been sent.
4040                        to_be_disposed.push(history.remove_at(app, index as usize));
4041                        entry = next;
4042                    }
4043                    RouteLifecycle::Disposing
4044                    | RouteLifecycle::Disposed
4045                    | RouteLifecycle::Staging => {
4046                        unreachable!("unexpected route lifecycle while flushing the history")
4047                    }
4048                }
4049                break;
4050            }
4051            index -= 1;
4052            next = entry;
4053            entry = previous;
4054            previous = (index > 0).then(|| history.at(app, (index - 1) as usize));
4055        }
4056
4057        // Informs the observers about route changes.
4058        self.flush_observer_notifications(app);
4059
4060        // Now that the list is clean, send the didChangeNext/didChangePrevious notifications.
4061        self.flush_route_announcement(app);
4062
4063        // Announces route name changes.
4064        let last_entry = self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
4065        if let Some(last_entry) = last_entry
4066            && app.get(self).last_topmost_route.handle() != Some(last_entry)
4067        {
4068            let top_route = app.get(last_entry).route.handle();
4069            let previous_top_route = app
4070                .get(self)
4071                .last_topmost_route
4072                .as_ref()
4073                .map(|entry| app.get(entry).route.handle());
4074            for observer in app.get(self).effective_observers.clone() {
4075                observer.did_change_top(app, top_route, previous_top_route);
4076            }
4077        }
4078        let last_topmost_route = last_entry.map(|entry| entry.keep(app));
4079        app.get_mut(self).last_topmost_route = last_topmost_route;
4080
4081        if self.widget(app).reports_route_update_to_engine {
4082            let route_name = last_entry.and_then(|entry| {
4083                app.get(entry)
4084                    .route
4085                    .settings(app)
4086                    .name()
4087                    .map(str::to_string)
4088            });
4089            if let Some(route_name) = route_name
4090                && Some(&route_name) != app.get(self).last_announced_route_name.as_ref()
4091            {
4092                // `SystemNavigator.routeInformationUpdated` waits; see PORTING.md.
4093                app.get_mut(self).last_announced_route_name = Some(route_name);
4094            }
4095        }
4096
4097        // Lastly, removes the overlay entries of all marked entries and disposes them.
4098        for entry in to_be_disposed {
4099            NavigatorState::dispose_route_entry(app, entry.handle(), true);
4100        }
4101        if rearrange_overlay && let Some(overlay) = self.overlay(app) {
4102            let entries = self.all_route_overlay_entries(app);
4103            overlay.rearrange(app, entries, None, None);
4104        }
4105        if self.bucket(app).is_some() {
4106            let serializable = self.serializable_history(app);
4107            let history = self.history(app);
4108            serializable.update(app, history);
4109        }
4110        app.get_mut(self).flushing_history = false;
4111    }
4112
4113    fn flush_observer_notifications(self: Handle<Self>, app: &mut App) {
4114        if app.get(self).effective_observers.is_empty() {
4115            app.get_mut(self).observed_route_deletions.clear();
4116            app.get_mut(self).observed_route_additions.clear();
4117            return;
4118        }
4119        while let Some(observation) = app.get_mut(self).observed_route_additions.pop_back() {
4120            for observer in app.get(self).effective_observers.clone() {
4121                observation.notify(app, observer.handle());
4122            }
4123        }
4124        while let Some(observation) = app.get_mut(self).observed_route_deletions.pop_front() {
4125            for observer in app.get(self).effective_observers.clone() {
4126                observation.notify(app, observer.handle());
4127            }
4128        }
4129    }
4130
4131    fn flush_route_announcement(self: Handle<Self>, app: &mut App) {
4132        let history = self.history(app);
4133        let mut index: i64 = history.len(app) as i64 - 1;
4134        while index >= 0 {
4135            let entry = history.at(app, index as usize);
4136            if !entry.suitable_for_announcement(app) {
4137                index -= 1;
4138                continue;
4139            }
4140            let next = self.get_route_after(
4141                app,
4142                index + 1,
4143                RouteEntry::suitable_for_transition_animation_predicate,
4144            );
4145            let next_route = next.map(|entry| app.get(entry).route.clone());
4146            if Some(next_route.handle()) != app.get(entry).last_announced_next_route() {
4147                if entry.should_announce_change_to_next(app, next_route.handle()) {
4148                    let route = app.get(entry).route.handle();
4149                    route.did_change_next(app, next_route.handle());
4150                }
4151                app.get_mut(entry).last_announced_next_route = Some(next_route);
4152            }
4153            let previous = self.get_route_before(
4154                app,
4155                index - 1,
4156                RouteEntry::suitable_for_transition_animation_predicate,
4157            );
4158            let previous_route = previous.map(|entry| app.get(entry).route.clone());
4159            if Some(previous_route.handle()) != app.get(entry).last_announced_previous_route() {
4160                let route = app.get(entry).route.handle();
4161                route.did_change_previous(app, previous_route.handle());
4162                app.get_mut(entry).last_announced_previous_route = Some(previous_route);
4163            }
4164            index -= 1;
4165        }
4166    }
4167
4168    fn route_named(
4169        self: Handle<Self>,
4170        app: &mut App,
4171        name: &str,
4172        arguments: Option<Rc<dyn Any>>,
4173        allow_null: bool,
4174    ) -> Option<RouteRef> {
4175        debug_assert!(!app.get(self).debug_locked);
4176        let on_generate_route = self.widget(app).on_generate_route.clone();
4177        let Some(on_generate_route) = on_generate_route else {
4178            assert!(
4179                allow_null,
4180                "Navigator.on_generate_route was None, but the route named \"{name}\" was \
4181                 referenced. To use the Navigator API with named routes (push_named, \
4182                 push_replacement_named, or push_named_and_remove_until), the Navigator must be \
4183                 provided with an on_generate_route handler."
4184            );
4185            return None;
4186        };
4187        let settings = RouteSettings {
4188            name: Some(name.to_string()),
4189            arguments,
4190        };
4191        let mut route = on_generate_route(app, &settings);
4192        if route.is_none() && !allow_null {
4193            let on_unknown_route = self.widget(app).on_unknown_route.clone();
4194            let on_unknown_route = on_unknown_route.unwrap_or_else(|| {
4195                panic!(
4196                    "Navigator.on_generate_route returned None when requested to build route \
4197                     \"{name}\". The on_generate_route callback must never return None, unless \
4198                     an on_unknown_route callback is provided as well."
4199                )
4200            });
4201            route = on_unknown_route(app, &settings);
4202            assert!(
4203                route.is_some(),
4204                "Navigator.on_unknown_route returned None when requested to build route \
4205                 \"{name}\". The on_unknown_route callback must never return None."
4206            );
4207        }
4208        debug_assert!(route.is_some() || allow_null);
4209        route
4210    }
4211}
4212
4213impl NavigatorState {
4214    /// Push a named route onto the navigator.
4215    ///
4216    /// The route name will be passed to [`Navigator::on_generate_route`].
4217    ///
4218    /// Returns a future that completes to the `result` value passed to [`pop`](Self::pop) when
4219    /// the pushed route is popped off the navigator.
4220    pub fn push_named(
4221        self: Handle<Self>,
4222        app: &mut App,
4223        route_name: &str,
4224        arguments: Option<Rc<dyn Any>>,
4225    ) -> CompleterFuture<RouteResult> {
4226        let route = self
4227            .route_named(app, route_name, arguments, false)
4228            .expect("a route for the given name");
4229        self.push(app, route)
4230    }
4231
4232    /// Push a named route onto the navigator and return its restoration ID.
4233    ///
4234    /// The route name will be passed to [`Navigator::on_generate_route`].
4235    pub fn restorable_push_named(
4236        self: Handle<Self>,
4237        app: &mut App,
4238        route_name: &str,
4239        arguments: Option<RestorationData>,
4240    ) -> String {
4241        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4242        let information = Rc::new(RestorationInformation::Named {
4243            name: route_name.to_string(),
4244            arguments,
4245            restoration_scope_id,
4246        });
4247        let entry = information.to_route_entry(app, self, RouteLifecycle::Push);
4248        let pushed = entry.handle();
4249        self.push_entry(app, entry);
4250        pushed.restoration_id(app).expect("a restorable entry")
4251    }
4252
4253    /// Replace the current route of the navigator by pushing the route named `route_name` and
4254    /// then disposing the previous route once the animation has completed.
4255    pub fn push_replacement_named(
4256        self: Handle<Self>,
4257        app: &mut App,
4258        route_name: &str,
4259        result: RouteResult,
4260        arguments: Option<Rc<dyn Any>>,
4261    ) -> CompleterFuture<RouteResult> {
4262        let route = self
4263            .route_named(app, route_name, arguments, false)
4264            .expect("a route for the given name");
4265        self.push_replacement(app, route, result)
4266    }
4267
4268    /// The restorable version of [`push_replacement_named`](Self::push_replacement_named).
4269    pub fn restorable_push_replacement_named(
4270        self: Handle<Self>,
4271        app: &mut App,
4272        route_name: &str,
4273        result: RouteResult,
4274        arguments: Option<RestorationData>,
4275    ) -> String {
4276        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4277        let information = Rc::new(RestorationInformation::Named {
4278            name: route_name.to_string(),
4279            arguments,
4280            restoration_scope_id,
4281        });
4282        let entry = information.to_route_entry(app, self, RouteLifecycle::PushReplace);
4283        let pushed = entry.handle();
4284        self.push_replacement_entry(app, entry, result);
4285        pushed.restoration_id(app).expect("a restorable entry")
4286    }
4287
4288    /// Pop the current route off the navigator and push a named route in its place.
4289    pub fn pop_and_push_named(
4290        self: Handle<Self>,
4291        app: &mut App,
4292        route_name: &str,
4293        result: RouteResult,
4294        arguments: Option<Rc<dyn Any>>,
4295    ) -> CompleterFuture<RouteResult> {
4296        self.pop(app, result);
4297        self.push_named(app, route_name, arguments)
4298    }
4299
4300    /// The restorable version of [`pop_and_push_named`](Self::pop_and_push_named).
4301    pub fn restorable_pop_and_push_named(
4302        self: Handle<Self>,
4303        app: &mut App,
4304        route_name: &str,
4305        result: RouteResult,
4306        arguments: Option<RestorationData>,
4307    ) -> String {
4308        self.pop(app, result);
4309        self.restorable_push_named(app, route_name, arguments)
4310    }
4311
4312    /// Push the route with the given name onto the navigator, and then remove all the previous
4313    /// routes until the `predicate` returns true.
4314    pub fn push_named_and_remove_until(
4315        self: Handle<Self>,
4316        app: &mut App,
4317        new_route_name: &str,
4318        predicate: RoutePredicate,
4319        arguments: Option<Rc<dyn Any>>,
4320    ) -> CompleterFuture<RouteResult> {
4321        let route = self
4322            .route_named(app, new_route_name, arguments, false)
4323            .expect("a route for the given name");
4324        self.push_and_remove_until(app, route, predicate)
4325    }
4326
4327    /// The restorable version of
4328    /// [`push_named_and_remove_until`](Self::push_named_and_remove_until).
4329    pub fn restorable_push_named_and_remove_until(
4330        self: Handle<Self>,
4331        app: &mut App,
4332        new_route_name: &str,
4333        predicate: RoutePredicate,
4334        arguments: Option<RestorationData>,
4335    ) -> String {
4336        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4337        let information = Rc::new(RestorationInformation::Named {
4338            name: new_route_name.to_string(),
4339            arguments,
4340            restoration_scope_id,
4341        });
4342        let entry = information.to_route_entry(app, self, RouteLifecycle::Push);
4343        let pushed = entry.handle();
4344        self.push_entry_and_remove_until(app, entry, predicate);
4345        pushed.restoration_id(app).expect("a restorable entry")
4346    }
4347
4348    /// Push the given route onto the navigator.
4349    ///
4350    /// Returns a future that completes to the `result` value passed to [`pop`](Self::pop) when
4351    /// the pushed route is popped off the navigator.
4352    pub fn push(
4353        self: Handle<Self>,
4354        app: &mut App,
4355        route: RouteRef,
4356    ) -> CompleterFuture<RouteResult> {
4357        let popped = route.popped(app);
4358        let entry = RouteEntry::new(app, route, RouteLifecycle::Push, false, None);
4359        self.push_entry(app, entry);
4360        popped
4361    }
4362
4363    /// Push a new route onto the navigator and return its restoration ID.
4364    ///
4365    /// The route is created by `route_builder`, which is called again during state restoration.
4366    pub fn restorable_push(
4367        self: Handle<Self>,
4368        app: &mut App,
4369        route_builder: RestorableRouteBuilder,
4370        arguments: Option<RestorationData>,
4371    ) -> String {
4372        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4373        let information = Rc::new(RestorationInformation::Anonymous {
4374            route_builder,
4375            arguments,
4376            restoration_scope_id,
4377        });
4378        let entry = information.to_route_entry(app, self, RouteLifecycle::Push);
4379        let pushed = entry.handle();
4380        self.push_entry(app, entry);
4381        pushed.restoration_id(app).expect("a restorable entry")
4382    }
4383
4384    fn push_entry(self: Handle<Self>, app: &mut App, kept: Ref<RouteEntry>) {
4385        let entry = kept.handle();
4386        debug_assert!(!app.get(self).debug_locked);
4387        app.get_mut(self).debug_locked = true;
4388        debug_assert!(!app.get(entry).route.installed(app));
4389        debug_assert!(app.get(entry).current_state == RouteLifecycle::Push);
4390        self.history(app).add(app, kept);
4391        self.flush_history_updates(app, true);
4392        app.get_mut(self).debug_locked = false;
4393        let route = app.get(entry).route.handle();
4394        self.after_navigation(app, Some(route));
4395    }
4396
4397    fn after_navigation(self: Handle<Self>, app: &mut App, route: Option<AnyRoute>) {
4398        // Dart posts a `Flutter.Navigation` developer event here; diagnostics wait.
4399        let _ = route;
4400        self.cancel_active_pointers(app);
4401    }
4402
4403    /// Replace the current route of the navigator by pushing the given route and then disposing
4404    /// the previous route once the new route has finished animating in.
4405    pub fn push_replacement(
4406        self: Handle<Self>,
4407        app: &mut App,
4408        new_route: RouteRef,
4409        result: RouteResult,
4410    ) -> CompleterFuture<RouteResult> {
4411        debug_assert!(!new_route.installed(app));
4412        let popped = new_route.popped(app);
4413        let entry = RouteEntry::new(app, new_route, RouteLifecycle::PushReplace, false, None);
4414        self.push_replacement_entry(app, entry, result);
4415        popped
4416    }
4417
4418    /// The restorable version of [`push_replacement`](Self::push_replacement).
4419    pub fn restorable_push_replacement(
4420        self: Handle<Self>,
4421        app: &mut App,
4422        route_builder: RestorableRouteBuilder,
4423        result: RouteResult,
4424        arguments: Option<RestorationData>,
4425    ) -> String {
4426        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4427        let information = Rc::new(RestorationInformation::Anonymous {
4428            route_builder,
4429            arguments,
4430            restoration_scope_id,
4431        });
4432        let entry = information.to_route_entry(app, self, RouteLifecycle::PushReplace);
4433        let pushed = entry.handle();
4434        self.push_replacement_entry(app, entry, result);
4435        pushed.restoration_id(app).expect("a restorable entry")
4436    }
4437
4438    fn push_replacement_entry(
4439        self: Handle<Self>,
4440        app: &mut App,
4441        kept: Ref<RouteEntry>,
4442        result: RouteResult,
4443    ) {
4444        let entry = kept.handle();
4445        debug_assert!(!app.get(self).debug_locked);
4446        app.get_mut(self).debug_locked = true;
4447        debug_assert!(!app.get(entry).route.installed(app));
4448        debug_assert!(!self.history(app).is_empty(app));
4449        debug_assert!(
4450            self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate)
4451                .is_some(),
4452            "Navigator has no active routes to replace."
4453        );
4454        debug_assert!(app.get(entry).current_state == RouteLifecycle::PushReplace);
4455        let last_present = self
4456            .last_route_entry_where_or_null(app, RouteEntry::is_present_predicate)
4457            .expect("asserted above");
4458        last_present.complete(app, result, true, true);
4459        self.history(app).add(app, kept);
4460        self.flush_history_updates(app, true);
4461        app.get_mut(self).debug_locked = false;
4462        let route = app.get(entry).route.handle();
4463        self.after_navigation(app, Some(route));
4464    }
4465
4466    /// Push the given route onto the navigator, and then remove all the previous routes until the
4467    /// `predicate` returns true.
4468    pub fn push_and_remove_until(
4469        self: Handle<Self>,
4470        app: &mut App,
4471        new_route: RouteRef,
4472        predicate: RoutePredicate,
4473    ) -> CompleterFuture<RouteResult> {
4474        debug_assert!(!new_route.installed(app));
4475        debug_assert!(new_route.overlay_entries(app).is_empty());
4476        let popped = new_route.popped(app);
4477        let entry = RouteEntry::new(app, new_route, RouteLifecycle::Push, false, None);
4478        self.push_entry_and_remove_until(app, entry, predicate);
4479        popped
4480    }
4481
4482    /// The restorable version of [`push_and_remove_until`](Self::push_and_remove_until).
4483    pub fn restorable_push_and_remove_until(
4484        self: Handle<Self>,
4485        app: &mut App,
4486        new_route_builder: RestorableRouteBuilder,
4487        predicate: RoutePredicate,
4488        arguments: Option<RestorationData>,
4489    ) -> String {
4490        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4491        let information = Rc::new(RestorationInformation::Anonymous {
4492            route_builder: new_route_builder,
4493            arguments,
4494            restoration_scope_id,
4495        });
4496        let entry = information.to_route_entry(app, self, RouteLifecycle::Push);
4497        let pushed = entry.handle();
4498        self.push_entry_and_remove_until(app, entry, predicate);
4499        pushed.restoration_id(app).expect("a restorable entry")
4500    }
4501
4502    fn push_entry_and_remove_until(
4503        self: Handle<Self>,
4504        app: &mut App,
4505        kept: Ref<RouteEntry>,
4506        predicate: RoutePredicate,
4507    ) {
4508        let entry = kept.handle();
4509        debug_assert!(!app.get(self).debug_locked);
4510        app.get_mut(self).debug_locked = true;
4511        debug_assert!(!app.get(entry).route.installed(app));
4512        debug_assert!(app.get(entry).route.overlay_entries(app).is_empty());
4513        debug_assert!(app.get(entry).current_state == RouteLifecycle::Push);
4514        let history = self.history(app);
4515        let mut index: i64 = history.len(app) as i64 - 1;
4516        history.add(app, kept);
4517        while index >= 0 {
4518            let candidate = history.at(app, index as usize);
4519            let route = app.get(candidate).route.handle();
4520            if predicate(app, route) {
4521                break;
4522            }
4523            if candidate.is_present(app) {
4524                candidate.complete(app, None, false, true);
4525            }
4526            index -= 1;
4527        }
4528        self.flush_history_updates(app, true);
4529        app.get_mut(self).debug_locked = false;
4530        let route = app.get(entry).route.handle();
4531        self.after_navigation(app, Some(route));
4532    }
4533
4534    /// Replaces a route on the navigator with a new route.
4535    pub fn replace(self: Handle<Self>, app: &mut App, old_route: AnyRoute, new_route: RouteRef) {
4536        debug_assert!(!app.get(self).debug_locked);
4537        debug_assert!(old_route.is_installed_in(app, self));
4538        let entry = RouteEntry::new(app, new_route, RouteLifecycle::Replace, false, None);
4539        self.replace_entry(app, entry, old_route);
4540    }
4541
4542    /// The restorable version of [`replace`](Self::replace).
4543    pub fn restorable_replace(
4544        self: Handle<Self>,
4545        app: &mut App,
4546        old_route: AnyRoute,
4547        new_route_builder: RestorableRouteBuilder,
4548        arguments: Option<RestorationData>,
4549    ) -> String {
4550        debug_assert!(old_route.is_installed_in(app, self));
4551        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4552        let information = Rc::new(RestorationInformation::Anonymous {
4553            route_builder: new_route_builder,
4554            arguments,
4555            restoration_scope_id,
4556        });
4557        let entry = information.to_route_entry(app, self, RouteLifecycle::Replace);
4558        let pushed = entry.handle();
4559        self.replace_entry(app, entry, old_route);
4560        pushed.restoration_id(app).expect("a restorable entry")
4561    }
4562
4563    fn replace_entry(
4564        self: Handle<Self>,
4565        app: &mut App,
4566        kept: Ref<RouteEntry>,
4567        old_route: AnyRoute,
4568    ) {
4569        let entry = kept.handle();
4570        debug_assert!(!app.get(self).debug_locked);
4571        if old_route == app.get(entry).route {
4572            return;
4573        }
4574        app.get_mut(self).debug_locked = true;
4575        debug_assert!(app.get(entry).current_state == RouteLifecycle::Replace);
4576        debug_assert!(!app.get(entry).route.installed(app));
4577        let history = self.history(app);
4578        let index = history
4579            .index_where(app, |app, other| app.get(other).route == old_route)
4580            .expect("This Navigator does not contain the specified old_route.");
4581        debug_assert!(
4582            history.at(app, index).is_present(app),
4583            "The specified old_route has already been removed from the Navigator."
4584        );
4585        let was_current = old_route.is_current(app);
4586        history.insert(app, index + 1, kept);
4587        history.at(app, index).complete(app, None, true, true);
4588        self.flush_history_updates(app, true);
4589        app.get_mut(self).debug_locked = false;
4590        if was_current {
4591            let route = app.get(entry).route.handle();
4592            self.after_navigation(app, Some(route));
4593        }
4594    }
4595
4596    /// Replaces a route on the navigator with a new route. The route to be replaced is the one
4597    /// below the given `anchor_route`.
4598    pub fn replace_route_below(
4599        self: Handle<Self>,
4600        app: &mut App,
4601        anchor_route: AnyRoute,
4602        new_route: RouteRef,
4603    ) {
4604        debug_assert!(!new_route.installed(app));
4605        debug_assert!(anchor_route.is_installed_in(app, self));
4606        let entry = RouteEntry::new(app, new_route, RouteLifecycle::Replace, false, None);
4607        self.replace_entry_below(app, entry, anchor_route);
4608    }
4609
4610    /// The restorable version of [`replace_route_below`](Self::replace_route_below).
4611    pub fn restorable_replace_route_below(
4612        self: Handle<Self>,
4613        app: &mut App,
4614        anchor_route: AnyRoute,
4615        new_route_builder: RestorableRouteBuilder,
4616        arguments: Option<RestorationData>,
4617    ) -> String {
4618        debug_assert!(anchor_route.is_installed_in(app, self));
4619        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
4620        let information = Rc::new(RestorationInformation::Anonymous {
4621            route_builder: new_route_builder,
4622            arguments,
4623            restoration_scope_id,
4624        });
4625        let entry = information.to_route_entry(app, self, RouteLifecycle::Replace);
4626        let pushed = entry.handle();
4627        self.replace_entry_below(app, entry, anchor_route);
4628        pushed.restoration_id(app).expect("a restorable entry")
4629    }
4630
4631    fn replace_entry_below(
4632        self: Handle<Self>,
4633        app: &mut App,
4634        entry: Ref<RouteEntry>,
4635        anchor_route: AnyRoute,
4636    ) {
4637        debug_assert!(!app.get(self).debug_locked);
4638        app.get_mut(self).debug_locked = true;
4639        let history = self.history(app);
4640        let anchor_index = history
4641            .index_where(app, |app, other| app.get(other).route == anchor_route)
4642            .expect("This Navigator does not contain the specified anchor_route.");
4643        debug_assert!(
4644            history.at(app, anchor_index).is_present(app),
4645            "The specified anchor_route has already been removed from the Navigator."
4646        );
4647        let mut index: i64 = anchor_index as i64 - 1;
4648        while index >= 0 {
4649            if history.at(app, index as usize).is_present(app) {
4650                break;
4651            }
4652            index -= 1;
4653        }
4654        assert!(
4655            index >= 0,
4656            "There are no routes below the specified anchor_route."
4657        );
4658        history.insert(app, (index + 1) as usize, entry);
4659        history
4660            .at(app, index as usize)
4661            .complete(app, None, true, true);
4662        self.flush_history_updates(app, true);
4663        app.get_mut(self).debug_locked = false;
4664    }
4665
4666    /// Whether the navigator can be popped.
4667    pub fn can_pop(self: Handle<Self>, app: &App) -> bool {
4668        let mut present = self
4669            .history_entries(app)
4670            .into_iter()
4671            .filter(|entry| entry.is_present(app));
4672        let Some(first) = present.next() else {
4673            // Non-existent route.
4674            return false;
4675        };
4676        if app.get(first).route.will_handle_pop_internally(app) {
4677            // The first route can handle pops itself.
4678            return true;
4679        }
4680        // There's at least two routes, so we can pop.
4681        present.next().is_some()
4682    }
4683
4684    /// Consults the current route's [`AnyRoute::pop_disposition`] method, and acts accordingly,
4685    /// potentially popping the route as a result; returns whether the pop request should be
4686    /// considered handled.
4687    pub fn maybe_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
4688        let last_entry = self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
4689        let Some(last_entry) = last_entry else {
4690            return false;
4691        };
4692        debug_assert!(app.get(last_entry).route.is_installed_in(app, self));
4693
4694        // Dart awaits the deprecated `willPop`; there is no event loop here, so it answers
4695        // within the call.
4696        let route = app.get(last_entry).route.handle();
4697        if route.will_pop(app) == RoutePopDisposition::DoNotPop {
4698            return true;
4699        }
4700        if !self.mounted(app) {
4701            // Forget about this pop, we were disposed in the meantime.
4702            return true;
4703        }
4704
4705        let new_last_entry =
4706            self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
4707        if Some(last_entry) != new_last_entry {
4708            // Forget about this pop, something happened to our history in the meantime.
4709            return true;
4710        }
4711
4712        match route.pop_disposition(app) {
4713            RoutePopDisposition::Bubble => false,
4714            RoutePopDisposition::Pop => {
4715                self.pop(app, result);
4716                true
4717            }
4718            RoutePopDisposition::DoNotPop => {
4719                route.on_pop_invoked_with_result(app, false, result);
4720                true
4721            }
4722        }
4723    }
4724
4725    /// Pop the top-most route off the navigator.
4726    pub fn pop(self: Handle<Self>, app: &mut App, result: RouteResult) {
4727        debug_assert!(!app.get(self).debug_locked);
4728        app.get_mut(self).debug_locked = true;
4729        let entry = self
4730            .last_route_entry_where_or_null(app, RouteEntry::is_present_predicate)
4731            .expect("a present route to pop");
4732        let on_pop_page = self.widget(app).on_pop_page.clone();
4733        if app.get(entry).page_based
4734            && let Some(on_pop_page) = on_pop_page
4735        {
4736            let route = app.get(entry).route.handle();
4737            if on_pop_page(app, route, result.clone()) {
4738                if app.get(entry).current_state <= RouteLifecycle::Idle {
4739                    debug_assert!(route.data(app).pop_completer.is_completed());
4740                    app.get_mut(entry).current_state = RouteLifecycle::Pop;
4741                }
4742                route.on_pop_invoked_with_result(app, true, result);
4743            }
4744        } else {
4745            entry.pop(app, result, true);
4746            debug_assert!(app.get(entry).current_state == RouteLifecycle::Pop);
4747        }
4748        if app.get(entry).current_state == RouteLifecycle::Pop {
4749            self.flush_history_updates(app, false);
4750        }
4751        app.get_mut(self).debug_locked = false;
4752        let route = app.get(entry).route.handle();
4753        self.after_navigation(app, Some(route));
4754    }
4755
4756    /// Calls [`pop`](Self::pop) repeatedly until the `predicate` returns true.
4757    pub fn pop_until(self: Handle<Self>, app: &mut App, predicate: RoutePredicate) {
4758        let mut candidate =
4759            self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
4760        while let Some(entry) = candidate {
4761            let route = app.get(entry).route.handle();
4762            if predicate(app, route) {
4763                return;
4764            }
4765            self.pop(app, None);
4766            candidate = self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
4767        }
4768    }
4769
4770    /// Calls [`pop`](Self::pop) repeatedly until the `predicate` returns true, passing `result`
4771    /// to the last route that is popped.
4772    pub fn pop_until_with_result(
4773        self: Handle<Self>,
4774        app: &mut App,
4775        predicate: RoutePredicate,
4776        result: RouteResult,
4777    ) {
4778        let mut candidate =
4779            self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
4780        while let Some(entry) = candidate {
4781            let route = app.get(entry).route.handle();
4782            if predicate(app, route) {
4783                return;
4784            }
4785
4786            let next = self.last_route_entry_where_or_null(app, move |app, other| {
4787                RouteEntry::is_present_predicate(app, other) && other != entry
4788            });
4789
4790            let pops_with_result = match next {
4791                Some(next) => {
4792                    let next_route = app.get(next).route.handle();
4793                    !route.will_handle_pop_internally(app) && predicate(app, next_route)
4794                }
4795                None => false,
4796            };
4797            if pops_with_result {
4798                self.pop(app, result.clone());
4799            } else {
4800                self.pop(app, None);
4801            }
4802
4803            candidate = self.last_route_entry_where_or_null(app, RouteEntry::is_present_predicate);
4804        }
4805    }
4806
4807    /// Immediately remove `route` from the navigator, and dispose of it.
4808    pub fn remove_route(self: Handle<Self>, app: &mut App, route: AnyRoute, result: RouteResult) {
4809        debug_assert!(!app.get(self).debug_locked);
4810        app.get_mut(self).debug_locked = true;
4811        debug_assert!(route.is_installed_in(app, self));
4812        let was_current = route.is_current(app);
4813        let entry = self
4814            .first_route_entry_where_or_null(app, move |app, entry| app.get(entry).route == route)
4815            .expect("This Navigator does not contain the specified route.");
4816        entry.complete(app, result, false, true);
4817        self.flush_history_updates(app, false);
4818        app.get_mut(self).debug_locked = false;
4819        if was_current {
4820            let route = self
4821                .last_route_entry_where_or_null(app, RouteEntry::is_present_predicate)
4822                .map(|entry| app.get(entry).route.handle());
4823            self.after_navigation(app, route);
4824        }
4825    }
4826
4827    /// Immediately remove a route from the navigator, and dispose of it. The route to be removed
4828    /// is the one below the given `anchor_route`.
4829    pub fn remove_route_below(
4830        self: Handle<Self>,
4831        app: &mut App,
4832        anchor_route: AnyRoute,
4833        result: RouteResult,
4834    ) {
4835        debug_assert!(!app.get(self).debug_locked);
4836        app.get_mut(self).debug_locked = true;
4837        debug_assert!(anchor_route.is_installed_in(app, self));
4838        let history = self.history(app);
4839        let anchor_index = history
4840            .index_where(app, move |app, entry| app.get(entry).route == anchor_route)
4841            .expect("This Navigator does not contain the specified anchor_route.");
4842        debug_assert!(
4843            history.at(app, anchor_index).is_present(app),
4844            "The specified anchor_route has already been removed from the Navigator."
4845        );
4846        let mut index: i64 = anchor_index as i64 - 1;
4847        while index >= 0 {
4848            if history.at(app, index as usize).is_present(app) {
4849                break;
4850            }
4851            index -= 1;
4852        }
4853        assert!(
4854            index >= 0,
4855            "There are no routes below the specified anchor_route."
4856        );
4857        history
4858            .at(app, index as usize)
4859            .complete(app, result, false, true);
4860        self.flush_history_updates(app, false);
4861        app.get_mut(self).debug_locked = false;
4862    }
4863
4864    /// Complete the lifecycle for a route that has been popped off the navigator.
4865    ///
4866    /// When the navigator pops a route, the navigator retains a reference to the route in order
4867    /// to call [`Route::dispose`] if the navigator itself is removed from the tree. When the
4868    /// route is finished with any exit animation, the route should call this function to complete
4869    /// its lifecycle (e.g., to receive a call to `dispose`).
4870    pub fn finalize_route(self: Handle<Self>, app: &mut App, route: AnyRoute) {
4871        // FinalizeRoute may have been called while we were already locked as a
4872        // responsibility of another route entry. For instance, popping a route may lead to
4873        // another route with the same animation being pushed and immediately finalized.
4874        let was_debug_locked = app.get(self).debug_locked;
4875        app.get_mut(self).debug_locked = true;
4876        let history = self.history(app);
4877        debug_assert!(
4878            history
4879                .entries(app)
4880                .iter()
4881                .filter(|entry| app.get(**entry).route == route)
4882                .count()
4883                == 1
4884        );
4885        let index = history
4886            .index_where(app, move |app, entry| app.get(entry).route == route)
4887            .expect("This Navigator does not contain the specified route.");
4888        let entry = history.at(app, index);
4889
4890        // For page-based route with zero transition, the finalizeRoute can be called on
4891        // the entry directly without popping the entry from the history.
4892        if app.get(entry).page_based && app.get(entry).current_state < RouteLifecycle::Pop {
4893            let previous_present = self
4894                .get_route_before(app, index as i64 - 1, RouteEntry::will_be_present_predicate)
4895                .map(|entry| app.get(entry).route.clone());
4896            let route = app.get(entry).route.clone();
4897            app.get_mut(self)
4898                .observed_route_deletions
4899                .push_back(NavigatorObservation::Pop {
4900                    primary_route: route,
4901                    secondary_route: previous_present,
4902                });
4903        } else {
4904            debug_assert!(app.get(entry).current_state == RouteLifecycle::Popping);
4905        }
4906        entry.finalize(app);
4907
4908        // finalizeRoute can be called during _flushHistoryUpdates if a pop is called from a
4909        // route's dispose.
4910        if !app.get(self).flushing_history {
4911            self.flush_history_updates(app, false);
4912        }
4913        app.get_mut(self).debug_locked = was_debug_locked;
4914    }
4915
4916    fn get_route_by_id(self: Handle<Self>, app: &App, id: &str) -> Option<AnyRoute> {
4917        let id = id.to_string();
4918        self.first_route_entry_where_or_null(app, move |app, entry| {
4919            entry.restoration_id(app).as_deref() == Some(id.as_str())
4920        })
4921        .map(|entry| app.get(entry).route.handle())
4922    }
4923
4924    fn set_user_gestures_in_progress(self: Handle<Self>, app: &mut App, value: i64) {
4925        app.get_mut(self).user_gestures_in_progress_count = value;
4926        let notifier = self.user_gesture_in_progress_notifier(app);
4927        notifier.set_value(app, value > 0);
4928    }
4929
4930    /// Called when a route is about to be moved by a user gesture.
4931    ///
4932    /// This is called by the route that is being moved, and is used to inform the observers.
4933    pub fn did_start_user_gesture(self: Handle<Self>, app: &mut App) {
4934        let count = app.get(self).user_gestures_in_progress_count + 1;
4935        self.set_user_gestures_in_progress(app, count);
4936        if count == 1 {
4937            let history = self.history(app);
4938            let route_index = self.get_index_before(
4939                app,
4940                history.len(app) as i64 - 1,
4941                RouteEntry::will_be_present_predicate,
4942            );
4943            let route = app
4944                .get(history.at(app, route_index as usize))
4945                .route
4946                .handle();
4947            let mut previous_route = None;
4948            if !route.will_handle_pop_internally(app) && route_index > 0 {
4949                previous_route = Some(
4950                    app.get(
4951                        self.get_route_before(
4952                            app,
4953                            route_index - 1,
4954                            RouteEntry::will_be_present_predicate,
4955                        )
4956                        .expect("a route below the one being moved"),
4957                    )
4958                    .route
4959                    .handle(),
4960                );
4961            }
4962            for observer in app.get(self).effective_observers.clone() {
4963                observer.did_start_user_gesture(app, route, previous_route);
4964            }
4965        }
4966    }
4967
4968    /// A user gesture completed.
4969    ///
4970    /// Notifies the navigator that a gesture regarding the navigation has stopped.
4971    pub fn did_stop_user_gesture(self: Handle<Self>, app: &mut App) {
4972        debug_assert!(app.get(self).user_gestures_in_progress_count > 0);
4973        let count = app.get(self).user_gestures_in_progress_count - 1;
4974        self.set_user_gestures_in_progress(app, count);
4975        if count == 0 {
4976            for observer in app.get(self).effective_observers.clone() {
4977                observer.did_stop_user_gesture(app);
4978            }
4979        }
4980    }
4981
4982    fn handle_pointer_down(self: Handle<Self>, app: &mut App, pointer: i64) {
4983        app.get_mut(self).active_pointers.insert(pointer);
4984    }
4985
4986    fn handle_pointer_up_or_cancel(self: Handle<Self>, app: &mut App, pointer: i64) {
4987        app.get_mut(self).active_pointers.remove(&pointer);
4988    }
4989
4990    fn cancel_active_pointers(self: Handle<Self>, app: &mut App) {
4991        // If we're between frames (SchedulerPhase.idle) then absorb any subsequent pointers
4992        // from this frame. The absorbing flag will be reset in the next build.
4993        if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::Idle {
4994            let absorber = app
4995                .get(self)
4996                .overlay_key
4997                .clone()
4998                .and_then(|key| key.current_context(app))
4999                .and_then(|context| {
5000                    context.find_ancestor_render_object_of_type::<RenderAbsorbPointer>(app)
5001                });
5002            if let Some(absorber) = absorber {
5003                absorber.set_absorbing(app, true);
5004            }
5005            // We do this in setState so that we will reset _absorbing in build.
5006            self.set_state(app, |_state| {});
5007        }
5008        let pointers: Vec<i64> = app.get(self).active_pointers.iter().copied().collect();
5009        let binding = GestureBinding::instance(app);
5010        for pointer in pointers {
5011            binding.cancel_pointer(app, pointer);
5012        }
5013    }
5014}
5015
5016impl TickerProviderStateMixin for NavigatorState {
5017    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
5018        &app.get(self).ticker_provider
5019    }
5020
5021    fn ticker_provider_data_mut(
5022        self: Handle<Self>,
5023        app: &mut App,
5024    ) -> &mut TickerProviderStateMixinData {
5025        &mut app.get_mut(self).ticker_provider
5026    }
5027}
5028
5029impl TickerProviderObject for NavigatorState {
5030    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
5031        TickerProviderStateMixin::create_ticker(self, app, on_tick)
5032    }
5033}
5034
5035impl RestorationMixin for NavigatorState {
5036    crate::restoration_mixin_accessors!();
5037
5038    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
5039        self.widget(app).restoration_scope_id.as_deref()
5040    }
5041
5042    fn restore_state(
5043        self: Handle<Self>,
5044        app: &mut App,
5045        _old_bucket: Option<Handle<RestorationBucket>>,
5046        _initial_restore: bool,
5047    ) {
5048        let raw_id = app
5049            .get(self)
5050            .raw_next_pageless_restoration_scope_id
5051            .handle()
5052            .expect("init_state has run");
5053        self.register_for_restoration(app, raw_id.as_property(), "id");
5054        let serializable = self.serializable_history(app);
5055        self.register_for_restoration(app, serializable.as_property(), "history");
5056
5057        // Delete everything in the old history and clear the overlay.
5058        self.forced_dispose_all_route_entries(app);
5059        debug_assert!(self.history(app).is_empty(app));
5060        app.get_mut(self).overlay_key = Some(GlobalKey::new());
5061
5062        // Populate the new history from restoration data.
5063        let history = self.history(app);
5064        let restored = serializable.restore_entries_for_page(app, None, self);
5065        history.add_all(app, restored);
5066        for page in self.widget(app).pages.clone() {
5067            let context = self.context(app);
5068            let route = page.create_route(app, context, &page);
5069            debug_assert!(
5070                route.settings(app) == RouteSettingsRef::Page(Rc::clone(&page)),
5071                "The settings of a page-based Route must be the Page object. Please set the \
5072                 settings to the Page in the Page::create_route method."
5073            );
5074            let entry = RouteEntry::new(app, route, RouteLifecycle::Add, true, None);
5075            let page_entry = entry.handle();
5076            history.add(app, entry);
5077            let restored = serializable.restore_entries_for_page(app, Some(page_entry), self);
5078            history.add_all(app, restored);
5079        }
5080
5081        // If there was nothing to restore, we need to process the initial route.
5082        if !serializable.has_data(app) {
5083            let mut initial_route = self.widget(app).initial_route.clone();
5084            if self.widget(app).pages.is_empty() {
5085                initial_route =
5086                    initial_route.or_else(|| Some(Navigator::DEFAULT_ROUTE_NAME.to_string()));
5087            }
5088            if initial_route.is_some() {
5089                let on_generate_initial_routes =
5090                    Rc::clone(&self.widget(app).on_generate_initial_routes);
5091                let name = self
5092                    .widget(app)
5093                    .initial_route
5094                    .clone()
5095                    .unwrap_or_else(|| Navigator::DEFAULT_ROUTE_NAME.to_string());
5096                let routes = on_generate_initial_routes(app, self, &name);
5097                let mut entries = Vec::with_capacity(routes.len());
5098                for route in routes {
5099                    let information = route.settings(app).name().map(|name| {
5100                        let restoration_scope_id = self.next_pageless_restoration_scope_id(app);
5101                        Rc::new(RestorationInformation::Named {
5102                            name: name.to_string(),
5103                            arguments: None,
5104                            restoration_scope_id,
5105                        })
5106                    });
5107                    entries.push(RouteEntry::new(
5108                        app,
5109                        route,
5110                        RouteLifecycle::Add,
5111                        false,
5112                        information,
5113                    ));
5114                }
5115                history.add_all(app, entries);
5116            }
5117        }
5118
5119        assert!(
5120            !history.is_empty(app),
5121            "All routes returned by on_generate_initial_routes are not restorable. Please make \
5122             sure that all routes returned by on_generate_initial_routes have their RouteSettings \
5123             defined with names that are defined in the app's routes table."
5124        );
5125        debug_assert!(!app.get(self).debug_locked);
5126        app.get_mut(self).debug_locked = true;
5127        self.flush_history_updates(app, true);
5128        app.get_mut(self).debug_locked = false;
5129    }
5130
5131    fn did_toggle_bucket(
5132        self: Handle<Self>,
5133        app: &mut App,
5134        old_bucket: Option<Handle<RestorationBucket>>,
5135    ) {
5136        let _ = old_bucket;
5137        let serializable = self.serializable_history(app);
5138        if self.bucket(app).is_some() {
5139            let history = self.history(app);
5140            serializable.update(app, history);
5141        } else {
5142            serializable.clear(app);
5143        }
5144    }
5145}
5146
5147impl State for NavigatorState {
5148    type Widget = Navigator;
5149
5150    crate::state_accessors!();
5151
5152    fn init_state(self: Handle<Self>, app: &mut App) {
5153        let history = History::new(app);
5154        let focus_node = FocusNode::new(app);
5155        focus_node
5156            .as_node()
5157            .set_debug_label(app, Some("Navigator".to_string()));
5158        let serializable_history = HistoryProperty::new(app);
5159        let raw_next_pageless_restoration_scope_id = RestorableInt::new(app, 0);
5160        let user_gesture_in_progress_notifier = app.create(ValueNotifier::new(false));
5161        {
5162            let state = app.get_mut(self);
5163            state.history = Some(history);
5164            state.focus_node = Some(focus_node);
5165            state.serializable_history = Some(serializable_history);
5166            state.raw_next_pageless_restoration_scope_id =
5167                Some(raw_next_pageless_restoration_scope_id);
5168            state.user_gesture_in_progress_notifier = Some(user_gesture_in_progress_notifier);
5169        }
5170        debug_assert!(self.debug_check_page_api_parameters(app));
5171        for observer in self.widget(app).observers.clone() {
5172            debug_assert!(observer.navigator(app).is_none());
5173            observer.set_navigator(app, Some(self));
5174        }
5175        app.get_mut(self).effective_observers = self.widget(app).observers.clone();
5176
5177        // We have to manually extract the inherited widget in initState because the
5178        // `didChangeDependencies` is called after the state is fully created.
5179        let context = self.context(app);
5180        let hero_controller = context
5181            .get_element_for_inherited_widget_of_exact_type::<HeroControllerScope>(app)
5182            .and_then(|element| {
5183                crate::framework::downcast_widget::<HeroControllerScope>(&**element.widget(app))
5184                    .and_then(|scope| scope.controller.handle())
5185            });
5186        self.update_hero_controller(app, hero_controller);
5187
5188        // `SystemNavigator.selectSingleEntryHistory` and the accessibility focus listener wait;
5189        // see PORTING.md.
5190        self.history(app).add_listener(
5191            app,
5192            Listener::handle_method(self, NavigatorState::handle_history_changed),
5193        );
5194    }
5195
5196    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
5197        self.did_change_dependencies_restoration(app);
5198        let context = self.context(app);
5199        let controller = HeroControllerScope::maybe_of(app, context);
5200        self.update_hero_controller(app, controller);
5201        for entry in self.history_entries(app) {
5202            let route = app.get(entry).route.handle();
5203            if route.navigator(app) == Some(self) {
5204                route.changed_external_state(app);
5205            }
5206        }
5207    }
5208
5209    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Navigator) {
5210        self.did_update_restoration_id(app);
5211        debug_assert!(self.debug_check_page_api_parameters(app));
5212        let observers_changed = old_widget.observers.len() != self.widget(app).observers.len()
5213            || old_widget
5214                .observers
5215                .iter()
5216                .zip(self.widget(app).observers.iter())
5217                .any(|(a, b)| a != b);
5218        let old_observers = old_widget.observers.clone();
5219        let old_pages = old_widget.pages.clone();
5220        if observers_changed {
5221            for observer in old_observers {
5222                observer.set_navigator(app, None);
5223            }
5224            for observer in self.widget(app).observers.clone() {
5225                debug_assert!(observer.navigator(app).is_none());
5226                observer.set_navigator(app, Some(self));
5227            }
5228            self.update_effective_observers(app);
5229        }
5230        let pages_changed = old_pages.len() != self.widget(app).pages.len()
5231            || old_pages
5232                .iter()
5233                .zip(self.widget(app).pages.iter())
5234                .any(|(a, b)| !Rc::ptr_eq(a, b));
5235        if pages_changed && !self.restore_pending(app) {
5236            self.update_pages(app);
5237        }
5238
5239        for entry in self.history_entries(app) {
5240            let route = app.get(entry).route.handle();
5241            if route.navigator(app) == Some(self) {
5242                route.changed_external_state(app);
5243            }
5244        }
5245    }
5246
5247    fn deactivate(self: Handle<Self>, app: &mut App) {
5248        for observer in app.get(self).effective_observers.clone() {
5249            observer.set_navigator(app, None);
5250        }
5251        app.get_mut(self).effective_observers.clear();
5252    }
5253
5254    fn activate(self: Handle<Self>, app: &mut App) {
5255        TickerProviderStateMixin::activate(self, app);
5256        self.update_effective_observers(app);
5257        for observer in app.get(self).effective_observers.clone() {
5258            debug_assert!(observer.navigator(app).is_none());
5259            observer.set_navigator(app, Some(self));
5260        }
5261    }
5262
5263    fn dispose(self: Handle<Self>, app: &mut App) {
5264        debug_assert!(!app.get(self).debug_locked);
5265        app.get_mut(self).debug_locked = true;
5266        debug_assert!(app.get(self).effective_observers.is_empty());
5267        self.update_hero_controller(app, None);
5268        self.focus_node(app).as_node().dispose(app);
5269        self.forced_dispose_all_route_entries(app);
5270        let raw_id = app
5271            .get(self)
5272            .raw_next_pageless_restoration_scope_id
5273            .handle()
5274            .expect("init_state has run");
5275        RestorableProperty::dispose(raw_id, app);
5276        let serializable = self.serializable_history(app);
5277        RestorableProperty::dispose(serializable, app);
5278        let notifier = self.user_gesture_in_progress_notifier(app);
5279        notifier.dispose(app);
5280        let history = self.history(app);
5281        history.remove_listener(
5282            app,
5283            &Listener::handle_method(self, NavigatorState::handle_history_changed),
5284        );
5285        ChangeNotifierData::dispose(app, history);
5286        TickerProviderStateMixin::dispose(self, app);
5287        self.dispose_restoration(app);
5288        // A route that is being disposed can call `finalize_route`, which reads `debug_locked`.
5289        debug_assert!(app.get(self).debug_locked);
5290    }
5291
5292    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
5293        debug_assert!(!app.get(self).debug_locked);
5294        debug_assert!(!self.history(app).is_empty(app));
5295
5296        let overlay_key: KeyRef = app
5297            .get(self)
5298            .overlay_key
5299            .clone()
5300            .expect("restore_state has run")
5301            .into();
5302        let initial_entries = match self.overlay(app) {
5303            None => self.all_route_overlay_entries(app),
5304            Some(_) => Vec::new(),
5305        };
5306        let bucket = self.bucket(app).map(|bucket| bucket.keep(app));
5307        let clip_behavior = self.widget(app).clip_behavior;
5308        let focus_node: FocusNodeRef = app
5309            .get(self)
5310            .focus_node
5311            .as_ref()
5312            .expect("init_state has run")
5313            .erase();
5314        let policy = FocusTraversalGroup::maybe_of(app, context).map(|policy| policy.keep(app));
5315
5316        let overlay = Overlay::new()
5317            .key(overlay_key)
5318            .clip_behavior(clip_behavior)
5319            .initial_entries(initial_entries);
5320        let scope = UnmanagedRestorationScope::new(overlay).bucket(bucket);
5321        let focus = Focus::new(scope)
5322            .focus_node(focus_node)
5323            .autofocus(true)
5324            .skip_traversal(true)
5325            .include_semantics(false);
5326        let mut group = FocusTraversalGroup::new(focus);
5327        if let Some(policy) = policy {
5328            group = group.policy(policy);
5329        }
5330        // `absorbing` is mutated directly by `cancel_active_pointers` above.
5331        let absorb = AbsorbPointer::new().absorbing(false).child(group);
5332        // The callbacks keep the state, as Dart's tear-offs keep `this`: a pointer that went
5333        // down before the navigator was disposed still ends on it.
5334        let this = self.keep(app);
5335        let on_up = this.clone();
5336        let on_cancel = this.clone();
5337        let listener = crate::widgets::basic::Listener::new()
5338            .on_pointer_down(Rc::new(
5339                move |app, event: waft_gestures::PointerDownEvent| {
5340                    this.handle_pointer_down(app, event.pointer);
5341                },
5342            ))
5343            .on_pointer_up(Rc::new(move |app, event: waft_gestures::PointerUpEvent| {
5344                on_up.handle_pointer_up_or_cancel(app, event.pointer);
5345            }))
5346            .on_pointer_cancel(Rc::new(
5347                move |app, event: waft_gestures::PointerCancelEvent| {
5348                    on_cancel.handle_pointer_up_or_cancel(app, event.pointer);
5349                },
5350            ))
5351            .child(absorb);
5352        let notification_listener = NotificationListener::<NavigationNotification>::new(listener)
5353            .on_notification(move |app, notification: &NavigationNotification| {
5354                // If the state of this Navigator does not change whether or not the whole
5355                // Navigator can handle pops, propagate the notification to the next ancestor
5356                // Navigator.
5357                if notification.can_handle_pop || !self.get_navigator_can_handle_pop(app) {
5358                    // Propagate to the next ancestor.
5359                    return false;
5360                }
5361                let context = self.context(app);
5362                NavigationNotification {
5363                    can_handle_pop: true,
5364                }
5365                .dispatch(app, Some(context));
5366                true
5367            })
5368            .into_widget();
5369        HeroControllerScope::none(notification_listener).into_widget()
5370    }
5371}
5372
5373// ---------------------------------------------------------------------------------------------
5374// Restoration of the history
5375
5376/// The kind of a serialized [`RestorationInformation`].
5377#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5378enum RouteRestorationType {
5379    Named,
5380    Anonymous,
5381}
5382
5383impl RouteRestorationType {
5384    fn index(self) -> i64 {
5385        match self {
5386            RouteRestorationType::Named => 0,
5387            RouteRestorationType::Anonymous => 1,
5388        }
5389    }
5390
5391    fn from_index(index: i64) -> RouteRestorationType {
5392        match index {
5393            0 => RouteRestorationType::Named,
5394            1 => RouteRestorationType::Anonymous,
5395            other => panic!("unknown route restoration type {other}"),
5396        }
5397    }
5398}
5399
5400/// What a pageless route needs to be re-created during state restoration.
5401///
5402/// Dart's `_RestorationInformation` and its two subclasses.
5403pub enum RestorationInformation {
5404    /// Dart's `_NamedRestorationInformation`: a route created from a route name.
5405    Named {
5406        /// The name passed to [`Navigator::on_generate_route`].
5407        name: String,
5408        /// The arguments passed to [`Navigator::on_generate_route`].
5409        arguments: Option<RestorationData>,
5410        /// The generated ID of the restoration scope this route lives in.
5411        restoration_scope_id: i64,
5412    },
5413    /// Dart's `_AnonymousRestorationInformation`: a route created from a builder.
5414    Anonymous {
5415        /// The builder that creates the route.
5416        route_builder: RestorableRouteBuilder,
5417        /// The arguments handed to the builder.
5418        arguments: Option<RestorationData>,
5419        /// The generated ID of the restoration scope this route lives in.
5420        restoration_scope_id: i64,
5421    },
5422}
5423
5424impl RestorationInformation {
5425    fn kind(&self) -> RouteRestorationType {
5426        match self {
5427            RestorationInformation::Named { .. } => RouteRestorationType::Named,
5428            RestorationInformation::Anonymous { .. } => RouteRestorationType::Anonymous,
5429        }
5430    }
5431
5432    /// The generated ID of the restoration scope the route lives in.
5433    pub fn restoration_scope_id(&self) -> i64 {
5434        match self {
5435            RestorationInformation::Named {
5436                restoration_scope_id,
5437                ..
5438            }
5439            | RestorationInformation::Anonymous {
5440                restoration_scope_id,
5441                ..
5442            } => *restoration_scope_id,
5443        }
5444    }
5445
5446    /// Whether this information can be written into the restoration data.
5447    ///
5448    /// An anonymous route cannot: there is no handle for a Rust function that survives a
5449    /// restart, so an anonymous route behaves as it does on the web.
5450    pub fn is_restorable(&self) -> bool {
5451        match self {
5452            RestorationInformation::Named { .. } => true,
5453            RestorationInformation::Anonymous { .. } => false,
5454        }
5455    }
5456
5457    fn serializable_data(&self) -> RestorationData {
5458        debug_assert!(self.is_restorable());
5459        let mut values = vec![RestorationData::Int(self.kind().index())];
5460        match self {
5461            RestorationInformation::Named {
5462                name,
5463                arguments,
5464                restoration_scope_id,
5465            } => {
5466                values.push(RestorationData::Int(*restoration_scope_id));
5467                values.push(RestorationData::String(name.clone()));
5468                if let Some(arguments) = arguments {
5469                    values.push(arguments.clone());
5470                }
5471            }
5472            RestorationInformation::Anonymous { .. } => {
5473                unreachable!("an anonymous route is not restorable")
5474            }
5475        }
5476        RestorationData::List(values)
5477    }
5478
5479    fn from_serializable_data(data: &RestorationData) -> Rc<RestorationInformation> {
5480        let values = data.as_list().expect("a serialized route is a list");
5481        debug_assert!(!values.is_empty());
5482        let kind =
5483            RouteRestorationType::from_index(values[0].as_int().expect("the type index is an int"));
5484        match kind {
5485            RouteRestorationType::Named => {
5486                debug_assert!(values.len() > 2);
5487                Rc::new(RestorationInformation::Named {
5488                    restoration_scope_id: values[1].as_int().expect("a scope id"),
5489                    name: values[2].as_str().expect("a route name").to_string(),
5490                    arguments: values.get(3).cloned(),
5491                })
5492            }
5493            RouteRestorationType::Anonymous => {
5494                unreachable!("an anonymous route is never written into the restoration data")
5495            }
5496        }
5497    }
5498
5499    fn create_route(&self, app: &mut App, navigator: Handle<NavigatorState>) -> RouteRef {
5500        match self {
5501            RestorationInformation::Named {
5502                name, arguments, ..
5503            } => {
5504                let arguments = arguments.clone().map(|data| Rc::new(data) as Rc<dyn Any>);
5505                navigator
5506                    .route_named(app, name, arguments, false)
5507                    .expect("a route for the restored name")
5508            }
5509            RestorationInformation::Anonymous {
5510                route_builder,
5511                arguments,
5512                ..
5513            } => {
5514                let context = navigator.context(app);
5515                let arguments = arguments.clone().map(|data| Rc::new(data) as Rc<dyn Any>);
5516                route_builder(app, context, arguments)
5517            }
5518        }
5519    }
5520
5521    fn to_route_entry(
5522        self: &Rc<Self>,
5523        app: &mut App,
5524        navigator: Handle<NavigatorState>,
5525        initial_state: RouteLifecycle,
5526    ) -> Ref<RouteEntry> {
5527        let route = self.create_route(app, navigator);
5528        RouteEntry::new(app, route, initial_state, false, Some(Rc::clone(self)))
5529    }
5530}
5531
5532impl Debug for RestorationInformation {
5533    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5534        match self {
5535            RestorationInformation::Named { name, .. } => f
5536                .debug_struct("RestorationInformation::Named")
5537                .field("name", name)
5538                .finish_non_exhaustive(),
5539            RestorationInformation::Anonymous { .. } => {
5540                f.write_str("RestorationInformation::Anonymous")
5541            }
5542        }
5543    }
5544}
5545
5546/// Dart's `_HistoryProperty`: the serialized pageless routes of a [`NavigatorState`], keyed by
5547/// the restoration ID of the page they belong to.
5548pub struct HistoryProperty {
5549    change_notifier: waft_foundation::ChangeNotifierData,
5550    property: RestorablePropertyData,
5551    page_to_pageless_routes: Option<HashMap<Option<String>, Vec<RestorationData>>>,
5552}
5553
5554impl HistoryProperty {
5555    fn new(app: &mut App) -> Ref<HistoryProperty> {
5556        app.create(HistoryProperty {
5557            change_notifier: waft_foundation::ChangeNotifierData::new(),
5558            property: RestorablePropertyData::new(),
5559            page_to_pageless_routes: None,
5560        })
5561    }
5562
5563    /// Updates the serialized pageless routes from the navigator's live history.
5564    fn update(self: Handle<Self>, app: &mut App, history: Handle<History>) {
5565        debug_assert!(RestorableProperty::is_registered(self, app));
5566        let was_uninitialized = app.get(self).page_to_pageless_routes.is_none();
5567        let mut needs_serialization = was_uninitialized;
5568        if was_uninitialized {
5569            app.get_mut(self).page_to_pageless_routes = Some(HashMap::new());
5570        }
5571        let old_map = app
5572            .get(self)
5573            .page_to_pageless_routes
5574            .clone()
5575            .expect("filled above");
5576        let mut current_page: Option<Handle<RouteEntry>> = None;
5577        let mut new_routes_for_current_page: Vec<RestorationData> = Vec::new();
5578        let mut old_routes_for_current_page: Vec<RestorationData> =
5579            old_map.get(&None).cloned().unwrap_or_default();
5580        let mut restoration_enabled = true;
5581
5582        let mut new_map: HashMap<Option<String>, Vec<RestorationData>> = HashMap::new();
5583        let mut removed_pages: HashSet<Option<String>> = old_map.keys().cloned().collect();
5584
5585        for entry in history.entries(app) {
5586            if !entry.is_present_for_restoration(app) {
5587                entry.set_restoration_enabled(app, false);
5588                continue;
5589            }
5590
5591            if app.get(entry).page_based {
5592                needs_serialization = needs_serialization
5593                    || new_routes_for_current_page.len() != old_routes_for_current_page.len();
5594                HistoryProperty::finalize_entry(
5595                    app,
5596                    std::mem::take(&mut new_routes_for_current_page),
5597                    current_page,
5598                    &mut new_map,
5599                    &mut removed_pages,
5600                );
5601                current_page = Some(entry);
5602                restoration_enabled = entry.restoration_id(app).is_some();
5603                entry.set_restoration_enabled(app, restoration_enabled);
5604                if restoration_enabled {
5605                    let id = entry.restoration_id(app);
5606                    debug_assert!(id.is_some());
5607                    new_routes_for_current_page.clear();
5608                    old_routes_for_current_page = old_map.get(&id).cloned().unwrap_or_default();
5609                } else {
5610                    new_routes_for_current_page.clear();
5611                    old_routes_for_current_page.clear();
5612                }
5613                continue;
5614            }
5615
5616            restoration_enabled = restoration_enabled
5617                && app
5618                    .get(entry)
5619                    .restoration_information
5620                    .as_ref()
5621                    .is_some_and(|information| information.is_restorable());
5622            entry.set_restoration_enabled(app, restoration_enabled);
5623            if restoration_enabled {
5624                debug_assert!(entry.restoration_id(app).is_some());
5625                debug_assert!(
5626                    current_page.is_none()
5627                        || current_page.expect("checked").restoration_id(app).is_some()
5628                );
5629                let information = app
5630                    .get(entry)
5631                    .restoration_information
5632                    .clone()
5633                    .expect("a restorable pageless entry has restoration information");
5634                let serialized_data = information.serializable_data();
5635                needs_serialization = needs_serialization
5636                    || old_routes_for_current_page.len() <= new_routes_for_current_page.len()
5637                    || old_routes_for_current_page[new_routes_for_current_page.len()]
5638                        != serialized_data;
5639                new_routes_for_current_page.push(serialized_data);
5640            }
5641        }
5642        needs_serialization = needs_serialization
5643            || new_routes_for_current_page.len() != old_routes_for_current_page.len();
5644        HistoryProperty::finalize_entry(
5645            app,
5646            new_routes_for_current_page,
5647            current_page,
5648            &mut new_map,
5649            &mut removed_pages,
5650        );
5651
5652        needs_serialization = needs_serialization || !removed_pages.is_empty();
5653
5654        if needs_serialization {
5655            app.get_mut(self).page_to_pageless_routes = Some(new_map);
5656            self.notify_listeners(app);
5657        }
5658    }
5659
5660    fn finalize_entry(
5661        app: &App,
5662        routes: Vec<RestorationData>,
5663        page: Option<Handle<RouteEntry>>,
5664        page_to_routes: &mut HashMap<Option<String>, Vec<RestorationData>>,
5665        pages_to_remove: &mut HashSet<Option<String>>,
5666    ) {
5667        debug_assert!(page.is_none_or(|page| app.get(page).page_based));
5668        let restoration_id = page.and_then(|page| page.restoration_id(app));
5669        debug_assert!(!page_to_routes.contains_key(&restoration_id));
5670        if !routes.is_empty() {
5671            debug_assert!(page.is_none() || restoration_id.is_some());
5672            page_to_routes.insert(restoration_id.clone(), routes);
5673            pages_to_remove.remove(&restoration_id);
5674        }
5675    }
5676
5677    /// Forgets the serialized routes.
5678    fn clear(self: Handle<Self>, app: &mut App) {
5679        debug_assert!(RestorableProperty::is_registered(self, app));
5680        if app.get(self).page_to_pageless_routes.is_none() {
5681            return;
5682        }
5683        app.get_mut(self).page_to_pageless_routes = None;
5684        self.notify_listeners(app);
5685    }
5686
5687    /// Whether there is restoration data to restore from.
5688    fn has_data(self: Handle<Self>, app: &App) -> bool {
5689        app.get(self).page_to_pageless_routes.is_some()
5690    }
5691
5692    /// The pageless [`RouteEntry`]s that belong to the given page.
5693    fn restore_entries_for_page(
5694        self: Handle<Self>,
5695        app: &mut App,
5696        page: Option<Handle<RouteEntry>>,
5697        navigator: Handle<NavigatorState>,
5698    ) -> Vec<Ref<RouteEntry>> {
5699        debug_assert!(RestorableProperty::is_registered(self, app));
5700        debug_assert!(page.is_none_or(|page| app.get(page).page_based));
5701        let mut result = Vec::new();
5702        if app.get(self).page_to_pageless_routes.is_none()
5703            || page.is_some_and(|page| page.restoration_id(app).is_none())
5704        {
5705            return result;
5706        }
5707        let key = page.and_then(|page| page.restoration_id(app));
5708        let Some(serialized_data) = app
5709            .get(self)
5710            .page_to_pageless_routes
5711            .as_ref()
5712            .and_then(|map| map.get(&key))
5713            .cloned()
5714        else {
5715            return result;
5716        };
5717        for data in serialized_data {
5718            let information = RestorationInformation::from_serializable_data(&data);
5719            result.push(information.to_route_entry(app, navigator, RouteLifecycle::Add));
5720        }
5721        result
5722    }
5723}
5724
5725impl waft_foundation::ChangeNotifier for HistoryProperty {
5726    fn change_notifier_data(&self) -> &waft_foundation::ChangeNotifierData {
5727        &self.change_notifier
5728    }
5729
5730    fn change_notifier_data_mut(&mut self) -> &mut waft_foundation::ChangeNotifierData {
5731        &mut self.change_notifier
5732    }
5733}
5734
5735impl RestorableProperty for HistoryProperty {
5736    type Value = Option<HashMap<Option<String>, Vec<RestorationData>>>;
5737
5738    crate::restorable_property_accessors!();
5739
5740    fn create_default_value(self: Handle<Self>, _app: &mut App) -> Self::Value {
5741        None
5742    }
5743
5744    fn from_primitives(self: Handle<Self>, _app: &mut App, data: &RestorationData) -> Self::Value {
5745        let map = data.as_map().expect("the serialized history is a map");
5746        let mut result = HashMap::new();
5747        for (key, value) in map {
5748            let key = match key {
5749                RestorationData::Null => None,
5750                RestorationData::String(name) => Some(name.clone()),
5751                other => panic!("unexpected history key {other:?}"),
5752            };
5753            let value = value
5754                .as_list()
5755                .expect("the serialized routes of a page are a list")
5756                .to_vec();
5757            result.insert(key, value);
5758        }
5759        Some(result)
5760    }
5761
5762    fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value) {
5763        app.get_mut(self).page_to_pageless_routes = value;
5764    }
5765
5766    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
5767        match &app.get(self).page_to_pageless_routes {
5768            None => RestorationData::Null,
5769            Some(map) => {
5770                let mut result = RestorationMap::new();
5771                for (key, value) in map {
5772                    let key = match key {
5773                        None => RestorationData::Null,
5774                        Some(name) => RestorationData::String(name.clone()),
5775                    };
5776                    result.insert(key, RestorationData::List(value.clone()));
5777                }
5778                RestorationData::Map(result)
5779            }
5780        }
5781    }
5782
5783    fn enabled(self: Handle<Self>, app: &App) -> bool {
5784        self.has_data(app)
5785    }
5786}
5787
5788/// Signature for a callback that finds the [`NavigatorState`] a [`RestorableRouteFuture`]
5789/// operates on.
5790pub type NavigatorFinderCallback = Rc<dyn Fn(&mut App, BuildContext) -> Handle<NavigatorState>>;
5791
5792/// Signature for the callback that presents the route a [`RestorableRouteFuture`] tracks.
5793///
5794/// The callback must use one of the `restorable*` methods and return the restoration ID it
5795/// produced.
5796pub type RoutePresentationCallback =
5797    Rc<dyn Fn(&mut App, Handle<NavigatorState>, Option<RestorationData>) -> String>;
5798
5799/// Signature for the callback that is called when the route a [`RestorableRouteFuture`] tracks
5800/// completes.
5801pub type RouteCompletionCallback = Rc<dyn Fn(&mut App, RouteResult)>;
5802
5803/// Gives access to a [`Route`] object and its return value that was added to a navigator via one
5804/// of its `restorable*` methods.
5805///
5806/// When a router is pushed with one of those methods, they return a restoration ID. That ID can
5807/// be used to obtain a [`RestorableRouteFuture`], which stays valid across state restoration.
5808pub struct RestorableRouteFuture {
5809    change_notifier: waft_foundation::ChangeNotifierData,
5810    property: RestorablePropertyData,
5811    /// A callback that given the [`BuildContext`] of the [`State`] object to which this property
5812    /// is registered returns the [`NavigatorState`] of the navigator the route should be added
5813    /// to.
5814    pub navigator_finder: NavigatorFinderCallback,
5815    /// A callback that adds a route to the navigator and returns its restoration ID.
5816    pub on_present: RoutePresentationCallback,
5817    /// A callback that is invoked when the route added by
5818    /// [`on_present`](Self::on_present) completes.
5819    pub on_complete: Option<RouteCompletionCallback>,
5820    route: Option<RouteRef>,
5821    disposed: bool,
5822}
5823
5824impl RestorableRouteFuture {
5825    /// Creates a [`RestorableRouteFuture`]; Dart's optional arguments are the setters.
5826    pub fn new(app: &mut App, on_present: RoutePresentationCallback) -> Ref<RestorableRouteFuture> {
5827        app.create(RestorableRouteFuture {
5828            change_notifier: waft_foundation::ChangeNotifierData::new(),
5829            property: RestorablePropertyData::new(),
5830            navigator_finder: Rc::new(RestorableRouteFuture::default_navigator_finder),
5831            on_present,
5832            on_complete: None,
5833            route: None,
5834            disposed: false,
5835        })
5836    }
5837
5838    /// Dart `RestorableRouteFuture(navigatorFinder:)`.
5839    pub fn set_navigator_finder(
5840        self: Handle<Self>,
5841        app: &mut App,
5842        navigator_finder: NavigatorFinderCallback,
5843    ) {
5844        app.get_mut(self).navigator_finder = navigator_finder;
5845    }
5846
5847    /// Dart `RestorableRouteFuture(onComplete:)`.
5848    pub fn set_on_complete(
5849        self: Handle<Self>,
5850        app: &mut App,
5851        on_complete: RouteCompletionCallback,
5852    ) {
5853        app.get_mut(self).on_complete = Some(on_complete);
5854    }
5855
5856    fn default_navigator_finder(app: &mut App, context: BuildContext) -> Handle<NavigatorState> {
5857        Navigator::of(app, context, false)
5858    }
5859
5860    /// Shows the route created by [`on_present`](Self::on_present).
5861    pub fn present(self: Handle<Self>, app: &mut App, arguments: Option<RestorationData>) {
5862        debug_assert!(!self.is_present(app));
5863        debug_assert!(RestorableProperty::is_registered(self, app));
5864        let navigator = self.navigator(app);
5865        let on_present = Rc::clone(&app.get(self).on_present);
5866        let route_id = on_present(app, navigator, arguments);
5867        self.hook_onto_route_future(app, &route_id);
5868        self.notify_listeners(app);
5869    }
5870
5871    /// Whether the [`route`](Self::route) is currently shown.
5872    pub fn is_present(self: Handle<Self>, app: &App) -> bool {
5873        app.get(self).route.is_some()
5874    }
5875
5876    /// The route the [`on_present`](Self::on_present) callback added to the navigator.
5877    pub fn route(self: Handle<Self>, app: &App) -> Option<AnyRoute> {
5878        app.get(self).route.handle()
5879    }
5880
5881    fn navigator(self: Handle<Self>, app: &mut App) -> Handle<NavigatorState> {
5882        let finder = Rc::clone(&app.get(self).navigator_finder);
5883        let state = RestorableProperty::state(self, app);
5884        let context = state.context(app);
5885        finder(app, context)
5886    }
5887
5888    fn hook_onto_route_future(self: Handle<Self>, app: &mut App, id: &str) {
5889        let navigator = self.navigator(app);
5890        let route = navigator
5891            .get_route_by_id(app, id)
5892            .expect("the restorable method's route is in the navigator");
5893        app.get_mut(self).route = Some(route.keep(app));
5894        let notifier = route.restoration_scope_id(app);
5895        notifier.add_listener(
5896            app,
5897            Listener::handle_method(self, RestorableRouteFuture::notify),
5898        );
5899        route.popped(app).then(app, move |app, result| {
5900            // Named bare and checked: the property keeps the route, so a `Ref` here would be a
5901            // ring that outlives the property's dispose.
5902            if !app.contains(self) || app.get(self).disposed {
5903                return;
5904            }
5905            if let Some(route) = app.get(self).route.handle() {
5906                let notifier = route.restoration_scope_id(app);
5907                notifier.remove_listener(
5908                    app,
5909                    &Listener::handle_method(self, RestorableRouteFuture::notify),
5910                );
5911            }
5912            app.get_mut(self).route = None;
5913            self.notify_listeners(app);
5914            if let Some(on_complete) = app.get(self).on_complete.clone() {
5915                on_complete(app, result);
5916            }
5917        });
5918    }
5919
5920    fn notify(self: Handle<Self>, app: &mut App) {
5921        self.notify_listeners(app);
5922    }
5923}
5924
5925impl waft_foundation::ChangeNotifier for RestorableRouteFuture {
5926    fn change_notifier_data(&self) -> &waft_foundation::ChangeNotifierData {
5927        &self.change_notifier
5928    }
5929
5930    fn change_notifier_data_mut(&mut self) -> &mut waft_foundation::ChangeNotifierData {
5931        &mut self.change_notifier
5932    }
5933}
5934
5935impl RestorableProperty for RestorableRouteFuture {
5936    type Value = Option<String>;
5937
5938    crate::restorable_property_accessors!();
5939
5940    fn create_default_value(self: Handle<Self>, _app: &mut App) -> Option<String> {
5941        None
5942    }
5943
5944    fn from_primitives(
5945        self: Handle<Self>,
5946        _app: &mut App,
5947        data: &RestorationData,
5948    ) -> Option<String> {
5949        Some(
5950            data.as_str()
5951                .expect("a restoration ID is a string")
5952                .to_string(),
5953        )
5954    }
5955
5956    fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<String>) {
5957        if let Some(value) = value {
5958            self.hook_onto_route_future(app, &value);
5959        }
5960    }
5961
5962    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
5963        let route = app.get(self).route.handle().expect("a presented route");
5964        debug_assert!(RestorableProperty::enabled(self, app));
5965        let notifier = route.restoration_scope_id(app);
5966        match app.get(notifier).value() {
5967            None => RestorationData::Null,
5968            Some(id) => RestorationData::String(id.clone()),
5969        }
5970    }
5971
5972    fn enabled(self: Handle<Self>, app: &App) -> bool {
5973        match app.get(self).route.handle() {
5974            None => false,
5975            Some(route) => {
5976                let notifier = route.restoration_scope_id(app);
5977                app.get(notifier).value().is_some()
5978            }
5979        }
5980    }
5981
5982    fn did_dispose(self: Handle<Self>, app: &mut App) {
5983        if let Some(route) = app.get(self).route.handle() {
5984            let notifier = route.restoration_scope_id(app);
5985            notifier.remove_listener(
5986                app,
5987                &Listener::handle_method(self, RestorableRouteFuture::notify),
5988            );
5989        }
5990        app.get_mut(self).disposed = true;
5991    }
5992}
5993
5994// ---------------------------------------------------------------------------------------------
5995// NavigationNotification
5996
5997/// A `Notification` that gets dispatched when the [`Navigator`] can or cannot handle a pop.
5998///
5999/// This is used by the framework to determine whether the app should handle back navigation
6000/// itself or hand it to the platform.
6001#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6002pub struct NavigationNotification {
6003    /// Whether the [`Navigator`] in the subtree can handle a pop.
6004    pub can_handle_pop: bool,
6005}
6006
6007impl NavigationNotification {
6008    /// Creates a notification that reports whether a pop can be handled.
6009    pub fn new(can_handle_pop: bool) -> NavigationNotification {
6010        NavigationNotification { can_handle_pop }
6011    }
6012}
6013
6014impl Notification for NavigationNotification {
6015    fn as_any(&self) -> &dyn Any {
6016        self
6017    }
6018}
6019
6020#[cfg(test)]
6021mod tests {
6022    use std::cell::{Cell, RefCell};
6023
6024    use waft_embedder::TextDirection;
6025    use waft_foundation::ValueKey;
6026
6027    use super::*;
6028    use crate::framework::IntoWidget;
6029    use crate::testing::{TestPointer, WidgetTester, test_widgets};
6030    use crate::widgets::basic::{Align, Directionality, SizedBox};
6031    use crate::widgets::pages::PageRouteBuilder;
6032    use crate::widgets::restoration::RootRestorationScope;
6033    use crate::widgets::routes::RoutePageBuilder;
6034
6035    fn corner_page() -> RoutePageBuilder {
6036        Rc::new(|_app, _context, _animation, _secondary| {
6037            Align::new()
6038                .alignment(waft_painting::AlignmentGeometry::TOP_LEFT)
6039                .child(SizedBox::new().width(10.0).height(10.0))
6040                .into_widget()
6041        })
6042    }
6043
6044    /// A page whose route is a plain [`PageRouteBuilder`]; keyed by its name.
6045    #[derive(Debug)]
6046    struct TestPage {
6047        name: String,
6048        key: KeyRef,
6049        restoration_id: Option<String>,
6050    }
6051
6052    impl TestPage {
6053        fn page(name: &str) -> PageRef {
6054            Rc::new(TestPage {
6055                name: name.to_string(),
6056                key: ValueKey::new(name.to_string()).into(),
6057                restoration_id: None,
6058            })
6059        }
6060
6061        fn restorable_page(name: &str) -> PageRef {
6062            Rc::new(TestPage {
6063                name: name.to_string(),
6064                key: ValueKey::new(name.to_string()).into(),
6065                restoration_id: Some(name.to_string()),
6066            })
6067        }
6068    }
6069
6070    impl Page for TestPage {
6071        fn as_any(&self) -> &dyn Any {
6072            self
6073        }
6074
6075        fn key(&self) -> Option<&KeyRef> {
6076            Some(&self.key)
6077        }
6078
6079        fn name(&self) -> Option<&str> {
6080            Some(&self.name)
6081        }
6082
6083        fn restoration_id(&self) -> Option<&str> {
6084            self.restoration_id.as_deref()
6085        }
6086
6087        fn create_route(&self, app: &mut App, _context: BuildContext, this: &PageRef) -> RouteRef {
6088            PageRouteBuilder::new(app, corner_page())
6089                .settings(app, RouteSettingsRef::Page(Rc::clone(this)))
6090                .into_erased()
6091        }
6092    }
6093
6094    /// The names of the pages the navigator's history currently holds, bottom-most first.
6095    fn history_names(state: Handle<NavigatorState>, tester: &WidgetTester) -> Vec<String> {
6096        let app = tester.cell.borrow();
6097        let app = &*app;
6098        state
6099            .history_entries(app)
6100            .into_iter()
6101            .filter(|entry| entry.is_present(app))
6102            .filter_map(|entry| {
6103                app.get(entry)
6104                    .route
6105                    .settings(app)
6106                    .name()
6107                    .map(str::to_string)
6108            })
6109            .collect()
6110    }
6111
6112    fn pages_navigator(key: &GlobalKey, pages: Vec<PageRef>) -> WidgetRef {
6113        Directionality::new(
6114            TextDirection::Ltr,
6115            Navigator::new()
6116                .key(key.clone().into())
6117                .pages(pages)
6118                .on_did_remove_page(|_app, _page| {}),
6119        )
6120        .into_widget()
6121    }
6122
6123    fn state(key: &GlobalKey, tester: &WidgetTester) -> Handle<NavigatorState> {
6124        key.current_state::<NavigatorState>(&tester.cell.borrow())
6125            .expect("a mounted navigator")
6126    }
6127
6128    // ---- the tests ----
6129
6130    #[test]
6131    fn the_pages_api_inserts_removes_and_reorders_routes_through_the_transition_delegate() {
6132        test_widgets(|tester| {
6133            let key = GlobalKey::new();
6134            tester.pump_widget(pages_navigator(
6135                &key,
6136                vec![TestPage::page("a"), TestPage::page("b")],
6137            ));
6138            let navigator_state = state(&key, tester);
6139            tester.pump_and_settle();
6140            assert_eq!(history_names(navigator_state, tester), vec!["a", "b"]);
6141
6142            // Insert in the middle.
6143            tester.pump_widget(pages_navigator(
6144                &key,
6145                vec![
6146                    TestPage::page("a"),
6147                    TestPage::page("c"),
6148                    TestPage::page("b"),
6149                ],
6150            ));
6151            tester.pump_and_settle();
6152            assert_eq!(history_names(navigator_state, tester), vec!["a", "c", "b"]);
6153
6154            // Reorder.
6155            tester.pump_widget(pages_navigator(
6156                &key,
6157                vec![
6158                    TestPage::page("a"),
6159                    TestPage::page("b"),
6160                    TestPage::page("c"),
6161                ],
6162            ));
6163            tester.pump_and_settle();
6164            assert_eq!(history_names(navigator_state, tester), vec!["a", "b", "c"]);
6165
6166            // Remove.
6167            tester.pump_widget(pages_navigator(&key, vec![TestPage::page("a")]));
6168            tester.pump_and_settle();
6169            assert_eq!(history_names(navigator_state, tester), vec!["a"]);
6170        });
6171    }
6172
6173    #[derive(Default)]
6174    struct Recorder {
6175        navigator_observer: NavigatorObserverData,
6176        log: RefCell<Vec<String>>,
6177    }
6178
6179    fn route_name(app: &App, route: Option<AnyRoute>) -> String {
6180        match route {
6181            None => "none".to_string(),
6182            Some(route) => route.settings(app).name().unwrap_or("?").to_string(),
6183        }
6184    }
6185
6186    impl NavigatorObserver for Recorder {
6187        crate::navigator_observer_accessors!();
6188
6189        fn did_push(
6190            self: Handle<Self>,
6191            app: &mut App,
6192            route: AnyRoute,
6193            previous_route: Option<AnyRoute>,
6194        ) {
6195            let entry = format!(
6196                "push {} over {}",
6197                route_name(app, Some(route)),
6198                route_name(app, previous_route)
6199            );
6200            app.get(self).log.borrow_mut().push(entry);
6201        }
6202
6203        fn did_pop(
6204            self: Handle<Self>,
6205            app: &mut App,
6206            route: AnyRoute,
6207            previous_route: Option<AnyRoute>,
6208        ) {
6209            let entry = format!(
6210                "pop {} to {}",
6211                route_name(app, Some(route)),
6212                route_name(app, previous_route)
6213            );
6214            app.get(self).log.borrow_mut().push(entry);
6215        }
6216
6217        fn did_remove(
6218            self: Handle<Self>,
6219            app: &mut App,
6220            route: AnyRoute,
6221            previous_route: Option<AnyRoute>,
6222        ) {
6223            let entry = format!(
6224                "remove {} above {}",
6225                route_name(app, Some(route)),
6226                route_name(app, previous_route)
6227            );
6228            app.get(self).log.borrow_mut().push(entry);
6229        }
6230
6231        fn did_replace(
6232            self: Handle<Self>,
6233            app: &mut App,
6234            new_route: Option<AnyRoute>,
6235            old_route: Option<AnyRoute>,
6236        ) {
6237            let entry = format!(
6238                "replace {} with {}",
6239                route_name(app, old_route),
6240                route_name(app, new_route)
6241            );
6242            app.get(self).log.borrow_mut().push(entry);
6243        }
6244    }
6245
6246    /// A route named as `settings` asks, showing the corner page.
6247    fn named_route(app: &mut App, settings: &RouteSettings) -> Option<RouteRef> {
6248        let name = settings.name.clone().unwrap_or_default();
6249        Some(
6250            PageRouteBuilder::new(app, corner_page())
6251                .settings(app, RouteSettings::new().name(name).into())
6252                .into_erased(),
6253        )
6254    }
6255
6256    #[test]
6257    fn a_navigator_observer_sees_every_push_pop_replace_and_remove() {
6258        test_widgets(|tester| {
6259            let key = GlobalKey::new();
6260            let observer = tester.update(|app| app.create(Recorder::default()));
6261            tester.pump_widget(Directionality::new(
6262                TextDirection::Ltr,
6263                Navigator::new()
6264                    .key(key.clone().into())
6265                    .observers(vec![observer.erase()])
6266                    .on_generate_route(named_route),
6267            ));
6268            let navigator_state = state(&key, tester);
6269            tester.pump_and_settle();
6270            assert_eq!(
6271                tester.cell.borrow().get(&observer).log.borrow().as_slice(),
6272                ["push / over none"]
6273            );
6274
6275            tester.update(|app| navigator_state.push_named(app, "second", None));
6276            tester.pump_and_settle();
6277            tester.update(|app| navigator_state.push_replacement_named(app, "third", None, None));
6278            tester.pump_and_settle();
6279            tester.update(|app| navigator_state.pop(app, None));
6280            tester.pump_and_settle();
6281
6282            assert_eq!(
6283                tester.cell.borrow().get(&observer).log.borrow().as_slice(),
6284                [
6285                    "push / over none",
6286                    "push second over /",
6287                    "replace second with third",
6288                    "pop third to /",
6289                ]
6290            );
6291        });
6292    }
6293
6294    /// A restorable navigator keyed `key` over a restorable page "a", under a root restoration
6295    /// scope.
6296    fn restorable_navigator(key: &GlobalKey) -> WidgetRef {
6297        Directionality::new(
6298            TextDirection::Ltr,
6299            RootRestorationScope::new(
6300                Some("root".to_string()),
6301                Navigator::new()
6302                    .key(key.clone().into())
6303                    .restoration_scope_id("nav")
6304                    .pages(vec![TestPage::restorable_page("a")])
6305                    .on_did_remove_page(|_app, _page| {})
6306                    .on_generate_route(named_route),
6307            ),
6308        )
6309        .into_widget()
6310    }
6311
6312    #[test]
6313    fn the_history_is_restored_from_the_restoration_data_of_a_previous_run() {
6314        // Run once, pushing a restorable named route on top of a restorable page.
6315        let mut tester = WidgetTester::restoring(None);
6316        let key = GlobalKey::new();
6317        tester.pump_widget(restorable_navigator(&key));
6318        let navigator_state = state(&key, &tester);
6319        tester.pump_and_settle();
6320        tester.update(|app| navigator_state.restorable_push_named(app, "second", None));
6321        tester.pump_and_settle();
6322        assert_eq!(history_names(navigator_state, &tester), vec!["a", "second"]);
6323        let saved = tester
6324            .restoration_data()
6325            .expect("the manager wrote the restoration data");
6326
6327        // Run again from the saved data: the pageless route comes back.
6328        let mut tester = WidgetTester::restoring(Some(saved));
6329        let key = GlobalKey::new();
6330        tester.pump_widget(restorable_navigator(&key));
6331        let restored = state(&key, &tester);
6332        tester.pump_and_settle();
6333        assert_eq!(history_names(restored, &tester), vec!["a", "second"]);
6334    }
6335
6336    #[test]
6337    fn a_route_reports_its_position_in_the_history() {
6338        test_widgets(|tester| {
6339            let key = GlobalKey::new();
6340            let pushed: Rc<Cell<Option<AnyRoute>>> = Rc::new(Cell::new(None));
6341            tester.pump_widget(Directionality::new(
6342                TextDirection::Ltr,
6343                Navigator::new().key(key.clone().into()).on_generate_route({
6344                    let pushed = Rc::clone(&pushed);
6345                    move |app, _settings| {
6346                        let route: RouteRef =
6347                            PageRouteBuilder::new(app, corner_page()).into_erased();
6348                        pushed.set(Some(route.handle()));
6349                        Some(route)
6350                    }
6351                }),
6352            ));
6353            let navigator_state = state(&key, tester);
6354            tester.pump_and_settle();
6355            let first = pushed.get().expect("the initial route");
6356            {
6357                let app = tester.cell.borrow();
6358                assert!(first.is_first(&app));
6359                assert!(first.is_current(&app));
6360                assert!(first.is_active(&app));
6361                assert!(!first.has_active_route_below(&app));
6362            }
6363
6364            let second: RouteRef =
6365                tester.update(|app| PageRouteBuilder::new(app, corner_page()).into_erased());
6366            tester.update(|app| navigator_state.push(app, second.clone()));
6367            tester.pump_and_settle();
6368            let app = tester.cell.borrow();
6369            assert!(first.is_first(&app));
6370            assert!(!first.is_current(&app));
6371            assert!(second.is_current(&app));
6372            assert!(!second.is_first(&app));
6373            assert!(second.has_active_route_below(&app));
6374        });
6375    }
6376
6377    /// A navigator whose every route is a plain [`PageRouteBuilder`] showing the corner page.
6378    fn pageless_navigator(key: &GlobalKey) -> WidgetRef {
6379        Directionality::new(
6380            TextDirection::Ltr,
6381            Navigator::new()
6382                .key(key.clone().into())
6383                .on_generate_route(|app, _settings| {
6384                    Some(PageRouteBuilder::new(app, corner_page()).into_erased())
6385                }),
6386        )
6387        .into_widget()
6388    }
6389
6390    /// Dart's `push` returns `route.popped`: the future completes within the pop, with the
6391    /// pop's result, and a `.then` on it runs at the microtask drain — never inline.
6392    #[test]
6393    fn push_returns_a_future_that_completes_with_the_pop_result() {
6394        test_widgets(|tester| {
6395            let key = GlobalKey::new();
6396            tester.pump_widget(pageless_navigator(&key));
6397            let navigator_state = state(&key, tester);
6398            tester.pump_and_settle();
6399
6400            let popped = tester.update(|app| {
6401                let second: RouteRef = PageRouteBuilder::new(app, corner_page()).into_erased();
6402                navigator_state.push(app, second)
6403            });
6404            tester.pump_and_settle();
6405            assert!(!popped.is_completed(), "the route is still up");
6406
6407            let seen: Rc<Cell<Option<i32>>> = Rc::default();
6408            tester.update(|app| {
6409                popped.clone().then(app, {
6410                    let seen = Rc::clone(&seen);
6411                    move |_app, result| {
6412                        seen.set(result.and_then(|value| value.downcast_ref::<i32>().copied()));
6413                    }
6414                });
6415                navigator_state.pop(app, Some(Rc::new(42)));
6416                assert!(
6417                    popped.is_completed(),
6418                    "did_complete resolves the future within the pop"
6419                );
6420                assert_eq!(seen.get(), None, "a listener never runs inline");
6421                app.drain_microtasks();
6422            });
6423            assert_eq!(seen.get(), Some(42));
6424            tester.pump_and_settle();
6425        });
6426    }
6427
6428    /// Dart's "remove a route whose value is awaited": `removeRoute(route, 'B')` completes the
6429    /// future the push returned, and the continuation awaiting it resumes at the checkpoint.
6430    #[test]
6431    fn remove_route_completes_the_awaited_value() {
6432        test_widgets(|tester| {
6433            let key = GlobalKey::new();
6434            tester.pump_widget(pageless_navigator(&key));
6435            let navigator_state = state(&key, tester);
6436            tester.pump_and_settle();
6437
6438            let route_a: RouteRef =
6439                tester.update(|app| PageRouteBuilder::new(app, corner_page()).into_erased());
6440            let page_value = tester.update(|app| navigator_state.push(app, route_a.clone()));
6441            tester.pump_and_settle();
6442            let awaited: Rc<Cell<Option<&'static str>>> = Rc::default();
6443            tester.update(|app| {
6444                app.spawn({
6445                    let awaited = Rc::clone(&awaited);
6446                    async move |_cx| {
6447                        let value = page_value.await;
6448                        awaited.set(value.and_then(|value| value.downcast_ref::<&str>().copied()));
6449                    }
6450                })
6451            });
6452            tester.cell.checkpoint();
6453            assert_eq!(
6454                awaited.get(),
6455                None,
6456                "the continuation is parked on the future"
6457            );
6458
6459            tester.update(|app| {
6460                navigator_state.remove_route(app, route_a.handle(), Some(Rc::new("B")));
6461            });
6462            assert_eq!(
6463                awaited.get(),
6464                None,
6465                "the continuation resumes only at the checkpoint"
6466            );
6467            tester.cell.checkpoint();
6468            assert_eq!(awaited.get(), Some("B"));
6469            tester.pump_and_settle();
6470        });
6471    }
6472
6473    /// Not a Dart case: the pointer listener keeps the disposed state readable, as Dart's
6474    /// tear-off keeps it alive, until the pointer ends.
6475    #[test]
6476    fn a_pointer_that_ends_after_its_navigator_is_disposed_ends_on_the_disposed_state() {
6477        test_widgets(|tester| {
6478            let key = GlobalKey::new();
6479            tester.pump_widget(pageless_navigator(&key));
6480            let navigator_state = state(&key, tester);
6481            tester.pump_and_settle();
6482            let mut pointer = TestPointer::touch(1);
6483            tester.down(&mut pointer, waft_embedder::Offset::new(5.0, 5.0));
6484            assert!(
6485                tester
6486                    .cell
6487                    .borrow()
6488                    .get(navigator_state)
6489                    .active_pointers
6490                    .contains(&1)
6491            );
6492
6493            tester.pump_widget(SizedBox::new());
6494            tester.pump_and_settle();
6495            assert!(
6496                tester.cell.borrow().is_disposed(navigator_state),
6497                "the navigator was disposed"
6498            );
6499
6500            // Kept, as Dart's local keeps the state once the pointer's listener lets it go.
6501            let navigator_state = navigator_state.keep(&tester.cell.borrow());
6502            tester.up(&pointer);
6503            assert!(
6504                !tester
6505                    .cell
6506                    .borrow()
6507                    .get(&navigator_state)
6508                    .active_pointers
6509                    .contains(&1)
6510            );
6511        });
6512    }
6513}