Skip to main content

waft_material/
tab_controller.rs

1//! Flutter counterpart: material_ui's `tab_controller.dart`.
2
3use 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
17/// Coordinates tab selection between a `TabBar` and a `TabBarView`.
18///
19/// The [`index`](Self::index) property is the index of the selected tab and the
20/// [`animation`](Self::animation) represents the current scroll positions of the tab bar and
21/// the tab bar view. The selected tab's index can be changed with
22/// [`animate_to`](Self::animate_to).
23///
24/// A stateful widget that builds a `TabBar` or a `TabBarView` can create
25/// a [`TabController`] and share it directly.
26///
27/// When the `TabBar` and `TabBarView` don't have a convenient stateful
28/// ancestor, a [`TabController`] can be shared by providing a
29/// [`DefaultTabController`] inherited widget.
30///
31/// A disposed controller stays in the arena, as a Dart object outlives its `dispose` while
32/// something still holds it: a `TabBar` rebuilt with a new controller reads the old one's
33/// [`animation`](Self::animation), `None`, to learn it was disposed. It is freed once nothing
34/// holds it.
35pub struct TabController {
36    change_notifier: ChangeNotifierData,
37    animation_controller: Option<Ref<AnimationController>>,
38    animation_duration: Duration,
39
40    /// The total number of tabs.
41    ///
42    /// Typically greater than one. Must match `TabBar::tabs`'s and
43    /// `TabBarView::children`'s length.
44    pub length: usize,
45
46    index: usize,
47    previous_index: usize,
48    index_is_changing_count: i32,
49}
50
51impl TabController {
52    /// Creates an object that manages the state required by `TabBar` and a
53    /// `TabBarView`.
54    ///
55    /// The `length` is typically a value greater than one, i.e. typically there are two or more
56    /// tabs. The `length` must match `TabBar::tabs`'s and `TabBarView::children`'s length.
57    ///
58    /// The `initial_index` must be valid given `length`. If `length` is zero, then
59    /// `initial_index` must be 0 (Dart's default).
60    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    // Private constructor used by `copy_with_and_dispose`. This allows a new TabController to
88    // be created without having to create a new animationController.
89    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    /// Creates a new [`TabController`] with `index`, `previous_index`, `length`, and
109    /// `animation_duration` if they are non-null, and disposes current instance.
110    ///
111    /// This method is used by [`DefaultTabController`].
112    ///
113    /// When [`DefaultTabController::length`] is updated, this method is called to
114    /// create a new [`TabController`] without creating a new [`AnimationController`].
115    /// Instead the animation controller is taken from the current instance and
116    /// passed to the new instance.
117    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    /// An animation whose value represents the current position of the `TabBar`'s
159    /// selected tab indicator as well as the scrollOffsets of the `TabBar`
160    /// and `TabBarView`.
161    ///
162    /// The animation's value ranges from 0.0 to [`length`](Self::length) - 1.0. After the
163    /// selected tab is changed, the animation's value equals [`index`](Self::index). The
164    /// animation's value can be [`offset`](Self::offset) by +/- 1.0 to reflect `TabBarView`
165    /// drag scrolling.
166    ///
167    /// If this [`TabController`] was disposed, then return `None`.
168    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    /// Controls the duration of TabController and TabBarView animations.
176    ///
177    /// Defaults to `K_TAB_SCROLL_DURATION`.
178    pub fn animation_duration(self: Handle<Self>, app: &App) -> Duration {
179        app.get(self).animation_duration
180    }
181
182    /// The total number of tabs; see [`length`](Self::length).
183    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); // Because the value of indexIsChanging may have changed.
211            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            // Dart's closure captures `this`, so the controller stays alive until the
218            // animation ends, even if it was disposed and every other reference went.
219            let this = self.keep(app);
220            future.when_complete_or_cancel(
221                app,
222                Listener::new(move |app| {
223                    let this = this.handle();
224                    // don't notify if we've been disposed
225                    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    /// The index of the currently selected tab.
240    ///
241    /// Changing the index also updates [`previous_index`](Self::previous_index), sets the
242    /// [`animation`](Self::animation)'s value to index, resets
243    /// [`index_is_changing`](Self::index_is_changing) to false, and notifies listeners.
244    ///
245    /// To change the currently selected tab and play the [`animation`](Self::animation) use
246    /// [`animate_to`](Self::animate_to).
247    ///
248    /// The value of [`index`](Self::index) must be valid given [`length`](Self::length). If
249    /// [`length`](Self::length) is zero, then [`index`](Self::index) will also be zero.
250    pub fn index(self: Handle<Self>, app: &App) -> usize {
251        app.get(self).index
252    }
253
254    /// Sets [`index`](Self::index).
255    pub fn set_index(self: Handle<Self>, app: &mut App, value: usize) {
256        self.change_index(app, value, None, None);
257    }
258
259    /// The index of the previously selected tab.
260    ///
261    /// Initially the same as [`index`](Self::index).
262    pub fn previous_index(self: Handle<Self>, app: &App) -> usize {
263        app.get(self).previous_index
264    }
265
266    /// True while we're animating from [`previous_index`](Self::previous_index) to
267    /// [`index`](Self::index) as a consequence of calling [`animate_to`](Self::animate_to).
268    ///
269    /// This value is true during the [`animate_to`](Self::animate_to) animation that's
270    /// triggered when the user taps a `TabBar` tab. It is false when [`offset`](Self::offset)
271    /// is changing as a consequence of the user dragging (and "flinging") the `TabBarView`.
272    pub fn index_is_changing(self: Handle<Self>, app: &App) -> bool {
273        app.get(self).index_is_changing_count != 0
274    }
275
276    /// Immediately sets [`index`](Self::index) and [`previous_index`](Self::previous_index)
277    /// and then plays the [`animation`](Self::animation) from its current value to
278    /// [`index`](Self::index).
279    ///
280    /// While the animation is running [`index_is_changing`](Self::index_is_changing) is true.
281    /// When the animation completes [`offset`](Self::offset) will be 0.0.
282    ///
283    /// Dart's defaults: `duration` the controller's
284    /// [`animation_duration`](Self::animation_duration), `curve` `Curves::ease()`.
285    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    /// The difference between the [`animation`](Self::animation)'s value and
302    /// [`index`](Self::index).
303    ///
304    /// The offset value must be between -1.0 and 1.0.
305    ///
306    /// This property is typically set by the `TabBarView` when the user
307    /// drags left or right. A value between -1.0 and 0.0 implies that the
308    /// TabBarView has been dragged to the left. Similarly a value between
309    /// 0.0 and 1.0 implies that the TabBarView has been dragged to the right.
310    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    /// Sets [`offset`](Self::offset).
315    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    /// Discards the controller's animation; Dart's `dispose`.
327    ///
328    /// The disposed animation controller lives on, as Dart's outlives its `dispose`: a tab
329    /// bar's indicator painter and its tabs' animations still hold it, and take their
330    /// listeners off it only when they are replaced.
331    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/// Dart's `_TabControllerScope`.
350#[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
367/// The [`TabController`] for descendant widgets that don't specify one
368/// explicitly.
369///
370/// [`DefaultTabController`] is an inherited widget that is used to share a
371/// [`TabController`] with a `TabBar` or a `TabBarView`. It's used when sharing an
372/// explicitly created [`TabController`] isn't convenient because the tab bar
373/// widgets are created by a stateless parent widget or by different parent
374/// widgets.
375pub struct DefaultTabController {
376    pub key: Option<KeyRef>,
377
378    /// The total number of tabs.
379    ///
380    /// Typically greater than one. Must match `TabBar::tabs`'s and
381    /// `TabBarView::children`'s length.
382    pub length: usize,
383
384    /// The initial index of the selected tab.
385    ///
386    /// Defaults to zero.
387    pub initial_index: usize,
388
389    /// Controls the duration of DefaultTabController and TabBarView animations.
390    ///
391    /// Defaults to `K_TAB_SCROLL_DURATION`.
392    pub animation_duration: Option<Duration>,
393
394    /// The widget below this widget in the tree.
395    ///
396    /// Typically a `Scaffold` whose `AppBar` includes a `TabBar`.
397    pub child: WidgetRef,
398}
399
400impl DefaultTabController {
401    /// Creates a default tab controller for the given [`child`](Self::child) widget.
402    ///
403    /// The [`length`](Self::length) argument is typically greater than one. The
404    /// [`length`](Self::length) must match `TabBar::tabs`'s and `TabBarView::children`'s length.
405    #[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    /// Dart `DefaultTabController(key:)`.
417    pub fn key(mut self, key: KeyRef) -> DefaultTabController {
418        self.key = Some(key);
419        self
420    }
421
422    /// Dart `DefaultTabController(initialIndex:)`.
423    pub fn initial_index(mut self, initial_index: usize) -> DefaultTabController {
424        self.initial_index = initial_index;
425        self
426    }
427
428    /// Dart `DefaultTabController(animationDuration:)`.
429    pub fn animation_duration(mut self, animation_duration: Duration) -> DefaultTabController {
430        self.animation_duration = Some(animation_duration);
431        self
432    }
433
434    /// Dart's constructor assert, across `length` and `initial_index`.
435    fn debug_check_constructor(&self) {
436        debug_assert!(self.length == 0 || self.initial_index < self.length);
437    }
438
439    /// The closest instance of [`DefaultTabController`] that encloses the given
440    /// context, or `None` if none is found.
441    ///
442    /// Typical usage is as follows:
443    ///
444    /// ```text
445    /// let controller = DefaultTabController::maybe_of(app, context);
446    /// ```
447    ///
448    /// Calling this method will create a dependency on the closest
449    /// [`DefaultTabController`] in the `context`, if there is one.
450    ///
451    /// See also:
452    ///
453    /// * [`DefaultTabController::of`], which is similar to this method, but asserts
454    ///   if no [`DefaultTabController`] ancestor is found.
455    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    /// The closest instance of [`DefaultTabController`] that encloses the given
462    /// context.
463    ///
464    /// If no instance is found, this method will assert in debug mode and throw
465    /// an exception in release mode.
466    ///
467    /// Calling this method will create a dependency on the closest
468    /// [`DefaultTabController`] in the `context`.
469    ///
470    /// Typical usage is as follows:
471    ///
472    /// ```text
473    /// let controller = DefaultTabController::of(app, context);
474    /// ```
475    ///
476    /// See also:
477    ///
478    /// * [`DefaultTabController::maybe_of`], which is similar to this method, but
479    ///   returns `None` if no [`DefaultTabController`] ancestor is found.
480    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
527/// Dart's `_DefaultTabControllerState`.
528pub struct DefaultTabControllerState {
529    state: StateData<DefaultTabController>,
530    single_ticker_provider: SingleTickerProviderStateMixinData,
531    /// Dart's `late TabController _controller`, created in `init_state`.
532    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
560/// Dart's `vsync: this`.
561impl 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            // If the length is shortened while the last tab is selected, we should
608            // automatically update the index of the controller to be the new last tab.
609            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}