1use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_animation::{
7 AnimationRef, AnimationStatus, AnimationStatusListener, ProxyAnimation, ReverseAnimation,
8 k_always_complete_animation, k_always_dismissed_animation,
9};
10use waft_foundation::{App, Handle, OptionRetained, Ref};
11
12use crate::framework::{
13 BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
14};
15
16pub type AnimatedTransitionBuilder =
30 Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>, Option<&WidgetRef>) -> WidgetRef>;
31
32pub struct DualTransitionBuilder {
47 pub key: Option<KeyRef>,
48
49 pub animation: AnimationRef<f64>,
55
56 pub forward_builder: AnimatedTransitionBuilder,
71
72 pub reverse_builder: AnimatedTransitionBuilder,
88
89 pub child: Option<WidgetRef>,
103}
104
105impl Debug for DualTransitionBuilder {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.debug_struct("DualTransitionBuilder")
108 .field("key", &self.key)
109 .field("animation", &self.animation)
110 .field("child", &self.child)
111 .finish_non_exhaustive()
112 }
113}
114
115impl DualTransitionBuilder {
116 pub fn new(
118 animation: AnimationRef<f64>,
119 forward_builder: impl Fn(
120 &mut App,
121 BuildContext,
122 AnimationRef<f64>,
123 Option<&WidgetRef>,
124 ) -> WidgetRef
125 + 'static,
126 reverse_builder: impl Fn(
127 &mut App,
128 BuildContext,
129 AnimationRef<f64>,
130 Option<&WidgetRef>,
131 ) -> WidgetRef
132 + 'static,
133 ) -> DualTransitionBuilder {
134 DualTransitionBuilder {
135 key: None,
136 animation,
137 forward_builder: Rc::new(forward_builder),
138 reverse_builder: Rc::new(reverse_builder),
139 child: None,
140 }
141 }
142
143 pub fn key(mut self, key: KeyRef) -> DualTransitionBuilder {
145 self.key = Some(key);
146 self
147 }
148
149 #[cfg_attr(debug_assertions, track_caller)]
151 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> DualTransitionBuilder {
152 self.child = Some(child.into_widget());
153 self
154 }
155}
156
157impl StatefulWidget for DualTransitionBuilder {
158 type State = DualTransitionBuilderState;
159
160 fn key(&self) -> Option<&KeyRef> {
161 self.key.as_ref()
162 }
163
164 fn create_state(&self) -> DualTransitionBuilderState {
165 DualTransitionBuilderState {
166 state: StateData::new(),
167 effective_animation_status: AnimationStatus::Dismissed,
168 forward_animation: None,
169 reverse_animation: None,
170 }
171 }
172}
173
174pub struct DualTransitionBuilderState {
179 state: StateData<DualTransitionBuilder>,
180 effective_animation_status: AnimationStatus,
181 forward_animation: Option<Ref<ProxyAnimation>>,
182 reverse_animation: Option<Ref<ProxyAnimation>>,
183}
184
185impl Debug for DualTransitionBuilderState {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 f.debug_struct("DualTransitionBuilderState")
188 .finish_non_exhaustive()
189 }
190}
191
192impl DualTransitionBuilderState {
193 fn forward_animation(self: Handle<Self>, app: &App) -> Handle<ProxyAnimation> {
194 app.get(self)
195 .forward_animation
196 .handle()
197 .expect("created in init_state")
198 }
199
200 fn reverse_animation(self: Handle<Self>, app: &App) -> Handle<ProxyAnimation> {
201 app.get(self)
202 .reverse_animation
203 .handle()
204 .expect("created in init_state")
205 }
206
207 fn animation_listener(self: Handle<Self>, app: &mut App, animation_status: AnimationStatus) {
208 let old_effective = app.get(self).effective_animation_status;
209 let effective = calculate_effective_animation_status(old_effective, animation_status);
210 app.get_mut(self).effective_animation_status = effective;
211 if old_effective != effective {
212 self.update_animations(app);
213 }
214 }
215
216 fn update_animations(self: Handle<Self>, app: &mut App) {
217 let animation = self.widget(app).animation.clone();
218 let forward_animation = self.forward_animation(app);
219 let reverse_animation = self.reverse_animation(app);
220 match app.get(self).effective_animation_status {
221 AnimationStatus::Dismissed | AnimationStatus::Forward => {
222 forward_animation.set_parent(app, Some(animation));
223 let dismissed = k_always_dismissed_animation(app);
224 reverse_animation.set_parent(app, Some(dismissed));
225 }
226 AnimationStatus::Reverse | AnimationStatus::Completed => {
227 let complete = k_always_complete_animation(app);
228 forward_animation.set_parent(app, Some(complete));
229 let reversed = ReverseAnimation::new(app, animation);
230 reverse_animation.set_parent(app, Some(reversed.into_erased()));
231 }
232 }
233 }
234}
235
236fn calculate_effective_animation_status(
241 last_effective: AnimationStatus,
242 current: AnimationStatus,
243) -> AnimationStatus {
244 match current {
245 AnimationStatus::Dismissed | AnimationStatus::Completed => current,
246 AnimationStatus::Forward => match last_effective {
247 AnimationStatus::Dismissed | AnimationStatus::Completed | AnimationStatus::Forward => {
248 current
249 }
250 AnimationStatus::Reverse => last_effective,
251 },
252 AnimationStatus::Reverse => match last_effective {
253 AnimationStatus::Dismissed | AnimationStatus::Completed | AnimationStatus::Reverse => {
254 current
255 }
256 AnimationStatus::Forward => last_effective,
257 },
258 }
259}
260
261impl State for DualTransitionBuilderState {
262 type Widget = DualTransitionBuilder;
263 crate::state_accessors!();
264
265 fn init_state(self: Handle<Self>, app: &mut App) {
266 let forward_animation = ProxyAnimation::new(app, None);
267 let reverse_animation = ProxyAnimation::new(app, None);
268 let state = app.get_mut(self);
269 state.forward_animation = Some(forward_animation);
270 state.reverse_animation = Some(reverse_animation);
271 let animation = self.widget(app).animation.handle();
272 app.get_mut(self).effective_animation_status = animation.status(app);
273 animation.add_status_listener(
274 app,
275 AnimationStatusListener::handle_method(self, Self::animation_listener),
276 );
277 self.update_animations(app);
278 }
279
280 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &DualTransitionBuilder) {
281 let animation = self.widget(app).animation.handle();
282 if old_widget.animation != animation {
283 old_widget.animation.remove_status_listener(
284 app,
285 &AnimationStatusListener::handle_method(self, Self::animation_listener),
286 );
287 animation.add_status_listener(
288 app,
289 AnimationStatusListener::handle_method(self, Self::animation_listener),
290 );
291 let status = animation.status(app);
292 self.animation_listener(app, status);
293 }
294 }
295
296 fn dispose(self: Handle<Self>, app: &mut App) {
297 let animation = self.widget(app).animation.handle();
298 animation.remove_status_listener(
299 app,
300 &AnimationStatusListener::handle_method(self, Self::animation_listener),
301 );
302 }
303
304 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
305 let widget = self.widget(app);
306 let forward_builder = Rc::clone(&widget.forward_builder);
307 let reverse_builder = Rc::clone(&widget.reverse_builder);
308 let child = widget.child.clone();
309 let state = app.get(self);
310 let forward_animation: AnimationRef<f64> = state
311 .forward_animation
312 .as_ref()
313 .expect("created in init_state")
314 .erase();
315 let reverse_animation: AnimationRef<f64> = state
316 .reverse_animation
317 .as_ref()
318 .expect("created in init_state")
319 .erase();
320 let reversed = reverse_builder(app, context, reverse_animation, child.as_ref());
321 forward_builder(app, context, forward_animation, Some(&reversed))
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use std::cell::Cell;
328 use std::time::Duration;
329 use waft_animation::Drive;
330 use waft_foundation::Ref;
331
332 use waft_animation::{AnimationBehavior, AnimationController, AnyAnimation, Tween};
333 use waft_embedder::Color;
334
335 use super::*;
336 use crate::testing::{TestVSync, WidgetTester, test_widgets};
337 use crate::widgets::basic::{Center, SizedBox};
338 use crate::widgets::container::Container;
339 use crate::widgets::transitions::{FadeTransition, ScaleTransition};
340
341 #[derive(Clone, Default)]
344 struct Observed {
345 scale: Rc<Cell<Option<AnyAnimation<f64>>>>,
346 opacity: Rc<Cell<Option<AnyAnimation<f64>>>>,
347 }
348
349 impl Observed {
350 fn scale(&self, app: &App) -> f64 {
351 self.scale.get().expect("built").value(app)
352 }
353
354 fn opacity(&self, app: &App) -> f64 {
355 self.opacity.get().expect("built").value(app)
356 }
357 }
358
359 fn controller(app: &mut App, value: Option<f64>) -> Ref<AnimationController> {
360 AnimationController::new(
361 app,
362 value,
363 Some(Duration::from_millis(300)),
364 None,
365 0.0,
366 1.0,
367 AnimationBehavior::Normal,
368 TestVSync,
369 )
370 }
371
372 fn tree(animation: AnimationRef<f64>, observed: &Observed, child: WidgetRef) -> WidgetRef {
373 let scale = Rc::clone(&observed.scale);
374 let opacity = Rc::clone(&observed.opacity);
375 Center::new()
376 .child(
377 DualTransitionBuilder::new(
378 animation,
379 move |_app, _context, animation, child| {
380 scale.set(Some(animation.handle()));
381 ScaleTransition::new(animation)
382 .child(child.expect("a child").clone())
383 .into_widget()
384 },
385 move |app, _context, animation, child| {
386 let tween = Tween::new(app, Some(1.0), Some(0.0));
387 let faded = animation.drive(app, tween);
388 opacity.set(Some(faded.handle()));
389 FadeTransition::new(faded)
390 .child(child.expect("a child").clone())
391 .into_widget()
392 },
393 )
394 .child(child),
395 )
396 .into_widget()
397 }
398
399 fn green_box() -> WidgetRef {
400 Container::new()
401 .color(Color::new(0xFF00FF00))
402 .height(100.0)
403 .width(100.0)
404 .into_widget()
405 }
406
407 fn ms(millis: u64) -> Duration {
408 Duration::from_millis(millis)
409 }
410
411 fn assert_scale_and_opacity(
412 tester: &WidgetTester,
413 observed: &Observed,
414 scale: f64,
415 opacity: f64,
416 ) {
417 let app = tester.cell.borrow();
418 assert_eq!(observed.scale(&app), scale);
419 assert_eq!(observed.opacity(&app), opacity);
420 }
421
422 fn pump_tree(
424 tester: &mut WidgetTester,
425 controller: &Ref<AnimationController>,
426 child: WidgetRef,
427 ) -> Observed {
428 let observed = Observed::default();
429 tester.pump_widget(tree(controller.erase(), &observed, child));
430 observed
431 }
432
433 #[test]
434 fn runs_animations() {
435 test_widgets(|tester| {
436 let controller = tester.update(|app| controller(app, None));
437 let observed = pump_tree(tester, &controller, green_box());
438 assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
439
440 tester.update(|app| controller.forward(app, None));
441 tester.pump();
442 tester.pump_by(ms(150));
443 assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
444
445 tester.pump_by(ms(150));
446 assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
447
448 tester.pump_by(ms(300));
449 assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
450
451 tester.update(|app| controller.reverse(app, None));
452 tester.pump();
453 tester.pump_by(ms(150));
454 assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
455
456 tester.pump_by(ms(150));
457 assert_scale_and_opacity(tester, &observed, 1.0, 0.0);
458
459 tester.pump_by(ms(300));
460 assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
461 tester.update(|app| controller.dispose(app));
462 });
463 }
464
465 #[test]
468 fn a_disposed_state_frees_its_proxies_and_reverse_animation() {
469 test_widgets(|tester| {
470 let controller = tester.update(|app| controller(app, Some(1.0)));
471 let forward: Rc<Cell<Option<AnyAnimation<f64>>>> = Rc::default();
472 let reverse: Rc<Cell<Option<AnyAnimation<f64>>>> = Rc::default();
473 let tree = {
474 let (forward, reverse) = (Rc::clone(&forward), Rc::clone(&reverse));
475 DualTransitionBuilder::new(
476 controller.erase(),
477 move |_app, _context, animation, child| {
478 forward.set(Some(animation.handle()));
479 child.cloned().expect("a child")
480 },
481 move |_app, _context, animation, child| {
482 reverse.set(Some(animation.handle()));
483 child.cloned().expect("a child")
484 },
485 )
486 .child(green_box())
487 .into_widget()
488 };
489 tester.pump_widget(Center::new().child(tree));
490 let proxies = [forward, reverse].map(|built| built.get().expect("the builder ran"));
491 let reverse_parent = {
492 let app = tester.cell.borrow();
493 let reverse = app
494 .handle::<ProxyAnimation>(proxies[1].id())
495 .expect("the reverse proxy");
496 reverse
497 .parent(&app)
498 .expect("a completed animation is reversed")
499 };
500
501 tester.pump_widget(SizedBox::new());
502 let app = tester.cell.borrow();
503 for freed in [proxies[0].id(), proxies[1].id(), reverse_parent.id()] {
504 assert!(!app.contains(freed), "{freed:?} is freed");
505 }
506 assert!(
507 app.contains(&controller),
508 "the widget's animation is its owner's"
509 );
510 });
511 }
512
513 #[test]
514 fn keeps_state() {
515 test_widgets(|tester| {
516 let controller = tester.update(|app| controller(app, None));
517 let probe = Probe::default();
518 pump_tree(tester, &controller, probe.widget());
519 assert_eq!((probe.inits.get(), probe.disposes.get()), (1, 0));
520
521 for direction in [AnimationController::forward, AnimationController::reverse] {
522 tester.update(|app| direction(controller.handle(), app, None));
523 for step in [0, 150, 150, 300] {
524 tester.pump_by(ms(step));
525 assert_eq!((probe.inits.get(), probe.disposes.get()), (1, 0));
526 }
527 }
528 tester.update(|app| controller.dispose(app));
529 });
530 }
531
532 #[test]
533 fn does_not_jump_when_interrupted_forward() {
534 test_widgets(|tester| {
535 let controller = tester.update(|app| controller(app, None));
536 let observed = pump_tree(tester, &controller, green_box());
537 assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
538
539 tester.update(|app| controller.forward(app, None));
540 tester.pump();
541 tester.pump_by(ms(150));
542 assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
543
544 tester.update(|app| controller.reverse(app, None));
545 assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
546 tester.pump();
547 assert_scale_and_opacity(tester, &observed, 0.5, 1.0);
548
549 tester.pump_by(ms(75));
550 assert_scale_and_opacity(tester, &observed, 0.25, 1.0);
551
552 tester.pump_by(ms(75));
553 assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
554
555 tester.pump_by(ms(300));
556 assert_scale_and_opacity(tester, &observed, 0.0, 1.0);
557 tester.update(|app| controller.dispose(app));
558 });
559 }
560
561 #[test]
562 fn does_not_jump_when_interrupted_reverse() {
563 test_widgets(|tester| {
564 let controller = tester.update(|app| controller(app, Some(1.0)));
565 let observed = pump_tree(tester, &controller, green_box());
566 assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
567
568 tester.update(|app| controller.reverse(app, None));
569 tester.pump();
570 tester.pump_by(ms(150));
571 assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
572
573 tester.update(|app| controller.forward(app, None));
574 assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
575 tester.pump();
576 assert_scale_and_opacity(tester, &observed, 1.0, 0.5);
577
578 tester.pump_by(ms(75));
579 assert_scale_and_opacity(tester, &observed, 1.0, 0.75);
580
581 tester.pump_by(ms(75));
582 assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
583
584 tester.pump_by(ms(300));
585 assert_scale_and_opacity(tester, &observed, 1.0, 1.0);
586 tester.update(|app| controller.dispose(app));
587 });
588 }
589
590 #[derive(Clone, Default)]
593 struct Probe {
594 inits: Rc<Cell<u32>>,
595 disposes: Rc<Cell<u32>>,
596 }
597
598 impl Probe {
599 fn widget(&self) -> WidgetRef {
600 ProbeWidget {
601 probe: self.clone(),
602 }
603 .into_widget()
604 }
605 }
606
607 #[derive(Debug)]
608 struct ProbeWidget {
609 probe: Probe,
610 }
611
612 impl Debug for Probe {
613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 f.write_str("Probe")
615 }
616 }
617
618 impl StatefulWidget for ProbeWidget {
619 type State = ProbeState;
620
621 fn create_state(&self) -> ProbeState {
622 ProbeState {
623 state: StateData::new(),
624 }
625 }
626 }
627
628 struct ProbeState {
629 state: StateData<ProbeWidget>,
630 }
631
632 impl State for ProbeState {
633 type Widget = ProbeWidget;
634 crate::state_accessors!();
635
636 fn init_state(self: Handle<Self>, app: &mut App) {
637 let inits = &self.widget(app).probe.inits;
638 inits.set(inits.get() + 1);
639 }
640
641 fn dispose(self: Handle<Self>, app: &mut App) {
642 let disposes = &self.widget(app).probe.disposes;
643 disposes.set(disposes.get() + 1);
644 }
645
646 fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
647 SizedBox::new().width(10.0).height(10.0).into_widget()
648 }
649 }
650}