Skip to main content

waft_material/
scrollbar.rs

1//! Flutter counterpart: material_ui's `scrollbar.dart`.
2//!
3//! [`Scrollbar`] picks a `CupertinoScrollbar` on iOS and Dart's `_MaterialScrollbar`
4//! otherwise, a `RawScrollbar` subclass whose state, `_MaterialScrollbarState`, extends
5//! `RawScrollbarState` the way `CupertinoScrollbar`'s does: a [`RawScrollbarStateLeaf`]
6//! that calls the base bodies on [`RawScrollbarState`] where Dart writes `super.…`.
7
8use std::collections::HashSet;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11use std::time::Duration;
12
13use waft_animation::{Animation, AnimationBehavior, AnimationController};
14use waft_cupertino::CupertinoScrollbar;
15use waft_embedder::{Brightness, Color, Offset, Radius, TargetPlatform};
16use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
17use waft_gestures::{PointerHoverEvent, Velocity};
18use waft_painting::EdgeInsetsGeometry;
19use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
20use waft_widgets::{
21    BuildContext, Directionality, IntoWidget, KeyRef, MediaQuery, RawScrollbarData,
22    RawScrollbarLeaf, RawScrollbarState, RawScrollbarStateData, RawScrollbarStateLeaf,
23    ScrollControllerRef, ScrollNotificationPredicate, ScrollbarOrientation, State, StateData,
24    StatefulWidget, StatelessWidget, TickerProviderStateMixin, TickerProviderStateMixinData,
25    WidgetRef, WidgetState, WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
26    default_scroll_notification_predicate,
27};
28
29use crate::color_scheme::ColorScheme;
30use crate::scrollbar_theme::{ScrollbarTheme, ScrollbarThemeData};
31use crate::theme::Theme;
32
33const K_SCROLLBAR_THICKNESS: f64 = 8.0;
34const K_SCROLLBAR_THICKNESS_WITH_TRACK: f64 = 12.0;
35const K_SCROLLBAR_MARGIN: f64 = 2.0;
36const K_SCROLLBAR_MIN_LENGTH: f64 = 48.0;
37const K_SCROLLBAR_RADIUS: Radius = Radius::circular(8.0);
38const K_SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(300);
39const K_SCROLLBAR_TIME_TO_FADE: Duration = Duration::from_millis(600);
40
41/// A Material Design scrollbar.
42///
43/// To add a scrollbar to a `ScrollView`, wrap the scroll view
44/// widget in a [`Scrollbar`] widget.
45///
46/// For more information, see `RawScrollbar`.
47///
48/// Dynamically changes to a [`CupertinoScrollbar`], an iOS style scrollbar, by
49/// default on the iOS platform.
50///
51/// The color of the Scrollbar thumb will change when [`WidgetState::Dragged`],
52/// or [`WidgetState::Hovered`] on desktop and web platforms. These stateful
53/// color choices can be changed using [`ScrollbarThemeData::thumb_color`].
54///
55/// When [`thumb_visibility`](Self::thumb_visibility) is true, the scrollbar thumb will
56/// remain visible without the fade animation. This requires that a `ScrollController` is
57/// provided to controller, or that the `PrimaryScrollController` is available.
58///
59/// When a `ScrollView::scroll_direction` is `Axis::Horizontal`, it is recommended
60/// that the [`Scrollbar`] is always visible, since scrolling in the horizontal
61/// axis is less discoverable.
62///
63/// A scrollbar track can be added using [`track_visibility`](Self::track_visibility). This
64/// can also be drawn when triggered by a hover event, or based on any [`WidgetState`] by
65/// using [`ScrollbarThemeData::track_visibility`].
66///
67/// The [`thickness`](Self::thickness) of the track and scrollbar thumb can be changed
68/// dynamically in response to [`WidgetState`]s using [`ScrollbarThemeData::thickness`].
69///
70/// See also:
71///
72///  * `RawScrollbar`, a basic scrollbar that fades in and out, extended
73///    by this class to add more animations and behaviors.
74///  * [`ScrollbarTheme`], which configures the Scrollbar's appearance.
75///  * [`CupertinoScrollbar`], an iOS style scrollbar.
76///  * `ListView`, which displays a linear, scrollable list of children.
77///  * `GridView`, which displays a 2 dimensional, scrollable array of children.
78pub struct Scrollbar {
79    pub key: Option<KeyRef>,
80
81    /// The widget below this widget in the tree.
82    ///
83    /// The scrollbar will be stacked on top of this child. This child (and its
84    /// subtree) should include a source of `ScrollNotification` notifications.
85    pub child: WidgetRef,
86
87    /// The `ScrollController` used to implement Scrollbar dragging.
88    ///
89    /// For more information, see `RawScrollbarData::controller`.
90    pub controller: Option<ScrollControllerRef>,
91
92    /// Indicates that the scrollbar thumb should be visible, even when a scroll
93    /// is not underway.
94    ///
95    /// For more information, see `RawScrollbarData::thumb_visibility`.
96    ///
97    /// If this property is `None`, then [`ScrollbarThemeData::thumb_visibility`] of
98    /// `ThemeData::scrollbar_theme` is used. If that is also `None`, the default value
99    /// is false.
100    ///
101    /// If the thumb visibility is related to the scrollbar's material state,
102    /// use the global [`ScrollbarThemeData::thumb_visibility`] or override the
103    /// sub-tree's theme data.
104    pub thumb_visibility: Option<bool>,
105
106    /// Indicates that the scrollbar track should be visible.
107    ///
108    /// When true, the scrollbar track will always be visible so long as the thumb
109    /// is visible. If the scrollbar thumb is not visible, the track will not be
110    /// visible either.
111    ///
112    /// If this property is `None`, then [`ScrollbarThemeData::track_visibility`] of
113    /// `ThemeData::scrollbar_theme` is used. If that is also `None`, the default value
114    /// is false.
115    ///
116    /// If the track visibility is related to the scrollbar's material state,
117    /// use the global [`ScrollbarThemeData::track_visibility`] or override the
118    /// sub-tree's theme data.
119    pub track_visibility: Option<bool>,
120
121    /// The thickness of the scrollbar in the cross axis of the scrollable.
122    ///
123    /// If `None`, the default value is platform dependent. On [`TargetPlatform::Android`],
124    /// the default thickness is 4.0 pixels. On [`TargetPlatform::IOS`],
125    /// [`CupertinoScrollbar::DEFAULT_THICKNESS`] is used. The remaining platforms have a
126    /// default thickness of 8.0 pixels.
127    pub thickness: Option<f64>,
128
129    /// The [`Radius`] of the scrollbar thumb's rounded rectangle corners.
130    ///
131    /// If `None`, the default value is platform dependent. On [`TargetPlatform::Android`],
132    /// no radius is applied to the scrollbar thumb. On [`TargetPlatform::IOS`],
133    /// [`CupertinoScrollbar::DEFAULT_RADIUS`] is used. The remaining platforms have a
134    /// default [`Radius::circular`] of 8.0 pixels.
135    pub radius: Option<Radius>,
136
137    /// Whether the scrollbar should be interactive and respond to dragging on the
138    /// thumb, or tapping in the track area.
139    ///
140    /// Does not apply to the [`CupertinoScrollbar`], which is always interactive to
141    /// match native behavior. On Android, the scrollbar is not interactive by
142    /// default.
143    ///
144    /// When false, the scrollbar will not respond to gesture or hover events,
145    /// and will allow to click through it.
146    ///
147    /// Defaults to true when `None`, unless on Android, which will default to
148    /// false when `None`.
149    pub interactive: Option<bool>,
150
151    /// A check that specifies whether a `ScrollNotification` should be
152    /// handled by this widget.
153    ///
154    /// By default, checks whether `notification.depth() == 0`. That means if the
155    /// scrollbar is wrapped around multiple scroll views, it only responds to the
156    /// nearest one and shows the corresponding scrollbar thumb.
157    pub notification_predicate: Option<ScrollNotificationPredicate>,
158
159    /// Dictates the orientation of the scrollbar.
160    ///
161    /// [`ScrollbarOrientation::Top`] places the scrollbar on top of the screen.
162    /// [`ScrollbarOrientation::Bottom`] places the scrollbar on the bottom of the screen.
163    /// [`ScrollbarOrientation::Left`] places the scrollbar on the left of the screen.
164    /// [`ScrollbarOrientation::Right`] places the scrollbar on the right of the screen.
165    ///
166    /// [`ScrollbarOrientation::Top`] and [`ScrollbarOrientation::Bottom`] can only be
167    /// used with a vertical scroll. [`ScrollbarOrientation::Left`] and
168    /// [`ScrollbarOrientation::Right`] can only be used with a horizontal scroll.
169    ///
170    /// For a vertical scroll the orientation defaults to
171    /// [`ScrollbarOrientation::Right`] for `TextDirection::Ltr` and
172    /// [`ScrollbarOrientation::Left`] for `TextDirection::Rtl`.
173    /// For a horizontal scroll the orientation defaults to
174    /// [`ScrollbarOrientation::Bottom`].
175    pub scrollbar_orientation: Option<ScrollbarOrientation>,
176}
177
178impl Scrollbar {
179    /// Creates a Material Design scrollbar that by default will connect to the
180    /// closest Scrollable descendant of [`child`](Self::child).
181    ///
182    /// The [`child`](Self::child) should be a source of `ScrollNotification`
183    /// notifications, typically a `Scrollable` widget.
184    ///
185    /// If the [`controller`](Self::controller) is `None`, the default behavior is to
186    /// enable scrollbar dragging using the `PrimaryScrollController`.
187    ///
188    /// When `None`, [`thickness`](Self::thickness) defaults to 8.0 pixels on desktop and
189    /// web, and 4.0 pixels when on mobile platforms. A `None` [`radius`](Self::radius) will
190    /// result in a default of an 8.0 pixel circular radius about the corners of the
191    /// scrollbar thumb, except for when executing on [`TargetPlatform::Android`], which
192    /// will render the thumb without a radius.
193    #[cfg_attr(debug_assertions, track_caller)]
194    pub fn new<K>(child: impl IntoWidget<K>) -> Scrollbar {
195        Scrollbar {
196            key: None,
197            child: child.into_widget(),
198            controller: None,
199            thumb_visibility: None,
200            track_visibility: None,
201            thickness: None,
202            radius: None,
203            interactive: None,
204            notification_predicate: None,
205            scrollbar_orientation: None,
206        }
207    }
208
209    /// Dart `Scrollbar(key:)`.
210    pub fn key(mut self, key: KeyRef) -> Scrollbar {
211        self.key = Some(key);
212        self
213    }
214
215    /// Dart `Scrollbar(controller:)`.
216    pub fn controller(mut self, controller: ScrollControllerRef) -> Scrollbar {
217        self.controller = Some(controller);
218        self
219    }
220
221    /// Dart `Scrollbar(thumbVisibility:)`.
222    pub fn thumb_visibility(mut self, thumb_visibility: bool) -> Scrollbar {
223        self.thumb_visibility = Some(thumb_visibility);
224        self
225    }
226
227    /// Dart `Scrollbar(trackVisibility:)`.
228    pub fn track_visibility(mut self, track_visibility: bool) -> Scrollbar {
229        self.track_visibility = Some(track_visibility);
230        self
231    }
232
233    /// Dart `Scrollbar(thickness:)`.
234    pub fn thickness(mut self, thickness: f64) -> Scrollbar {
235        self.thickness = Some(thickness);
236        self
237    }
238
239    /// Dart `Scrollbar(radius:)`.
240    pub fn radius(mut self, radius: Radius) -> Scrollbar {
241        self.radius = Some(radius);
242        self
243    }
244
245    /// Dart `Scrollbar(notificationPredicate:)`.
246    pub fn notification_predicate(
247        mut self,
248        notification_predicate: ScrollNotificationPredicate,
249    ) -> Scrollbar {
250        self.notification_predicate = Some(notification_predicate);
251        self
252    }
253
254    /// Dart `Scrollbar(interactive:)`.
255    pub fn interactive(mut self, interactive: bool) -> Scrollbar {
256        self.interactive = Some(interactive);
257        self
258    }
259
260    /// Dart `Scrollbar(scrollbarOrientation:)`.
261    pub fn scrollbar_orientation(
262        mut self,
263        scrollbar_orientation: ScrollbarOrientation,
264    ) -> Scrollbar {
265        self.scrollbar_orientation = Some(scrollbar_orientation);
266        self
267    }
268}
269
270impl Debug for Scrollbar {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        f.debug_struct("Scrollbar")
273            .field("child", &self.child)
274            .field("thumbVisibility", &self.thumb_visibility)
275            .field("trackVisibility", &self.track_visibility)
276            .field("thickness", &self.thickness)
277            .field("radius", &self.radius)
278            .field("interactive", &self.interactive)
279            .field("scrollbarOrientation", &self.scrollbar_orientation)
280            .finish_non_exhaustive()
281    }
282}
283
284impl StatelessWidget for Scrollbar {
285    fn key(&self) -> Option<&KeyRef> {
286        self.key.as_ref()
287    }
288
289    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
290        if Theme::of(app, context).platform == TargetPlatform::IOS {
291            let mut scrollbar = CupertinoScrollbar::new(self.child.clone())
292                .thumb_visibility(self.thumb_visibility.unwrap_or(false))
293                .thickness(
294                    self.thickness
295                        .unwrap_or(CupertinoScrollbar::DEFAULT_THICKNESS),
296                )
297                .thickness_while_dragging(
298                    self.thickness
299                        .unwrap_or(CupertinoScrollbar::DEFAULT_THICKNESS_WHILE_DRAGGING),
300                )
301                .radius(self.radius.unwrap_or(CupertinoScrollbar::DEFAULT_RADIUS))
302                .radius_while_dragging(
303                    self.radius
304                        .unwrap_or(CupertinoScrollbar::DEFAULT_RADIUS_WHILE_DRAGGING),
305                );
306            if let Some(controller) = self.controller.clone() {
307                scrollbar = scrollbar.controller(controller);
308            }
309            if let Some(notification_predicate) = &self.notification_predicate {
310                scrollbar = scrollbar.notification_predicate(Rc::clone(notification_predicate));
311            }
312            if let Some(scrollbar_orientation) = self.scrollbar_orientation {
313                scrollbar = scrollbar.scrollbar_orientation(scrollbar_orientation);
314            }
315            return scrollbar.into_widget();
316        }
317        let mut scrollbar =
318            MaterialScrollbar::new(self.child.clone(), self.notification_predicate.clone());
319        let raw_scrollbar = &mut scrollbar.raw_scrollbar;
320        raw_scrollbar.controller = self.controller.clone();
321        raw_scrollbar.thumb_visibility = self.thumb_visibility;
322        raw_scrollbar.track_visibility = self.track_visibility;
323        raw_scrollbar.thickness = self.thickness;
324        raw_scrollbar.radius = self.radius;
325        raw_scrollbar.interactive = self.interactive;
326        raw_scrollbar.scrollbar_orientation = self.scrollbar_orientation;
327        scrollbar.into_widget()
328    }
329}
330
331/// Dart's `_MaterialScrollbar`: a `RawScrollbar` with Material's fade timing and its own
332/// state.
333struct MaterialScrollbar {
334    raw_scrollbar: RawScrollbarData,
335}
336
337impl MaterialScrollbar {
338    /// Dart's `_MaterialScrollbar` constructor with what it hands `super` itself; the
339    /// arguments it forwards as `super.…` are written into
340    /// [`raw_scrollbar`](Self::raw_scrollbar) by [`Scrollbar`].
341    fn new(
342        child: WidgetRef,
343        notification_predicate: Option<ScrollNotificationPredicate>,
344    ) -> MaterialScrollbar {
345        let mut raw_scrollbar = RawScrollbarData::new(child);
346        raw_scrollbar.fade_duration = K_SCROLLBAR_FADE_DURATION;
347        raw_scrollbar.time_to_fade = K_SCROLLBAR_TIME_TO_FADE;
348        raw_scrollbar.press_duration = Duration::ZERO;
349        raw_scrollbar.notification_predicate = notification_predicate
350            .unwrap_or_else(|| Rc::new(default_scroll_notification_predicate));
351        MaterialScrollbar { raw_scrollbar }
352    }
353}
354
355impl RawScrollbarLeaf for MaterialScrollbar {
356    waft_widgets::raw_scrollbar_accessors!();
357}
358
359impl Debug for MaterialScrollbar {
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        f.write_str("_MaterialScrollbar")
362    }
363}
364
365impl StatefulWidget for MaterialScrollbar {
366    type State = MaterialScrollbarState;
367
368    fn key(&self) -> Option<&KeyRef> {
369        self.raw_scrollbar.key.as_ref()
370    }
371
372    fn create_state(&self) -> MaterialScrollbarState {
373        MaterialScrollbarState {
374            state: StateData::new(),
375            ticker_provider: TickerProviderStateMixinData::new(),
376            raw_scrollbar_state: RawScrollbarStateData::new(),
377            hover_animation_controller: None,
378            drag_is_active: false,
379            hover_is_active: false,
380            color_scheme: None,
381            scrollbar_theme: None,
382            use_android_scrollbar: None,
383        }
384    }
385}
386
387/// Dart's `_MaterialScrollbarState`. Its `late` fields are `None` until `initState` and
388/// `didChangeDependencies` set them.
389struct MaterialScrollbarState {
390    state: StateData<MaterialScrollbar>,
391    ticker_provider: TickerProviderStateMixinData,
392    raw_scrollbar_state: RawScrollbarStateData,
393    hover_animation_controller: Option<Ref<AnimationController>>,
394    drag_is_active: bool,
395    hover_is_active: bool,
396    color_scheme: Option<ColorScheme>,
397    scrollbar_theme: Option<ScrollbarThemeData>,
398    // On Android, scrollbars should match native appearance.
399    use_android_scrollbar: Option<bool>,
400}
401
402impl MaterialScrollbarState {
403    fn hover_animation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
404        app.get(self)
405            .hover_animation_controller
406            .handle()
407            .expect("initState creates the controller")
408    }
409
410    fn color_scheme(self: Handle<Self>, app: &App) -> &ColorScheme {
411        app.get(self)
412            .color_scheme
413            .as_ref()
414            .expect("didChangeDependencies reads the color scheme")
415    }
416
417    fn scrollbar_theme(self: Handle<Self>, app: &App) -> &ScrollbarThemeData {
418        app.get(self)
419            .scrollbar_theme
420            .as_ref()
421            .expect("didChangeDependencies reads the scrollbar theme")
422    }
423
424    fn use_android_scrollbar(self: Handle<Self>, app: &App) -> bool {
425        app.get(self)
426            .use_android_scrollbar
427            .expect("didChangeDependencies reads the platform")
428    }
429
430    fn track_visibility(self: Handle<Self>, app: &App) -> WidgetStatePropertyRef<bool> {
431        let widget_track_visibility = self.widget(app).raw_scrollbar.track_visibility;
432        let theme_track_visibility = self.scrollbar_theme(app).track_visibility.clone();
433        <dyn WidgetStateProperty<bool>>::resolve_with(move |states: &WidgetStates| {
434            widget_track_visibility
435                .or_else(|| {
436                    theme_track_visibility
437                        .as_ref()
438                        .and_then(|track_visibility| track_visibility.resolve(states))
439                })
440                .unwrap_or(false)
441        })
442    }
443
444    fn states(self: Handle<Self>, app: &App) -> WidgetStates {
445        let state = app.get(self);
446        let mut states = HashSet::new();
447        if state.drag_is_active {
448            states.insert(WidgetState::Dragged);
449        }
450        if state.hover_is_active {
451            states.insert(WidgetState::Hovered);
452        }
453        states
454    }
455
456    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
457    fn thumb_color(self: Handle<Self>, app: &mut App) -> WidgetStatePropertyRef<Color> {
458        let color_scheme = self.color_scheme(app);
459        let on_surface = color_scheme.on_surface();
460        let brightness = color_scheme.brightness();
461        let use_android_scrollbar = self.use_android_scrollbar(app);
462        let (drag_color, hover_color, idle_color) = match brightness {
463            Brightness::Light => (
464                on_surface.with_opacity(0.6),
465                on_surface.with_opacity(0.5),
466                if use_android_scrollbar {
467                    self.highlight_color(app).with_opacity(1.0)
468                } else {
469                    on_surface.with_opacity(0.1)
470                },
471            ),
472            Brightness::Dark => (
473                on_surface.with_opacity(0.75),
474                on_surface.with_opacity(0.65),
475                if use_android_scrollbar {
476                    self.highlight_color(app).with_opacity(1.0)
477                } else {
478                    on_surface.with_opacity(0.3)
479                },
480            ),
481        };
482
483        let theme_thumb_color = self.scrollbar_theme(app).thumb_color.clone();
484        let track_visibility = self.track_visibility(app);
485        let hover_value = self.hover_animation_controller(app).value(app);
486        <dyn WidgetStateProperty<Color>>::resolve_with(move |states: &WidgetStates| {
487            let theme_thumb_color = || {
488                theme_thumb_color
489                    .as_ref()
490                    .and_then(|thumb_color| thumb_color.resolve(states))
491            };
492            if states.contains(&WidgetState::Dragged) {
493                return theme_thumb_color().unwrap_or(drag_color);
494            }
495
496            // If the track is visible, the thumb color hover animation is ignored and
497            // changes immediately.
498            if track_visibility.resolve(states) {
499                return theme_thumb_color().unwrap_or(hover_color);
500            }
501
502            Color::lerp(
503                Some(theme_thumb_color().unwrap_or(idle_color)),
504                Some(theme_thumb_color().unwrap_or(hover_color)),
505                hover_value,
506            )
507            .expect("both colors are given")
508        })
509    }
510
511    fn highlight_color(self: Handle<Self>, app: &mut App) -> Color {
512        let context = self.context(app);
513        Theme::of(app, context).highlight_color
514    }
515
516    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
517    fn track_color(self: Handle<Self>, app: &mut App) -> WidgetStatePropertyRef<Color> {
518        let color_scheme = self.color_scheme(app);
519        let on_surface = color_scheme.on_surface();
520        let brightness = color_scheme.brightness();
521        let show_scrollbar = self.show_scrollbar(app);
522        let track_visibility = self.track_visibility(app);
523        let theme_track_color = self.scrollbar_theme(app).track_color.clone();
524        <dyn WidgetStateProperty<Color>>::resolve_with(move |states: &WidgetStates| {
525            if show_scrollbar && track_visibility.resolve(states) {
526                return theme_track_color
527                    .as_ref()
528                    .and_then(|track_color| track_color.resolve(states))
529                    .unwrap_or_else(|| match brightness {
530                        Brightness::Light => on_surface.with_opacity(0.03),
531                        Brightness::Dark => on_surface.with_opacity(0.05),
532                    });
533            }
534            Color::new(0x00000000)
535        })
536    }
537
538    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
539    fn track_border_color(self: Handle<Self>, app: &mut App) -> WidgetStatePropertyRef<Color> {
540        let color_scheme = self.color_scheme(app);
541        let on_surface = color_scheme.on_surface();
542        let brightness = color_scheme.brightness();
543        let show_scrollbar = self.show_scrollbar(app);
544        let track_visibility = self.track_visibility(app);
545        let theme_track_border_color = self.scrollbar_theme(app).track_border_color.clone();
546        <dyn WidgetStateProperty<Color>>::resolve_with(move |states: &WidgetStates| {
547            if show_scrollbar && track_visibility.resolve(states) {
548                return theme_track_border_color
549                    .as_ref()
550                    .and_then(|track_border_color| track_border_color.resolve(states))
551                    .unwrap_or_else(|| match brightness {
552                        Brightness::Light => on_surface.with_opacity(0.1),
553                        Brightness::Dark => on_surface.with_opacity(0.25),
554                    });
555            }
556            Color::new(0x00000000)
557        })
558    }
559
560    fn thickness(self: Handle<Self>, app: &App) -> WidgetStatePropertyRef<f64> {
561        let widget_thickness = self.widget(app).raw_scrollbar.thickness;
562        let theme_thickness = self.scrollbar_theme(app).thickness.clone();
563        let track_visibility = self.track_visibility(app);
564        let use_android_scrollbar = self.use_android_scrollbar(app);
565        <dyn WidgetStateProperty<f64>>::resolve_with(move |states: &WidgetStates| {
566            let thickness = || {
567                widget_thickness.or_else(|| {
568                    theme_thickness
569                        .as_ref()
570                        .and_then(|thickness| thickness.resolve(states))
571                })
572            };
573            if states.contains(&WidgetState::Hovered) && track_visibility.resolve(states) {
574                return thickness().unwrap_or(K_SCROLLBAR_THICKNESS_WITH_TRACK);
575            }
576            // The default scrollbar thickness is smaller on mobile.
577            thickness()
578                .unwrap_or(K_SCROLLBAR_THICKNESS / (if use_android_scrollbar { 2.0 } else { 1.0 }))
579        })
580    }
581}
582
583impl State for MaterialScrollbarState {
584    type Widget = MaterialScrollbar;
585    waft_widgets::state_accessors!();
586
587    fn init_state(self: Handle<Self>, app: &mut App) {
588        RawScrollbarState::init_state(self, app);
589        let controller = AnimationController::new(
590            app,
591            None,
592            Some(Duration::from_millis(200)),
593            None,
594            0.0,
595            1.0,
596            AnimationBehavior::Normal,
597            self,
598        );
599        app.get_mut(self).hover_animation_controller = Some(controller.clone());
600        controller.add_listener(
601            app,
602            Listener::new(move |app: &mut App| {
603                self.update_scrollbar_painter(app);
604            }),
605        );
606    }
607
608    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
609        let context = self.context(app);
610        let theme = Theme::of(app, context);
611        let scrollbar_theme = ScrollbarTheme::of(app, context);
612        let use_android_scrollbar = match theme.platform {
613            TargetPlatform::Android => true,
614            TargetPlatform::IOS
615            | TargetPlatform::Linux
616            | TargetPlatform::Fuchsia
617            | TargetPlatform::MacOS
618            | TargetPlatform::Windows => false,
619        };
620        let state = app.get_mut(self);
621        state.color_scheme = Some(theme.color_scheme.clone());
622        state.scrollbar_theme = Some(scrollbar_theme);
623        state.use_android_scrollbar = Some(use_android_scrollbar);
624        RawScrollbarState::did_change_dependencies(self, app);
625    }
626
627    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MaterialScrollbar) {
628        RawScrollbarState::did_update_widget(self, app, old_widget);
629    }
630
631    fn dispose(self: Handle<Self>, app: &mut App) {
632        let hover_animation_controller = self.hover_animation_controller(app);
633        hover_animation_controller.dispose(app);
634        RawScrollbarState::dispose(self, app);
635        TickerProviderStateMixin::dispose(self, app);
636    }
637
638    fn activate(self: Handle<Self>, app: &mut App) {
639        TickerProviderStateMixin::activate(self, app);
640    }
641
642    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
643        RawScrollbarState::build(self, app, context)
644    }
645}
646
647impl RawScrollbarStateLeaf for MaterialScrollbarState {
648    waft_widgets::raw_scrollbar_state_accessors!();
649
650    fn show_scrollbar(self: Handle<Self>, app: &mut App) -> bool {
651        let states = self.states(app);
652        self.widget(app)
653            .raw_scrollbar
654            .thumb_visibility
655            .or_else(|| {
656                self.scrollbar_theme(app)
657                    .thumb_visibility
658                    .as_ref()
659                    .and_then(|thumb_visibility| thumb_visibility.resolve(&states))
660            })
661            .unwrap_or(false)
662    }
663
664    fn enable_gestures(self: Handle<Self>, app: &mut App) -> bool {
665        self.widget(app)
666            .raw_scrollbar
667            .interactive
668            .or(self.scrollbar_theme(app).interactive)
669            .unwrap_or(!self.use_android_scrollbar(app))
670    }
671
672    fn update_scrollbar_painter(self: Handle<Self>, app: &mut App) {
673        let states = self.states(app);
674        let color = self.thumb_color(app).resolve(&states);
675        let track_color = self.track_color(app).resolve(&states);
676        let track_border_color = self.track_border_color(app).resolve(&states);
677        let context = self.context(app);
678        let text_direction = Directionality::of(app, context);
679        let thickness = self.thickness(app).resolve(&states);
680        let use_android_scrollbar = self.use_android_scrollbar(app);
681        let scrollbar_theme = self.scrollbar_theme(app);
682        let radius = self
683            .widget(app)
684            .raw_scrollbar
685            .radius
686            .or(scrollbar_theme.radius)
687            .or(if use_android_scrollbar {
688                None
689            } else {
690                Some(K_SCROLLBAR_RADIUS)
691            });
692        let cross_axis_margin =
693            scrollbar_theme
694                .cross_axis_margin
695                .unwrap_or(if use_android_scrollbar {
696                    0.0
697                } else {
698                    K_SCROLLBAR_MARGIN
699                });
700        let main_axis_margin = scrollbar_theme.main_axis_margin.unwrap_or(0.0);
701        let min_length = scrollbar_theme
702            .min_thumb_length
703            .unwrap_or(K_SCROLLBAR_MIN_LENGTH);
704        let padding = MediaQuery::padding_of(app, context);
705        let scrollbar_orientation = self.widget(app).raw_scrollbar.scrollbar_orientation;
706        let ignore_pointer = !self.enable_gestures(app);
707
708        let painter = RawScrollbarState::scrollbar_painter(self, app);
709        painter.set_color(app, color);
710        painter.set_track_color(app, track_color);
711        painter.set_track_border_color(app, track_border_color);
712        painter.set_text_direction(app, Some(text_direction));
713        painter.set_thickness(app, thickness);
714        painter.set_radius(app, radius);
715        painter.set_cross_axis_margin(app, cross_axis_margin);
716        painter.set_main_axis_margin(app, main_axis_margin);
717        painter.set_min_length(app, min_length);
718        painter.set_padding(app, EdgeInsetsGeometry::from(padding));
719        painter.set_scrollbar_orientation(app, scrollbar_orientation);
720        painter.set_ignore_pointer(app, ignore_pointer);
721    }
722
723    fn handle_thumb_press_start(self: Handle<Self>, app: &mut App, local_position: Offset) {
724        RawScrollbarState::handle_thumb_press_start(self, app, local_position);
725        self.set_state(app, |state| {
726            state.drag_is_active = true;
727        });
728    }
729
730    fn handle_thumb_press_end(
731        self: Handle<Self>,
732        app: &mut App,
733        local_position: Offset,
734        velocity: Velocity,
735    ) {
736        RawScrollbarState::handle_thumb_press_end(self, app, local_position, velocity);
737        self.set_state(app, |state| {
738            state.drag_is_active = false;
739        });
740    }
741
742    fn handle_hover(self: Handle<Self>, app: &mut App, event: &PointerHoverEvent) {
743        RawScrollbarState::handle_hover(self, app, event);
744        // Check if the position of the pointer falls over the painted scrollbar
745        if RawScrollbarState::is_pointer_over_scrollbar(self, app, event.position, event.kind) {
746            // Pointer is hovering over the scrollbar
747            self.set_state(app, |state| {
748                state.hover_is_active = true;
749            });
750            self.hover_animation_controller(app).forward(app, None);
751        } else if app.get(self).hover_is_active {
752            // Pointer was, but is no longer over painted scrollbar.
753            self.set_state(app, |state| {
754                state.hover_is_active = false;
755            });
756            self.hover_animation_controller(app).reverse(app, None);
757        }
758    }
759
760    fn handle_hover_exit(self: Handle<Self>, app: &mut App) {
761        RawScrollbarState::handle_hover_exit(self, app);
762        self.set_state(app, |state| {
763            state.hover_is_active = false;
764        });
765        self.hover_animation_controller(app).reverse(app, None);
766    }
767}
768
769impl TickerProviderObject for MaterialScrollbarState {
770    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
771        TickerProviderStateMixin::create_ticker(self, app, on_tick)
772    }
773}
774
775impl TickerProviderStateMixin for MaterialScrollbarState {
776    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
777        &app.get(self).ticker_provider
778    }
779
780    fn ticker_provider_data_mut(
781        self: Handle<Self>,
782        app: &mut App,
783    ) -> &mut TickerProviderStateMixinData {
784        &mut app.get_mut(self).ticker_provider
785    }
786}
787
788impl Debug for MaterialScrollbarState {
789    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
790        f.write_str("_MaterialScrollbarState")
791    }
792}
793
794#[cfg(test)]
795pub(crate) mod tests {
796    use std::cell::Cell;
797
798    use waft_cupertino::CupertinoScrollbarState;
799    use waft_embedder::Size;
800    use waft_embedder::{Canvas, PointerDeviceKind, RRect, Rect};
801    use waft_gestures::{GestureBinding, PointerEvent, PointerScrollEvent};
802    use waft_painting::{AxisDirection, Border, BorderSide, BorderStyle, BoxDecoration};
803    use waft_rendering::{HitTestBehavior, RenderViewport, RenderViewportBase};
804    use waft_scheduler::SchedulerBinding;
805    use waft_widgets::{
806        Center, Column, Container, CustomScrollView, FixedScrollMetrics, GestureDetector,
807        GlobalKey, Icon, ListView, MediaQueryData, PrimaryScrollController, ScrollBehavior,
808        ScrollBehaviorRef, ScrollConfiguration, ScrollController, Scrollable, ScrollableDetails,
809        SingleChildScrollView, SizedBox, SliverToBoxAdapter, StatefulBuilder, Text,
810    };
811
812    use waft_widgets::testing::{
813        TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_nothing,
814        finds_one_widget, test_widgets, test_widgets_variant,
815    };
816
817    use super::*;
818    use crate::app::{MaterialApp, MaterialScrollBehavior};
819    use crate::floating_action_button::FloatingActionButton;
820    use crate::icons::Icons;
821    use crate::scaffold::Scaffold;
822    use crate::test_support::material_app;
823    use crate::theme_data::ThemeData;
824    use waft_embedder::valo::Op;
825    use waft_rendering::testing::{PaintCall, assert_paints, draws, paints_exactly};
826    use waft_widgets::AnyScrollController;
827
828    pub(crate) const K_SCROLLBAR_FADE_DURATION_FOR_TESTS: Duration = Duration::from_millis(300);
829    pub(crate) const K_SCROLLBAR_TIME_TO_FADE_FOR_TESTS: Duration = Duration::from_millis(600);
830    pub(crate) const K_ANDROID_THUMB_IDLE_COLOR: u32 = 0xffbcbcbc;
831    pub(crate) const K_ANDROID_TRACK_DIMENSIONS: Rect = Rect::from_ltrb(796.0, 0.0, 800.0, 600.0);
832    pub(crate) const K_DEFAULT_THUMB_RADIUS: Radius = Radius::circular(8.0);
833    pub(crate) const K_DEFAULT_IDLE_THUMB_COLOR: u32 = 0x1a000000;
834    pub(crate) const K_TRANSPARENT: u32 = 0x00000000;
835
836    const ALL_PLATFORMS: [TargetPlatform; 6] = [
837        TargetPlatform::Android,
838        TargetPlatform::Fuchsia,
839        TargetPlatform::IOS,
840        TargetPlatform::Linux,
841        TargetPlatform::MacOS,
842        TargetPlatform::Windows,
843    ];
844
845    pub(crate) const DESKTOP: [TargetPlatform; 3] = [
846        TargetPlatform::Linux,
847        TargetPlatform::MacOS,
848        TargetPlatform::Windows,
849    ];
850
851    pub(crate) fn get_starting_thumb_rect(is_android: bool) -> Rect {
852        if is_android {
853            // On Android the thumb is slightly different. The thumb is only 4 pixels wide,
854            // and has no margin along the side of the viewport.
855            Rect::from_ltrb(796.0, 0.0, 800.0, 90.0)
856        } else {
857            // The Material Design thumb is 8 pixels wide, with a 2
858            // pixel margin to the right edge of the viewport.
859            Rect::from_ltrb(790.0, 0.0, 798.0, 90.0)
860        }
861    }
862
863    /// The tests' `NoScrollbarBehavior`, a `MaterialScrollBehavior` with no scrollbar of the
864    /// scroll behavior's own over the one a case puts.
865    #[derive(Debug)]
866    struct NoScrollbarBehavior;
867
868    impl ScrollBehavior for NoScrollbarBehavior {
869        fn as_any(&self) -> &dyn std::any::Any {
870            self
871        }
872
873        fn get_platform(&self, app: &mut App, context: BuildContext) -> TargetPlatform {
874            MaterialScrollBehavior::new().get_platform(app, context)
875        }
876
877        fn build_scrollbar(
878            &self,
879            _app: &mut App,
880            _context: BuildContext,
881            child: WidgetRef,
882            _details: &ScrollableDetails,
883        ) -> WidgetRef {
884            child
885        }
886
887        fn build_overscroll_indicator(
888            &self,
889            app: &mut App,
890            context: BuildContext,
891            child: WidgetRef,
892            details: &ScrollableDetails,
893        ) -> WidgetRef {
894            MaterialScrollBehavior::new().build_overscroll_indicator(app, context, child, details)
895        }
896    }
897
898    /// `ScrollConfiguration(behavior: const NoScrollbarBehavior(), child: child)`.
899    pub(crate) fn no_scrollbar<K>(child: impl IntoWidget<K>) -> WidgetRef {
900        ScrollConfiguration::new(ScrollBehaviorRef::new(NoScrollbarBehavior), child).into_widget()
901    }
902
903    /// `scrollbar_test.dart`'s `_buildBoilerplate`.
904    fn build_boilerplate<K>(child: impl IntoWidget<K>) -> WidgetRef {
905        Directionality::new(
906            waft_embedder::TextDirection::Ltr,
907            MediaQuery::new(MediaQueryData::new(), no_scrollbar(child)).into_widget(),
908        )
909        .into_widget()
910    }
911
912    /// `SingleChildScrollView(controller: controller, child: SizedBox(width:, height:))`.
913    pub(crate) fn scroll_view(
914        controller: Option<ScrollControllerRef>,
915        width: f64,
916        height: f64,
917    ) -> SingleChildScrollView {
918        let view = SingleChildScrollView::new().child(SizedBox::new().width(width).height(height));
919        match controller {
920            Some(controller) => view.controller(controller.clone()),
921            None => view,
922        }
923    }
924
925    /// The Material scrollbar's state.
926    fn material_state(tester: &WidgetTester) -> Handle<MaterialScrollbarState> {
927        let element = *find::by_type::<MaterialScrollbar>()
928            .evaluate(tester)
929            .first()
930            .expect("a Material scrollbar");
931        element
932            .state_handle::<MaterialScrollbarState>(&tester.cell.borrow())
933            .expect("its state")
934    }
935
936    /// What the scrollbar paints over its child: Dart's `paints` matcher on
937    /// `find.byType(Scrollbar)`, without the child's own draws.
938    pub(crate) fn painted(tester: &WidgetTester) -> Vec<Op> {
939        painted_by(tester, material_state(tester))
940    }
941
942    /// What the scrollbar painter of `state` paints over its child.
943    fn painted_by<S: RawScrollbarStateLeaf>(tester: &WidgetTester, state: Handle<S>) -> Vec<Op>
944    where
945        S::Widget: RawScrollbarLeaf,
946    {
947        let mut app = tester.cell.borrow_mut();
948        let painter = RawScrollbarState::scrollbar_painter(state, &app);
949        let size = state
950            .context(&app)
951            .find_render_object(&app)
952            .and_then(|render| render.as_box())
953            .expect("the scrollbar's render box")
954            .size(&app);
955        let mut canvas = Canvas::new();
956        painter.paint(&mut app, &mut canvas, size);
957        canvas.build().ops().to_vec()
958    }
959
960    /// Dart's `paints..rect(rect: track, color:)..line(p1:, p2:, color:)`: the track and
961    /// its border, the first two draws.
962    ///
963    /// Valo records no op for a paint that draws nothing, so a transparent track and border
964    /// leave only the thumb in `drawn`; their colours are then read from the painter, and the
965    /// track's width from the thickness and margin it is laid out with.
966    pub(crate) fn assert_track(
967        tester: &WidgetTester,
968        drawn: &[Op],
969        rect: Rect,
970        color: u32,
971        border: (Offset, Offset),
972        border_color: u32,
973    ) {
974        if color == K_TRANSPARENT && border_color == K_TRANSPARENT {
975            assert_eq!(draws(drawn).len(), 1, "only the thumb in {drawn:?}");
976            let state = material_state(tester);
977            let app = tester.cell.borrow();
978            let painter = RawScrollbarState::scrollbar_painter(state, &app);
979            assert_eq!(painter.track_color(&app).to_argb32(), K_TRANSPARENT);
980            assert_eq!(painter.track_border_color(&app).to_argb32(), K_TRANSPARENT);
981            assert_eq!(
982                rect.width(),
983                painter.thickness(&app) + 2.0 * painter.cross_axis_margin(&app),
984                "the track's width"
985            );
986            return;
987        }
988        assert_paints(
989            drawn,
990            &[
991                PaintCall::rect_at(rect, Some(Color::new(color))),
992                PaintCall::Line {
993                    p1: Some(border.0),
994                    p2: Some(border.1),
995                    color: Some(Color::new(border_color)),
996                    stroke_width: None,
997                },
998            ],
999        );
1000    }
1001
1002    /// Dart's `paints..rect(rect: thumb, color:)`: a square thumb, the last draw.
1003    pub(crate) fn assert_thumb_rect(drawn: &[Op], rect: Rect, color: u32) {
1004        assert_paints(drawn, &[PaintCall::rect_at(rect, Some(Color::new(color)))]);
1005    }
1006
1007    /// Dart's `paints..rrect(rrect: RRect.fromRectAndRadius(rect, radius), color:)`: a
1008    /// rounded thumb.
1009    pub(crate) fn assert_thumb_rrect(
1010        tester: &WidgetTester,
1011        rect: Rect,
1012        radius: Radius,
1013        color: u32,
1014    ) {
1015        assert_paints(
1016            &painted(tester),
1017            &[PaintCall::rrect_at(
1018                RRect::from_rect_and_radius(rect, radius),
1019                Some(Color::new(color)),
1020            )],
1021        );
1022    }
1023
1024    /// Whether the thumb is painted: Dart's `paints..rect()` against `isNot(paints..rect())`.
1025    pub(crate) fn paints_thumb(tester: &WidgetTester) -> bool {
1026        !draws(&painted(tester)).is_empty()
1027    }
1028
1029    /// Dart's `tester.startGesture(at)` and a settle.
1030    pub(crate) fn start_gesture(tester: &mut WidgetTester, at: Offset) -> TestPointer {
1031        let mut pointer = TestPointer::touch(1);
1032        tester.down(&mut pointer, at);
1033        pointer
1034    }
1035
1036    /// Dart's `gesture.moveBy(by)`.
1037    pub(crate) fn move_by(tester: &mut WidgetTester, pointer: &mut TestPointer, by: Offset) {
1038        let at = pointer.position + by;
1039        tester.move_to(pointer, at, true);
1040    }
1041
1042    /// Dart's `tester.createGesture(kind: mouse)`, `addPointer()` and `moveTo(at)`.
1043    pub(crate) fn hover_at(tester: &mut WidgetTester, at: Offset) -> TestPointer {
1044        let mut mouse = TestPointer::mouse(7, 0);
1045        tester.add_pointer(&mut mouse, Offset::ZERO);
1046        tester.move_to(&mut mouse, at, false);
1047        mouse
1048    }
1049
1050    /// The scroll offset of `controller`.
1051    fn offset(tester: &WidgetTester, controller: AnyScrollController) -> f64 {
1052        controller.offset(&tester.cell.borrow())
1053    }
1054
1055    fn controller(tester: &WidgetTester) -> ScrollControllerRef {
1056        ScrollController::default(&mut tester.cell.borrow_mut()).into_erased()
1057    }
1058
1059    fn m2(tester: &WidgetTester) -> ThemeData {
1060        ThemeData::builder()
1061            .use_material3(false)
1062            .build(&tester.cell.borrow())
1063    }
1064
1065    #[test]
1066    fn on_first_render_with_thumb_visibility_true_the_thumb_shows() {
1067        test_widgets(|tester| {
1068            let controller = controller(tester);
1069            let theme = ThemeData::new(&tester.cell.borrow());
1070            tester.pump_widget(build_boilerplate(Theme::new(
1071                theme,
1072                Scrollbar::new(scroll_view(Some(controller.clone()), 4000.0, 4000.0))
1073                    .thumb_visibility(true)
1074                    .controller(controller),
1075            )));
1076            tester.pump_and_settle();
1077            assert!(paints_thumb(tester));
1078        });
1079    }
1080
1081    #[test]
1082    fn on_first_render_with_thumb_visibility_true_the_thumb_shows_with_primary_scroll_controller() {
1083        test_widgets(|tester| {
1084            let controller = controller(tester);
1085            let theme = ThemeData::new(&tester.cell.borrow());
1086            tester.pump_widget(build_boilerplate(Theme::new(
1087                theme,
1088                PrimaryScrollController::new(
1089                    controller,
1090                    Scrollbar::new(scroll_view(None, 4000.0, 4000.0).primary(true))
1091                        .thumb_visibility(true),
1092                ),
1093            )));
1094            tester.pump_and_settle();
1095            assert!(paints_thumb(tester));
1096        });
1097    }
1098
1099    #[test]
1100    fn on_first_render_with_thumb_visibility_false_the_thumb_is_hidden() {
1101        test_widgets(|tester| {
1102            let controller = controller(tester);
1103            let theme = ThemeData::new(&tester.cell.borrow());
1104            tester.pump_widget(build_boilerplate(Theme::new(
1105                theme,
1106                Scrollbar::new(scroll_view(Some(controller.clone()), 4000.0, 4000.0))
1107                    .thumb_visibility(false)
1108                    .controller(controller),
1109            )));
1110            tester.pump_and_settle();
1111            assert!(!paints_thumb(tester));
1112        });
1113    }
1114
1115    #[test]
1116    fn toggling_thumb_visibility_while_not_scrolling_fades_the_thumb_in_and_out() {
1117        test_widgets(|tester| {
1118            let controller = controller(tester);
1119            let view_with_scroll = |tester: &WidgetTester, thumb_visibility: bool| {
1120                let theme = ThemeData::new(&tester.cell.borrow());
1121                build_boilerplate(Theme::new(
1122                    theme,
1123                    Scrollbar::new(scroll_view(Some(controller.clone()), 4000.0, 4000.0))
1124                        .thumb_visibility(thumb_visibility)
1125                        .controller(controller.clone()),
1126                ))
1127            };
1128            let tree = view_with_scroll(tester, true);
1129            tester.pump_widget(tree);
1130            tester.pump_and_settle();
1131            assert!(paints_thumb(tester));
1132
1133            let tree = view_with_scroll(tester, false);
1134            tester.pump_widget(tree);
1135            tester.pump_and_settle();
1136            assert!(!paints_thumb(tester));
1137
1138            let tree = view_with_scroll(tester, true);
1139            tester.pump_widget(tree);
1140            tester.pump_and_settle();
1141            assert!(
1142                paints_thumb(tester),
1143                "set thumbVisibility: true, the thumb shows directly"
1144            );
1145        });
1146    }
1147
1148    #[test]
1149    fn scrollbar_respects_thickness_and_radius() {
1150        test_widgets(|tester| {
1151            let controller = controller(tester);
1152            let view_with_scroll = |tester: &WidgetTester, radius: Option<Radius>| {
1153                let theme = ThemeData::new(&tester.cell.borrow());
1154                let mut scrollbar =
1155                    Scrollbar::new(scroll_view(Some(controller.clone()), 1600.0, 1200.0))
1156                        .controller(controller.clone())
1157                        .thickness(20.0);
1158                if let Some(radius) = radius {
1159                    scrollbar = scrollbar.radius(radius);
1160                }
1161                build_boilerplate(Theme::new(theme, scrollbar))
1162            };
1163
1164            // Scroll a bit to cause the scrollbar thumb to be shown;
1165            // undo the scroll to put the thumb back at the top.
1166            let tree = view_with_scroll(tester, None);
1167            tester.pump_widget(tree);
1168            const SCROLL_AMOUNT: f64 = 10.0;
1169            let mut scroll_gesture = start_gesture(tester, Offset::new(400.0, 300.0));
1170            move_by(
1171                tester,
1172                &mut scroll_gesture,
1173                Offset::new(0.0, -SCROLL_AMOUNT),
1174            );
1175            tester.pump();
1176            tester.pump_by(Duration::from_millis(500));
1177            move_by(tester, &mut scroll_gesture, Offset::new(0.0, SCROLL_AMOUNT));
1178            tester.pump();
1179            tester.up(&scroll_gesture);
1180            tester.pump();
1181
1182            // Long press on the scrollbar thumb and expect it to grow
1183            let drawn = painted(tester);
1184            assert_track(
1185                tester,
1186                &drawn,
1187                Rect::from_ltrb(780.0, 0.0, 800.0, 600.0),
1188                K_TRANSPARENT,
1189                (Offset::new(780.0, 0.0), Offset::new(780.0, 600.0)),
1190                K_TRANSPARENT,
1191            );
1192            assert_thumb_rect(
1193                &drawn,
1194                Rect::from_ltrb(780.0, 0.0, 800.0, 300.0),
1195                K_ANDROID_THUMB_IDLE_COLOR,
1196            );
1197            let tree = view_with_scroll(tester, Some(Radius::circular(10.0)));
1198            tester.pump_widget(tree);
1199            assert_thumb_rrect(
1200                tester,
1201                Rect::from_ltrb(780.0, 0.0, 800.0, 300.0),
1202                Radius::circular(10.0),
1203                K_ANDROID_THUMB_IDLE_COLOR,
1204            );
1205
1206            tester.pump_and_settle();
1207        });
1208    }
1209
1210    #[test]
1211    fn tapping_the_track_area_pages_the_scroll_view() {
1212        test_widgets(|tester| {
1213            let scroll_controller = controller(tester);
1214            tester.pump_widget(
1215                Directionality::new(
1216                    waft_embedder::TextDirection::Ltr,
1217                    MediaQuery::new(
1218                        MediaQueryData::new(),
1219                        Scrollbar::new(scroll_view(
1220                            Some(scroll_controller.clone()),
1221                            1000.0,
1222                            1000.0,
1223                        ))
1224                        .interactive(true)
1225                        .thumb_visibility(true)
1226                        .controller(scroll_controller.clone()),
1227                    )
1228                    .into_widget(),
1229                )
1230                .into_widget(),
1231            );
1232
1233            tester.pump_and_settle();
1234            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
1235            let border = (Offset::new(796.0, 0.0), Offset::new(796.0, 600.0));
1236            let drawn = painted(tester);
1237            assert_track(
1238                tester,
1239                &drawn,
1240                K_ANDROID_TRACK_DIMENSIONS,
1241                K_TRANSPARENT,
1242                border,
1243                K_TRANSPARENT,
1244            );
1245            assert_thumb_rect(
1246                &drawn,
1247                Rect::from_ltrb(796.0, 0.0, 800.0, 360.0),
1248                K_ANDROID_THUMB_IDLE_COLOR,
1249            );
1250
1251            // Tap on the track area below the thumb.
1252            tester.tap_at(Offset::new(796.0, 550.0), 1);
1253            tester.pump_and_settle();
1254
1255            assert_eq!(offset(tester, scroll_controller.handle()), 400.0);
1256            let drawn = painted(tester);
1257            assert_track(
1258                tester,
1259                &drawn,
1260                K_ANDROID_TRACK_DIMENSIONS,
1261                K_TRANSPARENT,
1262                border,
1263                K_TRANSPARENT,
1264            );
1265            assert_thumb_rect(
1266                &drawn,
1267                Rect::from_ltrb(796.0, 240.0, 800.0, 600.0),
1268                K_ANDROID_THUMB_IDLE_COLOR,
1269            );
1270
1271            // Tap on the track area above the thumb.
1272            tester.tap_at(Offset::new(796.0, 50.0), 1);
1273            tester.pump_and_settle();
1274
1275            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
1276            let drawn = painted(tester);
1277            assert_track(
1278                tester,
1279                &drawn,
1280                K_ANDROID_TRACK_DIMENSIONS,
1281                K_TRANSPARENT,
1282                border,
1283                K_TRANSPARENT,
1284            );
1285            assert_thumb_rect(
1286                &drawn,
1287                Rect::from_ltrb(796.0, 0.0, 800.0, 360.0),
1288                K_ANDROID_THUMB_IDLE_COLOR,
1289            );
1290        });
1291    }
1292
1293    #[test]
1294    fn scrollbar_never_goes_away_until_finger_lift() {
1295        test_widgets(|tester| {
1296            let theme = ThemeData::new(&tester.cell.borrow());
1297            tester.pump_widget(material_app(
1298                theme,
1299                Scrollbar::new(scroll_view(None, 4000.0, 4000.0)).into_widget(),
1300            ));
1301            let mut gesture = start_gesture(tester, Offset::new(400.0, 300.0));
1302            move_by(tester, &mut gesture, Offset::new(0.0, -20.0));
1303            tester.pump();
1304            // Scrollbar fully showing
1305            tester.pump_by(Duration::from_millis(500));
1306            let border = (Offset::new(796.0, 0.0), Offset::new(796.0, 600.0));
1307            let thumb = Rect::from_ltrb(796.0, 3.0, 800.0, 93.0);
1308            let drawn = painted(tester);
1309            assert_track(
1310                tester,
1311                &drawn,
1312                K_ANDROID_TRACK_DIMENSIONS,
1313                K_TRANSPARENT,
1314                border,
1315                K_TRANSPARENT,
1316            );
1317            assert_thumb_rect(&drawn, thumb, K_ANDROID_THUMB_IDLE_COLOR);
1318
1319            tester.pump_by(Duration::from_secs(3));
1320            tester.pump_by(Duration::from_secs(3));
1321            // Still there.
1322            let drawn = painted(tester);
1323            assert_track(
1324                tester,
1325                &drawn,
1326                K_ANDROID_TRACK_DIMENSIONS,
1327                K_TRANSPARENT,
1328                border,
1329                K_TRANSPARENT,
1330            );
1331            assert_thumb_rect(&drawn, thumb, K_ANDROID_THUMB_IDLE_COLOR);
1332
1333            tester.up(&gesture);
1334            tester.pump_by(K_SCROLLBAR_TIME_TO_FADE_FOR_TESTS);
1335            tester.pump_by(K_SCROLLBAR_FADE_DURATION_FOR_TESTS / 2);
1336
1337            // Opacity going down now.
1338            let drawn = painted(tester);
1339            assert_track(
1340                tester,
1341                &drawn,
1342                K_ANDROID_TRACK_DIMENSIONS,
1343                K_TRANSPARENT,
1344                border,
1345                K_TRANSPARENT,
1346            );
1347            assert_thumb_rect(&drawn, thumb, 0xc6bcbcbc);
1348        });
1349    }
1350
1351    #[test]
1352    fn scrollbar_thumb_can_be_dragged() {
1353        test_widgets(|tester| {
1354            let scroll_controller = controller(tester);
1355            let theme = m2(tester);
1356            tester.pump_widget(material_app(
1357                theme,
1358                PrimaryScrollController::new(
1359                    scroll_controller.clone(),
1360                    Scrollbar::new(scroll_view(None, 4000.0, 4000.0))
1361                        .interactive(true)
1362                        .thumb_visibility(true)
1363                        .controller(scroll_controller.clone()),
1364                )
1365                .into_widget(),
1366            ));
1367            tester.pump_and_settle();
1368            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
1369            let border = (Offset::new(796.0, 0.0), Offset::new(796.0, 600.0));
1370            let drawn = painted(tester);
1371            assert_track(
1372                tester,
1373                &drawn,
1374                K_ANDROID_TRACK_DIMENSIONS,
1375                K_TRANSPARENT,
1376                border,
1377                K_TRANSPARENT,
1378            );
1379            assert_thumb_rect(
1380                &drawn,
1381                get_starting_thumb_rect(true),
1382                K_ANDROID_THUMB_IDLE_COLOR,
1383            );
1384
1385            // Drag the thumb down to scroll down.
1386            const SCROLL_AMOUNT: f64 = 10.0;
1387            let mut drag_scrollbar_gesture = start_gesture(tester, Offset::new(797.0, 45.0));
1388            tester.pump_and_settle();
1389
1390            let drawn = painted(tester);
1391            assert_track(
1392                tester,
1393                &drawn,
1394                K_ANDROID_TRACK_DIMENSIONS,
1395                K_TRANSPARENT,
1396                border,
1397                K_TRANSPARENT,
1398            );
1399            // Drag color
1400            assert_thumb_rect(&drawn, get_starting_thumb_rect(true), 0x99000000);
1401
1402            move_by(
1403                tester,
1404                &mut drag_scrollbar_gesture,
1405                Offset::new(0.0, SCROLL_AMOUNT),
1406            );
1407            tester.pump_and_settle();
1408            tester.up(&drag_scrollbar_gesture);
1409            tester.pump_and_settle();
1410
1411            // The view has scrolled more than it would have by a swipe pointer of the
1412            // same distance.
1413            assert!(offset(tester, scroll_controller.handle()) > SCROLL_AMOUNT * 2.0);
1414            let drawn = painted(tester);
1415            assert_track(
1416                tester,
1417                &drawn,
1418                K_ANDROID_TRACK_DIMENSIONS,
1419                K_TRANSPARENT,
1420                border,
1421                K_TRANSPARENT,
1422            );
1423            assert_thumb_rect(
1424                &drawn,
1425                Rect::from_ltrb(796.0, 10.0, 800.0, 100.0),
1426                K_ANDROID_THUMB_IDLE_COLOR,
1427            );
1428        });
1429    }
1430
1431    /// Dart's `MaterialApp(theme: theme, home: SingleChildScrollView(...))` on a desktop,
1432    /// where `MaterialScrollBehavior` puts a `Scrollbar` over the scroll view with the
1433    /// scroll view's controller.
1434    fn desktop_app(tester: &WidgetTester, theme: ThemeData) -> WidgetRef {
1435        let controller = controller(tester);
1436        material_app(
1437            theme,
1438            no_scrollbar(
1439                Scrollbar::new(scroll_view(Some(controller.clone()), 4000.0, 4000.0))
1440                    .controller(controller),
1441            ),
1442        )
1443    }
1444
1445    #[test]
1446    fn scrollbar_thumb_color_completes_a_hover_animation() {
1447        for platform in DESKTOP {
1448            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1449                let theme =
1450                    ThemeData::builder()
1451                        .use_material3(false)
1452                        .scrollbar_theme(ScrollbarThemeData::new().thumb_visibility(
1453                            <dyn WidgetStateProperty<Option<bool>>>::all(Some(true)),
1454                        ))
1455                        .build(&tester.cell.borrow());
1456                let app = desktop_app(tester, theme);
1457                tester.pump_widget(app);
1458                tester.pump_and_settle();
1459                assert_thumb_rrect(
1460                    tester,
1461                    get_starting_thumb_rect(false),
1462                    K_DEFAULT_THUMB_RADIUS,
1463                    K_DEFAULT_IDLE_THUMB_COLOR,
1464                );
1465
1466                hover_at(tester, Offset::new(794.0, 5.0));
1467                tester.pump_and_settle();
1468
1469                // Hover color
1470                assert_thumb_rrect(
1471                    tester,
1472                    get_starting_thumb_rect(false),
1473                    K_DEFAULT_THUMB_RADIUS,
1474                    0x80000000,
1475                );
1476            });
1477        }
1478    }
1479
1480    /// The theme of the hover cases: Material 2 unless `use_material3`, the thumb always
1481    /// shown, the track only while hovered, and `thickness` if given.
1482    fn hover_track_theme(
1483        tester: &WidgetTester,
1484        use_material3: bool,
1485        thickness: Option<WidgetStatePropertyRef<Option<f64>>>,
1486    ) -> ThemeData {
1487        let mut scrollbar_theme = ScrollbarThemeData::new()
1488            .thumb_visibility(<dyn WidgetStateProperty<Option<bool>>>::all(Some(true)))
1489            .track_visibility(<dyn WidgetStateProperty<Option<bool>>>::resolve_with(
1490                |states: &WidgetStates| Some(states.contains(&WidgetState::Hovered)),
1491            ));
1492        if let Some(thickness) = thickness {
1493            scrollbar_theme = scrollbar_theme.thickness(thickness);
1494        }
1495        ThemeData::builder()
1496            .use_material3(use_material3)
1497            .scrollbar_theme(scrollbar_theme)
1498            .build(&tester.cell.borrow())
1499    }
1500
1501    #[test]
1502    fn hover_animation_is_not_triggered_by_tap_gestures() {
1503        test_widgets_variant(
1504            TargetPlatformVariant::only(TargetPlatform::Linux),
1505            |tester| {
1506                let theme = hover_track_theme(tester, false, None);
1507                let app = desktop_app(tester, theme);
1508                tester.pump_widget(app);
1509                tester.pump_and_settle();
1510                assert_thumb_rrect(
1511                    tester,
1512                    get_starting_thumb_rect(false),
1513                    K_DEFAULT_THUMB_RADIUS,
1514                    K_DEFAULT_IDLE_THUMB_COLOR,
1515                );
1516                tester.tap_at(Offset::new(794.0, 5.0), 1);
1517                tester.pump_and_settle();
1518
1519                // Tapping triggers a hover enter event. In this case, the Scrollbar should
1520                // be unchanged since it ignores hover events that aren't from a mouse.
1521                assert_thumb_rrect(
1522                    tester,
1523                    get_starting_thumb_rect(false),
1524                    K_DEFAULT_THUMB_RADIUS,
1525                    K_DEFAULT_IDLE_THUMB_COLOR,
1526                );
1527
1528                // Now trigger hover with a mouse.
1529                hover_at(tester, Offset::new(794.0, 5.0));
1530                tester.pump();
1531
1532                let drawn = painted(tester);
1533                assert_track(
1534                    tester,
1535                    &drawn,
1536                    Rect::from_ltrb(784.0, 0.0, 800.0, 600.0),
1537                    0x08000000,
1538                    (Offset::new(784.0, 0.0), Offset::new(784.0, 600.0)),
1539                    K_DEFAULT_IDLE_THUMB_COLOR,
1540                );
1541                // Scrollbar thumb is larger; hover color
1542                assert_thumb_rrect(
1543                    tester,
1544                    Rect::from_ltrb(786.0, 0.0, 798.0, 90.0),
1545                    K_DEFAULT_THUMB_RADIUS,
1546                    0x80000000,
1547                );
1548            },
1549        );
1550    }
1551
1552    #[test]
1553    fn scrollbar_theme_data_thickness_replaces_hover_thickness() {
1554        for platform in DESKTOP {
1555            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1556                let thickness = <dyn WidgetStateProperty<Option<f64>>>::resolve_with(
1557                    |states: &WidgetStates| {
1558                        if states.contains(&WidgetState::Hovered) {
1559                            return Some(40.0);
1560                        }
1561                        // Default thickness
1562                        Some(8.0)
1563                    },
1564                );
1565                let theme = hover_track_theme(tester, false, Some(thickness));
1566                let app = desktop_app(tester, theme);
1567                tester.pump_widget(app);
1568                tester.pump_and_settle();
1569                assert_thumb_rrect(
1570                    tester,
1571                    get_starting_thumb_rect(false),
1572                    K_DEFAULT_THUMB_RADIUS,
1573                    K_DEFAULT_IDLE_THUMB_COLOR,
1574                );
1575
1576                hover_at(tester, Offset::new(794.0, 5.0));
1577                tester.pump();
1578
1579                let drawn = painted(tester);
1580                assert_track(
1581                    tester,
1582                    &drawn,
1583                    Rect::from_ltrb(756.0, 0.0, 800.0, 600.0),
1584                    0x08000000,
1585                    (Offset::new(756.0, 0.0), Offset::new(756.0, 600.0)),
1586                    K_DEFAULT_IDLE_THUMB_COLOR,
1587                );
1588                // Scrollbar thumb is larger; hover color
1589                assert_thumb_rrect(
1590                    tester,
1591                    Rect::from_ltrb(758.0, 0.0, 798.0, 90.0),
1592                    K_DEFAULT_THUMB_RADIUS,
1593                    0x80000000,
1594                );
1595            });
1596        }
1597    }
1598
1599    #[test]
1600    fn scrollbar_track_visibility_on_hovered() {
1601        for platform in DESKTOP {
1602            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1603                let theme = hover_track_theme(tester, false, None);
1604                let app = desktop_app(tester, theme);
1605                tester.pump_widget(app);
1606                tester.pump_and_settle();
1607                assert_thumb_rrect(
1608                    tester,
1609                    get_starting_thumb_rect(false),
1610                    K_DEFAULT_THUMB_RADIUS,
1611                    K_DEFAULT_IDLE_THUMB_COLOR,
1612                );
1613
1614                hover_at(tester, Offset::new(794.0, 5.0));
1615                tester.pump();
1616
1617                let drawn = painted(tester);
1618                assert_track(
1619                    tester,
1620                    &drawn,
1621                    Rect::from_ltrb(784.0, 0.0, 800.0, 600.0),
1622                    0x08000000,
1623                    (Offset::new(784.0, 0.0), Offset::new(784.0, 600.0)),
1624                    K_DEFAULT_IDLE_THUMB_COLOR,
1625                );
1626                // Scrollbar thumb is larger; hover color
1627                assert_thumb_rrect(
1628                    tester,
1629                    Rect::from_ltrb(786.0, 0.0, 798.0, 90.0),
1630                    K_DEFAULT_THUMB_RADIUS,
1631                    0x80000000,
1632                );
1633            });
1634        }
1635    }
1636
1637    #[test]
1638    fn adaptive_scrollbar() {
1639        test_widgets(|tester| {
1640            let view_with_scroll = |tester: &WidgetTester, platform: TargetPlatform| {
1641                let theme = ThemeData::builder()
1642                    .platform(platform)
1643                    .build(&tester.cell.borrow());
1644                build_boilerplate(Theme::new(
1645                    theme,
1646                    Scrollbar::new(scroll_view(None, 4000.0, 4000.0)),
1647                ))
1648            };
1649
1650            let tree = view_with_scroll(tester, TargetPlatform::Android);
1651            tester.pump_widget(tree);
1652            tester.drag_from(Offset::new(400.0, 300.0), Offset::new(0.0, -10.0), 1);
1653            tester.pump();
1654            // Scrollbar fully showing
1655            tester.pump_by(Duration::from_millis(500));
1656            assert!(paints_thumb(tester));
1657            expect(
1658                tester,
1659                &find::by_type::<CupertinoScrollbar>(),
1660                finds_nothing(),
1661            );
1662
1663            let tree = view_with_scroll(tester, TargetPlatform::IOS);
1664            tester.pump_widget(tree);
1665            expect(
1666                tester,
1667                &find::by_type::<CupertinoScrollbar>(),
1668                finds_one_widget(),
1669            );
1670            expect(
1671                tester,
1672                &find::by_type::<MaterialScrollbar>(),
1673                finds_nothing(),
1674            );
1675            tester.pump_and_settle();
1676
1677            // Only iOS adapts: macOS keeps the Material scrollbar.
1678            let tree = view_with_scroll(tester, TargetPlatform::MacOS);
1679            tester.pump_widget(tree);
1680            expect(
1681                tester,
1682                &find::by_type::<CupertinoScrollbar>(),
1683                finds_nothing(),
1684            );
1685            expect(
1686                tester,
1687                &find::by_type::<MaterialScrollbar>(),
1688                finds_one_widget(),
1689            );
1690        });
1691    }
1692
1693    #[test]
1694    fn scrollbar_passes_controller_to_cupertino_scrollbar() {
1695        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
1696            let controller = controller(tester);
1697            let theme = ThemeData::new(&tester.cell.borrow());
1698            tester.pump_widget(build_boilerplate(Theme::new(
1699                theme,
1700                Scrollbar::new(scroll_view(Some(controller.clone()), 4000.0, 4000.0))
1701                    .controller(controller.clone()),
1702            )));
1703            let cupertino = *find::by_type::<CupertinoScrollbar>()
1704                .evaluate(tester)
1705                .first()
1706                .expect("a Cupertino scrollbar on iOS");
1707            let passed = tester.widget(cupertino, |scrollbar: &CupertinoScrollbar| {
1708                scrollbar.raw_scrollbar_data().controller.clone()
1709            });
1710            assert_eq!(passed, Some(controller));
1711        });
1712    }
1713
1714    #[test]
1715    fn scrollbar_dragging_can_be_disabled() {
1716        test_widgets_variant(
1717            TargetPlatformVariant::only(TargetPlatform::Fuchsia),
1718            |tester| {
1719                let scroll_controller = controller(tester);
1720                let theme = m2(tester);
1721                tester.pump_widget(material_app(
1722                    theme,
1723                    PrimaryScrollController::new(
1724                        scroll_controller.clone(),
1725                        Scrollbar::new(scroll_view(None, 4000.0, 4000.0))
1726                            .interactive(false)
1727                            .thumb_visibility(true)
1728                            .controller(scroll_controller.clone()),
1729                    )
1730                    .into_widget(),
1731                ));
1732                tester.pump_and_settle();
1733                assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
1734                let drawn = painted(tester);
1735                assert_track(
1736                    tester,
1737                    &drawn,
1738                    Rect::from_ltrb(788.0, 0.0, 800.0, 600.0),
1739                    K_TRANSPARENT,
1740                    (Offset::new(788.0, 0.0), Offset::new(788.0, 600.0)),
1741                    K_TRANSPARENT,
1742                );
1743                assert_thumb_rrect(
1744                    tester,
1745                    get_starting_thumb_rect(false),
1746                    K_DEFAULT_THUMB_RADIUS,
1747                    K_DEFAULT_IDLE_THUMB_COLOR,
1748                );
1749
1750                // Try to drag the thumb down.
1751                const SCROLL_AMOUNT: f64 = 10.0;
1752                let mut drag_scrollbar_thumb_gesture =
1753                    start_gesture(tester, Offset::new(797.0, 45.0));
1754                tester.pump_and_settle();
1755                move_by(
1756                    tester,
1757                    &mut drag_scrollbar_thumb_gesture,
1758                    Offset::new(0.0, SCROLL_AMOUNT),
1759                );
1760                tester.pump_and_settle();
1761                tester.up(&drag_scrollbar_thumb_gesture);
1762                tester.pump_and_settle();
1763                // Dragging on the thumb does not change the offset.
1764                assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
1765
1766                // Drag in the track area to validate pass through to scrollable.
1767                let mut drag_pass_through_track = start_gesture(tester, Offset::new(797.0, 250.0));
1768                move_by(
1769                    tester,
1770                    &mut drag_pass_through_track,
1771                    Offset::new(0.0, -SCROLL_AMOUNT),
1772                );
1773                tester.pump_and_settle();
1774                tester.up(&drag_pass_through_track);
1775                tester.pump_and_settle();
1776                // The scroll view received the drag.
1777                assert_eq!(offset(tester, scroll_controller.handle()), SCROLL_AMOUNT);
1778
1779                // Tap on the track to validate the scroll view will not page.
1780                tester.tap_at(Offset::new(797.0, 200.0), 1);
1781                tester.pump_and_settle();
1782                // The offset should not have changed.
1783                assert_eq!(offset(tester, scroll_controller.handle()), SCROLL_AMOUNT);
1784            },
1785        );
1786    }
1787
1788    #[test]
1789    fn scrollbar_dragging_is_disabled_by_default_on_android() {
1790        test_widgets(|tester| {
1791            let tap_count = Rc::new(Cell::new(0));
1792            let scroll_controller = controller(tester);
1793            let theme = ThemeData::new(&tester.cell.borrow());
1794            let on_tap = {
1795                let tap_count = Rc::clone(&tap_count);
1796                Listener::new(move |_app: &mut App| tap_count.set(tap_count.get() + 1))
1797            };
1798            tester.pump_widget(material_app(
1799                theme,
1800                PrimaryScrollController::new(
1801                    scroll_controller.clone(),
1802                    Scrollbar::new(
1803                        SingleChildScrollView::new()
1804                            .drag_start_behavior(waft_gestures::DragStartBehavior::Down)
1805                            .child(
1806                                GestureDetector::new()
1807                                    .behavior(HitTestBehavior::Opaque)
1808                                    .on_tap(on_tap)
1809                                    .child(SizedBox::new().width(4000.0).height(4000.0)),
1810                            ),
1811                    )
1812                    .thumb_visibility(true)
1813                    .controller(scroll_controller.clone()),
1814                )
1815                .into_widget(),
1816            ));
1817            tester.pump_and_settle();
1818            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
1819            let border = (Offset::new(796.0, 0.0), Offset::new(796.0, 600.0));
1820            let drawn = painted(tester);
1821            assert_track(
1822                tester,
1823                &drawn,
1824                K_ANDROID_TRACK_DIMENSIONS,
1825                K_TRANSPARENT,
1826                border,
1827                K_TRANSPARENT,
1828            );
1829            assert_thumb_rect(
1830                &drawn,
1831                get_starting_thumb_rect(true),
1832                K_ANDROID_THUMB_IDLE_COLOR,
1833            );
1834
1835            // Try to drag the thumb down.
1836            const SCROLL_AMOUNT: f64 = 50.0;
1837            // Dart's `dragFrom(touchSlopY: 0.0)`: one move, with no slop to cross.
1838            let drag_without_slop = |tester: &mut WidgetTester, offset: Offset| {
1839                let mut gesture = start_gesture(tester, Offset::new(797.0, 45.0));
1840                move_by(tester, &mut gesture, offset);
1841                tester.up(&gesture);
1842            };
1843            drag_without_slop(tester, Offset::new(0.0, SCROLL_AMOUNT));
1844            tester.pump_and_settle();
1845            // Dragging on the thumb does not change the offset.
1846            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
1847            assert_eq!(tap_count.get(), 0);
1848
1849            // Try to drag up in the thumb area to validate pass through to scrollable.
1850            tester.drag_from(
1851                Offset::new(797.0, 45.0),
1852                Offset::new(0.0, -SCROLL_AMOUNT),
1853                1,
1854            );
1855            tester.pump_and_settle();
1856            // The scroll view received the drag.
1857            assert_eq!(offset(tester, scroll_controller.handle()), SCROLL_AMOUNT);
1858            assert_eq!(tap_count.get(), 0);
1859
1860            // Drag in the track area to validate pass through to scrollable.
1861            drag_without_slop(tester, Offset::new(0.0, -SCROLL_AMOUNT));
1862            tester.pump_and_settle();
1863            // The scroll view received the drag.
1864            assert_eq!(
1865                offset(tester, scroll_controller.handle()),
1866                SCROLL_AMOUNT * 2.0
1867            );
1868            assert_eq!(tap_count.get(), 0);
1869
1870            // Tap on the thumb to validate the scroll view receives a click.
1871            tester.tap_at(Offset::new(797.0, 45.0), 1);
1872            tester.pump_and_settle();
1873            assert_eq!(tap_count.get(), 1);
1874
1875            // Tap on the track to validate the scroll view will not page and receives a click.
1876            tester.tap_at(Offset::new(797.0, 400.0), 1);
1877            tester.pump_and_settle();
1878            // The offset should not have changed.
1879            assert_eq!(
1880                offset(tester, scroll_controller.handle()),
1881                SCROLL_AMOUNT * 2.0
1882            );
1883            assert_eq!(tap_count.get(), 2);
1884        });
1885    }
1886
1887    #[test]
1888    fn scrollbar_scroll_orientation_works_correctly() {
1889        test_widgets(|tester| {
1890            let scroll_controller = controller(tester);
1891            let theme = ThemeData::builder()
1892                .platform(TargetPlatform::Android)
1893                .build(&tester.cell.borrow());
1894            tester.pump_widget(build_boilerplate(Theme::new(
1895                theme,
1896                PrimaryScrollController::new(
1897                    scroll_controller.clone(),
1898                    Scrollbar::new(scroll_view(None, 4000.0, 4000.0))
1899                        .interactive(true)
1900                        .thumb_visibility(true)
1901                        .scrollbar_orientation(ScrollbarOrientation::Left)
1902                        .controller(scroll_controller),
1903                ),
1904            )));
1905            tester.pump_and_settle();
1906
1907            let drawn = painted(tester);
1908            assert_track(
1909                tester,
1910                &drawn,
1911                Rect::from_ltrb(0.0, 0.0, 4.0, 600.0),
1912                K_TRANSPARENT,
1913                (Offset::new(4.0, 0.0), Offset::new(4.0, 600.0)),
1914                K_TRANSPARENT,
1915            );
1916            assert_thumb_rect(
1917                &drawn,
1918                Rect::from_ltrb(0.0, 0.0, 4.0, 90.0),
1919                K_ANDROID_THUMB_IDLE_COLOR,
1920            );
1921        });
1922    }
1923
1924    #[test]
1925    fn scrollbar_does_not_crash_at_zero_area() {
1926        test_widgets(|tester| {
1927            let theme = ThemeData::new(&tester.cell.borrow());
1928            tester.pump_widget(material_app(
1929                theme,
1930                waft_widgets::Center::new()
1931                    .child(SizedBox::shrink().child(Scrollbar::new(SingleChildScrollView::new())))
1932                    .into_widget(),
1933            ));
1934            let scrollbar = *find::by_type::<Scrollbar>()
1935                .evaluate(tester)
1936                .first()
1937                .expect("the scrollbar");
1938            let app = tester.cell.borrow();
1939            let size = scrollbar
1940                .find_render_object(&app)
1941                .and_then(|render| render.as_box())
1942                .expect("a render box")
1943                .size(&app);
1944            assert_eq!(size, waft_embedder::Size::ZERO);
1945        });
1946    }
1947
1948    #[test]
1949    fn material_3_scrollbar_colors_come_from_the_color_scheme_on_surface() {
1950        test_widgets_variant(
1951            TargetPlatformVariant::only(TargetPlatform::Linux),
1952            |tester| {
1953                let theme = hover_track_theme(tester, true, None);
1954                let on_surface = theme.color_scheme.on_surface();
1955                let app = desktop_app(tester, theme);
1956                tester.pump_widget(app);
1957                tester.pump_and_settle();
1958                #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
1959                let idle = on_surface.with_opacity(0.1).to_argb32();
1960                assert_thumb_rrect(
1961                    tester,
1962                    get_starting_thumb_rect(false),
1963                    K_DEFAULT_THUMB_RADIUS,
1964                    idle,
1965                );
1966
1967                hover_at(tester, Offset::new(794.0, 5.0));
1968                tester.pump();
1969                #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
1970                let (track, border, hover) = (
1971                    on_surface.with_opacity(0.03).to_argb32(),
1972                    on_surface.with_opacity(0.1).to_argb32(),
1973                    on_surface.with_opacity(0.5).to_argb32(),
1974                );
1975                let drawn = painted(tester);
1976                assert_track(
1977                    tester,
1978                    &drawn,
1979                    Rect::from_ltrb(784.0, 0.0, 800.0, 600.0),
1980                    track,
1981                    (Offset::new(784.0, 0.0), Offset::new(784.0, 600.0)),
1982                    border,
1983                );
1984                assert_thumb_rrect(
1985                    tester,
1986                    Rect::from_ltrb(786.0, 0.0, 798.0, 90.0),
1987                    K_DEFAULT_THUMB_RADIUS,
1988                    hover,
1989                );
1990            },
1991        );
1992    }
1993
1994    #[test]
1995    fn a_hovered_thumb_without_a_track_fades_to_the_hover_color() {
1996        test_widgets_variant(
1997            TargetPlatformVariant::only(TargetPlatform::Windows),
1998            |tester| {
1999                let theme =
2000                    ThemeData::builder()
2001                        .use_material3(false)
2002                        .scrollbar_theme(ScrollbarThemeData::new().thumb_visibility(
2003                            <dyn WidgetStateProperty<Option<bool>>>::all(Some(true)),
2004                        ))
2005                        .build(&tester.cell.borrow());
2006                let app = desktop_app(tester, theme);
2007                tester.pump_widget(app);
2008                tester.pump_and_settle();
2009
2010                let mouse = hover_at(tester, Offset::new(794.0, 5.0));
2011                assert_eq!(mouse.kind, PointerDeviceKind::Mouse);
2012                // Halfway through the 200ms hover animation the thumb is halfway between the
2013                // idle and the hover colour.
2014                tester.pump();
2015                tester.pump_by(Duration::from_millis(100));
2016                let halfway = Color::lerp(
2017                    Some(Color::new(K_DEFAULT_IDLE_THUMB_COLOR)),
2018                    Some(Color::new(0x80000000)),
2019                    0.5,
2020                )
2021                .expect("both colors are given")
2022                .to_argb32();
2023                assert_thumb_rrect(
2024                    tester,
2025                    get_starting_thumb_rect(false),
2026                    K_DEFAULT_THUMB_RADIUS,
2027                    halfway,
2028                );
2029            },
2030        );
2031    }
2032
2033    // 'MaterialScrollBehavior flings on different platforms'.
2034    #[test]
2035    fn material_scroll_behavior_flings_on_different_platforms() {
2036        test_widgets(|tester| {
2037            let get_scroll_offset = |tester: &WidgetTester| {
2038                let viewport = *tester.all::<RenderViewport>().last().expect("a viewport");
2039                let app = tester.cell.borrow();
2040                viewport.offset(&app).pixels(&app)
2041            };
2042            let reset_scroll_offset = |tester: &WidgetTester| {
2043                let viewport = tester.first::<RenderViewport>();
2044                let mut app = tester.cell.borrow_mut();
2045                let position = viewport.offset(&app);
2046                position.jump_to(&mut app, 0.0);
2047            };
2048            let pump_test = |tester: &mut WidgetTester, platform: TargetPlatform| {
2049                let theme = ThemeData::builder()
2050                    .platform(platform)
2051                    .build(&tester.cell.borrow());
2052                let every_kind = HashSet::from([
2053                    PointerDeviceKind::Touch,
2054                    PointerDeviceKind::Mouse,
2055                    PointerDeviceKind::Stylus,
2056                    PointerDeviceKind::InvertedStylus,
2057                    PointerDeviceKind::Trackpad,
2058                    PointerDeviceKind::Unknown,
2059                ]);
2060                tester.pump_widget(
2061                    MaterialApp::new()
2062                        .scroll_behavior(ScrollBehaviorRef::new(
2063                            ScrollBehaviorRef::new(NoScrollbarBehavior)
2064                                .copy_with()
2065                                .drag_devices(every_kind),
2066                        ))
2067                        .theme(theme)
2068                        .home(
2069                            CustomScrollView::new().slivers([SliverToBoxAdapter::new()
2070                                .child(SizedBox::new().height(2000.0))
2071                                .into_widget()]),
2072                        )
2073                        .into_widget(),
2074                );
2075                tester.pump_by(Duration::from_secs(5)); // to let the theme animate
2076            };
2077            let fling = |tester: &mut WidgetTester| {
2078                let scrollable = *find::by_type::<Scrollable>()
2079                    .evaluate(tester)
2080                    .first()
2081                    .expect("a scrollable");
2082                let center = tester.get_rect(scrollable).center();
2083                tester.fling_from(center, Offset::new(0.0, -DRAG_OFFSET), 1000.0, 1);
2084            };
2085
2086            const DRAG_OFFSET: f64 = 200.0;
2087
2088            pump_test(tester, TargetPlatform::Android);
2089            fling(tester);
2090            assert_eq!(get_scroll_offset(tester), DRAG_OFFSET);
2091            tester.pump(); // trigger fling
2092            assert_eq!(get_scroll_offset(tester), DRAG_OFFSET);
2093            tester.pump_by(Duration::from_secs(5));
2094            let android_result = get_scroll_offset(tester);
2095
2096            reset_scroll_offset(tester);
2097
2098            pump_test(tester, TargetPlatform::IOS);
2099            fling(tester);
2100            // Scroll starts ease into the scroll on iOS.
2101            assert!((get_scroll_offset(tester) - 197.16666666666669).abs() < 1e-10);
2102            tester.pump(); // trigger fling
2103            assert!((get_scroll_offset(tester) - 197.16666666666669).abs() < 1e-10);
2104            tester.pump_by(Duration::from_secs(5));
2105            let ios_result = get_scroll_offset(tester);
2106
2107            reset_scroll_offset(tester);
2108
2109            pump_test(tester, TargetPlatform::MacOS);
2110            fling(tester);
2111            // Scroll starts ease into the scroll on iOS.
2112            assert!((get_scroll_offset(tester) - 197.16666666666669).abs() < 1e-10);
2113            tester.pump(); // trigger fling
2114            assert!((get_scroll_offset(tester) - 197.16666666666669).abs() < 1e-10);
2115            tester.pump_by(Duration::from_secs(5));
2116            let mac_os_result = get_scroll_offset(tester);
2117
2118            // Android is slipperier than MacOS, so the scroll offset should be greater.
2119            assert!(android_result > mac_os_result);
2120            // iOS is slipperier than Android, so the scroll offset should be greater.
2121            assert!(ios_result > android_result);
2122            // iOS is slipperier than MacOS, so the scroll offset should be greater.
2123            assert!(ios_result > mac_os_result);
2124        });
2125    }
2126
2127    // "Scrollbar doesn't show when tapping list".
2128    #[test]
2129    fn scrollbar_does_not_show_when_tapping_list() {
2130        test_widgets(|tester| {
2131            let rows = (0..8).map(|index| {
2132                SizedBox::new()
2133                    .height(40.0)
2134                    .child(Text::new(index.to_string()))
2135                    .into_widget()
2136            });
2137            tester.pump_widget(build_boilerplate(
2138                Center::new().child(
2139                    Container::new()
2140                        .decoration(BoxDecoration::new().border(Border::all(
2141                            Color::new(0xFFFFFF00),
2142                            1.0,
2143                            BorderStyle::Solid,
2144                            BorderSide::STROKE_ALIGN_INSIDE,
2145                        )))
2146                        .height(200.0)
2147                        .width(300.0)
2148                        .child(Scrollbar::new(ListView::new().children(rows))),
2149                ),
2150            ));
2151
2152            let transient_callback_count = |tester: &WidgetTester| {
2153                SchedulerBinding::transient_callback_count(&mut tester.cell.borrow_mut())
2154            };
2155            assert_eq!(
2156                transient_callback_count(tester),
2157                0,
2158                "Building a list with a scrollbar triggered an animation."
2159            );
2160            let list = *find::by_type::<ListView>()
2161                .evaluate(tester)
2162                .first()
2163                .expect("a list");
2164            let center = tester.get_rect(list).center();
2165            tester.tap_at(center, 1);
2166            assert_eq!(
2167                transient_callback_count(tester),
2168                0,
2169                "Tapping a block with a scrollbar triggered an animation."
2170            );
2171            for _ in 0..4 {
2172                tester.pump_by(Duration::from_millis(200));
2173            }
2174            tester.drag_from(center, Offset::new(0.0, -10.0), 1);
2175            assert!(transient_callback_count(tester) > 0);
2176            for _ in 0..4 {
2177                tester.pump_by(Duration::from_millis(200));
2178            }
2179        });
2180    }
2181
2182    // 'ScrollbarPainter does not divide by zero'.
2183    #[test]
2184    fn scrollbar_painter_does_not_divide_by_zero() {
2185        test_widgets(|tester| {
2186            tester.pump_widget(build_boilerplate(
2187                SizedBox::new()
2188                    .height(200.0)
2189                    .width(300.0)
2190                    .child(Scrollbar::new(
2191                        ListView::new().children([SizedBox::new()
2192                            .height(40.0)
2193                            .child(Text::new("0"))
2194                            .into_widget()]),
2195                    )),
2196            ));
2197
2198            let scroll_painter = {
2199                let state = material_state(tester);
2200                RawScrollbarState::scrollbar_painter(state, &tester.cell.borrow())
2201            };
2202            // Dragging makes the scrollbar first appear.
2203            let text = *find::text("0").evaluate(tester).first().expect("the text");
2204            let center = tester.get_rect(text).center();
2205            tester.drag_from(center, Offset::new(0.0, -10.0), 1);
2206            tester.pump_by(Duration::from_millis(200));
2207            tester.pump_by(Duration::from_millis(200));
2208
2209            let mut app = tester.cell.borrow_mut();
2210            let metrics = FixedScrollMetrics::new(
2211                Some(0.0),
2212                Some(0.0),
2213                Some(0.0),
2214                Some(100.0),
2215                AxisDirection::Down,
2216                2.0,
2217            );
2218            scroll_painter.update(&mut app, Rc::new(metrics), AxisDirection::Down);
2219
2220            let mut canvas = Canvas::new();
2221            scroll_painter.paint(&mut app, &mut canvas, Size::new(10.0, 100.0));
2222
2223            // Scrollbar is not supposed to draw anything if there isn't enough content.
2224            assert!(canvas.build().ops().is_empty());
2225        });
2226    }
2227
2228    // 'When thumbVisibility is true, must pass a controller or find PrimaryScrollController'
2229    // (Dart runs the case twice).
2230    #[test]
2231    #[should_panic(
2232        expected = "A ScrollController is required when Scrollbar.thumbVisibility is true."
2233    )]
2234    fn when_thumb_visibility_is_true_must_pass_a_controller_or_find_primary_scroll_controller() {
2235        test_widgets(|tester| {
2236            let theme = ThemeData::new(&tester.cell.borrow());
2237            tester.pump_widget(build_boilerplate(Theme::new(
2238                theme,
2239                Scrollbar::new(scroll_view(None, 4000.0, 4000.0)).thumb_visibility(true),
2240            )));
2241        });
2242    }
2243
2244    // 'When thumbVisibility is true, must pass a controller that is attached to a scroll view
2245    // or find PrimaryScrollController' (Dart runs the case twice).
2246    #[test]
2247    #[should_panic(expected = "The Scrollbar's ScrollController has no ScrollPosition attached.")]
2248    fn when_thumb_visibility_is_true_must_pass_a_controller_that_is_attached_to_a_scroll_view() {
2249        test_widgets(|tester| {
2250            let controller = controller(tester);
2251            let theme = ThemeData::new(&tester.cell.borrow());
2252            tester.pump_widget(build_boilerplate(Theme::new(
2253                theme,
2254                Scrollbar::new(scroll_view(None, 4000.0, 4000.0))
2255                    .thumb_visibility(true)
2256                    .controller(controller),
2257            )));
2258        });
2259    }
2260
2261    // 'Scrollbar.thumbVisibility triggers assertion when multiple ScrollPositions are
2262    // attached.'
2263    #[test]
2264    fn thumb_visibility_panics_when_the_controller_has_two_positions() {
2265        fn get_tab_content(scroll_controller: Option<ScrollControllerRef>) -> WidgetRef {
2266            let list =
2267                ListView::builder(|_app, _context, _index| Some(Text::new("Test").into_widget()))
2268                    .item_count(200)
2269                    .build();
2270            let list = match scroll_controller.clone() {
2271                Some(controller) => list.controller(controller),
2272                None => list,
2273            };
2274            let scrollbar = Scrollbar::new(list).thumb_visibility(true);
2275            match scroll_controller {
2276                Some(controller) => scrollbar.controller(controller),
2277                None => scrollbar,
2278            }
2279            .into_widget()
2280        }
2281
2282        fn build_app(
2283            tester: &WidgetTester,
2284            scroll_controller: Option<ScrollControllerRef>,
2285        ) -> WidgetRef {
2286            let theme = ThemeData::new(&tester.cell.borrow());
2287            material_app(
2288                theme,
2289                crate::tab_controller::DefaultTabController::new(
2290                    2,
2291                    Scaffold::new().body(crate::tabs::TabBarView::new([
2292                        get_tab_content(scroll_controller.clone()),
2293                        get_tab_content(scroll_controller),
2294                    ])),
2295                )
2296                .into_widget(),
2297            )
2298        }
2299
2300        /// The panic message of swiping to the second tab, resulting in two attached
2301        /// ScrollPositions during the transition: Dart's `tester.drag` and `pump`, then
2302        /// `tester.takeException()`.
2303        fn swipe_and_take_exception(tester: &mut WidgetTester) -> String {
2304            let first = find::text("Test").evaluate(tester)[0];
2305            let center = {
2306                let render = tester.render_box_of(first);
2307                let app = tester.cell.borrow();
2308                let size = render.size(&app);
2309                render.local_to_global(&app, size.center(Offset::ZERO), None)
2310            };
2311            let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2312                tester.drag_from(center, Offset::new(-100.0, 0.0), 1);
2313                tester.pump();
2314            }))
2315            .expect_err("two attached positions panic");
2316            panicked
2317                .downcast_ref::<String>()
2318                .cloned()
2319                .or_else(|| panicked.downcast_ref::<&str>().map(|text| text.to_string()))
2320                .expect("a panic message")
2321        }
2322
2323        test_widgets(|tester| {
2324            // Asserts when using the PrimaryScrollController.
2325            let app = build_app(tester, None);
2326            tester.pump_widget(app);
2327            assert_eq!(
2328                swipe_and_take_exception(tester),
2329                "The PrimaryScrollController is attached to more than one ScrollPosition.\n\
2330                 The Scrollbar requires a single ScrollPosition in order to be painted.\n\
2331                 When Scrollbar.thumbVisibility is true, the associated ScrollController must \
2332                 only have one ScrollPosition attached.\n\
2333                 If a ScrollController has not been provided, the PrimaryScrollController is \
2334                 used by default on mobile platforms for ScrollViews with an Axis.vertical \
2335                 scroll direction.\n\
2336                 More than one ScrollView may have tried to use the PrimaryScrollController of \
2337                 the current context. ScrollView.primary can override this behavior."
2338            );
2339        });
2340        test_widgets(|tester| {
2341            // Asserts when using the ScrollController provided by the user; Dart's second app
2342            // has its own key, so a fresh tester stands for it.
2343            let scroll_controller = controller(tester);
2344            let app = build_app(tester, Some(scroll_controller.clone()));
2345            tester.pump_widget(app);
2346            assert_eq!(
2347                swipe_and_take_exception(tester),
2348                "The provided ScrollController is attached to more than one ScrollPosition.\n\
2349                 The Scrollbar requires a single ScrollPosition in order to be painted.\n\
2350                 When Scrollbar.thumbVisibility is true, the associated ScrollController must \
2351                 only have one ScrollPosition attached.\n\
2352                 The provided ScrollController cannot be shared by multiple ScrollView widgets."
2353            );
2354        });
2355    }
2356
2357    /// The toggle cases' tree: a `Scaffold` whose `FloatingActionButton` flips the
2358    /// scrollbar's `thumbVisibility`, which starts as `thumb_visibility`.
2359    fn toggled_view(controller: ScrollControllerRef, thumb_visibility: bool) -> WidgetRef {
2360        let thumb_visibility = Rc::new(Cell::new(thumb_visibility));
2361        build_boilerplate(StatefulBuilder::new(move |app, _context, set_state| {
2362            let toggled = Rc::clone(&thumb_visibility);
2363            Theme::new(
2364                ThemeData::new(app),
2365                Scaffold::new()
2366                    .floating_action_button(
2367                        FloatingActionButton::new(Some(Listener::new(move |app: &mut App| {
2368                            let toggled = Rc::clone(&toggled);
2369                            set_state(app, &mut move |_app| toggled.set(!toggled.get()));
2370                        })))
2371                        .child(Icon::new(Some(Icons::threed_rotation()))),
2372                    )
2373                    .body(
2374                        Scrollbar::new(scroll_view(Some(controller.clone()), 4000.0, 4000.0))
2375                            .thumb_visibility(thumb_visibility.get())
2376                            .controller(controller.clone()),
2377                    ),
2378            )
2379            .into_widget()
2380        }))
2381    }
2382
2383    /// Dart's `tester.fling(find.byType(SingleChildScrollView), Offset(0.0, -10.0), 10)`.
2384    fn fling_scroll_view(tester: &mut WidgetTester) {
2385        let view = *find::by_type::<SingleChildScrollView>()
2386            .evaluate(tester)
2387            .first()
2388            .expect("the scroll view");
2389        let center = tester.get_rect(view).center();
2390        tester.fling_from(center, Offset::new(0.0, -10.0), 10.0, 1);
2391    }
2392
2393    /// Dart's `tester.tap(find.byType(FloatingActionButton))`.
2394    fn tap_floating_action_button(tester: &mut WidgetTester) {
2395        let button = *find::by_type::<FloatingActionButton>()
2396            .evaluate(tester)
2397            .first()
2398            .expect("the button");
2399        let center = tester.get_rect(button).center();
2400        tester.tap_at(center, 2);
2401    }
2402
2403    // 'With thumbVisibility: true, fling a scroll. While it is still scrolling, set
2404    // thumbVisibility: false. The thumb should not fade out until the scrolling stops.'
2405    #[test]
2406    fn with_thumb_visibility_true_the_thumb_does_not_fade_out_until_a_fling_stops() {
2407        test_widgets(|tester| {
2408            let controller = controller(tester);
2409            tester.pump_widget(toggled_view(controller.clone(), true));
2410            tester.pump_and_settle();
2411            fling_scroll_view(tester);
2412            assert!(paints_thumb(tester));
2413
2414            tap_floating_action_button(tester);
2415            tester.pump_and_settle();
2416            // Scrollbar is not showing after scroll finishes
2417            assert!(!paints_thumb(tester));
2418        });
2419    }
2420
2421    // 'With thumbVisibility: false, set thumbVisibility: true. The thumb should be always
2422    // shown directly'.
2423    #[test]
2424    fn with_thumb_visibility_false_setting_it_true_shows_the_thumb_directly() {
2425        test_widgets(|tester| {
2426            let controller = controller(tester);
2427            tester.pump_widget(toggled_view(controller.clone(), false));
2428            tester.pump_and_settle();
2429            assert!(!paints_thumb(tester));
2430
2431            tap_floating_action_button(tester);
2432            tester.pump_and_settle();
2433            // Scrollbar is not showing after scroll finishes
2434            assert!(paints_thumb(tester));
2435        });
2436    }
2437
2438    // 'With thumbVisibility: false, fling a scroll. While it is still scrolling, set
2439    // thumbVisibility: true. The thumb should not fade even after the scrolling stops'.
2440    #[test]
2441    fn with_thumb_visibility_false_setting_it_true_during_a_fling_keeps_the_thumb() {
2442        test_widgets(|tester| {
2443            let controller = controller(tester);
2444            tester.pump_widget(toggled_view(controller.clone(), false));
2445            tester.pump_and_settle();
2446            assert!(!paints_thumb(tester));
2447            fling_scroll_view(tester);
2448            assert!(paints_thumb(tester));
2449
2450            tap_floating_action_button(tester);
2451            tester.pump();
2452            assert!(paints_thumb(tester));
2453
2454            // Wait for the timer delay to expire.
2455            tester.pump_by(Duration::from_millis(600)); // _kScrollbarTimeToFade
2456            tester.pump_and_settle();
2457            // Scrollbar thumb is showing after scroll finishes and timer ends.
2458            assert!(paints_thumb(tester));
2459        });
2460    }
2461
2462    /// What the scrollbar under the `Scrollbar` keyed `key` paints over its child, whether
2463    /// it adapted to a `CupertinoScrollbar` or not.
2464    fn painted_under(tester: &WidgetTester, key: &GlobalKey) -> Vec<Op> {
2465        let keyed = key
2466            .current_context(&tester.cell.borrow_mut())
2467            .expect("the keyed scrollbar is mounted");
2468        let raw = tester
2469            .elements()
2470            .into_iter()
2471            .find(|element| {
2472                let app = tester.cell.borrow();
2473                let widget = element.widget(&app);
2474                let is_raw = waft_widgets::downcast_widget::<MaterialScrollbar>(&**widget)
2475                    .is_some()
2476                    || waft_widgets::downcast_widget::<CupertinoScrollbar>(&**widget).is_some();
2477                drop(app);
2478                is_raw && tester.ancestor_of_type::<Scrollbar>(*element) == keyed
2479            })
2480            .expect("the keyed scrollbar's raw scrollbar");
2481        let app = tester.cell.borrow();
2482        if let Some(state) = raw.state_handle::<MaterialScrollbarState>(&app) {
2483            drop(app);
2484            return painted_by(tester, state);
2485        }
2486        let state = raw
2487            .state_handle::<CupertinoScrollbarState>(&app)
2488            .expect("a Cupertino scrollbar's state");
2489        drop(app);
2490        painted_by(tester, state)
2491    }
2492
2493    // "Scrollbar doesn't show when scroll the inner scrollable widget".
2494    #[test]
2495    fn scrollbar_does_not_show_when_scroll_the_inner_scrollable_widget() {
2496        for platform in ALL_PLATFORMS {
2497            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2498                let key1 = GlobalKey::new();
2499                let key2 = GlobalKey::new();
2500                let outer_key = GlobalKey::new();
2501                let inner_key = GlobalKey::new();
2502
2503                let theme = ThemeData::light(&tester.cell.borrow(), None);
2504                let theme_platform = theme.platform;
2505
2506                tester.pump_widget(
2507                    Theme::new(
2508                        theme,
2509                        Directionality::new(
2510                            waft_embedder::TextDirection::Ltr,
2511                            MediaQuery::new(
2512                                MediaQueryData::new(),
2513                                no_scrollbar(
2514                                    Scrollbar::new(
2515                                        SingleChildScrollView::new()
2516                                            .key(outer_key.clone().into())
2517                                            .child(
2518                                                SizedBox::new()
2519                                                    .height(1000.0)
2520                                                    .width(f64::INFINITY)
2521                                                    .child(Column::new().children([
2522                                                        Scrollbar::new(
2523                                                            SizedBox::new()
2524                                                                .height(300.0)
2525                                                                .width(f64::INFINITY)
2526                                                                .child(
2527                                                                    SingleChildScrollView::new()
2528                                                                        .key(inner_key.clone().into())
2529                                                                        .child(
2530                                                                            SizedBox::new()
2531                                                                                .key(
2532                                                                                    waft_foundation::ValueKey::new(
2533                                                                                        "Inner scrollable".to_owned(),
2534                                                                                    )
2535                                                                                    .into(),
2536                                                                                )
2537                                                                                .height(1000.0)
2538                                                                                .width(f64::INFINITY),
2539                                                                        ),
2540                                                                ),
2541                                                        )
2542                                                        .key(key1.clone().into())
2543                                                        .into_widget(),
2544                                                    ])),
2545                                            ),
2546                                    )
2547                                    .key(key2.clone().into()),
2548                                ),
2549                            )
2550                            .into_widget(),
2551                        ),
2552                    )
2553                    .into_widget(),
2554                );
2555
2556                // Drag the inner scrollable widget.
2557                let inner = tester.render_object(&inner_key).as_box().expect("a box");
2558                let center = tester.global_rect(inner).center();
2559                tester.drag_from(center, Offset::new(0.0, -25.0), 1);
2560                tester.pump();
2561                // Scrollbar fully showing.
2562                tester.pump_by(Duration::from_millis(500));
2563
2564                // Valo records no op for the transparent track and its border, which Dart's
2565                // `paintsExactlyCountTimes` counts: what is left is the thumb, and the outer
2566                // scrollbar draws nothing (Dart's counts on `key2` take in `key1`'s draws).
2567                assert!(draws(&painted_under(tester, &key2)).is_empty());
2568                let inner_drawn = painted_under(tester, &key1);
2569                match theme_platform {
2570                    TargetPlatform::Android => {
2571                        // On android, draws two rectangles for the track and thumb.
2572                        paints_exactly(&draws(&inner_drawn), &[PaintCall::rect(None)]).unwrap();
2573                    }
2574                    TargetPlatform::IOS
2575                    | TargetPlatform::Fuchsia
2576                    | TargetPlatform::Linux
2577                    | TargetPlatform::MacOS
2578                    | TargetPlatform::Windows => {
2579                        // Draws a rectangle for the track and a rounded rectangle for the thumb.
2580                        paints_exactly(&draws(&inner_drawn), &[PaintCall::rrect(None)]).unwrap();
2581                    }
2582                }
2583            });
2584        }
2585    }
2586
2587    // 'Simultaneous dragging and pointer scrolling does not cause a crash'.
2588    #[test]
2589    fn simultaneous_dragging_and_pointer_scrolling_does_not_cause_a_crash() {
2590        test_widgets(|tester| {
2591            // Regression test for https://github.com/flutter/flutter/issues/70105
2592            let scroll_controller = controller(tester);
2593            let theme = m2(tester);
2594            tester.pump_widget(material_app(
2595                theme,
2596                PrimaryScrollController::new(
2597                    scroll_controller.clone(),
2598                    Scrollbar::new(scroll_view(None, 4000.0, 4000.0))
2599                        .interactive(true)
2600                        .thumb_visibility(true)
2601                        .controller(scroll_controller.clone()),
2602                )
2603                .into_widget(),
2604            ));
2605            tester.pump_and_settle();
2606            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
2607            let border = (Offset::new(796.0, 0.0), Offset::new(796.0, 600.0));
2608            let assert_painted = |tester: &WidgetTester, thumb: Rect, color: u32| {
2609                let drawn = painted(tester);
2610                assert_track(
2611                    tester,
2612                    &drawn,
2613                    K_ANDROID_TRACK_DIMENSIONS,
2614                    K_TRANSPARENT,
2615                    border,
2616                    K_TRANSPARENT,
2617                );
2618                assert_thumb_rect(&drawn, thumb, color);
2619            };
2620            assert_painted(
2621                tester,
2622                get_starting_thumb_rect(true),
2623                K_ANDROID_THUMB_IDLE_COLOR,
2624            );
2625
2626            // Drag the thumb down to scroll down.
2627            const SCROLL_AMOUNT: f64 = 10.0;
2628            let mut drag_scrollbar_gesture = start_gesture(tester, Offset::new(797.0, 45.0));
2629            tester.pump_and_settle();
2630
2631            // Drag color
2632            assert_painted(tester, get_starting_thumb_rect(true), 0x99000000);
2633
2634            move_by(
2635                tester,
2636                &mut drag_scrollbar_gesture,
2637                Offset::new(0.0, SCROLL_AMOUNT),
2638            );
2639            tester.pump_and_settle();
2640            assert!(offset(tester, scroll_controller.handle()) > 10.0);
2641            let previous_offset = offset(tester, scroll_controller.handle());
2642            assert_painted(
2643                tester,
2644                Rect::from_ltrb(796.0, 10.0, 800.0, 100.0),
2645                0x99000000,
2646            );
2647
2648            // Execute a pointer scroll while dragging (drag gesture has not come up yet)
2649            let pointer_scroll = |tester: &mut WidgetTester, at: Offset, delta: Offset| {
2650                let mut app = tester.cell.borrow_mut();
2651                GestureBinding::instance(&mut app).handle_pointer_event(
2652                    &mut app,
2653                    PointerEvent::Scroll(PointerScrollEvent {
2654                        kind: PointerDeviceKind::Mouse,
2655                        device: 2,
2656                        position: at,
2657                        scroll_delta: delta,
2658                        ..PointerScrollEvent::default()
2659                    }),
2660                );
2661                app.drain_microtasks();
2662            };
2663            pointer_scroll(tester, Offset::new(798.0, 15.0), Offset::new(0.0, 20.0));
2664            tester.pump_and_settle();
2665
2666            // Scrolling while holding the drag on the scrollbar and still hovered over
2667            // the scrollbar should not have changed the scroll offset.
2668            assert_eq!(offset(tester, scroll_controller.handle()), previous_offset);
2669            assert_painted(
2670                tester,
2671                Rect::from_ltrb(796.0, 10.0, 800.0, 100.0),
2672                0x99000000,
2673            );
2674
2675            // Drag is still being held, move pointer to be hovering over another area
2676            // of the scrollable (not over the scrollbar) and execute another pointer scroll
2677            let view = *find::by_type::<SingleChildScrollView>()
2678                .evaluate(tester)
2679                .first()
2680                .expect("the scroll view");
2681            let center = tester.get_rect(view).center();
2682            assert_eq!(center, Offset::new(400.0, 300.0));
2683            pointer_scroll(tester, center, Offset::new(0.0, -90.0));
2684            tester.pump_and_settle();
2685            // Scrolling while holding the drag on the scrollbar changed the offset
2686            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
2687            assert_painted(tester, Rect::from_ltrb(796.0, 0.0, 800.0, 90.0), 0x99000000);
2688
2689            tester.up(&drag_scrollbar_gesture);
2690            tester.pump_and_settle();
2691            assert_eq!(offset(tester, scroll_controller.handle()), 0.0);
2692            assert_painted(tester, Rect::from_ltrb(796.0, 0.0, 800.0, 90.0), 0xffbcbcbc);
2693        });
2694    }
2695
2696    /// Dart's collector frees the hover controller `_MaterialScrollbarState` makes once the
2697    /// state is gone; here it is freed with the state's reference to it.
2698    #[test]
2699    fn a_disposed_scrollbar_frees_its_hover_controller() {
2700        test_widgets(|tester| {
2701            let controller = controller(tester);
2702            let theme = ThemeData::new(&tester.cell.borrow());
2703            tester.pump_widget(build_boilerplate(Theme::new(
2704                theme,
2705                Scrollbar::new(scroll_view(Some(controller.clone()), 4000.0, 4000.0))
2706                    .controller(controller),
2707            )));
2708            let hover = {
2709                let scrollbar = find::by_type::<MaterialScrollbar>().evaluate(tester)[0];
2710                let app = tester.cell.borrow();
2711                scrollbar
2712                    .state_handle::<MaterialScrollbarState>(&app)
2713                    .expect("a MaterialScrollbar is stateful")
2714                    .hover_animation_controller(&app)
2715            };
2716
2717            tester.pump_widget(SizedBox::new().into_widget());
2718            tester.cell.checkpoint();
2719            assert!(!tester.cell.borrow().contains(hover));
2720        });
2721    }
2722}