1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub enum CrossFadeState {
36 ShowFirst,
39
40 ShowSecond,
43}
44
45pub type AnimatedCrossFadeBuilder =
59 Rc<dyn Fn(&mut App, &WidgetRef, &KeyRef, &WidgetRef, &KeyRef) -> WidgetRef>;
60
61pub struct AnimatedCrossFade {
89 pub key: Option<KeyRef>,
90
91 pub first_child: WidgetRef,
96
97 pub second_child: WidgetRef,
102
103 pub cross_fade_state: CrossFadeState,
105
106 pub duration: Duration,
108
109 pub reverse_duration: Option<Duration>,
113
114 pub first_curve: Rc<dyn Curve>,
118
119 pub second_curve: Rc<dyn Curve>,
123
124 pub size_curve: Rc<dyn Curve>,
128
129 pub alignment: AlignmentGeometry,
140
141 pub layout_builder: AnimatedCrossFadeBuilder,
156
157 pub exclude_bottom_focus: bool,
165
166 pub clip_behavior: Clip,
178
179 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 #[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 pub fn key(mut self, key: KeyRef) -> AnimatedCrossFade {
231 self.key = Some(key);
232 self
233 }
234
235 pub fn reverse_duration(mut self, reverse_duration: Duration) -> AnimatedCrossFade {
237 self.reverse_duration = Some(reverse_duration);
238 self
239 }
240
241 pub fn first_curve(mut self, first_curve: Rc<dyn Curve>) -> AnimatedCrossFade {
243 self.first_curve = first_curve;
244 self
245 }
246
247 pub fn second_curve(mut self, second_curve: Rc<dyn Curve>) -> AnimatedCrossFade {
249 self.second_curve = second_curve;
250 self
251 }
252
253 pub fn size_curve(mut self, size_curve: Rc<dyn Curve>) -> AnimatedCrossFade {
255 self.size_curve = size_curve;
256 self
257 }
258
259 pub fn alignment(mut self, alignment: AlignmentGeometry) -> AnimatedCrossFade {
261 self.alignment = alignment;
262 self
263 }
264
265 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 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 pub fn clip_behavior(mut self, clip_behavior: Clip) -> AnimatedCrossFade {
283 self.clip_behavior = clip_behavior;
284 self
285 }
286
287 pub fn on_end(mut self, on_end: Listener) -> AnimatedCrossFade {
289 self.on_end = Some(on_end);
290 self
291 }
292
293 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
362pub 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 });
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 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, IgnorePointer::new().ignoring(false).child(
603 ExcludeSemantics::new()
604 .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 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 #[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 assert!(!watcher.ticker().muted(&tester.cell.borrow()));
944 }
945
946 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 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 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 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 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}