Skip to main content

waft_widgets/widgets/
dual_transition_builder.rs

1//! Flutter counterpart: `widgets/dual_transition_builder.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_animation::{
7    AnimationRef, AnimationStatus, AnimationStatusListener, ProxyAnimation, ReverseAnimation,
8    k_always_complete_animation, k_always_dismissed_animation,
9};
10use waft_foundation::{App, Handle, OptionRetained, Ref};
11
12use crate::framework::{
13    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
14};
15
16/// Builder callback used by [`DualTransitionBuilder`].
17///
18/// The builder is expected to return a transition powered by the provided
19/// `animation` and wrapping the provided `child`.
20///
21/// The `animation` provided to the builder always runs forward from 0.0 to 1.0.
22///
23/// An optional `child` widget which represents a pre-built widget subtree that
24/// does not depend on the animation's value.
25///
26/// Passing a pre-built widget here and incorporating it into the returned
27/// widget tree avoids rebuilding it for every frame of the animation and
28/// can improve performance significantly in some cases.
29pub type AnimatedTransitionBuilder =
30    Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>, Option<&WidgetRef>) -> WidgetRef>;
31
32/// A transition builder that animates its [`child`](Self::child) based on the
33/// [`AnimationStatus`] of the provided [`animation`](Self::animation).
34///
35/// This widget can be used to specify different enter and exit transitions for
36/// a [`child`](Self::child).
37///
38/// While the [`animation`](Self::animation) runs forward, the [`child`](Self::child) is
39/// animated according to [`forward_builder`](Self::forward_builder) and while the
40/// [`animation`](Self::animation) is running in reverse, it is animated according to
41/// [`reverse_builder`](Self::reverse_builder).
42///
43/// Using this builder allows the widget tree to maintain its shape by nesting
44/// the enter and exit transitions. This ensures that no state information of
45/// any descendant widget is lost when the transition starts or completes.
46pub struct DualTransitionBuilder {
47    pub key: Option<KeyRef>,
48
49    /// The animation that drives the [`child`](Self::child)'s transition.
50    ///
51    /// When this animation runs forward, the [`child`](Self::child) transitions as specified
52    /// by [`forward_builder`](Self::forward_builder). When it runs in reverse, the child
53    /// transitions according to [`reverse_builder`](Self::reverse_builder).
54    pub animation: AnimationRef<f64>,
55
56    /// A builder for the transition that makes [`child`](Self::child) appear on screen.
57    ///
58    /// The [`child`](Self::child) should be fully visible when the provided `animation`
59    /// reaches 1.0.
60    ///
61    /// The `animation` provided to this builder is running forward from 0.0 to
62    /// 1.0 when [`animation`](Self::animation) runs _forward_. When
63    /// [`animation`](Self::animation) runs in reverse, the given `animation` is set to
64    /// `k_always_complete_animation`.
65    ///
66    /// See also:
67    ///
68    ///  * [`reverse_builder`](Self::reverse_builder), which builds the transition for making
69    ///    the [`child`](Self::child) disappear from the screen.
70    pub forward_builder: AnimatedTransitionBuilder,
71
72    /// A builder for a transition that makes [`child`](Self::child) disappear from the
73    /// screen.
74    ///
75    /// The [`child`](Self::child) should be fully invisible when the provided `animation`
76    /// reaches 1.0.
77    ///
78    /// The `animation` provided to this builder is running forward from 0.0 to
79    /// 1.0 when [`animation`](Self::animation) runs in _reverse_. When
80    /// [`animation`](Self::animation) runs forward, the given `animation` is set to
81    /// `k_always_dismissed_animation`.
82    ///
83    /// See also:
84    ///
85    ///  * [`forward_builder`](Self::forward_builder), which builds the transition for making
86    ///    the [`child`](Self::child) appear on screen.
87    pub reverse_builder: AnimatedTransitionBuilder,
88
89    /// The widget below this [`DualTransitionBuilder`] in the tree.
90    ///
91    /// This child widget will be wrapped by the transitions built by
92    /// [`forward_builder`](Self::forward_builder) and
93    /// [`reverse_builder`](Self::reverse_builder).
94    ///
95    /// If a pre-built subtree is provided as the [`child`](Self::child), it will be passed to
96    /// the [`reverse_builder`](Self::reverse_builder), and the result of that will in turn be
97    /// passed to the [`forward_builder`](Self::forward_builder). This allows the builders to
98    /// incorporate the subtree without rebuilding it on every frame.
99    ///
100    /// Using this pre-built child is entirely optional, but can improve
101    /// performance significantly in some cases and is therefore a good practice.
102    pub child: Option<WidgetRef>,
103}
104
105impl Debug for DualTransitionBuilder {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.debug_struct("DualTransitionBuilder")
108            .field("key", &self.key)
109            .field("animation", &self.animation)
110            .field("child", &self.child)
111            .finish_non_exhaustive()
112    }
113}
114
115impl DualTransitionBuilder {
116    /// Creates a [`DualTransitionBuilder`].
117    pub fn new(
118        animation: AnimationRef<f64>,
119        forward_builder: impl Fn(
120            &mut App,
121            BuildContext,
122            AnimationRef<f64>,
123            Option<&WidgetRef>,
124        ) -> WidgetRef
125        + 'static,
126        reverse_builder: impl Fn(
127            &mut App,
128            BuildContext,
129            AnimationRef<f64>,
130            Option<&WidgetRef>,
131        ) -> WidgetRef
132        + 'static,
133    ) -> DualTransitionBuilder {
134        DualTransitionBuilder {
135            key: None,
136            animation,
137            forward_builder: Rc::new(forward_builder),
138            reverse_builder: Rc::new(reverse_builder),
139            child: None,
140        }
141    }
142
143    /// Dart `DualTransitionBuilder(key:)`.
144    pub fn key(mut self, key: KeyRef) -> DualTransitionBuilder {
145        self.key = Some(key);
146        self
147    }
148
149    /// Dart `DualTransitionBuilder(child:)`.
150    #[cfg_attr(debug_assertions, track_caller)]
151    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> DualTransitionBuilder {
152        self.child = Some(child.into_widget());
153        self
154    }
155}
156
157impl StatefulWidget for DualTransitionBuilder {
158    type State = DualTransitionBuilderState;
159
160    fn key(&self) -> Option<&KeyRef> {
161        self.key.as_ref()
162    }
163
164    fn create_state(&self) -> DualTransitionBuilderState {
165        DualTransitionBuilderState {
166            state: StateData::new(),
167            effective_animation_status: AnimationStatus::Dismissed,
168            forward_animation: None,
169            reverse_animation: None,
170        }
171    }
172}
173
174/// Dart's `_DualTransitionBuilderState`.
175///
176/// The two proxies are Dart's field initialisers; they need the `App`, so `init_state` makes
177/// them before anything reads them.
178pub struct DualTransitionBuilderState {
179    state: StateData<DualTransitionBuilder>,
180    effective_animation_status: AnimationStatus,
181    forward_animation: Option<Ref<ProxyAnimation>>,
182    reverse_animation: Option<Ref<ProxyAnimation>>,
183}
184
185impl Debug for DualTransitionBuilderState {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        f.debug_struct("DualTransitionBuilderState")
188            .finish_non_exhaustive()
189    }
190}
191
192impl DualTransitionBuilderState {
193    fn forward_animation(self: Handle<Self>, app: &App) -> Handle<ProxyAnimation> {
194        app.get(self)
195            .forward_animation
196            .handle()
197            .expect("created in init_state")
198    }
199
200    fn reverse_animation(self: Handle<Self>, app: &App) -> Handle<ProxyAnimation> {
201        app.get(self)
202            .reverse_animation
203            .handle()
204            .expect("created in init_state")
205    }
206
207    fn animation_listener(self: Handle<Self>, app: &mut App, animation_status: AnimationStatus) {
208        let old_effective = app.get(self).effective_animation_status;
209        let effective = calculate_effective_animation_status(old_effective, animation_status);
210        app.get_mut(self).effective_animation_status = effective;
211        if old_effective != effective {
212            self.update_animations(app);
213        }
214    }
215
216    fn update_animations(self: Handle<Self>, app: &mut App) {
217        let animation = self.widget(app).animation.clone();
218        let forward_animation = self.forward_animation(app);
219        let reverse_animation = self.reverse_animation(app);
220        match app.get(self).effective_animation_status {
221            AnimationStatus::Dismissed | AnimationStatus::Forward => {
222                forward_animation.set_parent(app, Some(animation));
223                let dismissed = k_always_dismissed_animation(app);
224                reverse_animation.set_parent(app, Some(dismissed));
225            }
226            AnimationStatus::Reverse | AnimationStatus::Completed => {
227                let complete = k_always_complete_animation(app);
228                forward_animation.set_parent(app, Some(complete));
229                let reversed = ReverseAnimation::new(app, animation);
230                reverse_animation.set_parent(app, Some(reversed.into_erased()));
231            }
232        }
233    }
234}
235
236/// When a transition is interrupted midway we just want to play the ongoing
237/// animation in reverse. Switching to the actual reverse transition would
238/// yield a disjoint experience since the forward and reverse transitions are
239/// very different.
240fn calculate_effective_animation_status(
241    last_effective: AnimationStatus,
242    current: AnimationStatus,
243) -> AnimationStatus {
244    match current {
245        AnimationStatus::Dismissed | AnimationStatus::Completed => current,
246        AnimationStatus::Forward => match last_effective {
247            AnimationStatus::Dismissed | AnimationStatus::Completed | AnimationStatus::Forward => {
248                current
249            }
250            AnimationStatus::Reverse => last_effective,
251        },
252        AnimationStatus::Reverse => match last_effective {
253            AnimationStatus::Dismissed | AnimationStatus::Completed | AnimationStatus::Reverse => {
254                current
255            }
256            AnimationStatus::Forward => last_effective,
257        },
258    }
259}
260
261impl State for DualTransitionBuilderState {
262    type Widget = DualTransitionBuilder;
263    crate::state_accessors!();
264
265    fn init_state(self: Handle<Self>, app: &mut App) {
266        let forward_animation = ProxyAnimation::new(app, None);
267        let reverse_animation = ProxyAnimation::new(app, None);
268        let state = app.get_mut(self);
269        state.forward_animation = Some(forward_animation);
270        state.reverse_animation = Some(reverse_animation);
271        let animation = self.widget(app).animation.handle();
272        app.get_mut(self).effective_animation_status = animation.status(app);
273        animation.add_status_listener(
274            app,
275            AnimationStatusListener::handle_method(self, Self::animation_listener),
276        );
277        self.update_animations(app);
278    }
279
280    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &DualTransitionBuilder) {
281        let animation = self.widget(app).animation.handle();
282        if old_widget.animation != animation {
283            old_widget.animation.remove_status_listener(
284                app,
285                &AnimationStatusListener::handle_method(self, Self::animation_listener),
286            );
287            animation.add_status_listener(
288                app,
289                AnimationStatusListener::handle_method(self, Self::animation_listener),
290            );
291            let status = animation.status(app);
292            self.animation_listener(app, status);
293        }
294    }
295
296    fn dispose(self: Handle<Self>, app: &mut App) {
297        let animation = self.widget(app).animation.handle();
298        animation.remove_status_listener(
299            app,
300            &AnimationStatusListener::handle_method(self, Self::animation_listener),
301        );
302    }
303
304    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
305        let widget = self.widget(app);
306        let forward_builder = Rc::clone(&widget.forward_builder);
307        let reverse_builder = Rc::clone(&widget.reverse_builder);
308        let child = widget.child.clone();
309        let state = app.get(self);
310        let forward_animation: AnimationRef<f64> = state
311            .forward_animation
312            .as_ref()
313            .expect("created in init_state")
314            .erase();
315        let reverse_animation: AnimationRef<f64> = state
316            .reverse_animation
317            .as_ref()
318            .expect("created in init_state")
319            .erase();
320        let reversed = reverse_builder(app, context, reverse_animation, child.as_ref());
321        forward_builder(app, context, forward_animation, Some(&reversed))
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use std::cell::Cell;
328    use std::time::Duration;
329    use waft_animation::Drive;
330    use waft_foundation::Ref;
331
332    use waft_animation::{AnimationBehavior, AnimationController, AnyAnimation, Tween};
333    use waft_embedder::Color;
334
335    use super::*;
336    use crate::testing::{TestVSync, WidgetTester, test_widgets};
337    use crate::widgets::basic::{Center, SizedBox};
338    use crate::widgets::container::Container;
339    use crate::widgets::transitions::{FadeTransition, ScaleTransition};
340
341    /// What the two builders were last given: Dart's `_getScale` and `_getOpacity` read the
342    /// `ScaleTransition` and `FadeTransition` the builders return, whose animations these are.
343    #[derive(Clone, Default)]
344    struct Observed {
345        scale: Rc<Cell<Option<AnyAnimation<f64>>>>,
346        opacity: Rc<Cell<Option<AnyAnimation<f64>>>>,
347    }
348
349    impl Observed {
350        fn scale(&self, app: &App) -> f64 {
351            self.scale.get().expect("built").value(app)
352        }
353
354        fn opacity(&self, app: &App) -> f64 {
355            self.opacity.get().expect("built").value(app)
356        }
357    }
358
359    fn controller(app: &mut App, value: Option<f64>) -> Ref<AnimationController> {
360        AnimationController::new(
361            app,
362            value,
363            Some(Duration::from_millis(300)),
364            None,
365            0.0,
366            1.0,
367            AnimationBehavior::Normal,
368            TestVSync,
369        )
370    }
371
372    fn tree(animation: AnimationRef<f64>, observed: &Observed, child: WidgetRef) -> WidgetRef {
373        let scale = Rc::clone(&observed.scale);
374        let opacity = Rc::clone(&observed.opacity);
375        Center::new()
376            .child(
377                DualTransitionBuilder::new(
378                    animation,
379                    move |_app, _context, animation, child| {
380                        scale.set(Some(animation.handle()));
381                        ScaleTransition::new(animation)
382                            .child(child.expect("a child").clone())
383                            .into_widget()
384                    },
385                    move |app, _context, animation, child| {
386                        let tween = Tween::new(app, Some(1.0), Some(0.0));
387                        let faded = animation.drive(app, tween);
388                        opacity.set(Some(faded.handle()));
389                        FadeTransition::new(faded)
390                            .child(child.expect("a child").clone())
391                            .into_widget()
392                    },
393                )
394                .child(child),
395            )
396            .into_widget()
397    }
398
399    fn green_box() -> WidgetRef {
400        Container::new()
401            .color(Color::new(0xFF00FF00))
402            .height(100.0)
403            .width(100.0)
404            .into_widget()
405    }
406
407    fn ms(millis: u64) -> Duration {
408        Duration::from_millis(millis)
409    }
410
411    fn assert_scale_and_opacity(
412        tester: &WidgetTester,
413        observed: &Observed,
414        scale: f64,
415        opacity: f64,
416    ) {
417        let app = tester.cell.borrow();
418        assert_eq!(observed.scale(&app), scale);
419        assert_eq!(observed.opacity(&app), opacity);
420    }
421
422    /// Pumps the tree for `controller`.
423    fn pump_tree(
424        tester: &mut WidgetTester,
425        controller: &Ref<AnimationController>,
426        child: WidgetRef,
427    ) -> Observed {
428        let observed = Observed::default();
429        tester.pump_widget(tree(controller.erase(), &observed, child));
430        observed
431    }
432
433    #[test]
434    fn runs_animations() {
435        test_widgets(|tester| {
436            let controller = tester.update(|app| controller(app, None));
437            let observed = pump_tree(tester, &controller, green_box());
438            assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
439
440            tester.update(|app| controller.forward(app, None));
441            tester.pump();
442            tester.pump_by(ms(150));
443            assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
444
445            tester.pump_by(ms(150));
446            assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
447
448            tester.pump_by(ms(300));
449            assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
450
451            tester.update(|app| controller.reverse(app, None));
452            tester.pump();
453            tester.pump_by(ms(150));
454            assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
455
456            tester.pump_by(ms(150));
457            assert_scale_and_opacity(tester, &observed, 1.0, 0.0);
458
459            tester.pump_by(ms(300));
460            assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
461            tester.update(|app| controller.dispose(app));
462        });
463    }
464
465    /// Not a Dart case: the proxies and the `ReverseAnimation` a state made are freed once the
466    /// unmounted tree lets go of them, as Dart's collector frees them.
467    #[test]
468    fn a_disposed_state_frees_its_proxies_and_reverse_animation() {
469        test_widgets(|tester| {
470            let controller = tester.update(|app| controller(app, Some(1.0)));
471            let forward: Rc<Cell<Option<AnyAnimation<f64>>>> = Rc::default();
472            let reverse: Rc<Cell<Option<AnyAnimation<f64>>>> = Rc::default();
473            let tree = {
474                let (forward, reverse) = (Rc::clone(&forward), Rc::clone(&reverse));
475                DualTransitionBuilder::new(
476                    controller.erase(),
477                    move |_app, _context, animation, child| {
478                        forward.set(Some(animation.handle()));
479                        child.cloned().expect("a child")
480                    },
481                    move |_app, _context, animation, child| {
482                        reverse.set(Some(animation.handle()));
483                        child.cloned().expect("a child")
484                    },
485                )
486                .child(green_box())
487                .into_widget()
488            };
489            tester.pump_widget(Center::new().child(tree));
490            let proxies = [forward, reverse].map(|built| built.get().expect("the builder ran"));
491            let reverse_parent = {
492                let app = tester.cell.borrow();
493                let reverse = app
494                    .handle::<ProxyAnimation>(proxies[1].id())
495                    .expect("the reverse proxy");
496                reverse
497                    .parent(&app)
498                    .expect("a completed animation is reversed")
499            };
500
501            tester.pump_widget(SizedBox::new());
502            let app = tester.cell.borrow();
503            for freed in [proxies[0].id(), proxies[1].id(), reverse_parent.id()] {
504                assert!(!app.contains(freed), "{freed:?} is freed");
505            }
506            assert!(
507                app.contains(&controller),
508                "the widget's animation is its owner's"
509            );
510        });
511    }
512
513    #[test]
514    fn keeps_state() {
515        test_widgets(|tester| {
516            let controller = tester.update(|app| controller(app, None));
517            let probe = Probe::default();
518            pump_tree(tester, &controller, probe.widget());
519            assert_eq!((probe.inits.get(), probe.disposes.get()), (1, 0));
520
521            for direction in [AnimationController::forward, AnimationController::reverse] {
522                tester.update(|app| direction(controller.handle(), app, None));
523                for step in [0, 150, 150, 300] {
524                    tester.pump_by(ms(step));
525                    assert_eq!((probe.inits.get(), probe.disposes.get()), (1, 0));
526                }
527            }
528            tester.update(|app| controller.dispose(app));
529        });
530    }
531
532    #[test]
533    fn does_not_jump_when_interrupted_forward() {
534        test_widgets(|tester| {
535            let controller = tester.update(|app| controller(app, None));
536            let observed = pump_tree(tester, &controller, green_box());
537            assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
538
539            tester.update(|app| controller.forward(app, None));
540            tester.pump();
541            tester.pump_by(ms(150));
542            assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
543
544            tester.update(|app| controller.reverse(app, None));
545            assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
546            tester.pump();
547            assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
548
549            tester.pump_by(ms(75));
550            assert_scale_and_opacity(tester, &observed, 0.25, 1.0);
551
552            tester.pump_by(ms(75));
553            assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
554
555            tester.pump_by(ms(300));
556            assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
557            tester.update(|app| controller.dispose(app));
558        });
559    }
560
561    #[test]
562    fn does_not_jump_when_interrupted_reverse() {
563        test_widgets(|tester| {
564            let controller = tester.update(|app| controller(app, Some(1.0)));
565            let observed = pump_tree(tester, &controller, green_box());
566            assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
567
568            tester.update(|app| controller.reverse(app, None));
569            tester.pump();
570            tester.pump_by(ms(150));
571            assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
572
573            tester.update(|app| controller.forward(app, None));
574            assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
575            tester.pump();
576            assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
577
578            tester.pump_by(ms(75));
579            assert_scale_and_opacity(tester, &observed, 1.0, 0.75);
580
581            tester.pump_by(ms(75));
582            assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
583
584            tester.pump_by(ms(300));
585            assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
586            tester.update(|app| controller.dispose(app));
587        });
588    }
589
590    /// Dart's `_StatefulTestWidget`, counting its state's life: `same(state)` is one `init_state`
591    /// and no `dispose`.
592    #[derive(Clone, Default)]
593    struct Probe {
594        inits: Rc<Cell<u32>>,
595        disposes: Rc<Cell<u32>>,
596    }
597
598    impl Probe {
599        fn widget(&self) -> WidgetRef {
600            ProbeWidget {
601                probe: self.clone(),
602            }
603            .into_widget()
604        }
605    }
606
607    #[derive(Debug)]
608    struct ProbeWidget {
609        probe: Probe,
610    }
611
612    impl Debug for Probe {
613        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614            f.write_str("Probe")
615        }
616    }
617
618    impl StatefulWidget for ProbeWidget {
619        type State = ProbeState;
620
621        fn create_state(&self) -> ProbeState {
622            ProbeState {
623                state: StateData::new(),
624            }
625        }
626    }
627
628    struct ProbeState {
629        state: StateData<ProbeWidget>,
630    }
631
632    impl State for ProbeState {
633        type Widget = ProbeWidget;
634        crate::state_accessors!();
635
636        fn init_state(self: Handle<Self>, app: &mut App) {
637            let inits = &self.widget(app).probe.inits;
638            inits.set(inits.get() + 1);
639        }
640
641        fn dispose(self: Handle<Self>, app: &mut App) {
642            let disposes = &self.widget(app).probe.disposes;
643            disposes.set(disposes.get() + 1);
644        }
645
646        fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
647            SizedBox::new().width(10.0).height(10.0).into_widget()
648        }
649    }
650}