Skip to main content

waft_widgets/widgets/
scroll_configuration.rs

1//! Flutter counterpart: `widgets/scroll_configuration.dart`.
2
3use std::any::{Any, TypeId};
4use std::collections::HashSet;
5use std::fmt::{self, Debug};
6use std::ops::Deref;
7use std::rc::Rc;
8
9use waft_embedder::{Color, PointerDeviceKind, TargetPlatform};
10use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty};
11use waft_gestures::{
12    GestureVelocityTrackerBuilder, IOSScrollViewFlingVelocityTracker,
13    MacOSScrollViewFlingVelocityTracker, MultitouchDragStrategy, VelocityTracker,
14};
15use waft_services::LogicalKeyboardKey;
16
17use crate::framework::{BuildContext, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
18use crate::widgets::overscroll_indicator::GlowingOverscrollIndicator;
19use crate::widgets::scroll_physics::{
20    BouncingScrollPhysics, ClampingScrollPhysics, RangeMaintainingScrollPhysics,
21    ScrollDecelerationRate, ScrollPhysicsRef,
22};
23use crate::widgets::scroll_view::ScrollViewKeyboardDismissBehavior;
24use crate::widgets::scrollable_helpers::ScrollableDetails;
25use crate::widgets::scrollbar::RawScrollbar;
26
27const K_DEFAULT_GLOW_COLOR: Color = Color::new(0xFFFFFFFF);
28
29/// Device types that scrollables should accept drag gestures from by default.
30///
31/// Dart's `_kTouchLikeDeviceTypes`, a function because a `HashSet` has no `const`
32/// constructor.
33fn k_touch_like_device_types() -> HashSet<PointerDeviceKind> {
34    HashSet::from([
35        PointerDeviceKind::Touch,
36        PointerDeviceKind::Stylus,
37        PointerDeviceKind::InvertedStylus,
38        PointerDeviceKind::Trackpad,
39        // The VoiceAccess sends pointer events with unknown type when scrolling
40        // scrollables.
41        PointerDeviceKind::Unknown,
42    ])
43}
44
45/// Types of overscroll indicators supported by [`TargetPlatform::Android`].
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47pub enum AndroidOverscrollIndicator {
48    /// Utilizes a `StretchingOverscrollIndicator`, which transforms the contents
49    /// of a `ScrollView` when overscrolled.
50    Stretch,
51
52    /// Utilizes a `GlowingOverscrollIndicator`, painting a glowing semi circle on
53    /// top of the `ScrollView` in response to overscrolling.
54    Glow,
55}
56
57/// Describes how `Scrollable` widgets should behave.
58///
59/// Used by [`ScrollConfiguration`] to configure the `Scrollable` widgets in a
60/// subtree.
61///
62/// This trait can be implemented to further customize a [`ScrollBehavior`] for a
63/// subtree. For example, overriding [`get_scroll_physics`](Self::get_scroll_physics) sets the
64/// default [`ScrollPhysics`](crate::ScrollPhysics) for `Scrollable`s that inherit this [`ScrollConfiguration`].
65///
66/// When looking to easily toggle the default decorations, use
67/// [`ScrollBehaviorRef::copy_with`] instead of writing a new [`ScrollBehavior`].
68/// The `scrollbars` and `overscroll` flags can turn these decorations off.
69///
70/// See also:
71///
72///   * [`ScrollConfiguration`], the inherited widget that controls how
73///     `Scrollable` widgets behave in a subtree.
74pub trait ScrollBehavior: Debug + 'static {
75    /// The value behind the erased behavior, for Dart's `behavior.runtimeType` and the
76    /// covariant `oldDelegate` a [`should_notify`](Self::should_notify) override casts.
77    fn as_any(&self) -> &dyn Any;
78
79    /// The platform whose scroll physics should be implemented.
80    ///
81    /// Defaults to the current platform.
82    fn get_platform(&self, app: &mut App, context: BuildContext) -> TargetPlatform {
83        ScrollBehaviorBase::get_platform(app, context)
84    }
85
86    /// The device kinds that the scrollable will accept drag gestures from.
87    ///
88    /// By default only [`PointerDeviceKind::Touch`], [`PointerDeviceKind::Stylus`],
89    /// [`PointerDeviceKind::InvertedStylus`], and [`PointerDeviceKind::Trackpad`]
90    /// are configured to create drag gestures. Enabling this for
91    /// [`PointerDeviceKind::Mouse`] will make it difficult or impossible to select
92    /// text in scrollable containers and is not recommended.
93    fn drag_devices(&self) -> HashSet<PointerDeviceKind> {
94        ScrollBehaviorBase::drag_devices()
95    }
96
97    /// The multi-finger drag strategy on multi-touch devices.
98    ///
99    /// By default, [`MultitouchDragStrategy::LatestPointer`] is configured to
100    /// create drag gestures for non-Apple platforms, and
101    /// [`MultitouchDragStrategy::AverageBoundaryPointers`] for Apple platforms.
102    fn get_multitouch_drag_strategy(
103        &self,
104        app: &mut App,
105        context: BuildContext,
106    ) -> MultitouchDragStrategy {
107        ScrollBehaviorBase::get_multitouch_drag_strategy(self, app, context)
108    }
109
110    /// A set of [`LogicalKeyboardKey`]s that, when any or all are pressed in
111    /// combination with a [`PointerDeviceKind::Mouse`] pointer scroll event, will
112    /// flip the axes of the scroll input.
113    ///
114    /// This will for example, result in the input of a vertical mouse wheel, to
115    /// move the `ScrollPosition` of a `ScrollView` with an
116    /// [`waft_painting::Axis::Horizontal`] scroll direction.
117    ///
118    /// If other keys exclusive of this set are pressed during a scroll event, in
119    /// conjunction with keys from this set, the scroll input will still be
120    /// flipped.
121    ///
122    /// Defaults to [`LogicalKeyboardKey::SHIFT_LEFT`] and
123    /// [`LogicalKeyboardKey::SHIFT_RIGHT`].
124    fn pointer_axis_modifiers(&self) -> HashSet<LogicalKeyboardKey> {
125        ScrollBehaviorBase::pointer_axis_modifiers()
126    }
127
128    /// Applies a [`RawScrollbar`] to the child widget on desktop platforms.
129    fn build_scrollbar(
130        &self,
131        app: &mut App,
132        context: BuildContext,
133        child: WidgetRef,
134        details: &ScrollableDetails,
135    ) -> WidgetRef {
136        ScrollBehaviorBase::build_scrollbar(self, app, context, child, details)
137    }
138
139    /// Applies a [`GlowingOverscrollIndicator`] to the child widget on
140    /// [`TargetPlatform::Android`] and [`TargetPlatform::Fuchsia`].
141    fn build_overscroll_indicator(
142        &self,
143        app: &mut App,
144        context: BuildContext,
145        child: WidgetRef,
146        details: &ScrollableDetails,
147    ) -> WidgetRef {
148        ScrollBehaviorBase::build_overscroll_indicator(self, app, context, child, details)
149    }
150
151    /// Specifies the type of velocity tracker to use in the descendant
152    /// `Scrollable`s' drag gesture recognizers, for estimating the velocity of a
153    /// drag gesture.
154    ///
155    /// This can be used to, for example, apply different fling velocity
156    /// estimation methods on different platforms, in order to match the
157    /// platform's native behavior.
158    ///
159    /// The default implementation provides a new
160    /// [`IOSScrollViewFlingVelocityTracker`] on iOS and macOS for each new pointer,
161    /// and a new [`VelocityTracker`] on other platforms for each new pointer.
162    fn velocity_tracker_builder(
163        &self,
164        app: &mut App,
165        context: BuildContext,
166    ) -> GestureVelocityTrackerBuilder {
167        ScrollBehaviorBase::velocity_tracker_builder(self, app, context)
168    }
169
170    /// The scroll physics to use for the platform given by
171    /// [`get_platform`](Self::get_platform).
172    ///
173    /// Defaults to [`RangeMaintainingScrollPhysics`] mixed with
174    /// [`BouncingScrollPhysics`] on iOS and [`ClampingScrollPhysics`] on
175    /// Android.
176    fn get_scroll_physics(&self, app: &mut App, context: BuildContext) -> ScrollPhysicsRef {
177        ScrollBehaviorBase::get_scroll_physics(self, app, context)
178    }
179
180    /// Called whenever a [`ScrollConfiguration`] is rebuilt with a new
181    /// [`ScrollBehavior`] of the same runtime type.
182    ///
183    /// If the new instance represents different information than the old
184    /// instance, then the method should return true, otherwise it should return
185    /// false.
186    ///
187    /// If this method returns true, all the widgets that inherit from the
188    /// [`ScrollConfiguration`] will rebuild using the new [`ScrollBehavior`]. If this
189    /// method returns false, the rebuilds might be optimized away.
190    fn should_notify(&self, old_delegate: &dyn ScrollBehavior) -> bool {
191        let _ = old_delegate;
192        false
193    }
194
195    /// The default keyboard dismissal behavior for `ScrollView` widgets.
196    ///
197    /// Defaults to [`ScrollViewKeyboardDismissBehavior::Manual`].
198    fn get_keyboard_dismiss_behavior(
199        &self,
200        app: &mut App,
201        context: BuildContext,
202    ) -> ScrollViewKeyboardDismissBehavior {
203        let _ = (app, context);
204        ScrollViewKeyboardDismissBehavior::Manual
205    }
206}
207
208/// The shared bodies of Dart's `ScrollBehavior`: call one where Dart writes `super.…`.
209pub struct ScrollBehaviorBase;
210
211impl ScrollBehaviorBase {
212    /// See [`ScrollBehavior::get_platform`].
213    pub fn get_platform(app: &mut App, context: BuildContext) -> TargetPlatform {
214        let _ = context;
215        app.platform().target_platform()
216    }
217
218    /// See [`ScrollBehavior::drag_devices`].
219    pub fn drag_devices() -> HashSet<PointerDeviceKind> {
220        k_touch_like_device_types()
221    }
222
223    /// See [`ScrollBehavior::get_multitouch_drag_strategy`].
224    pub fn get_multitouch_drag_strategy<B: ScrollBehavior + ?Sized>(
225        behavior: &B,
226        app: &mut App,
227        context: BuildContext,
228    ) -> MultitouchDragStrategy {
229        match behavior.get_platform(app, context) {
230            TargetPlatform::MacOS | TargetPlatform::IOS => {
231                MultitouchDragStrategy::AverageBoundaryPointers
232            }
233            TargetPlatform::Linux
234            | TargetPlatform::Windows
235            | TargetPlatform::Android
236            | TargetPlatform::Fuchsia => MultitouchDragStrategy::LatestPointer,
237        }
238    }
239
240    /// See [`ScrollBehavior::pointer_axis_modifiers`].
241    pub fn pointer_axis_modifiers() -> HashSet<LogicalKeyboardKey> {
242        HashSet::from([
243            LogicalKeyboardKey::SHIFT_LEFT,
244            LogicalKeyboardKey::SHIFT_RIGHT,
245        ])
246    }
247
248    /// See [`ScrollBehavior::build_scrollbar`].
249    pub fn build_scrollbar<B: ScrollBehavior + ?Sized>(
250        behavior: &B,
251        app: &mut App,
252        context: BuildContext,
253        child: WidgetRef,
254        details: &ScrollableDetails,
255    ) -> WidgetRef {
256        // When modifying this function, consider modifying the implementation in the
257        // Cupertino subclass as well.
258        match behavior.get_platform(app, context) {
259            TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
260                debug_assert!(details.controller.is_some());
261                let mut scrollbar = RawScrollbar::new(child);
262                if let Some(controller) = details.controller.clone() {
263                    scrollbar = scrollbar.controller(controller);
264                }
265                scrollbar.into_widget()
266            }
267            TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => child,
268        }
269    }
270
271    /// See [`ScrollBehavior::build_overscroll_indicator`].
272    pub fn build_overscroll_indicator<B: ScrollBehavior + ?Sized>(
273        behavior: &B,
274        app: &mut App,
275        context: BuildContext,
276        child: WidgetRef,
277        details: &ScrollableDetails,
278    ) -> WidgetRef {
279        // When modifying this function, consider modifying the implementation in the
280        // Material and Cupertino subclasses as well.
281        match behavior.get_platform(app, context) {
282            TargetPlatform::IOS
283            | TargetPlatform::Linux
284            | TargetPlatform::MacOS
285            | TargetPlatform::Windows => child,
286            TargetPlatform::Android | TargetPlatform::Fuchsia => {
287                GlowingOverscrollIndicator::new(details.direction, K_DEFAULT_GLOW_COLOR)
288                    .child(child)
289                    .into_widget()
290            }
291        }
292    }
293
294    /// See [`ScrollBehavior::velocity_tracker_builder`].
295    pub fn velocity_tracker_builder<B: ScrollBehavior + ?Sized>(
296        behavior: &B,
297        app: &mut App,
298        context: BuildContext,
299    ) -> GestureVelocityTrackerBuilder {
300        match behavior.get_platform(app, context) {
301            TargetPlatform::IOS => {
302                Rc::new(|event| Box::new(IOSScrollViewFlingVelocityTracker::new(event.kind())))
303            }
304            TargetPlatform::MacOS => {
305                Rc::new(|event| Box::new(MacOSScrollViewFlingVelocityTracker::new(event.kind())))
306            }
307            TargetPlatform::Android
308            | TargetPlatform::Fuchsia
309            | TargetPlatform::Linux
310            | TargetPlatform::Windows => {
311                Rc::new(|event| Box::new(VelocityTracker::with_kind(event.kind())))
312            }
313        }
314    }
315
316    /// Dart's `ScrollBehavior._bouncingPhysics`.
317    fn bouncing_physics() -> ScrollPhysicsRef {
318        Rc::new(
319            BouncingScrollPhysics::new().with_parent(Rc::new(RangeMaintainingScrollPhysics::new())),
320        )
321    }
322
323    /// Dart's `ScrollBehavior._bouncingDesktopPhysics`.
324    fn bouncing_desktop_physics() -> ScrollPhysicsRef {
325        Rc::new(
326            BouncingScrollPhysics::new()
327                .with_deceleration_rate(ScrollDecelerationRate::Fast)
328                .with_parent(Rc::new(RangeMaintainingScrollPhysics::new())),
329        )
330    }
331
332    /// Dart's `ScrollBehavior._clampingPhysics`.
333    fn clamping_physics() -> ScrollPhysicsRef {
334        Rc::new(
335            ClampingScrollPhysics::new().with_parent(Rc::new(RangeMaintainingScrollPhysics::new())),
336        )
337    }
338
339    /// See [`ScrollBehavior::get_scroll_physics`].
340    pub fn get_scroll_physics<B: ScrollBehavior + ?Sized>(
341        behavior: &B,
342        app: &mut App,
343        context: BuildContext,
344    ) -> ScrollPhysicsRef {
345        match behavior.get_platform(app, context) {
346            TargetPlatform::IOS => ScrollBehaviorBase::bouncing_physics(),
347            TargetPlatform::MacOS => ScrollBehaviorBase::bouncing_desktop_physics(),
348            TargetPlatform::Android
349            | TargetPlatform::Fuchsia
350            | TargetPlatform::Linux
351            | TargetPlatform::Windows => ScrollBehaviorBase::clamping_physics(),
352        }
353    }
354}
355
356/// Dart's instantiable `const ScrollBehavior()`.
357#[derive(Clone, Copy, Default, PartialEq, Eq)]
358pub struct PlainScrollBehavior;
359
360impl PlainScrollBehavior {
361    /// Creates a description of how `Scrollable` widgets should behave.
362    pub const fn new() -> PlainScrollBehavior {
363        PlainScrollBehavior
364    }
365}
366
367impl ScrollBehavior for PlainScrollBehavior {
368    fn as_any(&self) -> &dyn Any {
369        self
370    }
371}
372
373impl Debug for PlainScrollBehavior {
374    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375        // Dart's `objectRuntimeType(this, 'ScrollBehavior')`.
376        f.write_str("ScrollBehavior")
377    }
378}
379
380/// A [`ScrollBehavior`] held by value: what a Dart field or parameter typed `ScrollBehavior`
381/// becomes.
382///
383/// It is a newtype rather than a bare `Rc` so that [`copy_with`](Self::copy_with) — which
384/// Dart writes as a method capturing `this` as the new wrapper's delegate — has an `Rc` to
385/// capture.
386#[derive(Clone)]
387pub struct ScrollBehaviorRef(Rc<dyn ScrollBehavior>);
388
389impl ScrollBehaviorRef {
390    /// Erases a [`ScrollBehavior`].
391    pub fn new(behavior: impl ScrollBehavior) -> ScrollBehaviorRef {
392        ScrollBehaviorRef(Rc::new(behavior))
393    }
394
395    /// Dart's `const ScrollBehavior()`.
396    pub fn plain() -> ScrollBehaviorRef {
397        ScrollBehaviorRef::new(PlainScrollBehavior::new())
398    }
399
400    /// Creates a copy of this behavior, making it possible to
401    /// easily toggle `scrollbars` and `overscroll` effects.
402    ///
403    /// This is used by widgets like `PageView` and `ListWheelScrollView` to
404    /// override the current [`ScrollBehavior`] and manage how they are decorated.
405    ///
406    /// The result is a [`WrappedScrollBehavior`], whose fluent setters are Dart's named
407    /// arguments; copying a wrapper flattens it, as Dart's
408    /// `_WrappedScrollBehavior.copyWith` does.
409    pub fn copy_with(&self) -> WrappedScrollBehavior {
410        match self.0.as_any().downcast_ref::<WrappedScrollBehavior>() {
411            Some(wrapped) => WrappedScrollBehavior {
412                delegate: wrapped.delegate.clone(),
413                scrollbars: wrapped.scrollbars,
414                overscroll: wrapped.overscroll,
415                drag_devices: Some(ScrollBehavior::drag_devices(wrapped)),
416                multitouch_drag_strategy: wrapped.multitouch_drag_strategy,
417                pointer_axis_modifiers: Some(ScrollBehavior::pointer_axis_modifiers(wrapped)),
418                physics: wrapped.physics.clone(),
419                platform: wrapped.platform,
420                keyboard_dismiss_behavior: wrapped.keyboard_dismiss_behavior,
421            },
422            None => WrappedScrollBehavior::new(self.clone()),
423        }
424    }
425
426    /// Dart's `behavior.runtimeType`.
427    pub fn type_id(&self) -> TypeId {
428        self.0.as_any().type_id()
429    }
430}
431
432impl Deref for ScrollBehaviorRef {
433    type Target = dyn ScrollBehavior;
434
435    fn deref(&self) -> &dyn ScrollBehavior {
436        &*self.0
437    }
438}
439
440impl PartialEq for ScrollBehaviorRef {
441    fn eq(&self, other: &ScrollBehaviorRef) -> bool {
442        // Dart's `==` on a `ScrollBehavior` is object identity.
443        Rc::ptr_eq(&self.0, &other.0)
444    }
445}
446
447impl Debug for ScrollBehaviorRef {
448    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449        Debug::fmt(&*self.0, f)
450    }
451}
452
453/// The [`ScrollBehavior`] that [`ScrollBehaviorRef::copy_with`] returns; Dart's
454/// `_WrappedScrollBehavior`.
455#[derive(Clone)]
456pub struct WrappedScrollBehavior {
457    delegate: ScrollBehaviorRef,
458    scrollbars: bool,
459    overscroll: bool,
460    drag_devices: Option<HashSet<PointerDeviceKind>>,
461    multitouch_drag_strategy: Option<MultitouchDragStrategy>,
462    pointer_axis_modifiers: Option<HashSet<LogicalKeyboardKey>>,
463    physics: Option<ScrollPhysicsRef>,
464    platform: Option<TargetPlatform>,
465    keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,
466}
467
468impl WrappedScrollBehavior {
469    /// Wraps `delegate` with Dart's `copyWith` defaults: both decorations on and every other
470    /// override unset.
471    pub fn new(delegate: ScrollBehaviorRef) -> WrappedScrollBehavior {
472        WrappedScrollBehavior {
473            delegate,
474            scrollbars: true,
475            overscroll: true,
476            drag_devices: None,
477            multitouch_drag_strategy: None,
478            pointer_axis_modifiers: None,
479            physics: None,
480            platform: None,
481            keyboard_dismiss_behavior: None,
482        }
483    }
484
485    /// Dart `copyWith(scrollbars:)`.
486    pub fn scrollbars(mut self, scrollbars: bool) -> WrappedScrollBehavior {
487        self.scrollbars = scrollbars;
488        self
489    }
490
491    /// Dart `copyWith(overscroll:)`.
492    pub fn overscroll(mut self, overscroll: bool) -> WrappedScrollBehavior {
493        self.overscroll = overscroll;
494        self
495    }
496
497    /// Dart `copyWith(dragDevices:)`.
498    pub fn drag_devices(
499        mut self,
500        drag_devices: HashSet<PointerDeviceKind>,
501    ) -> WrappedScrollBehavior {
502        self.drag_devices = Some(drag_devices);
503        self
504    }
505
506    /// Dart `copyWith(multitouchDragStrategy:)`.
507    pub fn multitouch_drag_strategy(
508        mut self,
509        multitouch_drag_strategy: MultitouchDragStrategy,
510    ) -> WrappedScrollBehavior {
511        self.multitouch_drag_strategy = Some(multitouch_drag_strategy);
512        self
513    }
514
515    /// Dart `copyWith(pointerAxisModifiers:)`.
516    pub fn pointer_axis_modifiers(
517        mut self,
518        pointer_axis_modifiers: HashSet<LogicalKeyboardKey>,
519    ) -> WrappedScrollBehavior {
520        self.pointer_axis_modifiers = Some(pointer_axis_modifiers);
521        self
522    }
523
524    /// Dart `copyWith(physics:)`.
525    pub fn physics(mut self, physics: ScrollPhysicsRef) -> WrappedScrollBehavior {
526        self.physics = Some(physics);
527        self
528    }
529
530    /// Dart `copyWith(platform:)`.
531    pub fn platform(mut self, platform: TargetPlatform) -> WrappedScrollBehavior {
532        self.platform = Some(platform);
533        self
534    }
535
536    /// Dart `copyWith(keyboardDismissBehavior:)`.
537    pub fn keyboard_dismiss_behavior(
538        mut self,
539        keyboard_dismiss_behavior: ScrollViewKeyboardDismissBehavior,
540    ) -> WrappedScrollBehavior {
541        self.keyboard_dismiss_behavior = Some(keyboard_dismiss_behavior);
542        self
543    }
544
545    /// The behavior this one decorates.
546    pub fn delegate(&self) -> &ScrollBehaviorRef {
547        &self.delegate
548    }
549}
550
551impl ScrollBehavior for WrappedScrollBehavior {
552    fn as_any(&self) -> &dyn Any {
553        self
554    }
555
556    fn get_platform(&self, app: &mut App, context: BuildContext) -> TargetPlatform {
557        self.platform
558            .unwrap_or_else(|| self.delegate.get_platform(app, context))
559    }
560
561    fn drag_devices(&self) -> HashSet<PointerDeviceKind> {
562        self.drag_devices
563            .clone()
564            .unwrap_or_else(|| self.delegate.drag_devices())
565    }
566
567    fn get_multitouch_drag_strategy(
568        &self,
569        app: &mut App,
570        context: BuildContext,
571    ) -> MultitouchDragStrategy {
572        self.multitouch_drag_strategy
573            .unwrap_or_else(|| self.delegate.get_multitouch_drag_strategy(app, context))
574    }
575
576    fn pointer_axis_modifiers(&self) -> HashSet<LogicalKeyboardKey> {
577        self.pointer_axis_modifiers
578            .clone()
579            .unwrap_or_else(|| self.delegate.pointer_axis_modifiers())
580    }
581
582    fn build_scrollbar(
583        &self,
584        app: &mut App,
585        context: BuildContext,
586        child: WidgetRef,
587        details: &ScrollableDetails,
588    ) -> WidgetRef {
589        if self.scrollbars {
590            return self.delegate.build_scrollbar(app, context, child, details);
591        }
592        child
593    }
594
595    fn build_overscroll_indicator(
596        &self,
597        app: &mut App,
598        context: BuildContext,
599        child: WidgetRef,
600        details: &ScrollableDetails,
601    ) -> WidgetRef {
602        if self.overscroll {
603            return self
604                .delegate
605                .build_overscroll_indicator(app, context, child, details);
606        }
607        child
608    }
609
610    fn velocity_tracker_builder(
611        &self,
612        app: &mut App,
613        context: BuildContext,
614    ) -> GestureVelocityTrackerBuilder {
615        self.delegate.velocity_tracker_builder(app, context)
616    }
617
618    fn get_scroll_physics(&self, app: &mut App, context: BuildContext) -> ScrollPhysicsRef {
619        self.physics
620            .clone()
621            .unwrap_or_else(|| self.delegate.get_scroll_physics(app, context))
622    }
623
624    fn get_keyboard_dismiss_behavior(
625        &self,
626        app: &mut App,
627        context: BuildContext,
628    ) -> ScrollViewKeyboardDismissBehavior {
629        self.keyboard_dismiss_behavior
630            .unwrap_or_else(|| self.delegate.get_keyboard_dismiss_behavior(app, context))
631    }
632
633    fn should_notify(&self, old_delegate: &dyn ScrollBehavior) -> bool {
634        let old = old_delegate
635            .as_any()
636            .downcast_ref::<WrappedScrollBehavior>()
637            .expect("a _WrappedScrollBehavior only compares against another one");
638        old.delegate.type_id() != self.delegate.type_id()
639            || old.scrollbars != self.scrollbars
640            || old.overscroll != self.overscroll
641            || ScrollBehavior::drag_devices(old) != ScrollBehavior::drag_devices(self)
642            || old.multitouch_drag_strategy != self.multitouch_drag_strategy
643            || ScrollBehavior::pointer_axis_modifiers(old)
644                != ScrollBehavior::pointer_axis_modifiers(self)
645            || !match (&old.physics, &self.physics) {
646                (None, None) => true,
647                (Some(old), Some(physics)) => Rc::ptr_eq(old, physics),
648                _ => false,
649            }
650            || old.platform != self.platform
651            || self.delegate.should_notify(&*old.delegate)
652    }
653}
654
655impl Debug for WrappedScrollBehavior {
656    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657        // Dart's `objectRuntimeType(this, '_WrappedScrollBehavior')`.
658        f.write_str("_WrappedScrollBehavior")
659    }
660}
661
662/// Controls how `Scrollable` widgets behave in a subtree.
663///
664/// The scroll configuration determines the [`ScrollPhysics`](crate::ScrollPhysics) and viewport
665/// decorations used by descendants of [`child`](Self::child).
666#[derive(Debug)]
667pub struct ScrollConfiguration {
668    pub key: Option<KeyRef>,
669
670    /// How `Scrollable` widgets that are descendants of [`child`](Self::child) should behave.
671    pub behavior: ScrollBehaviorRef,
672
673    /// The widget below this widget in the tree.
674    pub child: WidgetRef,
675}
676
677impl ScrollConfiguration {
678    /// Creates a widget that controls how `Scrollable` widgets behave in a subtree.
679    #[cfg_attr(debug_assertions, track_caller)]
680    pub fn new<K>(
681        behavior: ScrollBehaviorRef,
682        child: impl crate::framework::IntoWidget<K>,
683    ) -> ScrollConfiguration {
684        ScrollConfiguration {
685            key: None,
686            behavior,
687            child: child.into_widget(),
688        }
689    }
690
691    /// Dart `ScrollConfiguration(key:)`.
692    pub fn key(mut self, key: KeyRef) -> ScrollConfiguration {
693        self.key = Some(key);
694        self
695    }
696
697    /// The [`ScrollBehavior`] for `Scrollable` widgets in the given [`BuildContext`].
698    ///
699    /// If no [`ScrollConfiguration`] widget is in scope of the given `context`,
700    /// a default [`PlainScrollBehavior`] is returned.
701    pub fn of(app: &mut App, context: BuildContext) -> ScrollBehaviorRef {
702        context
703            .depend_on_inherited_widget_of_exact_type::<ScrollConfiguration>(app)
704            .map(|configuration| configuration.behavior.clone())
705            .unwrap_or_else(ScrollBehaviorRef::plain)
706    }
707}
708
709impl InheritedWidget for ScrollConfiguration {
710    fn key(&self) -> Option<&KeyRef> {
711        self.key.as_ref()
712    }
713
714    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
715        properties.add(DiagnosticsProperty::<String>::new(
716            "behavior",
717            Some(format!("{:?}", self.behavior)),
718        ));
719    }
720
721    fn child(&self) -> &WidgetRef {
722        &self.child
723    }
724
725    fn update_should_notify(&self, old_widget: &ScrollConfiguration) -> bool {
726        self.behavior.type_id() != old_widget.behavior.type_id()
727            || (self.behavior != old_widget.behavior
728                && self.behavior.should_notify(&*old_widget.behavior))
729    }
730}
731
732#[cfg(test)]
733mod tests {
734    use waft_foundation::AppCell;
735
736    use waft_test::TestPlatform;
737
738    use super::*;
739    use crate::framework::{AnyElement, Element, IntoWidget};
740    use crate::test_harness::Harness;
741    use crate::testing::{expect, find, finds_nothing, finds_one_widget, test_widgets};
742    use crate::widgets::basic::SizedBox;
743
744    fn app_on(platform: TargetPlatform) -> Rc<AppCell> {
745        AppCell::with_platform(Rc::new(TestPlatform::new().on(platform)))
746    }
747
748    fn descendant(harness: &Harness, app: &App, depth: usize) -> AnyElement {
749        let mut element = harness.root.as_element();
750        for _ in 0..=depth {
751            element = element.children(app)[0];
752        }
753        element
754    }
755
756    fn mount(app: &mut App, widget: crate::framework::WidgetRef) -> Harness {
757        let harness = Harness::mount(app, widget);
758        harness.pump(app);
759        harness
760    }
761
762    #[test]
763    fn the_default_behavior_picks_its_physics_from_the_platform() {
764        for (platform, expected) in [
765            (TargetPlatform::IOS, "BouncingScrollPhysics"),
766            (TargetPlatform::MacOS, "BouncingScrollPhysics"),
767            (TargetPlatform::Android, "ClampingScrollPhysics"),
768            (TargetPlatform::Fuchsia, "ClampingScrollPhysics"),
769            (TargetPlatform::Linux, "ClampingScrollPhysics"),
770            (TargetPlatform::Windows, "ClampingScrollPhysics"),
771        ] {
772            let cell = app_on(platform);
773            let mut app = cell.borrow_mut();
774            let harness = mount(&mut app, SizedBox::shrink().into_widget());
775            let context = descendant(&harness, &app, 0);
776
777            let behavior = ScrollConfiguration::of(&mut app, context);
778            assert_eq!(behavior.get_platform(&mut app, context), platform);
779            let physics = behavior.get_scroll_physics(&mut app, context);
780            let described = format!("{physics:?}");
781            assert!(described.contains(expected), "{platform:?}: {described}");
782            assert!(
783                described.contains("RangeMaintainingScrollPhysics"),
784                "{platform:?}: {described}"
785            );
786        }
787    }
788
789    #[test]
790    fn of_falls_back_to_a_plain_behavior_and_reads_the_ambient_one() {
791        let cell = app_on(TargetPlatform::Android);
792        let mut app = cell.borrow_mut();
793        let harness = mount(&mut app, SizedBox::shrink().into_widget());
794        let context = descendant(&harness, &app, 0);
795        assert_eq!(
796            format!("{:?}", ScrollConfiguration::of(&mut app, context)),
797            "ScrollBehavior"
798        );
799
800        let behavior = ScrollBehaviorRef::new(
801            ScrollBehaviorRef::plain()
802                .copy_with()
803                .platform(TargetPlatform::IOS),
804        );
805        let harness = mount(
806            &mut app,
807            ScrollConfiguration::new(behavior, SizedBox::shrink()).into_widget(),
808        );
809        let context = descendant(&harness, &app, 1);
810        let ambient = ScrollConfiguration::of(&mut app, context);
811        assert_eq!(ambient.get_platform(&mut app, context), TargetPlatform::IOS);
812        // As in Dart, `_WrappedScrollBehavior.getScrollPhysics` defers to the delegate, which
813        // reads its own platform; only `copyWith(physics:)` replaces the physics.
814        assert!(
815            format!("{:?}", ambient.get_scroll_physics(&mut app, context))
816                .contains("ClampingScrollPhysics")
817        );
818
819        let bouncing: ScrollPhysicsRef = Rc::new(BouncingScrollPhysics::new());
820        let overridden = ScrollBehaviorRef::new(
821            ScrollBehaviorRef::plain()
822                .copy_with()
823                .physics(bouncing.clone()),
824        );
825        assert!(Rc::ptr_eq(
826            &overridden.get_scroll_physics(&mut app, context),
827            &bouncing
828        ));
829    }
830
831    #[test]
832    fn copy_with_overrides_the_delegate_and_flattens_a_second_copy() {
833        let plain = ScrollBehaviorRef::plain();
834        let once = plain.copy_with().scrollbars(false);
835        assert!(!once.scrollbars);
836        assert!(once.overscroll);
837        assert_eq!(once.delegate(), &plain);
838
839        let twice = ScrollBehaviorRef::new(once).copy_with().overscroll(false);
840        assert!(!twice.scrollbars);
841        assert!(!twice.overscroll);
842        // The second copy keeps the original delegate rather than nesting a wrapper.
843        assert_eq!(twice.delegate().type_id(), plain.type_id());
844    }
845
846    #[test]
847    fn the_default_behavior_flips_the_axes_for_shift_and_takes_touch_like_devices() {
848        let cell = app_on(TargetPlatform::Android);
849        let mut app = cell.borrow_mut();
850        let harness = mount(&mut app, SizedBox::shrink().into_widget());
851        let context = descendant(&harness, &app, 0);
852        let behavior = ScrollConfiguration::of(&mut app, context);
853
854        assert_eq!(
855            behavior.pointer_axis_modifiers(),
856            HashSet::from([
857                LogicalKeyboardKey::SHIFT_LEFT,
858                LogicalKeyboardKey::SHIFT_RIGHT
859            ])
860        );
861        assert!(behavior.drag_devices().contains(&PointerDeviceKind::Touch));
862        assert!(!behavior.drag_devices().contains(&PointerDeviceKind::Mouse));
863        assert_eq!(
864            behavior.get_multitouch_drag_strategy(&mut app, context),
865            MultitouchDragStrategy::LatestPointer
866        );
867    }
868
869    #[test]
870    fn the_desktop_platforms_wrap_the_child_in_a_scrollbar() {
871        for platform in [
872            TargetPlatform::Linux,
873            TargetPlatform::MacOS,
874            TargetPlatform::Windows,
875        ] {
876            let cell = app_on(platform);
877            let mut app = cell.borrow_mut();
878            let harness = mount(&mut app, SizedBox::shrink().into_widget());
879            let context = descendant(&harness, &app, 0);
880            let behavior = ScrollConfiguration::of(&mut app, context);
881            let controller = crate::widgets::scroll_controller::ScrollController::default(&mut app);
882            let details = ScrollableDetails::vertical(false).controller(controller.erase());
883
884            let child = SizedBox::shrink().into_widget();
885            let scrollbar = behavior.build_scrollbar(&mut app, context, child.clone(), &details);
886            assert!(
887                crate::framework::downcast_widget::<RawScrollbar>(&*scrollbar).is_some(),
888                "{platform:?} decorates the child with a RawScrollbar"
889            );
890            let indicator =
891                behavior.build_overscroll_indicator(&mut app, context, child.clone(), &details);
892            assert!(
893                Rc::ptr_eq(&indicator, &child),
894                "{platform:?} shows no overscroll indicator"
895            );
896        }
897    }
898
899    #[test]
900    fn ios_decorates_the_child_with_neither_a_scrollbar_nor_an_indicator() {
901        let cell = app_on(TargetPlatform::IOS);
902        let mut app = cell.borrow_mut();
903        let harness = mount(&mut app, SizedBox::shrink().into_widget());
904        let context = descendant(&harness, &app, 0);
905        let behavior = ScrollConfiguration::of(&mut app, context);
906        let details = ScrollableDetails::vertical(false);
907
908        let child = SizedBox::shrink().into_widget();
909        let scrollbar = behavior.build_scrollbar(&mut app, context, child.clone(), &details);
910        assert!(Rc::ptr_eq(&scrollbar, &child));
911        let indicator =
912            behavior.build_overscroll_indicator(&mut app, context, child.clone(), &details);
913        assert!(Rc::ptr_eq(&indicator, &child));
914    }
915
916    #[test]
917    fn android_and_fuchsia_wrap_the_child_in_a_white_glow_along_the_scroll_direction() {
918        for platform in [TargetPlatform::Android, TargetPlatform::Fuchsia] {
919            let cell = app_on(platform);
920            let mut app = cell.borrow_mut();
921            let harness = mount(&mut app, SizedBox::shrink().into_widget());
922            let context = descendant(&harness, &app, 0);
923            let behavior = ScrollConfiguration::of(&mut app, context);
924            let details = ScrollableDetails::vertical(true);
925
926            let child = SizedBox::shrink().into_widget();
927            let scrollbar = behavior.build_scrollbar(&mut app, context, child.clone(), &details);
928            assert!(Rc::ptr_eq(&scrollbar, &child), "{platform:?}");
929            let indicator =
930                behavior.build_overscroll_indicator(&mut app, context, child.clone(), &details);
931            let glow = crate::framework::downcast_widget::<GlowingOverscrollIndicator>(&*indicator)
932                .unwrap_or_else(|| panic!("{platform:?} glows"));
933            assert_eq!(glow.axis_direction, waft_painting::AxisDirection::Up);
934            assert_eq!(glow.color, Color::new(0xFFFFFFFF));
935            assert!(Rc::ptr_eq(
936                glow.child.as_ref().expect("the glow wraps the child"),
937                &child
938            ));
939        }
940    }
941
942    fn list_under(behavior: ScrollBehaviorRef) -> crate::framework::WidgetRef {
943        crate::widgets::basic::Directionality::new(
944            waft_embedder::TextDirection::Ltr,
945            ScrollConfiguration::new(
946                behavior,
947                crate::widgets::scroll_view::ListView::new()
948                    .children([SizedBox::new().height(1000.0).width(1000.0).into_widget()]),
949            ),
950        )
951        .into_widget()
952    }
953
954    /// `scroll_behavior_test.dart`: "ScrollBehavior default android overscroll indicator".
955    #[test]
956    fn the_default_behavior_glows_on_android() {
957        test_widgets(|tester| {
958            tester.pump_widget(list_under(ScrollBehaviorRef::plain()));
959
960            expect(
961                tester,
962                &find::by_type::<crate::widgets::overscroll_indicator::StretchingOverscrollIndicator>(
963                ),
964                finds_nothing(),
965            );
966            expect(
967                tester,
968                &find::by_type::<GlowingOverscrollIndicator>(),
969                finds_one_widget(),
970            );
971        });
972    }
973
974    /// `scroll_behavior_test.dart`: "ScrollBehavior configuration is maintained over multiple
975    /// copies": "overscroll".
976    #[test]
977    fn a_copy_without_overscroll_keeps_the_glow_off_through_a_second_copy() {
978        test_widgets(|tester| {
979            let glows = find::by_type::<GlowingOverscrollIndicator>;
980            let default_behavior = ScrollBehaviorRef::plain();
981            tester.pump_widget(list_under(default_behavior.clone()));
982            // Default adds a glowing overscroll indicator
983            expect(tester, &glows(), finds_one_widget());
984
985            let once_copied_behavior =
986                ScrollBehaviorRef::new(default_behavior.copy_with().overscroll(false));
987            tester.pump_widget(list_under(once_copied_behavior.clone()));
988            // Copy does not add indicator
989            expect(tester, &glows(), finds_nothing());
990
991            let twice_copied_behavior = ScrollBehaviorRef::new(once_copied_behavior.copy_with());
992            tester.pump_widget(list_under(twice_copied_behavior));
993            // Second copy maintains overscroll setting
994            expect(tester, &glows(), finds_nothing());
995        });
996    }
997}