Skip to main content

waft_widgets/widgets/
page_transitions_builder.rs

1//! Flutter counterpart: `widgets/page_transitions_builder.dart`.
2//!
3//! Dart's `buildTransitions<T>(PageRoute<T> route, ..)` takes the route erased, as an
4//! [`AnyPageRoute`]: routes carry no result type (`navigator.rs`), and a builder is held as an
5//! `Rc<dyn PageTransitionsBuilder>`, which a generic method could not be called through.
6
7use std::fmt::{self, Debug};
8use std::ops::Deref;
9use std::rc::Rc;
10use std::time::Duration;
11
12use waft_animation::{
13    Animatable, AnimationRef, Cubic, Curve, CurvedAnimation, Curves, Drive, ValueCurveTween,
14    ValueTween,
15};
16use waft_embedder::{Color, Offset, Size};
17use waft_foundation::{App, Handle, Listenable, MergingListenable, OptionRetained};
18use waft_painting::AlignmentGeometry;
19
20use crate::framework::{
21    BuildContext, IntoWidget, State, StateData, StatefulWidget, StatelessWidget, WidgetRef,
22};
23use crate::widgets::basic::{
24    Align, ClipRect, ColoredBox, FractionalTranslation, OverflowBox, SizedBox,
25};
26use crate::widgets::layout_builder::LayoutBuilder;
27use crate::widgets::pages::AnyPageRoute;
28use crate::widgets::transitions::{
29    AnimatedBuilder, DelegatedTransitionBuilder, FadeTransition, SlideTransition,
30};
31use waft_foundation::Ref;
32
33/// Defines a page transition animation for a [`PageRoute`](crate::PageRoute).
34///
35/// PageTransitionsBuilder can be used directly with widget layer primitives in any design
36/// system. Custom [`PageRoute`](crate::PageRoute) types can accept a PageTransitionsBuilder
37/// and delegate to its [`build_transitions`](Self::build_transitions) method when overriding
38/// [`ModalRoute::build_transitions`](crate::ModalRoute::build_transitions). This enables
39/// reusable transition animations that work with `Navigator` and other navigation primitives.
40///
41/// As an example of usage, in the Material library this trait is used by
42/// `PageTransitionsTheme` to define a `MaterialPageRoute` page transition animation. Apps can
43/// configure the map of builders for `ThemeData.pageTransitionsTheme` to customize the
44/// default `MaterialPageRoute` page transition animation for different platforms.
45///
46/// See also:
47///
48///  * `PageTransitionsTheme`, which uses this trait to configure page transitions.
49///  * `MaterialPageRoute`, which uses this trait to build its transition.
50///  * [`FadeUpwardsPageTransitionsBuilder`], which defines a page transition that's similar to
51///    the one provided by Android O.
52///  * [`OpenUpwardsPageTransitionsBuilder`], which defines a page transition that's similar to
53///    the one provided by Android P.
54///  * `ZoomPageTransitionsBuilder`, which defines the default page transition that's similar
55///    to the one provided in Android Q.
56///  * `CupertinoPageTransitionsBuilder`, which defines a horizontal page transition that
57///    matches native iOS page transitions.
58///  * `FadeForwardsPageTransitionsBuilder`, which defines a page transition that's similar to
59///    the one provided by Android U.
60pub trait PageTransitionsBuilder: Debug + 'static {
61    /// Provides a secondary transition to the previous route.
62    ///
63    /// See [`ModalRoute::delegated_transition`](crate::ModalRoute::delegated_transition).
64    fn delegated_transition(&self) -> Option<DelegatedTransitionBuilder> {
65        None
66    }
67
68    /// See [`TransitionRoute::transition_duration`](crate::TransitionRoute::transition_duration).
69    ///
70    /// Defaults to 300 milliseconds.
71    fn transition_duration(&self) -> Duration {
72        Duration::from_millis(300)
73    }
74
75    /// See
76    /// [`TransitionRoute::reverse_transition_duration`](crate::TransitionRoute::reverse_transition_duration).
77    ///
78    /// Defaults to 300 milliseconds.
79    fn reverse_transition_duration(&self) -> Duration {
80        self.transition_duration()
81    }
82
83    /// Wraps the child with one or more transition widgets which define how `route` arrives on
84    /// and leaves the screen.
85    ///
86    /// Implementors override this method to create a transition animation.
87    ///
88    /// The `MaterialPageRoute.buildTransitions` method is an example of a method that uses
89    /// this to build a transition. It looks up the current `PageTransitionsTheme` with
90    /// `Theme.of(context).pageTransitionsTheme` and delegates to this method with a
91    /// [`PageTransitionsBuilder`] based on the theme's `ThemeData.platform`.
92    fn build_transitions(
93        &self,
94        app: &mut App,
95        route: AnyPageRoute,
96        context: BuildContext,
97        animation: AnimationRef<f64>,
98        secondary_animation: AnimationRef<f64>,
99        child: WidgetRef,
100    ) -> WidgetRef;
101}
102
103/// A [`PageTransitionsBuilder`] held by value: what a Dart field, parameter or map value typed
104/// `PageTransitionsBuilder` becomes.
105///
106/// It compares by identity, as Dart's `==` on a builder does, so that a theme holding builders
107/// can compare them.
108#[derive(Clone)]
109pub struct PageTransitionsBuilderRef(Rc<dyn PageTransitionsBuilder>);
110
111impl PageTransitionsBuilderRef {
112    /// Erases a [`PageTransitionsBuilder`].
113    pub fn new(builder: impl PageTransitionsBuilder) -> PageTransitionsBuilderRef {
114        PageTransitionsBuilderRef(Rc::new(builder))
115    }
116}
117
118impl Deref for PageTransitionsBuilderRef {
119    type Target = dyn PageTransitionsBuilder;
120
121    fn deref(&self) -> &dyn PageTransitionsBuilder {
122        &*self.0
123    }
124}
125
126impl PartialEq for PageTransitionsBuilderRef {
127    fn eq(&self, other: &PageTransitionsBuilderRef) -> bool {
128        // Dart's `==` on a `PageTransitionsBuilder` is object identity.
129        Rc::ptr_eq(&self.0, &other.0)
130    }
131}
132
133impl Debug for PageTransitionsBuilderRef {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        Debug::fmt(&*self.0, f)
136    }
137}
138
139// Slides the page upwards and fades it in, starting from 1/4 screen below the top. The
140// transition is intended to match the default for Android O.
141struct FadeUpwardsPageTransition {
142    position_animation: AnimationRef<Offset>,
143    opacity_animation: AnimationRef<f64>,
144    child: WidgetRef,
145}
146
147impl FadeUpwardsPageTransition {
148    /// `route_animation` is the route's linear 0.0 - 1.0 animation.
149    fn new(
150        app: &mut App,
151        route_animation: AnimationRef<f64>,
152        child: WidgetRef,
153    ) -> FadeUpwardsPageTransition {
154        let position_animation = route_animation.drive(
155            app,
156            FadeUpwardsPageTransition::BOTTOM_UP_TWEEN
157                .chain(FadeUpwardsPageTransition::fast_out_slow_in_tween()),
158        );
159        let opacity_animation =
160            route_animation.drive(app, FadeUpwardsPageTransition::ease_in_tween());
161        FadeUpwardsPageTransition {
162            position_animation,
163            opacity_animation,
164            child,
165        }
166    }
167
168    // Fractional offset from 1/4 screen below the top to fully on screen.
169    const BOTTOM_UP_TWEEN: ValueTween<Offset> =
170        ValueTween::new(Offset::new(0.0, 0.25), Offset::ZERO);
171
172    fn fast_out_slow_in_tween() -> ValueCurveTween {
173        ValueCurveTween::new(Curves::fast_out_slow_in())
174    }
175
176    fn ease_in_tween() -> ValueCurveTween {
177        ValueCurveTween::new(Curves::ease_in())
178    }
179}
180
181impl Debug for FadeUpwardsPageTransition {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        f.write_str("_FadeUpwardsPageTransition")
184    }
185}
186
187impl StatelessWidget for FadeUpwardsPageTransition {
188    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
189        SlideTransition::new(self.position_animation.clone())
190            // TODO(ianh): tell the transform to be un-transformed for hit testing
191            .child(FadeTransition::new(self.opacity_animation.clone()).child(self.child.clone()))
192            .into_widget()
193    }
194}
195
196/// A page transition builder that animates incoming pages by fading and sliding them upwards.
197///
198/// This transition combines two animations:
199/// - A fade-in effect using an ease-in curve
200/// - An upward slide starting from 25% below the top of the screen
201///
202/// The resulting animation creates a smooth entrance effect where the new page appears to rise
203/// up while simultaneously becoming visible.
204///
205/// See also:
206///
207///  * [`OpenUpwardsPageTransitionsBuilder`], which defines a page transition that's similar to
208///    the one provided by Android P.
209///  * `ZoomPageTransitionsBuilder`, which defines the default page transition that's similar
210///    to the one provided in Android Q.
211///  * `CupertinoPageTransitionsBuilder`, which defines a horizontal page transition that
212///    matches native iOS page transitions.
213///  * `PredictiveBackPageTransitionsBuilder`, which defines a page transition that allows
214///    peeking behind the current route on Android U and above.
215#[derive(Clone, Copy, Debug, Default)]
216pub struct FadeUpwardsPageTransitionsBuilder;
217
218impl FadeUpwardsPageTransitionsBuilder {
219    /// Constructs a page transition animation that slides the page up.
220    pub const fn new() -> FadeUpwardsPageTransitionsBuilder {
221        FadeUpwardsPageTransitionsBuilder
222    }
223}
224
225impl PageTransitionsBuilder for FadeUpwardsPageTransitionsBuilder {
226    fn build_transitions(
227        &self,
228        app: &mut App,
229        _route: AnyPageRoute,
230        _context: BuildContext,
231        animation: AnimationRef<f64>,
232        _secondary_animation: AnimationRef<f64>,
233        child: WidgetRef,
234    ) -> WidgetRef {
235        FadeUpwardsPageTransition::new(app, animation, child).into_widget()
236    }
237}
238
239// This transition is intended to match the default for Android P.
240struct OpenUpwardsPageTransition {
241    animation: AnimationRef<f64>,
242    secondary_animation: AnimationRef<f64>,
243    child: WidgetRef,
244}
245
246impl OpenUpwardsPageTransition {
247    // The new page slides upwards just a little as its clip rectangle exposes the page from
248    // bottom to top.
249    const PRIMARY_TRANSLATION_TWEEN: ValueTween<Offset> =
250        ValueTween::new(Offset::new(0.0, 0.05), Offset::ZERO);
251
252    // The old page slides upwards a little as the new page appears.
253    const SECONDARY_TRANSLATION_TWEEN: ValueTween<Offset> =
254        ValueTween::new(Offset::ZERO, Offset::new(0.0, -0.025));
255
256    // The scrim color that obscures the old page during the transition.
257    const SCRIM_COLOR: Color = Color::new(0xFF000000);
258
259    // The scrim obscures the old page by becoming increasingly opaque.
260    const SCRIM_OPACITY_TWEEN: ValueTween<f64> = ValueTween::new(0.0, 0.25);
261
262    // Used by all of the transition animations.
263    const TRANSITION_CURVE: Cubic = Cubic::new(0.20, 0.00, 0.00, 1.00);
264
265    fn new(
266        animation: AnimationRef<f64>,
267        secondary_animation: AnimationRef<f64>,
268        child: WidgetRef,
269    ) -> OpenUpwardsPageTransition {
270        OpenUpwardsPageTransition {
271            animation,
272            secondary_animation,
273            child,
274        }
275    }
276
277    fn transition_curve() -> Rc<dyn Curve> {
278        Rc::new(OpenUpwardsPageTransition::TRANSITION_CURVE)
279    }
280}
281
282impl Debug for OpenUpwardsPageTransition {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        f.write_str("_OpenUpwardsPageTransition")
285    }
286}
287
288impl StatefulWidget for OpenUpwardsPageTransition {
289    type State = OpenUpwardsPageTransitionState;
290
291    fn create_state(&self) -> OpenUpwardsPageTransitionState {
292        OpenUpwardsPageTransitionState {
293            state: StateData::new(),
294            primary_animation: None,
295            secondary_translation_curved_animation: None,
296        }
297    }
298}
299
300/// Dart's `_OpenUpwardsPageTransitionState`.
301struct OpenUpwardsPageTransitionState {
302    state: StateData<OpenUpwardsPageTransition>,
303    primary_animation: Option<Ref<CurvedAnimation>>,
304    secondary_translation_curved_animation: Option<Ref<CurvedAnimation>>,
305}
306
307impl OpenUpwardsPageTransitionState {
308    fn set_animations(self: Handle<Self>, app: &mut App) {
309        let widget = self.widget(app);
310        let animation = widget.animation.clone();
311        let secondary_animation = widget.secondary_animation.clone();
312        let primary_animation = CurvedAnimation::new(
313            app,
314            animation,
315            OpenUpwardsPageTransition::transition_curve(),
316            Some(Rc::new(
317                OpenUpwardsPageTransition::transition_curve().flipped(),
318            )),
319        );
320        let secondary_translation_curved_animation = CurvedAnimation::new(
321            app,
322            secondary_animation,
323            OpenUpwardsPageTransition::transition_curve(),
324            Some(Rc::new(
325                OpenUpwardsPageTransition::transition_curve().flipped(),
326            )),
327        );
328        let state = app.get_mut(self);
329        state.primary_animation = Some(primary_animation);
330        state.secondary_translation_curved_animation = Some(secondary_translation_curved_animation);
331    }
332
333    fn dispose_animations(self: Handle<Self>, app: &mut App) {
334        let state = app.get(self);
335        let animations = [
336            state.primary_animation.handle(),
337            state.secondary_translation_curved_animation.handle(),
338        ];
339        for animation in animations.into_iter().flatten() {
340            animation.dispose(app);
341        }
342    }
343
344    /// The scrim, the clip and the two translations over the size the page is given.
345    fn build_for_constraints(self: Handle<Self>, app: &mut App, size: Size) -> WidgetRef {
346        let state = app.get(self);
347        let primary_animation: AnimationRef<f64> = state
348            .primary_animation
349            .as_ref()
350            .expect("init_state ran first")
351            .erase();
352        let secondary_translation_curved_animation: AnimationRef<f64> = state
353            .secondary_translation_curved_animation
354            .as_ref()
355            .expect("init_state ran first")
356            .erase();
357
358        // Gradually expose the new page from bottom to top.
359        let clip_animation =
360            ValueTween::new(0.0, size.height()).animate(app, primary_animation.clone());
361
362        let opacity_animation =
363            OpenUpwardsPageTransition::SCRIM_OPACITY_TWEEN.animate(app, primary_animation.clone());
364        let primary_translation_animation =
365            OpenUpwardsPageTransition::PRIMARY_TRANSLATION_TWEEN.animate(app, primary_animation);
366
367        let secondary_translation_animation =
368            OpenUpwardsPageTransition::SECONDARY_TRANSLATION_TWEEN
369                .animate(app, secondary_translation_curved_animation);
370
371        let widget = self.widget(app);
372        let animation: Rc<dyn Listenable> = Rc::new(widget.animation.clone());
373        let secondary_animation: Rc<dyn Listenable> = Rc::new(widget.secondary_animation.clone());
374        let merged = Rc::new(MergingListenable::new(vec![
375            Some(animation),
376            Some(secondary_animation),
377        ]));
378        AnimatedBuilder::new(merged, move |app, _context, _child| {
379            // Dart's `withOpacity`, deprecated there too: its rounding to an 8-bit alpha is
380            // part of the behaviour being ported.
381            #[allow(deprecated)]
382            let scrim_color =
383                OpenUpwardsPageTransition::SCRIM_COLOR.with_opacity(opacity_animation.value(app));
384            ColoredBox::new(scrim_color)
385                .child(
386                    Align::new()
387                        .alignment(AlignmentGeometry::BOTTOM_LEFT)
388                        .child(
389                            ClipRect::new().child(
390                                SizedBox::new().height(clip_animation.value(app)).child(
391                                    OverflowBox::new()
392                                        .alignment(AlignmentGeometry::BOTTOM_LEFT)
393                                        .max_height(size.height())
394                                        .child(
395                                            FractionalTranslation::new(
396                                                secondary_translation_animation.value(app),
397                                            )
398                                            .child(
399                                                FractionalTranslation::new(
400                                                    primary_translation_animation.value(app),
401                                                )
402                                                .child(self.widget(app).child.clone()),
403                                            ),
404                                        ),
405                                ),
406                            ),
407                        ),
408                )
409                .into_widget()
410        })
411        .into_widget()
412    }
413}
414
415impl State for OpenUpwardsPageTransitionState {
416    type Widget = OpenUpwardsPageTransition;
417    crate::state_accessors!();
418
419    fn init_state(self: Handle<Self>, app: &mut App) {
420        self.set_animations(app);
421    }
422
423    fn did_update_widget(
424        self: Handle<Self>,
425        app: &mut App,
426        old_widget: &OpenUpwardsPageTransition,
427    ) {
428        let widget = self.widget(app);
429        if old_widget.animation != widget.animation
430            || old_widget.secondary_animation != widget.secondary_animation
431        {
432            self.dispose_animations(app);
433            self.set_animations(app);
434        }
435    }
436
437    fn dispose(self: Handle<Self>, app: &mut App) {
438        self.dispose_animations(app);
439    }
440
441    fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
442        LayoutBuilder::new(move |app, _context, constraints| {
443            let size = constraints.biggest();
444            self.build_for_constraints(app, size)
445        })
446        .into_widget()
447    }
448}
449
450/// A page transition builder that animates incoming pages by revealing them from bottom to
451/// top with a clipping effect.
452///
453/// This transition combines several animations:
454/// - A clip animation that gradually reveals the new page from bottom to top
455/// - A subtle upward slide of the new page (5% translation)
456/// - A slight upward movement of the old page (2.5% translation)
457/// - A darkening scrim effect on the background
458///
459/// The resulting animation creates a layered effect where the new page appears to open upward
460/// from the bottom of the screen while the previous page slides back slightly.
461///
462/// See also:
463///
464///  * [`FadeUpwardsPageTransitionsBuilder`], which defines a page transition that's similar to
465///    the one provided by Android O.
466///  * `ZoomPageTransitionsBuilder`, which defines the default page transition that's similar
467///    to the one provided in Android Q.
468///  * `CupertinoPageTransitionsBuilder`, which defines a horizontal page transition that
469///    matches native iOS page transitions.
470///  * `PredictiveBackPageTransitionsBuilder`, which defines a page transition that allows
471///    peeking behind the current route on Android.
472///  * `FadeForwardsPageTransitionsBuilder`, which defines a page transition that's similar to
473///    the one provided by Android U.
474#[derive(Clone, Copy, Debug, Default)]
475pub struct OpenUpwardsPageTransitionsBuilder;
476
477impl OpenUpwardsPageTransitionsBuilder {
478    /// Constructs a page transition animation that matches the transition used on Android P.
479    pub const fn new() -> OpenUpwardsPageTransitionsBuilder {
480        OpenUpwardsPageTransitionsBuilder
481    }
482}
483
484impl PageTransitionsBuilder for OpenUpwardsPageTransitionsBuilder {
485    fn build_transitions(
486        &self,
487        _app: &mut App,
488        _route: AnyPageRoute,
489        _context: BuildContext,
490        animation: AnimationRef<f64>,
491        secondary_animation: AnimationRef<f64>,
492        child: WidgetRef,
493    ) -> WidgetRef {
494        OpenUpwardsPageTransition::new(animation, secondary_animation, child).into_widget()
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use std::cell::RefCell;
501    use std::collections::HashMap;
502    use waft_animation::AnimationRef;
503    use waft_animation::Drive;
504
505    use waft_embedder::TextDirection;
506    use waft_painting::TextStyle;
507
508    use super::*;
509    use crate::framework::GlobalKey;
510    use crate::testing::{
511        WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
512    };
513    use crate::widgets::basic::{Center, Directionality};
514    use crate::widgets::navigator::{Navigator, NavigatorState, RouteRef, RouteSettings};
515    use crate::widgets::pages::{PageRoute, PageRouteBuilder};
516    use crate::widgets::text::Text;
517    use crate::widgets::transitions::ScaleTransition;
518
519    /// The test's `_CustomPageRoute`: a page route whose transitions are `transitions_builder`'s,
520    /// handed the route itself.
521    fn custom_page_route(
522        app: &mut App,
523        settings: &RouteSettings,
524        transitions_builder: PageTransitionsBuilderRef,
525        builder: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static,
526    ) -> RouteRef {
527        let route = PageRouteBuilder::new(
528            app,
529            Rc::new(move |app, context, _animation, _secondary_animation| builder(app, context)),
530        )
531        .settings(app, settings.clone().into());
532        // The transitions builder lives on the route: it names the route without keeping it.
533        let page_route = PageRoute::as_page_route(route.handle());
534        let route = route.transitions_builder(
535            app,
536            Rc::new(move |app, context, animation, secondary_animation, child| {
537                transitions_builder.build_transitions(
538                    app,
539                    page_route,
540                    context,
541                    animation,
542                    secondary_animation,
543                    child,
544                )
545            }),
546        );
547        route.erase()
548    }
549
550    /// A navigator under the `Directionality` its overlay needs, building `route` for every
551    /// name.
552    fn navigator(
553        key: &GlobalKey,
554        route: impl Fn(&mut App, &RouteSettings) -> RouteRef + 'static,
555    ) -> WidgetRef {
556        Directionality::new(
557            TextDirection::Ltr,
558            Navigator::new()
559                .key(key.clone().into())
560                .on_generate_route(move |app, settings| Some(route(app, settings))),
561        )
562        .into_widget()
563    }
564
565    fn page_text(key: &GlobalKey, text: &str) -> WidgetRef {
566        Text::new(text)
567            .key(key.clone().into())
568            .style(
569                TextStyle::new()
570                    .color(Color::new(0xFFFFFFFF))
571                    .font_size(24.0),
572            )
573            .into_widget()
574    }
575
576    /// The test's two pages, `Page 1` on blue for `/` and `Page 2` on green for the rest, with
577    /// their texts under `page_1` and `page_2`.
578    fn two_pages(
579        page_1: &GlobalKey,
580        page_2: &GlobalKey,
581        settings: &RouteSettings,
582    ) -> impl Fn(&mut App, BuildContext) -> WidgetRef + 'static {
583        let first = settings.name.as_deref() == Some("/");
584        let page_1 = page_1.clone();
585        let page_2 = page_2.clone();
586        move |_app, _context| {
587            if first {
588                ColoredBox::new(Color::new(0xFF2196F3))
589                    .child(Center::new().child(page_text(&page_1, "Page 1")))
590                    .into_widget()
591            } else {
592                ColoredBox::new(Color::new(0xFF4CAF50))
593                    .child(Center::new().child(page_text(&page_2, "Page 2")))
594                    .into_widget()
595            }
596        }
597    }
598
599    fn state(key: &GlobalKey, tester: &WidgetTester) -> Handle<NavigatorState> {
600        key.current_state::<NavigatorState>(&tester.cell.borrow())
601            .expect("a mounted navigator")
602    }
603
604    /// The opacity of the `FadeTransition` nearest above the widget under `key`.
605    fn opacity_above(tester: &WidgetTester, key: &GlobalKey) -> f64 {
606        let app = tester.cell.borrow();
607        let context = key.current_context(&app).expect("the widget is mounted");
608        let opacity = context
609            .find_ancestor_widget_of_exact_type::<FadeTransition>(&app)
610            .expect("a FadeTransition above")
611            .opacity
612            .handle();
613        opacity.value(&app)
614    }
615
616    /// The test's `onBuildTransitions` signature: [`PageTransitionsBuilder::build_transitions`]'s.
617    type BuildTransitions = dyn Fn(
618        &mut App,
619        AnyPageRoute,
620        BuildContext,
621        AnimationRef<f64>,
622        AnimationRef<f64>,
623        WidgetRef,
624    ) -> WidgetRef;
625
626    /// The test's `_TestPageTransitionsBuilder`.
627    struct TestPageTransitionsBuilder {
628        on_build_transitions: Rc<BuildTransitions>,
629    }
630
631    impl Debug for TestPageTransitionsBuilder {
632        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
633            f.write_str("_TestPageTransitionsBuilder")
634        }
635    }
636
637    impl PageTransitionsBuilder for TestPageTransitionsBuilder {
638        fn build_transitions(
639            &self,
640            app: &mut App,
641            route: AnyPageRoute,
642            context: BuildContext,
643            animation: AnimationRef<f64>,
644            secondary_animation: AnimationRef<f64>,
645            child: WidgetRef,
646        ) -> WidgetRef {
647            (self.on_build_transitions)(app, route, context, animation, secondary_animation, child)
648        }
649    }
650
651    /// The opacity and the scale animation of one route's transition.
652    type RouteTransition = (AnimationRef<f64>, AnimationRef<f64>);
653
654    #[test]
655    fn page_transitions_builder_works_with_custom_navigator_and_page_route() {
656        test_widgets(|tester| {
657            // The opacity and scale animations of each route's transition, by route name.
658            let transitions: Rc<RefCell<HashMap<String, RouteTransition>>> = Rc::default();
659            let custom_transitions_builder =
660                PageTransitionsBuilderRef::new(TestPageTransitionsBuilder {
661                    on_build_transitions: Rc::new({
662                        let transitions = Rc::clone(&transitions);
663                        move |app, route, _context, animation, _secondary_animation, child| {
664                            let curve_tween =
665                                waft_animation::CurveTween::new(app, Curves::ease_in_out());
666                            let scale_tween = waft_animation::Tween::new(app, Some(0.5), Some(1.0));
667                            let scale = animation.drive(app, scale_tween.chain(curve_tween));
668                            let name = route.as_route().settings(app).name().map(str::to_string);
669                            transitions.borrow_mut().insert(
670                                name.expect("a named route"),
671                                (animation.clone(), scale.clone()),
672                            );
673                            FadeTransition::new(animation)
674                                .child(ScaleTransition::new(scale).child(child))
675                                .into_widget()
676                        }
677                    }),
678                });
679            let key = GlobalKey::new();
680            let navigate = GlobalKey::new();
681            let second_page = GlobalKey::new();
682            tester.pump_widget(navigator(&key, {
683                let navigate = navigate.clone();
684                let second_page = second_page.clone();
685                move |app, settings| {
686                    let first = settings.name.as_deref() == Some("/");
687                    let navigate = navigate.clone();
688                    let second_page = second_page.clone();
689                    custom_page_route(
690                        app,
691                        settings,
692                        custom_transitions_builder.clone(),
693                        move |_app, _context| {
694                            if first {
695                                Center::new()
696                                    .child(SizedBox::new().width(200.0).height(50.0).child(
697                                        ColoredBox::new(Color::new(0xFF2196F3)).child(
698                                            Center::new().child(page_text(&navigate, "Navigate")),
699                                        ),
700                                    ))
701                                    .into_widget()
702                            } else {
703                                ColoredBox::new(Color::new(0xFF4CAF50))
704                                    .child(
705                                        Center::new().child(page_text(&second_page, "Second Page")),
706                                    )
707                                    .into_widget()
708                            }
709                        },
710                    )
711                }
712            }));
713            expect(tester, &find::text("Navigate"), finds_one_widget());
714            expect(tester, &find::text("Second Page"), finds_nothing());
715
716            // Flutter taps the "Navigate" box, whose handler pushes `/second`.
717            let navigator_state = state(&key, tester);
718            tester.update(|app| navigator_state.push_named(app, "/second", None));
719            tester.pump();
720
721            expect(tester, &find::text("Navigate"), finds_one_widget());
722            expect(tester, &find::text("Second Page"), finds_one_widget());
723
724            tester.pump_by(Duration::from_millis(50));
725
726            // Each route was handed to `build_transitions` as itself (the first Flutter case's
727            // `capturedRoute!.settings.name`).
728            let mut names: Vec<String> = transitions.borrow().keys().cloned().collect();
729            names.sort();
730            assert_eq!(names, ["/", "/second"]);
731            {
732                let app = tester.cell.borrow();
733                for (opacity, scale) in transitions.borrow().values() {
734                    let opacity = opacity.value(&app);
735                    assert!(opacity > 0.0 && opacity <= 1.0, "opacity {opacity}");
736                    let scale = scale.value(&app);
737                    assert!((0.5..=1.0).contains(&scale), "scale {scale}");
738                }
739            }
740
741            tester.pump_and_settle();
742
743            expect(tester, &find::text("Navigate"), finds_nothing());
744            expect(tester, &find::text("Second Page"), finds_one_widget());
745        });
746    }
747
748    /// The test's navigator whose two pages, `Page 1` and `Page 2`, take their transitions from
749    /// `builder`, pumped; answers the navigator's state.
750    fn pump_two_pages(
751        tester: &mut WidgetTester,
752        builder: PageTransitionsBuilderRef,
753        page_1: &GlobalKey,
754        page_2: &GlobalKey,
755    ) -> Handle<NavigatorState> {
756        let key = GlobalKey::new();
757        tester.pump_widget(navigator(&key, {
758            let page_1 = page_1.clone();
759            let page_2 = page_2.clone();
760            move |app, settings| {
761                let pages = two_pages(&page_1, &page_2, settings);
762                custom_page_route(app, settings, builder.clone(), pages)
763            }
764        }));
765        state(&key, tester)
766    }
767
768    #[test]
769    fn fade_upwards_page_transitions_builder_test() {
770        test_widgets(|tester| {
771            let page_1 = GlobalKey::new();
772            let page_2 = GlobalKey::new();
773            let builder = PageTransitionsBuilderRef::new(FadeUpwardsPageTransitionsBuilder::new());
774            let navigator_state = pump_two_pages(tester, builder, &page_1, &page_2);
775            let widget_1_top_left = tester.get_top_left(&page_1);
776
777            // Flutter taps "Page 1", whose handler pushes `/second`.
778            tester.update(|app| navigator_state.push_named(app, "/second", None));
779            tester.pump();
780            tester.pump_by(Duration::from_millis(1));
781
782            let widget_2_opacity = opacity_above(tester, &page_2);
783            let widget_2_top_left = tester.get_top_left(&page_2);
784
785            assert!(widget_1_top_left.dx() == widget_2_top_left.dx());
786            assert!(widget_1_top_left.dy() < widget_2_top_left.dy());
787            assert!(widget_2_opacity < 0.01);
788
789            tester.pump_by(Duration::from_millis(300));
790
791            expect(tester, &find::text("Page 1"), finds_nothing());
792            expect(tester, &find::text("Page 2"), finds_one_widget());
793
794            tester.update(|app| navigator_state.pop(app, None));
795            tester.pump();
796            tester.pump_by(Duration::from_millis(1));
797
798            let widget_2_opacity = opacity_above(tester, &page_2);
799            let widget_2_top_left = tester.get_top_left(&page_2);
800
801            assert!(widget_1_top_left.dy() < widget_2_top_left.dy());
802            assert!(widget_2_opacity < 1.0);
803
804            tester.pump_by(Duration::from_millis(300));
805
806            expect(tester, &find::text("Page 1"), finds_one_widget());
807            expect(tester, &find::text("Page 2"), finds_nothing());
808        });
809    }
810
811    /// Checks that a frame 100 ms into a push with `builder` leaves no new arena objects.
812    fn assert_a_mid_push_frame_leaves_nothing(builder: fn() -> PageTransitionsBuilderRef) {
813        test_widgets(|tester| {
814            let page_1 = GlobalKey::new();
815            let page_2 = GlobalKey::new();
816            let navigator_state = pump_two_pages(tester, builder(), &page_1, &page_2);
817            tester.update(|app| navigator_state.push_named(app, "/second", None));
818            tester.pump();
819            tester.pump_by(Duration::from_millis(100));
820            tester.assert_leaves_nothing_behind(|tester| tester.pump_by(Duration::from_millis(16)));
821        });
822    }
823
824    /// Not a Dart case: the animations each frame's `_FadeUpwardsPageTransition` drives go with
825    /// the last transition that reads them, as Dart's collector frees them.
826    #[test]
827    fn a_frame_of_a_fade_upwards_push_leaves_no_new_arena_objects() {
828        assert_a_mid_push_frame_leaves_nothing(|| {
829            PageTransitionsBuilderRef::new(FadeUpwardsPageTransitionsBuilder::new())
830        });
831    }
832
833    /// Not a Dart case: the animations each layout of `_OpenUpwardsPageTransition` drives go
834    /// with the last builder that reads them, as Dart's collector frees them.
835    #[test]
836    fn a_frame_of_an_open_upwards_push_leaves_no_new_arena_objects() {
837        assert_a_mid_push_frame_leaves_nothing(|| {
838            PageTransitionsBuilderRef::new(OpenUpwardsPageTransitionsBuilder::new())
839        });
840    }
841
842    #[test]
843    fn open_upwards_page_transitions_builder_test() {
844        test_widgets(|tester| {
845            let page_1 = GlobalKey::new();
846            let page_2 = GlobalKey::new();
847            let builder = PageTransitionsBuilderRef::new(OpenUpwardsPageTransitionsBuilder::new());
848            let navigator_state = pump_two_pages(tester, builder, &page_1, &page_2);
849            let widget_1_top_left = tester.get_top_left(&page_1);
850
851            // Flutter taps "Page 1", whose handler pushes `/second`.
852            tester.update(|app| navigator_state.push_named(app, "/second", None));
853            tester.pump();
854            tester.pump_by(Duration::from_millis(1));
855
856            expect(tester, &find::text("Page 1"), finds_one_widget());
857            expect(tester, &find::text("Page 2"), finds_one_widget());
858
859            let widget_2_top_left = tester.get_top_left(&page_2);
860
861            assert_eq!(widget_1_top_left.dx(), widget_2_top_left.dx());
862            assert!(widget_1_top_left.dy() <= widget_2_top_left.dy());
863
864            tester.pump_by(Duration::from_millis(300));
865
866            // After animation, only Page 2 should be visible.
867            expect(tester, &find::text("Page 1"), finds_nothing());
868            expect(tester, &find::text("Page 2"), finds_one_widget());
869
870            tester.update(|app| navigator_state.pop(app, None));
871            tester.pump();
872            tester.pump_by(Duration::from_millis(1));
873
874            expect(tester, &find::text("Page 1"), finds_one_widget());
875            expect(tester, &find::text("Page 2"), finds_one_widget());
876
877            tester.pump_by(Duration::from_millis(300));
878
879            // After reverse animation, only Page 1 should be visible.
880            expect(tester, &find::text("Page 1"), finds_one_widget());
881            expect(tester, &find::text("Page 2"), finds_nothing());
882        });
883    }
884}