1use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_animation::{AnimationStatusListener, AnyAnimation};
7use waft_foundation::{App, Handle};
8
9use crate::framework::{
10 BuildContext, IntoWidget, KeyRef, State, StateData, Stateful, StatefulWidget, WidgetRef,
11 downcast_widget, short_type_name,
12};
13
14pub trait StatusTransitionWidget: Debug + 'static {
16 fn key(&self) -> Option<&KeyRef> {
18 None
19 }
20
21 fn animation(&self) -> AnyAnimation<f64>;
23
24 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef;
27}
28
29pub struct StatusTransitionKind;
31
32pub struct StatusTransition<W: StatusTransitionWidget>(pub W);
35
36impl<W: StatusTransitionWidget> IntoWidget<StatusTransitionKind> for W {
37 #[cfg_attr(debug_assertions, track_caller)]
38 fn into_widget(self) -> WidgetRef {
39 Rc::new(Stateful(
40 StatusTransition(self),
41 crate::CreationLocation::of_caller(),
42 ))
43 }
44}
45
46impl<W: StatusTransitionWidget> StatefulWidget for StatusTransition<W> {
47 type State = StatusTransitionState<W>;
48
49 fn key(&self) -> Option<&KeyRef> {
50 self.0.key()
51 }
52
53 fn type_name(&self) -> &'static str {
54 short_type_name::<W>()
55 }
56
57 fn create_state(&self) -> StatusTransitionState<W> {
58 StatusTransitionState {
59 state: StateData::new(),
60 }
61 }
62}
63
64impl<W: StatusTransitionWidget> Debug for StatusTransition<W> {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 self.0.fmt(f)
67 }
68}
69
70pub struct StatusTransitionState<W: StatusTransitionWidget> {
72 state: StateData<StatusTransition<W>>,
73}
74
75impl<W: StatusTransitionWidget> State for StatusTransitionState<W> {
76 type Widget = StatusTransition<W>;
77 crate::state_accessors!();
78
79 fn init_state(self: Handle<Self>, app: &mut App) {
80 let animation = self.widget(app).0.animation();
81 animation.add_status_listener(
82 app,
83 AnimationStatusListener::handle_method(self, Self::animation_status_changed),
84 );
85 }
86
87 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &StatusTransition<W>) {
88 let animation = self.widget(app).0.animation();
89 let old_animation = old_widget.0.animation();
90 if animation != old_animation {
91 old_animation.remove_status_listener(
92 app,
93 &AnimationStatusListener::handle_method(self, Self::animation_status_changed),
94 );
95 animation.add_status_listener(
96 app,
97 AnimationStatusListener::handle_method(self, Self::animation_status_changed),
98 );
99 }
100 }
101
102 fn dispose(self: Handle<Self>, app: &mut App) {
103 let animation = self.widget(app).0.animation();
104 animation.remove_status_listener(
105 app,
106 &AnimationStatusListener::handle_method(self, Self::animation_status_changed),
107 );
108 }
109
110 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
111 let widget = context.widget(app).clone();
112 downcast_widget::<StatusTransition<W>>(&*widget)
113 .expect("a StatusTransitionState builds its StatusTransitionWidget")
114 .0
115 .build(app, context)
116 }
117}
118
119impl<W: StatusTransitionWidget> StatusTransitionState<W> {
120 fn animation_status_changed(
121 self: Handle<Self>,
122 app: &mut App,
123 _status: waft_animation::AnimationStatus,
124 ) {
125 self.set_state(app, |_state| {
126 });
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use std::cell::Cell;
134 use std::time::Duration;
135 use waft_foundation::AppCell;
136 use waft_foundation::Ref;
137
138 use waft_animation::{
139 AnimationBehavior, AnimationController, AnimationRef, AnimationStatus, AnyAnimation, Curves,
140 };
141 use waft_scheduler::{Ticker, TickerCallback, TickerProvider};
142
143 use super::*;
144 use crate::test_harness::Harness;
145 use crate::widgets::basic::SizedBox;
146
147 struct TestVSync;
149
150 impl TickerProvider for TestVSync {
151 fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
152 Ticker::new(app, on_tick, None)
153 }
154 }
155
156 #[derive(Debug)]
158 struct StatusWidth {
159 animation: AnimationRef<f64>,
160 builds: Rc<Cell<u32>>,
161 }
162
163 impl StatusTransitionWidget for StatusWidth {
164 fn animation(&self) -> AnyAnimation<f64> {
165 self.animation.handle()
166 }
167
168 fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
169 self.builds.set(self.builds.get() + 1);
170 let width = match self.animation.status(app) {
171 AnimationStatus::Dismissed => 10.0,
172 AnimationStatus::Forward => 20.0,
173 AnimationStatus::Reverse => 30.0,
174 AnimationStatus::Completed => 40.0,
175 };
176 SizedBox::new().width(width).height(10.0).into_widget()
177 }
178 }
179
180 fn width_under_root(harness: &Harness, app: &App) -> f64 {
181 harness
182 .render_root(app)
183 .child(app)
184 .expect("a child")
185 .size(app)
186 .width()
187 }
188
189 #[test]
190 fn a_status_transition_rebuilds_on_status_changes_only() {
191 let cell = AppCell::new();
192 let mut app = cell.borrow_mut();
193 let controller = AnimationController::new(
194 &mut app,
195 None,
196 Some(Duration::from_millis(100)),
197 None,
198 0.0,
199 1.0,
200 AnimationBehavior::Normal,
201 TestVSync,
202 );
203 let builds = Rc::new(Cell::new(0));
204 let harness = Harness::mount(
205 &mut app,
206 StatusWidth {
207 animation: controller.erase(),
208 builds: Rc::clone(&builds),
209 }
210 .into_widget(),
211 );
212 harness.pump(&mut app);
213 assert_eq!(builds.get(), 1);
214 assert_eq!(width_under_root(&harness, &app), 10.0);
215
216 controller.animate_to(
217 &mut app,
218 1.0,
219 Some(Duration::from_millis(100)),
220 Curves::linear(),
221 );
222 harness.pump(&mut app);
223 assert_eq!(width_under_root(&harness, &app), 20.0, "forward");
224 let builds_after_forward = builds.get();
225
226 controller.set_value(&mut app, 0.5);
227 harness.pump(&mut app);
228 assert_eq!(
229 builds.get(),
230 builds_after_forward,
231 "a value change with no status change does not rebuild"
232 );
233
234 controller.set_value(&mut app, 1.0);
235 harness.pump(&mut app);
236 assert_eq!(width_under_root(&harness, &app), 40.0, "completed");
237
238 harness.set_child(&mut app, SizedBox::square(Some(5.0)).into_widget());
239 harness.pump(&mut app);
240 let builds_after_unmount = builds.get();
241 controller.set_value(&mut app, 0.0);
242 harness.pump(&mut app);
243 assert_eq!(
244 builds.get(),
245 builds_after_unmount,
246 "dispose removed the status listener"
247 );
248
249 controller.dispose(&mut app);
250 }
251}