1use crate::widgets::pages::PageRouteRef;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11
12use indexmap::IndexMap;
13use waft_animation::{
14 Animatable, Animation, AnimationRef, AnimationStatus, AnimationStatusListener, AnyAnimation,
15 Curve, CurveTween, CurvedAnimation, Curves, Drive, Interval, ProxyAnimation, RectTween,
16 ReverseAnimation, Tween, k_always_complete_animation,
17};
18use waft_embedder::{Offset, Rect, Size};
19use waft_foundation::{
20 AnyEq, App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Handle,
21 ListenableObject, Listener, OptionRetained, Retained,
22};
23use waft_painting::transform_rect;
24use waft_scheduler::{FrameCallback, SchedulerBinding};
25
26use crate::framework::{
27 AnyElement, BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget,
28 StatelessWidget, WidgetRef, downcast_widget,
29};
30use crate::view::View;
31use crate::widgets::basic::{IgnorePointer, KeyedSubtree, Offstage, Positioned, SizedBox};
32use crate::widgets::implicit_animations::EdgeInsetsTween;
33use crate::widgets::media_query::MediaQuery;
34use crate::widgets::navigator::{
35 AnyRoute, Navigator, NavigatorObserver, NavigatorObserverData, NavigatorState,
36};
37use crate::widgets::overlay::{OverlayEntry, OverlayState};
38use crate::widgets::routes::AnyModalRoute;
39use crate::widgets::ticker_provider::TickerMode;
40use crate::widgets::transitions::{AnimatedBuilder, FadeTransition};
41use waft_foundation::Ref;
42
43pub trait RectTweenObject: 'static {
52 fn begin(&self, app: &App) -> Option<Rect>;
54
55 fn end(&self, app: &App) -> Option<Rect>;
57
58 fn lerp(&self, app: &App, t: f64) -> Option<Rect>;
60
61 fn transform(&self, app: &App, t: f64) -> Option<Rect> {
64 if t == 0.0 {
65 return self.begin(app);
66 }
67 if t == 1.0 {
68 return self.end(app);
69 }
70 self.lerp(app, t)
71 }
72
73 fn evaluate(&self, app: &App, animation: AnyAnimation<f64>) -> Option<Rect> {
75 self.transform(app, animation.value(app))
76 }
77}
78
79impl RectTweenObject for Ref<RectTween> {
80 fn begin(&self, app: &App) -> Option<Rect> {
81 app.get(self).begin
82 }
83
84 fn end(&self, app: &App) -> Option<Rect> {
85 app.get(self).end
86 }
87
88 fn lerp(&self, app: &App, t: f64) -> Option<Rect> {
89 RectTween::lerp(self.handle(), app, t)
90 }
91}
92
93struct ReverseRectTween {
98 parent: Rc<dyn RectTweenObject>,
99}
100
101impl RectTweenObject for ReverseRectTween {
102 fn begin(&self, app: &App) -> Option<Rect> {
103 self.parent.end(app)
104 }
105
106 fn end(&self, app: &App) -> Option<Rect> {
107 self.parent.begin(app)
108 }
109
110 fn lerp(&self, app: &App, t: f64) -> Option<Rect> {
111 self.parent.lerp(app, 1.0 - t)
112 }
113}
114
115pub type CreateRectTween =
121 Rc<dyn Fn(&mut App, Option<Rect>, Option<Rect>) -> Rc<dyn RectTweenObject>>;
122
123pub type HeroPlaceholderBuilder = Rc<dyn Fn(&mut App, BuildContext, Size, WidgetRef) -> WidgetRef>;
134
135pub type HeroFlightShuttleBuilder = Rc<
139 dyn Fn(
140 &mut App,
141 BuildContext,
142 AnimationRef<f64>,
143 HeroFlightDirection,
144 BuildContext,
145 BuildContext,
146 ) -> WidgetRef,
147>;
148
149type OnFlightEnded = Rc<dyn Fn(&mut App, Handle<HeroFlight>)>;
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub enum HeroFlightDirection {
154 Push,
161
162 Pop,
169}
170
171pub struct Hero {
235 pub key: Option<KeyRef>,
237 pub tag: Rc<dyn AnyEq>,
241 pub create_rect_tween: Option<CreateRectTween>,
251 pub child: WidgetRef,
258 pub flight_shuttle_builder: Option<HeroFlightShuttleBuilder>,
282 pub placeholder_builder: Option<HeroPlaceholderBuilder>,
290 pub transition_on_user_gestures: bool,
303 pub curve: Rc<dyn Curve>,
307 pub reverse_curve: Option<Rc<dyn Curve>>,
311}
312
313impl Hero {
314 #[cfg_attr(debug_assertions, track_caller)]
320 pub fn new<K>(tag: Rc<dyn AnyEq>, child: impl IntoWidget<K>) -> Hero {
321 Hero {
322 key: None,
323 tag,
324 create_rect_tween: None,
325 child: child.into_widget(),
326 flight_shuttle_builder: None,
327 placeholder_builder: None,
328 transition_on_user_gestures: false,
329 curve: Curves::fast_out_slow_in(),
330 reverse_curve: None,
331 }
332 }
333
334 pub fn key(mut self, key: KeyRef) -> Hero {
336 self.key = Some(key);
337 self
338 }
339
340 pub fn create_rect_tween(mut self, create_rect_tween: CreateRectTween) -> Hero {
342 self.create_rect_tween = Some(create_rect_tween);
343 self
344 }
345
346 pub fn flight_shuttle_builder(
348 mut self,
349 flight_shuttle_builder: HeroFlightShuttleBuilder,
350 ) -> Hero {
351 self.flight_shuttle_builder = Some(flight_shuttle_builder);
352 self
353 }
354
355 pub fn placeholder_builder(mut self, placeholder_builder: HeroPlaceholderBuilder) -> Hero {
357 self.placeholder_builder = Some(placeholder_builder);
358 self
359 }
360
361 pub fn transition_on_user_gestures(mut self, transition_on_user_gestures: bool) -> Hero {
363 self.transition_on_user_gestures = transition_on_user_gestures;
364 self
365 }
366
367 pub fn curve(mut self, curve: Rc<dyn Curve>) -> Hero {
369 self.curve = curve;
370 self
371 }
372
373 pub fn reverse_curve(mut self, reverse_curve: Rc<dyn Curve>) -> Hero {
375 self.reverse_curve = Some(reverse_curve);
376 self
377 }
378
379 fn all_heroes_for(
382 app: &mut App,
383 context: BuildContext,
384 is_user_gesture_transition: bool,
385 navigator: Handle<NavigatorState>,
386 ) -> IndexMap<Rc<dyn AnyEq>, Handle<HeroState>> {
387 let mut result: IndexMap<Rc<dyn AnyEq>, Handle<HeroState>> = IndexMap::new();
388
389 fn visitor(app: &App, element: AnyElement, heroes: &mut Vec<AnyElement>) {
393 let widget = element.widget(app).clone();
394 if downcast_widget::<Hero>(&*widget).is_some() {
395 heroes.push(element);
396 } else if downcast_widget::<HeroMode>(&*widget).is_some_and(|mode| !mode.enabled) {
397 return;
398 }
399 element.visit_children(app, &mut |child| visitor(app, child, heroes));
400 }
401
402 let mut heroes = Vec::new();
403 context.visit_child_elements(app, &mut |child| visitor(app, child, &mut heroes));
404
405 for hero in heroes {
406 let widget = hero.widget(app).clone();
407 let hero_widget =
408 downcast_widget::<Hero>(&*widget).expect("collected from the Hero branch");
409 let tag = Rc::clone(&hero_widget.tag);
410 let transition_on_user_gestures = hero_widget.transition_on_user_gestures;
411 if Navigator::of(app, hero, false) == navigator {
412 invite_hero(
413 app,
414 &mut result,
415 hero,
416 tag,
417 transition_on_user_gestures,
418 is_user_gesture_transition,
419 );
420 } else {
421 let hero_route = AnyModalRoute::of(app, hero);
427 if let Some(hero_route) = hero_route
428 && hero_route.as_route().as_page_route(app).is_some()
429 && hero_route.as_route().is_current(app)
430 {
431 invite_hero(
432 app,
433 &mut result,
434 hero,
435 tag,
436 transition_on_user_gestures,
437 is_user_gesture_transition,
438 );
439 }
440 }
441 }
442
443 fn invite_hero(
444 app: &mut App,
445 result: &mut IndexMap<Rc<dyn AnyEq>, Handle<HeroState>>,
446 hero: AnyElement,
447 tag: Rc<dyn AnyEq>,
448 transition_on_user_gestures: bool,
449 is_user_gesture_transition: bool,
450 ) {
451 debug_assert!(
452 !result.contains_key(&tag),
453 "There are multiple heroes that share the same tag within a subtree. Within each \
454 subtree for which heroes are to be animated (i.e. a PageRoute subtree), each \
455 Hero must have a unique non-null tag."
456 );
457 let hero_state = hero
458 .state_handle::<HeroState>(app)
459 .expect("a Hero element holds a HeroState");
460 if !is_user_gesture_transition || transition_on_user_gestures {
461 result.insert(tag, hero_state);
462 } else {
463 hero_state.end_flight(app, false);
466 }
467 }
468
469 result
470 }
471}
472
473impl StatefulWidget for Hero {
474 type State = HeroState;
475
476 fn key(&self) -> Option<&KeyRef> {
477 self.key.as_ref()
478 }
479
480 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
481 properties.add(DiagnosticsProperty::<String>::new(
482 "tag",
483 Some(format!("{:?}", self.tag)),
484 ));
485 }
486
487 fn create_state(&self) -> HeroState {
488 HeroState {
489 state: StateData::new(),
490 key: GlobalKey::new(),
491 placeholder_size: None,
492 should_include_child: true,
493 }
494 }
495}
496
497impl Debug for Hero {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 f.debug_struct("Hero")
500 .field("tag", &self.tag)
501 .finish_non_exhaustive()
502 }
503}
504
505pub struct HeroState {
515 state: StateData<Hero>,
516 key: GlobalKey,
517 placeholder_size: Option<Size>,
518 should_include_child: bool,
522}
523
524impl HeroState {
525 pub fn start_flight(
538 self: Handle<Self>,
539 app: &mut App,
540 should_included_child_in_placeholder: bool,
541 ) {
542 app.get_mut(self).should_include_child = should_included_child_in_placeholder;
543 debug_assert!(self.mounted(app));
544 let render_box = self
545 .context(app)
546 .find_render_object(app)
547 .expect("a mounted Hero has a render object")
548 .as_box()
549 .expect("a Hero's render object is a box");
550 debug_assert!(render_box.has_size(app));
551 let size = render_box.size(app);
552 self.set_state(app, |state| state.placeholder_size = Some(size));
553 }
554
555 pub fn end_flight(self: Handle<Self>, app: &mut App, keep_placeholder: bool) {
563 if keep_placeholder || app.get(self).placeholder_size.is_none() {
564 return;
565 }
566
567 app.get_mut(self).placeholder_size = None;
568 if self.mounted(app) {
569 self.set_state(app, |_| {});
572 }
573 }
574}
575
576impl State for HeroState {
577 type Widget = Hero;
578 crate::state_accessors!();
579
580 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
581 debug_assert!(
582 context
583 .find_ancestor_widget_of_exact_type::<Hero>(app)
584 .is_none(),
585 "A Hero widget cannot be the descendant of another Hero widget."
586 );
587
588 let placeholder_size = app.get(self).placeholder_size;
589 let show_placeholder = placeholder_size.is_some();
590
591 if show_placeholder
592 && let Some(placeholder_builder) = self.widget(app).placeholder_builder.clone()
593 {
594 let child = self.widget(app).child.clone();
595 let size = placeholder_size.expect("the placeholder is showing");
596 return placeholder_builder(app, context, size, child);
597 }
598
599 if show_placeholder && !app.get(self).should_include_child {
600 let size = placeholder_size.expect("the placeholder is showing");
601 return SizedBox::new()
602 .width(size.width())
603 .height(size.height())
604 .into_widget();
605 }
606
607 let key = app.get(self).key.clone();
608 let child = self.widget(app).child.clone();
609 let mut sized = SizedBox::new();
610 if let Some(size) = placeholder_size {
611 sized = sized.width(size.width()).height(size.height());
612 }
613 sized
614 .child(
615 Offstage::new()
616 .offstage(show_placeholder)
617 .child(TickerMode::new(
618 !show_placeholder,
619 KeyedSubtree::new(child).key(key.into()),
620 )),
621 )
622 .into_widget()
623 }
624}
625
626struct HeroFlightManifest {
631 r#type: HeroFlightDirection,
632 overlay: Handle<OverlayState>,
633 from_route: PageRouteRef,
634 to_route: PageRouteRef,
635 from_hero: Ref<HeroState>,
636 to_hero: Ref<HeroState>,
637 create_rect_tween: Option<CreateRectTween>,
638 shuttle_builder: HeroFlightShuttleBuilder,
639 is_user_gesture_transition: bool,
640 is_diverted: bool,
641
642 animation: Option<Ref<CurvedAnimation>>,
643 from_hero_location: Option<Rect>,
645 to_hero_location: Option<Rect>,
646 is_valid: Option<bool>,
647}
648
649impl HeroFlightManifest {
650 #[expect(clippy::too_many_arguments, reason = "Dart's required named arguments")]
651 fn new(
652 app: &mut App,
653 r#type: HeroFlightDirection,
654 overlay: Handle<OverlayState>,
655 from_route: PageRouteRef,
656 to_route: PageRouteRef,
657 from_hero: Handle<HeroState>,
658 to_hero: Handle<HeroState>,
659 create_rect_tween: Option<CreateRectTween>,
660 shuttle_builder: HeroFlightShuttleBuilder,
661 is_user_gesture_transition: bool,
662 is_diverted: bool,
663 ) -> Ref<HeroFlightManifest> {
664 debug_assert!(*from_hero.widget(app).tag == *to_hero.widget(app).tag);
665 let from_hero = from_hero.keep(app);
666 let to_hero = to_hero.keep(app);
667 app.create(HeroFlightManifest {
668 r#type,
669 overlay,
670 from_route,
671 to_route,
672 from_hero,
673 to_hero,
674 create_rect_tween,
675 shuttle_builder,
676 is_user_gesture_transition,
677 is_diverted,
678 animation: None,
679 from_hero_location: None,
680 to_hero_location: None,
681 is_valid: None,
682 })
683 }
684
685 fn tag(self: Handle<Self>, app: &App) -> Rc<dyn AnyEq> {
686 let from_hero = app.get(self).from_hero.handle();
687 Rc::clone(&from_hero.widget(app).tag)
688 }
689
690 fn animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
691 if let Some(animation) = &app.get(self).animation {
692 return animation.erase();
693 }
694 let (curve, reverse_curve, parent) = match app.get(self).r#type {
695 HeroFlightDirection::Push => {
696 let to_route = app.get(self).to_route.handle();
697 let parent = to_route
698 .as_modal_route()
699 .animation(app)
700 .expect("an installed route has an animation");
701 let to_hero = app.get(self).to_hero.handle();
702 let widget = to_hero.widget(app);
703 let curve = Rc::clone(&widget.curve);
704 let reverse_curve = widget
705 .reverse_curve
706 .clone()
707 .unwrap_or_else(|| Rc::new(Rc::clone(&curve).flipped()));
708 (curve, reverse_curve, parent)
709 }
710 HeroFlightDirection::Pop => {
711 let from_route = app.get(self).from_route.handle();
712 let parent = from_route
713 .as_modal_route()
714 .animation(app)
715 .expect("an installed route has an animation");
716 let from_hero = app.get(self).from_hero.handle();
717 let widget = from_hero.widget(app);
718 let curve = Rc::clone(&widget.curve);
719 let reverse_curve = widget
720 .reverse_curve
721 .clone()
722 .unwrap_or_else(|| Rc::new(Rc::clone(&curve).flipped()));
723 (curve, reverse_curve, parent)
724 }
725 };
726
727 let parent = parent.keep(app);
728 let reverse_curve = (!app.get(self).is_diverted).then_some(reverse_curve);
729 let animation = CurvedAnimation::new(app, parent, curve, reverse_curve);
730 let erased = animation.erase();
731 app.get_mut(self).animation = Some(animation);
732 erased
733 }
734
735 fn create_hero_rect_tween(
736 self: Handle<Self>,
737 app: &mut App,
738 begin: Option<Rect>,
739 end: Option<Rect>,
740 ) -> Rc<dyn RectTweenObject> {
741 let to_hero = app.get(self).to_hero.handle();
742 let create_rect_tween = to_hero
743 .widget(app)
744 .create_rect_tween
745 .clone()
746 .or_else(|| app.get(self).create_rect_tween.clone());
747 match create_rect_tween {
748 Some(create_rect_tween) => create_rect_tween(app, begin, end),
749 None => Rc::new(RectTween::new(app, begin, end)),
750 }
751 }
752
753 fn bounding_box_for(
756 app: &App,
757 context: BuildContext,
758 ancestor_context: Option<BuildContext>,
759 ) -> Rect {
760 debug_assert!(ancestor_context.is_some());
761 let render_box = context
762 .find_render_object(app)
763 .expect("a mounted hero has a render object")
764 .as_box()
765 .expect("a hero's render object is a box");
766 debug_assert!(render_box.has_size(app) && render_box.size(app).is_finite());
767 let ancestor = ancestor_context.and_then(|context| context.find_render_object(app));
768 transform_rect(
769 &render_box.as_object().get_transform_to(app, ancestor),
770 Offset::ZERO & render_box.size(app),
771 )
772 }
773
774 fn from_hero_location(self: Handle<Self>, app: &mut App) -> Rect {
778 if let Some(location) = app.get(self).from_hero_location {
779 return location;
780 }
781 let context = app.get(self).from_hero.context(app);
782 let ancestor_context = app
783 .get(self)
784 .from_route
785 .as_modal_route()
786 .subtree_context(app);
787 let location = HeroFlightManifest::bounding_box_for(app, context, ancestor_context);
788 app.get_mut(self).from_hero_location = Some(location);
789 location
790 }
791
792 fn to_hero_location(self: Handle<Self>, app: &mut App) -> Rect {
796 if let Some(location) = app.get(self).to_hero_location {
797 return location;
798 }
799 let context = app.get(self).to_hero.context(app);
800 let ancestor_context = app.get(self).to_route.as_modal_route().subtree_context(app);
801 let location = HeroFlightManifest::bounding_box_for(app, context, ancestor_context);
802 app.get_mut(self).to_hero_location = Some(location);
803 location
804 }
805
806 fn is_valid(self: Handle<Self>, app: &mut App) -> bool {
812 if let Some(is_valid) = app.get(self).is_valid {
813 return is_valid;
814 }
815 let is_valid = self.to_hero_location(app).is_finite()
816 && (app.get(self).is_diverted || self.from_hero_location(app).is_finite());
817 app.get_mut(self).is_valid = Some(is_valid);
818 is_valid
819 }
820
821 fn dispose(self: Handle<Self>, app: &mut App) {
822 if let Some(animation) = app.get(self).animation.handle() {
823 animation.dispose(app);
824 }
825 }
826}
827
828struct HeroFlight {
833 on_flight_ended: OnFlightEnded,
834
835 hero_rect_tween: Option<Rc<dyn RectTweenObject>>,
836 shuttle: Option<WidgetRef>,
837
838 hero_opacity: AnimationRef<f64>,
839 proxy_animation: Ref<ProxyAnimation>,
840 manifest: Option<Ref<HeroFlightManifest>>,
842
843 overlay_entry: Option<Ref<OverlayEntry>>,
844 aborted: bool,
845
846 reverse_tween: Ref<Tween<f64>>,
849
850 scheduled_perform_animation_update: bool,
851 scheduled_gesture_navigator: Option<Handle<NavigatorState>>,
853}
854
855impl HeroFlight {
856 fn new(app: &mut App, on_flight_ended: OnFlightEnded) -> Ref<HeroFlight> {
857 let hero_opacity = k_always_complete_animation(app);
858 let proxy_animation = ProxyAnimation::new(app, None);
859 let proxy = proxy_animation.handle();
860 let reverse_tween = Tween::new(app, Some(1.0), Some(0.0));
861 let this = app.create(HeroFlight {
862 on_flight_ended,
863 hero_rect_tween: None,
864 shuttle: None,
865 hero_opacity,
866 proxy_animation,
867 manifest: None,
868 overlay_entry: None,
869 aborted: false,
870 reverse_tween,
871 scheduled_perform_animation_update: false,
872 scheduled_gesture_navigator: None,
873 });
874 proxy.add_status_listener(
875 app,
876 AnimationStatusListener::handle_method(
877 this.handle(),
878 HeroFlight::handle_animation_update,
879 ),
880 );
881 this
882 }
883
884 fn manifest(self: Handle<Self>, app: &App) -> Handle<HeroFlightManifest> {
885 app.get(self)
886 .manifest
887 .handle()
888 .expect("the flight has started")
889 }
890
891 fn set_manifest(self: Handle<Self>, app: &mut App, value: Ref<HeroFlightManifest>) {
892 if let Some(manifest) = app.get(self).manifest.handle() {
893 manifest.dispose(app);
894 }
895 app.get_mut(self).manifest = Some(value);
896 }
897
898 fn hero_rect_tween(self: Handle<Self>, app: &App) -> Rc<dyn RectTweenObject> {
899 Rc::clone(
900 app.get(self)
901 .hero_rect_tween
902 .as_ref()
903 .expect("the flight has started"),
904 )
905 }
906
907 fn build_overlay(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
909 if app.get(self).shuttle.is_none() {
910 let manifest = self.manifest(app);
911 let shuttle_builder = Rc::clone(&app.get(manifest).shuttle_builder);
912 let animation = manifest.animation(app);
913 let r#type = app.get(manifest).r#type;
914 let from_hero_context = app.get(manifest).from_hero.context(app);
915 let to_hero_context = app.get(manifest).to_hero.context(app);
916 let shuttle = shuttle_builder(
917 app,
918 context,
919 animation,
920 r#type,
921 from_hero_context,
922 to_hero_context,
923 );
924 app.get_mut(self).shuttle = Some(shuttle);
925 }
926 debug_assert!(app.get(self).shuttle.is_some());
927
928 let proxy_animation: AnimationRef<f64> = app.get(self).proxy_animation.erase();
929 let shuttle = app
930 .get(self)
931 .shuttle
932 .clone()
933 .expect("built just above if it was missing");
934 AnimatedBuilder::new(
935 Rc::new(proxy_animation.clone()),
936 move |app, _context, child| {
937 let rect = self
938 .hero_rect_tween(app)
939 .evaluate(app, proxy_animation.handle())
940 .expect("the hero rect tween has both ends");
941 let mut fade = FadeTransition::new(app.get(self).hero_opacity.clone());
942 if let Some(child) = child {
943 fade = fade.child(child.clone());
944 }
945 Positioned::from_rect(rect, IgnorePointer::new().child(fade)).into_widget()
946 },
947 )
948 .child(shuttle)
949 .into_widget()
950 }
951
952 fn perform_animation_update(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
953 if !status.is_animating() {
954 let proxy_animation = app.get(self).proxy_animation.handle();
955 proxy_animation.set_parent(app, None);
956
957 debug_assert!(app.get(self).overlay_entry.is_some());
958 let overlay_entry = app
959 .get_mut(self)
960 .overlay_entry
961 .take()
962 .expect("a started flight has an overlay entry");
963 overlay_entry.remove(app);
964 overlay_entry.dispose(app);
965 let manifest = self.manifest(app);
970 let from_hero = app.get(manifest).from_hero.handle();
971 let to_hero = app.get(manifest).to_hero.handle();
972 from_hero.end_flight(app, status.is_completed());
973 to_hero.end_flight(app, status.is_dismissed());
974 let on_flight_ended = Rc::clone(&app.get(self).on_flight_ended);
975 on_flight_ended(app, self);
976 Animation::remove_listener(
977 proxy_animation,
978 app,
979 &Listener::handle_method(self, HeroFlight::on_tick),
980 );
981 }
982 }
983
984 fn handle_animation_update(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
985 let manifest = self.manifest(app);
989 let navigator = app.get(manifest).from_route.as_route().navigator(app);
990 if navigator.map(|navigator| navigator.user_gesture_in_progress(app)) != Some(true) {
991 self.perform_animation_update(app, status);
992 return;
993 }
994
995 if app.get(self).scheduled_perform_animation_update {
996 return;
997 }
998
999 let navigator = navigator.expect("checked by the clause above");
1002
1003 debug_assert!(navigator.user_gesture_in_progress(app));
1004 let flight = app.get_mut(self);
1005 flight.scheduled_perform_animation_update = true;
1006 flight.scheduled_gesture_navigator = Some(navigator);
1007 let notifier = navigator.user_gesture_in_progress_notifier(app);
1008 notifier.add_listener(
1009 app,
1010 Listener::handle_method(self, HeroFlight::delayed_perform_animation_update),
1011 );
1012 }
1013
1014 fn delayed_perform_animation_update(self: Handle<Self>, app: &mut App) {
1015 let navigator = app
1016 .get(self)
1017 .scheduled_gesture_navigator
1018 .expect("set where the listener was registered");
1019 debug_assert!(!navigator.user_gesture_in_progress(app));
1020 debug_assert!(app.get(self).scheduled_perform_animation_update);
1021 let flight = app.get_mut(self);
1022 flight.scheduled_perform_animation_update = false;
1023 flight.scheduled_gesture_navigator = None;
1024 let notifier = navigator.user_gesture_in_progress_notifier(app);
1025 notifier.remove_listener(
1026 app,
1027 &Listener::handle_method(self, HeroFlight::delayed_perform_animation_update),
1028 );
1029 let status = app.get(self).proxy_animation.status(app);
1030 self.perform_animation_update(app, status);
1031 }
1032
1033 fn dispose(self: Handle<Self>, app: &mut App) {
1035 if let Some(overlay_entry) = app.get_mut(self).overlay_entry.take() {
1036 overlay_entry.remove(app);
1037 overlay_entry.dispose(app);
1038 let proxy_animation = app.get(self).proxy_animation.handle();
1039 proxy_animation.set_parent(app, None);
1040 Animation::remove_listener(
1041 proxy_animation,
1042 app,
1043 &Listener::handle_method(self, HeroFlight::on_tick),
1044 );
1045 proxy_animation.remove_status_listener(
1046 app,
1047 &AnimationStatusListener::handle_method(self, HeroFlight::handle_animation_update),
1048 );
1049 }
1050 if let Some(manifest) = app.get(self).manifest.handle() {
1051 manifest.dispose(app);
1052 }
1053 }
1054
1055 fn on_tick(self: Handle<Self>, app: &mut App) {
1056 let manifest = self.manifest(app);
1057 let to_hero = app.get(manifest).to_hero.handle();
1058 let to_hero_box = (!app.get(self).aborted && to_hero.mounted(app))
1059 .then(|| to_hero.context(app).find_render_object(app))
1060 .flatten()
1061 .map(|object| object.as_box().expect("a hero's render object is a box"));
1062 let to_hero_origin = match to_hero_box {
1064 Some(to_hero_box)
1065 if to_hero_box.as_object().attached(app) && to_hero_box.has_size(app) =>
1066 {
1067 let ancestor = app
1068 .get(manifest)
1069 .to_route
1070 .as_modal_route()
1071 .subtree_context(app)
1072 .and_then(|context| context.find_render_object(app))
1073 .map(|object| {
1074 object
1075 .as_box()
1076 .expect("a route's subtree render object is a box")
1077 .as_object()
1078 });
1079 Some(to_hero_box.local_to_global(app, Offset::ZERO, ancestor))
1080 }
1081 _ => None,
1082 };
1083
1084 if let Some(to_hero_origin) = to_hero_origin
1085 && to_hero_origin.is_finite()
1086 {
1087 let hero_rect_tween = self.hero_rect_tween(app);
1090 let end = hero_rect_tween
1091 .end(app)
1092 .expect("the hero rect tween has both ends");
1093 if to_hero_origin != end.top_left() {
1094 let hero_rect_end = to_hero_origin & end.size();
1095 let begin = hero_rect_tween.begin(app);
1096 let hero_rect_tween =
1097 manifest.create_hero_rect_tween(app, begin, Some(hero_rect_end));
1098 app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1099 }
1100 } else if app.get(self).hero_opacity.status(app).is_completed() {
1101 let proxy_animation = app.get(self).proxy_animation.clone();
1104 let curve = Interval::new(proxy_animation.value(app), 1.0, Curves::linear());
1105 let curve_tween = CurveTween::new(app, Rc::new(curve));
1106 let reverse_tween = app.get(self).reverse_tween.clone();
1107 let hero_opacity = proxy_animation.drive(app, reverse_tween.chain(curve_tween));
1108 app.get_mut(self).hero_opacity = hero_opacity;
1109 }
1110 app.get_mut(self).aborted =
1112 to_hero_origin.is_none_or(|to_hero_origin| !to_hero_origin.is_finite());
1113 }
1114
1115 fn start(self: Handle<Self>, app: &mut App, initial_manifest: Ref<HeroFlightManifest>) {
1117 debug_assert!(!app.get(self).aborted);
1118 if cfg!(debug_assertions) {
1119 let initial = initial_manifest.animation(app);
1120 let r#type = app.get(&initial_manifest).r#type;
1121 assert!(match r#type {
1122 HeroFlightDirection::Pop =>
1123 app.get(&initial_manifest).is_user_gesture_transition
1126 || initial.status(app) == AnimationStatus::Reverse,
1127 HeroFlightDirection::Push =>
1128 initial.value(app) == 0.0 && initial.status(app) == AnimationStatus::Forward,
1129 });
1130 }
1131
1132 self.set_manifest(app, initial_manifest);
1133
1134 let manifest = self.manifest(app);
1135 let proxy_animation = app.get(self).proxy_animation.handle();
1136 let animation = manifest.animation(app);
1137 let should_include_child_in_placeholder = match app.get(manifest).r#type {
1138 HeroFlightDirection::Pop => {
1139 let parent = ReverseAnimation::new(app, animation).into_erased();
1140 proxy_animation.set_parent(app, Some(parent));
1141 false
1142 }
1143 HeroFlightDirection::Push => {
1144 proxy_animation.set_parent(app, Some(animation));
1145 true
1146 }
1147 };
1148
1149 let begin = manifest.from_hero_location(app);
1150 let end = manifest.to_hero_location(app);
1151 let hero_rect_tween = manifest.create_hero_rect_tween(app, Some(begin), Some(end));
1152 app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1153 let from_hero = app.get(manifest).from_hero.handle();
1154 let to_hero = app.get(manifest).to_hero.handle();
1155 from_hero.start_flight(app, should_include_child_in_placeholder);
1156 to_hero.start_flight(app, false);
1157 let overlay_entry = OverlayEntry::new(
1158 app,
1159 Rc::new(move |app, context| self.build_overlay(app, context)),
1160 false,
1161 false,
1162 false,
1163 );
1164 app.get_mut(self).overlay_entry = Some(overlay_entry.clone());
1165 app.get(manifest)
1166 .overlay
1167 .insert(app, overlay_entry, None, None);
1168 Animation::add_listener(
1169 proxy_animation,
1170 app,
1171 Listener::handle_method(self, HeroFlight::on_tick),
1172 );
1173 }
1174
1175 fn divert(self: Handle<Self>, app: &mut App, new_manifest: Ref<HeroFlightManifest>) {
1178 let manifest = self.manifest(app);
1179 debug_assert!(*manifest.tag(app) == *new_manifest.tag(app));
1180 let proxy_animation = app.get(self).proxy_animation.handle();
1181 if app.get(manifest).r#type == HeroFlightDirection::Push
1182 && app.get(&new_manifest).r#type == HeroFlightDirection::Pop
1183 {
1184 let new_animation = new_manifest.animation(app);
1186 debug_assert!(new_animation.status(app) == AnimationStatus::Reverse);
1187 debug_assert!(app.get(manifest).from_hero == app.get(&new_manifest).to_hero);
1188 debug_assert!(app.get(manifest).to_hero == app.get(&new_manifest).from_hero);
1189 debug_assert!(app.get(manifest).from_route == app.get(&new_manifest).to_route);
1190 debug_assert!(app.get(manifest).to_route == app.get(&new_manifest).from_route);
1191
1192 let parent = ReverseAnimation::new(app, new_animation).into_erased();
1198 proxy_animation.set_parent(app, Some(parent));
1199 let parent_tween = self.hero_rect_tween(app);
1200 app.get_mut(self).hero_rect_tween = Some(Rc::new(ReverseRectTween {
1201 parent: parent_tween,
1202 }));
1203 } else if app.get(manifest).r#type == HeroFlightDirection::Pop
1204 && app.get(&new_manifest).r#type == HeroFlightDirection::Push
1205 {
1206 let new_animation = new_manifest.animation(app);
1208 debug_assert!(new_animation.status(app) == AnimationStatus::Forward);
1209 debug_assert!(app.get(manifest).to_hero == app.get(&new_manifest).from_hero);
1210 debug_assert!(app.get(manifest).to_route == app.get(&new_manifest).from_route);
1211
1212 let value = manifest.animation(app).value(app);
1213 let tween = Tween::new(app, Some(value), Some(1.0));
1214 let parent = new_animation.drive(app, tween);
1215 proxy_animation.set_parent(app, Some(parent));
1216 let from_hero = app.get(manifest).from_hero.handle();
1217 let new_to_hero = app.get(&new_manifest).to_hero.handle();
1218 if from_hero != new_to_hero {
1219 from_hero.end_flight(app, true);
1220 new_to_hero.start_flight(app, false);
1221 let hero_rect_tween = self.hero_rect_tween(app);
1222 let begin = hero_rect_tween.end(app);
1223 let end = new_manifest.to_hero_location(app);
1224 let hero_rect_tween = manifest.create_hero_rect_tween(app, begin, Some(end));
1225 app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1226 } else {
1227 let hero_rect_tween = self.hero_rect_tween(app);
1230 let begin = hero_rect_tween.end(app);
1231 let end = hero_rect_tween.begin(app);
1232 let hero_rect_tween = manifest.create_hero_rect_tween(app, begin, end);
1233 app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1234 }
1235 } else {
1236 debug_assert!(app.get(manifest).from_hero != app.get(&new_manifest).from_hero);
1240 debug_assert!(app.get(manifest).to_hero != app.get(&new_manifest).to_hero);
1241
1242 let hero_rect_tween = self.hero_rect_tween(app);
1243 let begin = hero_rect_tween.evaluate(app, proxy_animation.as_animation());
1244 let end = new_manifest.to_hero_location(app);
1245 let hero_rect_tween = manifest.create_hero_rect_tween(app, begin, Some(end));
1246 app.get_mut(self).hero_rect_tween = Some(hero_rect_tween);
1247 app.get_mut(self).shuttle = None;
1248
1249 let new_animation = new_manifest.animation(app);
1250 if app.get(&new_manifest).r#type == HeroFlightDirection::Pop {
1251 let parent = ReverseAnimation::new(app, new_animation).into_erased();
1252 proxy_animation.set_parent(app, Some(parent));
1253 } else {
1254 proxy_animation.set_parent(app, Some(new_animation));
1255 }
1256
1257 let from_hero = app.get(manifest).from_hero.handle();
1258 let to_hero = app.get(manifest).to_hero.handle();
1259 from_hero.end_flight(app, true);
1260 to_hero.end_flight(app, true);
1261
1262 let new_from_hero = app.get(&new_manifest).from_hero.handle();
1264 let new_to_hero = app.get(&new_manifest).to_hero.handle();
1265 let should_include_child_in_placeholder =
1266 app.get(&new_manifest).r#type == HeroFlightDirection::Push;
1267 new_from_hero.start_flight(app, should_include_child_in_placeholder);
1268 new_to_hero.start_flight(app, false);
1269
1270 app.get(self)
1273 .overlay_entry
1274 .handle()
1275 .expect("a started flight has an overlay entry")
1276 .mark_needs_build(app);
1277 }
1278
1279 self.set_manifest(app, new_manifest);
1280 }
1281
1282 fn abort(self: Handle<Self>, app: &mut App) {
1283 app.get_mut(self).aborted = true;
1284 }
1285}
1286
1287pub struct HeroController {
1294 navigator_observer: NavigatorObserverData,
1295 pub create_rect_tween: Option<CreateRectTween>,
1299 flights: IndexMap<Rc<dyn AnyEq>, Ref<HeroFlight>>,
1301}
1302
1303impl HeroController {
1304 pub fn new(app: &mut App) -> Ref<HeroController> {
1306 app.create(HeroController {
1307 navigator_observer: NavigatorObserverData::new(),
1308 create_rect_tween: None,
1309 flights: IndexMap::new(),
1310 })
1311 }
1312
1313 pub fn create_rect_tween(
1315 self: Ref<Self>,
1316 app: &mut App,
1317 create_rect_tween: CreateRectTween,
1318 ) -> Ref<Self> {
1319 app.get_mut(&self).create_rect_tween = Some(create_rect_tween);
1320 self
1321 }
1322
1323 fn maybe_start_hero_transition(
1326 self: Handle<Self>,
1327 app: &mut App,
1328 from_route: Option<AnyRoute>,
1329 to_route: Option<AnyRoute>,
1330 is_user_gesture_transition: bool,
1331 ) {
1332 if to_route == from_route {
1333 return;
1334 }
1335 let (Some(to_route), Some(from_route)) = (
1336 to_route.and_then(|route| route.as_page_route(app)),
1337 from_route.and_then(|route| route.as_page_route(app)),
1338 ) else {
1339 return;
1340 };
1341 let new_route_animation = to_route
1342 .as_modal_route()
1343 .animation(app)
1344 .expect("an installed route has an animation");
1345 let old_route_animation = from_route
1346 .as_modal_route()
1347 .animation(app)
1348 .expect("an installed route has an animation");
1349 let flight_type = match (
1350 is_user_gesture_transition,
1351 old_route_animation.status(app),
1352 new_route_animation.status(app),
1353 ) {
1354 (true, _, _) | (_, AnimationStatus::Reverse, _) => Some(HeroFlightDirection::Pop),
1355 (_, _, AnimationStatus::Forward) => Some(HeroFlightDirection::Push),
1356 _ => None,
1357 };
1358
1359 if let Some(flight_type) = flight_type {
1361 match flight_type {
1362 HeroFlightDirection::Pop => {
1363 if old_route_animation.value(app) == 0.0 {
1364 return;
1365 }
1366 }
1367 HeroFlightDirection::Push => {
1368 if new_route_animation.value(app) == 1.0 {
1369 return;
1370 }
1371 }
1372 }
1373 }
1374
1375 let from_route_render_box = to_route
1380 .as_modal_route()
1381 .subtree_context(app)
1382 .and_then(|context| context.find_render_object(app))
1383 .map(|object| {
1384 object
1385 .as_box()
1386 .expect("a route's subtree render object is a box")
1387 });
1388 let has_valid_size = from_route_render_box
1389 .is_some_and(|render_box| render_box.has_size(app) && render_box.size(app).is_finite());
1390 if is_user_gesture_transition
1391 && flight_type == Some(HeroFlightDirection::Pop)
1392 && to_route.as_modal_route().maintain_state(app)
1393 && has_valid_size
1394 {
1395 let from_route = from_route.keep(app);
1396 let to_route = to_route.keep(app);
1397 self.start_hero_transition(
1398 app,
1399 from_route,
1400 to_route,
1401 flight_type,
1402 is_user_gesture_transition,
1403 );
1404 } else {
1405 let offstage = new_route_animation.value(app) == 0.0;
1412 to_route.as_modal_route().set_offstage(app, offstage);
1413 let from_route = from_route.keep(app);
1416 let to_route = to_route.keep(app);
1417 let this = self.keep(app);
1418 SchedulerBinding::add_post_frame_callback(
1419 app,
1420 FrameCallback::new(move |app, _| {
1421 if from_route.as_route().navigator(app).is_none()
1422 || to_route.as_route().navigator(app).is_none()
1423 {
1424 return;
1425 }
1426 this.start_hero_transition(
1427 app,
1428 from_route.clone(),
1429 to_route.clone(),
1430 flight_type,
1431 is_user_gesture_transition,
1432 );
1433 }),
1434 self.navigator(app)
1435 .and_then(|navigator| View::maybe_id_of(app, navigator.context(app))),
1436 );
1437 }
1438 }
1439
1440 fn start_hero_transition(
1443 self: Handle<Self>,
1444 app: &mut App,
1445 from: PageRouteRef,
1446 to: PageRouteRef,
1447 flight_type: Option<HeroFlightDirection>,
1448 is_user_gesture_transition: bool,
1449 ) {
1450 to.as_modal_route().set_offstage(app, false);
1453
1454 let navigator = self.navigator(app);
1455 let overlay = navigator.and_then(|navigator| navigator.overlay(app));
1456 let (Some(navigator), Some(overlay)) = (navigator, overlay) else {
1460 return;
1461 };
1462
1463 let from_subtree_context = from.as_modal_route().subtree_context(app);
1468 let from_heroes = match from_subtree_context {
1469 Some(context) => {
1470 Hero::all_heroes_for(app, context, is_user_gesture_transition, navigator)
1471 }
1472 None => IndexMap::new(),
1473 };
1474 let to_subtree_context = to.as_modal_route().subtree_context(app);
1475 let mut to_heroes = match to_subtree_context {
1476 Some(context) => {
1477 Hero::all_heroes_for(app, context, is_user_gesture_transition, navigator)
1478 }
1479 None => IndexMap::new(),
1480 };
1481
1482 for (tag, from_hero) in from_heroes {
1483 let to_hero = to_heroes.get(&tag).copied();
1484 let existing_flight = app.get(self).flights.get(&tag).cloned();
1485 let manifest = match (to_hero, flight_type) {
1486 (Some(to_hero), Some(flight_type)) => {
1487 let shuttle_builder = to_hero
1488 .widget(app)
1489 .flight_shuttle_builder
1490 .clone()
1491 .or_else(|| from_hero.widget(app).flight_shuttle_builder.clone())
1492 .unwrap_or_else(|| {
1493 Rc::new(HeroController::default_hero_flight_shuttle_builder)
1494 });
1495 let create_rect_tween = app.get(self).create_rect_tween.clone();
1496 Some(HeroFlightManifest::new(
1497 app,
1498 flight_type,
1499 overlay,
1500 from.clone(),
1501 to.clone(),
1502 from_hero,
1503 to_hero,
1504 create_rect_tween,
1505 shuttle_builder,
1506 is_user_gesture_transition,
1507 existing_flight.is_some(),
1508 ))
1509 }
1510 _ => None,
1511 };
1512
1513 match manifest {
1516 Some(manifest) if manifest.is_valid(app) => {
1517 to_heroes.shift_remove(&tag);
1518 match existing_flight {
1519 Some(existing_flight) => existing_flight.divert(app, manifest),
1520 None => {
1521 let flight = HeroFlight::new(
1523 app,
1524 Rc::new(move |app, flight| self.handle_flight_ended(app, flight)),
1525 );
1526 flight.start(app, manifest);
1527 app.get_mut(self).flights.insert(tag, flight);
1528 }
1529 }
1530 }
1531 _ => {
1532 if let Some(existing_flight) = existing_flight {
1533 existing_flight.abort(app);
1534 }
1535 }
1536 }
1537 }
1538
1539 for to_hero in to_heroes.into_values() {
1545 to_hero.end_flight(app, false);
1546 }
1547 }
1548
1549 fn handle_flight_ended(self: Handle<Self>, app: &mut App, flight: Handle<HeroFlight>) {
1550 let tag = flight.manifest(app).tag(app);
1551 if let Some(flight) = app.get_mut(self).flights.shift_remove(&tag) {
1552 flight.dispose(app);
1553 }
1554 }
1555
1556 fn default_hero_flight_shuttle_builder(
1557 app: &mut App,
1558 _flight_context: BuildContext,
1559 animation: AnimationRef<f64>,
1560 flight_direction: HeroFlightDirection,
1561 from_hero_context: BuildContext,
1562 to_hero_context: BuildContext,
1563 ) -> WidgetRef {
1564 let to_hero_widget = to_hero_context.widget(app).clone();
1565 let to_hero =
1566 downcast_widget::<Hero>(&*to_hero_widget).expect("a hero context holds a Hero");
1567 let to_hero_child = to_hero.child.clone();
1568
1569 let to_media_query_data = MediaQuery::maybe_of(app, to_hero_context);
1570 let from_media_query_data = MediaQuery::maybe_of(app, from_hero_context);
1571
1572 let (Some(to_media_query_data), Some(from_media_query_data)) =
1573 (to_media_query_data, from_media_query_data)
1574 else {
1575 return to_hero_child;
1576 };
1577
1578 let from_hero_padding = from_media_query_data.padding;
1579 let to_hero_padding = to_media_query_data.padding;
1580
1581 AnimatedBuilder::new(Rc::new(animation.clone()), move |app, _context, _child| {
1582 let padding = match flight_direction {
1583 HeroFlightDirection::Push => {
1584 EdgeInsetsTween::new(Some(from_hero_padding), Some(to_hero_padding))
1585 .evaluate(app, animation.handle())
1586 }
1587 HeroFlightDirection::Pop => {
1588 EdgeInsetsTween::new(Some(to_hero_padding), Some(from_hero_padding))
1589 .evaluate(app, animation.handle())
1590 }
1591 };
1592 MediaQuery::new(
1593 to_media_query_data.copy_with().padding(padding),
1594 to_hero_child.clone(),
1595 )
1596 .into_widget()
1597 })
1598 .into_widget()
1599 }
1600
1601 pub fn dispose(self: Handle<Self>, app: &mut App) {
1603 let flights: Vec<Handle<HeroFlight>> = app
1604 .get(self)
1605 .flights
1606 .values()
1607 .map(Retained::handle)
1608 .collect();
1609 for flight in flights {
1610 flight.dispose(app);
1611 }
1612 }
1613}
1614
1615impl NavigatorObserver for HeroController {
1616 crate::navigator_observer_accessors!();
1617
1618 fn did_change_top(
1619 self: Handle<Self>,
1620 app: &mut App,
1621 top_route: AnyRoute,
1622 previous_top_route: Option<AnyRoute>,
1623 ) {
1624 debug_assert!(top_route.is_current(app));
1625 debug_assert!(self.navigator(app).is_some());
1626 let Some(previous_top_route) = previous_top_route else {
1627 return;
1628 };
1629 let navigator = self.navigator(app).expect("asserted above");
1632 if !navigator.user_gesture_in_progress(app) {
1633 self.maybe_start_hero_transition(app, Some(previous_top_route), Some(top_route), false);
1634 }
1635 }
1636
1637 fn did_start_user_gesture(
1638 self: Handle<Self>,
1639 app: &mut App,
1640 route: AnyRoute,
1641 previous_route: Option<AnyRoute>,
1642 ) {
1643 debug_assert!(self.navigator(app).is_some());
1644 self.maybe_start_hero_transition(app, Some(route), previous_route, true);
1645 }
1646
1647 fn did_stop_user_gesture(self: Handle<Self>, app: &mut App) {
1648 let navigator = self
1649 .navigator(app)
1650 .expect("a gesture is only stopped on an observed navigator");
1651 if navigator.user_gesture_in_progress(app) {
1652 return;
1653 }
1654
1655 let is_invalid_flight = |app: &App, flight: Handle<HeroFlight>| {
1661 let manifest = flight.manifest(app);
1662 app.get(manifest).is_user_gesture_transition
1663 && app.get(manifest).r#type == HeroFlightDirection::Pop
1664 && app.get(flight).proxy_animation.status(app).is_dismissed()
1665 };
1666
1667 let invalid_flights: Vec<Handle<HeroFlight>> = app
1668 .get(self)
1669 .flights
1670 .values()
1671 .map(Retained::handle)
1672 .filter(|flight| is_invalid_flight(app, *flight))
1673 .collect();
1674
1675 for flight in invalid_flights {
1678 flight.handle_animation_update(app, AnimationStatus::Dismissed);
1679 }
1680 }
1681}
1682
1683#[derive(Debug)]
1694pub struct HeroMode {
1695 pub key: Option<KeyRef>,
1697 pub child: WidgetRef,
1699 pub enabled: bool,
1706}
1707
1708impl HeroMode {
1709 #[cfg_attr(debug_assertions, track_caller)]
1712 pub fn new<K>(child: impl IntoWidget<K>) -> HeroMode {
1713 HeroMode {
1714 key: None,
1715 child: child.into_widget(),
1716 enabled: true,
1717 }
1718 }
1719
1720 pub fn key(mut self, key: KeyRef) -> HeroMode {
1722 self.key = Some(key);
1723 self
1724 }
1725
1726 pub fn enabled(mut self, enabled: bool) -> HeroMode {
1728 self.enabled = enabled;
1729 self
1730 }
1731}
1732
1733impl StatelessWidget for HeroMode {
1734 fn key(&self) -> Option<&KeyRef> {
1735 self.key.as_ref()
1736 }
1737
1738 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1739 properties.add(
1740 FlagProperty::new("mode", Some(self.enabled))
1741 .if_true("enabled")
1742 .if_false("disabled")
1743 .with_show_name(true),
1744 );
1745 }
1746
1747 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1748 self.child.clone()
1749 }
1750}
1751
1752#[cfg(test)]
1753mod tests {
1754 use std::time::Duration;
1755 use waft_foundation::AppCell;
1756
1757 use waft_embedder::TextDirection;
1758 use waft_painting::{AlignmentGeometry, EdgeInsets, EdgeInsetsGeometry};
1759 use waft_rendering::AnyRenderBox;
1760
1761 use super::*;
1762 use crate::testing::{WidgetTester, test_widgets};
1763 use crate::widgets::basic::{Align, Directionality, Padding};
1764 use crate::widgets::navigator::{HeroControllerScope, RouteSettings};
1765 use crate::widgets::pages::PageRouteBuilder;
1766 use crate::widgets::routes::RoutePageBuilder;
1767
1768 fn tag() -> Rc<dyn AnyEq> {
1769 Rc::new("photo")
1770 }
1771
1772 fn hero_page(
1774 left: f64,
1775 top: f64,
1776 width: f64,
1777 height: f64,
1778 hero_mode: bool,
1779 ) -> RoutePageBuilder {
1780 Rc::new(move |_app, _context, _animation, _secondary| {
1781 let hero = Hero::new(tag(), SizedBox::new().width(width).height(height));
1782 let child: WidgetRef = if hero_mode {
1783 hero.into_widget()
1784 } else {
1785 HeroMode::new(hero).enabled(false).into_widget()
1786 };
1787 Align::new()
1788 .alignment(AlignmentGeometry::TOP_LEFT)
1789 .child(
1790 Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, 0.0, 0.0)).child(child),
1791 )
1792 .into_widget()
1793 })
1794 }
1795
1796 fn hero_route(app: &mut App, name: &str, page: RoutePageBuilder) -> Ref<PageRouteBuilder> {
1797 PageRouteBuilder::new(app, page)
1798 .settings(app, RouteSettings::new().name(name.to_string()).into())
1799 }
1800
1801 fn hero_navigator(
1803 key: &GlobalKey,
1804 controller: Ref<HeroController>,
1805 first_page: RoutePageBuilder,
1806 ) -> WidgetRef {
1807 Directionality::new(
1808 TextDirection::Ltr,
1809 HeroControllerScope::new(
1810 controller,
1811 Navigator::new().key(key.clone().into()).on_generate_route(
1812 move |app, _settings| {
1813 Some(hero_route(app, "/", first_page.clone()).into_erased())
1814 },
1815 ),
1816 ),
1817 )
1818 .into_widget()
1819 }
1820
1821 fn mount_navigator(
1823 tester: &mut WidgetTester,
1824 key: &GlobalKey,
1825 controller: &Ref<HeroController>,
1826 first_page: RoutePageBuilder,
1827 ) -> Handle<NavigatorState> {
1828 tester.pump_widget(hero_navigator(key, controller.clone(), first_page));
1829 let navigator = key
1830 .current_state::<NavigatorState>(&tester.cell.borrow())
1831 .expect("a mounted navigator");
1832 tester.pump_and_settle();
1833 navigator
1834 }
1835
1836 fn push_second(
1838 tester: &mut WidgetTester,
1839 navigator: Handle<NavigatorState>,
1840 page: RoutePageBuilder,
1841 ) {
1842 tester.update(|app| {
1843 let second = hero_route(app, "second", page);
1844 navigator.push(app, second.into_erased());
1845 });
1846 }
1847
1848 fn ms(millis: u64) -> Duration {
1849 Duration::from_millis(millis)
1850 }
1851
1852 fn overlay_children(app: &mut App, navigator: Handle<NavigatorState>) -> Vec<AnyRenderBox> {
1854 let overlay = navigator.overlay(app).expect("a mounted overlay");
1855 let theater = overlay
1856 .context(app)
1857 .find_render_object(app)
1858 .expect("the overlay is laid out");
1859 let mut children = Vec::new();
1860 theater.visit_children(app, &mut |child| {
1861 children.push(child.as_box().expect("a theater child is a box"));
1862 });
1863 children
1864 }
1865
1866 fn top_overlay_rect(app: &mut App, navigator: Handle<NavigatorState>) -> Rect {
1868 let top = *overlay_children(app, navigator)
1869 .last()
1870 .expect("the overlay has children");
1871 top.local_to_global(app, Offset::ZERO, None) & top.size(app)
1872 }
1873
1874 fn only_flight(app: &App, controller: Handle<HeroController>) -> Handle<HeroFlight> {
1875 let flights = &app.get(controller).flights;
1876 assert_eq!(flights.len(), 1, "one flight per matching tag");
1877 flights
1878 .values()
1879 .next()
1880 .expect("checked just above")
1881 .handle()
1882 }
1883
1884 #[test]
1887 fn a_hero_flies_between_two_page_routes() {
1888 test_widgets(|tester| {
1889 let key = GlobalKey::new();
1890 let controller = tester.update(HeroController::new);
1891 let navigator = mount_navigator(
1892 tester,
1893 &key,
1894 &controller,
1895 hero_page(10.0, 20.0, 40.0, 30.0, true),
1896 );
1897 let entries_before = tester.update(|app| overlay_children(app, navigator).len());
1898
1899 push_second(tester, navigator, hero_page(150.0, 100.0, 80.0, 60.0, true));
1900
1901 tester.pump_by(ms(20));
1903 let (from_hero, to_hero) = tester.update(|app| {
1904 let flight = only_flight(app, controller.handle());
1905 let manifest = flight.manifest(app);
1906 let (from_hero, to_hero) = (
1907 app.get(manifest).from_hero.handle(),
1908 app.get(manifest).to_hero.handle(),
1909 );
1910 assert_eq!(
1911 app.get(manifest).r#type,
1912 HeroFlightDirection::Push,
1913 "a push flies forwards"
1914 );
1915 assert_eq!(
1916 (
1917 app.get(from_hero).placeholder_size,
1918 app.get(to_hero).placeholder_size
1919 ),
1920 (Some(Size::new(40.0, 30.0)), Some(Size::new(80.0, 60.0))),
1921 "both heroes hand their place to a placeholder of their own size"
1922 );
1923 assert_eq!(
1924 manifest.from_hero_location(app),
1925 Rect::from_ltrb(10.0, 20.0, 50.0, 50.0),
1926 "the source hero is measured in its route's coordinate space"
1927 );
1928 assert_eq!(
1929 manifest.to_hero_location(app),
1930 Rect::from_ltrb(150.0, 100.0, 230.0, 160.0),
1931 "the destination hero is measured after the offstage frame laid it out"
1932 );
1933 let tween = flight.hero_rect_tween(app);
1934 assert_eq!(
1935 (tween.transform(app, 0.0), tween.transform(app, 1.0)),
1936 (
1937 Some(Rect::from_ltrb(10.0, 20.0, 50.0, 50.0)),
1938 Some(Rect::from_ltrb(150.0, 100.0, 230.0, 160.0))
1939 ),
1940 "the flight interpolates from the source bounds to the destination bounds"
1941 );
1942 (from_hero, to_hero)
1943 });
1944
1945 tester.pump_by(ms(20));
1947 let children = tester.update(|app| overlay_children(app, navigator));
1948 assert!(
1949 children.len() > entries_before,
1950 "the flight added an overlay entry"
1951 );
1952 let mut rect = tester.update(|app| top_overlay_rect(app, navigator));
1953 assert!(
1954 rect.left < 80.0 && rect.width() < 60.0,
1955 "the shuttle starts at the source hero's bounds, not the destination's: {rect:?}"
1956 );
1957
1958 for _ in 0..4 {
1960 tester.pump_by(ms(40));
1961 let moved = tester.update(|app| top_overlay_rect(app, navigator));
1962 assert!(
1963 moved.left > rect.left && moved.width() > rect.width(),
1964 "the shuttle's rect grows towards the destination: {rect:?} then {moved:?}"
1965 );
1966 rect = moved;
1967 }
1968
1969 tester.pump_and_settle();
1970 tester.update(|app| {
1971 assert!(
1972 app.get(&controller).flights.is_empty(),
1973 "the finished flight is removed from the controller"
1974 );
1975 assert_eq!(
1976 overlay_children(app, navigator).len(),
1977 entries_before + 1,
1978 "the shuttle's entry is gone; only the pushed route's entry remains"
1979 );
1980 assert!(
1981 app.get(to_hero).placeholder_size.is_none(),
1982 "the destination hero is visible again"
1983 );
1984 assert!(
1985 app.get(from_hero).placeholder_size.is_some(),
1986 "the source hero stays hidden underneath the route on top"
1987 );
1988 });
1989 });
1990 }
1991
1992 #[test]
1993 fn popping_back_flies_the_hero_home_and_clears_its_placeholder() {
1994 test_widgets(|tester| {
1995 let key = GlobalKey::new();
1996 let controller = tester.update(HeroController::new);
1997 let navigator = mount_navigator(
1998 tester,
1999 &key,
2000 &controller,
2001 hero_page(10.0, 20.0, 40.0, 30.0, true),
2002 );
2003
2004 push_second(tester, navigator, hero_page(150.0, 100.0, 80.0, 60.0, true));
2005 tester.pump_and_settle();
2006 assert!(
2007 tester.cell.borrow().get(&controller).flights.is_empty(),
2008 "the push flight is over"
2009 );
2010
2011 tester.update(|app| navigator.pop(app, None));
2012 tester.pump_by(ms(20));
2013 let to_hero = tester.update(|app| {
2014 let flight = only_flight(app, controller.handle());
2015 let manifest = flight.manifest(app);
2016 assert_eq!(
2017 app.get(manifest).r#type,
2018 HeroFlightDirection::Pop,
2019 "a pop flies backwards"
2020 );
2021 app.get(manifest).to_hero.handle()
2022 });
2023
2024 tester.pump_by(ms(20));
2025 let mut rect = tester.update(|app| top_overlay_rect(app, navigator));
2026 assert!(
2027 rect.left > 80.0,
2028 "the shuttle starts at the popped route's hero: {rect:?}"
2029 );
2030 for _ in 0..4 {
2031 tester.pump_by(ms(40));
2032 let moved = tester.update(|app| top_overlay_rect(app, navigator));
2033 assert!(
2034 moved.left < rect.left,
2035 "the shuttle flies back: {rect:?} then {moved:?}"
2036 );
2037 rect = moved;
2038 }
2039
2040 tester.pump_and_settle();
2041 let app = tester.cell.borrow();
2042 assert!(app.get(&controller).flights.is_empty());
2043 assert!(
2044 app.get(to_hero).placeholder_size.is_none(),
2045 "the hero that stays on screen shows its child again"
2046 );
2047 });
2048 }
2049
2050 #[test]
2051 fn a_disabled_hero_mode_keeps_the_hero_out_of_the_flight() {
2052 test_widgets(|tester| {
2053 let key = GlobalKey::new();
2054 let controller = tester.update(HeroController::new);
2055 let navigator = mount_navigator(
2056 tester,
2057 &key,
2058 &controller,
2059 hero_page(10.0, 20.0, 40.0, 30.0, false),
2060 );
2061 let entries_before = tester.update(|app| overlay_children(app, navigator).len());
2062
2063 push_second(tester, navigator, hero_page(150.0, 100.0, 80.0, 60.0, true));
2064 tester.pump_by(ms(20));
2065 assert!(
2066 tester.cell.borrow().get(&controller).flights.is_empty(),
2067 "the source hero is behind a disabled HeroMode, so no pair matches"
2068 );
2069
2070 tester.pump_and_settle();
2071 assert_eq!(
2072 tester.update(|app| overlay_children(app, navigator).len()),
2073 entries_before + 1,
2074 "nothing but the pushed route was added to the overlay"
2075 );
2076 });
2077 }
2078
2079 #[test]
2080 fn a_custom_flight_shuttle_builder_supplies_the_in_flight_widget() {
2081 test_widgets(|tester| {
2082 let key = GlobalKey::new();
2083 let controller = tester.update(HeroController::new);
2084 let built = Rc::new(std::cell::Cell::new(0u32));
2085 let shuttle_builder: HeroFlightShuttleBuilder = {
2086 let built = Rc::clone(&built);
2087 Rc::new(move |_app, _flight, _animation, direction, _from, _to| {
2088 built.set(built.get() + 1);
2089 assert_eq!(direction, HeroFlightDirection::Push);
2090 SizedBox::new().width(11.0).height(13.0).into_widget()
2091 })
2092 };
2093 let navigator = mount_navigator(
2094 tester,
2095 &key,
2096 &controller,
2097 hero_page(10.0, 20.0, 40.0, 30.0, true),
2098 );
2099
2100 let page: RoutePageBuilder = Rc::new(move |_app, _context, _animation, _secondary| {
2101 Align::new()
2102 .alignment(AlignmentGeometry::TOP_LEFT)
2103 .child(
2104 Padding::new(EdgeInsetsGeometry::from_ltrb(150.0, 100.0, 0.0, 0.0)).child(
2105 Hero::new(tag(), SizedBox::new().width(80.0).height(60.0))
2106 .flight_shuttle_builder(shuttle_builder.clone()),
2107 ),
2108 )
2109 .into_widget()
2110 });
2111 push_second(tester, navigator, page);
2112 tester.pump_by(ms(20));
2113 tester.pump_by(ms(20));
2114
2115 assert_eq!(built.get(), 1, "the shuttle is built once and then reused");
2116 assert!(!tester.cell.borrow().get(&controller).flights.is_empty());
2119 tester.pump_and_settle();
2120 assert!(tester.cell.borrow().get(&controller).flights.is_empty());
2121 });
2122 }
2123
2124 #[test]
2125 fn hero_tags_match_by_value_and_type() {
2126 let a: Rc<dyn AnyEq> = Rc::new("photo");
2127 let b: Rc<dyn AnyEq> = Rc::new("photo");
2128 let c: Rc<dyn AnyEq> = Rc::new("other");
2129 let number: Rc<dyn AnyEq> = Rc::new(1_i32);
2130 assert!(*a == *b);
2131 assert!(*a != *c);
2132 assert!(*a != *number, "two tags of different types never match");
2133
2134 let mut flights: IndexMap<Rc<dyn AnyEq>, u32> = IndexMap::new();
2135 flights.insert(Rc::clone(&a), 1);
2136 assert_eq!(flights.get(&b).copied(), Some(1));
2137 assert_eq!(flights.get(&number), None);
2138 }
2139
2140 #[test]
2141 fn a_reverse_rect_tween_swaps_its_parent_ends() {
2142 let cell = AppCell::new();
2143 let mut app = cell.borrow_mut();
2144 let begin = Rect::from_ltrb(0.0, 0.0, 10.0, 10.0);
2145 let end = Rect::from_ltrb(20.0, 20.0, 40.0, 40.0);
2146 let parent: Rc<dyn RectTweenObject> =
2147 Rc::new(RectTween::new(&mut app, Some(begin), Some(end)));
2148 let reversed = ReverseRectTween {
2149 parent: Rc::clone(&parent),
2150 };
2151 assert_eq!(reversed.begin(&app), Some(end));
2152 assert_eq!(reversed.end(&app), Some(begin));
2153 assert_eq!(reversed.transform(&app, 0.0), Some(end));
2154 assert_eq!(reversed.transform(&app, 1.0), Some(begin));
2155 assert_eq!(
2156 reversed.lerp(&app, 0.25),
2157 parent.lerp(&app, 0.75),
2158 "the parent is evaluated in reverse"
2159 );
2160 }
2161
2162 #[test]
2163 fn an_edge_insets_tween_interpolates_the_shuttle_padding() {
2164 let cell = AppCell::new();
2165 let app = cell.borrow();
2166 let tween = EdgeInsetsTween::new(
2167 Some(EdgeInsets::from_ltrb(0.0, 0.0, 0.0, 0.0)),
2168 Some(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0)),
2169 );
2170 assert_eq!(
2171 tween.transform(&app, 0.5),
2172 EdgeInsets::from_ltrb(5.0, 10.0, 15.0, 20.0)
2173 );
2174 assert_eq!(
2175 tween.transform(&app, 1.0),
2176 EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0)
2177 );
2178 }
2179}