Skip to main content

waft_widgets/widgets/
animated_switcher.rs

1//! Flutter counterpart: `widgets/animated_switcher.dart`.
2
3use std::any::TypeId;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::{
9    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatusListener,
10    Curve, CurvedAnimation, Curves,
11};
12use waft_foundation::{App, DiagnosticPropertiesBuilder, Handle, HandleId, IntProperty, ValueKey};
13use waft_painting::AlignmentGeometry;
14use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
15
16use crate::framework::{
17    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef, can_update,
18    keys_equal,
19};
20use crate::widgets::basic::{KeyedSubtree, Stack};
21use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
22use crate::widgets::transitions::FadeTransition;
23use waft_foundation::Ref;
24
25/// Internal representation of a child that, now or in the past, was set on the
26/// [`AnimatedSwitcher::child`] field, but is now in the process of
27/// transitioning. The internal representation includes fields that we don't want
28/// to expose to the public API (like the controller).
29struct ChildEntry {
30    /// The animation controller for the child's transition.
31    controller: Ref<AnimationController>,
32
33    /// The (curved) animation being used to drive the transition.
34    animation: Ref<CurvedAnimation>,
35
36    /// The currently built transition for this child.
37    transition: WidgetRef,
38
39    /// The widget's child at the time this entry was created or updated.
40    /// Used to rebuild the transition if necessary.
41    widget_child: WidgetRef,
42}
43
44/// Signature for builders used to generate custom transitions for
45/// [`AnimatedSwitcher`].
46///
47/// The `child` should be transitioning in when the `animation` is running in
48/// the forward direction.
49///
50/// The function should return a widget which wraps the given `child`. It may
51/// also use the `animation` to inform its transition.
52///
53/// [`AnimatedSwitcher`] compares the builder it is given with the one it had, as Dart
54/// compares two function values: [`new`](Self::new) equals only its clones;
55/// [`function`](Self::function) equals any other built from the same function, as two
56/// tear-offs of one static method are identical; [`handle_method`](Self::handle_method) equals
57/// any other built from the same handle and function, as two tear-offs of one method on one
58/// object are (see the porting skill's callback-identity pattern).
59#[derive(Clone)]
60pub struct AnimatedSwitcherTransitionBuilder {
61    builder: Rc<AnimatedSwitcherTransitionBuilderFn>,
62    identity: AnimatedSwitcherTransitionBuilderIdentity,
63}
64
65/// The function an [`AnimatedSwitcherTransitionBuilder`] calls.
66type AnimatedSwitcherTransitionBuilderFn =
67    dyn Fn(&mut App, &WidgetRef, AnimationRef<f64>) -> WidgetRef;
68
69/// Equality key: closures compare by allocation, functions by the `TypeId` of the function
70/// item, handle-methods by `(handle, TypeId of the function item)`.
71#[derive(Clone, Copy, PartialEq)]
72enum AnimatedSwitcherTransitionBuilderIdentity {
73    Closure,
74    Function(TypeId),
75    HandleMethod(HandleId, TypeId),
76}
77
78impl AnimatedSwitcherTransitionBuilder {
79    /// Wraps a closure; it equals only its clones.
80    pub fn new(
81        builder: impl Fn(&mut App, &WidgetRef, AnimationRef<f64>) -> WidgetRef + 'static,
82    ) -> AnimatedSwitcherTransitionBuilder {
83        AnimatedSwitcherTransitionBuilder {
84            builder: Rc::new(builder),
85            identity: AnimatedSwitcherTransitionBuilderIdentity::Closure,
86        }
87    }
88
89    /// A function, comparable like a Dart tear-off of a static method.
90    ///
91    /// Pass the function by name. A fn pointer or capturing closure is rejected: it has no
92    /// canonical identity.
93    pub fn function<F>(builder: F) -> AnimatedSwitcherTransitionBuilder
94    where
95        F: Fn(&mut App, &WidgetRef, AnimationRef<f64>) -> WidgetRef + 'static,
96    {
97        const {
98            assert!(
99                std::mem::size_of::<F>() == 0,
100                "pass the function by name: a fn pointer or capturing closure has no canonical \
101                 identity"
102            )
103        };
104        AnimatedSwitcherTransitionBuilder {
105            builder: Rc::new(builder),
106            identity: AnimatedSwitcherTransitionBuilderIdentity::Function(TypeId::of::<F>()),
107        }
108    }
109
110    /// A handle's associated function, comparable like a Dart method tear-off such as a
111    /// state's `_buildTransition`.
112    ///
113    /// Pass the function by name; see [`Listener::handle_method`](waft_foundation::Listener::handle_method)
114    /// for the identity rule. A fn pointer or capturing closure is rejected: it has no canonical
115    /// identity.
116    pub fn handle_method<T: 'static, F>(this: Handle<T>, f: F) -> AnimatedSwitcherTransitionBuilder
117    where
118        F: Fn(Handle<T>, &mut App, &WidgetRef, AnimationRef<f64>) -> WidgetRef + 'static,
119    {
120        const {
121            assert!(
122                std::mem::size_of::<F>() == 0,
123                "pass the function by name: a fn pointer or capturing closure has no canonical \
124                 identity"
125            )
126        };
127        AnimatedSwitcherTransitionBuilder {
128            builder: Rc::new(move |app: &mut App, child: &WidgetRef, animation| {
129                f(this, app, child, animation)
130            }),
131            identity: AnimatedSwitcherTransitionBuilderIdentity::HandleMethod(
132                this.id(),
133                TypeId::of::<F>(),
134            ),
135        }
136    }
137
138    /// Calls the builder.
139    pub fn call(
140        &self,
141        app: &mut App,
142        child: &WidgetRef,
143        animation: AnimationRef<f64>,
144    ) -> WidgetRef {
145        (self.builder)(app, child, animation)
146    }
147}
148
149impl PartialEq for AnimatedSwitcherTransitionBuilder {
150    fn eq(&self, other: &AnimatedSwitcherTransitionBuilder) -> bool {
151        match (self.identity, other.identity) {
152            (
153                AnimatedSwitcherTransitionBuilderIdentity::Closure,
154                AnimatedSwitcherTransitionBuilderIdentity::Closure,
155            ) => Rc::ptr_eq(&self.builder, &other.builder),
156            (mine, theirs) => mine == theirs,
157        }
158    }
159}
160
161impl Debug for AnimatedSwitcherTransitionBuilder {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.write_str("AnimatedSwitcherTransitionBuilder")
164    }
165}
166
167/// Signature for builders used to generate custom layouts for
168/// [`AnimatedSwitcher`].
169///
170/// The builder should return a widget which contains the given children, laid
171/// out as desired. The builder should be able to handle an empty list of
172/// `previous_children`, or a `None` `current_child`.
173///
174/// The `previous_children` list is sorted with the oldest at the beginning and
175/// the newest at the end. It does not include the `current_child`.
176pub type AnimatedSwitcherLayoutBuilder =
177    Rc<dyn Fn(&mut App, Option<&WidgetRef>, &[WidgetRef]) -> WidgetRef>;
178
179/// A widget that by default does a cross-fade between a new widget and the
180/// widget previously set on the [`AnimatedSwitcher`] as a child.
181///
182/// If they are swapped fast enough (i.e. before [`duration`](Self::duration) elapses), more
183/// than one previous child can exist and be transitioning out while the newest one is
184/// transitioning in.
185///
186/// If the "new" child is the same widget type and key as the "old" child, but
187/// with different parameters, then [`AnimatedSwitcher`] will *not* do a
188/// transition between them, since as far as the framework is concerned, they
189/// are the same widget and the existing widget can be updated with the new
190/// parameters. To force the transition to occur, set a key on each child
191/// widget that you wish to be considered unique (typically a `ValueKey` on the
192/// widget data that distinguishes this child from the others).
193///
194/// The same key can be used for a new child as was used for an already-outgoing
195/// child; the two will not be considered related. (For example, if a progress
196/// indicator with key A is first shown, then an image with key B, then another
197/// progress indicator with key A again, all in rapid succession, then the old
198/// progress indicator and the image will be fading out while a new progress
199/// indicator is fading in.)
200///
201/// The type of transition can be changed from a cross-fade to a custom
202/// transition by setting the [`transition_builder`](Self::transition_builder).
203///
204/// See also:
205///
206///  * `AnimatedCrossFade`, which only fades between two children, but also
207///    interpolates their sizes, and is reversible.
208///  * `AnimatedOpacity`, which can be used to switch between nothingness and
209///    a given child by fading the child in and out.
210///  * [`FadeTransition`], which [`AnimatedSwitcher`] uses to perform the transition.
211pub struct AnimatedSwitcher {
212    pub key: Option<KeyRef>,
213
214    /// The current child widget to display. If there was a previous child, then
215    /// that child will be faded out using the [`switch_out_curve`](Self::switch_out_curve),
216    /// while the new child is faded in with the [`switch_in_curve`](Self::switch_in_curve),
217    /// over the [`duration`](Self::duration).
218    ///
219    /// If there was no previous child, then this child will fade in using the
220    /// [`switch_in_curve`](Self::switch_in_curve) over the [`duration`](Self::duration).
221    ///
222    /// The child is considered to be "new" if it has a different type or key
223    /// (see `Widget.canUpdate`).
224    ///
225    /// To change the kind of transition used, see
226    /// [`transition_builder`](Self::transition_builder).
227    pub child: Option<WidgetRef>,
228
229    /// The duration of the transition from the old [`child`](Self::child) value to the new
230    /// one.
231    ///
232    /// This duration is applied to the given [`child`](Self::child) when that property is set
233    /// to a new child. The same duration is used when fading out, unless
234    /// [`reverse_duration`](Self::reverse_duration) is set. Changing
235    /// [`duration`](Self::duration) will not affect the durations of transitions already in
236    /// progress.
237    pub duration: Duration,
238
239    /// The duration of the transition from the new [`child`](Self::child) value to the old
240    /// one.
241    ///
242    /// This duration is applied to the given [`child`](Self::child) when that property is set
243    /// to a new child. Changing [`reverse_duration`](Self::reverse_duration) will not affect
244    /// the durations of transitions already in progress.
245    ///
246    /// If not set, then the value of [`duration`](Self::duration) is used by default.
247    pub reverse_duration: Option<Duration>,
248
249    /// The animation curve to use when transitioning in a new [`child`](Self::child).
250    ///
251    /// This curve is applied to the given [`child`](Self::child) when that property is set to
252    /// a new child. Changing [`switch_in_curve`](Self::switch_in_curve) will not affect the
253    /// curve of a transition already in progress.
254    ///
255    /// The [`switch_out_curve`](Self::switch_out_curve) is used when fading out, except that
256    /// if [`child`](Self::child) is changed while the current child is in the middle of
257    /// fading in, [`switch_in_curve`](Self::switch_in_curve) will be run in reverse from that
258    /// point instead of jumping to the corresponding point on
259    /// [`switch_out_curve`](Self::switch_out_curve).
260    pub switch_in_curve: Rc<dyn Curve>,
261
262    /// The animation curve to use when transitioning a previous [`child`](Self::child) out.
263    ///
264    /// This curve is applied to the [`child`](Self::child) when the child is faded in (or
265    /// when the widget is created, for the first child). Changing
266    /// [`switch_out_curve`](Self::switch_out_curve) will not affect the curves of
267    /// already-visible widgets, it only affects the curves of future children.
268    ///
269    /// If [`child`](Self::child) is changed while the current child is in the middle of
270    /// fading in, [`switch_in_curve`](Self::switch_in_curve) will be run in reverse from that
271    /// point instead of jumping to the corresponding point on
272    /// [`switch_out_curve`](Self::switch_out_curve).
273    pub switch_out_curve: Rc<dyn Curve>,
274
275    /// A function that wraps a new [`child`](Self::child) with an animation that transitions
276    /// the [`child`](Self::child) in when the animation runs in the forward direction and out
277    /// when the animation runs in the reverse direction. This is only called
278    /// when a new [`child`](Self::child) is set (not for each build), or when a new
279    /// [`transition_builder`](Self::transition_builder) is set. If a new
280    /// [`transition_builder`](Self::transition_builder) is set, then the transition is
281    /// rebuilt for the current child and all previous children using the new
282    /// [`transition_builder`](Self::transition_builder).
283    ///
284    /// The default is [`AnimatedSwitcher::default_transition_builder`].
285    ///
286    /// The animation provided to the builder has the [`duration`](Self::duration) and
287    /// [`switch_in_curve`](Self::switch_in_curve) or
288    /// [`switch_out_curve`](Self::switch_out_curve) applied as provided when the
289    /// corresponding [`child`](Self::child) was first provided.
290    ///
291    /// See also:
292    ///
293    ///  * [`AnimatedSwitcherTransitionBuilder`] for more information about
294    ///    how a transition builder should function.
295    pub transition_builder: AnimatedSwitcherTransitionBuilder,
296
297    /// A function that wraps all of the children that are transitioning out, and
298    /// the [`child`](Self::child) that's transitioning in, with a widget that lays all of them
299    /// out. This is called every time this widget is built.
300    ///
301    /// The default is [`AnimatedSwitcher::default_layout_builder`].
302    ///
303    /// See also:
304    ///
305    ///  * [`AnimatedSwitcherLayoutBuilder`] for more information about
306    ///    how a layout builder should function.
307    pub layout_builder: AnimatedSwitcherLayoutBuilder,
308}
309
310impl Debug for AnimatedSwitcher {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.debug_struct("AnimatedSwitcher")
313            .field("key", &self.key)
314            .field("child", &self.child)
315            .field("duration", &self.duration)
316            .field("reverse_duration", &self.reverse_duration)
317            .finish_non_exhaustive()
318    }
319}
320
321impl AnimatedSwitcher {
322    /// Creates an [`AnimatedSwitcher`].
323    pub fn new(duration: Duration) -> AnimatedSwitcher {
324        AnimatedSwitcher {
325            key: None,
326            child: None,
327            duration,
328            reverse_duration: None,
329            switch_in_curve: Curves::linear(),
330            switch_out_curve: Curves::linear(),
331            transition_builder: AnimatedSwitcherTransitionBuilder::function(
332                AnimatedSwitcher::default_transition_builder,
333            ),
334            layout_builder: Rc::new(AnimatedSwitcher::default_layout_builder),
335        }
336    }
337
338    /// Dart `AnimatedSwitcher(key:)`.
339    pub fn key(mut self, key: KeyRef) -> AnimatedSwitcher {
340        self.key = Some(key);
341        self
342    }
343
344    /// Dart `AnimatedSwitcher(child:)`.
345    #[cfg_attr(debug_assertions, track_caller)]
346    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedSwitcher {
347        self.child = Some(child.into_widget());
348        self
349    }
350
351    /// Dart `AnimatedSwitcher(reverseDuration:)`.
352    pub fn reverse_duration(mut self, reverse_duration: Duration) -> AnimatedSwitcher {
353        self.reverse_duration = Some(reverse_duration);
354        self
355    }
356
357    /// Dart `AnimatedSwitcher(switchInCurve:)`.
358    pub fn switch_in_curve(mut self, switch_in_curve: Rc<dyn Curve>) -> AnimatedSwitcher {
359        self.switch_in_curve = switch_in_curve;
360        self
361    }
362
363    /// Dart `AnimatedSwitcher(switchOutCurve:)`.
364    pub fn switch_out_curve(mut self, switch_out_curve: Rc<dyn Curve>) -> AnimatedSwitcher {
365        self.switch_out_curve = switch_out_curve;
366        self
367    }
368
369    /// Dart `AnimatedSwitcher(transitionBuilder:)`.
370    pub fn transition_builder(
371        mut self,
372        transition_builder: AnimatedSwitcherTransitionBuilder,
373    ) -> AnimatedSwitcher {
374        self.transition_builder = transition_builder;
375        self
376    }
377
378    /// Dart `AnimatedSwitcher(layoutBuilder:)`.
379    pub fn layout_builder(
380        mut self,
381        layout_builder: impl Fn(&mut App, Option<&WidgetRef>, &[WidgetRef]) -> WidgetRef + 'static,
382    ) -> AnimatedSwitcher {
383        self.layout_builder = Rc::new(layout_builder);
384        self
385    }
386
387    /// The transition builder used as the default value of
388    /// [`transition_builder`](Self::transition_builder).
389    ///
390    /// The new child is given a [`FadeTransition`] which increases opacity as
391    /// the animation goes from 0.0 to 1.0, and decreases when the animation is
392    /// reversed.
393    ///
394    /// This is an [`AnimatedSwitcherTransitionBuilder`] function.
395    pub fn default_transition_builder(
396        _app: &mut App,
397        child: &WidgetRef,
398        animation: AnimationRef<f64>,
399    ) -> WidgetRef {
400        let key = ValueKey::new(child.key().cloned());
401        FadeTransition::new(animation)
402            .key(key.into())
403            .child(child.clone())
404            .into_widget()
405    }
406
407    /// The layout builder used as the default value of
408    /// [`layout_builder`](Self::layout_builder).
409    ///
410    /// The new child is placed in a [`Stack`] that sizes itself to match the
411    /// largest of the child or a previous child. The children are centered on
412    /// each other.
413    ///
414    /// This is an [`AnimatedSwitcherLayoutBuilder`] function.
415    pub fn default_layout_builder(
416        _app: &mut App,
417        current_child: Option<&WidgetRef>,
418        previous_children: &[WidgetRef],
419    ) -> WidgetRef {
420        Stack::new()
421            .alignment(AlignmentGeometry::CENTER)
422            .children(previous_children.iter().chain(current_child).cloned())
423            .into_widget()
424    }
425}
426
427impl StatefulWidget for AnimatedSwitcher {
428    type State = AnimatedSwitcherState;
429
430    fn key(&self) -> Option<&KeyRef> {
431        self.key.as_ref()
432    }
433
434    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
435        properties.add(IntProperty::new("duration", self.duration.as_millis() as i64).unit("ms"));
436        properties.add(
437            IntProperty::<i64>::new(
438                "reverseDuration",
439                self.reverse_duration
440                    .map(|duration| duration.as_millis() as i64),
441            )
442            .unit("ms")
443            .default_value(None),
444        );
445    }
446
447    fn create_state(&self) -> AnimatedSwitcherState {
448        AnimatedSwitcherState {
449            state: StateData::new(),
450            ticker_provider: TickerProviderStateMixinData::new(),
451            current_entry: None,
452            outgoing_entries: Vec::new(),
453            outgoing_widgets: Some(Vec::new()),
454            child_number: 0,
455        }
456    }
457}
458
459/// Dart's `_AnimatedSwitcherState`.
460///
461/// `outgoing_entries` is Dart's insertion-ordered `Set<_ChildEntry>`: an entry is only ever
462/// added once, so a `Vec` keeps the order and the set's identity.
463pub struct AnimatedSwitcherState {
464    state: StateData<AnimatedSwitcher>,
465    ticker_provider: TickerProviderStateMixinData,
466    current_entry: Option<ChildEntry>,
467    outgoing_entries: Vec<ChildEntry>,
468    outgoing_widgets: Option<Vec<WidgetRef>>,
469    child_number: i64,
470}
471
472impl Debug for AnimatedSwitcherState {
473    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474        f.debug_struct("AnimatedSwitcherState")
475            .finish_non_exhaustive()
476    }
477}
478
479impl TickerProviderStateMixin for AnimatedSwitcherState {
480    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
481        &app.get(self).ticker_provider
482    }
483
484    fn ticker_provider_data_mut(
485        self: Handle<Self>,
486        app: &mut App,
487    ) -> &mut TickerProviderStateMixinData {
488        &mut app.get_mut(self).ticker_provider
489    }
490}
491
492impl TickerProviderObject for AnimatedSwitcherState {
493    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
494        TickerProviderStateMixin::create_ticker(self, app, on_tick)
495    }
496}
497
498/// Dart's `_updateTransitionForEntry`: the entry's transition again, in the same key, over its
499/// current `widget_child`.
500fn update_transition_for_entry(
501    app: &mut App,
502    transition_builder: &AnimatedSwitcherTransitionBuilder,
503    entry: &mut ChildEntry,
504) {
505    let key = entry.transition.key().cloned();
506    let child = transition_builder.call(app, &entry.widget_child, entry.animation.erase());
507    let mut transition = KeyedSubtree::new(child);
508    transition.key = key;
509    entry.transition = transition.into_widget();
510}
511
512impl AnimatedSwitcherState {
513    fn add_entry_for_new_child(self: Handle<Self>, app: &mut App, animate: bool) {
514        debug_assert!(animate || app.get(self).current_entry.is_none());
515        if let Some(current_entry) = app.get_mut(self).current_entry.take() {
516            debug_assert!(animate);
517            let controller = current_entry.controller.handle();
518            let state = app.get_mut(self);
519            state.outgoing_entries.push(current_entry);
520            controller.reverse(app, None);
521            self.mark_child_widget_cache_as_dirty(app);
522        }
523        let widget = self.widget(app);
524        let Some(child) = widget.child.clone() else {
525            return;
526        };
527        let duration = widget.duration;
528        let reverse_duration = widget.reverse_duration;
529        let switch_in_curve = Rc::clone(&widget.switch_in_curve);
530        let switch_out_curve = Rc::clone(&widget.switch_out_curve);
531        let builder = widget.transition_builder.clone();
532        let controller = AnimationController::new(
533            app,
534            None,
535            Some(duration),
536            reverse_duration,
537            0.0,
538            1.0,
539            AnimationBehavior::Normal,
540            self,
541        );
542        let animation = CurvedAnimation::new(
543            app,
544            controller.erase(),
545            switch_in_curve,
546            Some(switch_out_curve),
547        );
548        let entry = self.new_entry(app, child, &builder, controller.clone(), animation);
549        app.get_mut(self).current_entry = Some(entry);
550        if animate {
551            controller.forward(app, None);
552        } else {
553            debug_assert!(app.get(self).outgoing_entries.is_empty());
554            controller.set_value(app, 1.0);
555        }
556    }
557
558    fn new_entry(
559        self: Handle<Self>,
560        app: &mut App,
561        child: WidgetRef,
562        builder: &AnimatedSwitcherTransitionBuilder,
563        controller: Ref<AnimationController>,
564        animation: Ref<CurvedAnimation>,
565    ) -> ChildEntry {
566        let child_number = app.get(self).child_number;
567        let transition =
568            KeyedSubtree::wrap(builder.call(app, &child, animation.erase()), child_number)
569                .into_widget();
570        // The listener lives on the animation: it names the entry's objects without keeping
571        // them, and the entry it removes was their keeper.
572        let (controller_handle, animation_handle) = (controller.handle(), animation.handle());
573        animation.as_animation().add_status_listener(
574            app,
575            AnimationStatusListener::new(move |status, app| {
576                let (controller, animation) = (controller_handle, animation_handle);
577                if status.is_dismissed() {
578                    self.set_state(app, |state| {
579                        debug_assert!(
580                            state
581                                .outgoing_entries
582                                .iter()
583                                .any(|entry| entry.controller == controller)
584                        );
585                        state
586                            .outgoing_entries
587                            .retain(|entry| entry.controller != controller);
588                        state.outgoing_widgets = None;
589                    });
590                    controller.dispose(app);
591                    animation.dispose(app);
592                }
593            }),
594        );
595        ChildEntry {
596            widget_child: child,
597            transition,
598            animation,
599            controller,
600        }
601    }
602
603    fn mark_child_widget_cache_as_dirty(self: Handle<Self>, app: &mut App) {
604        app.get_mut(self).outgoing_widgets = None;
605    }
606
607    fn rebuild_outgoing_widgets_if_needed(self: Handle<Self>, app: &mut App) {
608        let state = app.get_mut(self);
609        if state.outgoing_widgets.is_none() {
610            state.outgoing_widgets = Some(
611                state
612                    .outgoing_entries
613                    .iter()
614                    .map(|entry| entry.transition.clone())
615                    .collect(),
616            );
617        }
618        debug_assert_eq!(
619            state.outgoing_entries.len(),
620            state.outgoing_widgets.as_ref().map_or(0, Vec::len)
621        );
622    }
623
624    /// The transitions of the current entry and every outgoing one, rebuilt with the widget's
625    /// `transition_builder`.
626    fn update_transitions_for_all_entries(self: Handle<Self>, app: &mut App) {
627        let builder = self.widget(app).transition_builder.clone();
628        let mut outgoing_entries = std::mem::take(&mut app.get_mut(self).outgoing_entries);
629        for entry in &mut outgoing_entries {
630            update_transition_for_entry(app, &builder, entry);
631        }
632        app.get_mut(self).outgoing_entries = outgoing_entries;
633        if let Some(mut current_entry) = app.get_mut(self).current_entry.take() {
634            update_transition_for_entry(app, &builder, &mut current_entry);
635            app.get_mut(self).current_entry = Some(current_entry);
636        }
637    }
638}
639
640impl State for AnimatedSwitcherState {
641    type Widget = AnimatedSwitcher;
642    crate::state_accessors!();
643
644    fn init_state(self: Handle<Self>, app: &mut App) {
645        self.add_entry_for_new_child(app, false);
646    }
647
648    fn activate(self: Handle<Self>, app: &mut App) {
649        TickerProviderStateMixin::activate(self, app);
650    }
651
652    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedSwitcher) {
653        // If the transition builder changed, then update all of the previous
654        // transitions.
655        if self.widget(app).transition_builder != old_widget.transition_builder {
656            self.update_transitions_for_all_entries(app);
657            self.mark_child_widget_cache_as_dirty(app);
658        }
659
660        let widget_child = self.widget(app).child.clone();
661        let has_new_child = widget_child.is_some();
662        let has_old_child = app.get(self).current_entry.is_some();
663        let child_changed = match (&widget_child, &app.get(self).current_entry) {
664            (Some(child), Some(entry)) => !can_update(&**child, &*entry.widget_child),
665            _ => false,
666        };
667        if has_new_child != has_old_child || child_changed {
668            // Child has changed, fade current entry out and add new entry.
669            app.get_mut(self).child_number += 1;
670            self.add_entry_for_new_child(app, true);
671        } else if let (Some(widget_child), true) = (widget_child, has_old_child) {
672            debug_assert!(has_old_child && has_new_child);
673            // Child has been updated. Make sure we update the child widget and
674            // transition in current_entry even though we're not going to start a new
675            // animation, but keep the key from the previous transition so that we
676            // update the transition instead of replacing it.
677            let builder = self.widget(app).transition_builder.clone();
678            let mut current_entry = app
679                .get_mut(self)
680                .current_entry
681                .take()
682                .expect("has_old_child");
683            current_entry.widget_child = widget_child;
684            update_transition_for_entry(app, &builder, &mut current_entry); // uses entry.widget_child
685            app.get_mut(self).current_entry = Some(current_entry);
686            self.mark_child_widget_cache_as_dirty(app);
687        }
688    }
689
690    fn dispose(self: Handle<Self>, app: &mut App) {
691        let state = app.get_mut(self);
692        let entries: Vec<(Handle<AnimationController>, Handle<CurvedAnimation>)> = state
693            .current_entry
694            .iter()
695            .chain(&state.outgoing_entries)
696            .map(|entry| (entry.controller.handle(), entry.animation.handle()))
697            .collect();
698        for (controller, animation) in entries {
699            controller.dispose(app);
700            animation.dispose(app);
701        }
702        TickerProviderStateMixin::dispose(self, app);
703    }
704
705    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
706        self.rebuild_outgoing_widgets_if_needed(app);
707        let layout_builder = Rc::clone(&self.widget(app).layout_builder);
708        let state = app.get(self);
709        let current_transition = state
710            .current_entry
711            .as_ref()
712            .map(|entry| entry.transition.clone());
713        let current_key = current_transition
714            .as_ref()
715            .and_then(|transition| transition.key());
716        let mut previous_children: Vec<WidgetRef> = Vec::new();
717        for outgoing in state.outgoing_widgets.iter().flatten() {
718            if !keys_equal(outgoing.key(), current_key)
719                && !previous_children
720                    .iter()
721                    .any(|previous| Rc::ptr_eq(previous, outgoing))
722            {
723                previous_children.push(outgoing.clone());
724            }
725        }
726        layout_builder(app, current_transition.as_ref(), &previous_children)
727    }
728}
729
730#[cfg(test)]
731mod tests {
732    use std::cell::{Cell, RefCell};
733    use waft_foundation::{AppCell, UniqueKey};
734
735    use waft_embedder::{Size, TextDirection};
736
737    use super::*;
738    use crate::testing::{
739        Finder, WidgetTester, assert_more_or_less_equals_within, expect, find, finds_n_widgets,
740        finds_nothing, finds_one_widget, test_widgets,
741    };
742    use crate::widgets::basic::{Center, Column, Directionality, SizedBox};
743    use crate::widgets::transitions::{Animated, ScaleTransition, SizeTransition};
744
745    const DURATION: Duration = Duration::from_millis(100);
746
747    fn ms(milliseconds: u64) -> Duration {
748        Duration::from_millis(milliseconds)
749    }
750
751    /// The `FadeTransition`s the switcher builds: Dart's `find.byType(FadeTransition)`.
752    fn fade_transitions() -> Finder {
753        find::by_type::<FadeTransition>()
754    }
755
756    /// Dart's `tester.widget<FadeTransition>(finder).opacity.value`.
757    fn opacity(tester: &WidgetTester, finder: Finder) -> f64 {
758        let opacity = tester.widget(finder, |transition: &FadeTransition| {
759            transition.opacity.clone()
760        });
761        opacity.value(&tester.cell.borrow())
762    }
763
764    fn keyed_box(key: &KeyRef) -> WidgetRef {
765        SizedBox::new().key(key.clone()).into_widget()
766    }
767
768    fn switcher(child: Option<WidgetRef>) -> AnimatedSwitcher {
769        let switcher = AnimatedSwitcher::new(DURATION);
770        match child {
771            Some(child) => switcher.child(child),
772            None => switcher,
773        }
774    }
775
776    fn unique_key() -> KeyRef {
777        UniqueKey::new().into()
778    }
779
780    #[test]
781    fn fades_in_a_new_child() {
782        test_widgets(|tester| {
783            let (one, two, three) = (unique_key(), unique_key(), unique_key());
784            tester.pump_widget(switcher(Some(keyed_box(&one))));
785            expect(tester, &fade_transitions(), finds_one_widget());
786            assert_eq!(opacity(tester, fade_transitions().first()), 1.0);
787
788            tester.pump_widget(switcher(Some(keyed_box(&two))));
789            tester.pump_by(ms(50));
790            expect(tester, &fade_transitions(), finds_n_widgets(2));
791            assert_eq!(opacity(tester, fade_transitions().first()), 0.5);
792
793            tester.pump_widget(switcher(Some(keyed_box(&three))));
794            tester.pump_by(ms(10));
795            assert_more_or_less_equals_within(opacity(tester, fade_transitions().at(0)), 0.4, 0.01);
796            assert_more_or_less_equals_within(opacity(tester, fade_transitions().at(1)), 0.4, 0.01);
797            assert_more_or_less_equals_within(opacity(tester, fade_transitions().at(2)), 0.1, 0.01);
798            tester.pump_and_settle();
799        });
800    }
801
802    #[test]
803    fn can_handle_back_to_back_changes() {
804        test_widgets(|tester| {
805            let (one, two, three) = (unique_key(), unique_key(), unique_key());
806            tester.pump_widget(switcher(Some(keyed_box(&one))));
807            expect(tester, &find::by_key(one.clone()), finds_one_widget());
808            expect(tester, &find::by_key(two.clone()), finds_nothing());
809            expect(tester, &find::by_key(three.clone()), finds_nothing());
810
811            tester.pump_widget(switcher(Some(keyed_box(&two))));
812            expect(tester, &find::by_key(one.clone()), finds_one_widget());
813            expect(tester, &find::by_key(two.clone()), finds_one_widget());
814            expect(tester, &find::by_key(three.clone()), finds_nothing());
815
816            tester.pump_widget(switcher(Some(keyed_box(&three))));
817            expect(tester, &find::by_key(one.clone()), finds_one_widget());
818            expect(tester, &find::by_key(two.clone()), finds_nothing());
819            expect(tester, &find::by_key(three.clone()), finds_one_widget());
820        });
821    }
822
823    #[test]
824    fn does_not_transition_in_a_new_child_of_the_same_type() {
825        test_widgets(|tester| {
826            let plain = |width: f64| SizedBox::new().width(width).into_widget();
827            tester.pump_widget(switcher(Some(plain(1.0))));
828            expect(tester, &fade_transitions(), finds_one_widget());
829            assert_eq!(opacity(tester, fade_transitions().first()), 1.0);
830
831            tester.pump_widget(switcher(Some(plain(2.0))));
832            tester.pump_by(ms(50));
833            expect(tester, &fade_transitions(), finds_one_widget());
834            assert_eq!(opacity(tester, fade_transitions().first()), 1.0);
835            tester.pump_and_settle();
836        });
837    }
838
839    #[test]
840    fn handles_null_children() {
841        test_widgets(|tester| {
842            let plain = || SizedBox::new().into_widget();
843            tester.pump_widget(switcher(None));
844            expect(tester, &fade_transitions(), finds_nothing());
845
846            tester.pump_widget(switcher(Some(plain())));
847            tester.pump_by(ms(50));
848            assert_eq!(opacity(tester, fade_transitions().first()), 0.5);
849            tester.pump_and_settle();
850
851            tester.pump_widget(switcher(Some(plain())));
852            expect(tester, &fade_transitions(), finds_one_widget());
853            assert_eq!(opacity(tester, fade_transitions().first()), 1.0);
854
855            tester.pump_widget(switcher(None));
856            tester.pump_by(ms(50));
857            assert_eq!(opacity(tester, fade_transitions().first()), 0.5);
858
859            tester.pump_widget(switcher(None));
860            tester.pump_by(ms(50));
861            assert_eq!(opacity(tester, fade_transitions().first()), 0.0);
862
863            tester.pump_and_settle();
864        });
865    }
866
867    #[test]
868    fn does_not_start_any_animations_after_dispose() {
869        test_widgets(|tester| {
870            tester.pump_widget(switcher(Some(SizedBox::new().into_widget())));
871            tester.pump_by(ms(50));
872
873            // Change the widget tree in the middle of the animation.
874            tester.pump_widget(SizedBox::new().width(1.0));
875            assert_eq!(tester.pump_and_settle(), 1);
876        });
877    }
878
879    /// The curved animation each child entry drives is freed once the entry leaves, on the
880    /// outgoing child's dismissal and with the state, as Dart's collector frees it.
881    #[test]
882    fn frees_each_entrys_curved_animation_once_its_entry_leaves() {
883        test_widgets(|tester| {
884            let (one, two) = (unique_key(), unique_key());
885            tester.pump_widget(switcher(Some(keyed_box(&one))));
886            let current_animation = |tester: &WidgetTester| {
887                let element = tester.element(find::by_type::<AnimatedSwitcher>());
888                let app = tester.cell.borrow();
889                let state = element
890                    .state_handle::<AnimatedSwitcherState>(&app)
891                    .expect("a mounted AnimatedSwitcher");
892                app.get(state)
893                    .current_entry
894                    .as_ref()
895                    .expect("a child entry")
896                    .animation
897                    .handle()
898            };
899            let first = current_animation(tester);
900
901            tester.pump_widget(switcher(Some(keyed_box(&two))));
902            tester.pump_by(ms(200));
903            let second = current_animation(tester);
904            tester.cell.checkpoint();
905            assert!(
906                !tester.cell.borrow().contains(first),
907                "the outgoing entry's"
908            );
909            assert!(tester.cell.borrow().contains(second));
910
911            tester.pump_widget(SizedBox::new());
912            tester.cell.checkpoint();
913            assert!(
914                !tester.cell.borrow().contains(second),
915                "the current entry's, at dispose"
916            );
917        });
918    }
919
920    #[test]
921    fn uses_custom_layout() {
922        test_widgets(|tester| {
923            let widget = switcher(Some(SizedBox::new().into_widget())).layout_builder(
924                |_app, current_child, previous_children| {
925                    Column::new()
926                        .children(previous_children.iter().chain(current_child).cloned())
927                        .into_widget()
928                },
929            );
930            tester.pump_widget(widget);
931            expect(tester, &find::by_type::<Column>(), finds_one_widget());
932        });
933    }
934
935    /// A layout builder that records the children it was given, `current_child` first.
936    fn recording_layout(
937        found_children: &Rc<RefCell<Vec<WidgetRef>>>,
938    ) -> impl Fn(&mut App, Option<&WidgetRef>, &[WidgetRef]) -> WidgetRef + 'static {
939        let found_children = Rc::clone(found_children);
940        move |_app, current_child, previous_children| {
941            let children: Vec<WidgetRef> = current_child
942                .into_iter()
943                .chain(previous_children)
944                .cloned()
945                .collect();
946            *found_children.borrow_mut() = children.clone();
947            Column::new().children(children).into_widget()
948        }
949    }
950
951    fn as_keyed_subtree(widget: &WidgetRef) -> &KeyedSubtree {
952        widget
953            .as_any()
954            .downcast_ref::<KeyedSubtree>()
955            .expect("a KeyedSubtree")
956    }
957
958    #[test]
959    fn uses_custom_transitions() {
960        test_widgets(|tester| {
961            let found_children = Rc::new(RefCell::new(Vec::new()));
962            let transition_builder =
963                AnimatedSwitcherTransitionBuilder::new(|_app, child, animation| {
964                    SizeTransition::new(animation)
965                        .child(child.clone())
966                        .into_widget()
967                });
968            let tree = |child: Option<WidgetRef>| {
969                let mut switcher = switcher(child)
970                    .layout_builder(recording_layout(&found_children))
971                    .transition_builder(transition_builder.clone());
972                switcher.key = None;
973                Directionality::new(TextDirection::Rtl, switcher).into_widget()
974            };
975            tester.pump_widget(tree(Some(SizedBox::new().into_widget())));
976            expect(tester, &find::by_type::<Column>(), finds_one_widget());
977            for child in found_children.borrow().iter() {
978                as_keyed_subtree(child);
979            }
980
981            tester.pump_widget(tree(None));
982            tester.pump_by(ms(50));
983            assert!(!found_children.borrow().is_empty());
984            for child in found_children.borrow().iter() {
985                assert!(
986                    as_keyed_subtree(child)
987                        .child
988                        .as_any()
989                        .is::<Animated<SizeTransition>>()
990                );
991            }
992        });
993    }
994
995    /// Dart's `StatefulTest` with its static `generation`.
996    #[derive(Debug)]
997    struct StatefulTest {
998        key: KeyRef,
999        generation: Rc<Cell<u32>>,
1000    }
1001
1002    impl StatefulWidget for StatefulTest {
1003        type State = StatefulTestState;
1004
1005        fn key(&self) -> Option<&KeyRef> {
1006            Some(&self.key)
1007        }
1008
1009        fn create_state(&self) -> StatefulTestState {
1010            StatefulTestState {
1011                state: StateData::new(),
1012            }
1013        }
1014    }
1015
1016    struct StatefulTestState {
1017        state: StateData<StatefulTest>,
1018    }
1019
1020    impl State for StatefulTestState {
1021        type Widget = StatefulTest;
1022        crate::state_accessors!();
1023
1024        fn init_state(self: Handle<Self>, app: &mut App) {
1025            let generation = &self.widget(app).generation;
1026            generation.set(generation.get() + 1);
1027        }
1028
1029        fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
1030            SizedBox::new().into_widget()
1031        }
1032    }
1033
1034    #[test]
1035    fn does_not_reset_state_of_the_children_in_transitions() {
1036        test_widgets(|tester| {
1037            let generation = Rc::new(Cell::new(0));
1038            let stateful = |key: &KeyRef| {
1039                switcher(Some(
1040                    StatefulTest {
1041                        key: key.clone(),
1042                        generation: Rc::clone(&generation),
1043                    }
1044                    .into_widget(),
1045                ))
1046            };
1047            let (one, two, three) = (unique_key(), unique_key(), unique_key());
1048            tester.pump_widget(stateful(&one));
1049            expect(tester, &fade_transitions(), finds_one_widget());
1050            assert_eq!(opacity(tester, fade_transitions().first()), 1.0);
1051            assert_eq!(generation.get(), 1);
1052
1053            tester.pump_widget(stateful(&two));
1054            tester.pump_by(ms(50));
1055            expect(tester, &fade_transitions(), finds_n_widgets(2));
1056            assert_eq!(opacity(tester, fade_transitions().first()), 0.5);
1057            assert_eq!(generation.get(), 2);
1058
1059            tester.pump_widget(stateful(&three));
1060            tester.pump_by(ms(10));
1061            assert_eq!(generation.get(), 3);
1062            assert_more_or_less_equals_within(opacity(tester, fade_transitions().at(0)), 0.4, 0.01);
1063            assert_more_or_less_equals_within(opacity(tester, fade_transitions().at(1)), 0.4, 0.01);
1064            assert_more_or_less_equals_within(opacity(tester, fade_transitions().at(2)), 0.1, 0.01);
1065            tester.pump_and_settle();
1066            assert_eq!(generation.get(), 3);
1067        });
1068    }
1069
1070    #[test]
1071    fn updates_widgets_without_animating_if_they_are_isomorphic() {
1072        test_widgets(|tester| {
1073            let sized = |width: f64| {
1074                Directionality::new(
1075                    TextDirection::Rtl,
1076                    switcher(Some(SizedBox::new().width(width).into_widget())),
1077                )
1078            };
1079            tester.pump_widget(sized(1.0));
1080            tester.pump_by(ms(10));
1081            assert_eq!(opacity(tester, fade_transitions().first()), 1.0);
1082            let width = |tester: &WidgetTester| {
1083                tester.widget(find::by_type::<SizedBox>(), |sized_box: &SizedBox| {
1084                    sized_box.width
1085                })
1086            };
1087            assert_eq!(width(tester), Some(1.0));
1088
1089            tester.pump_widget(sized(2.0));
1090            tester.pump_by(ms(20));
1091            assert_eq!(opacity(tester, fade_transitions().first()), 1.0);
1092            assert_eq!(width(tester), Some(2.0));
1093        });
1094    }
1095
1096    #[test]
1097    fn updates_previous_child_transitions_if_the_transition_builder_changes() {
1098        test_widgets(|tester| {
1099            let found_children = Rc::new(RefCell::new(Vec::new()));
1100            let tree =
1101                |key: &KeyRef, transition_builder: Option<AnimatedSwitcherTransitionBuilder>| {
1102                    let mut switcher = switcher(Some(keyed_box(key)))
1103                        .layout_builder(recording_layout(&found_children));
1104                    if let Some(transition_builder) = transition_builder {
1105                        switcher = switcher.transition_builder(transition_builder);
1106                    }
1107                    switcher
1108                };
1109            let (one, two, three, four) = (unique_key(), unique_key(), unique_key(), unique_key());
1110            // Insert three unique children so that we have some previous children.
1111            tester.pump_widget(tree(&one, None));
1112            tester.pump_by(ms(10));
1113            tester.pump_widget(tree(&two, None));
1114            tester.pump_by(ms(10));
1115            tester.pump_widget(tree(&three, None));
1116            tester.pump_by(ms(10));
1117
1118            assert_eq!(found_children.borrow().len(), 3);
1119            for child in found_children.borrow().iter() {
1120                assert!(
1121                    as_keyed_subtree(child)
1122                        .child
1123                        .as_any()
1124                        .is::<FadeTransition>()
1125                );
1126            }
1127
1128            // Now set a new transition builder and make sure all the previous
1129            // transitions are replaced.
1130            let scale = AnimatedSwitcherTransitionBuilder::new(|_app, child, animation| {
1131                ScaleTransition::new(animation)
1132                    .child(child.clone())
1133                    .into_widget()
1134            });
1135            tester.pump_widget(tree(&four, Some(scale)));
1136            tester.pump_by(ms(10));
1137
1138            assert_eq!(found_children.borrow().len(), 3);
1139            for child in found_children.borrow().iter() {
1140                assert!(
1141                    as_keyed_subtree(child)
1142                        .child
1143                        .as_any()
1144                        .is::<Animated<ScaleTransition>>()
1145                );
1146            }
1147        });
1148    }
1149
1150    #[test]
1151    fn does_not_duplicate_animations_if_the_same_child_is_entered_twice() {
1152        test_widgets(|tester| {
1153            let (one, two): (KeyRef, KeyRef) = (
1154                waft_foundation::ValueKey::new("1".to_string()).into(),
1155                waft_foundation::ValueKey::new("2".to_string()).into(),
1156            );
1157            let tree = |key: &KeyRef| {
1158                Directionality::new(
1159                    TextDirection::Ltr,
1160                    AnimatedSwitcher::new(Duration::from_millis(1000)).child(keyed_box(key)),
1161                )
1162            };
1163            tester.pump_widget(tree(&one));
1164            tester.pump_widget(tree(&two));
1165            tester.pump_widget(tree(&one));
1166            tester.pump_by(ms(1000));
1167            expect(tester, &find::by_key(one.clone()), finds_one_widget());
1168        });
1169    }
1170
1171    #[test]
1172    fn does_not_crash_at_zero_area() {
1173        test_widgets(|tester| {
1174            let tree = |child: Option<WidgetRef>| {
1175                let mut switcher = AnimatedSwitcher::new(Duration::from_micros(500));
1176                if let Some(child) = child {
1177                    switcher = switcher.child(child);
1178                }
1179                Directionality::new(
1180                    TextDirection::Ltr,
1181                    Center::new().child(SizedBox::shrink().child(switcher)),
1182                )
1183            };
1184            let switcher_size =
1185                |tester: &WidgetTester| tester.get_size(find::by_type::<AnimatedSwitcher>());
1186            tester.pump_widget(tree(None));
1187            assert_eq!(switcher_size(tester), Size::ZERO);
1188
1189            let key =
1190                |name: &str| -> KeyRef { waft_foundation::ValueKey::new(name.to_string()).into() };
1191            tester.pump_widget(tree(Some(keyed_box(&key("x")))));
1192            assert_eq!(switcher_size(tester), Size::ZERO);
1193
1194            tester.pump_widget(tree(Some(keyed_box(&key("y")))));
1195            assert_eq!(switcher_size(tester), Size::ZERO);
1196        });
1197    }
1198
1199    #[test]
1200    fn the_default_builders_compare_as_the_same_function() {
1201        let first = AnimatedSwitcher::new(DURATION);
1202        let second = AnimatedSwitcher::new(DURATION);
1203        assert!(first.transition_builder == second.transition_builder);
1204        let custom =
1205            AnimatedSwitcherTransitionBuilder::new(|_app, child, _animation| child.clone());
1206        assert!(custom != first.transition_builder);
1207        assert!(custom == custom.clone());
1208        let _ = AppCell::new();
1209    }
1210
1211    #[test]
1212    fn two_tear_offs_of_one_method_on_one_object_compare_equal() {
1213        struct Host;
1214        fn build_transition(
1215            _this: Handle<Host>,
1216            _app: &mut App,
1217            child: &WidgetRef,
1218            _animation: AnimationRef<f64>,
1219        ) -> WidgetRef {
1220            child.clone()
1221        }
1222        fn other_build_transition(
1223            _this: Handle<Host>,
1224            _app: &mut App,
1225            child: &WidgetRef,
1226            _animation: AnimationRef<f64>,
1227        ) -> WidgetRef {
1228            child.clone()
1229        }
1230
1231        let cell = AppCell::new();
1232        let mut app = cell.borrow_mut();
1233        let host = app.create(Host);
1234        let other_host = app.create(Host);
1235        let tear_off =
1236            AnimatedSwitcherTransitionBuilder::handle_method(host.handle(), build_transition);
1237
1238        assert!(
1239            tear_off
1240                == AnimatedSwitcherTransitionBuilder::handle_method(
1241                    host.handle(),
1242                    build_transition
1243                )
1244        );
1245        assert!(
1246            tear_off
1247                != AnimatedSwitcherTransitionBuilder::handle_method(
1248                    other_host.handle(),
1249                    build_transition
1250                )
1251        );
1252        assert!(
1253            tear_off
1254                != AnimatedSwitcherTransitionBuilder::handle_method(
1255                    host.handle(),
1256                    other_build_transition
1257                )
1258        );
1259        assert!(tear_off != AnimatedSwitcher::new(DURATION).transition_builder);
1260        assert!(
1261            tear_off
1262                != AnimatedSwitcherTransitionBuilder::new(|_app, child, _animation| child.clone())
1263        );
1264    }
1265}