Skip to main content

waft_widgets/widgets/
animated_cross_fade.rs

1//! Flutter counterpart: `widgets/animated_cross_fade.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_animation::{
8    AnimationBehavior, AnimationController, AnimationRef, AnimationStatusListener, Curve,
9    CurveTween, Curves, Drive, Tween,
10};
11use waft_embedder::Clip;
12use waft_foundation::{
13    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, EnumProperty, Handle, IntProperty,
14    Listener, OptionRetained, ValueKey,
15};
16use waft_painting::AlignmentGeometry;
17use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
18
19use crate::framework::{
20    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
21};
22use crate::widgets::animated_size::AnimatedSize;
23use crate::widgets::basic::{ClipRect, ExcludeSemantics, IgnorePointer, Positioned, Stack};
24use crate::widgets::focus_scope::ExcludeFocus;
25use crate::widgets::ticker_provider::{
26    TickerMode, TickerProviderStateMixin, TickerProviderStateMixinData,
27};
28use crate::widgets::transitions::FadeTransition;
29use waft_foundation::Ref;
30
31/// Specifies which of two children to show. See [`AnimatedCrossFade`].
32///
33/// The child that is shown will fade in, while the other will fade out.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub enum CrossFadeState {
36    /// Show the first child ([`AnimatedCrossFade::first_child`]) and hide the second
37    /// ([`AnimatedCrossFade::second_child`]).
38    ShowFirst,
39
40    /// Show the second child ([`AnimatedCrossFade::second_child`]) and hide the first
41    /// ([`AnimatedCrossFade::first_child`]).
42    ShowSecond,
43}
44
45/// Signature for the [`AnimatedCrossFade::layout_builder`] callback.
46///
47/// The `top_child` is the child fading in, which is normally drawn on top. The
48/// `bottom_child` is the child fading out, normally drawn on the bottom.
49///
50/// For good performance, the returned widget tree should contain both the
51/// `top_child` and the `bottom_child`; the depth of the tree, and the types of
52/// the widgets in the tree, from the returned widget to each of the children
53/// should be the same; and where there is a widget with multiple children, the
54/// top child and the bottom child should be keyed using the provided
55/// `top_child_key` and `bottom_child_key` keys respectively.
56///
57/// See [`AnimatedCrossFade::default_layout_builder`] for the default.
58pub type AnimatedCrossFadeBuilder =
59    Rc<dyn Fn(&mut App, &WidgetRef, &KeyRef, &WidgetRef, &KeyRef) -> WidgetRef>;
60
61/// A widget that cross-fades between two given children and animates itself
62/// between their sizes.
63///
64/// The animation is controlled through the [`cross_fade_state`](Self::cross_fade_state)
65/// parameter. [`first_curve`](Self::first_curve) and [`second_curve`](Self::second_curve)
66/// represent the opacity curves of the two children. The
67/// [`first_curve`](Self::first_curve) is inverted, i.e. it fades out when providing a
68/// growing curve like `Curves::linear`. The [`size_curve`](Self::size_curve) is the curve
69/// used to animate between the size of the fading-out child and the size of the fading-in
70/// child.
71///
72/// This widget is intended to be used to fade a pair of widgets with the same
73/// width. In the case where the two children have different heights, the
74/// animation crops overflowing children during the animation by aligning their
75/// top edge, which means that the bottom will be clipped.
76///
77/// The animation is automatically triggered when an existing
78/// [`AnimatedCrossFade`] is rebuilt with a different value for the
79/// [`cross_fade_state`](Self::cross_fade_state) property.
80///
81/// See also:
82///
83///  * `AnimatedOpacity`, which fades between nothing and a single child.
84///  * `AnimatedSwitcher`, which switches out a child for a new one with a
85///    customizable transition, supporting multiple cross-fades at once.
86///  * [`AnimatedSize`], the lower-level widget which [`AnimatedCrossFade`] uses to
87///    automatically change size.
88pub struct AnimatedCrossFade {
89    pub key: Option<KeyRef>,
90
91    /// The child that is visible when [`cross_fade_state`](Self::cross_fade_state) is
92    /// [`CrossFadeState::ShowFirst`]. It fades out when transitioning
93    /// [`cross_fade_state`](Self::cross_fade_state) from [`CrossFadeState::ShowFirst`] to
94    /// [`CrossFadeState::ShowSecond`] and vice versa.
95    pub first_child: WidgetRef,
96
97    /// The child that is visible when [`cross_fade_state`](Self::cross_fade_state) is
98    /// [`CrossFadeState::ShowSecond`]. It fades in when transitioning
99    /// [`cross_fade_state`](Self::cross_fade_state) from [`CrossFadeState::ShowFirst`] to
100    /// [`CrossFadeState::ShowSecond`] and vice versa.
101    pub second_child: WidgetRef,
102
103    /// The child that will be shown when the animation has completed.
104    pub cross_fade_state: CrossFadeState,
105
106    /// The duration of the whole orchestrated animation.
107    pub duration: Duration,
108
109    /// The duration of the whole orchestrated animation when running in reverse.
110    ///
111    /// If not supplied, this defaults to [`duration`](Self::duration).
112    pub reverse_duration: Option<Duration>,
113
114    /// The fade curve of the first child.
115    ///
116    /// Defaults to `Curves::linear`.
117    pub first_curve: Rc<dyn Curve>,
118
119    /// The fade curve of the second child.
120    ///
121    /// Defaults to `Curves::linear`.
122    pub second_curve: Rc<dyn Curve>,
123
124    /// The curve of the animation between the two children's sizes.
125    ///
126    /// Defaults to `Curves::linear`.
127    pub size_curve: Rc<dyn Curve>,
128
129    /// How the children should be aligned while the size is animating.
130    ///
131    /// Defaults to `Alignment::TOP_CENTER`.
132    ///
133    /// See also:
134    ///
135    ///  * `Alignment`, a class with convenient constants typically used to
136    ///    specify an [`AlignmentGeometry`].
137    ///  * `AlignmentDirectional`, like `Alignment` for specifying alignments
138    ///    relative to text direction.
139    pub alignment: AlignmentGeometry,
140
141    /// A builder that positions the [`first_child`](Self::first_child) and
142    /// [`second_child`](Self::second_child) widgets.
143    ///
144    /// The widget returned by this method is wrapped in an [`AnimatedSize`].
145    ///
146    /// By default, this uses [`AnimatedCrossFade::default_layout_builder`], which uses
147    /// a [`Stack`] and aligns the `bottom_child` to the top of the stack while
148    /// providing the `top_child` as the non-positioned child to fill the provided
149    /// constraints. This works well when the [`AnimatedCrossFade`] is in a position
150    /// to change size and when the children are not flexible. However, if the
151    /// children are less fussy about their sizes (for example a
152    /// `CircularProgressIndicator` inside a `Center`), or if the
153    /// [`AnimatedCrossFade`] is being forced to a particular size, then it can
154    /// result in the widgets jumping about when the cross-fade state is changed.
155    pub layout_builder: AnimatedCrossFadeBuilder,
156
157    /// When true, this is equivalent to wrapping the bottom widget with an [`ExcludeFocus`]
158    /// widget while it is at the bottom of the cross-fade stack.
159    ///
160    /// Defaults to true. When it is false, the bottom widget in the cross-fade stack
161    /// can remain in focus until the top widget requests focus. This is useful for
162    /// animating between different `TextField`s so the keyboard remains open during the
163    /// cross-fade animation.
164    pub exclude_bottom_focus: bool,
165
166    /// Controls whether the content is clipped during the cross-fade transition.
167    ///
168    /// During the size transition between [`first_child`](Self::first_child) and
169    /// [`second_child`](Self::second_child), the content is clipped by default to prevent it
170    /// from overflowing the bounding box of the animating widget.
171    ///
172    /// Set this to [`Clip::None`] to disable clipping entirely. This can be
173    /// useful for widgets with shadows or visual effects that extend beyond
174    /// their bounds.
175    ///
176    /// Defaults to [`Clip::HardEdge`].
177    pub clip_behavior: Clip,
178
179    /// Called every time an animation completes.
180    ///
181    /// This can be useful to trigger additional actions (e.g. another animation)
182    /// at the end of the current animation.
183    pub on_end: Option<Listener>,
184}
185
186impl Debug for AnimatedCrossFade {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.debug_struct("AnimatedCrossFade")
189            .field("key", &self.key)
190            .field("cross_fade_state", &self.cross_fade_state)
191            .field("alignment", &self.alignment)
192            .field("duration", &self.duration)
193            .field("reverse_duration", &self.reverse_duration)
194            .finish_non_exhaustive()
195    }
196}
197
198impl AnimatedCrossFade {
199    /// Creates a cross-fade animation widget.
200    ///
201    /// The [`duration`](Self::duration) of the animation is the same for all components (fade
202    /// in, fade out, and size), and you can pass `Interval`s instead of `Curve`s in order to
203    /// have finer control, e.g., creating an overlap between the fades.
204    #[cfg_attr(debug_assertions, track_caller)]
205    pub fn new<F, S>(
206        first_child: impl IntoWidget<F>,
207        second_child: impl IntoWidget<S>,
208        cross_fade_state: CrossFadeState,
209        duration: Duration,
210    ) -> AnimatedCrossFade {
211        AnimatedCrossFade {
212            key: None,
213            first_child: first_child.into_widget(),
214            second_child: second_child.into_widget(),
215            cross_fade_state,
216            duration,
217            reverse_duration: None,
218            first_curve: Curves::linear(),
219            second_curve: Curves::linear(),
220            size_curve: Curves::linear(),
221            alignment: AlignmentGeometry::TOP_CENTER,
222            layout_builder: Rc::new(AnimatedCrossFade::default_layout_builder),
223            exclude_bottom_focus: true,
224            clip_behavior: Clip::HardEdge,
225            on_end: None,
226        }
227    }
228
229    /// Dart `AnimatedCrossFade(key:)`.
230    pub fn key(mut self, key: KeyRef) -> AnimatedCrossFade {
231        self.key = Some(key);
232        self
233    }
234
235    /// Dart `AnimatedCrossFade(reverseDuration:)`.
236    pub fn reverse_duration(mut self, reverse_duration: Duration) -> AnimatedCrossFade {
237        self.reverse_duration = Some(reverse_duration);
238        self
239    }
240
241    /// Dart `AnimatedCrossFade(firstCurve:)`.
242    pub fn first_curve(mut self, first_curve: Rc<dyn Curve>) -> AnimatedCrossFade {
243        self.first_curve = first_curve;
244        self
245    }
246
247    /// Dart `AnimatedCrossFade(secondCurve:)`.
248    pub fn second_curve(mut self, second_curve: Rc<dyn Curve>) -> AnimatedCrossFade {
249        self.second_curve = second_curve;
250        self
251    }
252
253    /// Dart `AnimatedCrossFade(sizeCurve:)`.
254    pub fn size_curve(mut self, size_curve: Rc<dyn Curve>) -> AnimatedCrossFade {
255        self.size_curve = size_curve;
256        self
257    }
258
259    /// Dart `AnimatedCrossFade(alignment:)`.
260    pub fn alignment(mut self, alignment: AlignmentGeometry) -> AnimatedCrossFade {
261        self.alignment = alignment;
262        self
263    }
264
265    /// Dart `AnimatedCrossFade(layoutBuilder:)`.
266    pub fn layout_builder(
267        mut self,
268        layout_builder: impl Fn(&mut App, &WidgetRef, &KeyRef, &WidgetRef, &KeyRef) -> WidgetRef
269        + 'static,
270    ) -> AnimatedCrossFade {
271        self.layout_builder = Rc::new(layout_builder);
272        self
273    }
274
275    /// Dart `AnimatedCrossFade(excludeBottomFocus:)`.
276    pub fn exclude_bottom_focus(mut self, exclude_bottom_focus: bool) -> AnimatedCrossFade {
277        self.exclude_bottom_focus = exclude_bottom_focus;
278        self
279    }
280
281    /// Dart `AnimatedCrossFade(clipBehavior:)`.
282    pub fn clip_behavior(mut self, clip_behavior: Clip) -> AnimatedCrossFade {
283        self.clip_behavior = clip_behavior;
284        self
285    }
286
287    /// Dart `AnimatedCrossFade(onEnd:)`.
288    pub fn on_end(mut self, on_end: Listener) -> AnimatedCrossFade {
289        self.on_end = Some(on_end);
290        self
291    }
292
293    /// The default layout algorithm used by [`AnimatedCrossFade`].
294    ///
295    /// The top child is placed in a stack that sizes itself to match the top
296    /// child. The bottom child is positioned at the top of the same stack, sized
297    /// to fit its width but without forcing the height. The stack is then
298    /// clipped.
299    ///
300    /// This is the default value for [`layout_builder`](Self::layout_builder). It implements
301    /// [`AnimatedCrossFadeBuilder`].
302    pub fn default_layout_builder(
303        _app: &mut App,
304        top_child: &WidgetRef,
305        top_child_key: &KeyRef,
306        bottom_child: &WidgetRef,
307        bottom_child_key: &KeyRef,
308    ) -> WidgetRef {
309        Stack::new()
310            .clip_behavior(Clip::None)
311            .children([
312                Positioned::new(bottom_child.clone())
313                    .key(bottom_child_key.clone())
314                    .left(0.0)
315                    .top(0.0)
316                    .right(0.0)
317                    .into_widget(),
318                Positioned::new(top_child.clone())
319                    .key(top_child_key.clone())
320                    .into_widget(),
321            ])
322            .into_widget()
323    }
324}
325
326impl StatefulWidget for AnimatedCrossFade {
327    type State = AnimatedCrossFadeState;
328
329    fn key(&self) -> Option<&KeyRef> {
330        self.key.as_ref()
331    }
332
333    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
334        properties.add(EnumProperty::new("crossFadeState", self.cross_fade_state));
335        properties.add(
336            DiagnosticsProperty::<AlignmentGeometry>::new("alignment", Some(self.alignment))
337                .default_value(Some(AlignmentGeometry::TOP_CENTER)),
338        );
339        properties.add(IntProperty::new("duration", self.duration.as_millis() as i64).unit("ms"));
340        properties.add(
341            IntProperty::<i64>::new(
342                "reverseDuration",
343                self.reverse_duration
344                    .map(|duration| duration.as_millis() as i64),
345            )
346            .unit("ms")
347            .default_value(None),
348        );
349    }
350
351    fn create_state(&self) -> AnimatedCrossFadeState {
352        AnimatedCrossFadeState {
353            state: StateData::new(),
354            ticker_provider: TickerProviderStateMixinData::new(),
355            controller: None,
356            first_animation: None,
357            second_animation: None,
358        }
359    }
360}
361
362/// Dart's `_AnimatedCrossFadeState`; its `late` fields are set by `init_state`.
363pub struct AnimatedCrossFadeState {
364    state: StateData<AnimatedCrossFade>,
365    ticker_provider: TickerProviderStateMixinData,
366    controller: Option<Ref<AnimationController>>,
367    first_animation: Option<AnimationRef<f64>>,
368    second_animation: Option<AnimationRef<f64>>,
369}
370
371impl Debug for AnimatedCrossFadeState {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        f.debug_struct("AnimatedCrossFadeState")
374            .finish_non_exhaustive()
375    }
376}
377
378impl TickerProviderStateMixin for AnimatedCrossFadeState {
379    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
380        &app.get(self).ticker_provider
381    }
382
383    fn ticker_provider_data_mut(
384        self: Handle<Self>,
385        app: &mut App,
386    ) -> &mut TickerProviderStateMixinData {
387        &mut app.get_mut(self).ticker_provider
388    }
389}
390
391impl TickerProviderObject for AnimatedCrossFadeState {
392    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
393        TickerProviderStateMixin::create_ticker(self, app, on_tick)
394    }
395}
396
397impl AnimatedCrossFadeState {
398    fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
399        app.get(self)
400            .controller
401            .handle()
402            .expect("created in init_state")
403    }
404
405    fn init_animation(
406        self: Handle<Self>,
407        app: &mut App,
408        curve: Rc<dyn Curve>,
409        inverted: bool,
410    ) -> AnimationRef<f64> {
411        let curve_tween = CurveTween::new(app, curve);
412        let controller = app
413            .get(self)
414            .controller
415            .clone()
416            .expect("created in init_state");
417        let mut result = controller.drive(app, curve_tween);
418        if inverted {
419            let tween = Tween::new(app, Some(1.0), Some(0.0));
420            result = result.drive(app, tween);
421        }
422        result
423    }
424}
425
426impl State for AnimatedCrossFadeState {
427    type Widget = AnimatedCrossFade;
428    crate::state_accessors!();
429
430    fn debug_fill_properties(
431        self: Handle<Self>,
432        app: &App,
433        properties: &mut DiagnosticPropertiesBuilder,
434    ) {
435        let widget = self.widget(app);
436        properties.add(EnumProperty::new("crossFadeState", widget.cross_fade_state));
437        properties.add(
438            DiagnosticsProperty::<String>::new(
439                "controller",
440                app.get(self)
441                    .controller
442                    .as_ref()
443                    .map(|controller| controller.handle().to_string(app)),
444            )
445            .with_show_name(false),
446        );
447        properties.add(
448            DiagnosticsProperty::<AlignmentGeometry>::new("alignment", Some(widget.alignment))
449                .default_value(Some(AlignmentGeometry::TOP_CENTER)),
450        );
451        properties.add(
452            EnumProperty::new("clipBehavior", widget.clip_behavior)
453                .default_value(Some(Clip::HardEdge)),
454        );
455    }
456
457    fn init_state(self: Handle<Self>, app: &mut App) {
458        let widget = self.widget(app);
459        let duration = widget.duration;
460        let reverse_duration = widget.reverse_duration;
461        let cross_fade_state = widget.cross_fade_state;
462        let first_curve = Rc::clone(&widget.first_curve);
463        let second_curve = Rc::clone(&widget.second_curve);
464        let controller = AnimationController::new(
465            app,
466            None,
467            Some(duration),
468            reverse_duration,
469            0.0,
470            1.0,
471            AnimationBehavior::Normal,
472            self,
473        );
474        app.get_mut(self).controller = Some(controller.clone());
475        if cross_fade_state == CrossFadeState::ShowSecond {
476            controller.set_value(app, 1.0);
477        }
478        let first_animation = self.init_animation(app, first_curve, true);
479        let second_animation = self.init_animation(app, second_curve, false);
480        let state = app.get_mut(self);
481        state.first_animation = Some(first_animation);
482        state.second_animation = Some(second_animation);
483        controller.view().add_status_listener(
484            app,
485            AnimationStatusListener::new(move |status, app| {
486                self.set_state(app, |_state| {
487                    // Trigger a rebuild because it depends on _isTransitioning, which
488                    // changes its value together with animation status.
489                });
490                if (status.is_completed() || status.is_dismissed())
491                    && let Some(on_end) = self.widget(app).on_end.clone()
492                {
493                    on_end.call(app);
494                }
495            }),
496        );
497    }
498
499    fn activate(self: Handle<Self>, app: &mut App) {
500        TickerProviderStateMixin::activate(self, app);
501    }
502
503    fn dispose(self: Handle<Self>, app: &mut App) {
504        self.controller(app).dispose(app);
505        TickerProviderStateMixin::dispose(self, app);
506    }
507
508    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedCrossFade) {
509        let widget = self.widget(app);
510        let duration = widget.duration;
511        let reverse_duration = widget.reverse_duration;
512        let first_curve = Rc::clone(&widget.first_curve);
513        let second_curve = Rc::clone(&widget.second_curve);
514        let cross_fade_state = widget.cross_fade_state;
515        let controller = self.controller(app);
516        if duration != old_widget.duration {
517            app.get_mut(controller).duration = Some(duration);
518        }
519        if reverse_duration != old_widget.reverse_duration {
520            app.get_mut(controller).reverse_duration = reverse_duration;
521        }
522        if !Rc::ptr_eq(&first_curve, &old_widget.first_curve) {
523            let first_animation = self.init_animation(app, first_curve, true);
524            app.get_mut(self).first_animation = Some(first_animation);
525        }
526        if !Rc::ptr_eq(&second_curve, &old_widget.second_curve) {
527            let second_animation = self.init_animation(app, second_curve, false);
528            app.get_mut(self).second_animation = Some(second_animation);
529        }
530        if cross_fade_state != old_widget.cross_fade_state {
531            match cross_fade_state {
532                CrossFadeState::ShowFirst => {
533                    controller.reverse(app, None);
534                }
535                CrossFadeState::ShowSecond => {
536                    controller.forward(app, None);
537                }
538            }
539        }
540    }
541
542    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
543        let first_child_key: KeyRef = ValueKey::new(CrossFadeState::ShowFirst).into();
544        let second_child_key: KeyRef = ValueKey::new(CrossFadeState::ShowSecond).into();
545        let widget = self.widget(app);
546        let first_child = widget.first_child.clone();
547        let second_child = widget.second_child.clone();
548        let exclude_bottom_focus = widget.exclude_bottom_focus;
549        let clip_behavior = widget.clip_behavior;
550        let alignment = widget.alignment;
551        let duration = widget.duration;
552        let reverse_duration = widget.reverse_duration;
553        let size_curve = Rc::clone(&widget.size_curve);
554        let layout_builder = Rc::clone(&widget.layout_builder);
555        let first_animation = app
556            .get(self)
557            .first_animation
558            .clone()
559            .expect("created in init_state");
560        let second_animation = app
561            .get(self)
562            .second_animation
563            .clone()
564            .expect("created in init_state");
565        let controller = self.controller(app);
566        let top_key;
567        let top_child;
568        let top_animation;
569        let bottom_key;
570        let bottom_child;
571        let bottom_animation;
572        if controller.status(app).is_forward_or_completed() {
573            top_key = second_child_key;
574            top_child = second_child;
575            top_animation = second_animation;
576            bottom_key = first_child_key;
577            bottom_child = first_child;
578            bottom_animation = first_animation;
579        } else {
580            top_key = first_child_key;
581            top_child = first_child;
582            top_animation = first_animation;
583            bottom_key = second_child_key;
584            bottom_child = second_child;
585            bottom_animation = second_animation;
586        }
587
588        let bottom_child = TickerMode::new(
589            controller.is_animating(app),
590            IgnorePointer::new().child(
591                // Always exclude the semantics of the widget that's fading out.
592                ExcludeSemantics::new().child(
593                    ExcludeFocus::new(FadeTransition::new(bottom_animation).child(bottom_child))
594                        .excluding(exclude_bottom_focus),
595                ),
596            ),
597        )
598        .key(bottom_key.clone())
599        .into_widget();
600        let top_child = TickerMode::new(
601            true, // Top widget always has its animations enabled.
602            IgnorePointer::new().ignoring(false).child(
603                ExcludeSemantics::new()
604                    // Always publish semantics for the widget that's fading in.
605                    .excluding(false)
606                    .child(
607                        ExcludeFocus::new(FadeTransition::new(top_animation).child(top_child))
608                            .excluding(false),
609                    ),
610            ),
611        )
612        .key(top_key.clone())
613        .into_widget();
614        let layout = layout_builder(app, &top_child, &top_key, &bottom_child, &bottom_key);
615        let mut animated_size = AnimatedSize::new(duration)
616            .alignment(alignment)
617            .curve(size_curve)
618            .clip_behavior(clip_behavior)
619            .child(layout);
620        if let Some(reverse_duration) = reverse_duration {
621            animated_size = animated_size.reverse_duration(reverse_duration);
622        }
623        ClipRect::new()
624            .clip_behavior(clip_behavior)
625            .child(animated_size)
626            .into_widget()
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use std::cell::Cell;
633
634    use waft_embedder::{Offset, Size, TextDirection};
635    use waft_foundation::UniqueKey;
636    use waft_scheduler::FrameCallback;
637
638    use super::*;
639    use crate::testing::{
640        WidgetTester, expect, find, finds_n_widgets, finds_nothing, finds_one_widget, test_widgets,
641    };
642    use crate::widgets::actions::FocusableActionDetector;
643    use crate::widgets::basic::{Builder, Center, Directionality, Semantics, SizedBox};
644    use crate::widgets::container::Container;
645    use crate::widgets::focus_scope::Focus;
646    use crate::widgets::gesture_detector::GestureDetector;
647    use crate::widgets::text::Text;
648    use crate::widgets::ticker_provider::{
649        SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
650    };
651
652    fn ms(milliseconds: u64) -> Duration {
653        Duration::from_millis(milliseconds)
654    }
655
656    fn sized(width: f64, height: f64) -> WidgetRef {
657        SizedBox::new().width(width).height(height).into_widget()
658    }
659
660    fn keyed(key: &KeyRef, width: f64, height: f64) -> WidgetRef {
661        SizedBox::new()
662            .key(key.clone())
663            .width(width)
664            .height(height)
665            .into_widget()
666    }
667
668    fn centered(text_direction: TextDirection, cross_fade: AnimatedCrossFade) -> WidgetRef {
669        Directionality::new(text_direction, Center::new().child(cross_fade)).into_widget()
670    }
671
672    fn simple_cross_fade(state: CrossFadeState) -> AnimatedCrossFade {
673        AnimatedCrossFade::new(sized(100.0, 100.0), sized(200.0, 200.0), state, ms(200))
674    }
675
676    #[test]
677    fn animates_between_the_sizes_of_its_children() {
678        test_widgets(|tester| {
679            tester.pump_widget(centered(
680                TextDirection::Ltr,
681                simple_cross_fade(CrossFadeState::ShowFirst),
682            ));
683            expect(
684                tester,
685                &find::by_type::<FadeTransition>(),
686                finds_n_widgets(2),
687            );
688            assert_eq!(
689                tester.get_size(find::by_type::<AnimatedCrossFade>()),
690                Size::new(100.0, 100.0)
691            );
692
693            tester.pump_widget(centered(
694                TextDirection::Ltr,
695                simple_cross_fade(CrossFadeState::ShowSecond),
696            ));
697            tester.pump_by(ms(100));
698
699            expect(
700                tester,
701                &find::by_type::<FadeTransition>(),
702                finds_n_widgets(2),
703            );
704            assert_eq!(
705                tester.get_size(find::by_type::<AnimatedCrossFade>()),
706                Size::new(150.0, 150.0)
707            );
708        });
709    }
710
711    #[test]
712    fn show_second_starts_at_the_size_of_the_second_child() {
713        test_widgets(|tester| {
714            tester.pump_widget(centered(
715                TextDirection::Ltr,
716                simple_cross_fade(CrossFadeState::ShowSecond),
717            ));
718            expect(
719                tester,
720                &find::by_type::<FadeTransition>(),
721                finds_n_widgets(2),
722            );
723            assert_eq!(
724                tester.get_size(find::by_type::<AnimatedCrossFade>()),
725                Size::new(200.0, 200.0)
726            );
727        });
728    }
729
730    /// The first and second children keep their places in the stack while the size animates:
731    /// `alignment` and the text direction decide where both sit.
732    fn assert_aligned_halfway(
733        text_direction: TextDirection,
734        alignment: AlignmentGeometry,
735        expected: Offset,
736    ) {
737        test_widgets(|tester| {
738            let (first_key, second_key): (KeyRef, KeyRef) =
739                (UniqueKey::new().into(), UniqueKey::new().into());
740            let tree = |state: CrossFadeState| {
741                centered(
742                    text_direction,
743                    AnimatedCrossFade::new(
744                        keyed(&first_key, 100.0, 100.0),
745                        keyed(&second_key, 200.0, 200.0),
746                        state,
747                        ms(200),
748                    )
749                    .alignment(alignment),
750                )
751            };
752            tester.pump_widget(tree(CrossFadeState::ShowFirst));
753            tester.pump_widget(tree(CrossFadeState::ShowSecond));
754            tester.pump_by(ms(100));
755
756            assert_eq!(
757                tester.get_top_left(find::by_key(first_key.clone())),
758                expected
759            );
760            assert_eq!(
761                tester.get_top_left(find::by_key(second_key.clone())),
762                expected
763            );
764        });
765    }
766
767    #[test]
768    fn alignment_visual() {
769        assert_aligned_halfway(
770            TextDirection::Ltr,
771            AlignmentGeometry::BOTTOM_RIGHT,
772            Offset::new(275.0, 175.0),
773        );
774    }
775
776    #[test]
777    fn alignment_ltr() {
778        assert_aligned_halfway(
779            TextDirection::Ltr,
780            AlignmentGeometry::BOTTOM_END,
781            Offset::new(275.0, 175.0),
782        );
783    }
784
785    #[test]
786    fn alignment_rtl() {
787        assert_aligned_halfway(
788            TextDirection::Rtl,
789            AlignmentGeometry::BOTTOM_END,
790            Offset::new(325.0, 175.0),
791        );
792    }
793
794    /// Dart's `_TickerWatchingWidget`: a state with a started ticker of its own.
795    #[derive(Debug)]
796    struct TickerWatching {
797        ticker: Rc<Cell<Option<Handle<Ticker>>>>,
798        inits: Rc<Cell<u32>>,
799    }
800
801    impl StatefulWidget for TickerWatching {
802        type State = TickerWatchingState;
803
804        fn create_state(&self) -> TickerWatchingState {
805            TickerWatchingState {
806                state: StateData::new(),
807                single_ticker_provider: SingleTickerProviderStateMixinData::new(),
808            }
809        }
810    }
811
812    struct TickerWatchingState {
813        state: StateData<TickerWatching>,
814        single_ticker_provider: SingleTickerProviderStateMixinData,
815    }
816
817    impl SingleTickerProviderStateMixin for TickerWatchingState {
818        fn single_ticker_provider_data(
819            self: Handle<Self>,
820            app: &App,
821        ) -> &SingleTickerProviderStateMixinData {
822            &app.get(self).single_ticker_provider
823        }
824
825        fn single_ticker_provider_data_mut(
826            self: Handle<Self>,
827            app: &mut App,
828        ) -> &mut SingleTickerProviderStateMixinData {
829            &mut app.get_mut(self).single_ticker_provider
830        }
831    }
832
833    impl TickerProviderObject for TickerWatchingState {
834        fn create_ticker(
835            self: Handle<Self>,
836            app: &mut App,
837            on_tick: TickerCallback,
838        ) -> Ref<Ticker> {
839            SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
840        }
841    }
842
843    impl State for TickerWatchingState {
844        type Widget = TickerWatching;
845        crate::state_accessors!();
846
847        fn init_state(self: Handle<Self>, app: &mut App) {
848            let ticker = SingleTickerProviderStateMixin::create_ticker(
849                self,
850                app,
851                FrameCallback::new(|_app, _elapsed| {}),
852            );
853            ticker.start(app);
854            let widget = self.widget(app);
855            widget.ticker.set(Some(ticker.handle()));
856            widget.inits.set(widget.inits.get() + 1);
857        }
858
859        fn activate(self: Handle<Self>, app: &mut App) {
860            SingleTickerProviderStateMixin::activate(self, app);
861        }
862
863        fn dispose(self: Handle<Self>, app: &mut App) {
864            let ticker = self
865                .widget(app)
866                .ticker
867                .get()
868                .expect("started in init_state");
869            ticker.dispose(app);
870            SingleTickerProviderStateMixin::dispose(self, app);
871        }
872
873        fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
874            Container::new().into_widget()
875        }
876    }
877
878    struct Watcher {
879        ticker: Rc<Cell<Option<Handle<Ticker>>>>,
880        inits: Rc<Cell<u32>>,
881    }
882
883    impl Watcher {
884        fn new() -> Watcher {
885            Watcher {
886                ticker: Rc::default(),
887                inits: Rc::default(),
888            }
889        }
890
891        fn cross_fade(&self, towards_second: bool) -> WidgetRef {
892            let first_child = TickerWatching {
893                ticker: Rc::clone(&self.ticker),
894                inits: Rc::clone(&self.inits),
895            };
896            Directionality::new(
897                TextDirection::Ltr,
898                AnimatedCrossFade::new(
899                    first_child,
900                    Container::new(),
901                    if towards_second {
902                        CrossFadeState::ShowSecond
903                    } else {
904                        CrossFadeState::ShowFirst
905                    },
906                    ms(50),
907                ),
908            )
909            .into_widget()
910        }
911
912        fn ticker(&self) -> Handle<Ticker> {
913            self.ticker.get().expect("the watching state started it")
914        }
915    }
916
917    #[test]
918    fn preserves_widget_state() {
919        test_widgets(|tester| {
920            let watcher = Watcher::new();
921            tester.pump_widget(watcher.cross_fade(false));
922            assert_eq!(watcher.inits.get(), 1);
923
924            tester.pump_widget(watcher.cross_fade(true));
925            for _ in 0..3 {
926                tester.pump_by(ms(25));
927                assert_eq!(watcher.inits.get(), 1);
928            }
929        });
930    }
931
932    #[test]
933    fn switches_off_ticker_mode_on_the_faded_out_widget() {
934        test_widgets(|tester| {
935            let watcher = Watcher::new();
936            tester.pump_widget(watcher.cross_fade(false));
937            assert!(!watcher.ticker().muted(&tester.cell.borrow()));
938
939            tester.pump_widget(watcher.cross_fade(true));
940            for _ in 0..2 {
941                tester.pump_by(ms(25));
942                // Animations are kept alive in the middle of cross-fade
943                assert!(!watcher.ticker().muted(&tester.cell.borrow()));
944            }
945
946            // In the final state animations should be off on the widget that's faded out.
947            tester.pump_by(ms(25));
948            assert!(watcher.ticker().muted(&tester.cell.borrow()));
949        });
950    }
951
952    #[test]
953    fn layout_builder_decides_which_children_are_in_the_tree() {
954        test_widgets(|tester| {
955            let (first, second): (KeyRef, KeyRef) =
956                (UniqueKey::new().into(), UniqueKey::new().into());
957            let tree = |state: CrossFadeState, only_top: bool| {
958                let mut cross_fade = AnimatedCrossFade::new(
959                    keyed(&first, 10.0, 10.0),
960                    keyed(&second, 10.0, 10.0),
961                    state,
962                    ms(50),
963                );
964                if only_top {
965                    cross_fade =
966                        cross_fade.layout_builder(|_app, top_child, _, _, _| top_child.clone());
967                }
968                Directionality::new(TextDirection::Ltr, cross_fade).into_widget()
969            };
970            tester.pump_widget(tree(CrossFadeState::ShowFirst, false));
971            expect(tester, &find::by_key(first.clone()), finds_one_widget());
972            expect(tester, &find::by_key(second.clone()), finds_one_widget());
973
974            tester.pump_widget(tree(CrossFadeState::ShowFirst, true));
975            expect(tester, &find::by_key(first.clone()), finds_one_widget());
976            expect(tester, &find::by_key(second.clone()), finds_nothing());
977
978            tester.pump_widget(tree(CrossFadeState::ShowSecond, true));
979            expect(tester, &find::by_key(second.clone()), finds_one_widget());
980            expect(tester, &find::by_key(first.clone()), finds_nothing());
981        });
982    }
983
984    /// The `Focus` nodes of the two children, as `Focus.of(tester.element(find.text(..)))` finds
985    /// them.
986    fn focus_tree(
987        exclude_bottom_focus: Option<bool>,
988        nodes: &Rc<[Cell<Option<crate::widgets::focus_manager::AnyFocusNode>>; 2]>,
989    ) -> WidgetRef {
990        let probe = |index: usize| {
991            let nodes = Rc::clone(nodes);
992            Focus::new(Builder::new(move |app, context| {
993                nodes[index].set(Some(Focus::of(app, context, true, false)));
994                SizedBox::shrink().into_widget()
995            }))
996            .into_widget()
997        };
998        let mut cross_fade =
999            AnimatedCrossFade::new(probe(0), probe(1), CrossFadeState::ShowFirst, ms(50));
1000        if let Some(exclude_bottom_focus) = exclude_bottom_focus {
1001            cross_fade = cross_fade.exclude_bottom_focus(exclude_bottom_focus);
1002        }
1003        Directionality::new(TextDirection::Ltr, cross_fade).into_widget()
1004    }
1005
1006    fn assert_hidden_focus(exclude_bottom_focus: Option<bool>, hidden_gets_focus: bool) {
1007        test_widgets(|tester| {
1008            let nodes = Rc::new([Cell::new(None), Cell::new(None)]);
1009            tester.pump_widget(focus_tree(exclude_bottom_focus, &nodes));
1010
1011            let visible = nodes[0].get().expect("built");
1012            tester.update(|app| visible.request_focus(app, None));
1013            tester.pump();
1014            assert!(visible.has_primary_focus(&tester.cell.borrow()));
1015
1016            let hidden = nodes[1].get().expect("built");
1017            tester.update(|app| hidden.request_focus(app, None));
1018            tester.pump();
1019            assert_eq!(
1020                hidden.has_primary_focus(&tester.cell.borrow()),
1021                hidden_gets_focus
1022            );
1023        });
1024    }
1025
1026    #[test]
1027    fn the_bottom_child_cannot_take_focus() {
1028        assert_hidden_focus(None, false);
1029    }
1030
1031    #[test]
1032    fn the_bottom_child_can_have_focus_when_not_excluded() {
1033        assert_hidden_focus(Some(false), true);
1034    }
1035
1036    #[test]
1037    fn does_not_crash_at_zero_area() {
1038        test_widgets(|tester| {
1039            tester.pump_widget(Directionality::new(
1040                TextDirection::Ltr,
1041                Center::new().child(SizedBox::shrink().child(AnimatedCrossFade::new(
1042                    sized(10.0, 10.0),
1043                    sized(20.0, 20.0),
1044                    CrossFadeState::ShowFirst,
1045                    Duration::from_secs(1),
1046                ))),
1047            ));
1048            assert_eq!(
1049                tester.get_size(find::by_type::<AnimatedCrossFade>()),
1050                Size::ZERO
1051            );
1052        });
1053    }
1054
1055    /// An `on_end` that counts its calls.
1056    fn counting_on_end() -> (Rc<Cell<u32>>, Listener) {
1057        let calls = Rc::new(Cell::new(0));
1058        let counted = Rc::clone(&calls);
1059        (
1060            calls,
1061            Listener::new(move |_app| counted.set(counted.get() + 1)),
1062        )
1063    }
1064
1065    fn with_on_end(state: CrossFadeState, on_end: &Listener) -> WidgetRef {
1066        Directionality::new(
1067            TextDirection::Ltr,
1068            simple_cross_fade(state).on_end(on_end.clone()),
1069        )
1070        .into_widget()
1071    }
1072
1073    /// Dart's `onEnd` cases: from `from`, a pump to `to`, no call 100ms in, one once settled.
1074    fn assert_on_end_once(from: CrossFadeState, to: CrossFadeState) {
1075        test_widgets(|tester| {
1076            let (calls, on_end) = counting_on_end();
1077            tester.pump_widget(with_on_end(from, &on_end));
1078            assert_eq!(calls.get(), 0);
1079
1080            tester.pump_widget(with_on_end(to, &on_end));
1081            tester.pump_by(ms(100));
1082            assert_eq!(calls.get(), 0);
1083
1084            tester.pump_and_settle();
1085            assert_eq!(calls.get(), 1);
1086        });
1087    }
1088
1089    #[test]
1090    fn on_end_is_called_when_the_animation_completes_forward() {
1091        assert_on_end_once(CrossFadeState::ShowFirst, CrossFadeState::ShowSecond);
1092    }
1093
1094    #[test]
1095    fn on_end_is_called_when_the_animation_completes_reverse() {
1096        assert_on_end_once(CrossFadeState::ShowSecond, CrossFadeState::ShowFirst);
1097    }
1098
1099    #[test]
1100    fn on_end_is_called_for_each_animation_cycle() {
1101        test_widgets(|tester| {
1102            let (calls, on_end) = counting_on_end();
1103            tester.pump_widget(with_on_end(CrossFadeState::ShowFirst, &on_end));
1104            assert_eq!(calls.get(), 0);
1105
1106            for (state, expected_calls) in [
1107                (CrossFadeState::ShowSecond, 1),
1108                (CrossFadeState::ShowFirst, 2),
1109                (CrossFadeState::ShowSecond, 3),
1110            ] {
1111                tester.pump_widget(with_on_end(state, &on_end));
1112                tester.pump_and_settle();
1113                assert_eq!(calls.get(), expected_calls);
1114            }
1115        });
1116    }
1117
1118    fn assert_clip_behavior(cross_fade: fn() -> AnimatedCrossFade, expected: Clip) {
1119        test_widgets(|tester| {
1120            tester.pump_widget(centered(TextDirection::Ltr, cross_fade()));
1121            assert_eq!(
1122                tester.widget(find::by_type::<ClipRect>(), |clip_rect: &ClipRect| {
1123                    clip_rect.clip_behavior
1124                }),
1125                expected
1126            );
1127            assert_eq!(
1128                tester.widget(
1129                    find::by_type::<AnimatedSize>(),
1130                    |animated_size: &AnimatedSize| { animated_size.clip_behavior }
1131                ),
1132                expected
1133            );
1134        });
1135    }
1136
1137    #[test]
1138    fn clip_behavior_defaults_to_hard_edge() {
1139        assert_clip_behavior(
1140            || simple_cross_fade(CrossFadeState::ShowFirst),
1141            Clip::HardEdge,
1142        );
1143    }
1144
1145    #[test]
1146    fn clip_behavior_is_forwarded_to_clip_rect_and_animated_size() {
1147        assert_clip_behavior(
1148            || simple_cross_fade(CrossFadeState::ShowFirst).clip_behavior(Clip::None),
1149            Clip::None,
1150        );
1151    }
1152
1153    #[test]
1154    fn the_alignment_default_is_top_center() {
1155        assert_eq!(
1156            simple_cross_fade(CrossFadeState::ShowFirst).alignment,
1157            AlignmentGeometry::TOP_CENTER
1158        );
1159    }
1160
1161    /// button_tester.dart's `TestButton`, without a focus node, so its `onFocus` does nothing.
1162    fn test_button(on_pressed: Listener, child: WidgetRef) -> WidgetRef {
1163        let on_tap = on_pressed.clone();
1164        Semantics::new()
1165            .label("button")
1166            .button(true)
1167            .enabled(true)
1168            .on_tap(Rc::new(move |app: &mut App| on_tap.call(app)))
1169            .on_focus(Rc::new(|_app: &mut App| {}))
1170            .focusable(true)
1171            .child(FocusableActionDetector::new(
1172                GestureDetector::new().on_tap(on_pressed).child(child),
1173            ))
1174            .into_widget()
1175    }
1176
1177    #[test]
1178    fn second_child_do_not_receive_touch_events() {
1179        test_widgets(|tester| {
1180            let number_of_touch_event_noticed = Rc::new(Cell::new(0));
1181            let on_pressed = Listener::new({
1182                let noticed = Rc::clone(&number_of_touch_event_noticed);
1183                move |_app| noticed.set(noticed.get() + 1)
1184            });
1185            let build_animated_frame =
1186                |cross_fade_state: CrossFadeState| -> WidgetRef {
1187                    SizedBox::new()
1188                        .width(300.0)
1189                        .height(600.0)
1190                        .child(Directionality::new(
1191                            TextDirection::Ltr,
1192                            AnimatedCrossFade::new(
1193                                Text::new("AAA"),
1194                                SizedBox::new().width(f64::INFINITY).height(600.0).child(
1195                                    test_button(on_pressed.clone(), Text::new("BBB").into_widget()),
1196                                ),
1197                                cross_fade_state,
1198                                ms(50),
1199                            ),
1200                        ))
1201                        .into_widget()
1202                };
1203            let touch_second_button = |tester: &mut WidgetTester| {
1204                tester.tap_at(Offset::new(150.0, 300.0), 1);
1205            };
1206
1207            tester.pump_widget(build_animated_frame(CrossFadeState::ShowSecond));
1208
1209            touch_second_button(tester);
1210            assert_eq!(number_of_touch_event_noticed.get(), 1);
1211
1212            tester.pump_widget(build_animated_frame(CrossFadeState::ShowFirst));
1213            touch_second_button(tester);
1214            touch_second_button(tester);
1215
1216            assert_eq!(number_of_touch_event_noticed.get(), 1);
1217        });
1218    }
1219}