1use std::fmt;
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_animation::{AnimationBehavior, AnimationController, AnyAnimation, Curve, Curves};
8use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, Listener, Ref};
9use waft_scheduler::{Ticker, TickerCallback, TickerProvider, TickerProviderObject};
10use waft_widgets::{
11 BuildContext, InheritedWidget, IntoWidget, KeyRef, SingleTickerProviderStateMixin,
12 SingleTickerProviderStateMixinData, State, StateData, StatefulWidget, TickerMode, WidgetRef,
13};
14
15use crate::constants::K_TAB_SCROLL_DURATION;
16
17pub struct TabController {
36 change_notifier: ChangeNotifierData,
37 animation_controller: Option<Ref<AnimationController>>,
38 animation_duration: Duration,
39
40 pub length: usize,
45
46 index: usize,
47 previous_index: usize,
48 index_is_changing_count: i32,
49}
50
51impl TabController {
52 pub fn new(
61 app: &mut App,
62 initial_index: usize,
63 animation_duration: Option<Duration>,
64 length: usize,
65 vsync: impl TickerProvider,
66 ) -> Ref<TabController> {
67 debug_assert!(length == 0 || initial_index < length);
68 let animation_controller = AnimationController::unbounded(
69 app,
70 initial_index as f64,
71 None,
72 None,
73 AnimationBehavior::Preserve,
74 vsync,
75 );
76 app.create(TabController {
77 change_notifier: ChangeNotifierData::new(),
78 animation_controller: Some(animation_controller),
79 animation_duration: animation_duration.unwrap_or(K_TAB_SCROLL_DURATION),
80 length,
81 index: initial_index,
82 previous_index: initial_index,
83 index_is_changing_count: 0,
84 })
85 }
86
87 fn new_private(
90 app: &mut App,
91 index: usize,
92 previous_index: usize,
93 animation_controller: Option<Ref<AnimationController>>,
94 animation_duration: Duration,
95 length: usize,
96 ) -> Ref<TabController> {
97 app.create(TabController {
98 change_notifier: ChangeNotifierData::new(),
99 animation_controller,
100 animation_duration,
101 length,
102 index,
103 previous_index,
104 index_is_changing_count: 0,
105 })
106 }
107
108 fn copy_with_and_dispose(
118 self: Handle<Self>,
119 app: &mut App,
120 index: Option<usize>,
121 length: Option<usize>,
122 previous_index: Option<usize>,
123 animation_duration: Option<Duration>,
124 ) -> Ref<TabController> {
125 if let Some(index) = index {
126 self.animation_controller_handle(app)
127 .set_value(app, index as f64);
128 }
129 let this = app.get(self);
130 let (current_index, current_length, current_previous_index, current_duration) = (
131 this.index,
132 this.length,
133 this.previous_index,
134 this.animation_duration,
135 );
136 let animation_controller = this.animation_controller.clone();
137 let result = TabController::new_private(
138 app,
139 index.unwrap_or(current_index),
140 previous_index.unwrap_or(current_previous_index),
141 animation_controller,
142 animation_duration.unwrap_or(current_duration),
143 length.unwrap_or(current_length),
144 );
145 app.get_mut(self).animation_controller = None;
146 self.dispose(app);
147 result
148 }
149
150 fn animation_controller_handle(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
151 app.get(self)
152 .animation_controller
153 .as_ref()
154 .expect("a TabController is used after dispose")
155 .handle()
156 }
157
158 pub fn animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
169 app.get(self)
170 .animation_controller
171 .as_ref()
172 .map(|controller| controller.view())
173 }
174
175 pub fn animation_duration(self: Handle<Self>, app: &App) -> Duration {
179 app.get(self).animation_duration
180 }
181
182 pub fn length(self: Handle<Self>, app: &App) -> usize {
184 app.get(self).length
185 }
186
187 fn change_index(
188 self: Handle<Self>,
189 app: &mut App,
190 value: usize,
191 duration: Option<Duration>,
192 curve: Option<Rc<dyn Curve>>,
193 ) {
194 let this = app.get(self);
195 debug_assert!(value < this.length || this.length == 0);
196 debug_assert!(duration.is_some() || curve.is_none());
197 debug_assert!(this.index_is_changing_count >= 0);
198 if value == this.index || this.length < 2 {
199 return;
200 }
201 let index = self.index(app);
202 let this = app.get_mut(self);
203 this.previous_index = index;
204 this.index = value;
205 let animation_controller = self.animation_controller_handle(app);
206 if let Some(duration) = duration
207 && duration > Duration::ZERO
208 {
209 app.get_mut(self).index_is_changing_count += 1;
210 self.notify_listeners(app); let future = animation_controller.animate_to(
212 app,
213 value as f64,
214 Some(duration),
215 curve.expect("a duration comes with a curve"),
216 );
217 let this = self.keep(app);
220 future.when_complete_or_cancel(
221 app,
222 Listener::new(move |app| {
223 let this = this.handle();
224 if app.get(this).animation_controller.is_some() {
226 app.get_mut(this).index_is_changing_count -= 1;
227 this.notify_listeners(app);
228 }
229 }),
230 );
231 } else {
232 app.get_mut(self).index_is_changing_count += 1;
233 animation_controller.set_value(app, value as f64);
234 app.get_mut(self).index_is_changing_count -= 1;
235 self.notify_listeners(app);
236 }
237 }
238
239 pub fn index(self: Handle<Self>, app: &App) -> usize {
251 app.get(self).index
252 }
253
254 pub fn set_index(self: Handle<Self>, app: &mut App, value: usize) {
256 self.change_index(app, value, None, None);
257 }
258
259 pub fn previous_index(self: Handle<Self>, app: &App) -> usize {
263 app.get(self).previous_index
264 }
265
266 pub fn index_is_changing(self: Handle<Self>, app: &App) -> bool {
273 app.get(self).index_is_changing_count != 0
274 }
275
276 pub fn animate_to(
286 self: Handle<Self>,
287 app: &mut App,
288 value: usize,
289 duration: Option<Duration>,
290 curve: Option<Rc<dyn Curve>>,
291 ) {
292 let duration = duration.unwrap_or(app.get(self).animation_duration);
293 self.change_index(
294 app,
295 value,
296 Some(duration),
297 Some(curve.unwrap_or_else(Curves::ease)),
298 );
299 }
300
301 pub fn offset(self: Handle<Self>, app: &App) -> f64 {
311 self.animation_controller_handle(app).value(app) - app.get(self).index as f64
312 }
313
314 pub fn set_offset(self: Handle<Self>, app: &mut App, value: f64) {
316 debug_assert!((-1.0..=1.0).contains(&value));
317 debug_assert!(!self.index_is_changing(app));
318 if value == self.offset(app) {
319 return;
320 }
321 let index = app.get(self).index as f64;
322 self.animation_controller_handle(app)
323 .set_value(app, value + index);
324 }
325
326 pub fn dispose(self: Handle<Self>, app: &mut App) {
332 if let Some(animation_controller) = app.get_mut(self).animation_controller.take() {
333 animation_controller.dispose(app);
334 }
335 ChangeNotifierData::dispose(app, self);
336 }
337}
338
339impl ChangeNotifier for TabController {
340 fn change_notifier_data(&self) -> &ChangeNotifierData {
341 &self.change_notifier
342 }
343
344 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
345 &mut self.change_notifier
346 }
347}
348
349#[derive(Debug)]
351struct TabControllerScope {
352 controller: Ref<TabController>,
353 enabled: bool,
354 child: WidgetRef,
355}
356
357impl InheritedWidget for TabControllerScope {
358 fn child(&self) -> &WidgetRef {
359 &self.child
360 }
361
362 fn update_should_notify(&self, old: &TabControllerScope) -> bool {
363 self.enabled != old.enabled || self.controller != old.controller
364 }
365}
366
367pub struct DefaultTabController {
376 pub key: Option<KeyRef>,
377
378 pub length: usize,
383
384 pub initial_index: usize,
388
389 pub animation_duration: Option<Duration>,
393
394 pub child: WidgetRef,
398}
399
400impl DefaultTabController {
401 #[cfg_attr(debug_assertions, track_caller)]
406 pub fn new<K>(length: usize, child: impl IntoWidget<K>) -> DefaultTabController {
407 DefaultTabController {
408 key: None,
409 length,
410 initial_index: 0,
411 animation_duration: None,
412 child: child.into_widget(),
413 }
414 }
415
416 pub fn key(mut self, key: KeyRef) -> DefaultTabController {
418 self.key = Some(key);
419 self
420 }
421
422 pub fn initial_index(mut self, initial_index: usize) -> DefaultTabController {
424 self.initial_index = initial_index;
425 self
426 }
427
428 pub fn animation_duration(mut self, animation_duration: Duration) -> DefaultTabController {
430 self.animation_duration = Some(animation_duration);
431 self
432 }
433
434 fn debug_check_constructor(&self) {
436 debug_assert!(self.length == 0 || self.initial_index < self.length);
437 }
438
439 pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Ref<TabController>> {
456 context
457 .depend_on_inherited_widget_of_exact_type::<TabControllerScope>(app)
458 .map(|scope| scope.controller.clone())
459 }
460
461 pub fn of(app: &mut App, context: BuildContext) -> Ref<TabController> {
481 let controller = DefaultTabController::maybe_of(app, context);
482 if cfg!(debug_assertions) && controller.is_none() {
483 panic!(
484 "DefaultTabController.of() was called with a context that does not contain a \
485 DefaultTabController widget.\n\
486 No DefaultTabController widget ancestor could be found starting from the \
487 context that was passed to DefaultTabController.of(). This can happen because \
488 you are using a widget that looks for a DefaultTabController ancestor, but no \
489 such ancestor exists.\n\
490 The context used was:\n {context:?}"
491 );
492 }
493 controller.expect("no DefaultTabController ancestor")
494 }
495}
496
497impl fmt::Debug for DefaultTabController {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 f.debug_struct("DefaultTabController")
500 .field("length", &self.length)
501 .field("initial_index", &self.initial_index)
502 .field("animation_duration", &self.animation_duration)
503 .finish()
504 }
505}
506
507impl StatefulWidget for DefaultTabController {
508 type State = DefaultTabControllerState;
509
510 fn key(&self) -> Option<&KeyRef> {
511 self.key.as_ref()
512 }
513
514 fn debug_check_constructor(&self) {
515 DefaultTabController::debug_check_constructor(self);
516 }
517
518 fn create_state(&self) -> DefaultTabControllerState {
519 DefaultTabControllerState {
520 state: StateData::new(),
521 single_ticker_provider: SingleTickerProviderStateMixinData::default(),
522 controller: None,
523 }
524 }
525}
526
527pub struct DefaultTabControllerState {
529 state: StateData<DefaultTabController>,
530 single_ticker_provider: SingleTickerProviderStateMixinData,
531 controller: Option<Ref<TabController>>,
533}
534
535impl DefaultTabControllerState {
536 fn controller(self: Handle<Self>, app: &App) -> Ref<TabController> {
537 app.get(self)
538 .controller
539 .clone()
540 .expect("created in init_state")
541 }
542}
543
544impl SingleTickerProviderStateMixin for DefaultTabControllerState {
545 fn single_ticker_provider_data(
546 self: Handle<Self>,
547 app: &App,
548 ) -> &SingleTickerProviderStateMixinData {
549 &app.get(self).single_ticker_provider
550 }
551
552 fn single_ticker_provider_data_mut(
553 self: Handle<Self>,
554 app: &mut App,
555 ) -> &mut SingleTickerProviderStateMixinData {
556 &mut app.get_mut(self).single_ticker_provider
557 }
558}
559
560impl TickerProviderObject for DefaultTabControllerState {
562 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
563 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
564 }
565}
566
567impl State for DefaultTabControllerState {
568 type Widget = DefaultTabController;
569 waft_widgets::state_accessors!();
570
571 fn init_state(self: Handle<Self>, app: &mut App) {
572 let widget = self.widget(app);
573 let (length, initial_index, animation_duration) = (
574 widget.length,
575 widget.initial_index,
576 widget.animation_duration,
577 );
578 let controller = TabController::new(app, initial_index, animation_duration, length, self);
579 app.get_mut(self).controller = Some(controller);
580 }
581
582 fn activate(self: Handle<Self>, app: &mut App) {
583 SingleTickerProviderStateMixin::activate(self, app);
584 }
585
586 fn dispose(self: Handle<Self>, app: &mut App) {
587 let controller = self.controller(app);
588 controller.dispose(app);
589 SingleTickerProviderStateMixin::dispose(self, app);
590 }
591
592 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
593 #[allow(deprecated)]
594 let enabled = TickerMode::of(app, context);
595 TabControllerScope {
596 controller: self.controller(app),
597 enabled,
598 child: self.widget(app).child.clone(),
599 }
600 .into_widget()
601 }
602
603 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &DefaultTabController) {
604 let widget = self.widget(app);
605 let (length, animation_duration) = (widget.length, widget.animation_duration);
606 if old_widget.length != length {
607 let controller = self.controller(app);
610 let mut new_index = None;
611 let mut previous_index = controller.previous_index(app);
612 if controller.index(app) >= length {
613 new_index = Some(length.saturating_sub(1));
614 previous_index = controller.index(app);
615 }
616 let controller = controller.copy_with_and_dispose(
617 app,
618 new_index,
619 Some(length),
620 Some(previous_index),
621 animation_duration,
622 );
623 app.get_mut(self).controller = Some(controller);
624 }
625
626 if old_widget.animation_duration != animation_duration {
627 let controller = self.controller(app);
628 let (index, previous_index) = (controller.index(app), controller.previous_index(app));
629 let controller = controller.copy_with_and_dispose(
630 app,
631 Some(index),
632 Some(length),
633 Some(previous_index),
634 animation_duration,
635 );
636 app.get_mut(self).controller = Some(controller);
637 }
638 }
639}