Skip to main content

waft_widgets/widgets/
scroll_position_with_single_context.rs

1//! Flutter counterpart: `widgets/scroll_position_with_single_context.dart`.
2
3use std::rc::Rc;
4use std::time::Duration;
5
6use waft_animation::Curve;
7use waft_foundation::{
8    App, ChangeNotifier, ChangeNotifierData, CompleterFuture, Handle, Listener, OptionRetained,
9};
10use waft_gestures::{Drag, DragStartDetails};
11use waft_painting::AxisDirection;
12use waft_physics::near_equal;
13use waft_rendering::{ScrollDirection, ViewportOffset};
14
15use crate::widgets::scroll_activity::{
16    BallisticScrollActivity, DragScrollActivity, DrivenScrollActivity, HoldScrollActivity,
17    IdleScrollActivity, ScrollActivityDelegate, ScrollActivityRef, ScrollDragController,
18    ScrollHoldController,
19};
20use crate::widgets::scroll_context::ScrollContext;
21use crate::widgets::scroll_physics::ScrollPhysicsRef;
22use crate::widgets::scroll_position::{
23    AnyScrollPosition, ScrollPosition, ScrollPositionBase, ScrollPositionData,
24};
25use waft_foundation::Ref;
26
27/// The fields of Dart's `ScrollPositionWithSingleContext`, which its subclasses carry.
28pub struct ScrollPositionWithSingleContextData {
29    /// Velocity from a previous activity temporarily held by [`ScrollPosition::hold`] to
30    /// potentially transfer to a next activity.
31    held_previous_velocity: f64,
32    user_scroll_direction: ScrollDirection,
33    current_drag: Option<Ref<ScrollDragController>>,
34}
35
36impl ScrollPositionWithSingleContextData {
37    /// The bag of a position that has neither an activity nor a drag yet.
38    pub fn new() -> ScrollPositionWithSingleContextData {
39        ScrollPositionWithSingleContextData {
40            held_previous_velocity: 0.0,
41            user_scroll_direction: ScrollDirection::Idle,
42            current_drag: None,
43        }
44    }
45}
46
47impl Default for ScrollPositionWithSingleContextData {
48    fn default() -> ScrollPositionWithSingleContextData {
49        ScrollPositionWithSingleContextData::new()
50    }
51}
52
53/// The accessors [`ScrollPositionWithSingleContextLeaf`] asks for, for a struct whose bag is
54/// the field `single_context`.
55#[macro_export]
56macro_rules! scroll_position_with_single_context_accessors {
57    () => {
58        fn single_context_data(
59            self: ::waft_foundation::Handle<Self>,
60            app: &::waft_foundation::App,
61        ) -> &$crate::ScrollPositionWithSingleContextData {
62            &app.get(self).single_context
63        }
64
65        fn single_context_data_mut(
66            self: ::waft_foundation::Handle<Self>,
67            app: &mut ::waft_foundation::App,
68        ) -> &mut $crate::ScrollPositionWithSingleContextData {
69            &mut app.get_mut(self).single_context
70        }
71    };
72}
73
74/// A [`ScrollPosition`] with the field Dart's `ScrollPositionWithSingleContext` declares and
75/// the members it overrides.
76///
77/// The shared bodies are associated functions on [`ScrollPositionWithSingleContext`]; an
78/// override calls one where Dart writes `super.…`.
79///
80/// A leaf writes [`scroll_position_with_single_context_viewport_offset_overrides!`](crate::scroll_position_with_single_context_viewport_offset_overrides),
81/// [`scroll_position_with_single_context_overrides!`](crate::scroll_position_with_single_context_overrides)
82/// and [`scroll_position_with_single_context_delegate_overrides!`](crate::scroll_position_with_single_context_delegate_overrides)
83/// to route the `ViewportOffset`, `ScrollPosition` and `ScrollActivityDelegate` virtuals here.
84pub trait ScrollPositionWithSingleContextLeaf: ScrollPosition + ScrollActivityDelegate {
85    /// Dart's `ScrollPositionWithSingleContext` fields, held under the field `single_context`
86    /// ([`scroll_position_with_single_context_accessors!`](crate::scroll_position_with_single_context_accessors)).
87    fn single_context_data(self: Handle<Self>, app: &App) -> &ScrollPositionWithSingleContextData;
88
89    /// See [`single_context_data`](Self::single_context_data).
90    fn single_context_data_mut(
91        self: Handle<Self>,
92        app: &mut App,
93    ) -> &mut ScrollPositionWithSingleContextData;
94
95    /// Dart's `ScrollPositionWithSingleContext.axisDirection`.
96    fn axis_direction(self: Handle<Self>, app: &App) -> AxisDirection {
97        ScrollPositionWithSingleContext::axis_direction(self, app)
98    }
99
100    /// Dart's `ScrollPositionWithSingleContext.setPixels`.
101    fn set_pixels(self: Handle<Self>, app: &mut App, new_pixels: f64) -> f64 {
102        ScrollPositionWithSingleContext::set_pixels(self, app, new_pixels)
103    }
104
105    /// Dart's `ScrollPositionWithSingleContext.absorb`.
106    fn absorb(self: Handle<Self>, app: &mut App, other: AnyScrollPosition) {
107        ScrollPositionWithSingleContext::absorb(self, app, other);
108    }
109
110    /// Dart's `ScrollPositionWithSingleContext.applyNewDimensions`.
111    fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
112        ScrollPositionWithSingleContext::apply_new_dimensions(self, app);
113    }
114
115    /// Dart's `ScrollPositionWithSingleContext.beginActivity`.
116    fn begin_activity(self: Handle<Self>, app: &mut App, new_activity: Option<ScrollActivityRef>) {
117        ScrollPositionWithSingleContext::begin_activity(self, app, new_activity);
118    }
119
120    /// Dart's `ScrollPositionWithSingleContext.applyUserOffset`.
121    fn apply_user_offset(self: Handle<Self>, app: &mut App, delta: f64) {
122        ScrollPositionWithSingleContext::apply_user_offset(self, app, delta);
123    }
124
125    /// Dart's `ScrollPositionWithSingleContext.goIdle`.
126    fn go_idle(self: Handle<Self>, app: &mut App) {
127        ScrollPositionWithSingleContext::go_idle(self, app);
128    }
129
130    /// Start a physics-driven simulation that settles the [`ViewportOffset::pixels`] position,
131    /// starting at a particular velocity.
132    ///
133    /// This method defers to [`crate::ScrollPhysics::create_ballistic_simulation`], which
134    /// typically provides a bounce simulation when the current position is out of
135    /// bounds and a friction simulation when the position is in bounds but has a
136    /// non-zero velocity.
137    ///
138    /// The velocity should be in logical pixels per second.
139    fn go_ballistic(self: Handle<Self>, app: &mut App, velocity: f64) {
140        ScrollPositionWithSingleContext::go_ballistic(self, app, velocity);
141    }
142
143    /// Dart's `ScrollPositionWithSingleContext.userScrollDirection`.
144    fn user_scroll_direction(self: Handle<Self>, app: &App) -> ScrollDirection {
145        self.single_context_data(app).user_scroll_direction
146    }
147
148    /// Set [`ViewportOffset::user_scroll_direction`] to the given value.
149    ///
150    /// If this changes the value, then a [`crate::UserScrollNotification`] is dispatched.
151    fn update_user_scroll_direction(self: Handle<Self>, app: &mut App, value: ScrollDirection) {
152        if ScrollPositionWithSingleContextLeaf::user_scroll_direction(self, app) == value {
153            return;
154        }
155        self.single_context_data_mut(app).user_scroll_direction = value;
156        self.did_update_scroll_direction(app, value);
157    }
158
159    /// Dart's `ScrollPositionWithSingleContext.animateTo`.
160    fn animate_to(
161        self: Handle<Self>,
162        app: &mut App,
163        to: f64,
164        duration: Duration,
165        curve: Rc<dyn Curve>,
166    ) -> CompleterFuture<()> {
167        ScrollPositionWithSingleContext::animate_to(self, app, to, duration, curve)
168    }
169
170    /// Dart's `ScrollPositionWithSingleContext.jumpTo`.
171    fn jump_to(self: Handle<Self>, app: &mut App, value: f64) {
172        ScrollPositionWithSingleContext::jump_to(self, app, value);
173    }
174
175    /// Dart's `ScrollPositionWithSingleContext.pointerScroll`.
176    fn pointer_scroll(self: Handle<Self>, app: &mut App, delta: f64) {
177        ScrollPositionWithSingleContext::pointer_scroll(self, app, delta);
178    }
179
180    /// Dart's deprecated `ScrollPositionWithSingleContext.jumpToWithoutSettling`.
181    fn jump_to_without_settling(self: Handle<Self>, app: &mut App, value: f64) {
182        ScrollPositionWithSingleContext::jump_to_without_settling(self, app, value);
183    }
184
185    /// Dart's `ScrollPositionWithSingleContext.hold`.
186    fn hold(
187        self: Handle<Self>,
188        app: &mut App,
189        hold_cancel_callback: Listener,
190    ) -> Rc<dyn ScrollHoldController> {
191        ScrollPositionWithSingleContext::hold(self, app, hold_cancel_callback)
192    }
193
194    /// Dart's `ScrollPositionWithSingleContext.drag`.
195    fn drag(
196        self: Handle<Self>,
197        app: &mut App,
198        details: DragStartDetails,
199        drag_cancel_callback: Listener,
200    ) -> Rc<dyn Drag> {
201        ScrollPositionWithSingleContext::drag(self, app, details, drag_cancel_callback)
202    }
203
204    /// Dart's `ScrollPositionWithSingleContext.dispose`.
205    fn dispose(self: Handle<Self>, app: &mut App) {
206        ScrollPositionWithSingleContext::dispose(self, app);
207    }
208
209    /// Dart's `ScrollPositionWithSingleContext.debugFillDescription`.
210    fn debug_fill_description(self: Handle<Self>, app: &App, description: &mut Vec<String>) {
211        ScrollPositionWithSingleContext::debug_fill_description(self, app, description);
212    }
213}
214
215/// The `ViewportOffset` members a [`ScrollPositionWithSingleContextLeaf`] inherits. Write it
216/// inside `impl ViewportOffset for MyPosition { .. }`.
217#[macro_export]
218macro_rules! scroll_position_with_single_context_viewport_offset_overrides {
219    () => {
220        fn pixels(self: ::waft_foundation::Handle<Self>, app: &::waft_foundation::App) -> f64 {
221            $crate::ScrollPositionBase::pixels(self, app)
222        }
223
224        fn has_pixels(self: ::waft_foundation::Handle<Self>, app: &::waft_foundation::App) -> bool {
225            $crate::ScrollPositionBase::has_pixels(self, app)
226        }
227
228        fn apply_viewport_dimension(
229            self: ::waft_foundation::Handle<Self>,
230            app: &mut ::waft_foundation::App,
231            viewport_dimension: f64,
232        ) -> bool {
233            $crate::ScrollPositionBase::apply_viewport_dimension(self, app, viewport_dimension)
234        }
235
236        fn apply_content_dimensions(
237            self: ::waft_foundation::Handle<Self>,
238            app: &mut ::waft_foundation::App,
239            min_scroll_extent: f64,
240            max_scroll_extent: f64,
241        ) -> bool {
242            $crate::ScrollPositionBase::apply_content_dimensions(
243                self,
244                app,
245                min_scroll_extent,
246                max_scroll_extent,
247            )
248        }
249
250        fn correct_by(
251            self: ::waft_foundation::Handle<Self>,
252            app: &mut ::waft_foundation::App,
253            correction: f64,
254        ) {
255            $crate::ScrollPositionBase::correct_by(self, app, correction);
256        }
257
258        fn jump_to(
259            self: ::waft_foundation::Handle<Self>,
260            app: &mut ::waft_foundation::App,
261            value: f64,
262        ) {
263            $crate::ScrollPositionWithSingleContextLeaf::jump_to(self, app, value);
264        }
265
266        fn animate_to(
267            self: ::waft_foundation::Handle<Self>,
268            app: &mut ::waft_foundation::App,
269            to: f64,
270            duration: ::std::time::Duration,
271            curve: ::std::rc::Rc<dyn ::waft_animation::Curve>,
272        ) -> ::waft_foundation::CompleterFuture<()> {
273            $crate::ScrollPositionWithSingleContextLeaf::animate_to(self, app, to, duration, curve)
274        }
275
276        fn move_to(
277            self: ::waft_foundation::Handle<Self>,
278            app: &mut ::waft_foundation::App,
279            to: f64,
280            duration: ::std::option::Option<::std::time::Duration>,
281            curve: ::std::option::Option<::std::rc::Rc<dyn ::waft_animation::Curve>>,
282            clamp: ::std::option::Option<bool>,
283        ) -> ::waft_foundation::CompleterFuture<()> {
284            $crate::ScrollPositionBase::move_to(self, app, to, duration, curve, clamp)
285        }
286
287        fn user_scroll_direction(
288            self: ::waft_foundation::Handle<Self>,
289            app: &::waft_foundation::App,
290        ) -> ::waft_rendering::ScrollDirection {
291            $crate::ScrollPositionWithSingleContextLeaf::user_scroll_direction(self, app)
292        }
293
294        fn allow_implicit_scrolling(
295            self: ::waft_foundation::Handle<Self>,
296            app: &::waft_foundation::App,
297        ) -> bool {
298            $crate::ScrollPositionBase::allow_implicit_scrolling(self, app)
299        }
300    };
301}
302
303/// The `ScrollPosition` members a [`ScrollPositionWithSingleContextLeaf`] inherits, plus
304/// [`scroll_position_accessors!`](crate::scroll_position_accessors). Write it inside
305/// `impl ScrollPosition for MyPosition { .. }`.
306#[macro_export]
307macro_rules! scroll_position_with_single_context_overrides {
308    () => {
309        $crate::scroll_position_accessors!();
310
311        fn axis_direction(
312            self: ::waft_foundation::Handle<Self>,
313            app: &::waft_foundation::App,
314        ) -> ::waft_painting::AxisDirection {
315            $crate::ScrollPositionWithSingleContextLeaf::axis_direction(self, app)
316        }
317
318        fn set_pixels(
319            self: ::waft_foundation::Handle<Self>,
320            app: &mut ::waft_foundation::App,
321            new_pixels: f64,
322        ) -> f64 {
323            $crate::ScrollPositionWithSingleContextLeaf::set_pixels(self, app, new_pixels)
324        }
325
326        fn absorb(
327            self: ::waft_foundation::Handle<Self>,
328            app: &mut ::waft_foundation::App,
329            other: $crate::AnyScrollPosition,
330        ) {
331            $crate::ScrollPositionWithSingleContextLeaf::absorb(self, app, other);
332        }
333
334        fn apply_new_dimensions(
335            self: ::waft_foundation::Handle<Self>,
336            app: &mut ::waft_foundation::App,
337        ) {
338            $crate::ScrollPositionWithSingleContextLeaf::apply_new_dimensions(self, app);
339        }
340
341        fn begin_activity(
342            self: ::waft_foundation::Handle<Self>,
343            app: &mut ::waft_foundation::App,
344            new_activity: ::std::option::Option<$crate::ScrollActivityRef>,
345        ) {
346            $crate::ScrollPositionWithSingleContextLeaf::begin_activity(self, app, new_activity);
347        }
348
349        fn pointer_scroll(
350            self: ::waft_foundation::Handle<Self>,
351            app: &mut ::waft_foundation::App,
352            delta: f64,
353        ) {
354            $crate::ScrollPositionWithSingleContextLeaf::pointer_scroll(self, app, delta);
355        }
356
357        fn jump_to_without_settling(
358            self: ::waft_foundation::Handle<Self>,
359            app: &mut ::waft_foundation::App,
360            value: f64,
361        ) {
362            $crate::ScrollPositionWithSingleContextLeaf::jump_to_without_settling(self, app, value);
363        }
364
365        fn hold(
366            self: ::waft_foundation::Handle<Self>,
367            app: &mut ::waft_foundation::App,
368            hold_cancel_callback: ::waft_foundation::Listener,
369        ) -> ::std::rc::Rc<dyn $crate::ScrollHoldController> {
370            $crate::ScrollPositionWithSingleContextLeaf::hold(self, app, hold_cancel_callback)
371        }
372
373        fn drag(
374            self: ::waft_foundation::Handle<Self>,
375            app: &mut ::waft_foundation::App,
376            details: ::waft_gestures::DragStartDetails,
377            drag_cancel_callback: ::waft_foundation::Listener,
378        ) -> ::std::rc::Rc<dyn ::waft_gestures::Drag> {
379            $crate::ScrollPositionWithSingleContextLeaf::drag(
380                self,
381                app,
382                details,
383                drag_cancel_callback,
384            )
385        }
386
387        fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
388            $crate::ScrollPositionWithSingleContextLeaf::dispose(self, app);
389        }
390
391        fn debug_fill_description(
392            self: ::waft_foundation::Handle<Self>,
393            app: &::waft_foundation::App,
394            description: &mut ::std::vec::Vec<::std::string::String>,
395        ) {
396            $crate::ScrollPositionWithSingleContextLeaf::debug_fill_description(
397                self,
398                app,
399                description,
400            );
401        }
402    };
403}
404
405/// The `ScrollActivityDelegate` members a [`ScrollPositionWithSingleContextLeaf`] implements.
406/// Write it inside `impl ScrollActivityDelegate for MyPosition { .. }`.
407#[macro_export]
408macro_rules! scroll_position_with_single_context_delegate_overrides {
409    () => {
410        fn axis_direction(
411            self: ::waft_foundation::Handle<Self>,
412            app: &::waft_foundation::App,
413        ) -> ::waft_painting::AxisDirection {
414            $crate::ScrollPositionWithSingleContextLeaf::axis_direction(self, app)
415        }
416
417        fn set_pixels(
418            self: ::waft_foundation::Handle<Self>,
419            app: &mut ::waft_foundation::App,
420            pixels: f64,
421        ) -> f64 {
422            $crate::ScrollPositionWithSingleContextLeaf::set_pixels(self, app, pixels)
423        }
424
425        fn apply_user_offset(
426            self: ::waft_foundation::Handle<Self>,
427            app: &mut ::waft_foundation::App,
428            delta: f64,
429        ) {
430            $crate::ScrollPositionWithSingleContextLeaf::apply_user_offset(self, app, delta);
431        }
432
433        fn go_idle(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
434            $crate::ScrollPositionWithSingleContextLeaf::go_idle(self, app);
435        }
436
437        fn go_ballistic(
438            self: ::waft_foundation::Handle<Self>,
439            app: &mut ::waft_foundation::App,
440            velocity: f64,
441        ) {
442            $crate::ScrollPositionWithSingleContextLeaf::go_ballistic(self, app, velocity);
443        }
444    };
445}
446
447/// A scroll position that manages scroll activities for a single
448/// [`ScrollContext`].
449///
450/// This type is a concrete implementor of [`ScrollPosition`] logic that handles a
451/// single scroll context, such as a `Scrollable`. An instance of this type
452/// manages [`ScrollActivity`] instances, which change what content is visible in
453/// the `Scrollable`'s `Viewport`.
454///
455/// It is also the base class `_DraggableScrollableSheetScrollPosition` and
456/// `_CupertinoSheetScrollPosition` extend: its field is the
457/// [`ScrollPositionWithSingleContextData`] bag, the members it overrides are
458/// [`ScrollPositionWithSingleContextLeaf`]'s, and the shared bodies are the associated
459/// functions below.
460///
461/// See also:
462///
463///  * [`ScrollPosition`], which defines the underlying model for a position
464///    within a `Scrollable` but is agnostic as to how that position is
465///    changed.
466///  * `ScrollController`, which can manipulate one or more [`ScrollPosition`]s,
467///    and which uses [`ScrollPositionWithSingleContext`] as its default type for
468///    scroll positions.
469pub struct ScrollPositionWithSingleContext {
470    change_notifier: ChangeNotifierData,
471    scroll_position: ScrollPositionData,
472    single_context: ScrollPositionWithSingleContextData,
473}
474
475impl ScrollPositionWithSingleContext {
476    /// Create a [`ScrollPosition`] object that manages its behavior using
477    /// [`ScrollActivity`] objects.
478    ///
479    /// The `initial_pixels` argument can be `None`, but in that case it is
480    /// imperative that the value be set, using [`ScrollPosition::correct_pixels`], as soon as
481    /// [`ScrollPosition::apply_new_dimensions`] is invoked, before calling
482    /// [`ScrollPositionBase::apply_new_dimensions`]. Dart's default is `0.0`.
483    ///
484    /// If `keep_scroll_offset` is true (Dart's default), the current scroll offset is
485    /// saved with `PageStorage` and restored if this scroll position's scrollable
486    /// is recreated.
487    pub fn new(
488        app: &mut App,
489        physics: ScrollPhysicsRef,
490        context: Rc<dyn ScrollContext>,
491        initial_pixels: Option<f64>,
492        keep_scroll_offset: bool,
493        old_position: Option<AnyScrollPosition>,
494        debug_label: Option<String>,
495    ) -> Ref<ScrollPositionWithSingleContext> {
496        let scroll_position =
497            ScrollPositionData::new(app, physics, context, keep_scroll_offset, debug_label);
498        let this = app.create(ScrollPositionWithSingleContext {
499            change_notifier: ChangeNotifierData::new(),
500            scroll_position,
501            single_context: ScrollPositionWithSingleContextData::new(),
502        });
503        ScrollPositionWithSingleContext::init(this.handle(), app, initial_pixels, old_position);
504        this
505    }
506
507    /// Dart's `ScrollPositionWithSingleContext` constructor body, which runs the
508    /// [`ScrollPositionBase::init`] of its superclass first.
509    ///
510    /// A leaf's constructor calls this right after `App::create`, where Dart's superclass
511    /// constructor would run.
512    pub fn init<P: ScrollPositionWithSingleContextLeaf>(
513        this: Handle<P>,
514        app: &mut App,
515        initial_pixels: Option<f64>,
516        old_position: Option<AnyScrollPosition>,
517    ) {
518        // If `old_position` is not `None`, the base constructor first calls `absorb`, which
519        // may set the pixels and the activity.
520        ScrollPositionBase::init(this, app, old_position);
521        if !ViewportOffset::has_pixels(this, app)
522            && let Some(initial_pixels) = initial_pixels
523        {
524            this.correct_pixels(app, initial_pixels);
525        }
526        if this.activity(app).is_none() {
527            ScrollActivityDelegate::go_idle(this, app);
528        }
529        debug_assert!(this.activity(app).is_some());
530    }
531
532    /// See [`ScrollPositionWithSingleContextLeaf::axis_direction`].
533    pub fn axis_direction<P: ScrollPositionWithSingleContextLeaf>(
534        this: Handle<P>,
535        app: &App,
536    ) -> AxisDirection {
537        this.context(app).axis_direction(app)
538    }
539
540    /// See [`ScrollPositionWithSingleContextLeaf::set_pixels`].
541    pub fn set_pixels<P: ScrollPositionWithSingleContextLeaf>(
542        this: Handle<P>,
543        app: &mut App,
544        new_pixels: f64,
545    ) -> f64 {
546        debug_assert!(
547            this.activity(app)
548                .expect("a position has an activity")
549                .is_scrolling(app)
550        );
551        ScrollPositionBase::set_pixels(this, app, new_pixels)
552    }
553
554    /// See [`ScrollPositionWithSingleContextLeaf::absorb`].
555    pub fn absorb<P: ScrollPositionWithSingleContextLeaf>(
556        this: Handle<P>,
557        app: &mut App,
558        other: AnyScrollPosition,
559    ) {
560        ScrollPositionBase::absorb(this, app, other);
561        let Some(other) = other.downcast::<P>(app) else {
562            ScrollActivityDelegate::go_idle(this, app);
563            return;
564        };
565        let delegate = this.as_scroll_activity_delegate();
566        this.activity(app)
567            .expect("absorb adopts the other activity")
568            .update_delegate(app, delegate);
569        this.single_context_data_mut(app).user_scroll_direction =
570            other.single_context_data(app).user_scroll_direction;
571        debug_assert!(this.single_context_data(app).current_drag.is_none());
572        if let Some(current_drag) = other.single_context_data_mut(app).current_drag.take() {
573            current_drag.update_delegate(app, delegate);
574            this.single_context_data_mut(app).current_drag = Some(current_drag);
575        }
576    }
577
578    /// See [`ScrollPositionWithSingleContextLeaf::apply_new_dimensions`].
579    pub fn apply_new_dimensions<P: ScrollPositionWithSingleContextLeaf>(
580        this: Handle<P>,
581        app: &mut App,
582    ) {
583        ScrollPositionBase::apply_new_dimensions(this, app);
584        let physics = this.physics(app);
585        let metrics = this.copy_with(app);
586        let can_drag = physics.should_accept_user_offset(&*metrics);
587        this.context(app).set_can_drag(app, can_drag);
588    }
589
590    /// See [`ScrollPositionWithSingleContextLeaf::begin_activity`].
591    pub fn begin_activity<P: ScrollPositionWithSingleContextLeaf>(
592        this: Handle<P>,
593        app: &mut App,
594        new_activity: Option<ScrollActivityRef>,
595    ) {
596        this.single_context_data_mut(app).held_previous_velocity = 0.0;
597        let Some(new_activity) = new_activity else {
598            return;
599        };
600        debug_assert!(new_activity.delegate(app) == this.as_scroll_activity_delegate());
601        ScrollPositionBase::begin_activity(this, app, Some(new_activity));
602        if let Some(current_drag) = this.single_context_data(app).current_drag.handle() {
603            current_drag.dispose(app);
604        }
605        this.single_context_data_mut(app).current_drag = None;
606        if !this
607            .activity(app)
608            .expect("a position has an activity")
609            .is_scrolling(app)
610        {
611            this.update_user_scroll_direction(app, ScrollDirection::Idle);
612        }
613    }
614
615    /// See [`ScrollPositionWithSingleContextLeaf::apply_user_offset`].
616    pub fn apply_user_offset<P: ScrollPositionWithSingleContextLeaf>(
617        this: Handle<P>,
618        app: &mut App,
619        delta: f64,
620    ) {
621        let direction = if delta > 0.0 {
622            ScrollDirection::Forward
623        } else {
624            ScrollDirection::Reverse
625        };
626        this.update_user_scroll_direction(app, direction);
627        let physics = this.physics(app);
628        let metrics = this.copy_with(app);
629        let new_pixels = ViewportOffset::pixels(this, app)
630            - physics.apply_physics_to_user_offset(&*metrics, delta);
631        ScrollPosition::set_pixels(this, app, new_pixels);
632    }
633
634    /// See [`ScrollPositionWithSingleContextLeaf::go_idle`].
635    pub fn go_idle<P: ScrollPositionWithSingleContextLeaf>(this: Handle<P>, app: &mut App) {
636        let activity = IdleScrollActivity::new(app, this.as_scroll_activity_delegate());
637        ScrollPosition::begin_activity(this, app, Some(activity.into_erased()));
638    }
639
640    /// See [`ScrollPositionWithSingleContextLeaf::go_ballistic`].
641    pub fn go_ballistic<P: ScrollPositionWithSingleContextLeaf>(
642        this: Handle<P>,
643        app: &mut App,
644        velocity: f64,
645    ) {
646        debug_assert!(ViewportOffset::has_pixels(this, app));
647        let physics = this.physics(app);
648        let metrics = this.copy_with(app);
649        match physics.create_ballistic_simulation(&*metrics, velocity) {
650            Some(simulation) => {
651                let vsync = this.context(app).vsync();
652                let should_ignore_pointer = this.should_ignore_pointer(app);
653                let activity = BallisticScrollActivity::new(
654                    app,
655                    this.as_scroll_activity_delegate(),
656                    simulation,
657                    vsync,
658                    should_ignore_pointer,
659                );
660                ScrollPosition::begin_activity(this, app, Some(activity.into_erased()));
661            }
662            None => ScrollActivityDelegate::go_idle(this, app),
663        }
664    }
665
666    /// See [`ScrollPositionWithSingleContextLeaf::animate_to`].
667    pub fn animate_to<P: ScrollPositionWithSingleContextLeaf>(
668        this: Handle<P>,
669        app: &mut App,
670        to: f64,
671        duration: Duration,
672        curve: Rc<dyn Curve>,
673    ) -> CompleterFuture<()> {
674        let physics = this.physics(app);
675        let metrics = this.copy_with(app);
676        if near_equal(
677            Some(to),
678            Some(ViewportOffset::pixels(this, app)),
679            physics.tolerance_for(&*metrics).distance,
680        ) {
681            // Skip the animation, go straight to the position as we are already close.
682            ViewportOffset::jump_to(this, app, to);
683            return CompleterFuture::ready(());
684        }
685
686        let from = ViewportOffset::pixels(this, app);
687        let vsync = this.context(app).vsync();
688        let activity = DrivenScrollActivity::new(
689            app,
690            this.as_scroll_activity_delegate(),
691            from,
692            to,
693            duration,
694            curve,
695            vsync,
696        );
697        ScrollPosition::begin_activity(this, app, Some(activity.erase()));
698        activity.done(app)
699    }
700
701    /// See [`ScrollPositionWithSingleContextLeaf::jump_to`].
702    pub fn jump_to<P: ScrollPositionWithSingleContextLeaf>(
703        this: Handle<P>,
704        app: &mut App,
705        value: f64,
706    ) {
707        ScrollActivityDelegate::go_idle(this, app);
708        if ViewportOffset::pixels(this, app) != value {
709            let old_pixels = ViewportOffset::pixels(this, app);
710            this.force_pixels(app, value);
711            this.did_start_scroll(app);
712            let delta = ViewportOffset::pixels(this, app) - old_pixels;
713            this.did_update_scroll_position_by(app, delta);
714            this.did_end_scroll(app);
715        }
716        ScrollActivityDelegate::go_ballistic(this, app, 0.0);
717    }
718
719    /// See [`ScrollPositionWithSingleContextLeaf::pointer_scroll`].
720    pub fn pointer_scroll<P: ScrollPositionWithSingleContextLeaf>(
721        this: Handle<P>,
722        app: &mut App,
723        delta: f64,
724    ) {
725        if delta == 0.0 {
726            ScrollActivityDelegate::go_ballistic(this, app, 0.0);
727            return;
728        }
729
730        let target_pixels = (ViewportOffset::pixels(this, app) + delta)
731            .max(this.min_scroll_extent(app))
732            .min(this.max_scroll_extent(app));
733        if target_pixels != ViewportOffset::pixels(this, app) {
734            ScrollActivityDelegate::go_idle(this, app);
735            let direction = if -delta > 0.0 {
736                ScrollDirection::Forward
737            } else {
738                ScrollDirection::Reverse
739            };
740            this.update_user_scroll_direction(app, direction);
741            let old_pixels = ViewportOffset::pixels(this, app);
742            // Set the notifier before calling force pixels.
743            // This is set to false again after going ballistic below.
744            this.is_scrolling_notifier(app).set_value(app, true);
745            this.force_pixels(app, target_pixels);
746            this.did_start_scroll(app);
747            let moved = ViewportOffset::pixels(this, app) - old_pixels;
748            this.did_update_scroll_position_by(app, moved);
749            this.did_end_scroll(app);
750            ScrollActivityDelegate::go_ballistic(this, app, 0.0);
751        }
752    }
753
754    /// See [`ScrollPositionWithSingleContextLeaf::jump_to_without_settling`].
755    pub fn jump_to_without_settling<P: ScrollPositionWithSingleContextLeaf>(
756        this: Handle<P>,
757        app: &mut App,
758        value: f64,
759    ) {
760        ScrollActivityDelegate::go_idle(this, app);
761        if ViewportOffset::pixels(this, app) != value {
762            let old_pixels = ViewportOffset::pixels(this, app);
763            this.force_pixels(app, value);
764            this.did_start_scroll(app);
765            let delta = ViewportOffset::pixels(this, app) - old_pixels;
766            this.did_update_scroll_position_by(app, delta);
767            this.did_end_scroll(app);
768        }
769    }
770
771    /// See [`ScrollPositionWithSingleContextLeaf::hold`].
772    pub fn hold<P: ScrollPositionWithSingleContextLeaf>(
773        this: Handle<P>,
774        app: &mut App,
775        hold_cancel_callback: Listener,
776    ) -> Rc<dyn ScrollHoldController> {
777        let previous_velocity = this
778            .activity(app)
779            .expect("a position has an activity")
780            .velocity(app);
781        let hold_activity = HoldScrollActivity::new(
782            app,
783            this.as_scroll_activity_delegate(),
784            Some(hold_cancel_callback),
785        );
786        ScrollPosition::begin_activity(this, app, Some(hold_activity.erase()));
787        this.single_context_data_mut(app).held_previous_velocity = previous_velocity;
788        Rc::new(hold_activity)
789    }
790
791    /// See [`ScrollPositionWithSingleContextLeaf::drag`].
792    pub fn drag<P: ScrollPositionWithSingleContextLeaf>(
793        this: Handle<P>,
794        app: &mut App,
795        details: DragStartDetails,
796        drag_cancel_callback: Listener,
797    ) -> Rc<dyn Drag> {
798        let physics = this.physics(app);
799        let held_previous_velocity = this.single_context_data(app).held_previous_velocity;
800        let drag = ScrollDragController::new(
801            app,
802            this.as_scroll_activity_delegate(),
803            details,
804            Some(drag_cancel_callback),
805            Some(physics.carried_momentum(held_previous_velocity)),
806            physics.drag_start_distance_motion_threshold(),
807        );
808        let activity =
809            DragScrollActivity::new(app, this.as_scroll_activity_delegate(), drag.clone());
810        ScrollPosition::begin_activity(this, app, Some(activity.into_erased()));
811        debug_assert!(this.single_context_data(app).current_drag.is_none());
812        this.single_context_data_mut(app).current_drag = Some(drag.clone());
813        // Dart's `Scrollable._drag` keeps the drag, as the position's `current_drag` does.
814        Rc::new(drag)
815    }
816
817    /// See [`ScrollPositionWithSingleContextLeaf::dispose`].
818    pub fn dispose<P: ScrollPositionWithSingleContextLeaf>(this: Handle<P>, app: &mut App) {
819        if let Some(current_drag) = this.single_context_data(app).current_drag.handle() {
820            current_drag.dispose(app);
821        }
822        this.single_context_data_mut(app).current_drag = None;
823        ScrollPositionBase::dispose(this, app);
824    }
825
826    /// See [`ScrollPositionWithSingleContextLeaf::debug_fill_description`].
827    pub fn debug_fill_description<P: ScrollPositionWithSingleContextLeaf>(
828        this: Handle<P>,
829        app: &App,
830        description: &mut Vec<String>,
831    ) {
832        ScrollPositionBase::debug_fill_description(this, app, description);
833        description.push(this.context(app).type_name().to_string());
834        description.push(format!("{:?}", this.physics(app)));
835        description.push(
836            this.activity(app)
837                .map_or_else(|| "null".to_string(), |activity| activity.describe(app)),
838        );
839        description.push(format!(
840            "{:?}",
841            ViewportOffset::user_scroll_direction(this, app)
842        ));
843    }
844}
845
846impl ChangeNotifier for ScrollPositionWithSingleContext {
847    fn change_notifier_data(&self) -> &ChangeNotifierData {
848        &self.change_notifier
849    }
850
851    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
852        &mut self.change_notifier
853    }
854}
855
856impl ViewportOffset for ScrollPositionWithSingleContext {
857    crate::scroll_position_with_single_context_viewport_offset_overrides!();
858}
859
860impl ScrollPosition for ScrollPositionWithSingleContext {
861    crate::scroll_position_with_single_context_overrides!();
862}
863
864impl ScrollActivityDelegate for ScrollPositionWithSingleContext {
865    crate::scroll_position_with_single_context_delegate_overrides!();
866}
867
868impl ScrollPositionWithSingleContextLeaf for ScrollPositionWithSingleContext {
869    crate::scroll_position_with_single_context_accessors!();
870}
871
872#[cfg(test)]
873mod tests {
874    use std::cell::Cell;
875    use waft_foundation::AppCell;
876
877    use waft_animation::Curves;
878    use waft_embedder::Offset;
879    use waft_foundation::ListenableObject;
880    use waft_gestures::{DragEndDetails, DragUpdateDetails, Velocity};
881    use waft_scheduler::SchedulerBinding;
882
883    use super::*;
884    use crate::test_harness::pump_every_view;
885    use crate::test_harness::{ScrollHarness, mount_scroll_harness};
886    use crate::widgets::scroll_physics::{BouncingScrollPhysics, ClampingScrollPhysics};
887
888    fn position(
889        app: &mut App,
890        harness: &ScrollHarness,
891        physics: ScrollPhysicsRef,
892    ) -> Ref<ScrollPositionWithSingleContext> {
893        ScrollPositionWithSingleContext::new(
894            app,
895            physics,
896            Rc::clone(&harness.scroll_context),
897            Some(0.0),
898            true,
899            None,
900            None,
901        )
902    }
903
904    /// The viewport reporting a 100 pixel window over 400 pixels of scrollable content.
905    fn lay_out(app: &mut App, position: Handle<ScrollPositionWithSingleContext>) {
906        assert!(position.apply_viewport_dimension(app, 100.0));
907        assert!(position.apply_content_dimensions(app, 0.0, 400.0));
908        app.drain_microtasks();
909    }
910
911    fn drag_by(delta: f64) -> DragUpdateDetails {
912        DragUpdateDetails::new(
913            Offset::ZERO,
914            None,
915            Some(Duration::ZERO),
916            Offset::new(0.0, delta),
917            Some(delta),
918            None,
919        )
920    }
921
922    fn is_scrolling(app: &App, position: Handle<ScrollPositionWithSingleContext>) -> bool {
923        *app.get(position.is_scrolling_notifier(app)).value()
924    }
925
926    #[test]
927    fn applying_dimensions_makes_the_metrics_available_and_move_to_clamps() {
928        let cell = AppCell::new();
929        let mut app = cell.borrow_mut();
930        let harness = mount_scroll_harness(&mut app);
931        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
932        let position = kept.handle();
933        assert!(!position.have_dimensions(&app));
934        assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
935
936        lay_out(&mut app, position);
937
938        assert!(position.have_dimensions(&app));
939        assert_eq!(position.min_scroll_extent(&app), 0.0);
940        assert_eq!(position.max_scroll_extent(&app), 400.0);
941        assert_eq!(position.viewport_dimension(&app), 100.0);
942        assert_eq!(position.extent_inside(&app), 100.0);
943        assert_eq!(position.extent_after(&app), 400.0);
944        assert_eq!(app.get(&harness.context).can_drag, vec![true]);
945
946        position.move_to(&mut app, 500.0, None, None, None);
947        assert_eq!(ViewportOffset::pixels(position, &app), 400.0);
948        position.move_to(&mut app, -50.0, None, None, None);
949        assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
950        assert!(!position.out_of_range(&app));
951    }
952
953    #[test]
954    fn jump_to_notifies_listeners_and_dispatches_start_update_end() {
955        let cell = AppCell::new();
956        let mut app = cell.borrow_mut();
957        let harness = mount_scroll_harness(&mut app);
958        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
959        let position = kept.handle();
960        lay_out(&mut app, position);
961        harness.notifications.borrow_mut().clear();
962
963        let notified = Rc::new(Cell::new(0));
964        let counter = notified.clone();
965        ListenableObject::add_listener(
966            position,
967            &mut app,
968            Listener::new(move |_app| counter.set(counter.get() + 1)),
969        );
970
971        ViewportOffset::jump_to(position, &mut app, 120.0);
972
973        assert_eq!(ViewportOffset::pixels(position, &app), 120.0);
974        assert_eq!(notified.get(), 1);
975        assert_eq!(
976            *harness.notifications.borrow(),
977            ["start", "update 120.0", "end"]
978        );
979        assert_eq!(app.get(&harness.context).saved_offsets, vec![120.0]);
980        assert!(!is_scrolling(&app, position));
981    }
982
983    #[test]
984    fn animate_to_drives_the_position_through_the_ticker() {
985        let cell = AppCell::new();
986        let mut app = cell.borrow_mut();
987        let harness = mount_scroll_harness(&mut app);
988        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
989        let position = kept.handle();
990        lay_out(&mut app, position);
991
992        ViewportOffset::animate_to(
993            position,
994            &mut app,
995            200.0,
996            Duration::from_millis(100),
997            Curves::linear(),
998        );
999        assert!(is_scrolling(&app, position));
1000
1001        pump_every_view(&mut app, Duration::ZERO);
1002        assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
1003
1004        pump_every_view(&mut app, Duration::from_millis(50));
1005        assert!((ViewportOffset::pixels(position, &app) - 100.0).abs() < 0.001);
1006
1007        pump_every_view(&mut app, Duration::from_millis(100));
1008        assert_eq!(ViewportOffset::pixels(position, &app), 200.0);
1009    }
1010
1011    /// `animate_to`'s future resolves when the activity ends, which happens on the microtask
1012    /// queue after the frame that finishes the animation; its listeners never run inline.
1013    #[test]
1014    fn animate_to_resolves_its_future_when_the_activity_ends() {
1015        let cell = AppCell::new();
1016        let mut app = cell.borrow_mut();
1017        let harness = mount_scroll_harness(&mut app);
1018        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1019        let position = kept.handle();
1020        lay_out(&mut app, position);
1021
1022        let done = ViewportOffset::animate_to(
1023            position,
1024            &mut app,
1025            200.0,
1026            Duration::from_millis(100),
1027            Curves::linear(),
1028        );
1029        assert!(!done.is_completed());
1030        let heard = Rc::new(Cell::new(false));
1031        let flag = Rc::clone(&heard);
1032        done.clone().then(&mut app, move |_app, ()| flag.set(true));
1033
1034        pump_every_view(&mut app, Duration::ZERO);
1035        pump_every_view(&mut app, Duration::from_millis(50));
1036        assert!(!done.is_completed(), "still animating");
1037        pump_every_view(&mut app, Duration::from_millis(100));
1038        assert_eq!(ViewportOffset::pixels(position, &app), 200.0);
1039        assert!(
1040            !done.is_completed(),
1041            "at the target, but the simulation ends after it"
1042        );
1043
1044        // The frame past the duration stops the ticker, whose completion queues the end.
1045        SchedulerBinding::handle_begin_frame(&mut app, &[], Some(Duration::from_millis(150)));
1046        assert!(
1047            !done.is_completed(),
1048            "the activity ends on the microtask queue, after the frame"
1049        );
1050        app.drain_microtasks();
1051        assert!(done.is_completed());
1052        assert!(heard.get(), "the listener ran in the same drain");
1053        assert!(!is_scrolling(&app, position));
1054    }
1055
1056    /// A task awaiting `animate_to` resumes at the checkpoint after the activity ends.
1057    #[test]
1058    fn a_task_awaiting_animate_to_resumes_at_the_checkpoint() {
1059        let cell = AppCell::new();
1060        let mut app = cell.borrow_mut();
1061        let harness = mount_scroll_harness(&mut app);
1062        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1063        let position = kept.handle();
1064        lay_out(&mut app, position);
1065
1066        let done = ViewportOffset::animate_to(
1067            position,
1068            &mut app,
1069            200.0,
1070            Duration::from_millis(100),
1071            Curves::linear(),
1072        );
1073        let resumed = Rc::new(Cell::new(false));
1074        let flag = Rc::clone(&resumed);
1075        app.spawn(async move |_cx| {
1076            done.await;
1077            flag.set(true);
1078        });
1079        pump_every_view(&mut app, Duration::ZERO);
1080        drop(app);
1081        cell.checkpoint();
1082        assert!(!resumed.get(), "pending: the animation is still running");
1083
1084        pump_every_view(&mut cell.borrow_mut(), Duration::from_millis(100));
1085        pump_every_view(&mut cell.borrow_mut(), Duration::from_millis(150));
1086        assert!(!resumed.get(), "a task resumes only at the checkpoint");
1087        cell.checkpoint();
1088        assert!(resumed.get());
1089    }
1090
1091    /// An animation another activity interrupts resolves `animate_to`'s future too, as Dart's
1092    /// does when the user grabs the view.
1093    #[test]
1094    fn an_interrupted_animation_resolves_animate_to_as_well() {
1095        let cell = AppCell::new();
1096        let mut app = cell.borrow_mut();
1097        let harness = mount_scroll_harness(&mut app);
1098        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1099        let position = kept.handle();
1100        lay_out(&mut app, position);
1101
1102        let done = ViewportOffset::animate_to(
1103            position,
1104            &mut app,
1105            200.0,
1106            Duration::from_millis(100),
1107            Curves::linear(),
1108        );
1109        pump_every_view(&mut app, Duration::ZERO);
1110        pump_every_view(&mut app, Duration::from_millis(50));
1111        assert!(!done.is_completed());
1112
1113        ViewportOffset::jump_to(position, &mut app, 0.0);
1114        assert!(done.is_completed(), "the driven activity was disposed");
1115        assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
1116        pump_every_view(&mut app, Duration::from_millis(100));
1117        assert_eq!(
1118            ViewportOffset::pixels(position, &app),
1119            0.0,
1120            "the animation is gone"
1121        );
1122    }
1123
1124    #[test]
1125    fn animate_to_within_the_tolerance_jumps_instead() {
1126        let cell = AppCell::new();
1127        let mut app = cell.borrow_mut();
1128        let harness = mount_scroll_harness(&mut app);
1129        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1130        let position = kept.handle();
1131        lay_out(&mut app, position);
1132        harness.notifications.borrow_mut().clear();
1133
1134        let done = ViewportOffset::animate_to(
1135            position,
1136            &mut app,
1137            0.000_001,
1138            Duration::from_millis(100),
1139            Curves::linear(),
1140        );
1141
1142        assert_eq!(ViewportOffset::pixels(position, &app), 0.000_001);
1143        assert!(!is_scrolling(&app, position));
1144        assert!(done.is_completed(), "a jump hands back a resolved future");
1145    }
1146
1147    #[test]
1148    fn a_clamping_drag_scrolls_the_position_and_settles_at_once() {
1149        let cell = AppCell::new();
1150        let mut app = cell.borrow_mut();
1151        let harness = mount_scroll_harness(&mut app);
1152        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1153        let position = kept.handle();
1154        lay_out(&mut app, position);
1155        harness.notifications.borrow_mut().clear();
1156
1157        let _hold = ScrollPosition::hold(position, &mut app, Listener::new(|_app| {}));
1158        let drag = ScrollPosition::drag(
1159            position,
1160            &mut app,
1161            DragStartDetails::default(),
1162            Listener::new(|_app| {}),
1163        );
1164
1165        drag.update(&mut app, drag_by(-30.0));
1166        assert_eq!(ViewportOffset::pixels(position, &app), 30.0);
1167        assert_eq!(
1168            ViewportOffset::user_scroll_direction(position, &app),
1169            ScrollDirection::Reverse
1170        );
1171        assert!(is_scrolling(&app, position));
1172
1173        drag.end(
1174            &mut app,
1175            DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
1176        );
1177
1178        // In range with no velocity, the physics offers no simulation, so the position idles.
1179        assert_eq!(ViewportOffset::pixels(position, &app), 30.0);
1180        assert!(!is_scrolling(&app, position));
1181        assert_eq!(
1182            ViewportOffset::user_scroll_direction(position, &app),
1183            ScrollDirection::Idle
1184        );
1185        assert_eq!(
1186            *harness.notifications.borrow(),
1187            ["start", "user Reverse", "update 30.0", "end", "user Idle"]
1188        );
1189    }
1190
1191    #[test]
1192    fn a_bouncing_drag_overscrolls_and_springs_back_over_frames() {
1193        let cell = AppCell::new();
1194        let mut app = cell.borrow_mut();
1195        let harness = mount_scroll_harness(&mut app);
1196        let kept = position(&mut app, &harness, Rc::new(BouncingScrollPhysics::new()));
1197        let position = kept.handle();
1198        lay_out(&mut app, position);
1199
1200        let drag = ScrollPosition::drag(
1201            position,
1202            &mut app,
1203            DragStartDetails::default(),
1204            Listener::new(|_app| {}),
1205        );
1206        drag.update(&mut app, drag_by(-500.0));
1207        assert!(ViewportOffset::pixels(position, &app) > 400.0);
1208        assert!(position.out_of_range(&app));
1209
1210        drag.end(
1211            &mut app,
1212            DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
1213        );
1214        // The ballistic activity has not ticked yet.
1215        assert!(position.out_of_range(&app));
1216        assert!(is_scrolling(&app, position));
1217
1218        for frame in 0..200 {
1219            pump_every_view(&mut app, Duration::from_millis(16 * frame));
1220            if !is_scrolling(&app, position) {
1221                break;
1222            }
1223        }
1224
1225        assert!(!is_scrolling(&app, position));
1226        assert!((ViewportOffset::pixels(position, &app) - 400.0).abs() < 1.0);
1227    }
1228
1229    #[test]
1230    fn a_new_position_absorbs_the_old_one() {
1231        let cell = AppCell::new();
1232        let mut app = cell.borrow_mut();
1233        let harness = mount_scroll_harness(&mut app);
1234        let kept_old = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1235        let old = kept_old.handle();
1236        lay_out(&mut app, old);
1237        ViewportOffset::jump_to(old, &mut app, 75.0);
1238
1239        let kept_new = ScrollPositionWithSingleContext::new(
1240            &mut app,
1241            Rc::new(ClampingScrollPhysics::new()),
1242            Rc::clone(&harness.scroll_context),
1243            Some(0.0),
1244            true,
1245            Some(old.as_scroll_position()),
1246            None,
1247        );
1248        let new = kept_new.handle();
1249
1250        assert_eq!(ViewportOffset::pixels(new, &app), 75.0);
1251        assert_eq!(new.max_scroll_extent(&app), 400.0);
1252        assert!(new.activity(&app).is_some());
1253        assert!(old.activity(&app).is_none());
1254    }
1255
1256    #[test]
1257    fn a_pointer_scroll_moves_the_position_within_the_extents() {
1258        let cell = AppCell::new();
1259        let mut app = cell.borrow_mut();
1260        let harness = mount_scroll_harness(&mut app);
1261        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1262        let position = kept.handle();
1263        lay_out(&mut app, position);
1264        harness.notifications.borrow_mut().clear();
1265
1266        ScrollPosition::pointer_scroll(position, &mut app, 60.0);
1267        assert_eq!(ViewportOffset::pixels(position, &app), 60.0);
1268        assert_eq!(
1269            *harness.notifications.borrow(),
1270            ["user Reverse", "start", "update 60.0", "end", "user Idle"]
1271        );
1272
1273        // Past the maximum extent it stops at the edge.
1274        ScrollPosition::pointer_scroll(position, &mut app, 1000.0);
1275        assert_eq!(ViewportOffset::pixels(position, &app), 400.0);
1276    }
1277
1278    #[test]
1279    fn the_description_names_the_context_the_physics_and_the_activity() {
1280        let cell = AppCell::new();
1281        let mut app = cell.borrow_mut();
1282        let harness = mount_scroll_harness(&mut app);
1283        let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
1284        let position = kept.handle();
1285        lay_out(&mut app, position);
1286
1287        let description = position.to_string(&app);
1288        assert!(description.contains("offset: 0.0"), "{description}");
1289        assert!(description.contains("range: 0.0..400.0"), "{description}");
1290        assert!(description.contains("viewport: 100.0"), "{description}");
1291        assert!(description.contains("TestScrollContext"), "{description}");
1292        assert!(
1293            description.contains("ClampingScrollPhysics"),
1294            "{description}"
1295        );
1296        assert!(description.contains("IdleScrollActivity"), "{description}");
1297    }
1298}