Skip to main content

waft_material/
predictive_back_page_transitions_builder.rs

1//! Port of material_ui's `predictive_back_page_transitions_builder.dart`.
2//!
3//! The gesture reaches these transitions through the binding's back-gesture dispatch
4//! (`WidgetsBinding::handle_start_back_gesture` and its siblings); until a host reports the
5//! system's back gesture there, the Android builders show their fallback transitions.
6
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9use std::time::Duration;
10
11use waft_animation::{
12    Animatable, Animation, AnimationRef, AnyAnimation, CurvedAnimation, Curves, Drive, Interval,
13    ProxyAnimation, ReverseAnimation, TweenSequence, TweenSequenceItem, ValueConstantTween,
14    ValueTween, k_always_dismissed_animation,
15};
16use waft_embedder::Radius;
17use waft_embedder::{Color, Offset, Size};
18use waft_foundation::{App, Handle, Listenable, OptionRetained, Ref};
19use waft_painting::BorderRadius;
20use waft_services::{PredictiveBackEvent, SwipeEdge};
21use waft_widgets::{
22    AnimatedBuilder, AnimatedOpacity, AnyPageRoute, BuildContext, ClipRRect, IntoWidget,
23    MediaQuery, Opacity, PageTransitionsBuilder, State, StateData, StatefulWidget, Transform,
24    WidgetRef, WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef,
25};
26
27use crate::page_transitions_theme::{
28    FadeForwardsPageTransitionsBuilder, ZoomPageTransitionsBuilder,
29};
30
31/// Used by `PageTransitionsTheme` to define a `MaterialPageRoute` page transition animation
32/// that looks like the default page transition used on Android U and above when using
33/// predictive back.
34///
35/// Predictive back is only supported on Android U and above, and if this
36/// [`PageTransitionsBuilder`] is used by any other platform, it will fall back to
37/// [`FadeForwardsPageTransitionsBuilder`].
38///
39/// When used on Android U and above, animates along with the back gesture to reveal the
40/// destination route. Can be canceled by dragging back towards the edge of the screen.
41///
42/// See also:
43///
44///  * [`PredictiveBackFullscreenPageTransitionsBuilder`], which is another variant of
45///    Android's predictive back page transition.
46///  * [`FadeForwardsPageTransitionsBuilder`], which defines the default page transition that's
47///    similar to the one provided in Android 16.
48///  * [`ZoomPageTransitionsBuilder`], which defines the default page transition that's similar
49///    to the one provided in Android 10.
50///  * `OpenUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
51///    the one provided by Android 9.
52///  * `FadeUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
53///    the one provided by Android 8.
54///  * `CupertinoPageTransitionsBuilder`, which defines a horizontal page transition that
55///    matches native iOS page transitions.
56///  * `PageRoute::allow_snapshotting`, which enables or disables snapshotting on a per route
57///    basis similar to the `allow_snapshotting` parameter.
58///  * <https://developer.android.com/design/ui/mobile/guides/patterns/predictive-back#shared-element-transition>,
59///    which is the Android spec for this page transition, called the Shared Element page
60///    transition.
61#[derive(Clone, Copy, Debug)]
62pub struct PredictiveBackPageTransitionsBuilder {
63    /// Whether page transitions will prefer to animate a snapshot of the entering and exiting
64    /// routes.
65    ///
66    /// If not specified, defaults to true.
67    ///
68    /// When this value is true, page transitions will snapshot the entering and exiting
69    /// routes. These snapshots are then animated in place of the underlying widgets to improve
70    /// performance of the transition.
71    ///
72    /// Generally this means that animations that occur on the entering/exiting route while the
73    /// route animation plays may appear frozen - unless they are a hero animation or something
74    /// that is drawn in a separate overlay.
75    pub allow_snapshotting: bool,
76
77    /// The color of the scrim (background) when the predictive back transition is not
78    /// supported.
79    ///
80    /// If not provided, the background color of a default
81    /// [`FadeForwardsPageTransitionsBuilder`] will be used.
82    pub fallback_color: Option<Color>,
83}
84
85impl Default for PredictiveBackPageTransitionsBuilder {
86    fn default() -> PredictiveBackPageTransitionsBuilder {
87        PredictiveBackPageTransitionsBuilder::new()
88    }
89}
90
91impl PredictiveBackPageTransitionsBuilder {
92    /// Creates an instance of a [`PageTransitionsBuilder`] that matches Android U's predictive
93    /// back transition.
94    pub const fn new() -> PredictiveBackPageTransitionsBuilder {
95        PredictiveBackPageTransitionsBuilder {
96            allow_snapshotting: true,
97            fallback_color: None,
98        }
99    }
100
101    /// Dart `PredictiveBackPageTransitionsBuilder(fallbackColor:)`.
102    pub const fn fallback_color(
103        mut self,
104        fallback_color: Color,
105    ) -> PredictiveBackPageTransitionsBuilder {
106        self.fallback_color = Some(fallback_color);
107        self
108    }
109
110    /// Dart `PredictiveBackPageTransitionsBuilder(allowSnapshotting:)`.
111    pub const fn allow_snapshotting(
112        mut self,
113        allow_snapshotting: bool,
114    ) -> PredictiveBackPageTransitionsBuilder {
115        self.allow_snapshotting = allow_snapshotting;
116        self
117    }
118}
119
120impl PageTransitionsBuilder for PredictiveBackPageTransitionsBuilder {
121    fn transition_duration(&self) -> Duration {
122        Duration::from_millis(FadeForwardsPageTransitionsBuilder::K_TRANSITION_MILLISECONDS)
123    }
124
125    fn build_transitions(
126        &self,
127        _app: &mut App,
128        route: AnyPageRoute,
129        _context: BuildContext,
130        animation: AnimationRef<f64>,
131        secondary_animation: AnimationRef<f64>,
132        child: WidgetRef,
133    ) -> WidgetRef {
134        let this = *self;
135        PredictiveBackGestureDetector {
136            route,
137            builder: Rc::new(
138                move |app, context, phase, start_back_event, current_back_event| {
139                    // Only do a predictive back transition when the user is performing a pop
140                    // gesture. Otherwise, for things like button presses or other programmatic
141                    // navigation, fall back to FadeForwardsPageTransitionsBuilder.
142                    if route.as_modal_route().pop_gesture_in_progress(app) {
143                        return PredictiveBackSharedElementPageTransition {
144                            is_delegated_transition: true,
145                            animation: animation.clone(),
146                            phase,
147                            secondary_animation: secondary_animation.clone(),
148                            start_back_event,
149                            current_back_event,
150                            child: child.clone(),
151                        }
152                        .into_widget();
153                    }
154
155                    let mut fallback = FadeForwardsPageTransitionsBuilder::new()
156                        .allow_snapshotting(this.allow_snapshotting);
157                    fallback.background_color = this.fallback_color;
158                    fallback.build_transitions(
159                        app,
160                        route,
161                        context,
162                        animation.clone(),
163                        secondary_animation.clone(),
164                        child.clone(),
165                    )
166                },
167            ),
168        }
169        .into_widget()
170    }
171}
172
173/// Used by `PageTransitionsTheme` to define a `MaterialPageRoute` page transition animation
174/// that looks like Android's Full Screen page transition.
175///
176/// Predictive back is only supported on Android U and above, and if this
177/// [`PageTransitionsBuilder`] is used by any other platform, it will fall back to
178/// [`ZoomPageTransitionsBuilder`].
179///
180/// When used on Android U and above, animates along with the back gesture to reveal the
181/// destination route. Can be canceled by dragging back towards the edge of the screen.
182///
183/// See also:
184///
185///  * [`PredictiveBackPageTransitionsBuilder`], which is the default Android predictive back
186///    page transition.
187///  * [`FadeForwardsPageTransitionsBuilder`], which defines the default page transition that's
188///    similar to the one provided in Android 16.
189///  * [`ZoomPageTransitionsBuilder`], which defines the default page transition that's similar
190///    to the one provided in Android 10.
191///  * `OpenUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
192///    the one provided by Android 9.
193///  * `FadeUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
194///    the one provided by Android 8.
195///  * `CupertinoPageTransitionsBuilder`, which defines a horizontal page transition that
196///    matches native iOS page transitions.
197///  * <https://developer.android.com/design/ui/mobile/guides/patterns/predictive-back#full-screen-surfaces>,
198///    which is the native Android docs for this page transition.
199#[derive(Clone, Copy, Debug, Default)]
200pub struct PredictiveBackFullscreenPageTransitionsBuilder {
201    /// The color of the scrim (background) when the predictive back transition is not
202    /// supported.
203    ///
204    /// If not provided, the background color of a default [`ZoomPageTransitionsBuilder`] will
205    /// be used.
206    pub fallback_color: Option<Color>,
207}
208
209impl PredictiveBackFullscreenPageTransitionsBuilder {
210    /// Creates an instance of a [`PageTransitionsBuilder`] that matches Android U's full screen
211    /// predictive back transition.
212    pub const fn new() -> PredictiveBackFullscreenPageTransitionsBuilder {
213        PredictiveBackFullscreenPageTransitionsBuilder {
214            fallback_color: None,
215        }
216    }
217
218    /// Dart `PredictiveBackFullscreenPageTransitionsBuilder(fallbackColor:)`.
219    pub const fn fallback_color(
220        mut self,
221        fallback_color: Color,
222    ) -> PredictiveBackFullscreenPageTransitionsBuilder {
223        self.fallback_color = Some(fallback_color);
224        self
225    }
226}
227
228impl PageTransitionsBuilder for PredictiveBackFullscreenPageTransitionsBuilder {
229    fn build_transitions(
230        &self,
231        _app: &mut App,
232        route: AnyPageRoute,
233        _context: BuildContext,
234        animation: AnimationRef<f64>,
235        secondary_animation: AnimationRef<f64>,
236        child: WidgetRef,
237    ) -> WidgetRef {
238        let fallback_color = self.fallback_color;
239        PredictiveBackGestureDetector {
240            route,
241            builder: Rc::new(
242                move |app, context, phase, _start_back_event, _current_back_event| {
243                    // Only do a predictive back transition when the user is performing a pop
244                    // gesture. Otherwise, for things like button presses or other programmatic
245                    // navigation, fall back to ZoomPageTransitionsBuilder.
246                    if route.as_modal_route().pop_gesture_in_progress(app) {
247                        return PredictiveBackFullscreenPageTransition {
248                            animation: animation.clone(),
249                            secondary_animation: secondary_animation.clone(),
250                            get_is_current: Rc::new(move |app| route.as_route().is_current(app)),
251                            phase,
252                            child: child.clone(),
253                        }
254                        .into_widget();
255                    }
256
257                    let mut fallback = ZoomPageTransitionsBuilder::new();
258                    fallback.background_color = fallback_color;
259                    fallback.build_transitions(
260                        app,
261                        route,
262                        context,
263                        animation.clone(),
264                        secondary_animation.clone(),
265                        child.clone(),
266                    )
267                },
268            ),
269        }
270        .into_widget()
271    }
272}
273
274type PredictiveBackGestureDetectorWidgetBuilder = Rc<
275    dyn Fn(
276        &mut App,
277        BuildContext,
278        PredictiveBackPhase,
279        Option<PredictiveBackEvent>,
280        Option<PredictiveBackEvent>,
281    ) -> WidgetRef,
282>;
283
284/// The phases of a predictive back gesture.
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
286pub(crate) enum PredictiveBackPhase {
287    /// There is no active predictive back gesture in progress.
288    Idle,
289
290    /// The user pointer has contacted the screen.
291    Start,
292
293    /// The user pointer has moved.
294    Update,
295
296    /// The user pointer has released in a position in which Android has determined that the
297    /// back gesture is successful and the current route should be popped.
298    Commit,
299
300    /// The user pointer has released in a position in which Android has determined that the
301    /// back gesture should be canceled and the original route should be shown.
302    Cancel,
303}
304
305pub(crate) struct PredictiveBackGestureDetector {
306    builder: PredictiveBackGestureDetectorWidgetBuilder,
307    route: AnyPageRoute,
308}
309
310impl Debug for PredictiveBackGestureDetector {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.debug_struct("_PredictiveBackGestureDetector")
313            .field("route", &self.route)
314            .finish_non_exhaustive()
315    }
316}
317
318impl StatefulWidget for PredictiveBackGestureDetector {
319    type State = PredictiveBackGestureDetectorState;
320
321    fn create_state(&self) -> PredictiveBackGestureDetectorState {
322        PredictiveBackGestureDetectorState {
323            state: StateData::new(),
324            phase: PredictiveBackPhase::Idle,
325            start_back_event: None,
326            current_back_event: None,
327            observer: None,
328        }
329    }
330}
331
332/// Dart's `_PredictiveBackGestureDetectorState`. `observer` is the registration of this state
333/// with the binding, kept to remove the same one again.
334pub(crate) struct PredictiveBackGestureDetectorState {
335    state: StateData<PredictiveBackGestureDetector>,
336    phase: PredictiveBackPhase,
337    start_back_event: Option<PredictiveBackEvent>,
338    current_back_event: Option<PredictiveBackEvent>,
339    observer: Option<WidgetsBindingObserverRef>,
340}
341
342impl PredictiveBackGestureDetectorState {
343    /// True when the predictive back gesture is enabled.
344    fn is_enabled(self: Handle<Self>, app: &mut App) -> bool {
345        let route = self.widget(app).route;
346        route.as_route().is_current(app)
347            && route
348                .as_modal_route()
349                .as_transition_route()
350                .pop_gesture_enabled(app)
351    }
352
353    pub(crate) fn phase(self: Handle<Self>, app: &App) -> PredictiveBackPhase {
354        app.get(self).phase
355    }
356
357    fn set_phase(self: Handle<Self>, app: &mut App, phase: PredictiveBackPhase) {
358        if app.get(self).phase != phase && self.mounted(app) {
359            self.set_state(app, |state| state.phase = phase);
360        }
361    }
362
363    /// The back event when the gesture first started.
364    pub(crate) fn start_back_event(self: Handle<Self>, app: &App) -> Option<PredictiveBackEvent> {
365        app.get(self).start_back_event
366    }
367
368    fn set_start_back_event(
369        self: Handle<Self>,
370        app: &mut App,
371        start_back_event: Option<PredictiveBackEvent>,
372    ) {
373        if app.get(self).start_back_event != start_back_event && self.mounted(app) {
374            self.set_state(app, |state| state.start_back_event = start_back_event);
375        }
376    }
377
378    /// The most recent back event during the gesture.
379    pub(crate) fn current_back_event(self: Handle<Self>, app: &App) -> Option<PredictiveBackEvent> {
380        app.get(self).current_back_event
381    }
382
383    fn set_current_back_event(
384        self: Handle<Self>,
385        app: &mut App,
386        current_back_event: Option<PredictiveBackEvent>,
387    ) {
388        if app.get(self).current_back_event != current_back_event && self.mounted(app) {
389            self.set_state(app, |state| state.current_back_event = current_back_event);
390        }
391    }
392}
393
394impl WidgetsBindingObserverObject for PredictiveBackGestureDetectorState {
395    fn handle_start_back_gesture(
396        self: Handle<Self>,
397        app: &mut App,
398        back_event: PredictiveBackEvent,
399    ) -> bool {
400        self.set_phase(app, PredictiveBackPhase::Start);
401        let gesture_in_progress = !back_event.is_button_event() && self.is_enabled(app);
402        if !gesture_in_progress {
403            return false;
404        }
405
406        let route = self.widget(app).route;
407        route
408            .as_modal_route()
409            .as_transition_route()
410            .handle_start_back_gesture(app, 1.0 - back_event.progress);
411        self.set_current_back_event(app, Some(back_event));
412        self.set_start_back_event(app, Some(back_event));
413        true
414    }
415
416    fn handle_update_back_gesture_progress(
417        self: Handle<Self>,
418        app: &mut App,
419        back_event: PredictiveBackEvent,
420    ) {
421        self.set_phase(app, PredictiveBackPhase::Update);
422
423        let route = self.widget(app).route;
424        route
425            .as_modal_route()
426            .as_transition_route()
427            .handle_update_back_gesture_progress(app, 1.0 - back_event.progress);
428        self.set_current_back_event(app, Some(back_event));
429    }
430
431    fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App) {
432        self.set_phase(app, PredictiveBackPhase::Cancel);
433
434        let route = self.widget(app).route;
435        route
436            .as_modal_route()
437            .as_transition_route()
438            .handle_cancel_back_gesture(app);
439        self.set_current_back_event(app, None);
440        self.set_start_back_event(app, None);
441    }
442
443    fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App) {
444        self.set_phase(app, PredictiveBackPhase::Commit);
445
446        let route = self.widget(app).route;
447        route
448            .as_modal_route()
449            .as_transition_route()
450            .handle_commit_back_gesture(app);
451        self.set_current_back_event(app, None);
452        self.set_start_back_event(app, None);
453    }
454}
455
456impl State for PredictiveBackGestureDetectorState {
457    type Widget = PredictiveBackGestureDetector;
458    waft_widgets::state_accessors!();
459
460    fn init_state(self: Handle<Self>, app: &mut App) {
461        let observer: WidgetsBindingObserverRef = Rc::new(self);
462        app.get_mut(self).observer = Some(Rc::clone(&observer));
463        WidgetsBinding::instance(app).add_observer(app, observer);
464    }
465
466    fn dispose(self: Handle<Self>, app: &mut App) {
467        if let Some(observer) = app.get_mut(self).observer.take() {
468            WidgetsBinding::instance(app).remove_observer(app, &observer);
469        }
470    }
471
472    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
473        let widget = self.widget(app);
474        let (route, builder) = (widget.route, Rc::clone(&widget.builder));
475        let effective_phase = if route.as_modal_route().pop_gesture_in_progress(app) {
476            self.phase(app)
477        } else {
478            PredictiveBackPhase::Idle
479        };
480        let start_back_event = self.start_back_event(app);
481        let current_back_event = self.current_back_event(app);
482        builder(
483            app,
484            context,
485            effective_phase,
486            start_back_event,
487            current_back_event,
488        )
489    }
490}
491
492/// Android's predictive back page shared element transition.
493///
494/// See also:
495///
496///  * <https://developer.android.com/design/ui/mobile/guides/patterns/predictive-back#shared-element-transition>,
497///    which is the Android spec for this transition.
498#[derive(Debug)]
499pub(crate) struct PredictiveBackSharedElementPageTransition {
500    is_delegated_transition: bool,
501    animation: AnimationRef<f64>,
502    secondary_animation: AnimationRef<f64>,
503    phase: PredictiveBackPhase,
504    start_back_event: Option<PredictiveBackEvent>,
505    current_back_event: Option<PredictiveBackEvent>,
506    child: WidgetRef,
507}
508
509impl StatefulWidget for PredictiveBackSharedElementPageTransition {
510    type State = PredictiveBackSharedElementPageTransitionState;
511
512    fn create_state(&self) -> PredictiveBackSharedElementPageTransitionState {
513        let _ = (
514            self.is_delegated_transition,
515            self.secondary_animation.clone(),
516        );
517        PredictiveBackSharedElementPageTransitionState {
518            state: StateData::new(),
519            commit_animation: None,
520            bounce_animation: None,
521            last_bounce_animation_value: 0.0,
522            animation: None,
523            curved_animation: None,
524            curved_animation_reversed: None,
525            position_animation: None,
526            last_drag: Offset::ZERO,
527        }
528    }
529}
530
531/// Dart's `_PredictiveBackSharedElementPageTransitionState`. The three proxies are Dart's field
532/// initialisers; they need the `App`, so `init_state` makes them before anything reads them.
533pub(crate) struct PredictiveBackSharedElementPageTransitionState {
534    state: StateData<PredictiveBackSharedElementPageTransition>,
535
536    // An animation that stays constant at zero before the commit, and after the commit goes
537    // from zero to one.
538    commit_animation: Option<Ref<ProxyAnimation>>,
539
540    // An animation that goes from zero to a maximum of one during a predictive back gesture,
541    // and then at commit, it goes from its current value to zero. Used for animations that
542    // follow the gesture and then animate back to their original value after commit.
543    bounce_animation: Option<Ref<ProxyAnimation>>,
544    last_bounce_animation_value: f64,
545
546    // An animation that proxies to widget.animation during the gesture and then to
547    // _commitAnimation after the commit. So, it goes from zero to a maximum of one before
548    // commit, and then after commit goes from zero to one again.
549    animation: Option<Ref<ProxyAnimation>>,
550
551    /// The same as widget.animation but with a curve applied.
552    curved_animation: Option<Ref<CurvedAnimation>>,
553
554    /// The reverse of `curved_animation`.
555    curved_animation_reversed: Option<Ref<CurvedAnimation>>,
556
557    position_animation: Option<AnimationRef<Offset>>,
558
559    last_drag: Offset,
560}
561
562impl PredictiveBackSharedElementPageTransitionState {
563    // Constants as per the motion specs
564    // https://developer.android.com/design/ui/mobile/guides/patterns/predictive-back#motion-specs
565    const K_MIN_SCALE: f64 = 0.90;
566    const K_DIVISION_FACTOR: f64 = 20.0;
567    const K_MARGIN: f64 = 8.0;
568    const K_Y_POSITION_FACTOR: f64 = 0.1;
569
570    // The duration of the commit transition.
571    //
572    // This is not the same as PredictiveBackPageTransitionsBuilder's duration, which is the
573    // duration of widget.animation, so an Interval is used.
574    //
575    // Eyeballed on a Pixel 9 running Android 16.
576    const K_COMMIT_MILLISECONDS: u64 = 400;
577
578    fn k_commit_interval() -> Interval {
579        Interval::new(
580            0.0,
581            PredictiveBackSharedElementPageTransitionState::K_COMMIT_MILLISECONDS as f64
582                / FadeForwardsPageTransitionsBuilder::K_TRANSITION_MILLISECONDS as f64,
583            Curves::ease_in_out_cubic_emphasized(),
584        )
585    }
586
587    // A fallback corner radius used when the display corner radii are unavailable (e.g., on
588    // Android API levels below 31, iOS, and other platforms). This is a best-guess value that
589    // looks reasonable on most devices.
590    // See https://github.com/flutter/flutter/issues/97349.
591    const K_DEVICE_BORDER_RADIUS: f64 = 32.0;
592
593    // Provides a smooth transition between the default radius and the _kDeviceBorderRadius,
594    // when the display corner radii are unavailable.
595    const BORDER_RADIUS_TWEEN: ValueTween<f64> = ValueTween::new(
596        0.0,
597        PredictiveBackSharedElementPageTransitionState::K_DEVICE_BORDER_RADIUS,
598    );
599
600    // The route fades out after commit.
601    const OPACITY_TWEEN: ValueTween<f64> = ValueTween::new(1.0, 0.0);
602
603    // The route shrinks during the gesture and animates back to normal after commit.
604    const SCALE_TWEEN: ValueTween<f64> = ValueTween::new(
605        1.0,
606        PredictiveBackSharedElementPageTransitionState::K_MIN_SCALE,
607    );
608
609    fn commit_animation(self: Handle<Self>, app: &App) -> Handle<ProxyAnimation> {
610        app.get(self)
611            .commit_animation
612            .handle()
613            .expect("created in init_state")
614    }
615
616    fn bounce_animation(self: Handle<Self>, app: &App) -> Handle<ProxyAnimation> {
617        app.get(self)
618            .bounce_animation
619            .handle()
620            .expect("created in init_state")
621    }
622
623    fn position_animation(self: Handle<Self>, app: &App) -> AnyAnimation<Offset> {
624        app.get(self)
625            .position_animation
626            .handle()
627            .expect("set in did_change_dependencies")
628    }
629
630    // This isn't done as an animation because it's based on the vertical drag amount, not the
631    // progression of the back gesture like widget.animation is.
632    fn get_y_shift_position(self: Handle<Self>, app: &App, screen_height: f64) -> f64 {
633        let widget = self.widget(app);
634        let start_touch_y = widget
635            .start_back_event
636            .and_then(|event| event.touch_offset)
637            .map_or(0.0, |offset| offset.dy());
638        let current_touch_y = widget
639            .current_back_event
640            .and_then(|event| event.touch_offset)
641            .map_or(0.0, |offset| offset.dy());
642
643        let y_shift_max = (screen_height
644            / PredictiveBackSharedElementPageTransitionState::K_DIVISION_FACTOR)
645            - PredictiveBackSharedElementPageTransitionState::K_MARGIN;
646
647        let raw_y_shift = current_touch_y - start_touch_y;
648        // This curve was eyeballed on a Pixel 9 running Android 16.
649        let eased_y_shift = Curves::ease_out()
650            .transform((raw_y_shift.abs() / screen_height).clamp(0.0, 1.0))
651            * dart_sign(raw_y_shift)
652            * y_shift_max;
653
654        eased_y_shift.clamp(-y_shift_max, y_shift_max)
655    }
656
657    fn update_animations(self: Handle<Self>, app: &mut App, screen_size: Size) {
658        let widget = self.widget(app);
659        let (phase, widget_animation, swipe_edge) = (
660            widget.phase,
661            widget.animation.clone(),
662            widget.current_back_event.map(|event| event.swipe_edge),
663        );
664        let state = app.get(self);
665        let curved_animation = state
666            .curved_animation
667            .clone()
668            .expect("set in did_change_dependencies");
669        let curved_animation_reversed = state
670            .curved_animation_reversed
671            .clone()
672            .expect("set in did_change_dependencies");
673        let last_bounce_animation_value = state.last_bounce_animation_value;
674        let last_drag = state.last_drag;
675
676        let animation = app
677            .get(self)
678            .animation
679            .clone()
680            .expect("created in init_state");
681        let animation_parent: AnimationRef<f64> = match phase {
682            PredictiveBackPhase::Commit => curved_animation_reversed.erase(),
683            _ => widget_animation.clone(),
684        };
685        animation.set_parent(app, Some(animation_parent));
686
687        let bounce_animation_parent: AnimationRef<f64> = match phase {
688            PredictiveBackPhase::Commit => ValueTween::new(0.0, last_bounce_animation_value)
689                .animate(app, curved_animation.erase()),
690            _ => ReverseAnimation::new(app, widget_animation).into_erased(),
691        };
692        self.bounce_animation(app)
693            .set_parent(app, Some(bounce_animation_parent));
694
695        let commit_animation_parent: AnimationRef<f64> = match phase {
696            PredictiveBackPhase::Commit => animation.erase(),
697            _ => k_always_dismissed_animation(app),
698        };
699        self.commit_animation(app)
700            .set_parent(app, Some(commit_animation_parent));
701
702        let x_shift = (screen_size.width()
703            / PredictiveBackSharedElementPageTransitionState::K_DIVISION_FACTOR)
704            - PredictiveBackSharedElementPageTransitionState::K_MARGIN;
705        let position_tween = match phase {
706            PredictiveBackPhase::Commit => ValueTween::new(
707                last_drag,
708                Offset::new(
709                    screen_size.height()
710                        * PredictiveBackSharedElementPageTransitionState::K_Y_POSITION_FACTOR,
711                    0.0,
712                ),
713            ),
714            // The y position before commit is given by the vertical drag, not by an animation.
715            _ => {
716                let y_shift = self.get_y_shift_position(app, screen_size.height());
717                let begin = match swipe_edge {
718                    Some(SwipeEdge::Left) => Offset::new(x_shift, y_shift),
719                    Some(SwipeEdge::Right) => Offset::new(-x_shift, y_shift),
720                    None => Offset::new(x_shift, y_shift),
721                };
722                ValueTween::new(begin, Offset::ZERO)
723            }
724        };
725        let position_animation = animation.drive(app, position_tween);
726        app.get_mut(self).position_animation = Some(position_animation);
727    }
728
729    fn update_curved_animations(self: Handle<Self>, app: &mut App) {
730        self.dispose_curved_animations(app);
731        let animation = self.widget(app).animation.clone();
732        let commit_interval: Rc<dyn waft_animation::Curve> =
733            Rc::new(PredictiveBackSharedElementPageTransitionState::k_commit_interval());
734        let curved_animation =
735            CurvedAnimation::new(app, animation.clone(), Rc::clone(&commit_interval), None);
736        let reversed = ReverseAnimation::new(app, animation).into_erased();
737        let curved_animation_reversed = CurvedAnimation::new(app, reversed, commit_interval, None);
738        let state = app.get_mut(self);
739        state.curved_animation = Some(curved_animation);
740        state.curved_animation_reversed = Some(curved_animation_reversed);
741    }
742
743    /// Dart's `_curvedAnimation?.dispose()` and `_curvedAnimationReversed?.dispose()`.
744    fn dispose_curved_animations(self: Handle<Self>, app: &mut App) {
745        let state = app.get(self);
746        let (curved_animation, curved_animation_reversed) = (
747            state.curved_animation.handle(),
748            state.curved_animation_reversed.handle(),
749        );
750        if let Some(curved_animation) = curved_animation {
751            curved_animation.dispose(app);
752        }
753        if let Some(curved_animation_reversed) = curved_animation_reversed {
754            curved_animation_reversed.dispose(app);
755        }
756    }
757
758    fn build_transition(
759        self: Handle<Self>,
760        app: &mut App,
761        context: BuildContext,
762        child: Option<&WidgetRef>,
763    ) -> WidgetRef {
764        let bounce_animation = self.bounce_animation(app).as_animation();
765        app.get_mut(self).last_bounce_animation_value = bounce_animation.value(app);
766        let scale = PredictiveBackSharedElementPageTransitionState::SCALE_TWEEN
767            .evaluate(app, bounce_animation);
768        let offset = match self.widget(app).phase {
769            PredictiveBackPhase::Commit => self.position_animation(app).value(app),
770            _ => {
771                let dx = self.position_animation(app).value(app).dx();
772                let screen_height = MediaQuery::height_of(app, context);
773                let last_drag = Offset::new(dx, self.get_y_shift_position(app, screen_height));
774                app.get_mut(self).last_drag = last_drag;
775                last_drag
776            }
777        };
778        let opacity = PredictiveBackSharedElementPageTransitionState::OPACITY_TWEEN
779            .evaluate(app, self.commit_animation(app).as_animation());
780        let border_radius =
781            MediaQuery::display_corner_radii_of(app, context).unwrap_or_else(|| {
782                BorderRadius::circular(
783                    PredictiveBackSharedElementPageTransitionState::BORDER_RADIUS_TWEEN
784                        .evaluate(app, bounce_animation),
785                )
786            });
787        let child = child.cloned().expect("the builder's child is the page");
788        Transform::scale(Some(scale), None, None)
789            .child(
790                Transform::translate(offset).child(
791                    Opacity::new(opacity).child(
792                        ClipRRect::new()
793                            .border_radius(border_radius.into())
794                            .child(child),
795                    ),
796                ),
797            )
798            .into_widget()
799    }
800}
801
802impl State for PredictiveBackSharedElementPageTransitionState {
803    type Widget = PredictiveBackSharedElementPageTransition;
804    waft_widgets::state_accessors!();
805
806    fn init_state(self: Handle<Self>, app: &mut App) {
807        let commit_animation = ProxyAnimation::new(app, None);
808        let bounce_animation = ProxyAnimation::new(app, None);
809        let animation = ProxyAnimation::new(app, None);
810        let state = app.get_mut(self);
811        state.commit_animation = Some(commit_animation);
812        state.bounce_animation = Some(bounce_animation);
813        state.animation = Some(animation);
814    }
815
816    fn did_update_widget(
817        self: Handle<Self>,
818        app: &mut App,
819        old_widget: &PredictiveBackSharedElementPageTransition,
820    ) {
821        let widget = self.widget(app);
822        let (animation, phase) = (widget.animation.clone(), widget.phase);
823        if animation != old_widget.animation {
824            self.update_curved_animations(app);
825        }
826        if phase != old_widget.phase && phase == PredictiveBackPhase::Commit {
827            let context = self.context(app);
828            let size = MediaQuery::size_of(app, context);
829            self.update_animations(app, size);
830        }
831    }
832
833    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
834        self.update_curved_animations(app);
835        let context = self.context(app);
836        let size = MediaQuery::size_of(app, context);
837        self.update_animations(app, size);
838    }
839
840    fn dispose(self: Handle<Self>, app: &mut App) {
841        debug_assert!(
842            app.get(self).curved_animation.is_some(),
843            "set in did_change_dependencies"
844        );
845        self.dispose_curved_animations(app);
846    }
847
848    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
849        let widget = self.widget(app);
850        let animation: Rc<dyn Listenable> = Rc::new(widget.animation.clone());
851        let child = widget.child.clone();
852        AnimatedBuilder::new(animation, move |app, context, child| {
853            self.build_transition(app, context, child)
854        })
855        .child(child)
856        .into_widget()
857    }
858}
859
860/// Android's predictive back page transition for full screen surfaces.
861///
862/// See also:
863///
864///  * <https://developer.android.com/design/ui/mobile/guides/patterns/predictive-back#full-screen-surfaces>,
865///    which is the Android spec for this transition.
866pub(crate) struct PredictiveBackFullscreenPageTransition {
867    animation: AnimationRef<f64>,
868    secondary_animation: AnimationRef<f64>,
869    phase: PredictiveBackPhase,
870    get_is_current: Rc<dyn Fn(&App) -> bool>,
871    child: WidgetRef,
872}
873
874impl Debug for PredictiveBackFullscreenPageTransition {
875    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876        f.debug_struct("_PredictiveBackFullscreenPageTransition")
877            .field("animation", &self.animation)
878            .field("secondary_animation", &self.secondary_animation)
879            .field("phase", &self.phase)
880            .field("child", &self.child)
881            .finish_non_exhaustive()
882    }
883}
884
885impl StatefulWidget for PredictiveBackFullscreenPageTransition {
886    type State = PredictiveBackFullscreenPageTransitionState;
887
888    fn create_state(&self) -> PredictiveBackFullscreenPageTransitionState {
889        PredictiveBackFullscreenPageTransitionState {
890            state: StateData::new(),
891            primary_position_tween: None,
892            secondary_position_tween: None,
893            secondary_current_position_tween: None,
894        }
895    }
896}
897
898/// Dart's `_PredictiveBackFullscreenPageTransitionState`.
899pub(crate) struct PredictiveBackFullscreenPageTransitionState {
900    state: StateData<PredictiveBackFullscreenPageTransition>,
901    primary_position_tween: Option<TweenSequence<Offset>>,
902    secondary_position_tween: Option<ValueTween<Offset>>,
903    secondary_current_position_tween: Option<ValueConstantTween<Offset>>,
904}
905
906impl PredictiveBackFullscreenPageTransitionState {
907    // These values were eyeballed to match the Android spec for the Full Screen page transition:
908    // https://developer.android.com/design/ui/mobile/guides/patterns/predictive-back#full-screen-surfaces
909    const K_SCALE_START: f64 = 1.0;
910    const K_SCALE_COMMIT: f64 = 0.95;
911    const K_OPACITY_FULLY_OPENED: f64 = 1.0;
912    const K_OPACITY_START_TRANSITION: f64 = 0.95;
913    // The point at which the drag would cause a commit instead of a cancel if it were released.
914    const K_COMMIT_AT: f64 = 0.65;
915    const K_WEIGHT_PRE_COMMIT: f64 = PredictiveBackFullscreenPageTransitionState::K_COMMIT_AT;
916    const K_WEIGHT_POST_COMMIT: f64 =
917        1.0 - PredictiveBackFullscreenPageTransitionState::K_WEIGHT_PRE_COMMIT;
918    const K_SCREEN_WIDTH_DIVISION_FACTOR: f64 = 20.0;
919    const K_X_SHIFT_ADJUSTMENT: f64 = 8.0;
920    const K_COMMIT_DURATION: Duration = Duration::from_millis(100);
921
922    const PRIMARY_OPACITY_TWEEN: ValueTween<f64> = ValueTween::new(
923        PredictiveBackFullscreenPageTransitionState::K_OPACITY_START_TRANSITION,
924        PredictiveBackFullscreenPageTransitionState::K_OPACITY_FULLY_OPENED,
925    );
926
927    fn primary_scale_tween() -> TweenSequence<f64> {
928        type S = PredictiveBackFullscreenPageTransitionState;
929        TweenSequence::new(vec![
930            TweenSequenceItem::new(
931                Rc::new(ValueTween::new(S::K_SCALE_START, S::K_SCALE_START)),
932                S::K_WEIGHT_PRE_COMMIT,
933            ),
934            TweenSequenceItem::new(
935                Rc::new(ValueTween::new(S::K_SCALE_COMMIT, S::K_SCALE_START)),
936                S::K_WEIGHT_POST_COMMIT,
937            ),
938        ])
939    }
940
941    const SECONDARY_SCALE_TWEEN_CURRENT: ValueConstantTween<f64> =
942        ValueConstantTween::new(PredictiveBackFullscreenPageTransitionState::K_SCALE_START);
943
944    fn secondary_tween_scale() -> TweenSequence<f64> {
945        type S = PredictiveBackFullscreenPageTransitionState;
946        TweenSequence::new(vec![
947            TweenSequenceItem::new(
948                Rc::new(ValueTween::new(S::K_SCALE_COMMIT, S::K_SCALE_START)),
949                S::K_WEIGHT_PRE_COMMIT,
950            ),
951            TweenSequenceItem::new(
952                Rc::new(ValueTween::new(S::K_SCALE_START, S::K_SCALE_START)),
953                S::K_WEIGHT_POST_COMMIT,
954            ),
955        ])
956    }
957
958    const SECONDARY_OPACITY_TWEEN_CURRENT: ValueConstantTween<f64> = ValueConstantTween::new(
959        PredictiveBackFullscreenPageTransitionState::K_OPACITY_FULLY_OPENED,
960    );
961
962    fn secondary_opacity_tween() -> TweenSequence<f64> {
963        type S = PredictiveBackFullscreenPageTransitionState;
964        TweenSequence::new(vec![
965            TweenSequenceItem::new(
966                Rc::new(ValueTween::new(
967                    S::K_OPACITY_FULLY_OPENED,
968                    S::K_OPACITY_START_TRANSITION,
969                )),
970                S::K_WEIGHT_PRE_COMMIT,
971            ),
972            TweenSequenceItem::new(
973                Rc::new(ValueTween::new(
974                    S::K_OPACITY_FULLY_OPENED,
975                    S::K_OPACITY_FULLY_OPENED,
976                )),
977                S::K_WEIGHT_POST_COMMIT,
978            ),
979        ])
980    }
981
982    fn secondary_animated_builder(
983        self: Handle<Self>,
984        app: &mut App,
985        child: Option<&WidgetRef>,
986    ) -> WidgetRef {
987        let widget = self.widget(app);
988        let (secondary_animation, get_is_current) = (
989            widget.secondary_animation.handle(),
990            Rc::clone(&widget.get_is_current),
991        );
992        let is_current = get_is_current(app);
993
994        let state = app.get(self);
995        let offset = if is_current {
996            state
997                .secondary_current_position_tween
998                .expect("set in did_change_dependencies")
999                .evaluate(app, secondary_animation)
1000        } else {
1001            state
1002                .secondary_position_tween
1003                .expect("set in did_change_dependencies")
1004                .evaluate(app, secondary_animation)
1005        };
1006        let scale = if is_current {
1007            Self::SECONDARY_SCALE_TWEEN_CURRENT.evaluate(app, secondary_animation)
1008        } else {
1009            Self::secondary_tween_scale().evaluate(app, secondary_animation)
1010        };
1011        let opacity = if is_current {
1012            Self::SECONDARY_OPACITY_TWEEN_CURRENT.evaluate(app, secondary_animation)
1013        } else {
1014            Self::secondary_opacity_tween().evaluate(app, secondary_animation)
1015        };
1016        let child = child.cloned().expect("the builder's child is the page");
1017        Transform::translate(offset)
1018            .child(
1019                Transform::scale(Some(scale), None, None).child(Opacity::new(opacity).child(child)),
1020            )
1021            .into_widget()
1022    }
1023
1024    fn primary_animated_builder(
1025        self: Handle<Self>,
1026        app: &mut App,
1027        child: Option<&WidgetRef>,
1028    ) -> WidgetRef {
1029        let widget = self.widget(app);
1030        let (animation, phase) = (widget.animation.handle(), widget.phase);
1031        let offset = app
1032            .get(self)
1033            .primary_position_tween
1034            .clone()
1035            .expect("set in did_change_dependencies")
1036            .evaluate(app, animation);
1037        let scale = Self::primary_scale_tween().evaluate(app, animation);
1038        let opacity = Self::PRIMARY_OPACITY_TWEEN.evaluate(app, animation);
1039        // A sudden fadeout at the commit point, driven by time and not the gesture.
1040        let commit_opacity = match phase {
1041            PredictiveBackPhase::Commit => 0.0,
1042            _ => {
1043                if animation.value(app) < Self::K_COMMIT_AT {
1044                    0.0
1045                } else {
1046                    1.0
1047                }
1048            }
1049        };
1050        let child = child.cloned().expect("the builder's child is the page");
1051        Transform::translate(offset)
1052            .child(Transform::scale(Some(scale), None, None).child(
1053                // A slight change in opacity before reaching the commit point.
1054                Opacity::new(opacity).child(
1055                    AnimatedOpacity::new(commit_opacity, Self::K_COMMIT_DURATION).child(child),
1056                ),
1057            ))
1058            .into_widget()
1059    }
1060}
1061
1062impl State for PredictiveBackFullscreenPageTransitionState {
1063    type Widget = PredictiveBackFullscreenPageTransition;
1064    waft_widgets::state_accessors!();
1065
1066    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1067        let context = self.context(app);
1068        let screen_width = MediaQuery::width_of(app, context);
1069        let x_shift =
1070            (screen_width / Self::K_SCREEN_WIDTH_DIVISION_FACTOR) - Self::K_X_SHIFT_ADJUSTMENT;
1071        let primary_position_tween = TweenSequence::new(vec![
1072            TweenSequenceItem::new(
1073                Rc::new(ValueTween::new(Offset::ZERO, Offset::ZERO)),
1074                Self::K_WEIGHT_PRE_COMMIT,
1075            ),
1076            TweenSequenceItem::new(
1077                Rc::new(ValueTween::new(Offset::new(x_shift, 0.0), Offset::ZERO)),
1078                Self::K_WEIGHT_POST_COMMIT,
1079            ),
1080        ]);
1081
1082        let state = app.get_mut(self);
1083        state.primary_position_tween = Some(primary_position_tween);
1084        state.secondary_current_position_tween = Some(ValueConstantTween::new(Offset::ZERO));
1085        state.secondary_position_tween =
1086            Some(ValueTween::new(Offset::new(x_shift, 0.0), Offset::ZERO));
1087    }
1088
1089    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1090        let widget = self.widget(app);
1091        let secondary_animation: Rc<dyn Listenable> = Rc::new(widget.secondary_animation.clone());
1092        let animation: Rc<dyn Listenable> = Rc::new(widget.animation.clone());
1093        let child = widget.child.clone();
1094        let border_radius =
1095            MediaQuery::display_corner_radii_of(app, context).unwrap_or_else(|| {
1096                BorderRadius::all(Radius::circular(
1097                    PredictiveBackSharedElementPageTransitionState::K_DEVICE_BORDER_RADIUS,
1098                ))
1099            });
1100        AnimatedBuilder::new(secondary_animation, move |app, _context, child| {
1101            self.secondary_animated_builder(app, child)
1102        })
1103        .child(
1104            AnimatedBuilder::new(animation, move |app, _context, child| {
1105                self.primary_animated_builder(app, child)
1106            })
1107            .child(
1108                ClipRRect::new()
1109                    .border_radius(border_radius.into())
1110                    .child(child),
1111            ),
1112        )
1113        .into_widget()
1114    }
1115}
1116
1117/// Dart's `double.sign`: -1.0, 0.0 or 1.0, where Rust's `signum` answers 1.0 for zero.
1118fn dart_sign(value: f64) -> f64 {
1119    if value == 0.0 || value.is_nan() {
1120        value
1121    } else {
1122        value.signum()
1123    }
1124}
1125
1126#[cfg(test)]
1127mod tests {
1128    use indexmap::IndexMap;
1129    use waft_embedder::{TargetPlatform, ViewId};
1130    use waft_foundation::Listener;
1131    use waft_widgets::{
1132        AnyElement, ColoredBox, Column, CrossAxisAlignment, Navigator, NavigatorState,
1133        PageTransitionsBuilderRef, RouteSettingsRef, SizedBox, SnapshotWidget, StateSetter,
1134        StatefulBuilder, Text, WidgetBuilder,
1135    };
1136
1137    use waft_widgets::testing::{
1138        TargetPlatformVariant, WidgetTester, expect, find, finds_one_widget, test_widgets,
1139        test_widgets_variant,
1140    };
1141
1142    use super::*;
1143    use crate::app::MaterialApp;
1144    use crate::colors::Colors;
1145    use crate::material::Material;
1146    use crate::page::MaterialPageRoute;
1147    use crate::page_transitions_theme::{
1148        FadeForwardsPageTransition, PageTransitionsTheme, ZoomEnterTransition, ZoomPageTransition,
1149    };
1150    use crate::test_support::{PaintInspection, material_page_app};
1151    use crate::text_button::TextButton;
1152    use crate::theme::Theme;
1153    use crate::theme_data::ThemeData;
1154    use waft_animation::AnimationWithParent;
1155    use waft_foundation::HandleId;
1156    use waft_rendering::testing::{PaintCall, assert_paints};
1157    use waft_test::{assert_no_new_objects, object_snapshot};
1158
1159    /// Not a Dart case: Dart's collector frees a disposed shared-element transition's proxies
1160    /// and animations; here they are freed with the state's references to them.
1161    #[test]
1162    fn a_disposed_shared_element_transition_frees_its_animations() {
1163        test_widgets(|tester| {
1164            let animation = tester
1165                .cell
1166                .borrow_mut()
1167                .create(waft_animation::AlwaysStoppedAnimation::new(0.5))
1168                .into_erased::<AnyAnimation<f64>>();
1169            tester.pump_widget(
1170                PredictiveBackSharedElementPageTransition {
1171                    is_delegated_transition: false,
1172                    animation: animation.clone(),
1173                    secondary_animation: animation.clone(),
1174                    phase: PredictiveBackPhase::Update,
1175                    start_back_event: None,
1176                    current_back_event: None,
1177                    child: waft_widgets::SizedBox::new().into_widget(),
1178                }
1179                .into_widget(),
1180            );
1181            let element =
1182                find::by_type::<PredictiveBackSharedElementPageTransition>().evaluate(tester)[0];
1183            let owned: Vec<HandleId> = {
1184                let app = tester.cell.borrow();
1185                let state = element
1186                    .state_handle::<PredictiveBackSharedElementPageTransitionState>(&app)
1187                    .expect("the transition's state");
1188                let curved_animation_reversed = app
1189                    .get(state)
1190                    .curved_animation_reversed
1191                    .as_ref()
1192                    .expect("set in did_change_dependencies")
1193                    .handle();
1194                vec![
1195                    state.commit_animation(&app).into(),
1196                    state.bounce_animation(&app).into(),
1197                    app.get(state)
1198                        .curved_animation
1199                        .as_ref()
1200                        .expect("set")
1201                        .handle()
1202                        .into(),
1203                    curved_animation_reversed.into(),
1204                    AnimationWithParent::parent(curved_animation_reversed, &app).id(),
1205                ]
1206            };
1207            tester.pump_widget(waft_widgets::SizedBox::new().into_widget());
1208            tester.cell.checkpoint();
1209            let app = tester.cell.borrow();
1210            for id in owned {
1211                assert!(!app.contains(id), "{id:?} is freed");
1212            }
1213        });
1214    }
1215
1216    /// Not a Dart case: Dart's collector frees the animations a shared-element transition's
1217    /// `_updateCurvedAnimations` and `_updateAnimations` replace; here they are freed with their
1218    /// last reference.
1219    #[test]
1220    fn a_shared_element_transition_given_new_dependencies_leaves_no_new_arena_objects() {
1221        test_widgets(|tester| {
1222            let animation = tester
1223                .cell
1224                .borrow_mut()
1225                .create(waft_animation::AlwaysStoppedAnimation::new(0.5))
1226                .into_erased::<AnyAnimation<f64>>();
1227            let transition = move |width: f64| -> WidgetRef {
1228                waft_widgets::MediaQuery::new(
1229                    waft_widgets::MediaQueryData::new().size(Size::new(width, 600.0)),
1230                    PredictiveBackSharedElementPageTransition {
1231                        is_delegated_transition: false,
1232                        animation: animation.clone(),
1233                        secondary_animation: animation.clone(),
1234                        phase: PredictiveBackPhase::Update,
1235                        start_back_event: None,
1236                        current_back_event: None,
1237                        child: waft_widgets::SizedBox::new().into_widget(),
1238                    },
1239                )
1240                .into_widget()
1241            };
1242            tester.pump_widget(transition(800.0));
1243            tester.pump_widget(transition(700.0));
1244            let snapshot = object_snapshot(&tester.cell.borrow());
1245            tester.pump_widget(transition(800.0));
1246            tester.pump_widget(transition(700.0));
1247            tester.cell.checkpoint();
1248            assert_no_new_objects(&tester.cell.borrow(), &snapshot);
1249        });
1250    }
1251
1252    const ALL_PLATFORMS: [TargetPlatform; 6] = [
1253        TargetPlatform::Android,
1254        TargetPlatform::Fuchsia,
1255        TargetPlatform::IOS,
1256        TargetPlatform::Linux,
1257        TargetPlatform::MacOS,
1258        TargetPlatform::Windows,
1259    ];
1260
1261    fn pump_app(
1262        tester: &mut WidgetTester,
1263        theme: impl FnOnce(&App) -> ThemeData,
1264        configure: impl FnOnce(MaterialApp) -> MaterialApp,
1265    ) {
1266        let root = {
1267            let theme = theme(&tester.cell.borrow());
1268            material_page_app(theme, configure)
1269        };
1270        tester.pump_widget(root);
1271    }
1272
1273    /// `ThemeData(pageTransitionsTheme:)` with `builder` for every platform.
1274    fn theme_for_every_platform(
1275        builder: PageTransitionsBuilderRef,
1276    ) -> impl FnOnce(&App) -> ThemeData {
1277        move |app| {
1278            ThemeData::builder()
1279                .page_transitions_theme(
1280                    PageTransitionsTheme::new().with_builders(
1281                        ALL_PLATFORMS
1282                            .into_iter()
1283                            .map(|platform| (platform, builder.clone()))
1284                            .collect(),
1285                    ),
1286                )
1287                .build(app)
1288        }
1289    }
1290
1291    /// The cases' `routes`: `/` a button 'push' that pushes `/b`, and `/b` the text 'page b'.
1292    fn push_routes() -> Vec<(String, WidgetBuilder)> {
1293        vec![
1294            (
1295                "/".to_string(),
1296                Rc::new(|_app: &mut App, context: BuildContext| {
1297                    Material::new()
1298                        .child(TextButton::new(
1299                            Some(Listener::new(move |app| {
1300                                Navigator::push_named(app, context, "/b", None);
1301                            })),
1302                            Some(Text::new("push")),
1303                        ))
1304                        .into_widget()
1305                }) as WidgetBuilder,
1306            ),
1307            (
1308                "/b".to_string(),
1309                Rc::new(|_app: &mut App, _context: BuildContext| Text::new("page b").into_widget())
1310                    as WidgetBuilder,
1311            ),
1312        ]
1313    }
1314
1315    fn found(tester: &WidgetTester, text: &str) -> usize {
1316        find::text(text).evaluate(tester).len()
1317    }
1318
1319    /// Dart's `find.byType(W)` with its default `skipOffstage`.
1320    fn count_of<W: 'static>(tester: &WidgetTester) -> usize {
1321        find::by_type::<W>()
1322            .evaluate(tester)
1323            .into_iter()
1324            .filter(|element| tester.is_onstage(*element))
1325            .count()
1326    }
1327
1328    /// The case's builder: the shared-element one, or the full-screen one.
1329    #[derive(Clone, Copy, Debug)]
1330    enum Variant {
1331        SharedElement,
1332        Fullscreen,
1333    }
1334
1335    impl Variant {
1336        fn builder(self) -> PageTransitionsBuilderRef {
1337            match self {
1338                Variant::SharedElement => {
1339                    PageTransitionsBuilderRef::new(PredictiveBackPageTransitionsBuilder::new())
1340                }
1341                Variant::Fullscreen => PageTransitionsBuilderRef::new(
1342                    PredictiveBackFullscreenPageTransitionsBuilder::new(),
1343                ),
1344            }
1345        }
1346
1347        /// Dart's `_findPredictiveBackPageTransition`.
1348        fn predictive_back_transitions(self, tester: &WidgetTester) -> usize {
1349            match self {
1350                Variant::SharedElement => {
1351                    count_of::<PredictiveBackSharedElementPageTransition>(tester)
1352                }
1353                Variant::Fullscreen => count_of::<PredictiveBackFullscreenPageTransition>(tester),
1354            }
1355        }
1356
1357        /// Dart's `_findFallbackPageTransition`.
1358        fn fallback_transitions(self, tester: &WidgetTester) -> usize {
1359            match self {
1360                Variant::SharedElement => count_of::<FadeForwardsPageTransition>(tester),
1361                Variant::Fullscreen => count_of::<ZoomPageTransition>(tester),
1362            }
1363        }
1364    }
1365
1366    fn view(tester: &WidgetTester) -> ViewId {
1367        let app = tester.cell.borrow();
1368        app.platform().views().first().expect("a view").id()
1369    }
1370
1371    /// The engine's `startBackGesture` on `flutter/backgesture`, from the left edge.
1372    fn start_back_gesture(tester: &WidgetTester, touch_offset: Offset, progress: f64) {
1373        let mut app = tester.cell.borrow_mut();
1374        let event = PredictiveBackEvent::new(Some(touch_offset), progress, SwipeEdge::Left);
1375        WidgetsBinding::instance(&mut app).handle_start_back_gesture(&mut app, event);
1376        app.drain_microtasks();
1377    }
1378
1379    /// The engine's `updateBackGestureProgress`, from the left edge.
1380    fn update_back_gesture(tester: &WidgetTester, touch_offset: Option<Offset>, progress: f64) {
1381        let mut app = tester.cell.borrow_mut();
1382        let event = PredictiveBackEvent::new(touch_offset, progress, SwipeEdge::Left);
1383        WidgetsBinding::instance(&mut app).handle_update_back_gesture_progress(&mut app, event);
1384        app.drain_microtasks();
1385    }
1386
1387    /// The engine's `commitBackGesture`.
1388    fn commit_back_gesture(tester: &WidgetTester) {
1389        let view = view(tester);
1390        let mut app = tester.cell.borrow_mut();
1391        WidgetsBinding::instance(&mut app).handle_commit_back_gesture(&mut app, view);
1392        app.drain_microtasks();
1393    }
1394
1395    /// The engine's `cancelBackGesture`.
1396    fn cancel_back_gesture(tester: &WidgetTester) {
1397        let mut app = tester.cell.borrow_mut();
1398        WidgetsBinding::instance(&mut app).handle_cancel_back_gesture(&mut app);
1399        app.drain_microtasks();
1400    }
1401
1402    /// The engine's `popRoute` on `flutter/navigation`.
1403    fn pop_route(tester: &WidgetTester) {
1404        let view = view(tester);
1405        let mut app = tester.cell.borrow_mut();
1406        WidgetsBinding::instance(&mut app).handle_pop_route(&mut app, view);
1407        app.drain_microtasks();
1408    }
1409
1410    fn top_left(tester: &WidgetTester, text: &str) -> Offset {
1411        let element: AnyElement = *find::text(text).evaluate(tester).first().expect("the text");
1412        tester.get_rect(element).top_left()
1413    }
1414
1415    /// The first part of the gesture cases: the app with `variant`'s builder on every platform
1416    /// and `routes` (a `/` with a 'push' button to `/b`, which shows 'page b'), `/b` pushed and
1417    /// settled; on Android, a back gesture started and dragged to `update_progress`. Answers whether the gesture ran.
1418    fn push_and_drag(
1419        tester: &mut WidgetTester,
1420        platform: TargetPlatform,
1421        variant: Variant,
1422        routes: Vec<(String, WidgetBuilder)>,
1423        update_touch: Option<Offset>,
1424        update_progress: f64,
1425    ) -> bool {
1426        pump_app(tester, theme_for_every_platform(variant.builder()), |app| {
1427            app.routes(routes)
1428        });
1429
1430        assert_eq!(found(tester, "push"), 1);
1431        assert_eq!(found(tester, "page b"), 0);
1432        assert_eq!(variant.predictive_back_transitions(tester), 0);
1433        assert_eq!(variant.fallback_transitions(tester), 1);
1434
1435        tester.tap(find::text("push"));
1436        tester.pump_and_settle();
1437
1438        assert_eq!(found(tester, "push"), 0);
1439        assert_eq!(found(tester, "page b"), 1);
1440        assert_eq!(variant.predictive_back_transitions(tester), 0);
1441        assert_eq!(variant.fallback_transitions(tester), 1);
1442
1443        // Only Android supports backGesture channel methods. Other platforms will do nothing.
1444        if platform != TargetPlatform::Android {
1445            return false;
1446        }
1447
1448        // Start a system pop gesture, which will switch to using the predictive back page
1449        // transition.
1450        start_back_gesture(tester, Offset::new(5.0, 300.0), 0.0);
1451        tester.pump();
1452
1453        assert_eq!(variant.predictive_back_transitions(tester), 1);
1454        assert_eq!(variant.fallback_transitions(tester), 0);
1455        let start_page_b_offset = top_left(tester, "page b");
1456        assert_eq!(start_page_b_offset.dx(), 0.0);
1457
1458        // Drag the system back gesture.
1459        update_back_gesture(tester, update_touch, update_progress);
1460        tester.pump_and_settle();
1461
1462        assert_eq!(variant.predictive_back_transitions(tester), 2);
1463        assert_eq!(variant.fallback_transitions(tester), 0);
1464
1465        let update_page_b_offset = top_left(tester, "page b");
1466        assert!(update_page_b_offset.dx() > start_page_b_offset.dx());
1467        true
1468    }
1469
1470    #[test]
1471    fn the_predictive_back_builders_follow_a_predictive_back_gesture_on_android() {
1472        for variant in [Variant::SharedElement, Variant::Fullscreen] {
1473            for platform in ALL_PLATFORMS {
1474                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1475                    if !push_and_drag(tester, platform, variant, push_routes(), None, 0.35) {
1476                        return;
1477                    }
1478
1479                    // Commit the system back gesture.
1480                    commit_back_gesture(tester);
1481                    tester.pump_and_settle();
1482
1483                    assert_eq!(
1484                        variant.predictive_back_transitions(tester),
1485                        0,
1486                        "{variant:?}"
1487                    );
1488                    assert_eq!(variant.fallback_transitions(tester), 1, "{variant:?}");
1489                    assert_eq!(found(tester, "push"), 1);
1490                    assert_eq!(found(tester, "page b"), 0);
1491                });
1492            }
1493        }
1494    }
1495
1496    #[test]
1497    fn the_predictive_back_builders_follow_a_canceled_predictive_back_gesture_on_android() {
1498        for variant in [Variant::SharedElement, Variant::Fullscreen] {
1499            for platform in ALL_PLATFORMS {
1500                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1501                    if !push_and_drag(
1502                        tester,
1503                        platform,
1504                        variant,
1505                        push_routes(),
1506                        Some(Offset::new(100.0, 300.0)),
1507                        0.35,
1508                    ) {
1509                        return;
1510                    }
1511
1512                    // Cancel the system back gesture.
1513                    cancel_back_gesture(tester);
1514                    tester.pump_and_settle();
1515
1516                    assert_eq!(found(tester, "push"), 0);
1517                    assert_eq!(found(tester, "page b"), 1);
1518                    assert_eq!(
1519                        variant.predictive_back_transitions(tester),
1520                        0,
1521                        "{variant:?}"
1522                    );
1523                    assert_eq!(variant.fallback_transitions(tester), 1, "{variant:?}");
1524                });
1525            }
1526        }
1527    }
1528
1529    /// The multiple-observers case's routes: `/` a button 'push' that pushes `/b`, and `/b` the
1530    /// text 'page b' over a `StatefulBuilder` that shows, once `including_nested_navigator` is
1531    /// set, a nested `Navigator` whose one route has `variant`'s builder on every platform.
1532    fn routes_with_nested_navigator(
1533        variant: Variant,
1534        including_nested_navigator: Rc<std::cell::Cell<bool>>,
1535        set_state: Rc<std::cell::RefCell<Option<StateSetter>>>,
1536    ) -> Vec<(String, WidgetBuilder)> {
1537        let mut routes = push_routes();
1538        routes[1].1 = Rc::new(move |_app: &mut App, _context: BuildContext| {
1539            let including_nested_navigator = Rc::clone(&including_nested_navigator);
1540            let set_state = Rc::clone(&set_state);
1541            Column::new()
1542                .cross_axis_alignment(CrossAxisAlignment::Start)
1543                .children([
1544                    Text::new("page b").into_widget(),
1545                    StatefulBuilder::new(move |_app, _context, local_set_state| {
1546                        *set_state.borrow_mut() = Some(local_set_state);
1547                        if !including_nested_navigator.get() {
1548                            return SizedBox::shrink().into_widget();
1549                        }
1550                        Navigator::new()
1551                            .initial_route("b/nested")
1552                            .on_generate_route(move |app, settings| {
1553                                let builder: WidgetBuilder = match settings.name.as_deref() {
1554                                    Some("b/nested") => Rc::new(move |app, _context| {
1555                                        Material::new()
1556                                            .child(Theme::new(
1557                                                theme_for_every_platform(variant.builder())(app),
1558                                                Column::new().children([Text::new(
1559                                                    "Nested route inside of page b",
1560                                                )
1561                                                .into_widget()]),
1562                                            ))
1563                                            .into_widget()
1564                                    }),
1565                                    name => panic!("Invalid route: {name:?}"),
1566                                };
1567                                Some(
1568                                    (MaterialPageRoute::new(app, builder).settings(
1569                                        app,
1570                                        RouteSettingsRef::Settings(settings.clone()),
1571                                    ))
1572                                    .into_erased(),
1573                                )
1574                            })
1575                            .into_widget()
1576                    })
1577                    .into_widget(),
1578                ])
1579                .into_widget()
1580        }) as WidgetBuilder;
1581        routes
1582    }
1583
1584    #[test]
1585    fn if_there_are_multiple_predictive_back_observers_only_one_gets_called_for_a_given_back_gesture()
1586     {
1587        for variant in [Variant::SharedElement, Variant::Fullscreen] {
1588            for platform in ALL_PLATFORMS {
1589                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1590                    let including_nested_navigator = Rc::new(std::cell::Cell::new(false));
1591                    let set_state = Rc::new(std::cell::RefCell::new(None::<StateSetter>));
1592                    let routes = routes_with_nested_navigator(
1593                        variant,
1594                        Rc::clone(&including_nested_navigator),
1595                        Rc::clone(&set_state),
1596                    );
1597                    let dragged = push_and_drag(
1598                        tester,
1599                        platform,
1600                        variant,
1601                        routes,
1602                        Some(Offset::new(100.0, 300.0)),
1603                        0.3,
1604                    );
1605                    assert_eq!(found(tester, "Nested route inside of page b"), 0);
1606                    if !dragged {
1607                        return;
1608                    }
1609                    let update_page_b_offset = top_left(tester, "page b");
1610
1611                    // In the middle of the system back gesture here, add a nested Navigator
1612                    // that includes a new predictive back gesture observer.
1613                    let set_state = set_state.borrow().clone().expect("page b built");
1614                    set_state(&mut tester.cell.borrow_mut(), &mut |_app| {
1615                        including_nested_navigator.set(true)
1616                    });
1617                    tester.pump_and_settle();
1618                    assert_eq!(found(tester, "push"), 1);
1619                    assert_eq!(found(tester, "page b"), 1);
1620                    assert_eq!(found(tester, "Nested route inside of page b"), 1);
1621
1622                    // Send another drag gesture, and ensure that the original observer still
1623                    // gets it.
1624                    update_back_gesture(tester, Some(Offset::new(110.0, 300.0)), 0.35);
1625                    tester.pump_and_settle();
1626
1627                    assert_eq!(
1628                        variant.predictive_back_transitions(tester),
1629                        2,
1630                        "{variant:?}"
1631                    );
1632                    // Despite using a predictive back transition, the new route has not
1633                    // received a start event, so it is still using the fallback transition.
1634                    assert_eq!(variant.fallback_transitions(tester), 1, "{variant:?}");
1635
1636                    let update2_page_b_offset = top_left(tester, "page b");
1637                    assert!(update2_page_b_offset.dx() > update_page_b_offset.dx());
1638
1639                    // Commit the system back gesture, and the original observer is able to
1640                    // handle the back without interference.
1641                    commit_back_gesture(tester);
1642                    tester.pump_and_settle();
1643
1644                    assert_eq!(
1645                        variant.predictive_back_transitions(tester),
1646                        0,
1647                        "{variant:?}"
1648                    );
1649                    assert_eq!(variant.fallback_transitions(tester), 1, "{variant:?}");
1650                    assert_eq!(found(tester, "push"), 1);
1651                    assert_eq!(found(tester, "page b"), 0);
1652                    assert_eq!(found(tester, "Nested route inside of page b"), 0);
1653                });
1654            }
1655        }
1656    }
1657
1658    /// The back-to-back case's routes: `/` a button 'push b' to `/b`, `/b` a button 'push c'
1659    /// to `/c`, and `/c` the text 'page c'.
1660    fn three_routes() -> Vec<(String, WidgetBuilder)> {
1661        let push_button = |label: &'static str, name: &'static str| -> WidgetBuilder {
1662            Rc::new(move |_app: &mut App, context: BuildContext| {
1663                Material::new()
1664                    .child(TextButton::new(
1665                        Some(Listener::new(move |app| {
1666                            Navigator::push_named(app, context, name, None);
1667                        })),
1668                        Some(Text::new(label)),
1669                    ))
1670                    .into_widget()
1671            })
1672        };
1673        vec![
1674            ("/".to_string(), push_button("push b", "/b")),
1675            ("/b".to_string(), push_button("push c", "/c")),
1676            (
1677                "/c".to_string(),
1678                Rc::new(|_app: &mut App, _context: BuildContext| Text::new("page c").into_widget())
1679                    as WidgetBuilder,
1680            ),
1681        ]
1682    }
1683
1684    #[test]
1685    fn two_back_gestures_back_to_back_dismiss_two_routes() {
1686        for variant in [Variant::SharedElement, Variant::Fullscreen] {
1687            for platform in ALL_PLATFORMS {
1688                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1689                    pump_app(tester, theme_for_every_platform(variant.builder()), |app| {
1690                        app.routes(three_routes())
1691                    });
1692
1693                    assert_eq!(found(tester, "push b"), 1);
1694                    assert_eq!(found(tester, "push c"), 0);
1695                    assert_eq!(found(tester, "page c"), 0);
1696                    assert_eq!(variant.predictive_back_transitions(tester), 0);
1697                    assert_eq!(variant.fallback_transitions(tester), 1);
1698
1699                    tester.tap(find::text("push b"));
1700                    tester.pump_and_settle();
1701
1702                    assert_eq!(found(tester, "push"), 0);
1703                    assert_eq!(found(tester, "push c"), 1);
1704                    assert_eq!(found(tester, "page c"), 0);
1705                    assert_eq!(variant.predictive_back_transitions(tester), 0);
1706                    assert_eq!(variant.fallback_transitions(tester), 1);
1707
1708                    tester.tap(find::text("push c"));
1709                    tester.pump_and_settle();
1710
1711                    assert_eq!(found(tester, "push"), 0);
1712                    assert_eq!(found(tester, "push c"), 0);
1713                    assert_eq!(found(tester, "page c"), 1);
1714                    assert_eq!(variant.predictive_back_transitions(tester), 0);
1715                    assert_eq!(variant.fallback_transitions(tester), 1);
1716
1717                    // Only Android supports backGesture channel methods. Other platforms will
1718                    // do nothing.
1719                    if platform != TargetPlatform::Android {
1720                        return;
1721                    }
1722
1723                    // Start a system pop gesture, which will switch to using the predictive
1724                    // back page transition.
1725                    start_back_gesture(tester, Offset::new(5.0, 300.0), 0.0);
1726                    tester.pump();
1727
1728                    assert_eq!(
1729                        variant.predictive_back_transitions(tester),
1730                        1,
1731                        "{variant:?}"
1732                    );
1733                    assert_eq!(variant.fallback_transitions(tester), 0, "{variant:?}");
1734
1735                    // Drag the system back gesture far enough to commit.
1736                    update_back_gesture(tester, None, 0.35);
1737                    tester.pump();
1738
1739                    assert_eq!(
1740                        variant.predictive_back_transitions(tester),
1741                        2,
1742                        "{variant:?}"
1743                    );
1744                    assert_eq!(variant.fallback_transitions(tester), 0, "{variant:?}");
1745
1746                    // Commit the system back gesture.
1747                    commit_back_gesture(tester);
1748                    tester.pump();
1749
1750                    // The predictive back page transitions still exist because the outgoing
1751                    // animation has not yet finished.
1752                    assert_eq!(
1753                        variant.predictive_back_transitions(tester),
1754                        2,
1755                        "{variant:?}"
1756                    );
1757                    assert_eq!(variant.fallback_transitions(tester), 0, "{variant:?}");
1758
1759                    assert_eq!(found(tester, "push"), 0);
1760                    assert_eq!(found(tester, "push c"), 1);
1761                    assert_eq!(found(tester, "page c"), 1);
1762
1763                    // Start another system pop gesture, before the first has finished
1764                    // animating out.
1765                    start_back_gesture(tester, Offset::new(5.0, 300.0), 0.0);
1766                    tester.pump();
1767
1768                    assert_eq!(
1769                        variant.predictive_back_transitions(tester),
1770                        2,
1771                        "{variant:?}"
1772                    );
1773                    assert_eq!(variant.fallback_transitions(tester), 0, "{variant:?}");
1774
1775                    // Drag the system back gesture far enough to commit.
1776                    update_back_gesture(tester, None, 0.35);
1777                    tester.pump();
1778
1779                    assert_eq!(
1780                        variant.predictive_back_transitions(tester),
1781                        3,
1782                        "{variant:?}"
1783                    );
1784                    assert_eq!(variant.fallback_transitions(tester), 0, "{variant:?}");
1785
1786                    // Commit the system back gesture.
1787                    commit_back_gesture(tester);
1788                    tester.pump_and_settle();
1789
1790                    assert_eq!(
1791                        variant.predictive_back_transitions(tester),
1792                        0,
1793                        "{variant:?}"
1794                    );
1795                    assert_eq!(variant.fallback_transitions(tester), 1, "{variant:?}");
1796
1797                    assert_eq!(found(tester, "push b"), 1);
1798                    assert_eq!(found(tester, "push c"), 0);
1799                    assert_eq!(found(tester, "page c"), 0);
1800                });
1801            }
1802        }
1803    }
1804
1805    // page_transitions_theme_test 'predictive back gestures pop the route on all platforms
1806    // regardless of whether their transition handles predictive back'.
1807    #[test]
1808    fn a_predictive_back_gesture_pops_the_route_on_every_platform() {
1809        for platform in ALL_PLATFORMS {
1810            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1811                pump_app(tester, ThemeData::new, |app| app.routes(push_routes()));
1812
1813                assert_eq!(found(tester, "push"), 1);
1814                assert_eq!(found(tester, "page b"), 0);
1815
1816                tester.tap(find::text("push"));
1817                tester.pump_and_settle();
1818
1819                assert_eq!(found(tester, "push"), 0);
1820                assert_eq!(found(tester, "page b"), 1);
1821
1822                // Start a system pop gesture.
1823                start_back_gesture(tester, Offset::new(5.0, 300.0), 0.0);
1824                tester.pump();
1825
1826                assert_eq!(found(tester, "push"), 0);
1827                assert_eq!(found(tester, "page b"), 1);
1828
1829                // Drag the system back gesture far enough to commit.
1830                update_back_gesture(tester, None, 0.35);
1831                tester.pump_and_settle();
1832
1833                match platform {
1834                    // Shows both pages while doing the "peek" predictive back transition.
1835                    TargetPlatform::Android => assert_eq!(found(tester, "push"), 1),
1836                    // Does no transition yet; still shows page b only.
1837                    _ => assert_eq!(found(tester, "push"), 0, "{platform:?}"),
1838                }
1839                assert_eq!(found(tester, "page b"), 1);
1840
1841                // Commit the system back gesture.
1842                commit_back_gesture(tester);
1843                tester.pump_and_settle();
1844                assert_eq!(found(tester, "push"), 1);
1845                assert_eq!(found(tester, "page b"), 0);
1846            });
1847        }
1848    }
1849
1850    #[test]
1851    fn predictive_back_is_the_default_on_android() {
1852        for platform in ALL_PLATFORMS {
1853            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1854                pump_app(tester, ThemeData::new, |app| app.routes(push_routes()));
1855
1856                let push = *find::text("push").evaluate(tester).first().expect("push");
1857                let builder = {
1858                    let mut app = tester.cell.borrow_mut();
1859                    Theme::of(&mut app, push)
1860                        .page_transitions_theme
1861                        .builders()
1862                        .get(&platform)
1863                        .cloned()
1864                };
1865                let is_predictive_back = builder.is_some_and(|builder| {
1866                    format!("{builder:?}").starts_with("PredictiveBackPageTransitionsBuilder")
1867                });
1868                assert_eq!(
1869                    is_predictive_back,
1870                    platform == TargetPlatform::Android,
1871                    "{platform:?}"
1872                );
1873            });
1874        }
1875    }
1876
1877    // 'PredictiveBackPageTransitionsBuilder uses display corner radii when available', for each
1878    // builder.
1879    #[test]
1880    fn the_predictive_back_builders_use_the_display_corner_radii_when_available() {
1881        let display_corner_radii = BorderRadius::all(Radius::circular(33.3));
1882        let clip_of_the_display_corners = move || {
1883            find::by_widget_predicate("a ClipRRect of the display corners", move |_, widget| {
1884                waft_widgets::downcast_widget::<ClipRRect>(widget)
1885                    .is_some_and(|clip| clip.border_radius == display_corner_radii.into())
1886            })
1887        };
1888        for variant in [Variant::SharedElement, Variant::Fullscreen] {
1889            test_widgets(|tester| {
1890                pump_app(tester, theme_for_every_platform(variant.builder()), |app| {
1891                    app.builder(move |app, context, child| {
1892                        MediaQuery::new(
1893                            MediaQuery::of(app, context)
1894                                .apply_display_corner_radii(Some(display_corner_radii)),
1895                            child.cloned().expect("the navigator"),
1896                        )
1897                        .into_widget()
1898                    })
1899                    .routes(push_routes())
1900                });
1901
1902                assert_eq!(variant.predictive_back_transitions(tester), 0);
1903                assert_eq!(variant.fallback_transitions(tester), 1);
1904                assert_eq!(count_of::<ClipRRect>(tester), 0);
1905
1906                tester.tap(find::text("push"));
1907                tester.pump_and_settle();
1908
1909                assert_eq!(variant.predictive_back_transitions(tester), 0);
1910                assert_eq!(variant.fallback_transitions(tester), 1);
1911                assert_eq!(count_of::<ClipRRect>(tester), 0);
1912
1913                // Start a system pop gesture, which will switch to using the predictive back
1914                // page transition.
1915                start_back_gesture(tester, Offset::new(5.0, 300.0), 0.0);
1916                tester.pump();
1917
1918                assert_eq!(variant.predictive_back_transitions(tester), 1);
1919                assert_eq!(variant.fallback_transitions(tester), 0);
1920                expect(tester, &clip_of_the_display_corners(), finds_one_widget());
1921            });
1922        }
1923    }
1924
1925    // page_transitions_theme_test 'predictive back falls back to FadeForwardsPageTransition'.
1926    #[test]
1927    fn predictive_back_falls_back_to_the_fade_forwards_transition() {
1928        for platform in ALL_PLATFORMS {
1929            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1930                let variant = Variant::SharedElement;
1931                pump_app(tester, theme_for_every_platform(variant.builder()), |app| {
1932                    app.routes(push_routes())
1933                });
1934
1935                assert_eq!(found(tester, "push"), 1);
1936                assert_eq!(found(tester, "page b"), 0);
1937
1938                tester.tap(find::text("push"));
1939                tester.pump_and_settle();
1940
1941                assert_eq!(found(tester, "push"), 0);
1942                assert_eq!(found(tester, "page b"), 1);
1943
1944                // Only Android sends system back gestures.
1945                let android = platform == TargetPlatform::Android;
1946                if android {
1947                    start_back_gesture(tester, Offset::new(5.0, 300.0), 0.0);
1948                    tester.pump();
1949                }
1950
1951                assert_eq!(
1952                    variant.predictive_back_transitions(tester),
1953                    usize::from(android)
1954                );
1955                assert_eq!(variant.fallback_transitions(tester), usize::from(!android));
1956
1957                assert_eq!(found(tester, "push"), 0);
1958                assert_eq!(found(tester, "page b"), 1);
1959
1960                // Drag the system back gesture far enough to commit.
1961                if android {
1962                    update_back_gesture(tester, None, 0.35);
1963                    tester.pump_and_settle();
1964                    assert_eq!(found(tester, "push"), 1);
1965                } else {
1966                    assert_eq!(found(tester, "push"), 0);
1967                }
1968
1969                assert_eq!(found(tester, "page b"), 1);
1970
1971                if android {
1972                    assert_eq!(variant.predictive_back_transitions(tester), 2);
1973                    assert_eq!(variant.fallback_transitions(tester), 0);
1974                } else {
1975                    assert_eq!(variant.predictive_back_transitions(tester), 0);
1976                    assert_eq!(variant.fallback_transitions(tester), 1);
1977                }
1978
1979                if android {
1980                    // Commit the system back gesture on Android.
1981                    commit_back_gesture(tester);
1982                } else {
1983                    // On other platforms, send a one-off system pop.
1984                    pop_route(tester);
1985                }
1986                tester.pump();
1987
1988                assert_eq!(found(tester, "push"), 1);
1989                assert_eq!(found(tester, "page b"), 1);
1990
1991                if android {
1992                    assert_eq!(variant.predictive_back_transitions(tester), 2);
1993                    assert_eq!(variant.fallback_transitions(tester), 0);
1994                } else {
1995                    assert_eq!(variant.predictive_back_transitions(tester), 0);
1996                    assert_eq!(variant.fallback_transitions(tester), 2);
1997                }
1998
1999                tester.pump_and_settle();
2000
2001                assert_eq!(found(tester, "push"), 1);
2002                assert_eq!(found(tester, "page b"), 0);
2003
2004                assert_eq!(variant.predictive_back_transitions(tester), 0);
2005                assert_eq!(variant.fallback_transitions(tester), 1);
2006            });
2007        }
2008    }
2009
2010    #[test]
2011    fn the_predictive_back_builder_falls_back_with_its_fallback_color() {
2012        for platform in ALL_PLATFORMS {
2013            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2014                let variant = Variant::SharedElement;
2015                pump_app(
2016                    tester,
2017                    theme_for_every_platform(PageTransitionsBuilderRef::new(
2018                        PredictiveBackPageTransitionsBuilder::new().fallback_color(Colors::BLACK),
2019                    )),
2020                    |app| app.routes(push_routes()),
2021                );
2022
2023                assert_eq!(found(tester, "push"), 1);
2024                assert_eq!(found(tester, "page b"), 0);
2025                assert_eq!(variant.predictive_back_transitions(tester), 0);
2026                assert_eq!(variant.fallback_transitions(tester), 1);
2027
2028                tester.tap(find::text("push"));
2029                tester.pump_by(Duration::from_millis(400));
2030
2031                let colored_box = *find::by_type::<ColoredBox>()
2032                    .evaluate(tester)
2033                    .into_iter()
2034                    .filter(|element| tester.is_onstage(*element))
2035                    .collect::<Vec<_>>()
2036                    .last()
2037                    .expect("a ColoredBox");
2038                let color = tester
2039                    .widget::<ColoredBox, _>(colored_box, |colored_box| colored_box.color.color());
2040                assert_eq!(color, Colors::BLACK, "{platform:?}");
2041
2042                tester.pump_and_settle();
2043            });
2044        }
2045    }
2046
2047    #[test]
2048    fn the_predictive_back_fullscreen_builder_falls_back_with_its_fallback_color() {
2049        for platform in ALL_PLATFORMS {
2050            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2051                let variant = Variant::Fullscreen;
2052                pump_app(
2053                    tester,
2054                    theme_for_every_platform(PageTransitionsBuilderRef::new(
2055                        PredictiveBackFullscreenPageTransitionsBuilder::new()
2056                            .fallback_color(Colors::BLACK),
2057                    )),
2058                    |app| app.routes(push_routes()),
2059                );
2060
2061                assert_eq!(found(tester, "push"), 1);
2062                assert_eq!(found(tester, "page b"), 0);
2063                assert_eq!(variant.predictive_back_transitions(tester), 0);
2064                assert_eq!(variant.fallback_transitions(tester), 1);
2065
2066                // Pump till animation is half-way through.
2067                tester.tap(find::text("push"));
2068                tester.pump();
2069                tester.pump_by(Duration::from_millis(125));
2070
2071                // The entering page's zoom transition paints the scrim.
2072                let enter = *find::by_type::<ZoomEnterTransition>()
2073                    .evaluate(tester)
2074                    .iter()
2075                    .find(|element| {
2076                        let app = tester.cell.borrow();
2077                        tester.widget::<ZoomEnterTransition, _>(**element, |enter| {
2078                            !enter.reverse && enter.animation.is_animating(&app)
2079                        })
2080                    })
2081                    .expect("the entering page's zoom transition");
2082                let render = tester.render_box_of(enter).as_object();
2083                let ops = tester.painted_ops(render);
2084                // Expect the color to be at exactly 59.6% opacity at this time.
2085                #[allow(deprecated)]
2086                let expected = Colors::BLACK.with_opacity(0.596);
2087                assert_paints(&ops, &[PaintCall::rect(Some(expected))]);
2088
2089                tester.pump_and_settle();
2090            });
2091        }
2092    }
2093
2094    /// The fallback snapshotting cases: page 1 and page 2 under `builder` on Android; pushes
2095    /// `/2` and pops, each a tenth into the transition, and answers whether page 1 and page 2
2096    /// snapshot each time: (push exiting, push entering, pop exiting, pop entering).
2097    fn push_and_pop_snapshotting(builder: PredictiveBackPageTransitionsBuilder) -> [bool; 4] {
2098        let mut result = [false; 4];
2099        test_widgets(|tester| {
2100            pump_app(
2101                tester,
2102                move |app| {
2103                    ThemeData::builder()
2104                        .page_transitions_theme(PageTransitionsTheme::new().with_builders(
2105                            IndexMap::from([(
2106                                TargetPlatform::Android,
2107                                PageTransitionsBuilderRef::new(builder),
2108                            )]),
2109                        ))
2110                        .build(app)
2111                },
2112                |app| {
2113                    app.on_generate_route(|app, settings| {
2114                        let text = if settings.name.as_deref() == Some("/") {
2115                            "Page 1"
2116                        } else {
2117                            "Page 2"
2118                        };
2119                        Some(
2120                            (MaterialPageRoute::new(
2121                                app,
2122                                Rc::new(move |_app, _context| {
2123                                    Material::new().child(Text::new(text)).into_widget()
2124                                }),
2125                            ))
2126                            .into_erased(),
2127                        )
2128                    })
2129                },
2130            );
2131            let is_snapshotting = |tester: &WidgetTester, text: &str| {
2132                let text = *find::text(text).evaluate(tester).first().expect("the text");
2133                let ancestors = tester.ancestors(text);
2134                let app = tester.cell.borrow();
2135                ancestors.into_iter().any(|ancestor| {
2136                    waft_widgets::downcast_widget::<SnapshotWidget>(&**ancestor.widget(&app))
2137                        .is_some_and(|snapshot| snapshot.controller.allow_snapshotting(&app))
2138                })
2139            };
2140            let navigator = {
2141                let element = *find::by_type::<Navigator>()
2142                    .evaluate(tester)
2143                    .first()
2144                    .expect("a navigator");
2145                element
2146                    .state_handle::<NavigatorState>(&tester.cell.borrow())
2147                    .expect("a navigator's state")
2148            };
2149            let partway = Duration::from_millis(
2150                FadeForwardsPageTransitionsBuilder::K_TRANSITION_MILLISECONDS / 10,
2151            );
2152
2153            navigator.push_named(&mut tester.cell.borrow_mut(), "/2", None);
2154            tester.pump();
2155            tester.pump_by(partway);
2156            assert!(Variant::SharedElement.fallback_transitions(tester) > 0);
2157            result[0] = is_snapshotting(tester, "Page 1");
2158            result[1] = is_snapshotting(tester, "Page 2");
2159            tester.pump_and_settle();
2160
2161            navigator.pop(&mut tester.cell.borrow_mut(), None);
2162            tester.pump();
2163            tester.pump_by(partway);
2164            result[2] = is_snapshotting(tester, "Page 2");
2165            result[3] = is_snapshotting(tester, "Page 1");
2166            tester.pump_and_settle();
2167        });
2168        result
2169    }
2170
2171    #[test]
2172    fn the_fallback_snapshots_the_entering_and_exiting_routes_by_default() {
2173        assert_eq!(
2174            push_and_pop_snapshotting(PredictiveBackPageTransitionsBuilder::new()),
2175            [true, true, true, true]
2176        );
2177    }
2178
2179    #[test]
2180    fn the_fallback_is_given_the_builders_allow_snapshotting() {
2181        assert_eq!(
2182            push_and_pop_snapshotting(
2183                PredictiveBackPageTransitionsBuilder::new().allow_snapshotting(false)
2184            ),
2185            [false, false, false, false]
2186        );
2187    }
2188
2189    #[test]
2190    fn a_button_back_event_starts_no_predictive_back_gesture() {
2191        test_widgets(|tester| {
2192            let variant = Variant::SharedElement;
2193            pump_app(tester, theme_for_every_platform(variant.builder()), |app| {
2194                app.routes(push_routes())
2195            });
2196            tester.tap(find::text("push"));
2197            tester.pump_and_settle();
2198
2199            let handled = {
2200                let mut app = tester.cell.borrow_mut();
2201                let event = PredictiveBackEvent::new(None, 0.0, SwipeEdge::Left);
2202                WidgetsBinding::instance(&mut app).handle_start_back_gesture(&mut app, event)
2203            };
2204            tester.pump();
2205
2206            assert!(!handled);
2207            assert_eq!(variant.predictive_back_transitions(tester), 0);
2208            assert_eq!(variant.fallback_transitions(tester), 1);
2209        });
2210    }
2211}