Skip to main content

waft_widgets/widgets/
scroll_controller.rs

1//! Flutter counterpart: `widgets/scroll_controller.dart`.
2
3use std::any::TypeId;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use indexmap::IndexMap;
9use waft_animation::Curve;
10use waft_foundation::{
11    App, ChangeNotifier, ChangeNotifierData, CompleterFuture, Handle, HandleId, Listenable,
12    ListenableObject, Listener, OptionRetained, Retained, wait_all,
13};
14
15use crate::widgets::scroll_context::ScrollContext;
16use crate::widgets::scroll_physics::ScrollPhysicsRef;
17use crate::widgets::scroll_position::{AnyScrollPosition, ScrollPositionRef};
18use crate::widgets::scroll_position_with_single_context::ScrollPositionWithSingleContext;
19use waft_foundation::Ref;
20
21/// Signature for when a [`ScrollController`] has added or removed a
22/// [`AnyScrollPosition`].
23///
24/// Since a scroll position is not created and attached to a controller until
25/// the `Scrollable` is built, this can be used to respond to the position being
26/// attached to a controller.
27///
28/// By having access to the position directly, additional listeners can be
29/// applied to aspects of the scroll position, like
30/// [`ScrollPosition::is_scrolling_notifier`].
31///
32/// Used by [`ScrollController::on_attach`] and [`ScrollController::on_detach`].
33pub type ScrollControllerCallback = Rc<dyn Fn(&mut App, AnyScrollPosition)>;
34
35/// The fields of Dart's `ScrollController`, held under the field `scroll_controller`.
36pub struct ScrollControllerData {
37    initial_scroll_offset: f64,
38    keep_scroll_offset: bool,
39    on_attach: Option<ScrollControllerCallback>,
40    on_detach: Option<ScrollControllerCallback>,
41    debug_label: Option<String>,
42    positions: Vec<ScrollPositionRef>,
43}
44
45impl ScrollControllerData {
46    /// The bag of a controller with no attached positions.
47    pub fn new(
48        initial_scroll_offset: f64,
49        keep_scroll_offset: bool,
50        debug_label: Option<String>,
51        on_attach: Option<ScrollControllerCallback>,
52        on_detach: Option<ScrollControllerCallback>,
53    ) -> ScrollControllerData {
54        ScrollControllerData {
55            initial_scroll_offset,
56            keep_scroll_offset,
57            on_attach,
58            on_detach,
59            debug_label,
60            positions: Vec::new(),
61        }
62    }
63}
64
65/// The accessors [`ScrollControllerLeaf`] asks for, for a struct whose bag is the field
66/// `scroll_controller`.
67#[macro_export]
68macro_rules! scroll_controller_accessors {
69    () => {
70        fn scroll_controller_data(
71            self: ::waft_foundation::Handle<Self>,
72            app: &::waft_foundation::App,
73        ) -> &$crate::ScrollControllerData {
74            &app.get(self).scroll_controller
75        }
76
77        fn scroll_controller_data_mut(
78            self: ::waft_foundation::Handle<Self>,
79            app: &mut ::waft_foundation::App,
80        ) -> &mut $crate::ScrollControllerData {
81            &mut app.get_mut(self).scroll_controller
82        }
83    };
84}
85
86/// The trait both scroll-controller leaves implement: [`ScrollController`] and
87/// [`TrackingScrollController`].
88///
89/// The virtuals a subclass overrides are the members with a default body here; the shared
90/// bodies are associated functions on [`ScrollController`], which an override calls where
91/// Dart writes `super.…`.
92pub trait ScrollControllerLeaf: ChangeNotifier + Sized + 'static {
93    /// Dart's `ScrollController` fields, held under the field `scroll_controller`
94    /// ([`scroll_controller_accessors!`](crate::scroll_controller_accessors)).
95    fn scroll_controller_data(self: Handle<Self>, app: &App) -> &ScrollControllerData;
96
97    /// See [`scroll_controller_data`](Self::scroll_controller_data).
98    fn scroll_controller_data_mut(self: Handle<Self>, app: &mut App) -> &mut ScrollControllerData;
99
100    /// The initial value to use for [`offset`](Self::offset).
101    ///
102    /// New [`ScrollPosition`] objects that are created and attached to this
103    /// controller will have their offset initialized to this value
104    /// if [`keep_scroll_offset`](Self::keep_scroll_offset) is false or a scroll offset hasn't
105    /// been saved yet.
106    ///
107    /// Defaults to 0.0.
108    fn initial_scroll_offset(self: Handle<Self>, app: &App) -> f64 {
109        ScrollController::initial_scroll_offset(self.as_controller(), app)
110    }
111
112    /// Register the given position with this controller.
113    ///
114    /// After this function returns, the [`animate_to`](Self::animate_to) and
115    /// [`jump_to`](Self::jump_to) methods on this controller will manipulate the given
116    /// position.
117    fn attach(self: Handle<Self>, app: &mut App, position: ScrollPositionRef) {
118        ScrollController::attach(self.as_controller(), app, position);
119    }
120
121    /// Unregister the given position with this controller.
122    ///
123    /// After this function returns, the [`animate_to`](Self::animate_to) and
124    /// [`jump_to`](Self::jump_to) methods on this controller will not manipulate the given
125    /// position.
126    fn detach(self: Handle<Self>, app: &mut App, position: AnyScrollPosition) {
127        ScrollController::detach(self.as_controller(), app, position);
128    }
129
130    /// Discards any resources used by the object.
131    fn dispose(self: Handle<Self>, app: &mut App) {
132        ScrollController::dispose(self.as_controller(), app);
133    }
134
135    /// Creates a [`ScrollPosition`] for use by a `Scrollable` widget.
136    ///
137    /// A leaf can override this function to customize the [`ScrollPosition`]
138    /// used by the scrollable widgets it controls. For example, `PageController`
139    /// overrides this function to return a page-oriented scroll position
140    /// that keeps the same page visible when the scrollable widget resizes.
141    ///
142    /// By default, returns a [`ScrollPositionWithSingleContext`].
143    ///
144    /// The arguments are generally passed to the [`ScrollPosition`] being created:
145    ///
146    ///  * `physics`: the [`crate::ScrollPhysics`] that determines how the
147    ///    [`ScrollPosition`] should react to user interactions, how it should
148    ///    simulate scrolling when released or flung, etc. It typically comes from the
149    ///    `ScrollView` or other widget that creates the `Scrollable`, or, if none was
150    ///    provided, from the ambient `ScrollConfiguration`.
151    ///  * `context`: a [`ScrollContext`] used for communicating with the object
152    ///    that is to own the [`ScrollPosition`] (typically, this is the `Scrollable`
153    ///    itself).
154    ///  * `old_position`: if this is not the first time a [`ScrollPosition`] has
155    ///    been created for this `Scrollable`, this will be the previous instance.
156    ///    This is used when the environment has changed and the `Scrollable`
157    ///    needs to recreate the [`ScrollPosition`] object. It is `None` the first
158    ///    time the [`ScrollPosition`] is created.
159    fn create_scroll_position(
160        self: Handle<Self>,
161        app: &mut App,
162        physics: ScrollPhysicsRef,
163        context: Rc<dyn ScrollContext>,
164        old_position: Option<AnyScrollPosition>,
165    ) -> ScrollPositionRef {
166        ScrollController::create_scroll_position(
167            self.as_controller(),
168            app,
169            physics,
170            context,
171            old_position,
172        )
173    }
174
175    /// Add additional information to the given `description` for use by
176    /// [`to_string`](Self::to_string).
177    ///
178    /// An override starts with a call to [`ScrollController::debug_fill_description`], where
179    /// Dart writes `super.debugFillDescription(description)`.
180    fn debug_fill_description(self: Handle<Self>, app: &App, description: &mut Vec<String>) {
181        ScrollController::debug_fill_description(self.as_controller(), app, description);
182    }
183
184    /// Dart's `notifyListeners` tear-off: the listener this controller keeps on each attached
185    /// position.
186    fn notification_listener(self: Handle<Self>) -> Listener {
187        Listener::handle_method(self, Self::forward_notification)
188    }
189
190    /// The body behind [`notification_listener`](Self::notification_listener).
191    fn forward_notification(self: Handle<Self>, app: &mut App) {
192        self.notify_listeners(app);
193    }
194
195    // ---- one-line forwarders to the type-erased handle ----
196
197    /// See [`AnyScrollController::keep_scroll_offset`].
198    fn keep_scroll_offset(self: Handle<Self>, app: &App) -> bool {
199        self.as_controller().keep_scroll_offset(app)
200    }
201
202    /// See [`AnyScrollController::on_attach`].
203    fn on_attach(self: Handle<Self>, app: &App) -> Option<ScrollControllerCallback> {
204        self.as_controller().on_attach(app)
205    }
206
207    /// See [`AnyScrollController::on_detach`].
208    fn on_detach(self: Handle<Self>, app: &App) -> Option<ScrollControllerCallback> {
209        self.as_controller().on_detach(app)
210    }
211
212    /// See [`AnyScrollController::debug_label`].
213    fn debug_label(self: Handle<Self>, app: &App) -> Option<String> {
214        self.as_controller().debug_label(app)
215    }
216
217    /// See [`AnyScrollController::positions`].
218    fn positions(self: Handle<Self>, app: &App) -> Vec<AnyScrollPosition> {
219        self.as_controller().positions(app)
220    }
221
222    /// See [`AnyScrollController::has_clients`].
223    fn has_clients(self: Handle<Self>, app: &App) -> bool {
224        self.as_controller().has_clients(app)
225    }
226
227    /// See [`AnyScrollController::position`].
228    fn position(self: Handle<Self>, app: &App) -> AnyScrollPosition {
229        self.as_controller().position(app)
230    }
231
232    /// See [`AnyScrollController::offset`].
233    fn offset(self: Handle<Self>, app: &App) -> f64 {
234        self.as_controller().offset(app)
235    }
236
237    /// See [`AnyScrollController::animate_to`].
238    fn animate_to(
239        self: Handle<Self>,
240        app: &mut App,
241        offset: f64,
242        duration: Duration,
243        curve: Rc<dyn Curve>,
244    ) -> CompleterFuture<()> {
245        self.as_controller()
246            .animate_to(app, offset, duration, curve)
247    }
248
249    /// See [`AnyScrollController::jump_to`].
250    fn jump_to(self: Handle<Self>, app: &mut App, value: f64) {
251        self.as_controller().jump_to(app, value);
252    }
253
254    /// See [`AnyScrollController::to_string`].
255    fn to_string(self: Handle<Self>, app: &App) -> String {
256        self.as_controller().to_string(app)
257    }
258
259    /// This controller as the erased [`AnyScrollController`] — what to pass where a Dart API
260    /// takes a `ScrollController`.
261    fn as_controller(self: Handle<Self>) -> AnyScrollController {
262        AnyScrollController {
263            id: self.id(),
264            vtable: const { &ScrollControllerVTable::of::<Self>() },
265        }
266    }
267}
268
269/// Controls a scrollable widget.
270///
271/// Scroll controllers are typically stored as member variables in `State`
272/// objects and are reused in each `State::build`. A single scroll controller can
273/// be used to control multiple scrollable widgets, but some operations, such
274/// as reading the scroll [`offset`](ScrollControllerLeaf::offset), require the controller to
275/// be used with a single scrollable widget.
276///
277/// A scroll controller creates a [`ScrollPosition`] to manage the state specific
278/// to an individual `Scrollable` widget. To use a custom [`ScrollPosition`],
279/// write a second [`ScrollControllerLeaf`] that overrides
280/// [`create_scroll_position`](ScrollControllerLeaf::create_scroll_position).
281///
282/// Typically used with `ListView`, `GridView`, `CustomScrollView`.
283///
284/// The associated functions on this type are the shared bodies of Dart's `ScrollController`;
285/// a leaf calls one where Dart writes `super.…`.
286///
287/// See also:
288///
289///  * `Scrollable`, which is the lower-level widget that creates and associates
290///    [`ScrollPosition`] objects with [`ScrollController`] objects.
291///  * [`ScrollPosition`], which manages the scroll offset for an individual
292///    scrolling widget.
293///  * [`crate::ScrollNotification`] and `NotificationListener`, which can be used to
294///    listen to scrolling occur without using a [`ScrollController`].
295pub struct ScrollController {
296    change_notifier: ChangeNotifierData,
297    scroll_controller: ScrollControllerData,
298}
299
300impl ScrollController {
301    /// Creates a controller for a scrollable widget.
302    ///
303    /// Dart's defaults: `initial_scroll_offset` 0.0, `keep_scroll_offset` true, and no
304    /// `debug_label`, `on_attach` or `on_detach`.
305    pub fn new(
306        app: &mut App,
307        initial_scroll_offset: f64,
308        keep_scroll_offset: bool,
309        debug_label: Option<String>,
310        on_attach: Option<ScrollControllerCallback>,
311        on_detach: Option<ScrollControllerCallback>,
312    ) -> Ref<ScrollController> {
313        app.create(ScrollController {
314            change_notifier: ChangeNotifierData::new(),
315            scroll_controller: ScrollControllerData::new(
316                initial_scroll_offset,
317                keep_scroll_offset,
318                debug_label,
319                on_attach,
320                on_detach,
321            ),
322        })
323    }
324
325    /// A controller with all of Dart's defaults; `ScrollController()`.
326    pub fn default(app: &mut App) -> Ref<ScrollController> {
327        ScrollController::new(app, 0.0, true, None, None, None)
328    }
329
330    /// See [`ScrollControllerLeaf::initial_scroll_offset`].
331    pub fn initial_scroll_offset(controller: AnyScrollController, app: &App) -> f64 {
332        controller.data(app).initial_scroll_offset
333    }
334
335    /// See [`ScrollControllerLeaf::attach`].
336    pub fn attach(controller: AnyScrollController, app: &mut App, position: ScrollPositionRef) {
337        debug_assert!(!controller.data(app).positions.contains(&position));
338        controller.data_mut(app).positions.push(position.clone());
339        let position = position.handle();
340        position.add_listener(app, controller.notification_listener());
341        if let Some(on_attach) = controller.on_attach(app) {
342            on_attach(app, position);
343        }
344    }
345
346    /// See [`ScrollControllerLeaf::detach`].
347    pub fn detach(controller: AnyScrollController, app: &mut App, position: AnyScrollPosition) {
348        debug_assert!(
349            controller
350                .data(app)
351                .positions
352                .iter()
353                .any(|attached| attached == position)
354        );
355        if let Some(on_detach) = controller.on_detach(app) {
356            on_detach(app, position);
357        }
358        position.remove_listener(app, &controller.notification_listener());
359        controller
360            .data_mut(app)
361            .positions
362            .retain(|attached| attached != position);
363    }
364
365    /// See [`ScrollControllerLeaf::dispose`].
366    pub fn dispose(controller: AnyScrollController, app: &mut App) {
367        let listener = controller.notification_listener();
368        for position in controller.positions(app) {
369            position.remove_listener(app, &listener);
370        }
371        controller.dispose_change_notifier(app);
372    }
373
374    /// See [`ScrollControllerLeaf::create_scroll_position`].
375    pub fn create_scroll_position(
376        controller: AnyScrollController,
377        app: &mut App,
378        physics: ScrollPhysicsRef,
379        context: Rc<dyn ScrollContext>,
380        old_position: Option<AnyScrollPosition>,
381    ) -> ScrollPositionRef {
382        let initial_pixels = controller.initial_scroll_offset(app);
383        let keep_scroll_offset = controller.keep_scroll_offset(app);
384        let debug_label = controller.debug_label(app);
385        ScrollPositionWithSingleContext::new(
386            app,
387            physics,
388            context,
389            Some(initial_pixels),
390            keep_scroll_offset,
391            old_position,
392            debug_label,
393        )
394        .into_erased()
395    }
396
397    /// See [`ScrollControllerLeaf::debug_fill_description`].
398    pub fn debug_fill_description(
399        controller: AnyScrollController,
400        app: &App,
401        description: &mut Vec<String>,
402    ) {
403        if let Some(debug_label) = controller.debug_label(app) {
404            description.push(debug_label);
405        }
406        let initial_scroll_offset = controller.initial_scroll_offset(app);
407        if initial_scroll_offset != 0.0 {
408            description.push(format!("initialScrollOffset: {initial_scroll_offset:.1}, "));
409        }
410        let positions = controller.positions(app);
411        match positions.len() {
412            0 => description.push("no clients".to_string()),
413            // Don't actually list the client itself, since its description may refer to us.
414            1 => description.push(format!("one client, offset {:.1}", controller.offset(app))),
415            count => description.push(format!("{count} clients")),
416        }
417    }
418}
419
420impl ChangeNotifier for ScrollController {
421    fn change_notifier_data(&self) -> &ChangeNotifierData {
422        &self.change_notifier
423    }
424
425    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
426        &mut self.change_notifier
427    }
428}
429
430impl ScrollControllerLeaf for ScrollController {
431    crate::scroll_controller_accessors!();
432}
433
434/// A [`ScrollController`] whose
435/// [`initial_scroll_offset`](ScrollControllerLeaf::initial_scroll_offset) tracks its most
436/// recently updated [`ScrollPosition`].
437///
438/// This type can be used to synchronize the scroll offset of two or more
439/// lazily created scroll views that share a single [`TrackingScrollController`].
440/// It tracks the most recently updated scroll position and reports it as its
441/// initial scroll offset.
442pub struct TrackingScrollController {
443    change_notifier: ChangeNotifierData,
444    scroll_controller: ScrollControllerData,
445    position_to_listener: IndexMap<ScrollPositionRef, Listener>,
446    last_updated: Option<ScrollPositionRef>,
447    last_updated_offset: Option<f64>,
448}
449
450impl TrackingScrollController {
451    /// Creates a scroll controller that continually updates its
452    /// [`initial_scroll_offset`](ScrollControllerLeaf::initial_scroll_offset) to match the
453    /// last scroll notification it received.
454    pub fn new(
455        app: &mut App,
456        initial_scroll_offset: f64,
457        keep_scroll_offset: bool,
458        debug_label: Option<String>,
459        on_attach: Option<ScrollControllerCallback>,
460        on_detach: Option<ScrollControllerCallback>,
461    ) -> Ref<TrackingScrollController> {
462        app.create(TrackingScrollController {
463            change_notifier: ChangeNotifierData::new(),
464            scroll_controller: ScrollControllerData::new(
465                initial_scroll_offset,
466                keep_scroll_offset,
467                debug_label,
468                on_attach,
469                on_detach,
470            ),
471            position_to_listener: IndexMap::new(),
472            last_updated: None,
473            last_updated_offset: None,
474        })
475    }
476
477    /// A tracking controller with all of Dart's defaults.
478    pub fn default(app: &mut App) -> Ref<TrackingScrollController> {
479        TrackingScrollController::new(app, 0.0, true, None, None, None)
480    }
481
482    /// The last [`ScrollPosition`] to change. Returns `None` if there aren't any
483    /// attached scroll positions, or there hasn't been any scrolling yet, or the
484    /// last position to change has since been removed.
485    pub fn most_recently_updated_position(
486        self: Handle<Self>,
487        app: &App,
488    ) -> Option<AnyScrollPosition> {
489        app.get(self).last_updated.handle()
490    }
491}
492
493impl ChangeNotifier for TrackingScrollController {
494    fn change_notifier_data(&self) -> &ChangeNotifierData {
495        &self.change_notifier
496    }
497
498    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
499        &mut self.change_notifier
500    }
501}
502
503impl ScrollControllerLeaf for TrackingScrollController {
504    crate::scroll_controller_accessors!();
505
506    /// Returns the scroll offset of the
507    /// [`most_recently_updated_position`](TrackingScrollController::most_recently_updated_position)
508    /// or, if that is `None`, the initial scroll offset provided to the constructor.
509    fn initial_scroll_offset(self: Handle<Self>, app: &App) -> f64 {
510        app.get(self)
511            .last_updated_offset
512            .unwrap_or_else(|| ScrollController::initial_scroll_offset(self.as_controller(), app))
513    }
514
515    fn attach(self: Handle<Self>, app: &mut App, position: ScrollPositionRef) {
516        ScrollController::attach(self.as_controller(), app, position.clone());
517        debug_assert!(!app.get(self).position_to_listener.contains_key(&position));
518        let listened = position.handle();
519        let listener = Listener::new(move |app| {
520            let pixels = listened.pixels(app);
521            let tracker = app.get_mut(self);
522            tracker.last_updated = tracker
523                .position_to_listener
524                .get_key_value(&listened)
525                .map(|(kept, _)| kept.clone());
526            tracker.last_updated_offset = Some(pixels);
527        });
528        app.get_mut(self)
529            .position_to_listener
530            .insert(position, listener.clone());
531        listened.add_listener(app, listener);
532    }
533
534    fn detach(self: Handle<Self>, app: &mut App, position: AnyScrollPosition) {
535        ScrollController::detach(self.as_controller(), app, position);
536        debug_assert!(app.get(self).position_to_listener.contains_key(&position));
537        let listener = app
538            .get_mut(self)
539            .position_to_listener
540            .shift_remove(&position)
541            .expect("an attached position has a listener");
542        position.remove_listener(app, &listener);
543        if app.get(self).last_updated.handle() == Some(position) {
544            app.get_mut(self).last_updated = None;
545        }
546        if app.get(self).position_to_listener.is_empty() {
547            app.get_mut(self).last_updated_offset = None;
548        }
549    }
550
551    fn dispose(self: Handle<Self>, app: &mut App) {
552        for position in self.positions(app) {
553            let listener = app.get(self).position_to_listener.get(&position).cloned();
554            let listener = listener.expect("an attached position has a listener");
555            position.remove_listener(app, &listener);
556        }
557        ScrollController::dispose(self.as_controller(), app);
558    }
559}
560
561/// The [`ScrollControllerVTable::create_scroll_position`] slot.
562type CreateScrollPositionFn = fn(
563    &mut App,
564    HandleId,
565    ScrollPhysicsRef,
566    Rc<dyn ScrollContext>,
567    Option<AnyScrollPosition>,
568) -> ScrollPositionRef;
569
570/// The vtable of an erased [`AnyScrollController`]: one `&'static` table per leaf type.
571struct ScrollControllerVTable {
572    type_name: fn() -> &'static str,
573    type_id: fn() -> TypeId,
574    add_listener: fn(&mut App, HandleId, Listener),
575    remove_listener: fn(&mut App, HandleId, &Listener),
576    dispose_change_notifier: fn(&mut App, HandleId),
577    data: fn(&App, HandleId) -> &ScrollControllerData,
578    data_mut: fn(&mut App, HandleId) -> &mut ScrollControllerData,
579    notification_listener: fn(HandleId) -> Listener,
580    initial_scroll_offset: fn(&App, HandleId) -> f64,
581    attach: fn(&mut App, HandleId, ScrollPositionRef),
582    detach: fn(&mut App, HandleId, AnyScrollPosition),
583    dispose: fn(&mut App, HandleId),
584    create_scroll_position: CreateScrollPositionFn,
585    debug_fill_description: fn(&App, HandleId, &mut Vec<String>),
586}
587
588/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
589fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
590    Handle::from_id(id)
591}
592
593impl ScrollControllerVTable {
594    /// The table for one leaf type.
595    const fn of<C: ScrollControllerLeaf>() -> ScrollControllerVTable {
596        ScrollControllerVTable {
597            type_name: std::any::type_name::<C>,
598            type_id: TypeId::of::<C>,
599            add_listener: |app, id, listener| {
600                ListenableObject::add_listener(resolve::<C>(id), app, listener);
601            },
602            remove_listener: |app, id, listener| {
603                ListenableObject::remove_listener(resolve::<C>(id), app, listener);
604            },
605            dispose_change_notifier: |app, id| ChangeNotifierData::dispose(app, resolve::<C>(id)),
606            data: |app, id| C::scroll_controller_data(resolve(id), app),
607            data_mut: |app, id| C::scroll_controller_data_mut(resolve(id), app),
608            notification_listener: |id| C::notification_listener(resolve(id)),
609            initial_scroll_offset: |app, id| C::initial_scroll_offset(resolve(id), app),
610            attach: |app, id, position| C::attach(resolve(id), app, position),
611            detach: |app, id, position| C::detach(resolve(id), app, position),
612            dispose: |app, id| C::dispose(resolve(id), app),
613            create_scroll_position: |app, id, physics, context, old_position| {
614                C::create_scroll_position(resolve(id), app, physics, context, old_position)
615            },
616            debug_fill_description: |app, id, description| {
617                C::debug_fill_description(resolve(id), app, description);
618            },
619        }
620    }
621}
622
623/// Erased [`ScrollControllerLeaf`]: what a field or parameter Dart types as
624/// `ScrollController` becomes.
625///
626/// Equality is Dart's `==` on an object reference.
627#[derive(Clone, Copy)]
628pub struct AnyScrollController {
629    id: HandleId,
630    vtable: &'static ScrollControllerVTable,
631}
632
633/// A field Dart types as the erased object, kept: AnyScrollController with its count.
634pub type ScrollControllerRef = Retained<AnyScrollController>;
635
636waft_foundation::erased_handle!(AnyScrollController: ScrollControllerLeaf => ScrollControllerLeaf::as_controller);
637
638impl AnyScrollController {
639    fn data(self, app: &App) -> &ScrollControllerData {
640        (self.vtable.data)(app, self.id)
641    }
642
643    fn data_mut(self, app: &mut App) -> &mut ScrollControllerData {
644        (self.vtable.data_mut)(app, self.id)
645    }
646
647    fn dispose_change_notifier(self, app: &mut App) {
648        (self.vtable.dispose_change_notifier)(app, self.id);
649    }
650
651    /// The identity a dump shows, Dart's `describeIdentity(controller)` without the description
652    /// its `toString` adds: a widget's properties are filled without an `App`.
653    pub fn identity_hash(self) -> u64 {
654        self.id.identity_hash()
655    }
656
657    /// Dart's `controller.runtimeType`, for the identity checks a `Scrollable` makes.
658    pub fn type_id(self) -> TypeId {
659        (self.vtable.type_id)()
660    }
661
662    /// See [`ScrollControllerLeaf::notification_listener`].
663    pub fn notification_listener(self) -> Listener {
664        (self.vtable.notification_listener)(self.id)
665    }
666
667    /// See [`ScrollControllerLeaf::initial_scroll_offset`].
668    pub fn initial_scroll_offset(self, app: &App) -> f64 {
669        (self.vtable.initial_scroll_offset)(app, self.id)
670    }
671
672    /// Each time a scroll completes, save the current scroll
673    /// [`offset`](Self::offset) with `PageStorage` and restore it if this controller's
674    /// scrollable is recreated.
675    ///
676    /// If this property is set to false, the scroll offset is never saved
677    /// and [`initial_scroll_offset`](Self::initial_scroll_offset) is always used to initialize
678    /// the scroll offset. If true (the default), the initial scroll offset is used the
679    /// first time the controller's scrollable is created, since there's no
680    /// scroll offset to restore yet. Subsequently the saved offset is
681    /// restored and the initial scroll offset is ignored.
682    pub fn keep_scroll_offset(self, app: &App) -> bool {
683        self.data(app).keep_scroll_offset
684    }
685
686    /// Called when a [`ScrollPosition`] is attached to the scroll controller.
687    ///
688    /// Since a scroll position is not attached until a `Scrollable` is actually
689    /// built, this can be used to respond to a new position being attached.
690    pub fn on_attach(self, app: &App) -> Option<ScrollControllerCallback> {
691        self.data(app).on_attach.clone()
692    }
693
694    /// Called when a [`ScrollPosition`] is detached from the scroll controller.
695    pub fn on_detach(self, app: &App) -> Option<ScrollControllerCallback> {
696        self.data(app).on_detach.clone()
697    }
698
699    /// A label that is used in the [`to_string`](Self::to_string) output. Intended to aid with
700    /// identifying scroll controller instances in debug output.
701    pub fn debug_label(self, app: &App) -> Option<String> {
702        self.data(app).debug_label.clone()
703    }
704
705    /// The currently attached positions.
706    ///
707    /// This should not be mutated directly. [`ScrollPosition`] objects can be added
708    /// and removed using [`attach`](Self::attach) and [`detach`](Self::detach).
709    pub fn positions(self, app: &App) -> Vec<AnyScrollPosition> {
710        self.data(app)
711            .positions
712            .iter()
713            .map(ScrollPositionRef::handle)
714            .collect()
715    }
716
717    /// Whether any [`ScrollPosition`] objects have attached themselves to this
718    /// controller using the [`attach`](Self::attach) method.
719    ///
720    /// If this is false, then members that interact with the [`ScrollPosition`],
721    /// such as [`position`](Self::position), [`offset`](Self::offset),
722    /// [`animate_to`](Self::animate_to), and [`jump_to`](Self::jump_to), must not be called.
723    pub fn has_clients(self, app: &App) -> bool {
724        !self.data(app).positions.is_empty()
725    }
726
727    /// Returns the attached [`ScrollPosition`], from which the actual scroll offset
728    /// of the `ScrollView` can be obtained.
729    ///
730    /// Calling this is only valid when only a single position is attached.
731    pub fn position(self, app: &App) -> AnyScrollPosition {
732        let positions = &self.data(app).positions;
733        assert!(
734            !positions.is_empty(),
735            "ScrollController not attached to any scroll views."
736        );
737        assert!(
738            positions.len() == 1,
739            "ScrollController attached to multiple scroll views."
740        );
741        positions[0].handle()
742    }
743
744    /// The current scroll offset of the scrollable widget.
745    ///
746    /// Requires the controller to be controlling exactly one scrollable widget.
747    pub fn offset(self, app: &App) -> f64 {
748        self.position(app).pixels(app)
749    }
750
751    /// Animates the position from its current value to the given value.
752    ///
753    /// Any active animation is canceled. If the user is currently scrolling, that
754    /// action is canceled.
755    ///
756    /// An animation will be interrupted whenever the user attempts to scroll
757    /// manually, or whenever another activity is started, or whenever the
758    /// animation reaches the edge of the viewport and attempts to overscroll. (If
759    /// the [`ScrollPosition`] does not overscroll but instead allows scrolling
760    /// beyond the extents, then going beyond the extents will not interrupt the
761    /// animation.)
762    ///
763    /// The animation is indifferent to changes to the viewport or content
764    /// dimensions.
765    ///
766    /// Once the animation has completed, the scroll position will attempt to
767    /// begin a ballistic activity in case its value is not stable.
768    ///
769    /// The duration must not be zero. To jump to a particular value without an
770    /// animation, use [`jump_to`](Self::jump_to).
771    ///
772    /// The returned future completes once every attached position's animation has ended.
773    pub fn animate_to(
774        self,
775        app: &mut App,
776        offset: f64,
777        duration: Duration,
778        curve: Rc<dyn Curve>,
779    ) -> CompleterFuture<()> {
780        assert!(
781            self.has_clients(app),
782            "ScrollController not attached to any scroll views."
783        );
784        let futures: Vec<CompleterFuture<()>> = self
785            .positions(app)
786            .into_iter()
787            .map(|position| position.animate_to(app, offset, duration, curve.clone()))
788            .collect();
789        CompleterFuture::spawn(app, async move {
790            wait_all(futures).await;
791        })
792    }
793
794    /// Jumps the scroll position from its current value to the given value,
795    /// without animation, and without checking if the new value is in range.
796    ///
797    /// Any active animation is canceled. If the user is currently scrolling, that
798    /// action is canceled.
799    ///
800    /// If this method changes the scroll position, a sequence of start/update/end
801    /// scroll notifications will be dispatched. No overscroll notifications can
802    /// be generated by this method.
803    ///
804    /// Immediately after the jump, a ballistic activity is started, in case the
805    /// value was out of range.
806    pub fn jump_to(self, app: &mut App, value: f64) {
807        assert!(
808            self.has_clients(app),
809            "ScrollController not attached to any scroll views."
810        );
811        for position in self.positions(app) {
812            position.jump_to(app, value);
813        }
814    }
815
816    /// See [`ScrollControllerLeaf::attach`].
817    pub fn attach(self, app: &mut App, position: ScrollPositionRef) {
818        (self.vtable.attach)(app, self.id, position);
819    }
820
821    /// See [`ScrollControllerLeaf::detach`].
822    pub fn detach(self, app: &mut App, position: AnyScrollPosition) {
823        (self.vtable.detach)(app, self.id, position);
824    }
825
826    /// See [`ScrollControllerLeaf::dispose`].
827    pub fn dispose(self, app: &mut App) {
828        (self.vtable.dispose)(app, self.id);
829    }
830
831    /// See [`ScrollControllerLeaf::create_scroll_position`].
832    pub fn create_scroll_position(
833        self,
834        app: &mut App,
835        physics: ScrollPhysicsRef,
836        context: Rc<dyn ScrollContext>,
837        old_position: Option<AnyScrollPosition>,
838    ) -> ScrollPositionRef {
839        (self.vtable.create_scroll_position)(app, self.id, physics, context, old_position)
840    }
841
842    /// See [`ScrollControllerLeaf::debug_fill_description`].
843    pub fn debug_fill_description(self, app: &App, description: &mut Vec<String>) {
844        (self.vtable.debug_fill_description)(app, self.id, description);
845    }
846
847    /// Dart's `toString`, which reads the arena and so cannot be [`std::fmt::Debug`].
848    pub fn to_string(self, app: &App) -> String {
849        let mut description = Vec::new();
850        self.debug_fill_description(app, &mut description);
851        let name = (self.vtable.type_name)();
852        let short = name.rsplit("::").next().unwrap_or(name);
853        format!("{short}#{:?}({})", self.id, description.join(", "))
854    }
855}
856
857impl Debug for AnyScrollController {
858    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
859        write!(f, "AnyScrollController({:?})", self.id)
860    }
861}
862
863impl Listenable for AnyScrollController {
864    fn add_listener(&self, app: &mut App, listener: Listener) {
865        (self.vtable.add_listener)(app, self.id, listener);
866    }
867
868    fn remove_listener(&self, app: &mut App, listener: &Listener) {
869        (self.vtable.remove_listener)(app, self.id, listener);
870    }
871}
872
873#[cfg(test)]
874mod tests {
875    use std::cell::Cell;
876    use waft_foundation::AppCell;
877
878    use waft_animation::Curves;
879    use waft_foundation::ListenableObject;
880
881    use super::*;
882    use crate::test_harness::pump_every_view;
883    use crate::test_harness::{ScrollHarness, mount_scroll_harness};
884    use crate::widgets::scroll_physics::ClampingScrollPhysics;
885
886    fn attached(
887        app: &mut App,
888        harness: &ScrollHarness,
889        controller: AnyScrollController,
890    ) -> ScrollPositionRef {
891        let position = controller.create_scroll_position(
892            app,
893            Rc::new(ClampingScrollPhysics::new()),
894            Rc::clone(&harness.scroll_context),
895            None,
896        );
897        controller.attach(app, position.clone());
898        position.apply_viewport_dimension(app, 100.0);
899        position.apply_content_dimensions(app, 0.0, 400.0);
900        app.drain_microtasks();
901        position
902    }
903
904    #[test]
905    fn a_controller_creates_its_position_at_the_initial_scroll_offset() {
906        let cell = AppCell::new();
907        let mut app = cell.borrow_mut();
908        let harness = mount_scroll_harness(&mut app);
909        let controller =
910            ScrollController::new(&mut app, 25.0, true, Some("list".to_string()), None, None);
911        assert!(!controller.has_clients(&app));
912        assert_eq!(controller.initial_scroll_offset(&app), 25.0);
913
914        let position = attached(&mut app, &harness, controller.as_controller());
915
916        assert!(controller.has_clients(&app));
917        assert_eq!(controller.offset(&app), 25.0);
918        assert_eq!(controller.positions(&app), vec![position.handle()]);
919        assert!(
920            controller
921                .to_string(&app)
922                .contains("one client, offset 25.0")
923        );
924
925        controller.detach(&mut app, position.handle());
926        assert!(!controller.has_clients(&app));
927        assert!(controller.to_string(&app).contains("no clients"));
928    }
929
930    #[test]
931    fn a_controller_forwards_its_positions_notifications() {
932        let cell = AppCell::new();
933        let mut app = cell.borrow_mut();
934        let harness = mount_scroll_harness(&mut app);
935        let controller = ScrollController::default(&mut app);
936        let position = attached(&mut app, &harness, controller.as_controller());
937
938        let notified = Rc::new(Cell::new(0));
939        let counter = notified.clone();
940        ListenableObject::add_listener(
941            controller.handle(),
942            &mut app,
943            Listener::new(move |_app| counter.set(counter.get() + 1)),
944        );
945
946        controller.jump_to(&mut app, 60.0);
947        assert_eq!(controller.offset(&app), 60.0);
948        assert_eq!(notified.get(), 1);
949
950        controller.detach(&mut app, position.handle());
951        position.jump_to(&mut app, 90.0);
952        assert_eq!(notified.get(), 1);
953    }
954
955    /// `animate_to` drives every attached position, and its future resolves only once the last
956    /// of them has settled, at the checkpoint that runs the continuation.
957    #[test]
958    fn animate_to_resolves_after_every_position_has_settled() {
959        let cell = AppCell::new();
960        let mut app = cell.borrow_mut();
961        let harness = mount_scroll_harness(&mut app);
962        let controller = ScrollController::default(&mut app);
963        let first = attached(&mut app, &harness, controller.as_controller());
964        let second = attached(&mut app, &harness, controller.as_controller());
965
966        let done = controller.animate_to(
967            &mut app,
968            200.0,
969            Duration::from_millis(100),
970            Curves::linear(),
971        );
972        pump_every_view(&mut app, Duration::ZERO);
973        pump_every_view(&mut app, Duration::from_millis(50));
974        assert!((first.pixels(&app) - 100.0).abs() < 0.001);
975        assert!((second.pixels(&app) - 100.0).abs() < 0.001);
976        assert!(!done.is_completed());
977
978        pump_every_view(&mut app, Duration::from_millis(100));
979        assert_eq!(first.pixels(&app), 200.0);
980        assert_eq!(second.pixels(&app), 200.0);
981        // The frame past the duration ends both activities.
982        pump_every_view(&mut app, Duration::from_millis(150));
983        assert!(
984            !done.is_completed(),
985            "the wait over the positions resolves at the checkpoint"
986        );
987        drop(app);
988        cell.checkpoint();
989        assert!(done.is_completed());
990    }
991
992    #[test]
993    fn on_attach_and_on_detach_see_the_position() {
994        let cell = AppCell::new();
995        let mut app = cell.borrow_mut();
996        let harness = mount_scroll_harness(&mut app);
997        let attaches = Rc::new(Cell::new(0));
998        let detaches = Rc::new(Cell::new(0));
999        let attached_count = attaches.clone();
1000        let detached_count = detaches.clone();
1001        let controller = ScrollController::new(
1002            &mut app,
1003            0.0,
1004            true,
1005            None,
1006            Some(Rc::new(move |_app, _position| {
1007                attached_count.set(attached_count.get() + 1);
1008            })),
1009            Some(Rc::new(move |_app, _position| {
1010                detached_count.set(detached_count.get() + 1);
1011            })),
1012        );
1013
1014        let position = attached(&mut app, &harness, controller.as_controller());
1015        assert_eq!(attaches.get(), 1);
1016        assert_eq!(detaches.get(), 0);
1017
1018        controller.detach(&mut app, position.handle());
1019        assert_eq!(detaches.get(), 1);
1020    }
1021
1022    #[test]
1023    fn a_tracking_controller_reports_the_most_recently_updated_offset() {
1024        let cell = AppCell::new();
1025        let mut app = cell.borrow_mut();
1026        let harness = mount_scroll_harness(&mut app);
1027        let controller = TrackingScrollController::new(&mut app, 10.0, true, None, None, None);
1028        assert_eq!(controller.initial_scroll_offset(&app), 10.0);
1029        assert!(controller.most_recently_updated_position(&app).is_none());
1030
1031        let position = attached(&mut app, &harness, controller.as_controller());
1032        assert_eq!(controller.initial_scroll_offset(&app), 10.0);
1033
1034        position.jump_to(&mut app, 80.0);
1035        assert_eq!(controller.initial_scroll_offset(&app), 80.0);
1036        assert_eq!(
1037            controller.most_recently_updated_position(&app),
1038            Some(position.handle())
1039        );
1040
1041        controller.detach(&mut app, position.handle());
1042        assert!(controller.most_recently_updated_position(&app).is_none());
1043        assert_eq!(controller.initial_scroll_offset(&app), 10.0);
1044    }
1045}