1use std::any::TypeId;
7use std::f64::consts::PI;
8use std::fmt::{self, Debug};
9use std::rc::Rc;
10
11use waft_animation::{Animatable, AnimationRef, AnyAnimation};
12use waft_embedder::{FilterQuality, Matrix4, Offset, Rect, Size, TextAlign, TextDirection};
13use waft_foundation::{
14 App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listenable, Listener,
15};
16use waft_painting::{Alignment, AlignmentGeometry, Axis, DecorationRef, TextOverflow, TextStyle};
17use waft_rendering::{
18 AnyRenderObject, DecorationPosition, RelativeRect, RenderAnimatedOpacity,
19 RenderAnimatedOpacityMixin, RenderBox, RenderHandle,
20};
21
22use crate::framework::{
23 BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, State,
24 StateData, Stateful, StatefulWidget, WidgetRef, downcast_widget, short_type_name,
25};
26use crate::widgets::basic::{Align, ClipRect, FractionalTranslation, Positioned, Transform};
27use crate::widgets::container::DecoratedBox;
28use crate::widgets::text::DefaultTextStyle;
29
30pub trait AnimatedWidget: Debug + 'static {
80 fn key(&self) -> Option<&KeyRef> {
82 None
83 }
84
85 fn listenable(&self) -> Rc<dyn Listenable>;
94
95 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef;
98
99 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
102 let listenable = self.listenable();
103 let identity = Rc::as_ptr(&listenable) as *const () as usize as u64;
104 properties.add(DiagnosticsProperty::<String>::new(
105 "listenable",
106 Some(waft_foundation::describe_identity("Listenable", identity)),
107 ));
108 }
109}
110
111pub struct AnimatedKind;
113
114pub struct Animated<W: AnimatedWidget>(pub W);
118
119impl<W: AnimatedWidget> IntoWidget<AnimatedKind> for W {
120 #[cfg_attr(debug_assertions, track_caller)]
121 fn into_widget(self) -> WidgetRef {
122 Rc::new(Stateful(
123 Animated(self),
124 crate::CreationLocation::of_caller(),
125 ))
126 }
127}
128
129impl<W: AnimatedWidget> StatefulWidget for Animated<W> {
130 type State = AnimatedState<W>;
131
132 fn key(&self) -> Option<&KeyRef> {
133 self.0.key()
134 }
135
136 fn type_name(&self) -> &'static str {
137 short_type_name::<W>()
138 }
139
140 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
141 self.0.debug_fill_properties(properties);
142 }
143
144 fn create_state(&self) -> AnimatedState<W> {
145 AnimatedState {
146 state: StateData::new(),
147 }
148 }
149}
150
151impl<W: AnimatedWidget> Debug for Animated<W> {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 self.0.fmt(f)
154 }
155}
156
157pub struct AnimatedState<W: AnimatedWidget> {
159 state: StateData<Animated<W>>,
160}
161
162impl<W: AnimatedWidget> State for AnimatedState<W> {
163 type Widget = Animated<W>;
164 crate::state_accessors!();
165
166 fn init_state(self: Handle<Self>, app: &mut App) {
167 let listenable = self.widget(app).0.listenable();
168 listenable.add_listener(app, Listener::handle_method(self, Self::handle_change));
169 }
170
171 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Animated<W>) {
172 let listenable = self.widget(app).0.listenable();
173 let old_listenable = old_widget.0.listenable();
174 if !Rc::ptr_eq(&listenable, &old_listenable) {
175 old_listenable
176 .remove_listener(app, &Listener::handle_method(self, Self::handle_change));
177 listenable.add_listener(app, Listener::handle_method(self, Self::handle_change));
178 }
179 }
180
181 fn dispose(self: Handle<Self>, app: &mut App) {
182 let listenable = self.widget(app).0.listenable();
183 listenable.remove_listener(app, &Listener::handle_method(self, Self::handle_change));
184 }
185
186 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
187 let widget = context.widget(app).clone();
188 downcast_widget::<Animated<W>>(&*widget)
189 .expect("an AnimatedState builds its AnimatedWidget")
190 .0
191 .build(app, context)
192 }
193}
194
195impl<W: AnimatedWidget> AnimatedState<W> {
196 fn handle_change(self: Handle<Self>, app: &mut App) {
197 if !self.mounted(app) {
198 return;
199 }
200 self.set_state(app, |_state| {
201 });
203 }
204}
205
206#[derive(Clone)]
222pub struct DelegatedTransitionBuilder {
223 builder: Rc<DelegatedTransitionBuilderFn>,
224 identity: DelegatedTransitionBuilderIdentity,
225}
226
227type DelegatedTransitionBuilderFn = dyn Fn(
229 &mut App,
230 BuildContext,
231 AnimationRef<f64>,
232 AnimationRef<f64>,
233 bool,
234 Option<&WidgetRef>,
235) -> Option<WidgetRef>;
236
237#[derive(Clone, Copy, PartialEq)]
240enum DelegatedTransitionBuilderIdentity {
241 Closure,
242 Function(TypeId),
243}
244
245impl DelegatedTransitionBuilder {
246 pub fn new(
248 builder: impl Fn(
249 &mut App,
250 BuildContext,
251 AnimationRef<f64>,
252 AnimationRef<f64>,
253 bool,
254 Option<&WidgetRef>,
255 ) -> Option<WidgetRef>
256 + 'static,
257 ) -> DelegatedTransitionBuilder {
258 DelegatedTransitionBuilder {
259 builder: Rc::new(builder),
260 identity: DelegatedTransitionBuilderIdentity::Closure,
261 }
262 }
263
264 pub fn function<F>(builder: F) -> DelegatedTransitionBuilder
269 where
270 F: Fn(
271 &mut App,
272 BuildContext,
273 AnimationRef<f64>,
274 AnimationRef<f64>,
275 bool,
276 Option<&WidgetRef>,
277 ) -> Option<WidgetRef>
278 + 'static,
279 {
280 const {
281 assert!(
282 std::mem::size_of::<F>() == 0,
283 "pass the function by name: a fn pointer or capturing closure has no canonical \
284 identity"
285 )
286 };
287 DelegatedTransitionBuilder {
288 builder: Rc::new(builder),
289 identity: DelegatedTransitionBuilderIdentity::Function(TypeId::of::<F>()),
290 }
291 }
292
293 pub fn call(
295 &self,
296 app: &mut App,
297 context: BuildContext,
298 animation: AnimationRef<f64>,
299 secondary_animation: AnimationRef<f64>,
300 allow_snapshotting: bool,
301 child: Option<&WidgetRef>,
302 ) -> Option<WidgetRef> {
303 (self.builder)(
304 app,
305 context,
306 animation,
307 secondary_animation,
308 allow_snapshotting,
309 child,
310 )
311 }
312}
313
314impl PartialEq for DelegatedTransitionBuilder {
315 fn eq(&self, other: &DelegatedTransitionBuilder) -> bool {
316 match (self.identity, other.identity) {
317 (
318 DelegatedTransitionBuilderIdentity::Closure,
319 DelegatedTransitionBuilderIdentity::Closure,
320 ) => Rc::ptr_eq(&self.builder, &other.builder),
321 (mine, theirs) => mine == theirs,
322 }
323 }
324}
325
326impl Debug for DelegatedTransitionBuilder {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 f.write_str("DelegatedTransitionBuilder")
329 }
330}
331
332#[derive(Debug)]
353pub struct SlideTransition {
354 pub key: Option<KeyRef>,
356
357 pub position: AnimationRef<Offset>,
363
364 pub text_direction: Option<TextDirection>,
376
377 pub transform_hit_tests: bool,
384
385 pub child: Option<WidgetRef>,
387}
388
389impl SlideTransition {
390 pub fn new(position: AnimationRef<Offset>) -> SlideTransition {
392 SlideTransition {
393 key: None,
394 position,
395 text_direction: None,
396 transform_hit_tests: true,
397 child: None,
398 }
399 }
400
401 pub fn key(mut self, key: KeyRef) -> SlideTransition {
403 self.key = Some(key);
404 self
405 }
406
407 pub fn text_direction(mut self, text_direction: TextDirection) -> SlideTransition {
409 self.text_direction = Some(text_direction);
410 self
411 }
412
413 pub fn transform_hit_tests(mut self, transform_hit_tests: bool) -> SlideTransition {
415 self.transform_hit_tests = transform_hit_tests;
416 self
417 }
418
419 #[cfg_attr(debug_assertions, track_caller)]
421 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SlideTransition {
422 self.child = Some(child.into_widget());
423 self
424 }
425}
426
427impl AnimatedWidget for SlideTransition {
428 fn key(&self) -> Option<&KeyRef> {
429 self.key.as_ref()
430 }
431
432 fn listenable(&self) -> Rc<dyn Listenable> {
433 Rc::new(self.position.clone())
434 }
435
436 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
437 let mut offset = self.position.value(app);
438 if self.text_direction == Some(TextDirection::Rtl) {
439 offset = Offset::new(-offset.dx(), offset.dy());
440 }
441 let mut translation =
442 FractionalTranslation::new(offset).transform_hit_tests(self.transform_hit_tests);
443 if let Some(child) = &self.child {
444 translation = translation.child(child.clone());
445 }
446 translation.into_widget()
447 }
448}
449
450pub type TransformCallback = Rc<dyn Fn(f64) -> Matrix4>;
455
456pub struct MatrixTransition {
468 pub key: Option<KeyRef>,
470
471 pub on_transform: TransformCallback,
474
475 pub animation: AnimationRef<f64>,
480
481 pub alignment: Alignment,
487
488 pub filter_quality: Option<FilterQuality>,
497
498 pub child: Option<WidgetRef>,
500}
501
502impl MatrixTransition {
503 pub fn new(
507 animation: AnimationRef<f64>,
508 on_transform: impl Fn(f64) -> Matrix4 + 'static,
509 ) -> MatrixTransition {
510 MatrixTransition {
511 key: None,
512 on_transform: Rc::new(on_transform),
513 animation,
514 alignment: Alignment::CENTER,
515 filter_quality: None,
516 child: None,
517 }
518 }
519
520 pub fn key(mut self, key: KeyRef) -> MatrixTransition {
522 self.key = Some(key);
523 self
524 }
525
526 pub fn alignment(mut self, alignment: Alignment) -> MatrixTransition {
528 self.alignment = alignment;
529 self
530 }
531
532 pub fn filter_quality(mut self, filter_quality: FilterQuality) -> MatrixTransition {
534 self.filter_quality = Some(filter_quality);
535 self
536 }
537
538 #[cfg_attr(debug_assertions, track_caller)]
540 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MatrixTransition {
541 self.child = Some(child.into_widget());
542 self
543 }
544
545 fn build_transform(
548 app: &App,
549 animation: AnyAnimation<f64>,
550 transform: Matrix4,
551 alignment: Alignment,
552 filter_quality: Option<FilterQuality>,
553 child: Option<&WidgetRef>,
554 ) -> WidgetRef {
555 let mut transform =
560 Transform::new(transform).alignment(AlignmentGeometry::Alignment(alignment));
561 transform.filter_quality = if animation.is_animating(app) {
562 filter_quality
563 } else {
564 None
565 };
566 if let Some(child) = child {
567 transform = transform.child(child.clone());
568 }
569 transform.into_widget()
570 }
571}
572
573impl Debug for MatrixTransition {
574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575 f.debug_struct("MatrixTransition")
576 .field("animation", &self.animation)
577 .field("alignment", &self.alignment)
578 .field("filter_quality", &self.filter_quality)
579 .field("child", &self.child)
580 .finish_non_exhaustive()
581 }
582}
583
584impl AnimatedWidget for MatrixTransition {
585 fn key(&self) -> Option<&KeyRef> {
586 self.key.as_ref()
587 }
588
589 fn listenable(&self) -> Rc<dyn Listenable> {
590 Rc::new(self.animation.clone())
591 }
592
593 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
594 let transform = (self.on_transform)(self.animation.value(app));
595 MatrixTransition::build_transform(
596 app,
597 self.animation.handle(),
598 transform,
599 self.alignment,
600 self.filter_quality,
601 self.child.as_ref(),
602 )
603 }
604}
605
606#[derive(Debug)]
617pub struct ScaleTransition {
618 pub key: Option<KeyRef>,
620
621 pub animation: AnimationRef<f64>,
624
625 pub alignment: Alignment,
627
628 pub filter_quality: Option<FilterQuality>,
630
631 pub child: Option<WidgetRef>,
633}
634
635impl ScaleTransition {
636 pub fn new(scale: AnimationRef<f64>) -> ScaleTransition {
640 ScaleTransition {
641 key: None,
642 animation: scale,
643 alignment: Alignment::CENTER,
644 filter_quality: None,
645 child: None,
646 }
647 }
648
649 pub fn scale(&self) -> AnyAnimation<f64> {
651 self.animation.handle()
652 }
653
654 pub fn key(mut self, key: KeyRef) -> ScaleTransition {
656 self.key = Some(key);
657 self
658 }
659
660 pub fn alignment(mut self, alignment: Alignment) -> ScaleTransition {
662 self.alignment = alignment;
663 self
664 }
665
666 pub fn filter_quality(mut self, filter_quality: FilterQuality) -> ScaleTransition {
668 self.filter_quality = Some(filter_quality);
669 self
670 }
671
672 #[cfg_attr(debug_assertions, track_caller)]
674 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ScaleTransition {
675 self.child = Some(child.into_widget());
676 self
677 }
678
679 fn handle_scale_matrix(value: f64) -> Matrix4 {
684 Matrix4::scale(value as f32, value as f32)
685 }
686}
687
688impl AnimatedWidget for ScaleTransition {
689 fn key(&self) -> Option<&KeyRef> {
690 self.key.as_ref()
691 }
692
693 fn listenable(&self) -> Rc<dyn Listenable> {
694 Rc::new(self.animation.clone())
695 }
696
697 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
698 let transform = ScaleTransition::handle_scale_matrix(self.animation.value(app));
699 MatrixTransition::build_transform(
700 app,
701 self.animation.handle(),
702 transform,
703 self.alignment,
704 self.filter_quality,
705 self.child.as_ref(),
706 )
707 }
708}
709
710#[derive(Debug)]
719pub struct RotationTransition {
720 pub key: Option<KeyRef>,
722
723 pub animation: AnimationRef<f64>,
725
726 pub alignment: Alignment,
728
729 pub filter_quality: Option<FilterQuality>,
731
732 pub child: Option<WidgetRef>,
734}
735
736impl RotationTransition {
737 pub fn new(turns: AnimationRef<f64>) -> RotationTransition {
739 RotationTransition {
740 key: None,
741 animation: turns,
742 alignment: Alignment::CENTER,
743 filter_quality: None,
744 child: None,
745 }
746 }
747
748 pub fn turns(&self) -> AnyAnimation<f64> {
750 self.animation.handle()
751 }
752
753 pub fn key(mut self, key: KeyRef) -> RotationTransition {
755 self.key = Some(key);
756 self
757 }
758
759 pub fn alignment(mut self, alignment: Alignment) -> RotationTransition {
761 self.alignment = alignment;
762 self
763 }
764
765 pub fn filter_quality(mut self, filter_quality: FilterQuality) -> RotationTransition {
767 self.filter_quality = Some(filter_quality);
768 self
769 }
770
771 #[cfg_attr(debug_assertions, track_caller)]
773 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RotationTransition {
774 self.child = Some(child.into_widget());
775 self
776 }
777
778 fn handle_turns_matrix(value: f64) -> Matrix4 {
783 Matrix4::rotation((value * PI * 2.0) as f32)
784 }
785}
786
787impl AnimatedWidget for RotationTransition {
788 fn key(&self) -> Option<&KeyRef> {
789 self.key.as_ref()
790 }
791
792 fn listenable(&self) -> Rc<dyn Listenable> {
793 Rc::new(self.animation.clone())
794 }
795
796 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
797 let transform = RotationTransition::handle_turns_matrix(self.animation.value(app));
798 MatrixTransition::build_transform(
799 app,
800 self.animation.handle(),
801 transform,
802 self.alignment,
803 self.filter_quality,
804 self.child.as_ref(),
805 )
806 }
807}
808
809#[derive(Debug)]
832pub struct SizeTransition {
833 pub key: Option<KeyRef>,
835
836 pub axis: Axis,
839
840 pub size_factor: AnimationRef<f64>,
849
850 #[deprecated(
870 note = "Use alignment instead. This property provides full control over both axes, \
871 which is an improvement over the old axisAlignment. This feature was \
872 deprecated after v3.41.0-1.0.pre."
873 )]
874 pub axis_alignment: Option<f64>,
875
876 pub alignment: Option<AlignmentGeometry>,
878
879 pub fixed_cross_axis_size_factor: Option<f64>,
886
887 pub child: Option<WidgetRef>,
889}
890
891impl SizeTransition {
892 #[allow(deprecated)]
898 pub fn new(size_factor: AnimationRef<f64>) -> SizeTransition {
899 SizeTransition {
900 key: None,
901 axis: Axis::Vertical,
902 size_factor,
903 axis_alignment: None,
904 alignment: None,
905 fixed_cross_axis_size_factor: None,
906 child: None,
907 }
908 }
909
910 pub fn key(mut self, key: KeyRef) -> SizeTransition {
912 self.key = Some(key);
913 self
914 }
915
916 pub fn axis(mut self, axis: Axis) -> SizeTransition {
918 self.axis = axis;
919 self
920 }
921
922 #[deprecated(
924 note = "Use alignment instead. This property provides full control over both axes, \
925 which is an improvement over the old axisAlignment. This feature was \
926 deprecated after v3.41.0-1.0.pre."
927 )]
928 #[allow(deprecated)]
929 pub fn axis_alignment(mut self, axis_alignment: f64) -> SizeTransition {
930 debug_assert!(
931 self.alignment.is_none(),
932 "Cannot provide both axisAlignment and alignment as axisAlignment has been \
933 deprecated and superseded by alignment."
934 );
935 self.axis_alignment = Some(axis_alignment);
936 self
937 }
938
939 #[allow(deprecated)]
941 pub fn alignment(mut self, alignment: AlignmentGeometry) -> SizeTransition {
942 debug_assert!(
943 self.axis_alignment.is_none(),
944 "Cannot provide both axisAlignment and alignment as axisAlignment has been \
945 deprecated and superseded by alignment."
946 );
947 self.alignment = Some(alignment);
948 self
949 }
950
951 pub fn fixed_cross_axis_size_factor(
953 mut self,
954 fixed_cross_axis_size_factor: f64,
955 ) -> SizeTransition {
956 debug_assert!(fixed_cross_axis_size_factor >= 0.0);
957 self.fixed_cross_axis_size_factor = Some(fixed_cross_axis_size_factor);
958 self
959 }
960
961 #[cfg_attr(debug_assertions, track_caller)]
963 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SizeTransition {
964 self.child = Some(child.into_widget());
965 self
966 }
967}
968
969impl AnimatedWidget for SizeTransition {
970 fn key(&self) -> Option<&KeyRef> {
971 self.key.as_ref()
972 }
973
974 fn listenable(&self) -> Rc<dyn Listenable> {
975 Rc::new(self.size_factor.clone())
976 }
977
978 #[allow(deprecated)]
979 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
980 let axis_alignment = self.axis_alignment.unwrap_or(0.0);
981 let alignment = self.alignment.unwrap_or(match self.axis {
982 Axis::Horizontal => AlignmentGeometry::directional(axis_alignment, -1.0),
983 Axis::Vertical => AlignmentGeometry::directional(-1.0, axis_alignment),
984 });
985 let size_factor = self.size_factor.value(app).max(0.0);
986 let (height_factor, width_factor) = match self.axis {
987 Axis::Vertical => (Some(size_factor), self.fixed_cross_axis_size_factor),
988 Axis::Horizontal => (self.fixed_cross_axis_size_factor, Some(size_factor)),
989 };
990 let mut align = Align::new().alignment(alignment);
991 if let Some(height_factor) = height_factor {
992 align = align.height_factor(height_factor);
993 }
994 if let Some(width_factor) = width_factor {
995 align = align.width_factor(width_factor);
996 }
997 if let Some(child) = &self.child {
998 align = align.child(child.clone());
999 }
1000 ClipRect::new().child(align).into_widget()
1001 }
1002}
1003
1004#[derive(Debug)]
1036pub struct FadeTransition {
1037 pub key: Option<KeyRef>,
1039
1040 pub opacity: AnimationRef<f64>,
1047
1048 pub child: Option<WidgetRef>,
1050}
1051
1052impl FadeTransition {
1053 pub fn new(opacity: AnimationRef<f64>) -> FadeTransition {
1055 FadeTransition {
1056 key: None,
1057 opacity,
1058 child: None,
1059 }
1060 }
1061
1062 pub fn key(mut self, key: KeyRef) -> FadeTransition {
1064 self.key = Some(key);
1065 self
1066 }
1067
1068 #[cfg_attr(debug_assertions, track_caller)]
1070 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> FadeTransition {
1071 self.child = Some(child.into_widget());
1072 self
1073 }
1074}
1075
1076impl RenderObjectWidget for FadeTransition {
1077 type RenderObject = RenderAnimatedOpacity;
1078
1079 fn key(&self) -> Option<&KeyRef> {
1080 self.key.as_ref()
1081 }
1082
1083 fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1084 properties.add(DiagnosticsProperty::<String>::new(
1085 "opacity",
1086 Some(self.opacity.to_string(app)),
1087 ));
1088 }
1089
1090 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1091 RenderAnimatedOpacity::new(app, self.opacity.clone(), None).as_object()
1092 }
1093
1094 fn update_render_object(
1095 &self,
1096 app: &mut App,
1097 _context: BuildContext,
1098 render_object: RenderHandle<RenderAnimatedOpacity>,
1099 ) {
1100 render_object.set_opacity(app, self.opacity.clone());
1101 }
1102}
1103
1104impl SingleChildRenderObjectWidget for FadeTransition {
1105 fn child(&self) -> Option<&WidgetRef> {
1106 self.child.as_ref()
1107 }
1108}
1109
1110#[derive(Clone, Debug)]
1123pub struct RelativeRectTween {
1124 pub begin: Option<RelativeRect>,
1126
1127 pub end: Option<RelativeRect>,
1129}
1130
1131impl RelativeRectTween {
1132 pub fn new(begin: Option<RelativeRect>, end: Option<RelativeRect>) -> RelativeRectTween {
1137 RelativeRectTween { begin, end }
1138 }
1139
1140 pub fn lerp(&self, t: f64) -> RelativeRect {
1142 RelativeRect::lerp(self.begin, self.end, t)
1143 .expect("RelativeRectTween.begin or end must be set before use")
1144 }
1145}
1146
1147impl Animatable<RelativeRect> for RelativeRectTween {
1148 fn transform(&self, _app: &App, t: f64) -> RelativeRect {
1149 if t == 0.0 {
1150 return self.begin.expect("Tween.begin must be set before use");
1151 }
1152 if t == 1.0 {
1153 return self.end.expect("Tween.end must be set before use");
1154 }
1155 self.lerp(t)
1156 }
1157}
1158
1159#[derive(Debug)]
1180pub struct PositionedTransition {
1181 pub key: Option<KeyRef>,
1183
1184 pub rect: AnimationRef<RelativeRect>,
1186
1187 pub child: WidgetRef,
1189}
1190
1191impl PositionedTransition {
1192 #[cfg_attr(debug_assertions, track_caller)]
1194 pub fn new<K>(
1195 rect: AnimationRef<RelativeRect>,
1196 child: impl IntoWidget<K>,
1197 ) -> PositionedTransition {
1198 PositionedTransition {
1199 key: None,
1200 rect,
1201 child: child.into_widget(),
1202 }
1203 }
1204
1205 pub fn key(mut self, key: KeyRef) -> PositionedTransition {
1207 self.key = Some(key);
1208 self
1209 }
1210}
1211
1212impl AnimatedWidget for PositionedTransition {
1213 fn key(&self) -> Option<&KeyRef> {
1214 self.key.as_ref()
1215 }
1216
1217 fn listenable(&self) -> Rc<dyn Listenable> {
1218 Rc::new(self.rect.clone())
1219 }
1220
1221 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1222 Positioned::from_relative_rect(self.rect.value(app), self.child.clone()).into_widget()
1223 }
1224}
1225
1226#[derive(Debug)]
1245pub struct RelativePositionedTransition {
1246 pub key: Option<KeyRef>,
1248
1249 pub rect: AnimationRef<Option<Rect>>,
1259
1260 pub size: Size,
1263
1264 pub child: WidgetRef,
1266}
1267
1268impl RelativePositionedTransition {
1269 #[cfg_attr(debug_assertions, track_caller)]
1275 pub fn new<K>(
1276 rect: AnimationRef<Option<Rect>>,
1277 size: Size,
1278 child: impl IntoWidget<K>,
1279 ) -> RelativePositionedTransition {
1280 RelativePositionedTransition {
1281 key: None,
1282 rect,
1283 size,
1284 child: child.into_widget(),
1285 }
1286 }
1287
1288 pub fn key(mut self, key: KeyRef) -> RelativePositionedTransition {
1290 self.key = Some(key);
1291 self
1292 }
1293}
1294
1295impl AnimatedWidget for RelativePositionedTransition {
1296 fn key(&self) -> Option<&KeyRef> {
1297 self.key.as_ref()
1298 }
1299
1300 fn listenable(&self) -> Rc<dyn Listenable> {
1301 Rc::new(self.rect.clone())
1302 }
1303
1304 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1305 let offsets =
1306 RelativeRect::from_size(self.rect.value(app).unwrap_or(Rect::ZERO), self.size);
1307 Positioned::new(self.child.clone())
1308 .top(offsets.top)
1309 .right(offsets.right)
1310 .bottom(offsets.bottom)
1311 .left(offsets.left)
1312 .into_widget()
1313 }
1314}
1315
1316#[derive(Debug)]
1325pub struct DecoratedBoxTransition {
1326 pub key: Option<KeyRef>,
1328
1329 pub decoration: AnimationRef<DecorationRef>,
1334
1335 pub position: DecorationPosition,
1337
1338 pub child: WidgetRef,
1340}
1341
1342impl DecoratedBoxTransition {
1343 #[cfg_attr(debug_assertions, track_caller)]
1350 pub fn new<K>(
1351 decoration: AnimationRef<DecorationRef>,
1352 child: impl IntoWidget<K>,
1353 ) -> DecoratedBoxTransition {
1354 DecoratedBoxTransition {
1355 key: None,
1356 decoration,
1357 position: DecorationPosition::Background,
1358 child: child.into_widget(),
1359 }
1360 }
1361
1362 pub fn key(mut self, key: KeyRef) -> DecoratedBoxTransition {
1364 self.key = Some(key);
1365 self
1366 }
1367
1368 pub fn position(mut self, position: DecorationPosition) -> DecoratedBoxTransition {
1370 self.position = position;
1371 self
1372 }
1373}
1374
1375impl AnimatedWidget for DecoratedBoxTransition {
1376 fn key(&self) -> Option<&KeyRef> {
1377 self.key.as_ref()
1378 }
1379
1380 fn listenable(&self) -> Rc<dyn Listenable> {
1381 Rc::new(self.decoration.clone())
1382 }
1383
1384 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1385 DecoratedBox::new(self.decoration.value(app))
1386 .position(self.position)
1387 .child(self.child.clone())
1388 .into_widget()
1389 }
1390}
1391
1392#[derive(Debug)]
1407pub struct AlignTransition {
1408 pub key: Option<KeyRef>,
1410
1411 pub alignment: AnimationRef<AlignmentGeometry>,
1413
1414 pub width_factor: Option<f64>,
1416
1417 pub height_factor: Option<f64>,
1419
1420 pub child: WidgetRef,
1422}
1423
1424impl AlignTransition {
1425 #[cfg_attr(debug_assertions, track_caller)]
1432 pub fn new<K>(
1433 alignment: AnimationRef<AlignmentGeometry>,
1434 child: impl IntoWidget<K>,
1435 ) -> AlignTransition {
1436 AlignTransition {
1437 key: None,
1438 alignment,
1439 width_factor: None,
1440 height_factor: None,
1441 child: child.into_widget(),
1442 }
1443 }
1444
1445 pub fn key(mut self, key: KeyRef) -> AlignTransition {
1447 self.key = Some(key);
1448 self
1449 }
1450
1451 pub fn width_factor(mut self, width_factor: f64) -> AlignTransition {
1453 self.width_factor = Some(width_factor);
1454 self
1455 }
1456
1457 pub fn height_factor(mut self, height_factor: f64) -> AlignTransition {
1459 self.height_factor = Some(height_factor);
1460 self
1461 }
1462}
1463
1464impl AnimatedWidget for AlignTransition {
1465 fn key(&self) -> Option<&KeyRef> {
1466 self.key.as_ref()
1467 }
1468
1469 fn listenable(&self) -> Rc<dyn Listenable> {
1470 Rc::new(self.alignment.clone())
1471 }
1472
1473 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1474 let mut align = Align::new().alignment(self.alignment.value(app));
1475 if let Some(width_factor) = self.width_factor {
1476 align = align.width_factor(width_factor);
1477 }
1478 if let Some(height_factor) = self.height_factor {
1479 align = align.height_factor(height_factor);
1480 }
1481 align.child(self.child.clone()).into_widget()
1482 }
1483}
1484
1485#[derive(Debug)]
1495pub struct DefaultTextStyleTransition {
1496 pub key: Option<KeyRef>,
1498
1499 pub style: AnimationRef<TextStyle>,
1501
1502 pub text_align: Option<TextAlign>,
1504
1505 pub soft_wrap: bool,
1509
1510 pub overflow: TextOverflow,
1512
1513 pub max_lines: Option<i32>,
1517
1518 pub child: WidgetRef,
1520}
1521
1522impl DefaultTextStyleTransition {
1523 #[cfg_attr(debug_assertions, track_caller)]
1526 pub fn new<K>(
1527 style: AnimationRef<TextStyle>,
1528 child: impl IntoWidget<K>,
1529 ) -> DefaultTextStyleTransition {
1530 DefaultTextStyleTransition {
1531 key: None,
1532 style,
1533 text_align: None,
1534 soft_wrap: true,
1535 overflow: TextOverflow::Clip,
1536 max_lines: None,
1537 child: child.into_widget(),
1538 }
1539 }
1540
1541 pub fn key(mut self, key: KeyRef) -> DefaultTextStyleTransition {
1543 self.key = Some(key);
1544 self
1545 }
1546
1547 pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyleTransition {
1549 self.text_align = Some(text_align);
1550 self
1551 }
1552
1553 pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyleTransition {
1555 self.soft_wrap = soft_wrap;
1556 self
1557 }
1558
1559 pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyleTransition {
1561 self.overflow = overflow;
1562 self
1563 }
1564
1565 pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyleTransition {
1567 self.max_lines = Some(max_lines);
1568 self
1569 }
1570}
1571
1572impl AnimatedWidget for DefaultTextStyleTransition {
1573 fn key(&self) -> Option<&KeyRef> {
1574 self.key.as_ref()
1575 }
1576
1577 fn listenable(&self) -> Rc<dyn Listenable> {
1578 Rc::new(self.style.clone())
1579 }
1580
1581 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1582 let mut default_text_style =
1583 DefaultTextStyle::new(self.style.value(app), self.child.clone())
1584 .soft_wrap(self.soft_wrap)
1585 .overflow(self.overflow);
1586 if let Some(text_align) = self.text_align {
1587 default_text_style = default_text_style.text_align(text_align);
1588 }
1589 if let Some(max_lines) = self.max_lines {
1590 default_text_style = default_text_style.max_lines(max_lines);
1591 }
1592 default_text_style.into_widget()
1593 }
1594}
1595
1596pub type TransitionBuilder = Rc<dyn Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef>;
1601
1602pub struct ListenableBuilder {
1623 pub key: Option<KeyRef>,
1624 pub listenable: Rc<dyn Listenable>,
1628 pub builder: TransitionBuilder,
1632 pub child: Option<WidgetRef>,
1645}
1646
1647pub type AnimatedBuilder = ListenableBuilder;
1650
1651impl ListenableBuilder {
1652 pub fn new(
1654 listenable: Rc<dyn Listenable>,
1655 builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
1656 ) -> ListenableBuilder {
1657 ListenableBuilder {
1658 key: None,
1659 listenable,
1660 builder: Rc::new(builder),
1661 child: None,
1662 }
1663 }
1664
1665 pub fn key(mut self, key: KeyRef) -> ListenableBuilder {
1667 self.key = Some(key);
1668 self
1669 }
1670
1671 #[cfg_attr(debug_assertions, track_caller)]
1673 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ListenableBuilder {
1674 self.child = Some(child.into_widget());
1675 self
1676 }
1677
1678 pub fn animation(&self) -> Rc<dyn Listenable> {
1680 Rc::clone(&self.listenable)
1681 }
1682}
1683
1684impl Debug for ListenableBuilder {
1685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1686 f.debug_struct("ListenableBuilder")
1687 .field("child", &self.child)
1688 .finish_non_exhaustive()
1689 }
1690}
1691
1692impl AnimatedWidget for ListenableBuilder {
1693 fn key(&self) -> Option<&KeyRef> {
1694 self.key.as_ref()
1695 }
1696
1697 fn listenable(&self) -> Rc<dyn Listenable> {
1698 Rc::clone(&self.listenable)
1699 }
1700
1701 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1702 (self.builder)(app, context, self.child.as_ref())
1703 }
1704}
1705
1706#[cfg(test)]
1707mod tests {
1708 use std::cell::Cell;
1709 use std::time::Duration;
1710 use waft_animation::Drive;
1711 use waft_foundation::AppCell;
1712 use waft_foundation::Ref;
1713
1714 use waft_animation::{AnimationBehavior, AnimationController, CallbackAnimatable};
1715 use waft_embedder::Color;
1716 use waft_foundation::{ChangeNotifier, ValueNotifier};
1717 use waft_painting::{AnyColor, BoxDecoration};
1718 use waft_rendering::{
1719 BoxConstraints, ContainerRenderObjectMixin, RenderAligningShiftedBox, RenderConstrainedBox,
1720 RenderConstrainedBoxBase, RenderFractionalTranslation, RenderObjectWithChildMixin,
1721 RenderTransform,
1722 };
1723 use waft_scheduler::{Ticker, TickerCallback, TickerProvider};
1724
1725 use super::*;
1726 use crate::framework::LeafRenderObjectWidget;
1727 use crate::test_harness::Harness;
1728 use crate::testing::assert_f32_equals;
1729 use crate::widgets::basic::{Builder, Directionality, SizedBox, Stack};
1730
1731 struct TestVSync;
1733
1734 impl TickerProvider for TestVSync {
1735 fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1736 Ticker::new(app, on_tick, None)
1737 }
1738 }
1739
1740 #[derive(Debug)]
1742 struct Sized {
1743 size: Size,
1744 }
1745
1746 impl RenderObjectWidget for Sized {
1747 type RenderObject = RenderConstrainedBox;
1748
1749 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1750 RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
1751 }
1752
1753 fn update_render_object(
1754 &self,
1755 app: &mut App,
1756 _context: BuildContext,
1757 render_object: RenderHandle<RenderConstrainedBox>,
1758 ) {
1759 render_object.set_additional_constraints(app, BoxConstraints::tight(self.size));
1760 }
1761 }
1762
1763 impl LeafRenderObjectWidget for Sized {}
1764
1765 fn new_controller(app: &mut App) -> Ref<AnimationController> {
1766 AnimationController::new(
1767 app,
1768 None,
1769 Some(Duration::from_millis(100)),
1770 None,
1771 0.0,
1772 1.0,
1773 AnimationBehavior::Normal,
1774 TestVSync,
1775 )
1776 }
1777
1778 fn fade(opacity: AnimationRef<f64>) -> WidgetRef {
1779 FadeTransition::new(opacity)
1780 .child(Sized {
1781 size: Size::new(10.0, 10.0),
1782 })
1783 .into_widget()
1784 }
1785
1786 fn fade_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderAnimatedOpacity> {
1787 harness
1788 .render_root(app)
1789 .child(app)
1790 .expect("a child")
1791 .as_object()
1792 .downcast::<RenderAnimatedOpacity>(app)
1793 .expect("a RenderAnimatedOpacity")
1794 }
1795
1796 fn root_child_size(harness: &Harness, app: &App) -> Size {
1797 harness
1798 .render_root(app)
1799 .child(app)
1800 .expect("a child")
1801 .size(app)
1802 }
1803
1804 fn under_root<T: waft_rendering::RenderObject>(
1806 harness: &Harness,
1807 app: &App,
1808 ) -> RenderHandle<T> {
1809 harness
1810 .render_root(app)
1811 .child(app)
1812 .expect("a child")
1813 .as_object()
1814 .downcast::<T>(app)
1815 .expect("the expected render object")
1816 }
1817
1818 fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
1820 Directionality::new(TextDirection::Ltr, child).into_widget()
1821 }
1822
1823 fn ten_by_ten() -> Sized {
1824 Sized {
1825 size: Size::new(10.0, 10.0),
1826 }
1827 }
1828
1829 #[test]
1831 fn a_slide_transition_translates_by_the_animation_and_flips_in_rtl() {
1832 let cell = AppCell::new();
1833 let mut app = cell.borrow_mut();
1834 let controller = new_controller(&mut app);
1835 let position = controller.drive(
1836 &mut app,
1837 CallbackAnimatable::from_callback(|t| Offset::new(t, t * 2.0)),
1838 );
1839 let slide = |text_direction: Option<TextDirection>| {
1840 let mut transition = SlideTransition::new(position.clone())
1841 .transform_hit_tests(false)
1842 .child(ten_by_ten());
1843 if let Some(text_direction) = text_direction {
1844 transition = transition.text_direction(text_direction);
1845 }
1846 transition.into_widget()
1847 };
1848 let harness = Harness::mount(&mut app, slide(None));
1849 harness.pump(&mut app);
1850 controller.set_value(&mut app, 0.5);
1851 harness.pump(&mut app);
1852 let translation: RenderHandle<RenderFractionalTranslation> = under_root(&harness, &app);
1853 assert_eq!(translation.translation(&app), Offset::new(0.5, 1.0));
1854 assert!(!translation.transform_hit_tests(&app));
1855
1856 harness.set_child(&mut app, slide(Some(TextDirection::Rtl)));
1857 harness.pump(&mut app);
1858 assert_eq!(translation.translation(&app), Offset::new(-0.5, 1.0));
1859
1860 harness.set_child(&mut app, slide(Some(TextDirection::Ltr)));
1861 harness.pump(&mut app);
1862 assert_eq!(translation.translation(&app), Offset::new(0.5, 1.0));
1863
1864 controller.dispose(&mut app);
1865 }
1866
1867 #[test]
1869 fn a_matrix_transition_paints_the_matrix_its_callback_returns() {
1870 let cell = AppCell::new();
1871 let mut app = cell.borrow_mut();
1872 let controller = new_controller(&mut app);
1873 let widget = MatrixTransition::new(controller.erase(), |value| {
1874 Matrix4::translation(value as f32 * 100.0, 0.0)
1875 })
1876 .alignment(Alignment::TOP_LEFT)
1877 .child(ten_by_ten())
1878 .into_widget();
1879 let harness = Harness::mount(&mut app, widget);
1880 harness.pump(&mut app);
1881 let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
1882 assert_eq!(
1883 transform.alignment(&app),
1884 Some(AlignmentGeometry::Alignment(Alignment::TOP_LEFT))
1885 );
1886
1887 controller.set_value(&mut app, 0.5);
1888 harness.pump(&mut app);
1889 let child = transform.child(&app).expect("the sized child");
1890 assert_f32_equals(
1891 child.local_to_global(&app, Offset::ZERO, None),
1892 Offset::new(50.0, 0.0),
1893 );
1894
1895 controller.dispose(&mut app);
1896 }
1897
1898 #[test]
1900 fn a_scale_transition_scales_about_its_alignment() {
1901 let cell = AppCell::new();
1902 let mut app = cell.borrow_mut();
1903 let controller = new_controller(&mut app);
1904 let widget = ScaleTransition::new(controller.erase())
1905 .child(ten_by_ten())
1906 .into_widget();
1907 let harness = Harness::mount(&mut app, widget);
1908 controller.set_value(&mut app, 0.5);
1909 harness.pump(&mut app);
1910
1911 let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
1912 assert_eq!(
1913 transform.alignment(&app),
1914 Some(AlignmentGeometry::Alignment(Alignment::CENTER))
1915 );
1916 let child = transform.child(&app).expect("the sized child");
1917 assert_f32_equals(
1919 child.local_to_global(&app, Offset::ZERO, None),
1920 Offset::new(2.5, 2.5),
1921 );
1922
1923 controller.set_value(&mut app, 1.0);
1924 harness.pump(&mut app);
1925 assert_f32_equals(
1926 child.local_to_global(&app, Offset::ZERO, None),
1927 Offset::ZERO,
1928 );
1929
1930 controller.dispose(&mut app);
1931 }
1932
1933 #[test]
1935 fn a_rotation_transition_turns_a_full_circle_per_unit() {
1936 let cell = AppCell::new();
1937 let mut app = cell.borrow_mut();
1938 let controller = new_controller(&mut app);
1939 let widget = RotationTransition::new(controller.erase())
1940 .child(ten_by_ten())
1941 .into_widget();
1942 let harness = Harness::mount(&mut app, widget);
1943 controller.set_value(&mut app, 0.25);
1944 harness.pump(&mut app);
1945
1946 let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
1947 let child = transform.child(&app).expect("the sized child");
1948 assert_f32_equals(
1950 child.local_to_global(&app, Offset::ZERO, None),
1951 Offset::new(10.0, 0.0),
1952 );
1953
1954 controller.set_value(&mut app, 0.5);
1955 harness.pump(&mut app);
1956 assert_f32_equals(
1957 child.local_to_global(&app, Offset::ZERO, None),
1958 Offset::new(10.0, 10.0),
1959 );
1960
1961 controller.dispose(&mut app);
1962 }
1963
1964 fn has_matrix_filter_layer(harness: &Harness, app: &App) -> bool {
1967 harness.layers(app).into_iter().any(|layer| {
1968 app.handle::<waft_rendering::ImageFilterLayer>(layer.id())
1969 .and_then(|filter_layer| filter_layer.image_filter(app))
1970 .is_some_and(|filter| filter.to_string().starts_with("ImageFilter.matrix("))
1971 })
1972 }
1973
1974 fn uses_an_image_filter_while_animating(
1977 transition: impl FnOnce(AnimationRef<f64>) -> WidgetRef,
1978 ) {
1979 let cell = AppCell::new();
1980 let mut app = cell.borrow_mut();
1981 let controller = new_controller(&mut app);
1982 let animation = waft_animation::Tween::new(&mut app, Some(0.0), Some(1.0))
1983 .animate(&mut app, controller.erase());
1984 let harness = Harness::mount(&mut app, ltr(transition(animation)));
1985 harness.pump(&mut app);
1986
1987 assert!(!has_matrix_filter_layer(&harness, &app));
1989
1990 for value in [0.25, 0.5, 0.75] {
1991 controller.set_value(&mut app, value);
1992 harness.pump(&mut app);
1993 assert!(has_matrix_filter_layer(&harness, &app), "at {value}");
1994 }
1995
1996 controller.set_value(&mut app, 1.0);
1997 harness.pump(&mut app);
1998
1999 assert!(!has_matrix_filter_layer(&harness, &app));
2001
2002 controller.dispose(&mut app);
2003 }
2004
2005 #[test]
2006 fn a_matrix_transition_uses_an_image_filter_when_provided_with_a_filter_quality() {
2007 uses_an_image_filter_while_animating(|animation| {
2008 MatrixTransition::new(animation, |_value| Matrix4::IDENTITY)
2009 .filter_quality(FilterQuality::None)
2010 .child(ten_by_ten())
2011 .into_widget()
2012 });
2013 }
2014
2015 #[test]
2016 fn a_scale_transition_uses_an_image_filter_when_provided_with_a_filter_quality() {
2017 uses_an_image_filter_while_animating(|animation| {
2018 ScaleTransition::new(animation)
2019 .filter_quality(FilterQuality::None)
2020 .child(ten_by_ten())
2021 .into_widget()
2022 });
2023 }
2024
2025 #[test]
2026 fn a_rotation_transition_uses_an_image_filter_when_provided_with_a_filter_quality() {
2027 uses_an_image_filter_while_animating(|animation| {
2028 RotationTransition::new(animation)
2029 .filter_quality(FilterQuality::None)
2030 .child(ten_by_ten())
2031 .into_widget()
2032 });
2033 }
2034
2035 #[test]
2037 fn a_size_transition_clips_its_child_to_the_size_factor() {
2038 let cell = AppCell::new();
2039 let mut app = cell.borrow_mut();
2040 let controller = new_controller(&mut app);
2041 let widget = SizeTransition::new(controller.erase())
2042 .child(ten_by_ten())
2043 .into_widget();
2044 let harness = Harness::mount(&mut app, ltr(widget));
2045 harness.pump(&mut app);
2046 let clip: RenderHandle<waft_rendering::RenderClipRect> = under_root(&harness, &app);
2047 assert_eq!(clip.size(&app).height(), 0.0);
2048
2049 controller.set_value(&mut app, 0.5);
2050 harness.pump(&mut app);
2051 assert_eq!(clip.size(&app).height(), 5.0);
2052 assert_eq!(
2053 clip.size(&app).width(),
2054 crate::test_harness::VIEW_WIDTH,
2055 "the cross axis is as large as the parent"
2056 );
2057
2058 controller.set_value(&mut app, 1.0);
2059 harness.pump(&mut app);
2060 assert_eq!(clip.size(&app).height(), 10.0);
2061
2062 controller.dispose(&mut app);
2063 }
2064
2065 #[test]
2066 fn a_horizontal_size_transition_fixes_its_cross_axis_factor() {
2067 let cell = AppCell::new();
2068 let mut app = cell.borrow_mut();
2069 let controller = new_controller(&mut app);
2070 let widget = SizeTransition::new(controller.erase())
2071 .axis(Axis::Horizontal)
2072 .fixed_cross_axis_size_factor(1.0)
2073 .child(ten_by_ten())
2074 .into_widget();
2075 let harness = Harness::mount(&mut app, ltr(widget));
2076 controller.set_value(&mut app, 0.5);
2077 harness.pump(&mut app);
2078 let clip: RenderHandle<waft_rendering::RenderClipRect> = under_root(&harness, &app);
2079 assert_eq!(clip.size(&app), Size::new(5.0, 10.0));
2080
2081 controller.dispose(&mut app);
2082 }
2083
2084 #[test]
2086 fn a_positioned_transition_places_its_child_by_the_relative_rect() {
2087 let cell = AppCell::new();
2088 let mut app = cell.borrow_mut();
2089 let controller = new_controller(&mut app);
2090 let tween = RelativeRectTween::new(
2091 Some(RelativeRect::from_ltrb(0.0, 0.0, 200.0, 100.0)),
2092 Some(RelativeRect::from_ltrb(100.0, 50.0, 0.0, 0.0)),
2093 );
2094 let rect = controller.drive(&mut app, tween);
2095 let widget = Stack::new()
2096 .children([PositionedTransition::new(rect.clone(), ten_by_ten()).into_widget()])
2097 .into_widget();
2098 let harness = Harness::mount(&mut app, ltr(widget));
2099 controller.set_value(&mut app, 0.5);
2100 harness.pump(&mut app);
2101
2102 let stack: RenderHandle<waft_rendering::RenderStack> = under_root(&harness, &app);
2103 let child = stack.first_child(&app).expect("the positioned child");
2104 assert_f32_equals(
2105 child.local_to_global(&app, Offset::ZERO, None),
2106 Offset::new(50.0, 25.0),
2107 );
2108 assert_eq!(child.size(&app), Size::new(150.0, 125.0));
2109
2110 controller.dispose(&mut app);
2111 }
2112
2113 #[test]
2115 fn a_relative_positioned_transition_places_its_child_inside_the_given_size() {
2116 let cell = AppCell::new();
2117 let mut app = cell.borrow_mut();
2118 let controller = new_controller(&mut app);
2119 let rect = controller.drive(
2120 &mut app,
2121 CallbackAnimatable::from_callback(|t| {
2122 Some(Rect::from_ltwh(t * 40.0, t * 20.0, 30.0, 15.0))
2123 }),
2124 );
2125 let widget = Stack::new()
2126 .children([RelativePositionedTransition::new(
2127 rect.clone(),
2128 Size::new(100.0, 100.0),
2129 ten_by_ten(),
2130 )
2131 .into_widget()])
2132 .into_widget();
2133 let harness = Harness::mount(&mut app, ltr(widget));
2134 controller.set_value(&mut app, 0.5);
2135 harness.pump(&mut app);
2136
2137 let stack: RenderHandle<waft_rendering::RenderStack> = under_root(&harness, &app);
2138 let child = stack.first_child(&app).expect("the positioned child");
2139 assert_f32_equals(
2141 child.local_to_global(&app, Offset::ZERO, None),
2142 Offset::new(20.0, 10.0),
2143 );
2144 assert_eq!(
2145 child.size(&app),
2146 Size::new(
2147 crate::test_harness::VIEW_WIDTH - 20.0 - 50.0,
2148 crate::test_harness::VIEW_HEIGHT - 10.0 - 75.0,
2149 )
2150 );
2151
2152 controller.dispose(&mut app);
2153 }
2154
2155 #[test]
2157 fn a_decorated_box_transition_hands_the_animated_decoration_to_its_render_object() {
2158 let cell = AppCell::new();
2159 let mut app = cell.borrow_mut();
2160 let controller = new_controller(&mut app);
2161 let decoration = controller.drive(
2162 &mut app,
2163 CallbackAnimatable::from_callback(|t| {
2164 DecorationRef::new(BoxDecoration::new().color(Color::from_argb(
2165 (t * 255.0).round() as i32,
2166 0,
2167 0,
2168 0,
2169 )))
2170 }),
2171 );
2172 let widget = DecoratedBoxTransition::new(decoration.clone(), ten_by_ten())
2173 .position(DecorationPosition::Foreground)
2174 .into_widget();
2175 let harness = Harness::mount(&mut app, widget);
2176 controller.set_value(&mut app, 0.5);
2177 harness.pump(&mut app);
2178
2179 let decorated: RenderHandle<waft_rendering::RenderDecoratedBox> =
2180 under_root(&harness, &app);
2181 assert_eq!(decorated.position(&app), DecorationPosition::Foreground);
2182 let painted = decorated
2183 .decoration(&app)
2184 .as_any()
2185 .downcast_ref::<BoxDecoration>()
2186 .expect("a BoxDecoration");
2187 assert_eq!(
2188 painted.color.as_ref().map(AnyColor::color),
2189 Some(Color::from_argb(128, 0, 0, 0))
2190 );
2191
2192 controller.dispose(&mut app);
2193 }
2194
2195 #[test]
2197 fn an_align_transition_hands_the_animated_alignment_to_its_render_object() {
2198 let cell = AppCell::new();
2199 let mut app = cell.borrow_mut();
2200 let controller = new_controller(&mut app);
2201 let alignment = controller.drive(
2202 &mut app,
2203 CallbackAnimatable::from_callback(|t| AlignmentGeometry::xy(t, -t)),
2204 );
2205 let widget = AlignTransition::new(alignment.clone(), ten_by_ten())
2206 .width_factor(2.0)
2207 .height_factor(3.0)
2208 .into_widget();
2209 let harness = Harness::mount(&mut app, widget);
2210 controller.set_value(&mut app, 0.5);
2211 harness.pump(&mut app);
2212
2213 let positioned: RenderHandle<waft_rendering::RenderPositionedBox> =
2214 under_root(&harness, &app);
2215 assert_eq!(
2216 RenderAligningShiftedBox::alignment(positioned, &app),
2217 AlignmentGeometry::xy(0.5, -0.5)
2218 );
2219 assert_eq!(positioned.width_factor(&app), Some(2.0));
2220 assert_eq!(positioned.height_factor(&app), Some(3.0));
2221 assert_eq!(positioned.size(&app), Size::new(20.0, 30.0));
2222
2223 controller.dispose(&mut app);
2224 }
2225
2226 #[test]
2228 fn a_default_text_style_transition_publishes_the_animated_style() {
2229 let cell = AppCell::new();
2230 let mut app = cell.borrow_mut();
2231 let controller = new_controller(&mut app);
2232 let style = controller.drive(
2233 &mut app,
2234 CallbackAnimatable::from_callback(|t| TextStyle::new().font_size(10.0 + t * 10.0)),
2235 );
2236 let seen: Rc<Cell<f64>> = Rc::new(Cell::new(0.0));
2237 let child = Builder {
2238 key: None,
2239 builder: Rc::new({
2240 let seen = Rc::clone(&seen);
2241 move |app, context| {
2242 let default = DefaultTextStyle::of(app, context);
2243 seen.set(default.style.font_size.expect("a font size"));
2244 ten_by_ten().into_widget()
2245 }
2246 }),
2247 };
2248 let widget = DefaultTextStyleTransition::new(style.clone(), child)
2249 .max_lines(3)
2250 .overflow(TextOverflow::Ellipsis)
2251 .soft_wrap(false)
2252 .into_widget();
2253 let harness = Harness::mount(&mut app, widget);
2254 controller.set_value(&mut app, 0.5);
2255 harness.pump(&mut app);
2256 assert_eq!(seen.get(), 15.0);
2257
2258 controller.set_value(&mut app, 1.0);
2259 harness.pump(&mut app);
2260 assert_eq!(seen.get(), 20.0);
2261
2262 controller.dispose(&mut app);
2263 }
2264
2265 #[test]
2267 fn a_fade_transition_hands_its_animation_to_the_render_object() {
2268 let cell = AppCell::new();
2269 let mut app = cell.borrow_mut();
2270 let controller = new_controller(&mut app);
2271 let harness = Harness::mount(&mut app, fade(controller.erase()));
2272 harness.pump(&mut app);
2273 let render_object = fade_under_root(&harness, &app);
2274 assert_eq!(render_object.opacity(&app), controller.view());
2275 assert_eq!(render_object.opacity(&app).value(&app), 0.0);
2276 assert!(
2277 !render_object.as_object().is_repaint_boundary(&app),
2278 "fully transparent"
2279 );
2280
2281 for value in [0.25, 0.5, 0.75, 1.0] {
2282 controller.set_value(&mut app, value);
2283 harness.pump(&mut app);
2284 assert_eq!(render_object.opacity(&app).value(&app), value);
2285 }
2286 assert!(
2287 render_object.as_object().is_repaint_boundary(&app),
2288 "the render object heard the controller"
2289 );
2290
2291 let other = new_controller(&mut app);
2292 harness.set_child(&mut app, fade(other.erase()));
2293 harness.pump(&mut app);
2294 assert_eq!(
2295 fade_under_root(&harness, &app),
2296 render_object,
2297 "reconfigured in place"
2298 );
2299 assert_eq!(render_object.opacity(&app), other.view());
2300
2301 controller.dispose(&mut app);
2302 other.dispose(&mut app);
2303 }
2304
2305 #[derive(Debug)]
2307 struct Grower {
2308 notifier: Ref<ValueNotifier<f64>>,
2309 builds: Rc<Cell<u32>>,
2310 }
2311
2312 impl AnimatedWidget for Grower {
2313 fn listenable(&self) -> Rc<dyn Listenable> {
2314 Rc::new(self.notifier.clone())
2315 }
2316
2317 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
2318 self.builds.set(self.builds.get() + 1);
2319 let width = *app.get(&self.notifier).value();
2320 Sized {
2321 size: Size::new(width, 10.0),
2322 }
2323 .into_widget()
2324 }
2325 }
2326
2327 fn has_listeners(app: &App, notifier: Handle<ValueNotifier<f64>>) -> bool {
2328 app.get(notifier).change_notifier_data().has_listeners()
2329 }
2330
2331 #[test]
2332 fn an_animated_widget_rebuilds_when_its_listenable_notifies() {
2333 let cell = AppCell::new();
2334 let mut app = cell.borrow_mut();
2335 let notifier = app.create(ValueNotifier::new(10.0));
2336 let builds = Rc::new(Cell::new(0));
2337 let harness = Harness::mount(
2338 &mut app,
2339 Grower {
2340 notifier: notifier.clone(),
2341 builds: Rc::clone(&builds),
2342 }
2343 .into_widget(),
2344 );
2345 harness.pump(&mut app);
2346 assert_eq!(builds.get(), 1);
2347 assert!(has_listeners(&app, notifier.handle()));
2348 assert_eq!(root_child_size(&harness, &app), Size::new(10.0, 10.0));
2349
2350 notifier.set_value(&mut app, 20.0);
2351 assert_eq!(builds.get(), 1, "rebuilt at the next frame, not inline");
2352 harness.pump(&mut app);
2353 assert_eq!(builds.get(), 2);
2354 assert_eq!(root_child_size(&harness, &app), Size::new(20.0, 10.0));
2355 }
2356
2357 #[test]
2358 fn an_animated_widget_follows_a_new_listenable_and_unsubscribes_on_unmount() {
2359 let cell = AppCell::new();
2360 let mut app = cell.borrow_mut();
2361 let first = app.create(ValueNotifier::new(10.0));
2362 let second = app.create(ValueNotifier::new(30.0));
2363 let builds = Rc::new(Cell::new(0));
2364 let grower = |notifier| {
2365 Grower {
2366 notifier,
2367 builds: Rc::clone(&builds),
2368 }
2369 .into_widget()
2370 };
2371 let harness = Harness::mount(&mut app, grower(first.clone()));
2372 harness.pump(&mut app);
2373
2374 harness.set_child(&mut app, grower(second.clone()));
2375 harness.pump(&mut app);
2376 assert!(
2377 !has_listeners(&app, first.handle()),
2378 "did_update_widget left the old listenable"
2379 );
2380 assert!(has_listeners(&app, second.handle()));
2381 assert_eq!(root_child_size(&harness, &app), Size::new(30.0, 10.0));
2382
2383 harness.set_child(
2384 &mut app,
2385 Sized {
2386 size: Size::new(5.0, 5.0),
2387 }
2388 .into_widget(),
2389 );
2390 harness.pump(&mut app);
2391 assert!(
2392 !has_listeners(&app, second.handle()),
2393 "dispose removed the listener"
2394 );
2395 let builds_before = builds.get();
2396 second.set_value(&mut app, 40.0);
2397 harness.pump(&mut app);
2398 assert_eq!(
2399 builds.get(),
2400 builds_before,
2401 "a disposed state never builds again"
2402 );
2403 }
2404
2405 #[test]
2406 fn a_listenable_builder_rebuilds_on_notify_and_hands_back_its_child() {
2407 let cell = AppCell::new();
2408 let mut app = cell.borrow_mut();
2409 let notifier = app.create(ValueNotifier::new(0i32));
2410 let builds = Rc::new(Cell::new(0));
2411 let child: WidgetRef = SizedBox::square(Some(4.0)).into_widget();
2412 let same_child = Rc::new(Cell::new(true));
2413 let widget = AnimatedBuilder::new(Rc::new(notifier.clone()), {
2414 let builds = Rc::clone(&builds);
2415 let same_child = Rc::clone(&same_child);
2416 let child = child.clone();
2417 move |_app, _context, passed| {
2418 builds.set(builds.get() + 1);
2419 same_child.set(passed.is_some_and(|passed| Rc::ptr_eq(passed, &child)));
2420 passed.expect("the child is passed back").clone()
2421 }
2422 })
2423 .child(child.clone());
2424 let harness = Harness::mount(&mut app, widget.into_widget());
2425 harness.pump(&mut app);
2426 assert_eq!(builds.get(), 1);
2427 assert!(same_child.get());
2428
2429 notifier.set_value(&mut app, 1);
2430 harness.pump(&mut app);
2431 assert_eq!(builds.get(), 2);
2432 }
2433}