Skip to main content

waft_widgets/widgets/
sliver_fill.rs

1//! Flutter counterpart: `widgets/sliver_fill.dart`.
2//!
3//! `SliverFillRemaining.debugFillProperties` waits for diagnostics.
4
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_embedder::{Matrix4, Offset, clamp_double};
9use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, IterableProperty};
10use waft_painting::{Axis, EdgeInsets};
11use waft_rendering::{
12    AnyRenderObject, AnyRenderSliver, PaintingContext, RenderHandle, RenderObject,
13    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin, RenderSliver,
14    RenderSliverData, RenderSliverEdgeInsetsPadding, RenderSliverFillRemaining,
15    RenderSliverFillRemainingAndOverscroll, RenderSliverFillRemainingWithScrollable,
16    RenderSliverFillViewport, SliverConstraints, SliverHitTestResult,
17};
18
19use crate::framework::{
20    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget,
21    StatelessWidget, WidgetRef,
22};
23use crate::widgets::scroll_delegate::SliverChildDelegateRef;
24use crate::widgets::sliver::{
25    SliverMultiBoxAdaptorWidget, SliverWithKeepAliveWidget, child_manager_of,
26};
27
28/// A sliver that contains multiple box children that each fills the viewport.
29///
30/// _To learn more about slivers, see `CustomScrollView::slivers`._
31///
32/// [`SliverFillViewport`] places its children in a linear array along the main axis. Each child
33/// is sized to fill the viewport, both in the main and cross axis.
34///
35/// See also:
36///
37///  * [`crate::SliverFixedExtentList`], which has a configurable
38///    [`item_extent`](crate::SliverFixedExtentList::item_extent).
39///  * `SliverPrototypeExtentList`, which is similar to [`crate::SliverFixedExtentList`] except
40///    that it uses a prototype list item instead of a pixel value to define the main axis extent
41///    of each item.
42///  * [`crate::SliverList`], which does not require its children to have the same extent in the
43///    main axis.
44#[derive(Debug)]
45pub struct SliverFillViewport {
46    pub key: Option<KeyRef>,
47
48    /// The fraction of the viewport that each child should fill in the main axis.
49    ///
50    /// If this fraction is less than 1.0, more than one child will be visible at once. If this
51    /// fraction is greater than 1.0, each child will be larger than the viewport in the main
52    /// axis.
53    pub viewport_fraction: f64,
54
55    /// Whether to add padding to both ends of the list.
56    ///
57    /// If this is set to true and [`viewport_fraction`](Self::viewport_fraction) < 1.0, padding
58    /// will be added such that the first and last child slivers will be in the center of the
59    /// viewport when scrolled all the way to the start or end, respectively. You may want to set
60    /// this to false if this [`SliverFillViewport`] is not the only widget along this main axis,
61    /// such as in a `CustomScrollView` with multiple children.
62    ///
63    /// If [`viewport_fraction`](Self::viewport_fraction) is greater than one, this option has no
64    /// effect. Defaults to true.
65    pub pad_ends: bool,
66
67    /// The delegate that provides the children for this widget.
68    pub delegate: SliverChildDelegateRef,
69
70    /// Whether the pages answer implicit scrolling, as `PageView::allow_implicit_scrolling`
71    /// describes.
72    pub allow_implicit_scrolling: bool,
73}
74
75impl SliverFillViewport {
76    /// Creates a sliver whose box children that each fill the viewport.
77    pub fn new(delegate: SliverChildDelegateRef) -> SliverFillViewport {
78        SliverFillViewport {
79            key: None,
80            viewport_fraction: 1.0,
81            pad_ends: true,
82            delegate,
83            allow_implicit_scrolling: true,
84        }
85    }
86
87    /// Dart `SliverFillViewport(key:)`.
88    pub fn key(mut self, key: KeyRef) -> SliverFillViewport {
89        self.key = Some(key);
90        self
91    }
92
93    /// Dart `SliverFillViewport(viewportFraction:)`.
94    pub fn viewport_fraction(mut self, viewport_fraction: f64) -> SliverFillViewport {
95        debug_assert!(viewport_fraction > 0.0);
96        self.viewport_fraction = viewport_fraction;
97        self
98    }
99
100    /// Dart `SliverFillViewport(padEnds:)`.
101    pub fn pad_ends(mut self, pad_ends: bool) -> SliverFillViewport {
102        self.pad_ends = pad_ends;
103        self
104    }
105
106    /// Dart `SliverFillViewport(allowImplicitScrolling:)`.
107    pub fn allow_implicit_scrolling(
108        mut self,
109        allow_implicit_scrolling: bool,
110    ) -> SliverFillViewport {
111        self.allow_implicit_scrolling = allow_implicit_scrolling;
112        self
113    }
114}
115
116impl StatelessWidget for SliverFillViewport {
117    fn key(&self) -> Option<&KeyRef> {
118        self.key.as_ref()
119    }
120
121    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
122        let viewport_fraction = if self.pad_ends {
123            clamp_double(1.0 - self.viewport_fraction, 0.0, 1.0) / 2.0
124        } else {
125            0.0
126        };
127        SliverFractionalPadding::new(viewport_fraction)
128            .sliver(SliverFillViewportRenderObjectWidget::new(
129                Rc::clone(&self.delegate),
130                self.viewport_fraction,
131                self.allow_implicit_scrolling,
132            ))
133            .into_widget()
134    }
135}
136
137/// Dart's `_SliverFillViewportRenderObjectWidget`.
138#[derive(Debug)]
139struct SliverFillViewportRenderObjectWidget {
140    delegate: SliverChildDelegateRef,
141    viewport_fraction: f64,
142    allow_implicit_scrolling: bool,
143}
144
145impl SliverFillViewportRenderObjectWidget {
146    fn new(
147        delegate: SliverChildDelegateRef,
148        viewport_fraction: f64,
149        allow_implicit_scrolling: bool,
150    ) -> SliverFillViewportRenderObjectWidget {
151        debug_assert!(viewport_fraction > 0.0);
152        SliverFillViewportRenderObjectWidget {
153            delegate,
154            viewport_fraction,
155            allow_implicit_scrolling,
156        }
157    }
158}
159
160impl RenderObjectWidget for SliverFillViewportRenderObjectWidget {
161    type RenderObject = RenderSliverFillViewport;
162
163    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
164        let child_manager = child_manager_of::<SliverFillViewportRenderObjectWidget>(app, context);
165        RenderSliverFillViewport::new(
166            app,
167            child_manager,
168            self.viewport_fraction,
169            self.allow_implicit_scrolling,
170        )
171        .as_object()
172    }
173
174    fn update_render_object(
175        &self,
176        app: &mut App,
177        _context: BuildContext,
178        render_object: RenderHandle<RenderSliverFillViewport>,
179    ) {
180        render_object.set_viewport_fraction(app, self.viewport_fraction);
181        render_object.set_allow_implicit_scrolling(app, self.allow_implicit_scrolling);
182    }
183}
184
185impl SliverWithKeepAliveWidget for SliverFillViewportRenderObjectWidget {}
186
187impl SliverMultiBoxAdaptorWidget for SliverFillViewportRenderObjectWidget {
188    fn delegate(&self) -> &SliverChildDelegateRef {
189        &self.delegate
190    }
191}
192
193/// Dart's `_SliverFractionalPadding`.
194#[derive(Debug)]
195struct SliverFractionalPadding {
196    viewport_fraction: f64,
197    sliver: Option<WidgetRef>,
198}
199
200impl SliverFractionalPadding {
201    fn new(viewport_fraction: f64) -> SliverFractionalPadding {
202        debug_assert!(viewport_fraction >= 0.0);
203        debug_assert!(viewport_fraction <= 0.5);
204        SliverFractionalPadding {
205            viewport_fraction,
206            sliver: None,
207        }
208    }
209
210    #[cfg_attr(debug_assertions, track_caller)]
211    fn sliver<K>(mut self, sliver: impl IntoWidget<K>) -> SliverFractionalPadding {
212        self.sliver = Some(sliver.into_widget());
213        self
214    }
215}
216
217impl RenderObjectWidget for SliverFractionalPadding {
218    type RenderObject = RenderSliverFractionalPadding;
219
220    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
221        RenderSliverFractionalPadding::new(app, self.viewport_fraction).as_object()
222    }
223
224    fn update_render_object(
225        &self,
226        app: &mut App,
227        _context: BuildContext,
228        render_object: RenderHandle<RenderSliverFractionalPadding>,
229    ) {
230        render_object.set_viewport_fraction(app, self.viewport_fraction);
231    }
232}
233
234impl SingleChildRenderObjectWidget for SliverFractionalPadding {
235    fn child(&self) -> Option<&WidgetRef> {
236        self.sliver.as_ref()
237    }
238}
239
240/// Dart's `_RenderSliverFractionalPadding`: pads its sliver on both ends of the main axis by
241/// [`viewport_fraction`](Self::viewport_fraction) of the viewport's main axis extent.
242struct RenderSliverFractionalPadding {
243    render_object: RenderObjectData,
244    render_sliver: RenderSliverData,
245    child: RenderObjectWithChildData<AnyRenderSliver>,
246    last_resolved_constraints: Option<SliverConstraints>,
247    viewport_fraction: f64,
248    resolved_padding: Option<EdgeInsets>,
249}
250
251impl RenderSliverFractionalPadding {
252    fn new(app: &mut App, viewport_fraction: f64) -> RenderHandle<RenderSliverFractionalPadding> {
253        debug_assert!(viewport_fraction <= 0.5);
254        debug_assert!(viewport_fraction >= 0.0);
255        RenderHandle::new_sliver(
256            app,
257            RenderSliverFractionalPadding {
258                render_object: RenderObjectData::new(),
259                render_sliver: RenderSliverData::new(),
260                child: RenderObjectWithChildData::new(),
261                last_resolved_constraints: None,
262                viewport_fraction,
263                resolved_padding: None,
264            },
265        )
266    }
267
268    fn set_viewport_fraction(self: RenderHandle<Self>, app: &mut App, new_value: f64) {
269        if self.get(app).viewport_fraction == new_value {
270            return;
271        }
272        self.get_mut(app).viewport_fraction = new_value;
273        self.mark_needs_resolution(app);
274    }
275
276    fn mark_needs_resolution(self: RenderHandle<Self>, app: &mut App) {
277        self.get_mut(app).resolved_padding = None;
278        self.mark_needs_layout(app);
279    }
280
281    fn resolve(self: RenderHandle<Self>, app: &mut App) {
282        let constraints = self.constraints(app);
283        let this = self.get(app);
284        if this.resolved_padding.is_some() && this.last_resolved_constraints == Some(constraints) {
285            return;
286        }
287
288        let padding_value = constraints.viewport_main_axis_extent * this.viewport_fraction;
289        let resolved_padding = match constraints.axis() {
290            Axis::Horizontal => EdgeInsets::symmetric(0.0, padding_value),
291            Axis::Vertical => EdgeInsets::symmetric(padding_value, 0.0),
292        };
293        let this = self.get_mut(app);
294        this.last_resolved_constraints = Some(constraints);
295        this.resolved_padding = Some(resolved_padding);
296    }
297}
298
299impl Debug for RenderSliverFractionalPadding {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        f.debug_struct("_RenderSliverFractionalPadding")
302            .field("viewport_fraction", &self.viewport_fraction)
303            .finish()
304    }
305}
306
307impl RenderObjectWithChildMixin for RenderSliverFractionalPadding {
308    type ChildType = AnyRenderSliver;
309
310    fn child_data(
311        self: RenderHandle<Self>,
312        app: &App,
313    ) -> &RenderObjectWithChildData<AnyRenderSliver> {
314        &self.get(app).child
315    }
316
317    fn child_data_mut(
318        self: RenderHandle<Self>,
319        app: &mut App,
320    ) -> &mut RenderObjectWithChildData<AnyRenderSliver> {
321        &mut self.get_mut(app).child
322    }
323}
324
325impl RenderSliverEdgeInsetsPadding for RenderSliverFractionalPadding {
326    fn resolved_padding(self: RenderHandle<Self>, app: &App) -> Option<EdgeInsets> {
327        self.get(app).resolved_padding
328    }
329}
330
331impl RenderObject for RenderSliverFractionalPadding {
332    waft_rendering::render_object_accessors!();
333
334    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
335        RenderSliverEdgeInsetsPadding::setup_parent_data(self, app, child)
336    }
337
338    fn visit_children(
339        self: RenderHandle<Self>,
340        app: &App,
341        visitor: &mut dyn FnMut(AnyRenderObject),
342    ) {
343        if let Some(child) = self.child(app) {
344            visitor(child.as_object());
345        }
346    }
347
348    fn apply_paint_transform(
349        self: RenderHandle<Self>,
350        app: &App,
351        child: AnyRenderObject,
352        transform: &mut Matrix4,
353    ) {
354        RenderSliverEdgeInsetsPadding::apply_paint_transform(self, app, child, transform)
355    }
356
357    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
358        self.resolve(app);
359        RenderSliverEdgeInsetsPadding::perform_layout(self, app)
360    }
361
362    fn paint(
363        self: RenderHandle<Self>,
364        app: &mut App,
365        context: &mut PaintingContext,
366        offset: Offset,
367    ) {
368        RenderSliverEdgeInsetsPadding::paint(self, app, context, offset)
369    }
370}
371
372impl RenderSliver for RenderSliverFractionalPadding {
373    waft_rendering::render_sliver_accessors!();
374
375    fn hit_test_children(
376        self: RenderHandle<Self>,
377        app: &mut App,
378        result: &mut SliverHitTestResult<'_>,
379        main_axis_position: f64,
380        cross_axis_position: f64,
381    ) -> bool {
382        RenderSliverEdgeInsetsPadding::hit_test_children(
383            self,
384            app,
385            result,
386            main_axis_position,
387            cross_axis_position,
388        )
389    }
390
391    fn child_main_axis_position(
392        self: RenderHandle<Self>,
393        app: &App,
394        child: AnyRenderObject,
395    ) -> f64 {
396        RenderSliverEdgeInsetsPadding::child_main_axis_position(self, app, child)
397    }
398
399    fn child_cross_axis_position(
400        self: RenderHandle<Self>,
401        app: &App,
402        child: AnyRenderObject,
403    ) -> f64 {
404        RenderSliverEdgeInsetsPadding::child_cross_axis_position(self, app, child)
405    }
406
407    fn child_scroll_offset(
408        self: RenderHandle<Self>,
409        app: &App,
410        child: AnyRenderObject,
411    ) -> Option<f64> {
412        RenderSliverEdgeInsetsPadding::child_scroll_offset(self, app, child)
413    }
414}
415
416/// A sliver that contains a single box child that fills the remaining space in the viewport.
417///
418/// _To learn more about slivers, see `CustomScrollView::slivers`._
419///
420/// [`SliverFillRemaining`] will size its [`child`](Self::child) to fill the viewport in the cross
421/// axis. The extent of the sliver and its child's size in the main axis is computed
422/// conditionally, described in further detail below.
423///
424/// Typically this will be the last sliver in a viewport, since (by definition) there is never
425/// any room for anything beyond this sliver.
426///
427/// ## Main Axis Extent
428///
429/// ### When [`SliverFillRemaining`] has a scrollable child
430///
431/// The [`has_scroll_body`](Self::has_scroll_body) flag indicates whether the sliver's child has a
432/// scrollable body. This value is never null, and defaults to true. A common example of this use
433/// is a `NestedScrollView`. In this case, the sliver will size its child to fill the maximum
434/// available extent. [`SliverFillRemaining`] will not constrain the scrollable area, as it could
435/// potentially have an infinite depth. This is also true for use cases such as a `ScrollView`
436/// when `ScrollView::shrink_wrap` is true.
437///
438/// ### When [`SliverFillRemaining`] does not have a scrollable child
439///
440/// When [`has_scroll_body`](Self::has_scroll_body) is set to false, the child's size is taken
441/// into account when considering the extent to which it should fill the space. The extent to
442/// which the preceding slivers have been scrolled is also taken into account in deciding how to
443/// layout this sliver.
444///
445/// [`SliverFillRemaining`] will size its [`child`](Self::child) to fill the viewport in the main
446/// axis if that space is larger than the child's extent, and the amount of space that has been
447/// scrolled beforehand has not exceeded the main axis extent of the viewport.
448///
449/// [`SliverFillRemaining`] will defer to the size of its [`child`](Self::child) if the child's
450/// size exceeds the remaining space in the viewport.
451///
452/// [`SliverFillRemaining`] will defer to the size of its [`child`](Self::child) if the
453/// `SliverConstraints::preceding_scroll_extent` exceeded the length of the viewport's main axis.
454///
455/// For `ScrollPhysics` that allow overscroll, such as `BouncingScrollPhysics`, setting the
456/// [`fill_overscroll`](Self::fill_overscroll) flag to true allows the size of the
457/// [`child`](Self::child) to _stretch_, filling the overscroll area. It does this regardless of
458/// the path chosen to provide the child's size.
459///
460/// See also:
461///
462///  * [`SliverFillViewport`], which sizes its children based on the size of the viewport,
463///    regardless of what else is in the scroll view.
464///  * [`crate::SliverList`], which shows a list of variable-sized children in a viewport.
465#[derive(Debug)]
466pub struct SliverFillRemaining {
467    pub key: Option<KeyRef>,
468
469    /// Box child widget that fills the remaining space in the viewport.
470    ///
471    /// The main [`SliverFillRemaining`] documentation contains more details.
472    pub child: Option<WidgetRef>,
473
474    /// Indicates whether the child has a scrollable body, this value cannot be null.
475    ///
476    /// Defaults to true such that the child will extend beyond the viewport and scroll, as seen
477    /// in `NestedScrollView`.
478    ///
479    /// Setting this value to false will allow the child to fill the remainder of the viewport
480    /// and not extend further. However, if the `SliverConstraints::preceding_scroll_extent`
481    /// and/or the [`child`](Self::child)'s extent exceeds the size of the viewport, the sliver
482    /// will defer to the child's size rather than overriding it.
483    pub has_scroll_body: bool,
484
485    /// Indicates whether the child should stretch to fill the overscroll area created by certain
486    /// scroll physics, such as iOS' default scroll physics. This flag is only relevant when
487    /// [`has_scroll_body`](Self::has_scroll_body) is false.
488    ///
489    /// Defaults to false, meaning that the default behavior is for the child to maintain its
490    /// size and not extend into the overscroll area.
491    pub fill_overscroll: bool,
492}
493
494impl Default for SliverFillRemaining {
495    fn default() -> SliverFillRemaining {
496        SliverFillRemaining {
497            key: None,
498            child: None,
499            has_scroll_body: true,
500            fill_overscroll: false,
501        }
502    }
503}
504
505impl SliverFillRemaining {
506    /// Creates a sliver that fills the remaining space in the viewport.
507    pub fn new() -> SliverFillRemaining {
508        SliverFillRemaining::default()
509    }
510
511    /// Dart `SliverFillRemaining(key:)`.
512    pub fn key(mut self, key: KeyRef) -> SliverFillRemaining {
513        self.key = Some(key);
514        self
515    }
516
517    /// Dart `SliverFillRemaining(child:)`.
518    #[cfg_attr(debug_assertions, track_caller)]
519    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SliverFillRemaining {
520        self.child = Some(child.into_widget());
521        self
522    }
523
524    /// Dart `SliverFillRemaining(hasScrollBody:)`.
525    pub fn has_scroll_body(mut self, has_scroll_body: bool) -> SliverFillRemaining {
526        self.has_scroll_body = has_scroll_body;
527        self
528    }
529
530    /// Dart `SliverFillRemaining(fillOverscroll:)`.
531    pub fn fill_overscroll(mut self, fill_overscroll: bool) -> SliverFillRemaining {
532        self.fill_overscroll = fill_overscroll;
533        self
534    }
535}
536
537impl StatelessWidget for SliverFillRemaining {
538    fn key(&self) -> Option<&KeyRef> {
539        self.key.as_ref()
540    }
541
542    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
543        if let Some(child) = &self.child {
544            properties.add_rc(Rc::new(child.to_diagnostics_node(
545                app,
546                Some("child".to_string()),
547                None,
548            )));
549        } else {
550            properties.add(DiagnosticsProperty::<String>::new("child", None::<String>));
551        }
552        let mut flags: Vec<String> = Vec::new();
553        if self.has_scroll_body {
554            flags.push("scrollable".to_string());
555        }
556        if self.fill_overscroll {
557            flags.push("fillOverscroll".to_string());
558        }
559        if flags.is_empty() {
560            flags.push("nonscrollable".to_string());
561        }
562        properties.add(IterableProperty::<String>::new("mode", flags));
563    }
564
565    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
566        let child = self.child.clone();
567        if self.has_scroll_body {
568            return SliverFillRemainingWithScrollable { child }.into_widget();
569        }
570        if !self.fill_overscroll {
571            return SliverFillRemainingWithoutScrollable { child }.into_widget();
572        }
573        SliverFillRemainingAndOverscroll { child }.into_widget()
574    }
575}
576
577/// Declares one of [`SliverFillRemaining`]'s private single-child widgets over its render
578/// sliver.
579macro_rules! sliver_fill_remaining_widget {
580    ($(#[$doc:meta])* $widget:ident => $render_object:ident) => {
581        $(#[$doc])*
582        #[derive(Debug)]
583        struct $widget {
584            child: Option<WidgetRef>,
585        }
586
587        impl RenderObjectWidget for $widget {
588            type RenderObject = $render_object;
589
590            fn create_render_object(
591                &self,
592                app: &mut App,
593                _context: BuildContext,
594            ) -> AnyRenderObject {
595                $render_object::new(app, None).as_object()
596            }
597        }
598
599        impl SingleChildRenderObjectWidget for $widget {
600            fn child(&self) -> Option<&WidgetRef> {
601                self.child.as_ref()
602            }
603        }
604    };
605}
606
607sliver_fill_remaining_widget!(
608    /// Dart's `_SliverFillRemainingWithScrollable`.
609    SliverFillRemainingWithScrollable => RenderSliverFillRemainingWithScrollable
610);
611
612sliver_fill_remaining_widget!(
613    /// Dart's `_SliverFillRemainingWithoutScrollable`.
614    SliverFillRemainingWithoutScrollable => RenderSliverFillRemaining
615);
616
617sliver_fill_remaining_widget!(
618    /// Dart's `_SliverFillRemainingAndOverscroll`.
619    SliverFillRemainingAndOverscroll => RenderSliverFillRemainingAndOverscroll
620);
621
622#[cfg(test)]
623mod tests {
624    use waft_foundation::Ref;
625
626    use waft_embedder::{Color, Offset, Rect, Size, TargetPlatform, TextDirection};
627    use waft_foundation::{Handle, Listener};
628    use waft_painting::{AlignmentGeometry, AxisDirection, EdgeInsetsGeometry};
629    use waft_rendering::{
630        AnyRenderSliver, BoxConstraints, ContainerRenderObjectMixin, GrowthDirection, MainAxisSize,
631        RenderSliverFixedExtentList, RenderSliverMultiBoxAdaptor, ScrollCacheExtent,
632        ScrollDirection, SliverMultiBoxAdaptorParentData,
633    };
634
635    use super::*;
636    use crate::framework::GlobalKey;
637    use crate::testing::{
638        TargetPlatformVariant, WidgetTester, expect, find, finds_nothing, finds_one_widget,
639        test_widgets, test_widgets_variant,
640    };
641    use crate::widgets::basic::{
642        Align, Center, ColoredBox, Column, Directionality, Flexible, Padding, SizedBox,
643        SliverToBoxAdapter,
644    };
645    use crate::widgets::gesture_detector::GestureDetector;
646    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
647    use crate::widgets::scroll_delegate::SliverChildListDelegate;
648    use crate::widgets::scroll_view::CustomScrollView;
649    use crate::widgets::scrollable::Scrollable;
650    use crate::widgets::sliver::SliverFixedExtentList;
651    use crate::widgets::text::Text;
652
653    const DEBUG_RED: Color = Color::new(0xFFFF0000);
654
655    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
656        Directionality::new(TextDirection::Ltr, child).into_widget()
657    }
658
659    // ---- sliver_fill_viewport_test.dart ----
660
661    /// The index of every child the first `T` has laid out whose extent overlaps its paint
662    /// region, as `SliverMultiBoxAdaptorElement.debugVisitOnstageChildren` tests.
663    fn onstage_children_of<T: RenderSliverMultiBoxAdaptor>(tester: &WidgetTester) -> Vec<i32> {
664        let fill = *tester
665            .all::<T>()
666            .first()
667            .expect("a mounted sliver of the type");
668        let app = tester.cell.borrow();
669        let constraints = fill.constraints(&app);
670        let mut onstage = Vec::new();
671        let mut child = fill.first_child(&app);
672        while let Some(current) = child {
673            let layout_offset = current
674                .as_object()
675                .parent_data_of::<SliverMultiBoxAdaptorParentData>(&app)
676                .layout_offset()
677                .expect("a laid out child");
678            let extent = current.size(&app).height();
679            if layout_offset < constraints.scroll_offset + constraints.remaining_paint_extent
680                && layout_offset + extent > constraints.scroll_offset
681            {
682                onstage.push(fill.index_of(&app, current));
683            }
684            child = fill.child_after(&app, current);
685        }
686        onstage
687    }
688
689    /// The sliver the first `SliverFillViewport` builds: Dart's
690    /// `tester.renderObject<RenderSliver>(find.byType(SliverFillViewport))`.
691    fn fill_viewport_sliver(tester: &WidgetTester) -> AnyRenderSliver {
692        tester
693            .render_object(find::by_type::<SliverFillViewport>())
694            .as_sliver()
695            .expect("the fill viewport builds a sliver")
696    }
697
698    /// Dart's `tester.renderObject<RenderBox>(find.byType(ColoredBox).first).size.height`.
699    fn first_colored_box_height(tester: &WidgetTester) -> f64 {
700        tester
701            .get_size(find::by_type::<ColoredBox>().first())
702            .height()
703    }
704
705    fn fill_viewport_children(count: usize) -> SliverChildDelegateRef {
706        SliverChildListDelegate::new(
707            (0..count)
708                .map(|i| {
709                    ColoredBox::new(Color::new(0xff00ff00))
710                        .child(Text::new(format!("{i}")).text_direction(TextDirection::Ltr))
711                        .into_widget()
712                })
713                .collect(),
714        )
715        .add_automatic_keep_alives(false)
716        .add_semantic_indexes(false)
717        .into_delegate()
718    }
719
720    #[test]
721    fn a_sliver_fill_viewport_sizes_each_child_to_the_viewport() {
722        test_widgets(|tester| {
723            tester.pump_widget(ltr(CustomScrollView::new().slivers([
724                SliverFillViewport::new(fill_viewport_children(20)).into_widget(),
725            ])));
726
727            assert_eq!(first_colored_box_height(tester), 600.0);
728
729            expect(tester, &find::text("0"), finds_one_widget());
730            expect(tester, &find::text("1"), finds_nothing());
731            expect(tester, &find::text("2"), finds_nothing());
732
733            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -700.0));
734            tester.pump();
735
736            expect(tester, &find::text("0"), finds_nothing());
737            expect(tester, &find::text("1"), finds_one_widget());
738            expect(tester, &find::text("2"), finds_one_widget());
739            expect(tester, &find::text("3"), finds_nothing());
740            expect(tester, &find::text("4"), finds_nothing());
741
742            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, 200.0));
743            tester.pump();
744
745            expect(tester, &find::text("0"), finds_one_widget());
746            expect(tester, &find::text("1"), finds_one_widget());
747            expect(tester, &find::text("2"), finds_nothing());
748            expect(tester, &find::text("3"), finds_nothing());
749
750            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, 700.0));
751            tester.pump();
752
753            assert_eq!(first_colored_box_height(tester), 600.0);
754
755            expect(tester, &find::text("0"), finds_one_widget());
756            expect(tester, &find::text("1"), finds_nothing());
757            expect(tester, &find::text("2"), finds_nothing());
758            expect(tester, &find::text("3"), finds_nothing());
759
760            let padding = fill_viewport_sliver(tester);
761            let fill = *tester
762                .all::<RenderSliverFillViewport>()
763                .first()
764                .expect("a mounted sliver fill viewport");
765            let app = tester.cell.borrow();
766            // The padding and the fill viewport inside it get the same constraints and geometry.
767            for (constraints, geometry) in [
768                (padding.constraints(&app), padding.geometry(&app)),
769                (fill.constraints(&app), fill.geometry(&app)),
770            ] {
771                assert_eq!(constraints.axis_direction, AxisDirection::Down);
772                assert_eq!(constraints.growth_direction, GrowthDirection::Forward);
773                assert_eq!(constraints.user_scroll_direction, ScrollDirection::Idle);
774                assert_eq!(constraints.scroll_offset, 0.0);
775                assert_eq!(constraints.preceding_scroll_extent, 0.0);
776                assert_eq!(constraints.remaining_paint_extent, 600.0);
777                assert_eq!(constraints.cross_axis_extent, 800.0);
778                assert_eq!(constraints.cross_axis_direction, AxisDirection::Right);
779                assert_eq!(constraints.viewport_main_axis_extent, 600.0);
780                assert_eq!(constraints.remaining_cache_extent, 850.0);
781                assert_eq!(constraints.cache_origin, 0.0);
782
783                assert_eq!(geometry.scroll_extent, 12000.0);
784                assert_eq!(geometry.paint_extent, 600.0);
785                assert_eq!(geometry.max_paint_extent, 12000.0);
786                assert!(geometry.has_visual_overflow);
787                assert_eq!(geometry.cache_extent, 850.0);
788            }
789
790            // Currently live children: 0 to 1.
791            let mut live = Vec::new();
792            let mut child = fill.first_child(&app);
793            while let Some(current) = child {
794                live.push((
795                    fill.index_of(&app, current),
796                    current
797                        .as_object()
798                        .parent_data_of::<SliverMultiBoxAdaptorParentData>(&app)
799                        .layout_offset(),
800                    current.constraints(&app),
801                    current.size(&app),
802                ));
803                child = fill.child_after(&app, current);
804            }
805            let page = Size::new(800.0, 600.0);
806            assert_eq!(
807                live,
808                [
809                    (0, Some(0.0), BoxConstraints::tight(page), page),
810                    (1, Some(600.0), BoxConstraints::tight(page), page),
811                ]
812            );
813        });
814    }
815
816    #[test]
817    fn a_sliver_fill_viewport_pads_its_ends_by_its_viewport_fraction() {
818        test_widgets(|tester| {
819            let delegate = SliverChildListDelegate::new(vec![SizedBox::new().into_widget()])
820                .add_automatic_keep_alives(false)
821                .add_semantic_indexes(false)
822                .into_delegate();
823
824            tester.pump_widget(ltr(CustomScrollView::new().slivers([
825                SliverFillViewport::new(Rc::clone(&delegate))
826                    .viewport_fraction(0.5)
827                    .into_widget(),
828            ])));
829
830            let box_with_padding = fill_viewport_sliver(tester);
831            assert_eq!(
832                box_with_padding
833                    .geometry(&tester.cell.borrow())
834                    .paint_extent,
835                600.0
836            );
837
838            tester.pump_widget(ltr(CustomScrollView::new().slivers([
839                SliverFillViewport::new(delegate)
840                    .pad_ends(false)
841                    .viewport_fraction(0.5)
842                    .into_widget(),
843            ])));
844
845            let box_without_padding = fill_viewport_sliver(tester);
846            assert_eq!(
847                box_without_padding
848                    .geometry(&tester.cell.borrow())
849                    .paint_extent,
850                300.0
851            );
852        });
853    }
854
855    // ---- sliver_fill_remaining_test.dart ----
856
857    /// The test file's `sliverBox`: a 150 x 150 box.
858    fn sliver_box() -> WidgetRef {
859        SliverToBoxAdapter::new()
860            .child(
861                SizedBox::new()
862                    .width(150.0)
863                    .height(150.0)
864                    .child(ColoredBox::new(DEBUG_RED)),
865            )
866            .into_widget()
867    }
868
869    /// The test file's `boilerplate`.
870    fn boilerplate(
871        slivers: Vec<WidgetRef>,
872        controller: Option<Ref<ScrollController>>,
873        scroll_direction: Axis,
874    ) -> WidgetRef {
875        let mut scroll_view = CustomScrollView::new()
876            .scroll_direction(scroll_direction)
877            .slivers(slivers);
878        if let Some(controller) = controller {
879            scroll_view = scroll_view.controller(controller.erase());
880        }
881        ltr(scroll_view)
882    }
883
884    fn jump_to(tester: &mut WidgetTester, controller: Handle<ScrollController>, value: f64) {
885        controller.jump_to(&mut tester.cell.borrow_mut(), value);
886        tester.pump();
887    }
888
889    fn offset(tester: &WidgetTester, controller: Handle<ScrollController>) -> f64 {
890        controller.offset(&tester.cell.borrow())
891    }
892
893    #[test]
894    fn a_scroll_body_with_no_siblings_fills_the_viewport() {
895        test_widgets(|tester| {
896            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
897            let key = GlobalKey::new();
898            tester.pump_widget(boilerplate(
899                vec![
900                    SliverFillRemaining::new()
901                        .child(SizedBox::new().key(key.clone().into()))
902                        .into_widget(),
903                ],
904                Some(controller.clone()),
905                Axis::Vertical,
906            ));
907            assert_eq!(tester.get_size(&key).height(), 600.0);
908
909            for pixels in [50.0, -100.0, 0.0] {
910                jump_to(tester, controller.handle(), pixels);
911                assert_eq!(tester.get_size(&key).height(), 600.0, "at {pixels}");
912            }
913        });
914    }
915
916    #[test]
917    fn a_scroll_body_with_one_sibling_fills_what_remains() {
918        test_widgets(|tester| {
919            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
920            let key = GlobalKey::new();
921            tester.pump_widget(boilerplate(
922                vec![
923                    SliverToBoxAdapter::new()
924                        .child(SizedBox::new().height(100.0))
925                        .into_widget(),
926                    SliverFillRemaining::new()
927                        .child(SizedBox::new().key(key.clone().into()))
928                        .into_widget(),
929                ],
930                Some(controller.clone()),
931                Axis::Vertical,
932            ));
933            assert_eq!(tester.get_size(&key).height(), 500.0);
934
935            for (pixels, height) in [(50.0, 550.0), (-100.0, 400.0), (0.0, 500.0)] {
936                jump_to(tester, controller.handle(), pixels);
937                assert_eq!(tester.get_size(&key).height(), height, "at {pixels}");
938            }
939        });
940    }
941
942    #[test]
943    fn a_scroll_body_scrolls_beyond_the_viewport_extent() {
944        test_widgets(|tester| {
945            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
946            let fill_key = GlobalKey::new();
947            tester.pump_widget(boilerplate(
948                vec![
949                    sliver_box(),
950                    SliverFillRemaining::new()
951                        .child(ColoredBox::new(DEBUG_RED).key(fill_key.clone().into()))
952                        .into_widget(),
953                ],
954                Some(controller.clone()),
955                Axis::Vertical,
956            ));
957            assert_eq!(offset(tester, controller.handle()), 0.0);
958            controller.jump_to(&mut tester.cell.borrow_mut(), 150.0);
959            tester.pump_and_settle();
960            assert_eq!(offset(tester, controller.handle()), 150.0);
961            assert_eq!(tester.get_rect(&fill_key).top, 0.0);
962        });
963    }
964
965    /// `has correct semantics when`: past the viewport, a scroll body inside the cache extent is
966    /// laid out at the size it asks for, and outside it at none. Accessibility is deferred, so
967    /// this checks the layout the semantic nodes follow.
968    #[test]
969    fn a_scroll_body_past_the_viewport_is_laid_out_only_within_the_cache_extent() {
970        // Viewport is 800x600
971        const VIEWPORT_HEIGHT: f64 = 600.0;
972        const CACHE_EXTENT: f64 = 250.0;
973        for (preceding_height, height) in [
974            // This sliver takes up entire viewport and leaves 250 remaining cacheExtent
975            (VIEWPORT_HEIGHT, 100.0),
976            // This sliver takes up entire viewport and leaves 0 remaining cacheExtent
977            (VIEWPORT_HEIGHT + CACHE_EXTENT, 0.0),
978        ] {
979            test_widgets(|tester| {
980                let key = GlobalKey::new();
981                tester.pump_widget(ltr(CustomScrollView::new()
982                    .scroll_cache_extent(ScrollCacheExtent::Pixels(CACHE_EXTENT))
983                    .slivers([
984                        SliverToBoxAdapter::new()
985                            .child(
986                                SizedBox::new()
987                                    .width(150.0)
988                                    .height(preceding_height)
989                                    .child(ColoredBox::new(DEBUG_RED)),
990                            )
991                            .into_widget(),
992                        SliverFillRemaining::new()
993                            .child(SizedBox::new().key(key.clone().into()).height(100.0))
994                            .into_widget(),
995                    ])));
996                assert_eq!(
997                    tester.get_size(&key).height(),
998                    height,
999                    "after {preceding_height}"
1000                );
1001            });
1002        }
1003    }
1004
1005    fn without_scroll_body(child: WidgetRef) -> Vec<WidgetRef> {
1006        vec![
1007            sliver_box(),
1008            SliverFillRemaining::new()
1009                .has_scroll_body(false)
1010                .child(child)
1011                .into_widget(),
1012        ]
1013    }
1014
1015    #[test]
1016    fn a_body_that_does_not_scroll_does_not_extend_past_the_viewport() {
1017        test_widgets(|tester| {
1018            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1019            tester.pump_widget(boilerplate(
1020                without_scroll_body(ColoredBox::new(DEBUG_RED).into_widget()),
1021                Some(controller.clone()),
1022                Axis::Vertical,
1023            ));
1024            assert_eq!(offset(tester, controller.handle()), 0.0);
1025            controller.jump_to(&mut tester.cell.borrow_mut(), 150.0);
1026            tester.pump_and_settle();
1027            assert_eq!(offset(tester, controller.handle()), 0.0);
1028        });
1029    }
1030
1031    #[test]
1032    fn a_child_without_a_size_is_sized_by_the_extent() {
1033        test_widgets(|tester| {
1034            let fill_key = GlobalKey::new();
1035            let slivers = || {
1036                without_scroll_body(
1037                    ColoredBox::new(DEBUG_RED)
1038                        .key(fill_key.clone().into())
1039                        .into_widget(),
1040                )
1041            };
1042
1043            tester.pump_widget(boilerplate(slivers(), None, Axis::Vertical));
1044            assert_eq!(tester.get_size(&fill_key).height(), 450.0);
1045
1046            tester.pump_widget(boilerplate(slivers(), None, Axis::Horizontal));
1047            assert_eq!(tester.get_size(&fill_key).width(), 650.0);
1048        });
1049    }
1050
1051    #[test]
1052    fn the_extent_is_overridden_by_a_larger_child() {
1053        test_widgets(|tester| {
1054            let key = GlobalKey::new();
1055            let slivers = || {
1056                without_scroll_body(
1057                    SizedBox::new()
1058                        .key(key.clone().into())
1059                        .width(1000.0)
1060                        .height(600.0)
1061                        .child(ColoredBox::new(DEBUG_RED))
1062                        .into_widget(),
1063                )
1064            };
1065
1066            tester.pump_widget(boilerplate(slivers(), None, Axis::Vertical));
1067            assert_eq!(tester.get_size(&key).height(), 600.0);
1068
1069            tester.pump_widget(boilerplate(slivers(), None, Axis::Horizontal));
1070            assert_eq!(tester.get_size(&key).width(), 1000.0);
1071        });
1072    }
1073
1074    /// The test file's `_sizedTestButton`: a box the size of Material's default elevated button
1075    /// at the platform's visual density, `TestButton` itself being only a tap target.
1076    fn sized_test_button(platform: TargetPlatform, key: &GlobalKey) -> WidgetRef {
1077        let density_vertical = match platform {
1078            TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => 0.0,
1079            TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => -2.0,
1080        };
1081        SizedBox::new()
1082            .key(key.clone().into())
1083            .width(116.0)
1084            .height(48.0 + density_vertical * 4.0)
1085            .child(ColoredBox::new(DEBUG_RED))
1086            .into_widget()
1087    }
1088
1089    /// A button pinned to the bottom center of a keyed box.
1090    fn bottom_center_button(
1091        platform: TargetPlatform,
1092        key: &GlobalKey,
1093        button: &GlobalKey,
1094    ) -> WidgetRef {
1095        ColoredBox::new(DEBUG_RED)
1096            .key(key.clone().into())
1097            .child(
1098                Align::new()
1099                    .alignment(AlignmentGeometry::BOTTOM_CENTER)
1100                    .child(sized_test_button(platform, button)),
1101            )
1102            .into_widget()
1103    }
1104
1105    /// A button centered in 50 of padding in a keyed box: 148 of intrinsic height on Android.
1106    fn padded_center_button(
1107        platform: TargetPlatform,
1108        key: &GlobalKey,
1109        button: &GlobalKey,
1110    ) -> WidgetRef {
1111        ColoredBox::new(DEBUG_RED)
1112            .key(key.clone().into())
1113            .child(
1114                Align::new().child(
1115                    Padding::new(EdgeInsetsGeometry::all(50.0))
1116                        .child(sized_test_button(platform, button)),
1117                ),
1118            )
1119            .into_widget()
1120    }
1121
1122    fn five_fixed_extent_items() -> WidgetRef {
1123        SliverFixedExtentList::builder(
1124            |_, _, _| Some(ColoredBox::new(DEBUG_RED).into_widget()),
1125            150.0,
1126        )
1127        .item_count(5)
1128        .into_widget()
1129    }
1130
1131    fn fill_without_scroll_body(fill_overscroll: bool, child: WidgetRef) -> WidgetRef {
1132        SliverFillRemaining::new()
1133            .has_scroll_body(false)
1134            .fill_overscroll(fill_overscroll)
1135            .child(child)
1136            .into_widget()
1137    }
1138
1139    fn jump_to_max_scroll_extent(tester: &mut WidgetTester, controller: Handle<ScrollController>) {
1140        let max_scroll_extent = {
1141            let app = tester.cell.borrow();
1142            controller.position(&app).max_scroll_extent(&app)
1143        };
1144        jump_to(tester, controller, max_scroll_extent);
1145    }
1146
1147    #[test]
1148    fn a_child_with_a_smaller_size_is_sized_by_the_extent() {
1149        test_widgets(|tester| {
1150            let (key, button) = (GlobalKey::new(), GlobalKey::new());
1151            let slivers = || {
1152                without_scroll_body(bottom_center_button(TargetPlatform::Android, &key, &button))
1153            };
1154
1155            tester.pump_widget(boilerplate(slivers(), None, Axis::Vertical));
1156            assert_eq!(tester.get_size(&key).height(), 450.0);
1157
1158            // Also check that the button alignment is true to expectations
1159            let button_rect = tester.get_rect(&button);
1160            assert_eq!(button_rect.bottom, 600.0);
1161            assert_eq!(button_rect.center().dx(), 400.0);
1162
1163            // Check Axis.horizontal
1164            tester.pump_widget(boilerplate(slivers(), None, Axis::Horizontal));
1165            assert_eq!(tester.get_size(&key).width(), 650.0);
1166        });
1167    }
1168
1169    #[test]
1170    fn the_extent_is_the_childs_once_the_preceding_slivers_pass_the_viewport() {
1171        test_widgets(|tester| {
1172            let (key, button) = (GlobalKey::new(), GlobalKey::new());
1173            tester.pump_widget(boilerplate(
1174                vec![
1175                    five_fixed_extent_items(),
1176                    fill_without_scroll_body(
1177                        false,
1178                        padded_center_button(TargetPlatform::Android, &key, &button),
1179                    ),
1180                ],
1181                None,
1182                Axis::Vertical,
1183            ));
1184            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -750.0));
1185            tester.pump();
1186            assert_eq!(tester.get_size(&key).height(), 148.0);
1187
1188            // Also check that the button alignment is true to expectations
1189            let button_rect = tester.get_rect(&button);
1190            assert_eq!(button_rect.bottom, 550.0);
1191            assert_eq!(button_rect.center().dx(), 400.0);
1192        });
1193    }
1194
1195    /// The column of `alignment with a flexible works`: a flexible, centered 100 x 100 logo above
1196    /// the sized test button.
1197    fn flexible_logo_and_button(
1198        platform: TargetPlatform,
1199        key: &GlobalKey,
1200        logo: &GlobalKey,
1201        button: &GlobalKey,
1202    ) -> WidgetRef {
1203        Column::new()
1204            .key(key.clone().into())
1205            .main_axis_size(MainAxisSize::Min)
1206            .children([
1207                Flexible::new(
1208                    Center::new().child(
1209                        SizedBox::new()
1210                            .key(logo.clone().into())
1211                            .width(100.0)
1212                            .height(100.0),
1213                    ),
1214                )
1215                .into_widget(),
1216                sized_test_button(platform, button),
1217            ])
1218            .into_widget()
1219    }
1220
1221    /// `alignment with a flexible works`: a column whose flexible logo and button keep their
1222    /// places as the scroll view overscrolls.
1223    #[test]
1224    fn a_flexible_child_keeps_its_alignment() {
1225        test_widgets_variant(ios_and_macos(), |tester| {
1226            let platform = tester.target_platform();
1227            let density_vertical = if platform == TargetPlatform::MacOS {
1228                -2.0
1229            } else {
1230                0.0
1231            };
1232            let (key, logo, button) = (GlobalKey::new(), GlobalKey::new(), GlobalKey::new());
1233            tester.pump_widget(boilerplate(
1234                without_scroll_body(flexible_logo_and_button(platform, &key, &logo, &button)),
1235                None,
1236                Axis::Vertical,
1237            ));
1238            assert_eq!(tester.get_size(&key).height(), 450.0, "{platform:?}");
1239
1240            // Check that the logo alignment is true to expectations
1241            assert_eq!(
1242                tester.get_size(&logo),
1243                Size::new(100.0, 100.0),
1244                "{platform:?}"
1245            );
1246            assert_eq!(
1247                tester.get_rect(&logo).center(),
1248                Offset::new(400.0, 351.0 - density_vertical * 2.0),
1249                "{platform:?}"
1250            );
1251
1252            // Also check that the button alignment is true to expectations
1253            assert_eq!(
1254                tester.get_size(&button),
1255                Size::new(116.0, 48.0 + density_vertical * 4.0),
1256                "{platform:?}"
1257            );
1258            let button_rect = tester.get_rect(&button);
1259            assert_eq!(button_rect.bottom, 600.0, "{platform:?}");
1260            assert_eq!(button_rect.center().dx(), 400.0, "{platform:?}");
1261
1262            // Overscroll and see that alignment and size is maintained
1263            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1264            tester.pump();
1265            assert_eq!(tester.get_size(&key).height(), 450.0, "{platform:?}");
1266            assert_eq!(
1267                tester.get_size(&logo),
1268                Size::new(100.0, 100.0),
1269                "{platform:?}"
1270            );
1271            assert!(tester.get_rect(&logo).center().dy() < 351.0, "{platform:?}");
1272            assert_eq!(
1273                tester.get_size(&button),
1274                Size::new(116.0, 48.0 + density_vertical * 4.0),
1275                "{platform:?}"
1276            );
1277            let button_rect = tester.get_rect(&button);
1278            assert!(button_rect.bottom < 600.0, "{platform:?}");
1279            assert_eq!(button_rect.center().dx(), 400.0, "{platform:?}");
1280        });
1281    }
1282
1283    /// `alignment with a flexible works with fillOverscroll`: the logo stays centered in the
1284    /// column as it stretches into the overscroll, and the button stays at the bottom.
1285    #[test]
1286    fn a_flexible_child_keeps_its_alignment_as_it_fills_the_overscroll() {
1287        test_widgets_variant(ios_and_macos(), |tester| {
1288            let platform = tester.target_platform();
1289            let density_vertical = if platform == TargetPlatform::MacOS {
1290                -2.0
1291            } else {
1292                0.0
1293            };
1294            let (key, logo, button) = (GlobalKey::new(), GlobalKey::new(), GlobalKey::new());
1295            tester.pump_widget(boilerplate(
1296                vec![
1297                    sliver_box(),
1298                    fill_without_scroll_body(
1299                        true,
1300                        flexible_logo_and_button(platform, &key, &logo, &button),
1301                    ),
1302                ],
1303                None,
1304                Axis::Vertical,
1305            ));
1306            let assert_at_rest = |tester: &WidgetTester| {
1307                assert_eq!(tester.get_size(&key).height(), 450.0, "{platform:?}");
1308
1309                // Check that the logo alignment is true to expectations.
1310                assert_eq!(
1311                    tester.get_size(&logo),
1312                    Size::new(100.0, 100.0),
1313                    "{platform:?}"
1314                );
1315                assert_eq!(
1316                    tester.get_rect(&logo).center(),
1317                    Offset::new(400.0, 351.0 - density_vertical * 2.0),
1318                    "{platform:?}"
1319                );
1320
1321                // Also check that the button alignment is true to expectations.
1322                assert_eq!(
1323                    tester.get_size(&button),
1324                    Size::new(116.0, 48.0 + density_vertical * 4.0),
1325                    "{platform:?}"
1326                );
1327                let button_rect = tester.get_rect(&button);
1328                assert_eq!(button_rect.bottom, 600.0, "{platform:?}");
1329                assert_eq!(button_rect.center().dx(), 400.0, "{platform:?}");
1330            };
1331            assert_at_rest(tester);
1332
1333            // Overscroll and see that logo alignment shifts to maintain center as
1334            // container stretches with overscroll, button remains aligned at the
1335            // bottom.
1336            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1337            tester.pump();
1338            assert!(tester.get_size(&key).height() > 450.0, "{platform:?}");
1339            assert_eq!(
1340                tester.get_size(&logo),
1341                Size::new(100.0, 100.0),
1342                "{platform:?}"
1343            );
1344            assert!(tester.get_rect(&logo).center().dy() < 351.0, "{platform:?}");
1345            assert_eq!(
1346                tester.get_size(&button),
1347                Size::new(116.0, 48.0 + density_vertical * 4.0),
1348                "{platform:?}"
1349            );
1350            let button_rect = tester.get_rect(&button);
1351            assert_eq!(button_rect.bottom, 600.0, "{platform:?}");
1352            assert_eq!(button_rect.center().dx(), 400.0, "{platform:?}");
1353
1354            // Ensure overscroll retracts to original position when gesture is
1355            // released.
1356            tester.pump_and_settle();
1357            assert_at_rest(tester);
1358        });
1359    }
1360
1361    fn overscrolling_slivers(fill_key: &GlobalKey, with_box: bool) -> Vec<WidgetRef> {
1362        let fill = SliverFillRemaining::new()
1363            .has_scroll_body(false)
1364            .fill_overscroll(true)
1365            .child(
1366                SizedBox::expand().child(ColoredBox::new(DEBUG_RED).key(fill_key.clone().into())),
1367            )
1368            .into_widget();
1369        if with_box {
1370            vec![sliver_box(), fill]
1371        } else {
1372            vec![fill]
1373        }
1374    }
1375
1376    /// `TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS})`.
1377    fn ios_and_macos() -> TargetPlatformVariant {
1378        TargetPlatformVariant::new([TargetPlatform::IOS, TargetPlatform::MacOS])
1379    }
1380
1381    #[test]
1382    fn a_child_without_a_size_is_sized_by_the_extent_and_the_overscroll() {
1383        test_widgets_variant(ios_and_macos(), |tester| {
1384            let platform = tester.target_platform();
1385            let fill_key = GlobalKey::new();
1386            tester.pump_widget(boilerplate(
1387                overscrolling_slivers(&fill_key, true),
1388                None,
1389                Axis::Vertical,
1390            ));
1391            assert_eq!(tester.get_size(&fill_key).height(), 450.0, "{platform:?}");
1392
1393            // Overscroll and check size
1394            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1395            tester.pump();
1396            assert!(tester.get_size(&fill_key).height() > 450.0, "{platform:?}");
1397
1398            // Ensure overscroll retracts to original size after releasing gesture
1399            tester.pump_and_settle();
1400            assert_eq!(tester.get_size(&fill_key).height(), 450.0, "{platform:?}");
1401        });
1402    }
1403
1404    #[test]
1405    fn a_child_stretches_into_overscroll_that_exceeds_the_preceding_extent() {
1406        test_widgets_variant(ios_and_macos(), |tester| {
1407            let platform = tester.target_platform();
1408            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1409            let fill_key = GlobalKey::new();
1410            tester.pump_widget(boilerplate(
1411                overscrolling_slivers(&fill_key, true),
1412                Some(controller.clone()),
1413                Axis::Vertical,
1414            ));
1415            assert_eq!(
1416                tester.get_rect(&fill_key),
1417                Rect::from_ltrb(0.0, 150.0, 800.0, 600.0),
1418                "{platform:?}"
1419            );
1420
1421            // Overscroll by 200: the preceding box frees up 150 of paint room
1422            // and the remaining 50 become this sliver's scrollOffset.
1423            jump_to(tester, controller.handle(), 200.0);
1424
1425            let rect = tester.get_rect(&fill_key);
1426            assert_eq!(rect.bottom, 600.0, "{platform:?}");
1427            assert_eq!(rect.height(), 650.0, "{platform:?}");
1428
1429            jump_to(tester, controller.handle(), 0.0);
1430            assert_eq!(
1431                tester.get_rect(&fill_key),
1432                Rect::from_ltrb(0.0, 150.0, 800.0, 600.0),
1433                "{platform:?}"
1434            );
1435        });
1436    }
1437
1438    #[test]
1439    fn a_lone_child_stretches_to_cover_the_whole_overscroll() {
1440        test_widgets_variant(ios_and_macos(), |tester| {
1441            let platform = tester.target_platform();
1442            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1443            let fill_key = GlobalKey::new();
1444            tester.pump_widget(boilerplate(
1445                overscrolling_slivers(&fill_key, false),
1446                Some(controller.clone()),
1447                Axis::Vertical,
1448            ));
1449            assert_eq!(
1450                tester.get_rect(&fill_key),
1451                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0),
1452                "{platform:?}"
1453            );
1454
1455            jump_to(tester, controller.handle(), 50.0);
1456
1457            let rect = tester.get_rect(&fill_key);
1458            assert_eq!(rect.bottom, 600.0, "{platform:?}");
1459            assert_eq!(rect.height(), 650.0, "{platform:?}");
1460
1461            jump_to(tester, controller.handle(), 0.0);
1462            assert_eq!(
1463                tester.get_rect(&fill_key),
1464                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0),
1465                "{platform:?}"
1466            );
1467        });
1468    }
1469
1470    #[test]
1471    fn fill_overscroll_is_ignored_where_scrolling_clamps() {
1472        test_widgets(|tester| {
1473            let fill_key = GlobalKey::new();
1474            tester.pump_widget(boilerplate(
1475                vec![
1476                    sliver_box(),
1477                    SliverFillRemaining::new()
1478                        .has_scroll_body(false)
1479                        .fill_overscroll(true)
1480                        .child(ColoredBox::new(DEBUG_RED).key(fill_key.clone().into()))
1481                        .into_widget(),
1482                ],
1483                None,
1484                Axis::Vertical,
1485            ));
1486            assert_eq!(tester.get_size(&fill_key).height(), 450.0);
1487
1488            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1489            tester.pump();
1490            assert_eq!(tester.get_size(&fill_key).height(), 450.0);
1491        });
1492    }
1493    /// A lone stretching child in a reversed scroll view, with a tap target that answers
1494    /// whether a hit test at a point reaches it.
1495    fn reversed_overscrolling_view(
1496        controller: Ref<ScrollController>,
1497        scroll_direction: Axis,
1498        fill_key: &GlobalKey,
1499        taps: &Rc<std::cell::Cell<u32>>,
1500    ) -> WidgetRef {
1501        let taps = Rc::clone(taps);
1502        ltr(CustomScrollView::new()
1503            .scroll_direction(scroll_direction)
1504            .reverse(true)
1505            .controller(controller.erase())
1506            .slivers(vec![fill_without_scroll_body(
1507                true,
1508                SizedBox::expand()
1509                    .child(
1510                        GestureDetector::new()
1511                            .on_tap(Listener::new(move |_| taps.set(taps.get() + 1)))
1512                            .child(ColoredBox::new(DEBUG_RED).key(fill_key.clone().into())),
1513                    )
1514                    .into_widget(),
1515            )]))
1516    }
1517
1518    #[test]
1519    fn a_child_in_a_reversed_scroll_view_stretches_towards_the_leading_edge() {
1520        test_widgets_variant(ios_and_macos(), |tester| {
1521            let platform = tester.target_platform();
1522            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1523            let fill_key = GlobalKey::new();
1524            let taps = Rc::new(std::cell::Cell::new(0));
1525            tester.pump_widget(reversed_overscrolling_view(
1526                controller.clone(),
1527                Axis::Vertical,
1528                &fill_key,
1529                &taps,
1530            ));
1531            assert_eq!(
1532                tester.get_rect(&fill_key),
1533                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0),
1534                "{platform:?}"
1535            );
1536
1537            jump_to(tester, controller.handle(), 50.0);
1538
1539            let rect = tester.get_rect(&fill_key);
1540            assert_eq!(rect.top, 0.0, "{platform:?}");
1541            assert_eq!(rect.height(), 650.0, "{platform:?}");
1542            // `hitTestOnBinding(Offset(400.0, 25.0))` reaches the stretched child.
1543            tester.tap_at(Offset::new(400.0, 25.0), 1);
1544            assert_eq!(taps.get(), 1, "{platform:?}");
1545
1546            jump_to(tester, controller.handle(), 0.0);
1547            assert_eq!(
1548                tester.get_rect(&fill_key),
1549                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0),
1550                "{platform:?}"
1551            );
1552        });
1553    }
1554
1555    #[test]
1556    fn a_child_in_a_reversed_horizontal_scroll_view_stretches_towards_the_leading_edge() {
1557        test_widgets_variant(ios_and_macos(), |tester| {
1558            let platform = tester.target_platform();
1559            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1560            let fill_key = GlobalKey::new();
1561            let taps = Rc::new(std::cell::Cell::new(0));
1562            tester.pump_widget(reversed_overscrolling_view(
1563                controller.clone(),
1564                Axis::Horizontal,
1565                &fill_key,
1566                &taps,
1567            ));
1568            assert_eq!(
1569                tester.get_rect(&fill_key),
1570                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0),
1571                "{platform:?}"
1572            );
1573
1574            jump_to(tester, controller.handle(), 50.0);
1575
1576            let rect = tester.get_rect(&fill_key);
1577            assert_eq!(rect.left, 0.0, "{platform:?}");
1578            assert_eq!(rect.width(), 850.0, "{platform:?}");
1579
1580            jump_to(tester, controller.handle(), 0.0);
1581            assert_eq!(
1582                tester.get_rect(&fill_key),
1583                Rect::from_ltrb(0.0, 0.0, 800.0, 600.0),
1584                "{platform:?}"
1585            );
1586        });
1587    }
1588
1589    #[test]
1590    fn a_child_with_a_smaller_size_stretches_by_the_extent_and_the_overscroll() {
1591        test_widgets_variant(ios_and_macos(), |tester| {
1592            let platform = tester.target_platform();
1593            let (key, button) = (GlobalKey::new(), GlobalKey::new());
1594            tester.pump_widget(boilerplate(
1595                vec![
1596                    sliver_box(),
1597                    fill_without_scroll_body(true, bottom_center_button(platform, &key, &button)),
1598                ],
1599                None,
1600                Axis::Vertical,
1601            ));
1602            assert_eq!(tester.get_size(&key).height(), 450.0, "{platform:?}");
1603
1604            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1605            tester.pump();
1606            assert!(tester.get_size(&key).height() > 450.0, "{platform:?}");
1607
1608            // Also check that the button alignment is true to expectations
1609            let button_rect = tester.get_rect(&button);
1610            assert_eq!(button_rect.bottom, 600.0, "{platform:?}");
1611            assert_eq!(button_rect.center().dx(), 400.0, "{platform:?}");
1612
1613            // Ensure overscroll retracts to original size after releasing gesture
1614            tester.pump_and_settle();
1615            assert_eq!(tester.get_size(&key).height(), 450.0, "{platform:?}");
1616        });
1617    }
1618
1619    #[test]
1620    fn a_child_larger_than_the_extent_stretches_into_the_overscroll() {
1621        test_widgets_variant(ios_and_macos(), |tester| {
1622            let platform = tester.target_platform();
1623            let density_vertical = if platform == TargetPlatform::MacOS {
1624                -2.0
1625            } else {
1626                0.0
1627            };
1628            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1629            let (key, button) = (GlobalKey::new(), GlobalKey::new());
1630            tester.pump_widget(boilerplate(
1631                vec![
1632                    five_fixed_extent_items(),
1633                    fill_without_scroll_body(true, padded_center_button(platform, &key, &button)),
1634                ],
1635                Some(controller.clone()),
1636                Axis::Vertical,
1637            ));
1638
1639            // Scroll to the end
1640            jump_to_max_scroll_extent(tester, controller.handle());
1641            assert_eq!(
1642                tester.get_size(&key).height(),
1643                148.0 + density_vertical * 4.0,
1644                "{platform:?}"
1645            );
1646            // Check that the button alignment is true to expectations
1647            let button_rect = tester.get_rect(&button);
1648            assert_eq!(button_rect.bottom, 550.0, "{platform:?}");
1649            assert_eq!(button_rect.center().dx(), 400.0, "{platform:?}");
1650
1651            // Overscroll and check size
1652            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1653            tester.pump();
1654            assert!(tester.get_size(&key).height() > 148.0, "{platform:?}");
1655
1656            // Check that the button alignment is true to expectations
1657            let button_rect = tester.get_rect(&button);
1658            assert!(button_rect.bottom < 550.0, "{platform:?}");
1659            assert_eq!(button_rect.center().dx(), 400.0, "{platform:?}");
1660
1661            // Ensure overscroll retracts to original size after releasing gesture
1662            tester.pump_and_settle();
1663            assert_eq!(
1664                tester.get_size(&key).height(),
1665                148.0 + density_vertical * 4.0,
1666                "{platform:?}"
1667            );
1668        });
1669    }
1670
1671    #[test]
1672    fn a_child_without_a_size_past_the_viewport_shows_only_in_the_overscroll() {
1673        test_widgets_variant(ios_and_macos(), |tester| {
1674            let platform = tester.target_platform();
1675            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1676            let key = GlobalKey::new();
1677            tester.pump_widget(boilerplate(
1678                vec![
1679                    five_fixed_extent_items(),
1680                    fill_without_scroll_body(
1681                        true,
1682                        ColoredBox::new(DEBUG_RED)
1683                            .key(key.clone().into())
1684                            .into_widget(),
1685                    ),
1686                ],
1687                Some(controller.clone()),
1688                Axis::Vertical,
1689            ));
1690            expect(tester, &find::by_global_key(&key), finds_nothing());
1691            assert!(!fixed_extent_item_is_onstage(tester, 4), "{platform:?}");
1692
1693            // Scroll to bottom
1694            jump_to_max_scroll_extent(tester, controller.handle());
1695            // End of list
1696            expect(tester, &find::by_global_key(&key), finds_nothing());
1697            assert!(fixed_extent_item_is_onstage(tester, 4), "{platform:?}");
1698
1699            // Overscroll
1700            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1701            tester.pump();
1702            expect(tester, &find::by_global_key(&key), finds_one_widget());
1703            assert!(fixed_extent_item_is_onstage(tester, 4), "{platform:?}");
1704
1705            tester.pump_and_settle();
1706            expect(tester, &find::by_global_key(&key), finds_nothing());
1707            assert!(fixed_extent_item_is_onstage(tester, 4), "{platform:?}");
1708        });
1709    }
1710
1711    /// Whether the fixed extent list's item `index` is onstage: `find.bySemanticsLabel` finds
1712    /// it, which waits for accessibility.
1713    fn fixed_extent_item_is_onstage(tester: &WidgetTester, index: i32) -> bool {
1714        onstage_children_of::<RenderSliverFixedExtentList>(tester).contains(&index)
1715    }
1716
1717    #[test]
1718    fn a_child_without_a_size_past_the_viewport_ignores_fill_overscroll_where_scrolling_clamps() {
1719        test_widgets(|tester| {
1720            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1721            let key = GlobalKey::new();
1722            tester.pump_widget(boilerplate(
1723                vec![
1724                    five_fixed_extent_items(),
1725                    fill_without_scroll_body(
1726                        true,
1727                        ColoredBox::new(DEBUG_RED)
1728                            .key(key.clone().into())
1729                            .into_widget(),
1730                    ),
1731                ],
1732                Some(controller.clone()),
1733                Axis::Vertical,
1734            ));
1735            expect(tester, &find::by_global_key(&key), finds_nothing());
1736            assert!(!fixed_extent_item_is_onstage(tester, 4));
1737
1738            // Scroll to bottom
1739            jump_to_max_scroll_extent(tester, controller.handle());
1740
1741            // End of list
1742            expect(tester, &find::by_global_key(&key), finds_nothing());
1743            assert!(fixed_extent_item_is_onstage(tester, 4));
1744
1745            // Overscroll
1746            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1747            tester.pump();
1748
1749            expect(tester, &find::by_global_key(&key), finds_nothing());
1750            assert!(fixed_extent_item_is_onstage(tester, 4));
1751        });
1752    }
1753
1754    #[test]
1755    fn a_sized_child_ignores_fill_overscroll_where_scrolling_clamps() {
1756        test_widgets(|tester| {
1757            let (key, button) = (GlobalKey::new(), GlobalKey::new());
1758            tester.pump_widget(boilerplate(
1759                vec![
1760                    sliver_box(),
1761                    fill_without_scroll_body(
1762                        true,
1763                        bottom_center_button(TargetPlatform::Android, &key, &button),
1764                    ),
1765                ],
1766                None,
1767                Axis::Vertical,
1768            ));
1769            assert_eq!(tester.get_size(&key).height(), 450.0);
1770
1771            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1772            tester.pump();
1773            assert_eq!(tester.get_size(&key).height(), 450.0);
1774
1775            // Also check that the button alignment is true to expectations
1776            let button_rect = tester.get_rect(&button);
1777            assert_eq!(button_rect.bottom, 600.0);
1778            assert_eq!(button_rect.center().dx(), 400.0);
1779        });
1780    }
1781
1782    #[test]
1783    fn a_larger_child_ignores_fill_overscroll_where_scrolling_clamps() {
1784        test_widgets(|tester| {
1785            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
1786            let (key, button) = (GlobalKey::new(), GlobalKey::new());
1787            tester.pump_widget(boilerplate(
1788                vec![
1789                    five_fixed_extent_items(),
1790                    fill_without_scroll_body(
1791                        true,
1792                        padded_center_button(TargetPlatform::Android, &key, &button),
1793                    ),
1794                ],
1795                Some(controller.clone()),
1796                Axis::Vertical,
1797            ));
1798
1799            // Scroll to the end
1800            jump_to_max_scroll_extent(tester, controller.handle());
1801            assert_eq!(tester.get_size(&key).height(), 148.0);
1802
1803            // Check that the button alignment is true to expectations
1804            let button_rect = tester.get_rect(&button);
1805            assert_eq!(button_rect.bottom, 550.0);
1806            assert_eq!(button_rect.center().dx(), 400.0);
1807
1808            tester.drag(find::by_type::<Scrollable>(), Offset::new(0.0, -50.0));
1809            tester.pump();
1810            assert_eq!(tester.get_size(&key).height(), 148.0);
1811
1812            // Check that the button alignment is still centered
1813            let button_rect = tester.get_rect(&button);
1814            assert_eq!(button_rect.bottom, 550.0);
1815            assert_eq!(button_rect.center().dx(), 400.0);
1816        });
1817    }
1818}