Skip to main content

waft_material/
page.rs

1//! Port of material_ui's `page.dart`.
2//!
3//! `debugLabel` waits with diagnostics.
4
5use std::any::{Any, TypeId};
6use std::fmt::{self, Debug};
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_animation::AnimationRef;
11use waft_cupertino::CupertinoPageTransitionsBuilder;
12use waft_embedder::{Color, TargetPlatform};
13use waft_foundation::{App, Handle, Ref};
14use waft_scheduler::TickerFuture;
15use waft_widgets::{
16    AnyRoute, AnyTransitionRoute, BuildContext, DelegatedTransitionBuilder, IntoWidget, KeyRef,
17    LocalHistoryRoute, LocalHistoryRouteData, ModalRoute, ModalRouteData, OverlayRoute,
18    OverlayRouteData, Page, PageRef, PageRoute, PageRouteData, PageTransitionsBuilderRef,
19    PopInvokedWithResultCallback, PredictiveBackRoute, Route, RouteData, RouteRef, RouteResult,
20    RouteSettingsRef, Semantics, State, TransitionRoute, TransitionRouteData,
21    TraversalEdgeBehavior, WidgetBuilder, WidgetRef,
22};
23
24use crate::page_transitions_theme::ZoomPageTransitionsBuilder;
25use crate::theme::Theme;
26
27/// A modal route that replaces the entire screen with a platform-adaptive transition.
28///
29/// For Android, the entrance transition for the page zooms in and fades in while the exiting
30/// page zooms out and fades out. The exit transition is similar, but in reverse.
31///
32/// For iOS, the page slides in from the right and exits in reverse. The page also shifts to the
33/// left in parallax when another page enters to cover it. (These directions are flipped in
34/// environments with a right-to-left reading direction.)
35///
36/// By default, when a modal route is replaced by another, the previous route remains in memory.
37/// To free all the resources when this is not necessary, set
38/// [`maintain_state`](Self::maintain_state) to false.
39///
40/// The `fullscreen_dialog` property specifies whether the incoming route is a fullscreen modal
41/// dialog. On iOS, those routes animate from the bottom to the top rather than horizontally.
42///
43/// If `barrier_dismissible` is true, then pressing the escape key on the keyboard will cause the
44/// current route to be popped with no value.
45///
46/// See also:
47///
48///  * [`MaterialRouteTransitionMixin`], which provides the material transition for this route.
49///  * [`MaterialPage`], which is a [`Page`] of this class.
50pub struct MaterialPageRoute {
51    route: RouteData,
52    overlay_route: OverlayRouteData,
53    transition_route: TransitionRouteData,
54    local_history: LocalHistoryRouteData,
55    modal_route: ModalRouteData,
56    page_route: PageRouteData,
57    /// Builds the primary contents of the route.
58    pub builder: WidgetBuilder,
59    maintain_state: bool,
60    include_route_semantics: bool,
61}
62
63impl MaterialPageRoute {
64    /// Construct a MaterialPageRoute whose contents are defined by `builder`; Dart's optional
65    /// arguments are the setters.
66    ///
67    /// Dart's defaults: `maintain_state` true, `fullscreen_dialog` false, `allow_snapshotting`
68    /// true, `include_route_semantics` true, `barrier_dismissible` false.
69    pub fn new(app: &mut App, builder: WidgetBuilder) -> Ref<MaterialPageRoute> {
70        let route = RouteData::new(app, None, None);
71        let transition_route = TransitionRouteData::new(app);
72        let modal_route = ModalRouteData::new(app);
73        let this = app.create(MaterialPageRoute {
74            route,
75            overlay_route: OverlayRouteData::new(),
76            transition_route,
77            local_history: LocalHistoryRouteData::new(),
78            modal_route,
79            page_route: PageRouteData::new(),
80            builder,
81            maintain_state: true,
82            include_route_semantics: true,
83        });
84        debug_assert!(TransitionRoute::opaque(this.handle(), app));
85        this
86    }
87
88    /// Dart `MaterialPageRoute(settings:)`.
89    pub fn settings(self: Ref<Self>, app: &mut App, settings: RouteSettingsRef) -> Ref<Self> {
90        self.route_data_mut(app).set_settings(settings);
91        self
92    }
93
94    /// Dart `MaterialPageRoute(requestFocus:)`.
95    pub fn request_focus(self: Ref<Self>, app: &mut App, request_focus: bool) -> Ref<Self> {
96        self.route_data_mut(app)
97            .set_request_focus(Some(request_focus));
98        self
99    }
100
101    /// Dart `MaterialPageRoute(maintainState:)`.
102    pub fn maintain_state(self: Ref<Self>, app: &mut App, maintain_state: bool) -> Ref<Self> {
103        app.get_mut(&self).maintain_state = maintain_state;
104        self
105    }
106
107    /// Dart `MaterialPageRoute(fullscreenDialog:)`.
108    pub fn fullscreen_dialog(self: Ref<Self>, app: &mut App, fullscreen_dialog: bool) -> Ref<Self> {
109        self.page_route_data_mut(app).fullscreen_dialog = fullscreen_dialog;
110        self
111    }
112
113    /// Dart `MaterialPageRoute(allowSnapshotting:)`.
114    pub fn allow_snapshotting(
115        self: Ref<Self>,
116        app: &mut App,
117        allow_snapshotting: bool,
118    ) -> Ref<Self> {
119        self.page_route_data_mut(app).allow_snapshotting = allow_snapshotting;
120        self
121    }
122
123    /// Dart `MaterialPageRoute(includeRouteSemantics:)`.
124    pub fn include_route_semantics(
125        self: Ref<Self>,
126        app: &mut App,
127        include_route_semantics: bool,
128    ) -> Ref<Self> {
129        app.get_mut(&self).include_route_semantics = include_route_semantics;
130        self
131    }
132
133    /// Dart `MaterialPageRoute(barrierDismissible:)`.
134    pub fn barrier_dismissible(
135        self: Ref<Self>,
136        app: &mut App,
137        barrier_dismissible: bool,
138    ) -> Ref<Self> {
139        self.page_route_data_mut(app).barrier_dismissible = barrier_dismissible;
140        self
141    }
142
143    /// Dart `MaterialPageRoute(traversalEdgeBehavior:)`.
144    pub fn traversal_edge_behavior(
145        self: Ref<Self>,
146        app: &mut App,
147        traversal_edge_behavior: TraversalEdgeBehavior,
148    ) -> Ref<Self> {
149        self.modal_route_data_mut(app).traversal_edge_behavior = Some(traversal_edge_behavior);
150        self
151    }
152
153    /// Dart `MaterialPageRoute(directionalTraversalEdgeBehavior:)`.
154    pub fn directional_traversal_edge_behavior(
155        self: Ref<Self>,
156        app: &mut App,
157        directional_traversal_edge_behavior: TraversalEdgeBehavior,
158    ) -> Ref<Self> {
159        self.modal_route_data_mut(app)
160            .directional_traversal_edge_behavior = Some(directional_traversal_edge_behavior);
161        self
162    }
163}
164
165impl Route for MaterialPageRoute {
166    crate::material_route_transition_mixin_route_overrides!();
167}
168
169impl OverlayRoute for MaterialPageRoute {
170    waft_widgets::modal_overlay_route_overrides!();
171}
172
173impl PredictiveBackRoute for MaterialPageRoute {
174    waft_widgets::page_predictive_back_route_overrides!();
175}
176
177impl TransitionRoute for MaterialPageRoute {
178    crate::material_route_transition_mixin_transition_route_overrides!();
179
180    fn opaque(self: Handle<Self>, app: &App) -> bool {
181        PageRoute::opaque(self, app)
182    }
183}
184
185impl LocalHistoryRoute for MaterialPageRoute {
186    waft_widgets::local_history_route_accessors!();
187}
188
189impl ModalRoute for MaterialPageRoute {
190    crate::material_route_transition_mixin_modal_route_overrides!();
191
192    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
193        app.get(self).maintain_state
194    }
195
196    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
197        PageRoute::fullscreen_dialog(self, app)
198    }
199}
200
201impl PageRoute for MaterialPageRoute {
202    waft_widgets::page_route_accessors!();
203}
204
205impl MaterialRouteTransitionMixin for MaterialPageRoute {
206    fn build_content(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
207        let builder = Rc::clone(&app.get(self).builder);
208        builder(app, context)
209    }
210
211    fn include_route_semantics(self: Handle<Self>, app: &App) -> bool {
212        app.get(self).include_route_semantics
213    }
214}
215
216/// A mixin that provides platform-adaptive transitions for a [`PageRoute`].
217///
218/// For Android, the entrance transition for the page zooms in and fades in while the exiting
219/// page zooms out and fades out. The exit transition is similar, but in reverse.
220///
221/// For iOS, the page slides in from the right and exits in reverse. The page also shifts to the
222/// left in parallax when another page enters to cover it. (These directions are flipped in
223/// environments with a right-to-left reading direction.)
224///
225/// A leaf writes [`material_route_transition_mixin_route_overrides!`](crate::material_route_transition_mixin_route_overrides),
226/// [`material_route_transition_mixin_transition_route_overrides!`](crate::material_route_transition_mixin_transition_route_overrides)
227/// and [`material_route_transition_mixin_modal_route_overrides!`](crate::material_route_transition_mixin_modal_route_overrides)
228/// into its `Route`, `TransitionRoute` and `ModalRoute` impls, where Dart's mixin overrides
229/// those classes' members.
230///
231/// See also:
232///
233///  * [`PageTransitionsTheme`](crate::PageTransitionsTheme), which defines the default page
234///    transitions used by the [`MaterialRouteTransitionMixin::build_transitions`].
235///  * [`ZoomPageTransitionsBuilder`], which is the default page transition used by the
236///    [`PageTransitionsTheme`](crate::PageTransitionsTheme).
237///  * [`CupertinoPageTransitionsBuilder`], which is the default page transition for iOS and
238///    macOS.
239pub trait MaterialRouteTransitionMixin: PageRoute {
240    /// Builds the primary contents of the route.
241    fn build_content(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef;
242
243    /// Whether this route introduces a route scope in the semantics tree.
244    ///
245    /// Defaults to true. When true, screen readers can treat pushes and pops of
246    /// this route as page-level navigation. Set to false for routes that represent
247    /// tab or shell content in a nested navigator. This prevents screen readers
248    /// from treating the route as a new screen.
249    fn include_route_semantics(self: Handle<Self>, app: &App) -> bool {
250        let _ = app;
251        true
252    }
253
254    /// Dart's `MaterialRouteTransitionMixin.transitionDuration`.
255    fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
256        let context = navigator_context(self, app);
257        get_page_transition_builder(app, context).map_or(Duration::from_micros(300), |builder| {
258            builder.transition_duration()
259        })
260    }
261
262    /// Dart's `MaterialRouteTransitionMixin.reverseTransitionDuration`.
263    fn reverse_transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
264        let context = navigator_context(self, app);
265        get_page_transition_builder(app, context).map_or(Duration::from_micros(300), |builder| {
266            builder.reverse_transition_duration()
267        })
268    }
269
270    // The transitionDuration is used to create the AnimationController which is only built
271    // once, so when page transition builder is updated and transitionDuration has a new value,
272    // the AnimationController cannot be updated automatically. So we manually update its
273    // duration here.
274    // TODO(quncCccccc): Clean up this override method when controller can be updated as the transitionDuration is changed.
275    /// Dart's `MaterialRouteTransitionMixin.didPush`.
276    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
277        if let Some(controller) = TransitionRoute::controller(self, app) {
278            let duration = TransitionRoute::transition_duration(self, app);
279            app.get_mut(controller).duration = Some(duration);
280        }
281        ModalRoute::did_push(self, app)
282    }
283
284    // The reverseTransitionDuration is used to create the AnimationController which is only
285    // built once, so when page transition builder is updated and reverseTransitionDuration has
286    // a new value, the AnimationController cannot be updated automatically. So we manually
287    // update its reverseDuration here.
288    // TODO(quncCccccc): Clean up this override method when controller can beupdated as the reverseTransitionDuration is changed.
289    /// Dart's `MaterialRouteTransitionMixin.didPop`.
290    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
291        if let Some(controller) = TransitionRoute::controller(self, app) {
292            let reverse_duration = TransitionRoute::reverse_transition_duration(self, app);
293            app.get_mut(controller).reverse_duration = Some(reverse_duration);
294        }
295        LocalHistoryRoute::did_pop(self, app, result)
296    }
297
298    /// Dart's `MaterialRouteTransitionMixin.barrierColor`.
299    fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color> {
300        let _ = app;
301        None
302    }
303
304    /// Dart's `MaterialRouteTransitionMixin.barrierLabel`.
305    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
306        let _ = app;
307        None
308    }
309
310    /// Dart's `MaterialRouteTransitionMixin.delegatedTransition`: the tear-off of the static
311    /// `_delegatedTransition`, so every route that mixes this in hands out an equal builder.
312    fn delegated_transition(self: Handle<Self>, app: &App) -> Option<DelegatedTransitionBuilder> {
313        let _ = app;
314        Some(DelegatedTransitionBuilder::function(
315            material_delegated_transition,
316        ))
317    }
318
319    /// Dart's `MaterialRouteTransitionMixin.canTransitionTo`.
320    fn can_transition_to(self: Handle<Self>, app: &App, next_route: AnyTransitionRoute) -> bool {
321        let next_route = next_route.as_route();
322        // Don't perform outgoing animation if the next route is a fullscreen dialog, or there is
323        // no matching transition to use.
324        // Don't perform outgoing animation if the next route is a fullscreen dialog.
325        let next_route_is_not_fullscreen = match next_route.as_page_route(app) {
326            None => true,
327            Some(next_route) => !next_route.as_modal_route().fullscreen_dialog(app),
328        };
329
330        // If the next route has a delegated transition, then this route is able to use that
331        // delegated transition to smoothly sync with the next route's transition.
332        let next_route_has_delegated_transition = next_route
333            .as_modal_route(app)
334            .is_some_and(|next_route| next_route.delegated_transition(app).is_some());
335
336        // Otherwise if the next route has the same route transition mixin as this one, then this
337        // route will already be synced with its transition.
338        next_route_is_not_fullscreen
339            && (next_route
340                .interface::<Rc<dyn MaterialRouteTransition>>()
341                .is_some()
342                || next_route_has_delegated_transition)
343    }
344
345    /// Dart's `MaterialRouteTransitionMixin.canTransitionFrom`.
346    fn can_transition_from(
347        self: Handle<Self>,
348        app: &App,
349        previous_route: AnyTransitionRoute,
350    ) -> bool {
351        // Suppress previous route from transitioning if this is a fullscreenDialog route.
352        previous_route.as_route().as_page_route(app).is_some()
353            && !PageRoute::fullscreen_dialog(self, app)
354    }
355
356    /// Dart's `MaterialRouteTransitionMixin.buildPage`.
357    fn build_page(
358        self: Handle<Self>,
359        app: &mut App,
360        context: BuildContext,
361        animation: AnimationRef<f64>,
362        secondary_animation: AnimationRef<f64>,
363    ) -> WidgetRef {
364        let _ = (animation, secondary_animation);
365        let result = self.build_content(app, context);
366        if !self.include_route_semantics(app) {
367            return result;
368        }
369        Semantics::new()
370            .scopes_route(true)
371            .explicit_child_nodes(true)
372            .child(result)
373            .into_widget()
374    }
375
376    /// Dart's `MaterialRouteTransitionMixin.buildTransitions`.
377    fn build_transitions(
378        self: Handle<Self>,
379        app: &mut App,
380        context: BuildContext,
381        animation: AnimationRef<f64>,
382        secondary_animation: AnimationRef<f64>,
383        child: WidgetRef,
384    ) -> WidgetRef {
385        let theme = Theme::of(app, context).page_transitions_theme.clone();
386        theme.build_transitions(
387            app,
388            PageRoute::as_page_route(self),
389            context,
390            animation,
391            secondary_animation,
392            child,
393        )
394    }
395
396    /// Dart's `route is MaterialRouteTransitionMixin`, answered through `Route::interface`:
397    /// this route as an `Rc<dyn MaterialRouteTransition>` when `id` names that type.
398    fn interface(self: Handle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
399        if id != TypeId::of::<Rc<dyn MaterialRouteTransition>>() {
400            return None;
401        }
402        let transition: Rc<dyn MaterialRouteTransition> = Rc::new(self);
403        Some(Box::new(transition))
404    }
405}
406
407/// [`MaterialRouteTransitionMixin`] on a shared reference: what Dart's
408/// `route is MaterialRouteTransitionMixin` produces, read as
409/// `route.interface::<Rc<dyn MaterialRouteTransition>>()` on an [`AnyRoute`]. Every route that
410/// implements the mixin is one through its handle.
411pub trait MaterialRouteTransition {
412    /// This route as the erased [`AnyRoute`].
413    fn as_route(&self) -> AnyRoute;
414}
415
416impl<T: MaterialRouteTransitionMixin> MaterialRouteTransition for Handle<T> {
417    fn as_route(&self) -> AnyRoute {
418        Route::as_route(*self)
419    }
420}
421
422/// Dart's `navigator!.context`.
423fn navigator_context<R: Route>(route: Handle<R>, app: &App) -> BuildContext {
424    Route::navigator(route, app)
425        .expect("an installed route has a navigator")
426        .context(app)
427}
428
429/// Dart's `_getPageTransitionBuilder`.
430fn get_page_transition_builder(
431    app: &mut App,
432    context: BuildContext,
433) -> Option<PageTransitionsBuilderRef> {
434    let platform = Theme::of(app, context).platform;
435    let page_transitions_theme = Theme::of(app, context).page_transitions_theme.clone();
436    let builder = match page_transitions_theme.builders().get(&platform) {
437        Some(builder) => builder.clone(),
438        None => match platform {
439            TargetPlatform::IOS | TargetPlatform::MacOS => {
440                PageTransitionsBuilderRef::new(CupertinoPageTransitionsBuilder::new())
441            }
442            TargetPlatform::Android
443            | TargetPlatform::Fuchsia
444            | TargetPlatform::Windows
445            | TargetPlatform::Linux => {
446                PageTransitionsBuilderRef::new(ZoomPageTransitionsBuilder::new())
447            }
448        },
449    };
450    Some(builder)
451}
452
453/// Dart's static `MaterialRouteTransitionMixin._delegatedTransition`.
454fn material_delegated_transition(
455    app: &mut App,
456    context: BuildContext,
457    animation: AnimationRef<f64>,
458    secondary_animation: AnimationRef<f64>,
459    allow_snapshotting: bool,
460    child: Option<&WidgetRef>,
461) -> Option<WidgetRef> {
462    let theme_data = Theme::of(app, context);
463    let theme = theme_data.page_transitions_theme.clone();
464    let platform = theme_data.platform;
465    let theme_delegated_transition = theme.delegated_transition(platform);
466    match theme_delegated_transition {
467        Some(theme_delegated_transition) => theme_delegated_transition.call(
468            app,
469            context,
470            animation,
471            secondary_animation,
472            allow_snapshotting,
473            child,
474        ),
475        None => None,
476    }
477}
478
479/// The `Route` overrides a [`MaterialRouteTransitionMixin`] leaf inherits: `waft-widgets`'
480/// `page_route_overrides!` with `did_push`, `did_pop` and `interface` pointed at the mixin.
481/// Write it inside `impl Route for MyRoute { .. }`.
482#[macro_export]
483macro_rules! material_route_transition_mixin_route_overrides {
484    () => {
485        ::waft_widgets::route_accessors!();
486
487        fn as_transition_route(
488            self: ::waft_foundation::Handle<Self>,
489        ) -> ::std::option::Option<::waft_widgets::AnyTransitionRoute> {
490            ::std::option::Option::Some(::waft_widgets::TransitionRoute::as_transition_route(self))
491        }
492
493        fn as_modal_route(
494            self: ::waft_foundation::Handle<Self>,
495        ) -> ::std::option::Option<::waft_widgets::AnyModalRoute> {
496            ::std::option::Option::Some(::waft_widgets::ModalRoute::as_modal_route(self))
497        }
498
499        fn as_page_route(
500            self: ::waft_foundation::Handle<Self>,
501        ) -> ::std::option::Option<::waft_widgets::AnyPageRoute> {
502            ::std::option::Option::Some(::waft_widgets::PageRoute::as_page_route(self))
503        }
504
505        fn interface(
506            self: ::waft_foundation::Handle<Self>,
507            id: ::std::any::TypeId,
508        ) -> ::std::option::Option<::std::boxed::Box<dyn ::std::any::Any>> {
509            $crate::MaterialRouteTransitionMixin::interface(self, id)
510        }
511
512        fn overlay_entries(
513            self: ::waft_foundation::Handle<Self>,
514            app: &::waft_foundation::App,
515        ) -> ::std::vec::Vec<::waft_foundation::Handle<::waft_widgets::OverlayEntry>> {
516            ::waft_widgets::OverlayRoute::overlay_entries(self, app)
517        }
518
519        fn install(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
520            ::waft_widgets::ModalRoute::install(self, app)
521        }
522
523        fn did_push(
524            self: ::waft_foundation::Handle<Self>,
525            app: &mut ::waft_foundation::App,
526        ) -> ::waft_scheduler::TickerFuture {
527            $crate::MaterialRouteTransitionMixin::did_push(self, app)
528        }
529
530        fn did_add(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
531            ::waft_widgets::ModalRoute::did_add(self, app)
532        }
533
534        fn did_replace(
535            self: ::waft_foundation::Handle<Self>,
536            app: &mut ::waft_foundation::App,
537            old_route: ::std::option::Option<::waft_widgets::AnyRoute>,
538        ) {
539            ::waft_widgets::TransitionRoute::did_replace(self, app, old_route)
540        }
541
542        fn will_pop(
543            self: ::waft_foundation::Handle<Self>,
544            app: &mut ::waft_foundation::App,
545        ) -> ::waft_widgets::RoutePopDisposition {
546            ::waft_widgets::LocalHistoryRoute::will_pop(self, app)
547        }
548
549        fn pop_disposition(
550            self: ::waft_foundation::Handle<Self>,
551            app: &mut ::waft_foundation::App,
552        ) -> ::waft_widgets::RoutePopDisposition {
553            ::waft_widgets::ModalRoute::pop_disposition(self, app)
554        }
555
556        fn on_pop_invoked_with_result(
557            self: ::waft_foundation::Handle<Self>,
558            app: &mut ::waft_foundation::App,
559            did_pop: bool,
560            result: ::waft_widgets::RouteResult,
561        ) {
562            ::waft_widgets::ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
563        }
564
565        fn will_handle_pop_internally(
566            self: ::waft_foundation::Handle<Self>,
567            app: &::waft_foundation::App,
568        ) -> bool {
569            ::waft_widgets::LocalHistoryRoute::will_handle_pop_internally(self, app)
570        }
571
572        fn did_pop(
573            self: ::waft_foundation::Handle<Self>,
574            app: &mut ::waft_foundation::App,
575            result: ::waft_widgets::RouteResult,
576        ) -> bool {
577            $crate::MaterialRouteTransitionMixin::did_pop(self, app, result)
578        }
579
580        fn did_pop_next(
581            self: ::waft_foundation::Handle<Self>,
582            app: &mut ::waft_foundation::App,
583            next_route: ::waft_widgets::AnyRoute,
584        ) {
585            ::waft_widgets::ModalRoute::did_pop_next(self, app, next_route)
586        }
587
588        fn did_change_next(
589            self: ::waft_foundation::Handle<Self>,
590            app: &mut ::waft_foundation::App,
591            next_route: ::std::option::Option<::waft_widgets::AnyRoute>,
592        ) {
593            ::waft_widgets::ModalRoute::did_change_next(self, app, next_route)
594        }
595
596        fn did_change_previous(
597            self: ::waft_foundation::Handle<Self>,
598            app: &mut ::waft_foundation::App,
599            previous_route: ::std::option::Option<::waft_widgets::AnyRoute>,
600        ) {
601            ::waft_widgets::ModalRoute::did_change_previous(self, app, previous_route)
602        }
603
604        fn changed_internal_state(
605            self: ::waft_foundation::Handle<Self>,
606            app: &mut ::waft_foundation::App,
607        ) {
608            ::waft_widgets::ModalRoute::changed_internal_state(self, app)
609        }
610
611        fn changed_external_state(
612            self: ::waft_foundation::Handle<Self>,
613            app: &mut ::waft_foundation::App,
614        ) {
615            ::waft_widgets::ModalRoute::changed_external_state(self, app)
616        }
617
618        fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
619            ::waft_widgets::TransitionRoute::dispose(self, app)
620        }
621    };
622}
623
624/// The `TransitionRoute` overrides a [`MaterialRouteTransitionMixin`] leaf inherits, plus
625/// `waft-widgets`' `modal_transition_route_overrides!`. Write it inside
626/// `impl TransitionRoute for MyRoute { .. }`, next to the leaf's own `opaque`.
627#[macro_export]
628macro_rules! material_route_transition_mixin_transition_route_overrides {
629    () => {
630        ::waft_widgets::modal_transition_route_overrides!();
631
632        fn allow_snapshotting(
633            self: ::waft_foundation::Handle<Self>,
634            app: &::waft_foundation::App,
635        ) -> bool {
636            ::waft_widgets::PageRoute::allow_snapshotting(self, app)
637        }
638
639        fn transition_duration(
640            self: ::waft_foundation::Handle<Self>,
641            app: &mut ::waft_foundation::App,
642        ) -> ::std::time::Duration {
643            $crate::MaterialRouteTransitionMixin::transition_duration(self, app)
644        }
645
646        fn reverse_transition_duration(
647            self: ::waft_foundation::Handle<Self>,
648            app: &mut ::waft_foundation::App,
649        ) -> ::std::time::Duration {
650            $crate::MaterialRouteTransitionMixin::reverse_transition_duration(self, app)
651        }
652
653        fn can_transition_to(
654            self: ::waft_foundation::Handle<Self>,
655            app: &::waft_foundation::App,
656            next_route: ::waft_widgets::AnyTransitionRoute,
657        ) -> bool {
658            $crate::MaterialRouteTransitionMixin::can_transition_to(self, app, next_route)
659        }
660
661        fn can_transition_from(
662            self: ::waft_foundation::Handle<Self>,
663            app: &::waft_foundation::App,
664            previous_route: ::waft_widgets::AnyTransitionRoute,
665        ) -> bool {
666            $crate::MaterialRouteTransitionMixin::can_transition_from(self, app, previous_route)
667        }
668    };
669}
670
671/// The `ModalRoute` overrides a [`MaterialRouteTransitionMixin`] leaf inherits, plus
672/// `waft-widgets`' `modal_route_accessors!`. Write it inside
673/// `impl ModalRoute for MyRoute { .. }`, next to the leaf's own `maintain_state`.
674#[macro_export]
675macro_rules! material_route_transition_mixin_modal_route_overrides {
676    () => {
677        ::waft_widgets::modal_route_accessors!();
678
679        fn barrier_dismissible(
680            self: ::waft_foundation::Handle<Self>,
681            app: &::waft_foundation::App,
682        ) -> bool {
683            ::waft_widgets::PageRoute::barrier_dismissible(self, app)
684        }
685
686        fn barrier_color(
687            self: ::waft_foundation::Handle<Self>,
688            app: &::waft_foundation::App,
689        ) -> ::std::option::Option<::waft_painting::Color> {
690            $crate::MaterialRouteTransitionMixin::barrier_color(self, app)
691        }
692
693        fn barrier_label(
694            self: ::waft_foundation::Handle<Self>,
695            app: &::waft_foundation::App,
696        ) -> ::std::option::Option<::std::string::String> {
697            $crate::MaterialRouteTransitionMixin::barrier_label(self, app)
698        }
699
700        fn delegated_transition(
701            self: ::waft_foundation::Handle<Self>,
702            app: &::waft_foundation::App,
703        ) -> ::std::option::Option<::waft_widgets::DelegatedTransitionBuilder> {
704            $crate::MaterialRouteTransitionMixin::delegated_transition(self, app)
705        }
706
707        fn build_page(
708            self: ::waft_foundation::Handle<Self>,
709            app: &mut ::waft_foundation::App,
710            context: ::waft_widgets::BuildContext,
711            animation: ::waft_animation::AnimationRef<f64>,
712            secondary_animation: ::waft_animation::AnimationRef<f64>,
713        ) -> ::waft_widgets::WidgetRef {
714            $crate::MaterialRouteTransitionMixin::build_page(
715                self,
716                app,
717                context,
718                animation,
719                secondary_animation,
720            )
721        }
722
723        fn build_transitions(
724            self: ::waft_foundation::Handle<Self>,
725            app: &mut ::waft_foundation::App,
726            context: ::waft_widgets::BuildContext,
727            animation: ::waft_animation::AnimationRef<f64>,
728            secondary_animation: ::waft_animation::AnimationRef<f64>,
729            child: ::waft_widgets::WidgetRef,
730        ) -> ::waft_widgets::WidgetRef {
731            $crate::MaterialRouteTransitionMixin::build_transitions(
732                self,
733                app,
734                context,
735                animation,
736                secondary_animation,
737                child,
738            )
739        }
740    };
741}
742
743/// A page that creates a material style [`PageRoute`].
744///
745/// For Android, the entrance transition for the page zooms in and fades in while the exiting
746/// page zooms out and fades out. The exit transition is similar, but in reverse.
747///
748/// For iOS, the page slides in from the right and exits in reverse. The page also shifts to the
749/// left in parallax when another page enters to cover it. (These directions are flipped in
750/// environments with a right-to-left reading direction.)
751///
752/// By default, when the created route is replaced by another, the previous route remains in
753/// memory. To free all the resources when this is not necessary, set
754/// [`maintain_state`](Self::maintain_state) to false.
755///
756/// The `fullscreen_dialog` property specifies whether the created route is a fullscreen modal
757/// dialog. On iOS, those routes animate from the bottom to the top rather than horizontally.
758///
759/// See also:
760///
761///  * [`MaterialPageRoute`], which is the [`PageRoute`] version of this class
762#[derive(Clone)]
763pub struct MaterialPage {
764    /// See [`Page::key`].
765    pub key: Option<KeyRef>,
766
767    /// See [`Page::can_pop`].
768    pub can_pop: bool,
769
770    /// See [`Page::on_pop_invoked`].
771    pub on_pop_invoked: Option<PopInvokedWithResultCallback>,
772
773    /// See [`Page::name`].
774    pub name: Option<String>,
775
776    /// See [`Page::arguments`].
777    pub arguments: Option<Rc<dyn Any>>,
778
779    /// See [`Page::restoration_id`].
780    pub restoration_id: Option<String>,
781
782    /// The content to be shown in the [`Route`] created by this page.
783    pub child: WidgetRef,
784
785    /// Whether the route should remain in memory when it is inactive.
786    pub maintain_state: bool,
787
788    /// Whether this page route is a full-screen dialog.
789    pub fullscreen_dialog: bool,
790
791    /// Whether the route transition will prefer to animate a snapshot of the entering and
792    /// exiting routes.
793    pub allow_snapshotting: bool,
794
795    /// Whether the route introduces a route scope in the semantics tree; see
796    /// [`MaterialRouteTransitionMixin::include_route_semantics`].
797    pub include_route_semantics: bool,
798}
799
800impl MaterialPage {
801    /// Creates a material page; Dart's optional arguments are the setters.
802    ///
803    /// Dart's defaults: `maintain_state` true, `fullscreen_dialog` false, `allow_snapshotting`
804    /// true, `include_route_semantics` true, `can_pop` true.
805    #[cfg_attr(debug_assertions, track_caller)]
806    pub fn new<K>(child: impl IntoWidget<K>) -> MaterialPage {
807        MaterialPage {
808            key: None,
809            can_pop: true,
810            on_pop_invoked: None,
811            name: None,
812            arguments: None,
813            restoration_id: None,
814            child: child.into_widget(),
815            maintain_state: true,
816            fullscreen_dialog: false,
817            allow_snapshotting: true,
818            include_route_semantics: true,
819        }
820    }
821
822    /// Dart `MaterialPage(maintainState:)`.
823    pub fn maintain_state(mut self, maintain_state: bool) -> MaterialPage {
824        self.maintain_state = maintain_state;
825        self
826    }
827
828    /// Dart `MaterialPage(fullscreenDialog:)`.
829    pub fn fullscreen_dialog(mut self, fullscreen_dialog: bool) -> MaterialPage {
830        self.fullscreen_dialog = fullscreen_dialog;
831        self
832    }
833
834    /// Dart `MaterialPage(allowSnapshotting:)`.
835    pub fn allow_snapshotting(mut self, allow_snapshotting: bool) -> MaterialPage {
836        self.allow_snapshotting = allow_snapshotting;
837        self
838    }
839
840    /// Dart `MaterialPage(includeRouteSemantics:)`.
841    pub fn include_route_semantics(mut self, include_route_semantics: bool) -> MaterialPage {
842        self.include_route_semantics = include_route_semantics;
843        self
844    }
845
846    /// Dart `MaterialPage(key:)`.
847    pub fn key(mut self, key: KeyRef) -> MaterialPage {
848        self.key = Some(key);
849        self
850    }
851
852    /// Dart `MaterialPage(canPop:)`.
853    pub fn can_pop(mut self, can_pop: bool) -> MaterialPage {
854        self.can_pop = can_pop;
855        self
856    }
857
858    /// Dart `MaterialPage(onPopInvoked:)`.
859    pub fn on_pop_invoked(mut self, on_pop_invoked: PopInvokedWithResultCallback) -> MaterialPage {
860        self.on_pop_invoked = Some(on_pop_invoked);
861        self
862    }
863
864    /// Dart `MaterialPage(name:)`.
865    pub fn name(mut self, name: String) -> MaterialPage {
866        self.name = Some(name);
867        self
868    }
869
870    /// Dart `MaterialPage(arguments:)`.
871    pub fn arguments(mut self, arguments: Rc<dyn Any>) -> MaterialPage {
872        self.arguments = Some(arguments);
873        self
874    }
875
876    /// Dart `MaterialPage(restorationId:)`.
877    pub fn restoration_id(mut self, restoration_id: String) -> MaterialPage {
878        self.restoration_id = Some(restoration_id);
879        self
880    }
881}
882
883impl Debug for MaterialPage {
884    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885        f.debug_struct("MaterialPage")
886            .field("name", &self.name)
887            .field("child", &self.child)
888            .finish_non_exhaustive()
889    }
890}
891
892impl Page for MaterialPage {
893    fn as_any(&self) -> &dyn Any {
894        self
895    }
896
897    fn key(&self) -> Option<&KeyRef> {
898        self.key.as_ref()
899    }
900
901    fn name(&self) -> Option<&str> {
902        self.name.as_deref()
903    }
904
905    fn arguments(&self) -> Option<&Rc<dyn Any>> {
906        self.arguments.as_ref()
907    }
908
909    fn restoration_id(&self) -> Option<&str> {
910        self.restoration_id.as_deref()
911    }
912
913    fn can_pop(&self) -> bool {
914        self.can_pop
915    }
916
917    fn on_pop_invoked(&self, app: &mut App, did_pop: bool, result: RouteResult) {
918        if let Some(on_pop_invoked) = self.on_pop_invoked.clone() {
919            on_pop_invoked(app, did_pop, result);
920        }
921    }
922
923    fn create_route(&self, app: &mut App, context: BuildContext, this: &PageRef) -> RouteRef {
924        let _ = context;
925        PageBasedMaterialPageRoute::new(app, Rc::clone(this), self.allow_snapshotting).into_erased()
926    }
927}
928
929// A page-based version of MaterialPageRoute.
930//
931// This route uses the builder from the page to build its content. This ensures the content is up
932// to date after page updates.
933struct PageBasedMaterialPageRoute {
934    route: RouteData,
935    overlay_route: OverlayRouteData,
936    transition_route: TransitionRouteData,
937    local_history: LocalHistoryRouteData,
938    modal_route: ModalRouteData,
939    page_route: PageRouteData,
940}
941
942impl PageBasedMaterialPageRoute {
943    fn new(
944        app: &mut App,
945        page: PageRef,
946        allow_snapshotting: bool,
947    ) -> Ref<PageBasedMaterialPageRoute> {
948        let route = RouteData::new(app, Some(RouteSettingsRef::Page(page)), None);
949        let transition_route = TransitionRouteData::new(app);
950        let modal_route = ModalRouteData::new(app);
951        let mut page_route = PageRouteData::new();
952        page_route.allow_snapshotting = allow_snapshotting;
953        let this = app.create(PageBasedMaterialPageRoute {
954            route,
955            overlay_route: OverlayRouteData::new(),
956            transition_route,
957            local_history: LocalHistoryRouteData::new(),
958            modal_route,
959            page_route,
960        });
961        debug_assert!(TransitionRoute::opaque(this.handle(), app));
962        this
963    }
964
965    /// Dart's `_page` getter, read in place.
966    fn with_page<T>(self: Handle<Self>, app: &App, read: impl FnOnce(&MaterialPage) -> T) -> T {
967        match Route::settings(self, app) {
968            RouteSettingsRef::Page(page) => read(
969                page.as_any()
970                    .downcast_ref::<MaterialPage>()
971                    .expect("a page-based material page route's settings are its MaterialPage"),
972            ),
973            RouteSettingsRef::Settings(_) => {
974                panic!("a page-based material page route's settings are its MaterialPage")
975            }
976        }
977    }
978}
979
980impl Route for PageBasedMaterialPageRoute {
981    crate::material_route_transition_mixin_route_overrides!();
982}
983
984impl OverlayRoute for PageBasedMaterialPageRoute {
985    waft_widgets::modal_overlay_route_overrides!();
986}
987
988impl PredictiveBackRoute for PageBasedMaterialPageRoute {
989    waft_widgets::page_predictive_back_route_overrides!();
990}
991
992impl TransitionRoute for PageBasedMaterialPageRoute {
993    crate::material_route_transition_mixin_transition_route_overrides!();
994
995    fn opaque(self: Handle<Self>, app: &App) -> bool {
996        PageRoute::opaque(self, app)
997    }
998}
999
1000impl LocalHistoryRoute for PageBasedMaterialPageRoute {
1001    waft_widgets::local_history_route_accessors!();
1002}
1003
1004impl ModalRoute for PageBasedMaterialPageRoute {
1005    crate::material_route_transition_mixin_modal_route_overrides!();
1006
1007    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
1008        self.with_page(app, |page| page.maintain_state)
1009    }
1010
1011    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
1012        PageRoute::fullscreen_dialog(self, app)
1013    }
1014}
1015
1016impl PageRoute for PageBasedMaterialPageRoute {
1017    waft_widgets::page_route_accessors!();
1018
1019    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
1020        self.with_page(app, |page| page.fullscreen_dialog)
1021    }
1022}
1023
1024impl MaterialRouteTransitionMixin for PageBasedMaterialPageRoute {
1025    fn build_content(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1026        let _ = context;
1027        self.with_page(app, |page| page.child.clone())
1028    }
1029
1030    fn include_route_semantics(self: Handle<Self>, app: &App) -> bool {
1031        self.with_page(app, |page| page.include_route_semantics)
1032    }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037    use std::cell::{Cell, RefCell};
1038
1039    use waft_cupertino::CupertinoPageRoute;
1040    use waft_embedder::Offset;
1041    use waft_foundation::Listener;
1042    use waft_painting::EdgeInsetsGeometry;
1043    use waft_rendering::{AnyLayer, OpacityLayer, TransformLayer};
1044    use waft_widgets::{
1045        AnyElement, AnyModalRoute, Center, Container, FocusNodeLeaf, FocusScope, GestureDetector,
1046        GlobalKey, Navigator, NavigatorState, Padding, PageRouteBuilder, PreferredSizeWidgetRef,
1047        SizedBox, SnapshotWidget, StatefulBuilder, Text,
1048    };
1049
1050    use waft_widgets::testing::{
1051        TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_nothing,
1052        finds_one_widget, test_widgets, test_widgets_variant,
1053    };
1054
1055    use super::*;
1056    use crate::app::MaterialApp;
1057    use crate::app_bar::AppBar;
1058    use crate::elevated_button::ElevatedButton;
1059    use crate::icon_button::IconButton;
1060    use crate::material::Material;
1061    use crate::page_transitions_theme::PageTransitionsTheme;
1062    use crate::scaffold::Scaffold;
1063    use crate::test_support::material_page_app;
1064    use crate::text_button::TextButton;
1065    use crate::theme_data::ThemeData;
1066
1067    /// `tester.pumpWidget(MaterialApp(theme: theme(app), ..))` with the pages `configure` gives.
1068    fn pump_app(
1069        tester: &mut WidgetTester,
1070        theme: impl FnOnce(&App) -> ThemeData,
1071        configure: impl FnOnce(MaterialApp) -> MaterialApp,
1072    ) {
1073        let root = {
1074            let theme = theme(&tester.cell.borrow());
1075            material_page_app(theme, configure)
1076        };
1077        tester.pump_widget(root);
1078    }
1079
1080    fn material_text(text: &'static str) -> WidgetBuilder {
1081        Rc::new(move |_app, _context| Material::new().child(Text::new(text)).into_widget())
1082    }
1083
1084    fn scaffold_text(text: &'static str) -> WidgetBuilder {
1085        Rc::new(move |_app, _context| Scaffold::new().body(Text::new(text)).into_widget())
1086    }
1087
1088    fn navigator(tester: &WidgetTester) -> Handle<NavigatorState> {
1089        let element = *find::by_type::<Navigator>()
1090            .evaluate(tester)
1091            .first()
1092            .expect("a navigator");
1093        element
1094            .state_handle::<NavigatorState>(&tester.cell.borrow())
1095            .expect("a navigator's state")
1096    }
1097
1098    fn the_text(tester: &WidgetTester, text: &str) -> AnyElement {
1099        *find::text(text)
1100            .evaluate(tester)
1101            .first()
1102            .expect("the text is mounted")
1103    }
1104
1105    /// Dart's `tester.getTopLeft(find.text(text))`.
1106    fn top_left(tester: &WidgetTester, text: &str) -> Offset {
1107        tester.get_rect(the_text(tester, text)).top_left()
1108    }
1109
1110    fn onstage(tester: &WidgetTester, text: &str) -> bool {
1111        !find::text(text).evaluate(tester).is_empty()
1112    }
1113
1114    fn push(tester: &WidgetTester, route: impl FnOnce(&mut App) -> RouteRef) {
1115        let navigator = navigator(tester);
1116        let mut app = tester.cell.borrow_mut();
1117        let route = route(&mut app);
1118        navigator.push(&mut app, route);
1119    }
1120
1121    fn pop(tester: &WidgetTester) {
1122        navigator(tester).pop(&mut tester.cell.borrow_mut(), None);
1123    }
1124
1125    // 'test page transition (CupertinoPageTransition)', without the edge shadow's paints, which
1126    // waft-cupertino's cases cover.
1127    #[test]
1128    fn a_material_page_route_slides_in_from_the_right_on_ios_and_macos() {
1129        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1130            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1131                pump_app(tester, ThemeData::new, |app| {
1132                    app.home(Material::new().child(Text::new("Page 1")))
1133                        .routes([("/next".to_string(), material_text("Page 2"))])
1134                });
1135
1136                let widget_1_initial_top_left = top_left(tester, "Page 1");
1137
1138                navigator(tester).push_named(&mut tester.cell.borrow_mut(), "/next", None);
1139
1140                tester.pump();
1141                tester.pump_by(Duration::from_millis(150));
1142
1143                let widget_1_transient_top_left = top_left(tester, "Page 1");
1144                let widget_2_top_left = top_left(tester, "Page 2");
1145
1146                // Page 1 is moving to the left.
1147                assert!(widget_1_transient_top_left.dx() < widget_1_initial_top_left.dx());
1148                // Page 1 isn't moving vertically.
1149                assert!(widget_1_transient_top_left.dy() == widget_1_initial_top_left.dy());
1150                // iOS transition is horizontal only.
1151                assert!(widget_1_initial_top_left.dy() == widget_2_top_left.dy());
1152                // Page 2 is coming in from the right.
1153                assert!(widget_2_top_left.dx() > widget_1_initial_top_left.dx());
1154
1155                tester.pump_and_settle();
1156
1157                // Page 2 covers page 1.
1158                assert!(!onstage(tester, "Page 1"));
1159                assert!(onstage(tester, "Page 2"));
1160
1161                pop(tester);
1162                tester.pump();
1163                tester.pump_by(Duration::from_millis(100));
1164
1165                let widget_1_transient_top_left = top_left(tester, "Page 1");
1166                let widget_2_top_left = top_left(tester, "Page 2");
1167
1168                // Page 1 is coming back from the left.
1169                assert!(widget_1_transient_top_left.dx() < widget_1_initial_top_left.dx());
1170                // Page 1 isn't moving vertically.
1171                assert!(widget_1_transient_top_left.dy() == widget_1_initial_top_left.dy());
1172                // iOS transition is horizontal only.
1173                assert!(widget_1_initial_top_left.dy() == widget_2_top_left.dy());
1174                // Page 2 is leaving towards the right.
1175                assert!(widget_2_top_left.dx() > widget_1_initial_top_left.dx());
1176
1177                tester.pump_and_settle();
1178
1179                assert!(onstage(tester, "Page 1"));
1180                assert!(find::text("Page 2").evaluate(tester).is_empty());
1181
1182                // Page 1 is back where it started.
1183                assert_eq!(top_left(tester, "Page 1"), widget_1_initial_top_left);
1184            });
1185        }
1186    }
1187
1188    #[test]
1189    fn a_fullscreen_dialog_comes_in_from_the_bottom_on_ios_and_macos() {
1190        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1191            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1192                pump_app(tester, ThemeData::new, |app| {
1193                    app.home(Material::new().child(Text::new("Page 1")))
1194                });
1195
1196                let widget_1_initial_top_left = top_left(tester, "Page 1");
1197
1198                push(tester, |app| {
1199                    let route = MaterialPageRoute::new(app, material_text("Page 2"))
1200                        .fullscreen_dialog(app, true);
1201                    route.into_erased()
1202                });
1203
1204                tester.pump();
1205                tester.pump_by(Duration::from_millis(100));
1206
1207                let widget_1_transient_top_left = top_left(tester, "Page 1");
1208                let widget_2_top_left = top_left(tester, "Page 2");
1209
1210                // Page 1 doesn't move.
1211                assert_eq!(widget_1_transient_top_left, widget_1_initial_top_left);
1212                // Fullscreen dialogs transitions vertically only.
1213                assert!(widget_1_initial_top_left.dx() == widget_2_top_left.dx());
1214                // Page 2 is coming in from the bottom.
1215                assert!(widget_2_top_left.dy() > widget_1_initial_top_left.dy());
1216
1217                tester.pump_and_settle();
1218
1219                // Page 2 covers page 1.
1220                assert!(!onstage(tester, "Page 1"));
1221                assert!(onstage(tester, "Page 2"));
1222
1223                pop(tester);
1224                tester.pump();
1225                tester.pump_by(Duration::from_millis(100));
1226
1227                let widget_1_transient_top_left = top_left(tester, "Page 1");
1228                let widget_2_top_left = top_left(tester, "Page 2");
1229
1230                // Page 1 doesn't move.
1231                assert_eq!(widget_1_transient_top_left, widget_1_initial_top_left);
1232                // Fullscreen dialogs transitions vertically only.
1233                assert!(widget_1_initial_top_left.dx() == widget_2_top_left.dx());
1234                // Page 2 is leaving towards the bottom.
1235                assert!(widget_2_top_left.dy() > widget_1_initial_top_left.dy());
1236
1237                tester.pump_and_settle();
1238
1239                assert!(onstage(tester, "Page 1"));
1240                assert!(find::text("Page 2").evaluate(tester).is_empty());
1241
1242                // Page 1 is back where it started.
1243                assert_eq!(top_left(tester, "Page 1"), widget_1_initial_top_left);
1244            });
1245        }
1246    }
1247
1248    /// The back-gesture cases' app: `Page 1` at home and `Page 2` at `/next`, each the body of a
1249    /// scaffold, with `/next` pushed and settled.
1250    fn pushed_scaffold_pages(platform: TargetPlatform) -> WidgetTester {
1251        let mut tester = WidgetTester::on(platform);
1252        pump_app(&mut tester, ThemeData::new, |app| {
1253            app.home(Scaffold::new().body(Text::new("Page 1")))
1254                .routes([("/next".to_string(), scaffold_text("Page 2"))])
1255        });
1256
1257        navigator(&tester).push_named(&mut tester.cell.borrow_mut(), "/next", None);
1258        tester.pump_and_settle();
1259
1260        expect(&tester, &find::text("Page 1"), finds_nothing());
1261        assert!(onstage(&tester, "Page 2"));
1262        tester
1263    }
1264
1265    #[test]
1266    fn there_is_no_back_gesture_on_android() {
1267        test_widgets(|_tester| {
1268            let mut tester = pushed_scaffold_pages(TargetPlatform::Android);
1269
1270            // Drag from left edge to invoke the gesture.
1271            let mut gesture = TestPointer::touch(1);
1272            tester.down(&mut gesture, Offset::new(5.0, 100.0));
1273            tester.move_to(&mut gesture, Offset::new(405.0, 100.0), true);
1274            tester.pump();
1275
1276            expect(&tester, &find::text("Page 1"), finds_nothing());
1277            assert!(onstage(&tester, "Page 2"));
1278
1279            // Page 2 didn't move.
1280            assert_eq!(top_left(&tester, "Page 2"), Offset::ZERO);
1281        });
1282    }
1283
1284    #[test]
1285    fn the_back_gesture_drags_the_page_with_the_finger_on_ios_and_macos() {
1286        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1287            test_widgets(|_tester| {
1288                let mut tester = pushed_scaffold_pages(platform);
1289
1290                // Drag from left edge to invoke the gesture.
1291                let mut gesture = TestPointer::touch(1);
1292                tester.down(&mut gesture, Offset::new(5.0, 100.0));
1293                tester.move_to(&mut gesture, Offset::new(405.0, 100.0), true);
1294                tester.pump();
1295
1296                // Page 1 is now visible.
1297                assert!(onstage(&tester, "Page 1"));
1298                assert!(onstage(&tester, "Page 2"));
1299
1300                // The route widget position needs to track the finger position very exactly.
1301                assert_eq!(top_left(&tester, "Page 2"), Offset::new(400.0, 0.0));
1302
1303                tester.move_to(&mut gesture, Offset::new(205.0, 100.0), true);
1304                tester.pump();
1305
1306                assert_eq!(top_left(&tester, "Page 2"), Offset::new(200.0, 0.0));
1307
1308                tester.move_to(&mut gesture, Offset::new(105.0, 300.0), true);
1309                tester.pump();
1310
1311                assert_eq!(top_left(&tester, "Page 2"), Offset::new(100.0, 0.0));
1312            });
1313        }
1314    }
1315
1316    #[test]
1317    fn there_is_no_back_gesture_on_a_fullscreen_dialog_on_ios_and_macos() {
1318        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1319            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1320                pump_app(tester, ThemeData::new, |app| {
1321                    app.home(Scaffold::new().body(Text::new("Page 1")))
1322                });
1323
1324                push(tester, |app| {
1325                    let route = MaterialPageRoute::new(app, scaffold_text("Page 2"))
1326                        .fullscreen_dialog(app, true);
1327                    route.into_erased()
1328                });
1329                tester.pump_and_settle();
1330
1331                expect(tester, &find::text("Page 1"), finds_nothing());
1332                assert!(onstage(tester, "Page 2"));
1333
1334                // Drag from left edge to invoke the gesture.
1335                let mut gesture = TestPointer::touch(1);
1336                tester.down(&mut gesture, Offset::new(5.0, 100.0));
1337                tester.move_to(&mut gesture, Offset::new(405.0, 100.0), true);
1338                tester.pump();
1339
1340                expect(tester, &find::text("Page 1"), finds_nothing());
1341                assert!(onstage(tester, "Page 2"));
1342
1343                // Page 2 didn't move.
1344                assert_eq!(top_left(tester, "Page 2"), Offset::ZERO);
1345            });
1346        }
1347    }
1348
1349    fn app_bar_page(title: &'static str) -> WidgetRef {
1350        Scaffold::new()
1351            .app_bar(PreferredSizeWidgetRef::new(
1352                AppBar::new().title(Text::new(title)),
1353            ))
1354            .body(SizedBox::new())
1355            .into_widget()
1356    }
1357
1358    #[test]
1359    fn a_fullscreen_dialog_does_not_move_the_route_below_it_on_ios_and_macos() {
1360        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1361            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1362                pump_app(tester, ThemeData::new, |app| {
1363                    app.initial_route("/").on_generate_route(|app, settings| {
1364                        if settings.name.as_deref() == Some("/") {
1365                            let route = PageRouteBuilder::new(
1366                                app,
1367                                Rc::new(|_app, _context, _animation, _secondary| {
1368                                    app_bar_page("Page 1")
1369                                }),
1370                            );
1371                            return Some(route.erase());
1372                        }
1373                        let route = MaterialPageRoute::new(
1374                            app,
1375                            Rc::new(|_app, _context| app_bar_page("Page 2")),
1376                        )
1377                        .fullscreen_dialog(app, true);
1378                        Some(route.erase())
1379                    })
1380                });
1381
1382                expect(tester, &find::text("Page 1"), finds_one_widget());
1383                expect(tester, &find::text("Page 2"), finds_nothing());
1384
1385                let page_title_dx = top_left(tester, "Page 1").dx();
1386
1387                navigator(tester).push_named(&mut tester.cell.borrow_mut(), "/next", None);
1388                tester.pump();
1389                tester.pump_by(Duration::from_millis(100));
1390
1391                // Second page transition has started.
1392                expect(tester, &find::text("Page 2"), finds_one_widget());
1393
1394                // First page has not moved.
1395                assert_eq!(top_left(tester, "Page 1").dx(), page_title_dx);
1396            });
1397        }
1398    }
1399
1400    #[test]
1401    fn a_material_page_route_slides_out_under_a_cupertino_page_route_on_ios_and_macos() {
1402        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1403            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1404                pump_app(
1405                    tester,
1406                    |app| {
1407                        ThemeData::builder()
1408                            .platform(TargetPlatform::IOS)
1409                            .build(app)
1410                    },
1411                    |app| app.home(app_bar_page("Title")),
1412                );
1413
1414                let title_initial_top_left = top_left(tester, "Title");
1415
1416                push(tester, |app| {
1417                    (CupertinoPageRoute::new(
1418                        app,
1419                        Rc::new(|_app, _context| SizedBox::expand().into_widget()),
1420                    ))
1421                    .into_erased()
1422                });
1423
1424                tester.pump();
1425                tester.pump_by(Duration::from_millis(150));
1426
1427                let title_transient_top_left = top_left(tester, "Title");
1428
1429                // Title of the first route slides to the left.
1430                assert_eq!(title_initial_top_left.dy(), title_transient_top_left.dy());
1431                assert!(title_initial_top_left.dx() > title_transient_top_left.dx());
1432            });
1433        }
1434    }
1435
1436    // 'test adaptable transitions switch during execution'.
1437    #[test]
1438    fn the_transition_follows_the_theme_platform_while_it_runs() {
1439        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1440            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1441                let routes = || [("/next".to_string(), material_text("Page 2"))];
1442                pump_app(
1443                    tester,
1444                    |app| {
1445                        ThemeData::builder()
1446                            .platform(TargetPlatform::Android)
1447                            .page_transitions_theme(PageTransitionsTheme::new().with_builders(
1448                                indexmap::IndexMap::from([(
1449                                    TargetPlatform::Android,
1450                                    PageTransitionsBuilderRef::new(
1451                                        waft_widgets::FadeUpwardsPageTransitionsBuilder::new(),
1452                                    ),
1453                                )]),
1454                            ))
1455                            .build(app)
1456                    },
1457                    move |app| {
1458                        app.home(Material::new().child(Text::new("Page 1")))
1459                            .routes(routes())
1460                    },
1461                );
1462
1463                let widget_1_initial_top_left = top_left(tester, "Page 1");
1464
1465                navigator(tester).push_named(&mut tester.cell.borrow_mut(), "/next", None);
1466                tester.pump();
1467                tester.pump_by(Duration::from_millis(100));
1468
1469                let widget_2_rect = tester.get_rect(the_text(tester, "Page 2"));
1470                let widget_2_top_left = widget_2_rect.top_left();
1471
1472                // Android transition is vertical only.
1473                assert!(widget_1_initial_top_left.dx() == widget_2_top_left.dx());
1474                // Page 1 is above page 2 mid-transition.
1475                assert!(widget_1_initial_top_left.dy() < widget_2_top_left.dy());
1476                // Animation begins from the top of the page.
1477                assert!(widget_2_top_left.dy() < widget_2_rect.height());
1478
1479                tester.pump_by(Duration::from_millis(300));
1480
1481                // Page 2 covers page 1.
1482                expect(tester, &find::text("Page 1"), finds_nothing());
1483                assert!(onstage(tester, "Page 2"));
1484
1485                // Re-pump the same app but with iOS instead of Android.
1486                pump_app(tester, ThemeData::new, move |app| {
1487                    app.home(Material::new().child(Text::new("Page 1")))
1488                        .routes(routes())
1489                });
1490
1491                pop(tester);
1492                tester.pump();
1493                tester.pump_by(Duration::from_millis(100));
1494
1495                let widget_1_transient_top_left = top_left(tester, "Page 1");
1496                let widget_2_top_left = top_left(tester, "Page 2");
1497
1498                // Page 1 is coming back from the left.
1499                assert!(widget_1_transient_top_left.dx() < widget_1_initial_top_left.dx());
1500                // Page 1 isn't moving vertically.
1501                assert!(widget_1_transient_top_left.dy() == widget_1_initial_top_left.dy());
1502                // iOS transition is horizontal only.
1503                assert!(widget_1_initial_top_left.dy() == widget_2_top_left.dy());
1504                // Page 2 is leaving towards the right.
1505                assert!(widget_2_top_left.dx() > widget_1_initial_top_left.dx());
1506
1507                tester.pump_by(Duration::from_millis(300));
1508
1509                assert!(onstage(tester, "Page 1"));
1510                assert!(find::text("Page 2").evaluate(tester).is_empty());
1511
1512                // Page 1 is back where it started.
1513                assert_eq!(top_left(tester, "Page 1"), widget_1_initial_top_left);
1514            });
1515        }
1516    }
1517
1518    #[test]
1519    fn a_barrier_dismissible_material_page_route_pops_on_escape() {
1520        test_widgets(|tester| {
1521            pump_app(tester, ThemeData::new, |app| {
1522                app.home(Scaffold::new().body(Text::new("home")))
1523            });
1524            push(tester, |app| {
1525                let route = MaterialPageRoute::new(app, scaffold_text("route"))
1526                    .barrier_dismissible(app, true);
1527                route.into_erased()
1528            });
1529            tester.pump_and_settle();
1530            expect(tester, &find::text("route"), finds_one_widget());
1531            expect(tester, &find::text("home"), finds_nothing());
1532
1533            // Try to dismiss the route with the escape key.
1534            tester.send_key_event(
1535                waft_services::PhysicalKeyboardKey::ESCAPE,
1536                waft_services::LogicalKeyboardKey::ESCAPE,
1537            );
1538            tester.pump_and_settle();
1539
1540            expect(tester, &find::text("route"), finds_nothing());
1541        });
1542    }
1543
1544    #[test]
1545    fn a_route_that_does_not_maintain_state_is_not_built_under_another() {
1546        test_widgets(|tester| {
1547            pump_app(tester, ThemeData::new, |app| {
1548                app.on_generate_route(|app, settings| {
1549                    let first = settings.name.as_deref() == Some("/");
1550                    let route = MaterialPageRoute::new(
1551                        app,
1552                        Rc::new(move |_app, _context| {
1553                            Text::new(if first { "first" } else { "second" }).into_widget()
1554                        }),
1555                    )
1556                    .maintain_state(app, !first);
1557                    Some(route.erase())
1558                })
1559            });
1560            navigator(tester).push_named(&mut tester.cell.borrow_mut(), "/second", None);
1561            tester.pump_and_settle();
1562
1563            // The first page does not maintain state.
1564            assert!(
1565                find::text("first")
1566                    .skip_offstage(false)
1567                    .evaluate(tester)
1568                    .is_empty()
1569            );
1570            expect(tester, &find::text("second"), finds_one_widget());
1571        });
1572    }
1573
1574    #[test]
1575    fn material_page_routes_hand_each_other_one_delegated_transition() {
1576        test_widgets(|tester| {
1577            let first_page_context: Rc<std::cell::Cell<Option<BuildContext>>> = Rc::default();
1578            pump_app(tester, ThemeData::new, {
1579                let first_page_context = Rc::clone(&first_page_context);
1580                move |app| {
1581                    app.home(waft_widgets::Builder::new(move |_app, context| {
1582                        first_page_context.set(Some(context));
1583                        Text::new("first").into_widget()
1584                    }))
1585                }
1586            });
1587            let pushed: Rc<std::cell::Cell<Option<Handle<MaterialPageRoute>>>> = Rc::default();
1588            push(tester, |app| {
1589                let route = MaterialPageRoute::new(app, material_text("second"));
1590                pushed.set(Some(route.handle()));
1591                route.into_erased()
1592            });
1593            tester.pump_and_settle();
1594
1595            let mut app = tester.cell.borrow_mut();
1596            let first = AnyModalRoute::of(&mut app, first_page_context.get().expect("built"))
1597                .expect("the first page's route")
1598                .as_route()
1599                .downcast::<MaterialPageRoute>(&app)
1600                .expect("a material page route");
1601            let second = pushed.get().expect("pushed");
1602            // Both are the tear-off of the mixin's static `_delegatedTransition`.
1603            assert_eq!(
1604                ModalRoute::delegated_transition(first, &app),
1605                ModalRoute::delegated_transition(second, &app)
1606            );
1607            assert!(ModalRoute::delegated_transition(first, &app).is_some());
1608            // So the route below receives no transition: the two already run in sync.
1609            assert!(first.modal_route_data(&app).received_transition.is_none());
1610            assert!(TransitionRoute::can_transition_to(
1611                first,
1612                &app,
1613                TransitionRoute::as_transition_route(second)
1614            ));
1615        });
1616    }
1617
1618    #[test]
1619    fn a_material_page_updates_its_route_content_without_a_new_route() {
1620        test_widgets(|tester| {
1621            let key: KeyRef = KeyRef::Local(Rc::new(waft_foundation::UniqueKey::new()));
1622            let context: Rc<std::cell::Cell<Option<BuildContext>>> = Rc::default();
1623            let pages = |text: &'static str| -> Vec<PageRef> {
1624                let context = Rc::clone(&context);
1625                vec![Rc::new(
1626                    MaterialPage::new(waft_widgets::Builder::new(move |_app, page_context| {
1627                        context.set(Some(page_context));
1628                        Text::new(text).into_widget()
1629                    }))
1630                    .key(key.clone()),
1631                )]
1632            };
1633            let navigator_for = |pages: Vec<PageRef>| {
1634                waft_widgets::Directionality::new(
1635                    waft_embedder::TextDirection::Ltr,
1636                    Navigator::new()
1637                        .pages(pages)
1638                        .on_did_remove_page(|_app, _page| panic!("no page is removed")),
1639                )
1640                .into_widget()
1641            };
1642            tester.pump_widget(navigator_for(pages("first")));
1643            expect(tester, &find::text("first"), finds_one_widget());
1644            let first_route = {
1645                let mut app = tester.cell.borrow_mut();
1646                AnyModalRoute::of(&mut app, context.get().expect("built")).expect("a route")
1647            };
1648
1649            tester.pump_widget(navigator_for(pages("second")));
1650            let second_route = {
1651                let mut app = tester.cell.borrow_mut();
1652                AnyModalRoute::of(&mut app, context.get().expect("built")).expect("a route")
1653            };
1654            // There should be no transition because the page has the same key.
1655            assert_eq!(first_route, second_route);
1656            // The content does update.
1657            assert!(find::text("first").evaluate(tester).is_empty());
1658            expect(tester, &find::text("second"), finds_one_widget());
1659        });
1660    }
1661
1662    #[test]
1663    fn a_material_page_can_toggle_maintain_state() {
1664        test_widgets(|tester| {
1665            let key_one: KeyRef = KeyRef::Local(Rc::new(waft_foundation::UniqueKey::new()));
1666            let key_two: KeyRef = KeyRef::Local(Rc::new(waft_foundation::UniqueKey::new()));
1667            let pages = |maintain_state: bool| -> Vec<PageRef> {
1668                vec![
1669                    Rc::new(
1670                        MaterialPage::new(Text::new("first"))
1671                            .key(key_one.clone())
1672                            .maintain_state(maintain_state),
1673                    ),
1674                    Rc::new(MaterialPage::new(Text::new("second")).key(key_two.clone())),
1675                ]
1676            };
1677            let navigator_for = |pages: Vec<PageRef>| {
1678                waft_widgets::Directionality::new(
1679                    waft_embedder::TextDirection::Ltr,
1680                    Navigator::new()
1681                        .pages(pages)
1682                        .on_did_remove_page(|_app, _page| panic!("no page is removed")),
1683                )
1684                .into_widget()
1685            };
1686            tester.pump_widget(navigator_for(pages(false)));
1687
1688            // Page one does not maintain state.
1689            assert!(find::text("first").evaluate(tester).is_empty());
1690            expect(tester, &find::text("second"), finds_one_widget());
1691
1692            tester.pump_widget(navigator_for(pages(true)));
1693
1694            // Page one sets the maintain state to be true, its widget tree should be built.
1695            assert_eq!(
1696                find::text("first")
1697                    .skip_offstage(false)
1698                    .evaluate(tester)
1699                    .len(),
1700                1
1701            );
1702            expect(tester, &find::text("second"), finds_one_widget());
1703        });
1704    }
1705
1706    #[test]
1707    fn the_route_transition_durations_are_the_platform_builders() {
1708        for (platform, duration) in [
1709            (TargetPlatform::Android, Duration::from_millis(450)),
1710            (TargetPlatform::IOS, Duration::from_millis(500)),
1711            (TargetPlatform::MacOS, Duration::from_millis(500)),
1712            (TargetPlatform::Windows, Duration::from_millis(300)),
1713            (TargetPlatform::Linux, Duration::from_millis(300)),
1714            (TargetPlatform::Fuchsia, Duration::from_millis(300)),
1715        ] {
1716            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1717                pump_app(tester, ThemeData::new, |app| {
1718                    app.home(Material::new().child(Text::new("home")))
1719                });
1720                let pushed: Rc<std::cell::Cell<Option<Handle<MaterialPageRoute>>>> = Rc::default();
1721                push(tester, |app| {
1722                    let route = MaterialPageRoute::new(app, material_text("next"));
1723                    pushed.set(Some(route.handle()));
1724                    route.into_erased()
1725                });
1726                let route = pushed.get().expect("pushed");
1727                let mut app = tester.cell.borrow_mut();
1728                assert_eq!(
1729                    TransitionRoute::transition_duration(route, &mut app),
1730                    duration,
1731                    "{platform:?}"
1732                );
1733                let controller = TransitionRoute::controller(route, &app).expect("installed");
1734                assert_eq!(app.get(controller).duration, Some(duration), "{platform:?}");
1735            });
1736        }
1737    }
1738
1739    /// A page with a `TextButton` showing `label` that runs `on_pressed` with the page's context.
1740    fn button_page(
1741        label: &'static str,
1742        on_pressed: impl Fn(&mut App, BuildContext) + 'static,
1743    ) -> WidgetBuilder {
1744        let on_pressed = Rc::new(on_pressed);
1745        Rc::new(move |_app, context| {
1746            let on_pressed = Rc::clone(&on_pressed);
1747            Material::new()
1748                .child(TextButton::new(
1749                    Some(Listener::new(move |app| on_pressed(app, context))),
1750                    Some(Text::new(label)),
1751                ))
1752                .into_widget()
1753        })
1754    }
1755
1756    /// Dart's `tester.getCenter(find.text(text))`.
1757    fn center(tester: &WidgetTester, text: &str) -> Offset {
1758        tester.get_rect(the_text(tester, text)).center()
1759    }
1760
1761    fn count_onstage(tester: &WidgetTester, text: &str) -> usize {
1762        find::text(text).evaluate(tester).len()
1763    }
1764
1765    fn platform_at(tester: &WidgetTester, text: &str) -> TargetPlatform {
1766        let element = the_text(tester, text);
1767        Theme::of(&mut tester.cell.borrow_mut(), element).platform
1768    }
1769
1770    fn platform_theme(platform: TargetPlatform) -> impl FnOnce(&App) -> ThemeData {
1771        move |app| ThemeData::builder().platform(platform).build(app)
1772    }
1773
1774    #[test]
1775    fn back_gesture_while_os_changes() {
1776        test_widgets(|tester| {
1777            let routes = || {
1778                [
1779                    (
1780                        "/".to_string(),
1781                        button_page("PUSH", |app, context| {
1782                            Navigator::push_named(app, context, "/b", None);
1783                        }),
1784                    ),
1785                    (
1786                        "/b".to_string(),
1787                        Rc::new(|_app: &mut App, _context: BuildContext| {
1788                            Text::new("HELLO").into_widget()
1789                        }) as WidgetBuilder,
1790                    ),
1791                ]
1792            };
1793            pump_app(tester, platform_theme(TargetPlatform::IOS), |app| {
1794                app.routes(routes())
1795            });
1796            tester.tap(find::text("PUSH"));
1797            assert_eq!(tester.pump_and_settle_by(Duration::from_secs(60)), 2);
1798            assert_eq!(count_onstage(tester, "PUSH"), 0);
1799            assert_eq!(count_onstage(tester, "HELLO"), 1);
1800            let hello_position_1 = center(tester, "HELLO");
1801            let mut gesture = TestPointer::touch(1);
1802            tester.down(&mut gesture, Offset::new(2.5, 300.0));
1803            tester.pump_by(Duration::from_millis(20));
1804            let to = gesture.position + Offset::new(100.0, 0.0);
1805            tester.move_to(&mut gesture, to, true);
1806            assert_eq!(count_onstage(tester, "PUSH"), 0);
1807            assert_eq!(count_onstage(tester, "HELLO"), 1);
1808            tester.pump_by(Duration::from_millis(20));
1809            assert_eq!(count_onstage(tester, "PUSH"), 1);
1810            assert_eq!(count_onstage(tester, "HELLO"), 1);
1811            let hello_position_2 = center(tester, "HELLO");
1812            assert!(hello_position_1.dx() < hello_position_2.dx());
1813            assert_eq!(hello_position_1.dy(), hello_position_2.dy());
1814            assert_eq!(platform_at(tester, "HELLO"), TargetPlatform::IOS);
1815            pump_app(tester, platform_theme(TargetPlatform::Android), |app| {
1816                app.routes(routes())
1817            });
1818            // Now we have to let the theme animation run through.
1819            // This takes three frames (including the first one above):
1820            //  1. Start the Theme animation. It's at t=0 so everything else is identical.
1821            //  2. Start any animations that are informed by the Theme, for example, the
1822            //     DefaultTextStyle, on the first frame that the theme is not at t=0. In
1823            //     this case, it's at t=1.0 of the theme animation, so this is also the
1824            //     frame in which the theme animation ends.
1825            //  3. End all the other animations.
1826            assert_eq!(tester.pump_and_settle_by(Duration::from_secs(60)), 2);
1827            assert_eq!(platform_at(tester, "HELLO"), TargetPlatform::Android);
1828            let hello_position_3 = center(tester, "HELLO");
1829            assert_eq!(hello_position_3, hello_position_2);
1830            assert_eq!(count_onstage(tester, "PUSH"), 1);
1831            assert_eq!(count_onstage(tester, "HELLO"), 1);
1832            let to = gesture.position + Offset::new(100.0, 0.0);
1833            tester.move_to(&mut gesture, to, true);
1834            tester.pump_by(Duration::from_millis(20));
1835            assert_eq!(count_onstage(tester, "PUSH"), 1);
1836            assert_eq!(count_onstage(tester, "HELLO"), 1);
1837            let hello_position_4 = center(tester, "HELLO");
1838            assert!(hello_position_3.dx() < hello_position_4.dx());
1839            assert_eq!(hello_position_3.dy(), hello_position_4.dy());
1840            let to = gesture.position + Offset::new(500.0, 0.0);
1841            tester.move_to(&mut gesture, to, true);
1842            tester.up(&gesture);
1843            assert_eq!(tester.pump_and_settle_by(Duration::from_secs(60)), 3);
1844            assert_eq!(count_onstage(tester, "PUSH"), 1);
1845            assert!(find::text("HELLO").evaluate(tester).is_empty());
1846
1847            pump_app(tester, platform_theme(TargetPlatform::MacOS), |app| {
1848                app.routes(routes())
1849            });
1850            tester.tap(find::text("PUSH"));
1851            assert_eq!(tester.pump_and_settle_by(Duration::from_secs(60)), 2);
1852            assert_eq!(count_onstage(tester, "PUSH"), 0);
1853            assert_eq!(count_onstage(tester, "HELLO"), 1);
1854            let hello_position_5 = center(tester, "HELLO");
1855            tester.down(&mut gesture, Offset::new(2.5, 300.0));
1856            tester.pump_by(Duration::from_millis(20));
1857            let to = gesture.position + Offset::new(100.0, 0.0);
1858            tester.move_to(&mut gesture, to, true);
1859            assert_eq!(count_onstage(tester, "PUSH"), 0);
1860            assert_eq!(count_onstage(tester, "HELLO"), 1);
1861            tester.pump_by(Duration::from_millis(20));
1862            assert_eq!(count_onstage(tester, "PUSH"), 1);
1863            assert_eq!(count_onstage(tester, "HELLO"), 1);
1864            let hello_position_6 = center(tester, "HELLO");
1865            assert!(hello_position_5.dx() < hello_position_6.dx());
1866            assert_eq!(hello_position_5.dy(), hello_position_6.dy());
1867            assert_eq!(platform_at(tester, "HELLO"), TargetPlatform::MacOS);
1868        });
1869    }
1870
1871    /// `MaterialApp(onGenerateRoute:)` of `MaterialPageRoute`s: `/` is 'Page 1', the rest
1872    /// 'Page 2', each in a `Center`.
1873    fn numbered_pages(tester: &mut WidgetTester) {
1874        pump_app(tester, ThemeData::new, |app| {
1875            app.on_generate_route(|app, settings| {
1876                let page_number = if settings.name.as_deref() == Some("/") {
1877                    "1"
1878                } else {
1879                    "2"
1880                };
1881                let route = MaterialPageRoute::new(
1882                    app,
1883                    Rc::new(move |_app, _context| {
1884                        Center::new()
1885                            .child(Text::new(format!("Page {page_number}")))
1886                            .into_widget()
1887                    }),
1888                )
1889                .settings(app, RouteSettingsRef::Settings(settings.clone()));
1890                Some(route.erase())
1891            })
1892        });
1893    }
1894
1895    #[test]
1896    fn test_edge_swipe_then_drop_back_at_starting_point_works() {
1897        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1898            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1899                numbered_pages(tester);
1900
1901                navigator(tester).push_named(&mut tester.cell.borrow_mut(), "/next", None);
1902
1903                tester.pump();
1904                tester.pump_by(Duration::from_secs(1));
1905
1906                assert_eq!(count_onstage(tester, "Page 1"), 0);
1907                assert!(onstage(tester, "Page 2"));
1908
1909                let mut gesture = TestPointer::touch(1);
1910                tester.down(&mut gesture, Offset::new(5.0, 200.0));
1911                let to = gesture.position + Offset::new(300.0, 0.0);
1912                tester.move_to(&mut gesture, to, true);
1913                tester.pump();
1914                // Bring it exactly back such that there's nothing to animate when releasing.
1915                let to = gesture.position + Offset::new(-300.0, 0.0);
1916                tester.move_to(&mut gesture, to, true);
1917                tester.up(&gesture);
1918                tester.pump();
1919
1920                assert_eq!(count_onstage(tester, "Page 1"), 0);
1921                assert!(onstage(tester, "Page 2"));
1922            });
1923        }
1924    }
1925
1926    #[test]
1927    fn test_edge_swipe_then_drop_back_at_ending_point_works() {
1928        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1929            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1930                numbered_pages(tester);
1931
1932                navigator(tester).push_named(&mut tester.cell.borrow_mut(), "/next", None);
1933
1934                tester.pump();
1935                tester.pump_by(Duration::from_secs(1));
1936
1937                assert_eq!(count_onstage(tester, "Page 1"), 0);
1938                assert!(onstage(tester, "Page 2"));
1939
1940                let mut gesture = TestPointer::touch(1);
1941                tester.down(&mut gesture, Offset::new(5.0, 200.0));
1942                // The width of the page.
1943                let to = gesture.position + Offset::new(800.0, 0.0);
1944                tester.move_to(&mut gesture, to, true);
1945                tester.up(&gesture);
1946                tester.pump();
1947
1948                assert!(onstage(tester, "Page 1"));
1949                assert_eq!(count_onstage(tester, "Page 2"), 0);
1950            });
1951        }
1952    }
1953
1954    /// Dart's `tester.getTopLeft(find.ancestor(of: find.text(text), matching: find.byType(Scaffold)))`.
1955    fn scaffold_top_left(tester: &WidgetTester, text: &str) -> Offset {
1956        let scaffold = tester.ancestor_of_type::<Scaffold>(the_text(tester, text));
1957        tester.get_rect(scaffold).top_left()
1958    }
1959
1960    /// Dart's `tester.getTopLeft(find.byKey(key))`.
1961    fn key_top_left(tester: &WidgetTester, key: &GlobalKey) -> Offset {
1962        let render = tester.render_object(key).as_box().expect("a render box");
1963        render.local_to_global(&tester.cell.borrow(), Offset::ZERO, None)
1964    }
1965
1966    fn route_scaffold(app: &mut App) -> RouteRef {
1967        let route = MaterialPageRoute::new(
1968            app,
1969            Rc::new(|_app, _context| {
1970                Scaffold::new()
1971                    .body(Center::new().child(Text::new("route")))
1972                    .into_widget()
1973            }),
1974        );
1975        route.into_erased()
1976    }
1977
1978    #[test]
1979    fn back_swipe_dismiss_interrupted_by_route_push() {
1980        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1981            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1982                // Regression test for https://github.com/flutter/flutter/issues/28728
1983                let scaffold_key = GlobalKey::new();
1984                let home_key = scaffold_key.clone();
1985                pump_app(tester, ThemeData::new, move |app| {
1986                    let push_key = home_key.clone();
1987                    app.home(
1988                        Scaffold::new()
1989                            .key(home_key.into())
1990                            .body(Center::new().child(ElevatedButton::new(
1991                                Some(Listener::new(move |app| {
1992                                    let context = push_key.current_context(app).expect("mounted");
1993                                    let route = route_scaffold(app);
1994                                    Navigator::push(app, context, route.clone());
1995                                })),
1996                                Some(Text::new("push")),
1997                            ))),
1998                    )
1999                });
2000
2001                // Check the basic iOS back-swipe dismiss transition. Dragging the pushed
2002                // route halfway across the screen will trigger the iOS dismiss animation.
2003
2004                tester.tap(find::text("push"));
2005                tester.pump_and_settle();
2006                assert_eq!(count_onstage(tester, "route"), 1);
2007                assert_eq!(count_onstage(tester, "push"), 0);
2008
2009                let mut gesture = TestPointer::touch(1);
2010                tester.down(&mut gesture, Offset::new(5.0, 300.0));
2011                let to = gesture.position + Offset::new(400.0, 0.0);
2012                tester.move_to(&mut gesture, to, true);
2013                tester.up(&gesture);
2014                tester.pump();
2015                // The 'route' route has been dragged to the right, halfway across the screen.
2016                assert_eq!(scaffold_top_left(tester, "route"), Offset::new(400.0, 0.0));
2017                // The 'push' route is sliding in from the left.
2018                assert!(scaffold_top_left(tester, "push").dx() < 0.0);
2019                tester.pump_and_settle();
2020                assert_eq!(count_onstage(tester, "push"), 1);
2021                assert_eq!(scaffold_top_left(tester, "push"), Offset::ZERO);
2022                assert_eq!(count_onstage(tester, "route"), 0);
2023
2024                // Run the dismiss animation 60%, which exposes the route "push" button,
2025                // and then press the button. A drag dropped animation is 400ms when dropped
2026                // exactly halfway. It follows a curve that is very steep initially.
2027
2028                tester.tap(find::text("push"));
2029                tester.pump_and_settle();
2030                assert_eq!(count_onstage(tester, "route"), 1);
2031                assert_eq!(count_onstage(tester, "push"), 0);
2032
2033                let mut gesture = TestPointer::touch(2);
2034                tester.down(&mut gesture, Offset::new(5.0, 300.0));
2035                // Drag halfway.
2036                let to = gesture.position + Offset::new(400.0, 0.0);
2037                tester.move_to(&mut gesture, to, true);
2038                tester.up(&gesture);
2039                // Trigger the dropped snapping animation.
2040                tester.pump();
2041                assert_eq!(scaffold_top_left(tester, "route"), Offset::new(400.0, 0.0));
2042                // Let the dismissing snapping animation go 60%.
2043                tester.pump_by(Duration::from_millis(240));
2044                let dx = scaffold_top_left(tester, "route").dx();
2045                assert!((dx - 794.0).abs() <= 1.0, "{dx}");
2046
2047                // Use the navigator to push a route instead of tapping the 'push' button.
2048                // The topmost route (the one that's animating away), ignores input while
2049                // the pop is underway because route.navigator.userGestureInProgress.
2050                {
2051                    let mut app = tester.cell.borrow_mut();
2052                    let context = scaffold_key.current_context(&app).expect("mounted");
2053                    let route = route_scaffold(&mut app);
2054                    Navigator::push(&mut app, context, route.clone());
2055                }
2056
2057                tester.pump_and_settle();
2058                assert_eq!(count_onstage(tester, "route"), 1);
2059                assert_eq!(count_onstage(tester, "push"), 0);
2060            });
2061        }
2062    }
2063
2064    /// The home scaffold and the page scaffold of the back-swipe input cases, each over a
2065    /// `GestureDetector` that counts its taps; answers the two counts.
2066    fn tap_counting_pages(
2067        tester: &mut WidgetTester,
2068        home_scaffold_key: &GlobalKey,
2069    ) -> (Rc<Cell<u32>>, Rc<Cell<u32>>) {
2070        let home_tap_count: Rc<Cell<u32>> = Rc::default();
2071        let page_tap_count: Rc<Cell<u32>> = Rc::default();
2072        let home_key = home_scaffold_key.clone();
2073        let home_taps = Rc::clone(&home_tap_count);
2074        pump_app(tester, ThemeData::new, move |app| {
2075            app.home(
2076                Scaffold::new()
2077                    .key(home_key.into())
2078                    .body(GestureDetector::new().on_tap(Listener::new(move |_app| {
2079                        home_taps.set(home_taps.get() + 1);
2080                    }))),
2081            )
2082        });
2083        (home_tap_count, page_tap_count)
2084    }
2085
2086    fn push_tap_counting_page(
2087        tester: &WidgetTester,
2088        home_scaffold_key: &GlobalKey,
2089        page_scaffold_key: &GlobalKey,
2090        page_tap_count: &Rc<Cell<u32>>,
2091    ) {
2092        let mut app = tester.cell.borrow_mut();
2093        let context = home_scaffold_key.current_context(&app).expect("mounted");
2094        let page_key = page_scaffold_key.clone();
2095        let page_taps = Rc::clone(page_tap_count);
2096        let route = MaterialPageRoute::new(
2097            &mut app,
2098            Rc::new(move |_app, _context| {
2099                let page_taps = Rc::clone(&page_taps);
2100                Scaffold::new()
2101                    .key(page_key.clone().into())
2102                    .app_bar(PreferredSizeWidgetRef::new(
2103                        AppBar::new().title(Text::new("Page")),
2104                    ))
2105                    .body(Padding::new(EdgeInsetsGeometry::all(16.0)).child(
2106                        GestureDetector::new().on_tap(Listener::new(move |_app| {
2107                            page_taps.set(page_taps.get() + 1);
2108                        })),
2109                    ))
2110                    .into_widget()
2111            }),
2112        );
2113        Navigator::push(&mut app, context, route.erase());
2114    }
2115
2116    fn tap_key(tester: &mut WidgetTester, key: &GlobalKey) {
2117        let at = tester.get_center(key);
2118        tester.tap_at(at, 1);
2119    }
2120
2121    #[test]
2122    fn during_back_swipe_the_route_ignores_input() {
2123        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
2124            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2125                // Regression test for https://github.com/flutter/flutter/issues/39989
2126
2127                let home_scaffold_key = GlobalKey::new();
2128                let page_scaffold_key = GlobalKey::new();
2129                let (home_tap_count, page_tap_count) =
2130                    tap_counting_pages(tester, &home_scaffold_key);
2131
2132                tap_key(tester, &home_scaffold_key);
2133                assert_eq!(home_tap_count.get(), 1);
2134                assert_eq!(page_tap_count.get(), 0);
2135
2136                push_tap_counting_page(
2137                    tester,
2138                    &home_scaffold_key,
2139                    &page_scaffold_key,
2140                    &page_tap_count,
2141                );
2142
2143                tester.pump_and_settle();
2144                tap_key(tester, &page_scaffold_key);
2145                assert_eq!(home_tap_count.get(), 1);
2146                assert_eq!(page_tap_count.get(), 1);
2147
2148                // Start the basic iOS back-swipe dismiss transition. Drag the pushed
2149                // "page" route halfway across the screen. The underlying "home" will
2150                // start sliding in from the left.
2151
2152                let mut gesture = TestPointer::touch(2);
2153                tester.down(&mut gesture, Offset::new(5.0, 300.0));
2154                let to = gesture.position + Offset::new(400.0, 0.0);
2155                tester.move_to(&mut gesture, to, true);
2156                tester.pump();
2157                assert_eq!(
2158                    key_top_left(tester, &page_scaffold_key),
2159                    Offset::new(400.0, 0.0)
2160                );
2161                assert!(key_top_left(tester, &home_scaffold_key).dx() < 0.0);
2162
2163                // Tapping on the "page" route doesn't trigger the GestureDetector because
2164                // it's being dragged.
2165                tap_key(tester, &page_scaffold_key);
2166                assert_eq!(home_tap_count.get(), 1);
2167                assert_eq!(page_tap_count.get(), 1);
2168
2169                // Tapping the "page" route's back button doesn't do anything either.
2170                let back_button = find::by_type::<IconButton>()
2171                    .evaluate(tester)
2172                    .into_iter()
2173                    .find(|button| {
2174                        tester.widget(*button, |button: &IconButton| {
2175                            button.tooltip.as_deref() == Some("Back")
2176                        })
2177                    })
2178                    .expect("the back button");
2179                let at = tester.get_rect(back_button).center();
2180                tester.tap_at(at, 1);
2181                tester.pump_and_settle();
2182                assert_eq!(
2183                    key_top_left(tester, &page_scaffold_key),
2184                    Offset::new(400.0, 0.0)
2185                );
2186                assert!(key_top_left(tester, &home_scaffold_key).dx() < 0.0);
2187            });
2188        }
2189    }
2190
2191    #[test]
2192    fn after_a_pop_caused_by_a_back_swipe_input_reaches_the_exposed_route() {
2193        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
2194            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2195                // Regression test for https://github.com/flutter/flutter/issues/41024
2196
2197                let home_scaffold_key = GlobalKey::new();
2198                let page_scaffold_key = GlobalKey::new();
2199                let (home_tap_count, page_tap_count) =
2200                    tap_counting_pages(tester, &home_scaffold_key);
2201
2202                tap_key(tester, &home_scaffold_key);
2203                assert_eq!(home_tap_count.get(), 1);
2204                assert_eq!(page_tap_count.get(), 0);
2205
2206                let notifier = {
2207                    let mut app = tester.cell.borrow_mut();
2208                    let context = home_scaffold_key.current_context(&app).expect("mounted");
2209                    Navigator::of(&mut app, context, false).user_gesture_in_progress_notifier(&app)
2210                };
2211                assert!(!*tester.cell.borrow().get(notifier).value());
2212
2213                push_tap_counting_page(
2214                    tester,
2215                    &home_scaffold_key,
2216                    &page_scaffold_key,
2217                    &page_tap_count,
2218                );
2219
2220                tester.pump_and_settle();
2221                tap_key(tester, &page_scaffold_key);
2222                assert_eq!(home_tap_count.get(), 1);
2223                assert_eq!(page_tap_count.get(), 1);
2224
2225                // Trigger the basic iOS back-swipe dismiss transition. Drag the pushed
2226                // "page" route more than halfway across the screen and then release it.
2227
2228                let mut gesture = TestPointer::touch(2);
2229                tester.down(&mut gesture, Offset::new(5.0, 300.0));
2230                let to = gesture.position + Offset::new(500.0, 0.0);
2231                tester.move_to(&mut gesture, to, true);
2232                tester.pump();
2233                assert_eq!(
2234                    key_top_left(tester, &page_scaffold_key),
2235                    Offset::new(500.0, 0.0)
2236                );
2237                assert!(key_top_left(tester, &home_scaffold_key).dx() < 0.0);
2238                assert!(*tester.cell.borrow().get(notifier).value());
2239                tester.up(&gesture);
2240                tester.pump_and_settle();
2241                assert!(!*tester.cell.borrow().get(notifier).value());
2242                assert!(
2243                    page_scaffold_key
2244                        .current_context(&tester.cell.borrow_mut())
2245                        .is_none()
2246                );
2247
2248                // The back-swipe dismiss pop transition has finished and input on the
2249                // home page still works.
2250                tap_key(tester, &home_scaffold_key);
2251                assert_eq!(home_tap_count.get(), 2);
2252                assert_eq!(page_tap_count.get(), 1);
2253            });
2254        }
2255    }
2256
2257    #[test]
2258    fn material_page_does_not_lose_its_state_when_transitioning_out() {
2259        test_widgets(|tester| {
2260            let navigator_key = GlobalKey::new();
2261            // Dart's `KeepsStateTestWidget`.
2262            let subpage: Rc<RefCell<Option<String>>> =
2263                Rc::new(RefCell::new(Some("subpage".to_string())));
2264            let keeps_state = StatefulBuilder::new({
2265                let navigator_key = navigator_key.clone();
2266                move |_app, _context, set_state| {
2267                    let mut pages: Vec<PageRef> =
2268                        vec![Rc::new(MaterialPage::new(Text::new("home")))];
2269                    if let Some(subpage) = subpage.borrow().clone() {
2270                        pages.push(Rc::new(MaterialPage::new(Text::new(subpage))));
2271                    }
2272                    let subpage = Rc::clone(&subpage);
2273                    MaterialApp::new()
2274                        .home(
2275                            Navigator::new()
2276                                .key(navigator_key.clone().into())
2277                                .pages(pages)
2278                                .on_pop_page(move |app, route, result| {
2279                                    if !route.did_pop(app, result) {
2280                                        return false;
2281                                    }
2282                                    let subpage = Rc::clone(&subpage);
2283                                    set_state(app, &mut move |_app| {
2284                                        *subpage.borrow_mut() = None;
2285                                    });
2286                                    true
2287                                }),
2288                        )
2289                        .into_widget()
2290                }
2291            });
2292            tester.pump_widget(keeps_state.into_widget());
2293            assert_eq!(count_onstage(tester, "subpage"), 1);
2294            assert_eq!(count_onstage(tester, "home"), 0);
2295
2296            {
2297                let mut app = tester.cell.borrow_mut();
2298                navigator_key
2299                    .current_state::<NavigatorState>(&app)
2300                    .expect("a navigator")
2301                    .pop(&mut app, None);
2302            }
2303            tester.pump();
2304
2305            assert_eq!(count_onstage(tester, "subpage"), 1);
2306            assert_eq!(count_onstage(tester, "home"), 1);
2307        });
2308    }
2309
2310    #[test]
2311    fn setting_material_page_route_request_focus_to_false_does_not_request_focus_on_the_page() {
2312        test_widgets(|tester| {
2313            let saved_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
2314            const PAGE_TWO_TEXT: &str = "Page Two";
2315            let saved = Rc::clone(&saved_context);
2316            pump_app(tester, ThemeData::new, move |app| {
2317                app.home(waft_widgets::Builder::new(move |_app, context| {
2318                    saved.set(Some(context));
2319                    Container::new().into_widget()
2320                }))
2321            });
2322            tester.pump();
2323
2324            // Check page two is not on the screen.
2325            assert_eq!(count_onstage(tester, PAGE_TWO_TEXT), 0);
2326
2327            // Navigate to page two with text.
2328            let navigator = Navigator::of(
2329                &mut tester.cell.borrow_mut(),
2330                saved_context.get().expect("built"),
2331                false,
2332            );
2333            push(tester, |app| {
2334                (MaterialPageRoute::new(
2335                    app,
2336                    Rc::new(|_app, _context| Text::new(PAGE_TWO_TEXT).into_widget()),
2337                ))
2338                .into_erased()
2339            });
2340            tester.pump();
2341            tester.pump_by(Duration::from_millis(100));
2342
2343            // The page two is showing and the text widget has focus.
2344            let text_on_page_two = the_text(tester, PAGE_TWO_TEXT);
2345            {
2346                let mut app = tester.cell.borrow_mut();
2347                let focus_scope_node = FocusScope::of(&mut app, text_on_page_two, false);
2348                assert!(focus_scope_node.has_focus(&mut app));
2349            }
2350
2351            // Navigate back to page one.
2352            navigator.pop(&mut tester.cell.borrow_mut(), None);
2353            tester.pump();
2354            tester.pump_by(Duration::from_millis(100));
2355
2356            // Navigate to page two again with requestFocus set to false.
2357            push(tester, |app| {
2358                (MaterialPageRoute::new(
2359                    app,
2360                    Rc::new(|_app, _context| Text::new(PAGE_TWO_TEXT).into_widget()),
2361                )
2362                .request_focus(app, false))
2363                .into_erased()
2364            });
2365            tester.pump();
2366            tester.pump_by(Duration::from_millis(100));
2367
2368            // The page two is showing and the text widget is not focused.
2369            let text_on_page_two = the_text(tester, PAGE_TWO_TEXT);
2370            let mut app = tester.cell.borrow_mut();
2371            let focus_scope_node = FocusScope::of(&mut app, text_on_page_two, false);
2372            assert!(!focus_scope_node.has_focus(&mut app));
2373        });
2374    }
2375
2376    /// The `SnapshotWidget` nearest above `text`: Dart's
2377    /// `find.ancestor(of: of, matching: find.byType(SnapshotWidget)).first`.
2378    fn snapshot_above(tester: &WidgetTester, text: &str) -> AnyElement {
2379        tester.ancestor_of_type::<SnapshotWidget>(the_text(tester, text))
2380    }
2381
2382    /// Whether a `SnapshotWidget` above `text` is set to take a snapshot. Dart's
2383    /// `isSnapshotted` reads that from the two layers a snapshot leaves in the layer tree around
2384    /// the page; Waft's `SnapshotWidget` paints the child live (`OffsetLayer.toImageSync` is
2385    /// deferred), so the case reads the controllers, as page_transitions_theme's cases do.
2386    fn is_snapshotted(tester: &WidgetTester, text: &str) -> bool {
2387        let ancestors = tester.ancestors(the_text(tester, text));
2388        let app = tester.cell.borrow();
2389        ancestors.into_iter().any(|ancestor| {
2390            waft_widgets::downcast_widget::<SnapshotWidget>(&**ancestor.widget(&app))
2391                .is_some_and(|snapshot| snapshot.controller.allow_snapshotting(&app))
2392        })
2393    }
2394
2395    fn count_layers<T: 'static>(tester: &WidgetTester, layers: &[AnyLayer]) -> usize {
2396        let app = tester.cell.borrow();
2397        layers
2398            .iter()
2399            .filter(|layer| app.handle::<T>(layer.id()).is_some())
2400            .count()
2401    }
2402
2403    fn is_transitioning_without_snapshotting(tester: &WidgetTester, text: &str) -> bool {
2404        // When snapshotting is off, the OpacityLayer and TransformLayer will be
2405        // applied directly.
2406        let layers = tester.layer_list_of(snapshot_above(tester, text));
2407        !is_snapshotted(tester, text)
2408            && count_layers::<OpacityLayer>(tester, &layers) == 1
2409            && count_layers::<TransformLayer>(tester, &layers) == 1
2410    }
2411
2412    #[test]
2413    fn test_page_transition_zoom_page_transition_with_rasterization_disables_snapshotting_for_enter_route()
2414     {
2415        test_widgets(|tester| {
2416            pump_app(tester, ThemeData::new, |app| {
2417                app.routes([
2418                    ("/1".to_string(), material_text("Page 1")),
2419                    ("/2".to_string(), material_text("Page 2")),
2420                ])
2421                .initial_route("/1")
2422                .builder(|app, context, child| {
2423                    let theme_data = Theme::of(app, context);
2424                    let mut builders = theme_data.page_transitions_theme.builders().clone();
2425                    builders.insert(
2426                        TargetPlatform::Android,
2427                        PageTransitionsBuilderRef::new(
2428                            ZoomPageTransitionsBuilder::new().allow_enter_route_snapshotting(false),
2429                        ),
2430                    );
2431                    let child = child.cloned().expect("the navigator");
2432                    Theme::new(
2433                        theme_data
2434                            .copy_with()
2435                            .page_transitions_theme(
2436                                PageTransitionsTheme::new().with_builders(builders),
2437                            )
2438                            .build(),
2439                        waft_widgets::Builder::new(move |_app, _context| child.clone()),
2440                    )
2441                    .into_widget()
2442                })
2443            });
2444
2445            // Page 1 on top.
2446            assert!(!is_snapshotted(tester, "Page 1"));
2447
2448            // Transitioning from page 1 to page 2.
2449            navigator(tester).push_named(&mut tester.cell.borrow_mut(), "/2", None);
2450            tester.pump();
2451            tester.pump_by(Duration::from_millis(50));
2452
2453            assert!(is_snapshotted(tester, "Page 1"));
2454            assert!(is_transitioning_without_snapshotting(tester, "Page 2"));
2455
2456            // Page 2 on top.
2457            tester.pump_and_settle();
2458            assert!(!is_snapshotted(tester, "Page 2"));
2459
2460            // Transitioning back from page 2 to page 1.
2461            pop(tester);
2462            tester.pump();
2463            tester.pump_by(Duration::from_millis(50));
2464
2465            assert!(is_transitioning_without_snapshotting(tester, "Page 1"));
2466            assert!(is_snapshotted(tester, "Page 2"));
2467
2468            // Page 1 on top.
2469            tester.pump_and_settle();
2470            assert!(!is_snapshotted(tester, "Page 1"));
2471        });
2472    }
2473}