1use 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
25struct ChildEntry {
30 controller: Ref<AnimationController>,
32
33 animation: Ref<CurvedAnimation>,
35
36 transition: WidgetRef,
38
39 widget_child: WidgetRef,
42}
43
44#[derive(Clone)]
60pub struct AnimatedSwitcherTransitionBuilder {
61 builder: Rc<AnimatedSwitcherTransitionBuilderFn>,
62 identity: AnimatedSwitcherTransitionBuilderIdentity,
63}
64
65type AnimatedSwitcherTransitionBuilderFn =
67 dyn Fn(&mut App, &WidgetRef, AnimationRef<f64>) -> WidgetRef;
68
69#[derive(Clone, Copy, PartialEq)]
72enum AnimatedSwitcherTransitionBuilderIdentity {
73 Closure,
74 Function(TypeId),
75 HandleMethod(HandleId, TypeId),
76}
77
78impl AnimatedSwitcherTransitionBuilder {
79 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 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 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 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
167pub type AnimatedSwitcherLayoutBuilder =
177 Rc<dyn Fn(&mut App, Option<&WidgetRef>, &[WidgetRef]) -> WidgetRef>;
178
179pub struct AnimatedSwitcher {
212 pub key: Option<KeyRef>,
213
214 pub child: Option<WidgetRef>,
228
229 pub duration: Duration,
238
239 pub reverse_duration: Option<Duration>,
248
249 pub switch_in_curve: Rc<dyn Curve>,
261
262 pub switch_out_curve: Rc<dyn Curve>,
274
275 pub transition_builder: AnimatedSwitcherTransitionBuilder,
296
297 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 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 pub fn key(mut self, key: KeyRef) -> AnimatedSwitcher {
340 self.key = Some(key);
341 self
342 }
343
344 #[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 pub fn reverse_duration(mut self, reverse_duration: Duration) -> AnimatedSwitcher {
353 self.reverse_duration = Some(reverse_duration);
354 self
355 }
356
357 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 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 pub fn transition_builder(
371 mut self,
372 transition_builder: AnimatedSwitcherTransitionBuilder,
373 ) -> AnimatedSwitcher {
374 self.transition_builder = transition_builder;
375 self
376 }
377
378 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 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 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
459pub 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
498fn 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 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 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 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 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 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); 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 fn fade_transitions() -> Finder {
753 find::by_type::<FadeTransition>()
754 }
755
756 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 tester.pump_widget(SizedBox::new().width(1.0));
875 assert_eq!(tester.pump_and_settle(), 1);
876 });
877 }
878
879 #[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 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 #[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 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 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}