Skip to main content

waft_widgets/widgets/
scroll_view.rs

1//! Flutter counterpart: `widgets/scroll_view.dart`.
2//!
3//! [`ScrollView`] is Dart's abstract stateless widget: a trait over a
4//! [`ScrollViewData`] bag whose shared `build` body lives on [`ScrollViewBase`].
5//! [`CustomScrollView`], [`BoxScrollView`], [`ListView`] and [`GridView`] follow.
6
7use std::fmt::Debug;
8use std::rc::Rc;
9
10use waft_embedder::Clip;
11use waft_foundation::{
12    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty,
13    FlagProperty,
14};
15use waft_gestures::DragStartBehavior;
16use waft_painting::{Axis, AxisDirection, EdgeInsetsGeometry};
17use waft_rendering::{
18    HitTestBehavior, ItemExtentBuilder, ScrollCacheExtent, SliverGridDelegate,
19    SliverGridDelegateWithFixedCrossAxisCount, SliverGridDelegateWithMaxCrossAxisExtent,
20    SliverPaintOrder, ViewportOffsetRef,
21};
22
23use crate::framework::{
24    BuildContext, IntoWidget, KeyRef, StatelessKind, StatelessWidget, WidgetRef,
25};
26use crate::widgets::basic::{
27    SliverPadding, get_axis_direction_from_axis_reverse_and_directionality,
28};
29use crate::widgets::focus_manager::{FocusNodeLeaf, UnfocusDisposition, primary_focus};
30use crate::widgets::focus_scope::FocusScope;
31use crate::widgets::media_query::MediaQuery;
32use crate::widgets::notification_listener::NotificationListener;
33use crate::widgets::primary_scroll_controller::PrimaryScrollController;
34use crate::widgets::scroll_configuration::{ScrollBehaviorRef, ScrollConfiguration};
35use crate::widgets::scroll_controller::ScrollControllerRef;
36use crate::widgets::scroll_delegate::{
37    ChildIndexGetter, NullableIndexedWidgetBuilder, SliverChildBuilderDelegate,
38    SliverChildDelegateRef, SliverChildListDelegate,
39};
40use crate::widgets::scroll_notification::ScrollUpdateNotification;
41use crate::widgets::scroll_physics::{AlwaysScrollableScrollPhysics, ScrollPhysicsRef};
42use crate::widgets::scrollable::{Scrollable, ViewportBuilder};
43use crate::widgets::sliver::{
44    SliverFixedExtentList, SliverGrid, SliverList, SliverVariedExtentList,
45};
46use crate::widgets::sliver_prototype_extent_list::SliverPrototypeExtentList;
47use crate::widgets::viewport::{ShrinkWrappingViewport, Viewport};
48
49/// A representation of how a [`ScrollView`] should dismiss the on-screen
50/// keyboard.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum ScrollViewKeyboardDismissBehavior {
53    /// There is no automatic dismissal of the on-screen keyboard. It is up to the
54    /// client to dismiss the keyboard.
55    #[default]
56    Manual,
57
58    /// The [`ScrollView`] will dismiss an on-screen keyboard when a drag begins.
59    OnDrag,
60}
61
62/// The fields of Dart's `ScrollView`, which its subclasses carry.
63///
64/// Dart's `physics` initializer — the one that substitutes an
65/// [`AlwaysScrollableScrollPhysics`] for an omitted physics — runs in
66/// [`ScrollViewBase::build`] instead, because a fluent setter cannot see the
67/// `primary`, `controller` and `scroll_direction` a later setter will supply.
68#[derive(Clone, Debug)]
69pub struct ScrollViewData {
70    pub key: Option<KeyRef>,
71
72    /// The [`Axis`] along which the scroll view's offset increases.
73    ///
74    /// For the direction in which active scrolling may be occurring, see
75    /// `ScrollDirection`.
76    ///
77    /// Defaults to [`Axis::Vertical`].
78    pub scroll_direction: Axis,
79
80    /// Whether the scroll view scrolls in the reading direction.
81    ///
82    /// For example, if the reading direction is left-to-right and
83    /// [`scroll_direction`](Self::scroll_direction) is [`Axis::Horizontal`], then the scroll
84    /// view scrolls from left to right when [`reverse`](Self::reverse) is false and from
85    /// right to left when it is true.
86    ///
87    /// Defaults to false.
88    pub reverse: bool,
89
90    /// An object that can be used to control the position to which this scroll
91    /// view is scrolled.
92    ///
93    /// Must be `None` if [`primary`](Self::primary) is true.
94    pub controller: Option<ScrollControllerRef>,
95
96    /// Whether this is the primary scroll view associated with the parent
97    /// [`PrimaryScrollController`].
98    ///
99    /// When this is true, the scroll view is scrollable even if it does not have
100    /// sufficient content to actually scroll. Otherwise, by default the user can
101    /// only scroll the view if it has sufficient content.
102    ///
103    /// Cannot be true while a controller is provided, only one controller can be
104    /// associated with a scroll view.
105    ///
106    /// Setting to false will explicitly prevent inheriting any
107    /// [`PrimaryScrollController`].
108    ///
109    /// Defaults to `None`. When `None`, and a controller is not provided,
110    /// [`PrimaryScrollController::should_inherit`] is used to decide automatic
111    /// inheritance.
112    pub primary: Option<bool>,
113
114    /// How the scroll view should respond to user input.
115    ///
116    /// For example, determines how the scroll view continues to animate after the
117    /// user stops dragging the scroll view.
118    ///
119    /// Defaults to matching platform conventions. Furthermore, if
120    /// [`primary`](Self::primary) is false, then the user cannot scroll if there is
121    /// insufficient content to scroll, while if it is true, they can always attempt to
122    /// scroll.
123    ///
124    /// If an explicit [`ScrollBehaviorRef`] is provided to
125    /// [`scroll_behavior`](Self::scroll_behavior), the physics provided by that behavior
126    /// will take precedence after this one.
127    pub physics: Option<ScrollPhysicsRef>,
128
129    /// A [`ScrollBehaviorRef`] that will be applied to this widget individually.
130    ///
131    /// Defaults to `None`, wherein the inherited behavior is copied and modified to
132    /// alter the viewport decoration.
133    pub scroll_behavior: Option<ScrollBehaviorRef>,
134
135    /// Whether the extent of the scroll view in the
136    /// [`scroll_direction`](Self::scroll_direction) should be determined by the contents
137    /// being viewed.
138    ///
139    /// If the scroll view does not shrink wrap, then the scroll view will expand
140    /// to the maximum allowed size in the scroll direction. If the scroll view
141    /// has unbounded constraints in the scroll direction, then this must be true.
142    ///
143    /// Shrink wrapping the content of the scroll view is significantly more
144    /// expensive than expanding to the maximum allowed size because the content
145    /// can expand and contract during scrolling, which means the size of the
146    /// scroll view needs to be recomputed whenever the scroll position changes.
147    ///
148    /// Defaults to false.
149    pub shrink_wrap: bool,
150
151    /// The first child in the `GrowthDirection::Forward` growth direction.
152    ///
153    /// Children after the center will be placed in the [`AxisDirection`] determined
154    /// by [`scroll_direction`](Self::scroll_direction) and [`reverse`](Self::reverse)
155    /// relative to the center. Children before the center will be placed in the opposite
156    /// of the axis direction relative to the center. This makes the center the inflection
157    /// point of the growth direction.
158    ///
159    /// The center must be the key of one of the slivers built by
160    /// [`ScrollView::build_slivers`].
161    ///
162    /// Of the built-in subclasses of [`ScrollView`], only [`CustomScrollView`]
163    /// supports a center.
164    pub center: Option<KeyRef>,
165
166    /// The relative position of the zero scroll offset.
167    ///
168    /// For example, if the anchor is 0.5 and the [`AxisDirection`] determined by
169    /// [`scroll_direction`](Self::scroll_direction) and [`reverse`](Self::reverse) is
170    /// [`AxisDirection::Down`] or [`AxisDirection::Up`], then the zero scroll offset is
171    /// vertically centered within the viewport. If the anchor is 1.0, and the axis
172    /// direction is [`AxisDirection::Right`], then the zero scroll offset is on the left
173    /// edge of the viewport.
174    pub anchor: f64,
175
176    /// Deprecated: use [`scroll_cache_extent`](Self::scroll_cache_extent) instead.
177    ///
178    /// The viewport has an area before and after the visible area to cache items
179    /// that are about to become visible when the user scrolls.
180    #[deprecated(note = "Use scroll_cache_extent instead.")]
181    pub cache_extent: Option<f64>,
182
183    /// The viewport has an area before and after the visible area to cache items
184    /// that are about to become visible when the user scrolls.
185    pub scroll_cache_extent: Option<ScrollCacheExtent>,
186
187    /// The number of children that will contribute semantic information.
188    ///
189    /// Some subtypes of [`ScrollView`] can infer this value automatically. For
190    /// example [`ListView`] will use the number of widgets in the child list,
191    /// while the [`ListView::separated`] constructor will use half that amount.
192    ///
193    /// For [`CustomScrollView`] and other types which do not receive a builder
194    /// or list of widgets, the child count must be explicitly provided. If the
195    /// number is unknown or unbounded this should be left unset.
196    pub semantic_child_count: Option<i32>,
197
198    /// The order in which the viewport paints its slivers.
199    ///
200    /// Defaults to [`SliverPaintOrder::FirstIsTop`].
201    pub paint_order: SliverPaintOrder,
202
203    /// Determines the way that drag start behavior is handled.
204    pub drag_start_behavior: DragStartBehavior,
205
206    /// How this [`ScrollView`] will dismiss the keyboard automatically.
207    ///
208    /// If `None` then it will fall back to
209    /// [`scroll_behavior`](Self::scroll_behavior). If that is also `None`, the inherited
210    /// [`ScrollBehavior::get_keyboard_dismiss_behavior`](crate::ScrollBehavior::get_keyboard_dismiss_behavior)
211    /// will be used.
212    pub keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,
213
214    /// Restoration ID to save and restore the scroll offset of the scrollable.
215    pub restoration_id: Option<String>,
216
217    /// The content will be clipped (or not) according to this option.
218    ///
219    /// Defaults to [`Clip::HardEdge`].
220    pub clip_behavior: Clip,
221
222    /// How to behave during hit testing when deciding how the hit test propagates
223    /// to children and whether to consider targets behind this scroll view.
224    ///
225    /// Defaults to [`HitTestBehavior::Opaque`].
226    pub hit_test_behavior: HitTestBehavior,
227}
228
229impl ScrollViewData {
230    /// Dart's `ScrollView.debugFillProperties`, which every scroll view's own body calls where
231    /// Dart writes `super`.
232    pub fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
233        properties.add(EnumProperty::new("scrollDirection", self.scroll_direction));
234        properties.add(
235            FlagProperty::new("reverse", Some(self.reverse))
236                .if_true("reversed")
237                .with_show_name(true),
238        );
239        properties.add(
240            DiagnosticsProperty::<String>::new(
241                "controller",
242                self.controller
243                    .as_ref()
244                    .map(|controller| controller.to_string(app)),
245            )
246            .with_show_name(false)
247            .default_value(None),
248        );
249        properties.add(
250            FlagProperty::new("primary", self.primary)
251                .if_true("using primary controller")
252                .with_show_name(true),
253        );
254        properties.add(
255            DiagnosticsProperty::<String>::new(
256                "physics",
257                self.physics.as_ref().map(|physics| format!("{physics:?}")),
258            )
259            .with_show_name(false)
260            .default_value(None),
261        );
262        properties.add(
263            FlagProperty::new("shrinkWrap", Some(self.shrink_wrap))
264                .if_true("shrink-wrapping")
265                .with_show_name(true),
266        );
267        properties.add(
268            DiagnosticsProperty::<ScrollCacheExtent>::new(
269                "scrollCacheExtent",
270                self.scroll_cache_extent,
271            )
272            .default_value(None),
273        );
274    }
275
276    /// Dart's `ScrollView` constructor defaults.
277    pub fn new() -> ScrollViewData {
278        #[allow(deprecated)]
279        ScrollViewData {
280            key: None,
281            scroll_direction: Axis::Vertical,
282            reverse: false,
283            controller: None,
284            primary: None,
285            physics: None,
286            scroll_behavior: None,
287            shrink_wrap: false,
288            center: None,
289            anchor: 0.0,
290            cache_extent: None,
291            scroll_cache_extent: None,
292            semantic_child_count: None,
293            paint_order: SliverPaintOrder::FirstIsTop,
294            drag_start_behavior: DragStartBehavior::Start,
295            keyboard_dismiss_behavior: None,
296            restoration_id: None,
297            clip_behavior: Clip::HardEdge,
298            hit_test_behavior: HitTestBehavior::Opaque,
299        }
300    }
301}
302
303impl Default for ScrollViewData {
304    fn default() -> ScrollViewData {
305        ScrollViewData::new()
306    }
307}
308
309/// The [`ScrollViewData`] accessors a [`ScrollView`] implementor writes; the bag lives under
310/// the field `scroll_view`.
311#[macro_export]
312macro_rules! scroll_view_accessors {
313    () => {
314        fn scroll_view_data(&self) -> &$crate::ScrollViewData {
315            &self.scroll_view
316        }
317
318        fn scroll_view_data_mut(&mut self) -> &mut $crate::ScrollViewData {
319            &mut self.scroll_view
320        }
321    };
322}
323
324/// The fluent setters of the `ScrollView` named arguments every subclass takes; the ones
325/// only `CustomScrollView` exposes (`scrollBehavior`, `center`, `anchor`, `paintOrder`) are
326/// written on it.
327#[macro_export]
328macro_rules! scroll_view_setters {
329    ($name:ident) => {
330        /// Dart `key:`.
331        pub fn key(mut self, key: $crate::KeyRef) -> $name {
332            self.scroll_view.key = Some(key);
333            self
334        }
335
336        /// Dart `scrollDirection:`.
337        pub fn scroll_direction(mut self, scroll_direction: waft_painting::Axis) -> $name {
338            self.scroll_view.scroll_direction = scroll_direction;
339            self
340        }
341
342        /// Dart `reverse:`.
343        pub fn reverse(mut self, reverse: bool) -> $name {
344            self.scroll_view.reverse = reverse;
345            self
346        }
347
348        /// Dart `controller:`.
349        pub fn controller(mut self, controller: $crate::ScrollControllerRef) -> $name {
350            debug_assert!(
351                !self.scroll_view.primary.unwrap_or(false),
352                "Primary ScrollViews obtain their ScrollController via inheritance from a \
353                 PrimaryScrollController widget. You cannot both set primary to true and pass \
354                 an explicit controller."
355            );
356            self.scroll_view.controller = Some(controller);
357            self
358        }
359
360        /// Dart `primary:`.
361        pub fn primary(mut self, primary: bool) -> $name {
362            debug_assert!(
363                !(self.scroll_view.controller.is_some() && primary),
364                "Primary ScrollViews obtain their ScrollController via inheritance from a \
365                 PrimaryScrollController widget. You cannot both set primary to true and pass \
366                 an explicit controller."
367            );
368            self.scroll_view.primary = Some(primary);
369            self
370        }
371
372        /// Dart `physics:`.
373        pub fn physics(mut self, physics: $crate::ScrollPhysicsRef) -> $name {
374            self.scroll_view.physics = Some(physics);
375            self
376        }
377
378        /// Dart `shrinkWrap:`.
379        pub fn shrink_wrap(mut self, shrink_wrap: bool) -> $name {
380            debug_assert!(!shrink_wrap || self.scroll_view.center.is_none());
381            self.scroll_view.shrink_wrap = shrink_wrap;
382            self
383        }
384
385        /// Dart `cacheExtent:`.
386        #[deprecated(note = "Use scroll_cache_extent instead.")]
387        pub fn cache_extent(mut self, cache_extent: f64) -> $name {
388            #[allow(deprecated)]
389            {
390                self.scroll_view.cache_extent = Some(cache_extent);
391            }
392            self
393        }
394
395        /// Dart `scrollCacheExtent:`.
396        pub fn scroll_cache_extent(
397            mut self,
398            scroll_cache_extent: waft_rendering::ScrollCacheExtent,
399        ) -> $name {
400            self.scroll_view.scroll_cache_extent = Some(scroll_cache_extent);
401            self
402        }
403
404        /// Dart `semanticChildCount:`.
405        pub fn semantic_child_count(mut self, semantic_child_count: i32) -> $name {
406            debug_assert!(semantic_child_count >= 0);
407            self.scroll_view.semantic_child_count = Some(semantic_child_count);
408            self
409        }
410
411        /// Dart `dragStartBehavior:`.
412        pub fn drag_start_behavior(
413            mut self,
414            drag_start_behavior: waft_gestures::DragStartBehavior,
415        ) -> $name {
416            self.scroll_view.drag_start_behavior = drag_start_behavior;
417            self
418        }
419
420        /// Dart `keyboardDismissBehavior:`.
421        pub fn keyboard_dismiss_behavior(
422            mut self,
423            keyboard_dismiss_behavior: $crate::ScrollViewKeyboardDismissBehavior,
424        ) -> $name {
425            self.scroll_view.keyboard_dismiss_behavior = Some(keyboard_dismiss_behavior);
426            self
427        }
428
429        /// Dart `restorationId:`.
430        pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> $name {
431            self.scroll_view.restoration_id = Some(restoration_id.into());
432            self
433        }
434
435        /// Dart `clipBehavior:`.
436        pub fn clip_behavior(mut self, clip_behavior: waft_embedder::Clip) -> $name {
437            self.scroll_view.clip_behavior = clip_behavior;
438            self
439        }
440
441        /// Dart `hitTestBehavior:`.
442        pub fn hit_test_behavior(
443            mut self,
444            hit_test_behavior: waft_rendering::HitTestBehavior,
445        ) -> $name {
446            self.scroll_view.hit_test_behavior = hit_test_behavior;
447            self
448        }
449    };
450}
451
452/// A widget that combines a `Scrollable` and a [`Viewport`] to create an
453/// interactive scrolling pane of content in one dimension.
454///
455/// Scrollable widgets consist of three pieces:
456///
457///  1. A `Scrollable` widget, which listens for various user gestures and
458///     implements the interaction design for scrolling.
459///  2. A viewport widget, such as [`Viewport`] or [`ShrinkWrappingViewport`], which
460///     implements the visual design for scrolling by displaying only a portion
461///     of the widgets inside the scroll view.
462///  3. One or more slivers, which are widgets that can be composed to create
463///     various scrolling effects, such as lists, grids, and expanding headers.
464///
465/// [`ScrollView`] helps orchestrate these pieces by creating the `Scrollable` and
466/// the viewport and deferring to its implementor to create the slivers.
467///
468/// Dart's abstract `ScrollView` is this trait over a [`ScrollViewData`] bag; the shared
469/// `build` body lives on [`ScrollViewBase`], which an implementor's
470/// [`StatelessWidget::build`] calls.
471///
472/// ## Persisting the scroll position during a session
473///
474/// Scroll views attempt to persist their scroll position using `PageStorage`.
475/// This can be disabled by setting
476/// [`ScrollControllerLeaf::keep_scroll_offset`](crate::ScrollControllerLeaf::keep_scroll_offset)
477/// to false on the controller.
478pub trait ScrollView: Clone + Debug + Sized + 'static {
479    /// The [`ScrollViewData`] bag ([`scroll_view_accessors!`](crate::scroll_view_accessors)).
480    fn scroll_view_data(&self) -> &ScrollViewData;
481
482    /// The [`ScrollViewData`] bag, mutably.
483    fn scroll_view_data_mut(&mut self) -> &mut ScrollViewData;
484
485    /// Returns the [`AxisDirection`] in which the scroll view scrolls.
486    ///
487    /// Combines the [`ScrollViewData::scroll_direction`] with the
488    /// [`ScrollViewData::reverse`] boolean to obtain the concrete [`AxisDirection`].
489    ///
490    /// If the scroll direction is [`Axis::Horizontal`], the ambient `Directionality` is
491    /// also considered when selecting the concrete [`AxisDirection`].
492    fn get_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
493        ScrollViewBase::get_direction(self, app, context)
494    }
495
496    /// Build the list of widgets to place inside the viewport.
497    ///
498    /// Implementors override this method to build the slivers for the inside of
499    /// the viewport.
500    fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef>;
501
502    /// Build the viewport.
503    ///
504    /// Implementors may override this method to change how the viewport is built.
505    /// The default implementation uses a [`ShrinkWrappingViewport`] if
506    /// [`ScrollViewData::shrink_wrap`] is true, and a regular [`Viewport`] otherwise.
507    ///
508    /// The `offset` argument is the value obtained from
509    /// [`Scrollable::viewport_builder`].
510    ///
511    /// The `axis_direction` argument is the value obtained from
512    /// [`get_direction`](Self::get_direction).
513    ///
514    /// The `slivers` argument is the value obtained from
515    /// [`build_slivers`](Self::build_slivers).
516    fn build_viewport(
517        &self,
518        app: &mut App,
519        context: BuildContext,
520        offset: ViewportOffsetRef,
521        axis_direction: AxisDirection,
522        slivers: Vec<WidgetRef>,
523    ) -> WidgetRef {
524        ScrollViewBase::build_viewport(self, app, context, offset, axis_direction, slivers)
525    }
526}
527
528/// The shared bodies of Dart's `ScrollView`: call one where Dart writes `super.…`.
529pub struct ScrollViewBase;
530
531impl ScrollViewBase {
532    /// See [`ScrollView::get_direction`].
533    pub fn get_direction<V: ScrollView>(
534        view: &V,
535        app: &mut App,
536        context: BuildContext,
537    ) -> AxisDirection {
538        let data = view.scroll_view_data();
539        get_axis_direction_from_axis_reverse_and_directionality(
540            app,
541            context,
542            data.scroll_direction,
543            data.reverse,
544        )
545    }
546
547    /// See [`ScrollView::build_viewport`].
548    pub fn build_viewport<V: ScrollView>(
549        view: &V,
550        app: &mut App,
551        context: BuildContext,
552        offset: ViewportOffsetRef,
553        axis_direction: AxisDirection,
554        slivers: Vec<WidgetRef>,
555    ) -> WidgetRef {
556        let _ = (app, context);
557        let data = view.scroll_view_data();
558        #[allow(deprecated)]
559        let effective_scroll_cache_extent = data
560            .scroll_cache_extent
561            .or(data.cache_extent.map(ScrollCacheExtent::Pixels));
562        if data.shrink_wrap {
563            let mut viewport = ShrinkWrappingViewport::new(offset)
564                .axis_direction(axis_direction)
565                .slivers(slivers)
566                .paint_order(data.paint_order)
567                .clip_behavior(data.clip_behavior);
568            if let Some(cache_extent) = effective_scroll_cache_extent {
569                viewport = viewport.scroll_cache_extent(cache_extent);
570            }
571            return viewport.into_widget();
572        }
573        let mut viewport = Viewport::new(offset)
574            .axis_direction(axis_direction)
575            .slivers(slivers)
576            .anchor(data.anchor)
577            .paint_order(data.paint_order)
578            .clip_behavior(data.clip_behavior);
579        if let Some(cache_extent) = effective_scroll_cache_extent {
580            viewport = viewport.scroll_cache_extent(cache_extent);
581        }
582        if let Some(center) = data.center.clone() {
583            viewport = viewport.center(center);
584        }
585        viewport.into_widget()
586    }
587
588    /// Dart's `ScrollView.build`, which an implementor's [`StatelessWidget::build`] calls.
589    pub fn build<V: ScrollView>(view: &V, app: &mut App, context: BuildContext) -> WidgetRef {
590        let slivers = view.build_slivers(app, context);
591        let axis_direction = view.get_direction(app, context);
592
593        let data = view.scroll_view_data().clone();
594        let effective_primary = data.primary.unwrap_or_else(|| {
595            data.controller.is_none()
596                && PrimaryScrollController::should_inherit(app, context, data.scroll_direction)
597        });
598
599        let scroll_controller = if effective_primary {
600            PrimaryScrollController::maybe_of(app, context)
601        } else {
602            data.controller
603        };
604
605        let this = view.clone();
606        let viewport_builder: ViewportBuilder = Rc::new(move |app, context, offset| {
607            this.build_viewport(app, context, offset, axis_direction, slivers.clone())
608        });
609
610        let mut scrollable = Scrollable::new(viewport_builder)
611            .axis_direction(axis_direction)
612            .drag_start_behavior(data.drag_start_behavior)
613            .hit_test_behavior(data.hit_test_behavior)
614            .clip_behavior(data.clip_behavior);
615        let has_scroll_controller = scroll_controller.is_some();
616        if let Some(controller) = scroll_controller {
617            scrollable = scrollable.controller(controller);
618        }
619        if let Some(physics) = ScrollViewBase::effective_physics(view) {
620            scrollable = scrollable.physics(physics);
621        }
622        if let Some(scroll_behavior) = data.scroll_behavior.clone() {
623            scrollable = scrollable.scroll_behavior(scroll_behavior);
624        }
625        if let Some(restoration_id) = data.restoration_id.clone() {
626            scrollable = scrollable.restoration_id(restoration_id);
627        }
628
629        let scrollable_result = if effective_primary && has_scroll_controller {
630            // Further descendant scroll views will not inherit the same
631            // `PrimaryScrollController`.
632            PrimaryScrollController::none(scrollable).into_widget()
633        } else {
634            scrollable.into_widget()
635        };
636
637        let effective_keyboard_dismiss_behavior = data
638            .keyboard_dismiss_behavior
639            .or_else(|| {
640                data.scroll_behavior
641                    .as_ref()
642                    .map(|behavior| behavior.get_keyboard_dismiss_behavior(app, context))
643            })
644            .unwrap_or_else(|| {
645                ScrollConfiguration::of(app, context).get_keyboard_dismiss_behavior(app, context)
646            });
647
648        if effective_keyboard_dismiss_behavior == ScrollViewKeyboardDismissBehavior::OnDrag {
649            NotificationListener::<ScrollUpdateNotification>::new(scrollable_result)
650                .on_notification(move |app, notification: &ScrollUpdateNotification| {
651                    let current_scope = FocusScope::of(app, context, true).as_node();
652                    if notification.drag_details.is_some()
653                        && !current_scope.has_primary_focus(app)
654                        && current_scope.has_focus(app)
655                        && let Some(primary) = primary_focus(app)
656                    {
657                        primary.unfocus(app, UnfocusDisposition::Scope);
658                    }
659                    false
660                })
661                .into_widget()
662        } else {
663            scrollable_result
664        }
665    }
666
667    /// Dart's `physics` constructor initializer: an omitted physics becomes an
668    /// [`AlwaysScrollableScrollPhysics`] for a primary scroll view, and for a vertical one
669    /// that neither names a controller nor opts out of inheriting the primary one.
670    fn effective_physics<V: ScrollView>(view: &V) -> Option<ScrollPhysicsRef> {
671        let data = view.scroll_view_data();
672        if let Some(physics) = data.physics.clone() {
673            return Some(physics);
674        }
675        let implied = data.primary.unwrap_or(false)
676            || (data.primary.is_none()
677                && data.controller.is_none()
678                && data.scroll_direction == Axis::Vertical);
679        implied.then(|| Rc::new(AlwaysScrollableScrollPhysics::new()) as ScrollPhysicsRef)
680    }
681}
682
683/// A [`ScrollView`] that combines multiple [`slivers`](Self::slivers) in one scrollable view.
684///
685/// A [`CustomScrollView`] lets you combine lists, grids, and other widgets in a
686/// single scrollable view by supplying slivers directly. Slivers can
687/// represent lists, grids, and expanding headers. Widgets that use the box
688/// layout model can be included using a `SliverToBoxAdapter`.
689///
690/// ```ignore
691/// CustomScrollView::new().slivers([
692///     SliverToBoxAdapter::new().child(header).into_widget(),
693///     SliverList::list(items).into_widget(),
694/// ])
695/// ```
696#[derive(Clone, Debug, Default)]
697pub struct CustomScrollView {
698    scroll_view: ScrollViewData,
699
700    /// The slivers to place inside the viewport.
701    ///
702    /// A _sliver_ is a widget backed by a `RenderSliver`, i.e. one that implements the
703    /// constraint/geometry protocol that uses `SliverConstraints` and `SliverGeometry`.
704    /// This is as distinct from those widgets that are backed by `RenderBox`, which use
705    /// `BoxConstraints` and `Size` respectively, and are known as box widgets.
706    ///
707    /// While boxes are much more straightforward (implementing a simple two-dimensional
708    /// Cartesian layout system), slivers are much more powerful, and are optimized for
709    /// one-axis scrolling environments.
710    ///
711    /// In general, slivers always wrap box widgets to actually render anything; the sliver
712    /// part of the equation is mostly about how these boxes should be laid out in a
713    /// viewport.
714    pub slivers: Vec<WidgetRef>,
715}
716
717impl CustomScrollView {
718    /// Creates a [`ScrollView`] that combines multiple slivers in one scrollable
719    /// view.
720    pub fn new() -> CustomScrollView {
721        CustomScrollView {
722            scroll_view: ScrollViewData::new(),
723            slivers: Vec::new(),
724        }
725    }
726
727    crate::scroll_view_setters!(CustomScrollView);
728
729    /// Dart `CustomScrollView(scrollBehavior:)`.
730    pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> CustomScrollView {
731        self.scroll_view.scroll_behavior = Some(scroll_behavior);
732        self
733    }
734
735    /// Dart `CustomScrollView(center:)`.
736    pub fn center(mut self, center: KeyRef) -> CustomScrollView {
737        debug_assert!(!self.scroll_view.shrink_wrap);
738        self.scroll_view.center = Some(center);
739        self
740    }
741
742    /// Dart `CustomScrollView(anchor:)`.
743    pub fn anchor(mut self, anchor: f64) -> CustomScrollView {
744        debug_assert!((0.0..=1.0).contains(&anchor));
745        self.scroll_view.anchor = anchor;
746        self
747    }
748
749    /// Dart `CustomScrollView(paintOrder:)`.
750    pub fn paint_order(mut self, paint_order: SliverPaintOrder) -> CustomScrollView {
751        self.scroll_view.paint_order = paint_order;
752        self
753    }
754
755    /// Dart `CustomScrollView(slivers:)`.
756    pub fn slivers(mut self, slivers: impl IntoIterator<Item = WidgetRef>) -> CustomScrollView {
757        self.slivers = slivers.into_iter().collect();
758        self
759    }
760}
761
762impl ScrollView for CustomScrollView {
763    crate::scroll_view_accessors!();
764
765    fn build_slivers(&self, _app: &mut App, _context: BuildContext) -> Vec<WidgetRef> {
766        self.slivers.clone()
767    }
768}
769
770impl StatelessWidget for CustomScrollView {
771    fn key(&self) -> Option<&KeyRef> {
772        self.scroll_view.key.as_ref()
773    }
774
775    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
776        self.scroll_view.debug_fill_properties(app, properties);
777    }
778
779    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
780        ScrollViewBase::build(self, app, context)
781    }
782}
783
784/// The fields Dart's `BoxScrollView` adds to a [`ScrollView`].
785#[derive(Clone, Debug, Default)]
786pub struct BoxScrollViewData {
787    /// The amount of space by which to inset the children.
788    pub padding: Option<EdgeInsetsGeometry>,
789}
790
791impl BoxScrollViewData {
792    /// Dart's `BoxScrollView.debugFillProperties`, which an implementor's own body calls where
793    /// Dart writes `super`.
794    pub fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
795        properties.add(
796            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
797                .default_value(None),
798        );
799    }
800
801    /// Dart's `BoxScrollView` constructor defaults.
802    pub fn new() -> BoxScrollViewData {
803        BoxScrollViewData { padding: None }
804    }
805}
806
807/// The [`BoxScrollViewData`] accessors a [`BoxScrollView`] implementor writes; the bag lives
808/// under the field `box_scroll_view`.
809#[macro_export]
810macro_rules! box_scroll_view_accessors {
811    () => {
812        fn box_scroll_view_data(&self) -> &$crate::BoxScrollViewData {
813            &self.box_scroll_view
814        }
815
816        fn box_scroll_view_data_mut(&mut self) -> &mut $crate::BoxScrollViewData {
817            &mut self.box_scroll_view
818        }
819    };
820}
821
822/// A [`ScrollView`] that uses a single child layout model.
823///
824/// Scroll views are often decorated with scrollbars and overscroll indicators,
825/// which are managed by the inherited
826/// [`ScrollBehavior`](crate::ScrollBehavior). Placing a [`ScrollConfiguration`] above a
827/// scroll view can modify these behaviors for that scroll view.
828///
829/// The shared `buildSlivers` body lives on [`BoxScrollViewBase`], which an implementor's
830/// [`ScrollView::build_slivers`] calls.
831pub trait BoxScrollView: ScrollView {
832    /// The [`BoxScrollViewData`] bag
833    /// ([`box_scroll_view_accessors!`](crate::box_scroll_view_accessors)).
834    fn box_scroll_view_data(&self) -> &BoxScrollViewData;
835
836    /// The [`BoxScrollViewData`] bag, mutably.
837    fn box_scroll_view_data_mut(&mut self) -> &mut BoxScrollViewData;
838
839    /// Implementors override this method to build the layout model.
840    fn build_child_layout(&self, app: &mut App, context: BuildContext) -> WidgetRef;
841}
842
843/// The shared bodies of Dart's `BoxScrollView`: call one where Dart writes `super.…`.
844pub struct BoxScrollViewBase;
845
846impl BoxScrollViewBase {
847    /// Dart's `BoxScrollView.buildSlivers`, which an implementor's
848    /// [`ScrollView::build_slivers`] calls.
849    pub fn build_slivers<V: BoxScrollView>(
850        view: &V,
851        app: &mut App,
852        context: BuildContext,
853    ) -> Vec<WidgetRef> {
854        let mut sliver = view.build_child_layout(app, context);
855        let padding = view.box_scroll_view_data().padding;
856        let mut effective_padding = padding;
857        if padding.is_none()
858            && let Some(media_query) = MediaQuery::maybe_of(app, context)
859        {
860            // Automatically pad sliver with padding from `MediaQuery`.
861            let media_query_horizontal_padding =
862                media_query
863                    .padding
864                    .copy_with(None, Some(0.0), None, Some(0.0));
865            let media_query_vertical_padding =
866                media_query
867                    .padding
868                    .copy_with(Some(0.0), None, Some(0.0), None);
869            let vertical = view.scroll_view_data().scroll_direction == Axis::Vertical;
870            // Consume the main axis padding with a `SliverPadding`.
871            effective_padding = Some(EdgeInsetsGeometry::from(if vertical {
872                media_query_vertical_padding
873            } else {
874                media_query_horizontal_padding
875            }));
876            // Leave behind the cross axis padding.
877            sliver = MediaQuery::new(
878                media_query.copy_with().padding(if vertical {
879                    media_query_horizontal_padding
880                } else {
881                    media_query_vertical_padding
882                }),
883                sliver,
884            )
885            .into_widget();
886        }
887
888        if let Some(effective_padding) = effective_padding {
889            sliver = SliverPadding::new(effective_padding)
890                .sliver(sliver)
891                .into_widget();
892        }
893        vec![sliver]
894    }
895}
896
897/// A scrollable list of widgets arranged linearly.
898///
899/// [`ListView`] is the most commonly used scrolling widget. It displays its
900/// children one after another in the scroll direction. In the cross axis, the
901/// children are required to fill the [`ListView`].
902///
903/// If non-`None`, the [`item_extent`](Self::item_extent) forces the children to have the
904/// given extent in the scroll direction. Specifying an item extent is more efficient than
905/// letting the children determine their own extent because the scrolling machinery can make
906/// use of the foreknowledge of the children's extent to save work, for example when the
907/// scroll position changes drastically.
908///
909/// If non-`None`, the [`prototype_item`](Self::prototype_item) forces the children to have the
910/// same extent as the given widget in the scroll direction. You can't specify more than one of
911/// [`item_extent`](Self::item_extent), [`prototype_item`](Self::prototype_item) and
912/// [`item_extent_builder`](Self::item_extent_builder).
913///
914/// There are four ways to construct a [`ListView`]:
915///
916///  1. [`ListView::new`] takes an explicit list of children through the
917///     [`children`](Self::children) setter. This is appropriate for list views with a small
918///     number of children because constructing the list requires doing work for every child
919///     that could possibly be displayed in the list view instead of just those children that
920///     are actually visible.
921///
922///  2. [`ListView::builder`] takes an item builder, which builds the children on demand.
923///     This is appropriate for list views with a large (or infinite) number of children
924///     because the builder is called only for those children that are actually visible.
925///
926///  3. [`ListView::separated`] takes two builders: `item_builder` builds child items on
927///     demand, and `separator_builder` similarly builds separator children which appear in
928///     between the child items. This is appropriate for list views with a fixed number of
929///     children.
930///
931///  4. [`ListView::custom`] takes a
932///     [`SliverChildDelegateRef`], which provides the ability to customize additional
933///     aspects of the child model.
934///
935/// By default, a [`ListView`] will automatically pad the list's scrollable
936/// extremities to avoid partial obstructions indicated by the `MediaQuery`'s
937/// padding. To avoid this behavior, override with a zero
938/// [`padding`](Self::padding).
939///
940/// ## Transitioning to [`CustomScrollView`]
941///
942/// A [`ListView`] is basically a [`CustomScrollView`] with a single [`SliverList`] in
943/// its [`CustomScrollView::slivers`] property. The
944/// [`padding`](Self::padding) corresponds to having a `SliverPadding` in the slivers
945/// instead of the list itself, and having the [`SliverList`] instead be a child of the
946/// `SliverPadding`.
947pub struct ListView {
948    scroll_view: ScrollViewData,
949    box_scroll_view: BoxScrollViewData,
950
951    /// If non-`None`, forces the children to have the given extent in the scroll
952    /// direction.
953    ///
954    /// Specifying an item extent is more efficient than letting the children
955    /// determine their own extent because the scrolling machinery can make use of
956    /// the foreknowledge of the children's extent to save work, for example when
957    /// the scroll position changes drastically.
958    pub item_extent: Option<f64>,
959
960    /// If non-`None`, forces the children to have the corresponding extent returned
961    /// by the builder.
962    ///
963    /// Specifying an item extent builder is more efficient than letting the
964    /// children determine their own extent because the scrolling machinery can
965    /// make use of the foreknowledge of the children's extent to save work, for
966    /// example when the scroll position changes drastically.
967    pub item_extent_builder: Option<ItemExtentBuilder>,
968
969    /// If non-`None`, forces the children to have the same extent as the given
970    /// widget in the scroll direction.
971    ///
972    /// Specifying a prototype item is more efficient than letting the children
973    /// determine their own extent because the scrolling machinery can make use of
974    /// the foreknowledge of the children's extent to save work, for example when
975    /// the scroll position changes drastically.
976    ///
977    /// See also:
978    ///
979    ///  * [`SliverPrototypeExtentList`], the sliver used internally when this
980    ///    property is provided. It constrains its box children to have the same
981    ///    extent as a prototype item along the main axis.
982    ///  * The [`item_extent`](Self::item_extent) property, which allows forcing the
983    ///    children's extent to a given value.
984    ///  * The [`item_extent_builder`](Self::item_extent_builder) property, which allows
985    ///    forcing the children's extent to be the value returned by the callback.
986    pub prototype_item: Option<WidgetRef>,
987
988    /// A delegate that provides the children for the [`ListView`].
989    ///
990    /// The [`SliverList::delegate`] property corresponds to this one.
991    pub children_delegate: SliverChildDelegateRef,
992
993    // Dart's default constructor's `children` and `add*` arguments, kept so that whichever
994    // of their setters runs last can rebuild `children_delegate` out of all of them. `None`
995    // for the constructors that take (or build) a delegate.
996    list_arguments: Option<ListArguments>,
997}
998
999/// The `SliverChildListDelegate` arguments of the Dart constructors that take children:
1000/// `ListView`'s default one, and `GridView`'s default, `count` and `extent` ones.
1001#[derive(Clone, Debug)]
1002struct ListArguments {
1003    children: Vec<WidgetRef>,
1004    add_automatic_keep_alives: bool,
1005    add_repaint_boundaries: bool,
1006    add_semantic_indexes: bool,
1007}
1008
1009impl ListArguments {
1010    fn new() -> ListArguments {
1011        ListArguments {
1012            children: Vec::new(),
1013            add_automatic_keep_alives: true,
1014            add_repaint_boundaries: true,
1015            add_semantic_indexes: true,
1016        }
1017    }
1018
1019    fn into_delegate(self) -> SliverChildDelegateRef {
1020        SliverChildListDelegate::new(self.children)
1021            .add_automatic_keep_alives(self.add_automatic_keep_alives)
1022            .add_repaint_boundaries(self.add_repaint_boundaries)
1023            .add_semantic_indexes(self.add_semantic_indexes)
1024            .into_delegate()
1025    }
1026}
1027
1028/// The fluent setters of the `SliverChildListDelegate` arguments, on a scroll view whose
1029/// `list_arguments` holds them; each rebuilds `children_delegate` out of all of them.
1030macro_rules! list_arguments_setters {
1031    ($name:ident) => {
1032        /// Dart `children:`.
1033        ///
1034        /// The children also fill in [`ScrollViewData::semantic_child_count`] while it still
1035        /// holds the constructor's default, as Dart's `semanticChildCount ?? children.length`
1036        /// does.
1037        pub fn children(self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
1038            let children: Vec<WidgetRef> = children.into_iter().collect();
1039            let count = children.len() as i32;
1040            let mut this = self.with_list_arguments(|arguments| arguments.children = children);
1041            if this.scroll_view.semantic_child_count == Some(0) {
1042                this.scroll_view.semantic_child_count = Some(count);
1043            }
1044            this
1045        }
1046
1047        /// Dart `addAutomaticKeepAlives:` on a constructor that takes children.
1048        pub fn add_automatic_keep_alives(self, value: bool) -> $name {
1049            self.with_list_arguments(|arguments| arguments.add_automatic_keep_alives = value)
1050        }
1051
1052        /// Dart `addRepaintBoundaries:` on a constructor that takes children.
1053        pub fn add_repaint_boundaries(self, value: bool) -> $name {
1054            self.with_list_arguments(|arguments| arguments.add_repaint_boundaries = value)
1055        }
1056
1057        /// Dart `addSemanticIndexes:` on a constructor that takes children.
1058        pub fn add_semantic_indexes(self, value: bool) -> $name {
1059            self.with_list_arguments(|arguments| arguments.add_semantic_indexes = value)
1060        }
1061
1062        /// Applies one of the constructor's delegate arguments and rebuilds
1063        /// [`children_delegate`](Self::children_delegate) out of all of them.
1064        fn with_list_arguments(mut self, apply: impl FnOnce(&mut ListArguments)) -> $name {
1065            let mut arguments = self.list_arguments.expect(concat!(
1066                "the children and add* setters belong to the ",
1067                stringify!($name),
1068                " constructors that take children"
1069            ));
1070            apply(&mut arguments);
1071            self.children_delegate = arguments.clone().into_delegate();
1072            self.list_arguments = Some(arguments);
1073            self
1074        }
1075    };
1076}
1077
1078impl ListView {
1079    /// Creates a scrollable, linear array of widgets from an explicit list, which
1080    /// the [`children`](Self::children) setter supplies.
1081    ///
1082    /// This constructor is appropriate for list views with a small number of
1083    /// children because constructing the list requires doing work for every
1084    /// child that could possibly be displayed in the list view instead of just
1085    /// those children that are actually visible.
1086    ///
1087    /// It is usually more efficient to create children on demand using
1088    /// [`ListView::builder`].
1089    pub fn new() -> ListView {
1090        let list_arguments = ListArguments::new();
1091        ListView {
1092            scroll_view: ScrollViewData {
1093                semantic_child_count: Some(0),
1094                ..ScrollViewData::new()
1095            },
1096            box_scroll_view: BoxScrollViewData::new(),
1097            item_extent: None,
1098            item_extent_builder: None,
1099            prototype_item: None,
1100            children_delegate: list_arguments.clone().into_delegate(),
1101            list_arguments: Some(list_arguments),
1102        }
1103    }
1104
1105    /// Creates a scrollable, linear array of widgets that are created on demand.
1106    ///
1107    /// This constructor is appropriate for list views with a large (or infinite)
1108    /// number of children because the builder is called only for those children
1109    /// that are actually visible.
1110    ///
1111    /// The item builder will be called only with indices greater than or equal to
1112    /// zero and less than [`item_count`](ListViewBuilder::item_count).
1113    pub fn builder(
1114        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1115    ) -> ListViewBuilder {
1116        ListViewBuilder::new(Rc::new(item_builder))
1117    }
1118
1119    /// Creates a fixed-length scrollable linear array of list "items" separated
1120    /// by list item "separators".
1121    ///
1122    /// This constructor is appropriate for list views with a large number of
1123    /// item and separator children because the builders are only called for
1124    /// the children that are actually visible.
1125    ///
1126    /// The `separator_builder` is similar to `item_builder`, except it is the widget that
1127    /// gets placed between `item_builder(context, index)` and
1128    /// `item_builder(context, index + 1)`.
1129    pub fn separated(
1130        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1131        separator_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1132        item_count: i32,
1133    ) -> ListViewSeparated {
1134        ListViewSeparated::new(
1135            Rc::new(item_builder),
1136            Rc::new(separator_builder),
1137            item_count,
1138        )
1139    }
1140
1141    /// Creates a scrollable, linear array of widgets with a custom child model.
1142    ///
1143    /// For example, a custom child model can control the algorithm used to
1144    /// estimate the size of children that are not actually visible.
1145    pub fn custom(children_delegate: SliverChildDelegateRef) -> ListView {
1146        ListView {
1147            scroll_view: ScrollViewData::new(),
1148            box_scroll_view: BoxScrollViewData::new(),
1149            item_extent: None,
1150            item_extent_builder: None,
1151            prototype_item: None,
1152            children_delegate,
1153            list_arguments: None,
1154        }
1155    }
1156
1157    crate::scroll_view_setters!(ListView);
1158
1159    /// Dart `ListView(padding:)`.
1160    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ListView {
1161        let padding = padding.into();
1162        self.box_scroll_view.padding = Some(padding);
1163        self
1164    }
1165
1166    /// Dart `ListView(itemExtent:)`.
1167    pub fn item_extent(mut self, item_extent: f64) -> ListView {
1168        debug_assert!(
1169            self.prototype_item.is_none() && self.item_extent_builder.is_none(),
1170            "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
1171        );
1172        self.item_extent = Some(item_extent);
1173        self
1174    }
1175
1176    /// Dart `ListView(itemExtentBuilder:)`.
1177    pub fn item_extent_builder(mut self, item_extent_builder: ItemExtentBuilder) -> ListView {
1178        debug_assert!(
1179            self.item_extent.is_none() && self.prototype_item.is_none(),
1180            "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
1181        );
1182        self.item_extent_builder = Some(item_extent_builder);
1183        self
1184    }
1185
1186    /// Dart `ListView(prototypeItem:)`.
1187    #[cfg_attr(debug_assertions, track_caller)]
1188    pub fn prototype_item<K>(mut self, prototype_item: impl IntoWidget<K>) -> ListView {
1189        debug_assert!(
1190            self.item_extent.is_none() && self.item_extent_builder.is_none(),
1191            "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
1192        );
1193        self.prototype_item = Some(prototype_item.into_widget());
1194        self
1195    }
1196
1197    list_arguments_setters!(ListView);
1198}
1199
1200impl Default for ListView {
1201    fn default() -> ListView {
1202        ListView::new()
1203    }
1204}
1205
1206impl ScrollView for ListView {
1207    crate::scroll_view_accessors!();
1208
1209    fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef> {
1210        BoxScrollViewBase::build_slivers(self, app, context)
1211    }
1212}
1213
1214impl BoxScrollView for ListView {
1215    crate::box_scroll_view_accessors!();
1216
1217    fn build_child_layout(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1218        if let Some(item_extent) = self.item_extent {
1219            return SliverFixedExtentList::new(self.children_delegate.clone(), item_extent)
1220                .into_widget();
1221        }
1222        if let Some(item_extent_builder) = self.item_extent_builder.clone() {
1223            return SliverVariedExtentList::new(
1224                self.children_delegate.clone(),
1225                item_extent_builder,
1226            )
1227            .into_widget();
1228        }
1229        if let Some(prototype_item) = self.prototype_item.clone() {
1230            return SliverPrototypeExtentList::new(self.children_delegate.clone(), prototype_item)
1231                .into_widget();
1232        }
1233        SliverList::new(self.children_delegate.clone()).into_widget()
1234    }
1235}
1236
1237impl StatelessWidget for ListView {
1238    fn key(&self) -> Option<&KeyRef> {
1239        self.scroll_view.key.as_ref()
1240    }
1241
1242    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1243        self.scroll_view.debug_fill_properties(app, properties);
1244        self.box_scroll_view.debug_fill_properties(properties);
1245        properties.add(DoubleProperty::new("itemExtent", self.item_extent).default_value(None));
1246    }
1247
1248    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1249        ScrollViewBase::build(self, app, context)
1250    }
1251}
1252
1253/// Dart's `ListView.builder(..)` arguments; the value converts to the [`ListView`].
1254pub struct ListViewBuilder {
1255    list_view: ListView,
1256    delegate: SliverChildBuilderDelegate,
1257}
1258
1259impl ListViewBuilder {
1260    fn new(item_builder: NullableIndexedWidgetBuilder) -> ListViewBuilder {
1261        ListViewBuilder {
1262            list_view: ListView::custom(SliverChildListDelegate::new(Vec::new()).into_delegate()),
1263            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
1264        }
1265    }
1266
1267    /// Dart `itemCount:`, which also fills in
1268    /// [`ScrollViewData::semantic_child_count`], as Dart's
1269    /// `semanticChildCount ?? itemCount` does.
1270    pub fn item_count(mut self, item_count: i32) -> ListViewBuilder {
1271        debug_assert!(item_count >= 0);
1272        self.delegate = self.delegate.child_count(item_count);
1273        if self.list_view.scroll_view.semantic_child_count.is_none() {
1274            self.list_view.scroll_view.semantic_child_count = Some(item_count);
1275        }
1276        self
1277    }
1278
1279    /// Dart `findChildIndexCallback:`.
1280    pub fn find_child_index_callback(
1281        mut self,
1282        find_child_index_callback: ChildIndexGetter,
1283    ) -> ListViewBuilder {
1284        self.delegate = self
1285            .delegate
1286            .find_child_index_callback(find_child_index_callback);
1287        self
1288    }
1289
1290    /// Dart `addAutomaticKeepAlives:`.
1291    pub fn add_automatic_keep_alives(mut self, value: bool) -> ListViewBuilder {
1292        self.delegate = self.delegate.add_automatic_keep_alives(value);
1293        self
1294    }
1295
1296    /// Dart `addRepaintBoundaries:`.
1297    pub fn add_repaint_boundaries(mut self, value: bool) -> ListViewBuilder {
1298        self.delegate = self.delegate.add_repaint_boundaries(value);
1299        self
1300    }
1301
1302    /// Dart `addSemanticIndexes:`.
1303    pub fn add_semantic_indexes(mut self, value: bool) -> ListViewBuilder {
1304        self.delegate = self.delegate.add_semantic_indexes(value);
1305        self
1306    }
1307
1308    /// The [`ListView`] this builder describes.
1309    pub fn build(self) -> ListView {
1310        ListView {
1311            children_delegate: self.delegate.into_delegate(),
1312            ..self.list_view
1313        }
1314    }
1315}
1316
1317/// Dart's `ListView.separated(..)` arguments; the value converts to the [`ListView`].
1318pub struct ListViewSeparated {
1319    list_view: ListView,
1320    delegate: SliverChildBuilderDelegate,
1321}
1322
1323impl ListViewSeparated {
1324    fn new(
1325        item_builder: NullableIndexedWidgetBuilder,
1326        separator_builder: NullableIndexedWidgetBuilder,
1327        item_count: i32,
1328    ) -> ListViewSeparated {
1329        debug_assert!(item_count >= 0);
1330        let delegate = SliverChildBuilderDelegate::from_builder(Rc::new(
1331            move |app: &mut App, context, index: i32| {
1332                let item_index = index.div_euclid(2);
1333                if index % 2 == 0 {
1334                    item_builder(app, context, item_index)
1335                } else {
1336                    separator_builder(app, context, item_index)
1337                }
1338            },
1339        ))
1340        .child_count(compute_actual_child_count(item_count))
1341        .semantic_index_callback(Rc::new(|_widget, index| {
1342            (index % 2 == 0).then_some(index / 2)
1343        }));
1344        ListViewSeparated {
1345            list_view: ListView {
1346                scroll_view: ScrollViewData {
1347                    semantic_child_count: Some(item_count),
1348                    ..ScrollViewData::new()
1349                },
1350                ..ListView::custom(SliverChildListDelegate::new(Vec::new()).into_delegate())
1351            },
1352            delegate,
1353        }
1354    }
1355
1356    /// Dart `findItemIndexCallback:`, which reports item indices (separators excluded).
1357    pub fn find_item_index_callback(
1358        mut self,
1359        find_item_index_callback: ChildIndexGetter,
1360    ) -> ListViewSeparated {
1361        self.delegate = self.delegate.find_child_index_callback(Rc::new(move |key| {
1362            find_item_index_callback(key).map(|item_index| item_index * 2)
1363        }));
1364        self
1365    }
1366
1367    /// Dart `addAutomaticKeepAlives:`.
1368    pub fn add_automatic_keep_alives(mut self, value: bool) -> ListViewSeparated {
1369        self.delegate = self.delegate.add_automatic_keep_alives(value);
1370        self
1371    }
1372
1373    /// Dart `addRepaintBoundaries:`.
1374    pub fn add_repaint_boundaries(mut self, value: bool) -> ListViewSeparated {
1375        self.delegate = self.delegate.add_repaint_boundaries(value);
1376        self
1377    }
1378
1379    /// Dart `addSemanticIndexes:`.
1380    pub fn add_semantic_indexes(mut self, value: bool) -> ListViewSeparated {
1381        self.delegate = self.delegate.add_semantic_indexes(value);
1382        self
1383    }
1384
1385    /// The [`ListView`] this value describes.
1386    pub fn build(self) -> ListView {
1387        ListView {
1388            children_delegate: self.delegate.into_delegate(),
1389            ..self.list_view
1390        }
1391    }
1392}
1393
1394impl IntoWidget<StatelessKind> for ListViewBuilder {
1395    #[cfg_attr(debug_assertions, track_caller)]
1396    fn into_widget(self) -> WidgetRef {
1397        self.build().into_widget()
1398    }
1399}
1400
1401impl IntoWidget<StatelessKind> for ListViewSeparated {
1402    #[cfg_attr(debug_assertions, track_caller)]
1403    fn into_widget(self) -> WidgetRef {
1404        self.build().into_widget()
1405    }
1406}
1407
1408/// Helper method to compute the actual child count for the separated constructor.
1409fn compute_actual_child_count(item_count: i32) -> i32 {
1410    (item_count * 2 - 1).max(0)
1411}
1412
1413impl Clone for ListView {
1414    fn clone(&self) -> ListView {
1415        ListView {
1416            scroll_view: self.scroll_view.clone(),
1417            box_scroll_view: self.box_scroll_view.clone(),
1418            item_extent: self.item_extent,
1419            item_extent_builder: self.item_extent_builder.clone(),
1420            prototype_item: self.prototype_item.clone(),
1421            children_delegate: self.children_delegate.clone(),
1422            list_arguments: self.list_arguments.clone(),
1423        }
1424    }
1425}
1426
1427impl Debug for ListView {
1428    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1429        f.debug_struct("ListView")
1430            .field("itemExtent", &self.item_extent)
1431            .field("childrenDelegate", &self.children_delegate)
1432            .finish_non_exhaustive()
1433    }
1434}
1435
1436/// A scrollable, 2D array of widgets.
1437///
1438/// The main axis direction of a grid is the direction in which it scrolls (the
1439/// [`ScrollViewData::scroll_direction`]).
1440///
1441/// The most commonly used grid layouts are [`GridView::count`], which creates a layout with a
1442/// fixed number of tiles in the cross axis, and [`GridView::extent`], which creates a layout
1443/// with tiles that have a maximum cross-axis extent. A custom [`SliverGridDelegate`] can
1444/// produce an arbitrary 2D arrangement of children, including arrangements that are unaligned
1445/// or overlapping.
1446///
1447/// To create a grid with a large (or infinite) number of children, use the
1448/// [`GridView::builder`] constructor with either a [`SliverGridDelegateWithFixedCrossAxisCount`]
1449/// or a [`SliverGridDelegateWithMaxCrossAxisExtent`] for the grid delegate.
1450///
1451/// To use a custom `SliverChildDelegate`, use [`GridView::custom`].
1452///
1453/// To create a linear array of children, use a [`ListView`].
1454///
1455/// To control the initial scroll offset of the scroll view, provide a
1456/// [`controller`](Self::controller) with its `ScrollController::initial_scroll_offset`
1457/// property set.
1458///
1459/// ## Transitioning to [`CustomScrollView`]
1460///
1461/// A [`GridView`] is basically a [`CustomScrollView`] with a single [`SliverGrid`] in its
1462/// [`CustomScrollView::slivers`] property.
1463///
1464/// By default, [`GridView`] will automatically pad the limits of the grid's scrollable to avoid
1465/// partial obstructions indicated by `MediaQuery`'s padding. To avoid this behavior, override
1466/// with a zero [`padding`](Self::padding) property.
1467pub struct GridView {
1468    scroll_view: ScrollViewData,
1469    box_scroll_view: BoxScrollViewData,
1470
1471    /// A delegate that controls the layout of the children within the [`GridView`].
1472    ///
1473    /// The [`GridView::new`], [`GridView::builder`], and [`GridView::custom`] constructors let
1474    /// you specify this delegate explicitly. The other constructors create a
1475    /// [`grid_delegate`](Self::grid_delegate) implicitly.
1476    pub grid_delegate: Rc<dyn SliverGridDelegate>,
1477
1478    /// A delegate that provides the children for the [`GridView`].
1479    ///
1480    /// The [`GridView::custom`] constructor lets you specify this delegate explicitly. The
1481    /// other constructors create a [`children_delegate`](Self::children_delegate) that wraps
1482    /// the given child list.
1483    pub children_delegate: SliverChildDelegateRef,
1484
1485    // As `ListView`'s: the arguments of the constructors that take children, for their setters.
1486    list_arguments: Option<ListArguments>,
1487}
1488
1489impl GridView {
1490    /// Creates a scrollable, 2D array of widgets with a custom [`SliverGridDelegate`], from an
1491    /// explicit list of children that the [`children`](Self::children) setter supplies.
1492    pub fn new(grid_delegate: Rc<dyn SliverGridDelegate>) -> GridView {
1493        let list_arguments = ListArguments::new();
1494        GridView {
1495            scroll_view: ScrollViewData {
1496                semantic_child_count: Some(0),
1497                ..ScrollViewData::new()
1498            },
1499            box_scroll_view: BoxScrollViewData::new(),
1500            grid_delegate,
1501            children_delegate: list_arguments.clone().into_delegate(),
1502            list_arguments: Some(list_arguments),
1503        }
1504    }
1505
1506    /// Creates a scrollable, 2D array of widgets that are created on demand.
1507    ///
1508    /// This constructor is appropriate for grid views with a large (or infinite) number of
1509    /// children because the builder is called only for those children that are actually
1510    /// visible.
1511    ///
1512    /// Providing a non-`None` [`item_count`](GridViewBuilder::item_count) improves the ability
1513    /// of the [`GridView`] to estimate the maximum scroll extent.
1514    ///
1515    /// The item builder will be called only with indices greater than or equal to zero and less
1516    /// than the item count.
1517    pub fn builder(
1518        grid_delegate: Rc<dyn SliverGridDelegate>,
1519        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1520    ) -> GridViewBuilder {
1521        GridViewBuilder::new(grid_delegate, Rc::new(item_builder))
1522    }
1523
1524    /// Creates a scrollable, 2D array of widgets with both a custom [`SliverGridDelegate`] and a
1525    /// custom `SliverChildDelegate`.
1526    ///
1527    /// To use an item builder callback to build children, either use a
1528    /// [`SliverChildBuilderDelegate`] or use the [`GridView::builder`] constructor.
1529    pub fn custom(
1530        grid_delegate: Rc<dyn SliverGridDelegate>,
1531        children_delegate: SliverChildDelegateRef,
1532    ) -> GridView {
1533        GridView {
1534            scroll_view: ScrollViewData::new(),
1535            box_scroll_view: BoxScrollViewData::new(),
1536            grid_delegate,
1537            children_delegate,
1538            list_arguments: None,
1539        }
1540    }
1541
1542    /// Creates a scrollable, 2D array of widgets with a fixed number of tiles in the cross axis.
1543    ///
1544    /// Uses a [`SliverGridDelegateWithFixedCrossAxisCount`] as the
1545    /// [`grid_delegate`](Self::grid_delegate).
1546    ///
1547    /// See also:
1548    ///
1549    ///  * [`SliverGrid::count`], the equivalent constructor for [`SliverGrid`].
1550    pub fn count(cross_axis_count: i32) -> GridViewCount {
1551        let grid_delegate = SliverGridDelegateWithFixedCrossAxisCount::new(cross_axis_count);
1552        GridViewCount {
1553            grid_view: GridView::new(Rc::new(grid_delegate.clone())),
1554            grid_delegate,
1555        }
1556    }
1557
1558    /// Creates a scrollable, 2D array of widgets with tiles that each have a maximum cross-axis
1559    /// extent.
1560    ///
1561    /// Uses a [`SliverGridDelegateWithMaxCrossAxisExtent`] as the
1562    /// [`grid_delegate`](Self::grid_delegate).
1563    ///
1564    /// See also:
1565    ///
1566    ///  * [`SliverGrid::extent`], the equivalent constructor for [`SliverGrid`].
1567    pub fn extent(max_cross_axis_extent: f64) -> GridViewExtent {
1568        let grid_delegate = SliverGridDelegateWithMaxCrossAxisExtent::new(max_cross_axis_extent);
1569        GridViewExtent {
1570            grid_view: GridView::new(Rc::new(grid_delegate.clone())),
1571            grid_delegate,
1572        }
1573    }
1574
1575    crate::scroll_view_setters!(GridView);
1576
1577    /// Dart `GridView(padding:)`.
1578    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> GridView {
1579        let padding = padding.into();
1580        self.box_scroll_view.padding = Some(padding);
1581        self
1582    }
1583
1584    list_arguments_setters!(GridView);
1585}
1586
1587impl ScrollView for GridView {
1588    crate::scroll_view_accessors!();
1589
1590    fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef> {
1591        BoxScrollViewBase::build_slivers(self, app, context)
1592    }
1593}
1594
1595impl BoxScrollView for GridView {
1596    crate::box_scroll_view_accessors!();
1597
1598    fn build_child_layout(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1599        SliverGrid::new(
1600            self.children_delegate.clone(),
1601            Rc::clone(&self.grid_delegate),
1602        )
1603        .into_widget()
1604    }
1605}
1606
1607impl StatelessWidget for GridView {
1608    fn key(&self) -> Option<&KeyRef> {
1609        self.scroll_view.key.as_ref()
1610    }
1611
1612    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1613        self.scroll_view.debug_fill_properties(app, properties);
1614        self.box_scroll_view.debug_fill_properties(properties);
1615    }
1616
1617    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1618        ScrollViewBase::build(self, app, context)
1619    }
1620}
1621
1622impl Clone for GridView {
1623    fn clone(&self) -> GridView {
1624        GridView {
1625            scroll_view: self.scroll_view.clone(),
1626            box_scroll_view: self.box_scroll_view.clone(),
1627            grid_delegate: Rc::clone(&self.grid_delegate),
1628            children_delegate: self.children_delegate.clone(),
1629            list_arguments: self.list_arguments.clone(),
1630        }
1631    }
1632}
1633
1634impl Debug for GridView {
1635    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1636        f.debug_struct("GridView")
1637            .field("gridDelegate", &self.grid_delegate)
1638            .field("childrenDelegate", &self.children_delegate)
1639            .finish_non_exhaustive()
1640    }
1641}
1642
1643/// Dart's `GridView.builder(..)` arguments; the value converts to the [`GridView`].
1644pub struct GridViewBuilder {
1645    grid_view: GridView,
1646    delegate: SliverChildBuilderDelegate,
1647}
1648
1649impl GridViewBuilder {
1650    fn new(
1651        grid_delegate: Rc<dyn SliverGridDelegate>,
1652        item_builder: NullableIndexedWidgetBuilder,
1653    ) -> GridViewBuilder {
1654        GridViewBuilder {
1655            grid_view: GridView::custom(
1656                grid_delegate,
1657                SliverChildListDelegate::new(Vec::new()).into_delegate(),
1658            ),
1659            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
1660        }
1661    }
1662
1663    /// Dart `itemCount:`, which also fills in [`ScrollViewData::semantic_child_count`], as
1664    /// Dart's `semanticChildCount ?? itemCount` does.
1665    pub fn item_count(mut self, item_count: i32) -> GridViewBuilder {
1666        self.delegate = self.delegate.child_count(item_count);
1667        if self.grid_view.scroll_view.semantic_child_count.is_none() {
1668            self.grid_view.scroll_view.semantic_child_count = Some(item_count);
1669        }
1670        self
1671    }
1672
1673    /// Dart `findChildIndexCallback:`.
1674    pub fn find_child_index_callback(
1675        mut self,
1676        find_child_index_callback: ChildIndexGetter,
1677    ) -> GridViewBuilder {
1678        self.delegate = self
1679            .delegate
1680            .find_child_index_callback(find_child_index_callback);
1681        self
1682    }
1683
1684    /// Dart `addAutomaticKeepAlives:`.
1685    pub fn add_automatic_keep_alives(mut self, value: bool) -> GridViewBuilder {
1686        self.delegate = self.delegate.add_automatic_keep_alives(value);
1687        self
1688    }
1689
1690    /// Dart `addRepaintBoundaries:`.
1691    pub fn add_repaint_boundaries(mut self, value: bool) -> GridViewBuilder {
1692        self.delegate = self.delegate.add_repaint_boundaries(value);
1693        self
1694    }
1695
1696    /// Dart `addSemanticIndexes:`.
1697    pub fn add_semantic_indexes(mut self, value: bool) -> GridViewBuilder {
1698        self.delegate = self.delegate.add_semantic_indexes(value);
1699        self
1700    }
1701
1702    /// Dart `padding:`, as [`GridView::padding`].
1703    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> GridViewBuilder {
1704        self.grid_view = self.grid_view.padding(padding);
1705        self
1706    }
1707
1708    /// The [`GridView`] this builder describes.
1709    pub fn build(self) -> GridView {
1710        GridView {
1711            children_delegate: self.delegate.into_delegate(),
1712            ..self.grid_view
1713        }
1714    }
1715}
1716
1717impl IntoWidget<StatelessKind> for GridViewBuilder {
1718    #[cfg_attr(debug_assertions, track_caller)]
1719    fn into_widget(self) -> WidgetRef {
1720        self.build().into_widget()
1721    }
1722}
1723
1724/// The fluent arguments `GridView::count` and `GridView::extent` share: their grid delegate's
1725/// spacing, aspect ratio and tile extent, and the children.
1726macro_rules! tiles_constructor_setters {
1727    ($name:ident) => {
1728        /// Dart `mainAxisSpacing:`.
1729        pub fn main_axis_spacing(mut self, value: f64) -> $name {
1730            self.grid_delegate = self.grid_delegate.main_axis_spacing(value);
1731            self
1732        }
1733
1734        /// Dart `crossAxisSpacing:`.
1735        pub fn cross_axis_spacing(mut self, value: f64) -> $name {
1736            self.grid_delegate = self.grid_delegate.cross_axis_spacing(value);
1737            self
1738        }
1739
1740        /// Dart `childAspectRatio:`.
1741        pub fn child_aspect_ratio(mut self, value: f64) -> $name {
1742            self.grid_delegate = self.grid_delegate.child_aspect_ratio(value);
1743            self
1744        }
1745
1746        /// Dart `mainAxisExtent:`.
1747        pub fn main_axis_extent(mut self, value: f64) -> $name {
1748            self.grid_delegate = self.grid_delegate.main_axis_extent(value);
1749            self
1750        }
1751
1752        /// See [`GridView::children`].
1753        pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
1754            self.grid_view = self.grid_view.children(children);
1755            self
1756        }
1757
1758        /// Dart `padding:`, as [`GridView::padding`].
1759        pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> $name {
1760            self.grid_view = self.grid_view.padding(padding);
1761            self
1762        }
1763
1764        /// See [`GridView::add_automatic_keep_alives`].
1765        pub fn add_automatic_keep_alives(mut self, value: bool) -> $name {
1766            self.grid_view = self.grid_view.add_automatic_keep_alives(value);
1767            self
1768        }
1769
1770        /// See [`GridView::add_repaint_boundaries`].
1771        pub fn add_repaint_boundaries(mut self, value: bool) -> $name {
1772            self.grid_view = self.grid_view.add_repaint_boundaries(value);
1773            self
1774        }
1775
1776        /// See [`GridView::add_semantic_indexes`].
1777        pub fn add_semantic_indexes(mut self, value: bool) -> $name {
1778            self.grid_view = self.grid_view.add_semantic_indexes(value);
1779            self
1780        }
1781
1782        /// The [`GridView`] this value describes.
1783        pub fn build(self) -> GridView {
1784            GridView {
1785                grid_delegate: Rc::new(self.grid_delegate),
1786                ..self.grid_view
1787            }
1788        }
1789    };
1790}
1791
1792/// Dart's `GridView.count(..)` arguments; the value converts to the [`GridView`].
1793pub struct GridViewCount {
1794    grid_view: GridView,
1795    grid_delegate: SliverGridDelegateWithFixedCrossAxisCount,
1796}
1797
1798impl GridViewCount {
1799    tiles_constructor_setters!(GridViewCount);
1800}
1801
1802impl IntoWidget<StatelessKind> for GridViewCount {
1803    #[cfg_attr(debug_assertions, track_caller)]
1804    fn into_widget(self) -> WidgetRef {
1805        self.build().into_widget()
1806    }
1807}
1808
1809/// Dart's `GridView.extent(..)` arguments; the value converts to the [`GridView`].
1810pub struct GridViewExtent {
1811    grid_view: GridView,
1812    grid_delegate: SliverGridDelegateWithMaxCrossAxisExtent,
1813}
1814
1815impl GridViewExtent {
1816    tiles_constructor_setters!(GridViewExtent);
1817}
1818
1819impl IntoWidget<StatelessKind> for GridViewExtent {
1820    #[cfg_attr(debug_assertions, track_caller)]
1821    fn into_widget(self) -> WidgetRef {
1822        self.build().into_widget()
1823    }
1824}
1825
1826#[cfg(test)]
1827mod tests {
1828    use std::cell::RefCell;
1829    use waft_foundation::{AppCell, ValueKey};
1830
1831    use waft_embedder::{Size, TextDirection};
1832    use waft_painting::{EdgeInsets, EdgeInsetsDirectional};
1833    use waft_rendering::{AnyRenderObject, RenderSliverPadding};
1834
1835    use super::*;
1836    use crate::test_harness::{Harness, VIEW_HEIGHT};
1837    use crate::testing::{WidgetTester, find, test_widgets};
1838    use crate::widgets::basic::{Directionality, SizedBox};
1839    use crate::widgets::media_query::MediaQueryData;
1840    use crate::widgets::reorderable_list::ReorderableDragStartListener;
1841    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
1842    use crate::widgets::text::Text;
1843
1844    const ITEM_EXTENT: f64 = 50.0;
1845    const ITEM_COUNT: usize = 40;
1846
1847    /// The tree every scroll view test mounts: a text direction and a media query, which a
1848    /// `Scrollable` reads for its gesture settings.
1849    fn wrap<K>(child: impl IntoWidget<K>) -> WidgetRef {
1850        wrap_with(
1851            MediaQueryData::new().size(Size::new(300.0, VIEW_HEIGHT)),
1852            child,
1853        )
1854    }
1855
1856    /// [`wrap`] for a tree in a [`WidgetTester`]'s view.
1857    fn wrap_in_tester_view<K>(child: impl IntoWidget<K>) -> WidgetRef {
1858        wrap_with(MediaQueryData::new().size(WidgetTester::SIZE), child)
1859    }
1860
1861    fn wrap_with<K>(data: MediaQueryData, child: impl IntoWidget<K>) -> WidgetRef {
1862        let query: WidgetRef = MediaQuery::new(data, child).into_widget();
1863        Directionality::new(TextDirection::Ltr, query).into_widget()
1864    }
1865
1866    fn boxes(count: usize) -> Vec<WidgetRef> {
1867        (0..count)
1868            .map(|_| SizedBox::new().height(ITEM_EXTENT).into_widget())
1869            .collect()
1870    }
1871
1872    /// Counts the render objects under `object` for which `matches` holds.
1873    fn count_render_objects(
1874        app: &App,
1875        object: AnyRenderObject,
1876        matches: &dyn Fn(&App, AnyRenderObject) -> bool,
1877    ) -> usize {
1878        let mut total = usize::from(matches(app, object));
1879        object.visit_children(app, &mut |child| {
1880            total += count_render_objects(app, child, matches);
1881        });
1882        total
1883    }
1884
1885    /// Whether `object` is the `IndexedSemantics` or the `RepaintBoundary` a delegate wraps each
1886    /// child in, which take their child's size.
1887    fn is_child_wrapper(app: &App, object: AnyRenderObject) -> bool {
1888        object
1889            .downcast::<waft_rendering::RenderIndexedSemantics>(app)
1890            .is_some()
1891            || object
1892                .downcast::<waft_rendering::RenderRepaintBoundary>(app)
1893                .is_some()
1894    }
1895
1896    fn item_count(app: &App, harness: &Harness) -> usize {
1897        count_render_objects(app, harness.render_root(app).as_object(), &|app, object| {
1898            !is_child_wrapper(app, object)
1899                && object
1900                    .as_box()
1901                    .is_some_and(|render_box| render_box.size(app).height() == ITEM_EXTENT)
1902        })
1903    }
1904
1905    #[test]
1906    fn a_list_view_lays_out_only_the_visible_children_and_scrolls_through_its_controller() {
1907        test_widgets(|tester| {
1908            let controller = tester.update(ScrollController::default);
1909            let list = ListView::new()
1910                .controller(controller.erase())
1911                .children(boxes(ITEM_COUNT));
1912            tester.pump_widget(wrap_in_tester_view(list));
1913
1914            let visible = (WidgetTester::SIZE.height() / ITEM_EXTENT) as usize;
1915            let laid_out = tester.update(item_count_under_view);
1916            assert!(
1917                laid_out >= visible && laid_out < ITEM_COUNT,
1918                "only the visible children (plus the cache) are laid out, not all of them: {laid_out}"
1919            );
1920
1921            tester.update(|app| controller.jump_to(app, 500.0));
1922            tester.pump();
1923            assert_eq!(controller.offset(&tester.cell.borrow()), 500.0);
1924            let scrolled = tester.update(item_count_under_view);
1925            assert!(
1926                scrolled >= visible && scrolled < ITEM_COUNT,
1927                "still only the visible children (plus the cache) after scrolling: {scrolled}"
1928            );
1929        });
1930    }
1931
1932    /// A scrollable built as a list settles at its end and dropped in the same frame has its
1933    /// metrics' notification still scheduled: the microtask finds it disposed and sends nothing,
1934    /// as Flutter's does, rather than reaching a destroyed state.
1935    #[test]
1936    fn a_nested_scrollable_dropped_in_the_frame_it_was_laid_out_sends_no_metrics_notification() {
1937        test_widgets(|tester| {
1938            let controller = tester.update(ScrollController::default);
1939            let mut children = boxes(ITEM_COUNT);
1940            for _ in 0..4 {
1941                children.push(
1942                    crate::widgets::single_child_scroll_view::SingleChildScrollView::new()
1943                        .scroll_direction(waft_painting::Axis::Horizontal)
1944                        .child(SizedBox::new().width(1000.0).height(ITEM_EXTENT))
1945                        .into_widget(),
1946                );
1947            }
1948            let list = ListView::new()
1949                .controller(controller.erase())
1950                .children(children);
1951            tester.pump_widget(wrap_in_tester_view(list));
1952            tester.update(|app| controller.jump_to(app, 100_000.0));
1953            tester.pump();
1954            tester.pump();
1955        });
1956    }
1957
1958    fn item_count_under_view(app: &mut App) -> usize {
1959        let root = crate::binding::WidgetsBinding::instance(app)
1960            .root_element(app)
1961            .expect("a mounted root element")
1962            .find_render_object(app)
1963            .expect("a mounted view has a render object");
1964        count_render_objects(app, root, &|app, object| {
1965            !is_child_wrapper(app, object)
1966                && object.as_box().is_some_and(|render_box| {
1967                    render_box.has_size(app) && render_box.size(app).height() == ITEM_EXTENT
1968                })
1969        })
1970    }
1971
1972    #[test]
1973    fn a_list_view_builder_creates_its_children_lazily() {
1974        let built: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
1975        let recorded = built.clone();
1976        let list = ListView::builder(move |_app, _context, index| {
1977            recorded.borrow_mut().push(index);
1978            Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
1979        })
1980        .item_count(1000)
1981        .build();
1982
1983        let cell = AppCell::new();
1984        let mut app = cell.borrow_mut();
1985        let harness = Harness::mount(&mut app, wrap(list));
1986        harness.pump(&mut app);
1987
1988        let built = built.borrow();
1989        assert!(!built.is_empty(), "the visible children are built");
1990        assert!(
1991            built.len() < 1000,
1992            "only the visible children are built, not all 1000: {}",
1993            built.len()
1994        );
1995        assert!(
1996            built.iter().all(|index| *index < built.len() as i32),
1997            "the builder is called for the leading indices only: {built:?}"
1998        );
1999    }
2000
2001    #[test]
2002    #[should_panic(
2003        expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2004    )]
2005    fn a_list_view_asserts_on_both_non_null_item_extent_and_prototype_item() {
2006        ListView::new()
2007            .item_extent(100.0)
2008            .prototype_item(SizedBox::new());
2009    }
2010
2011    #[test]
2012    #[should_panic(
2013        expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2014    )]
2015    fn a_list_view_builder_asserts_on_both_non_null_item_extent_and_prototype_item() {
2016        ListView::builder(|_app, _context, _index| Some(SizedBox::new().into_widget()))
2017            .build()
2018            .item_extent(100.0)
2019            .prototype_item(SizedBox::new());
2020    }
2021
2022    #[test]
2023    #[should_panic(
2024        expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2025    )]
2026    fn a_list_view_custom_asserts_on_both_non_null_item_extent_and_prototype_item() {
2027        let delegate = SliverChildBuilderDelegate::from_builder(Rc::new(
2028            |_app: &mut App, _context, _index: i32| Some(SizedBox::new().into_widget()),
2029        ))
2030        .into_delegate();
2031        ListView::custom(delegate)
2032            .item_extent(100.0)
2033            .prototype_item(SizedBox::new());
2034    }
2035
2036    /// `prototypeItem` and `itemExtentBuilder` exclude each other too, as Dart's assert says.
2037    #[test]
2038    #[should_panic(
2039        expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
2040    )]
2041    fn a_list_view_asserts_on_both_non_null_prototype_item_and_item_extent_builder() {
2042        ListView::new()
2043            .prototype_item(SizedBox::new())
2044            .item_extent_builder(Rc::new(|_index, _dimensions| Some(30.0)));
2045    }
2046
2047    #[test]
2048    fn if_prototype_item_is_non_null_children_have_same_extent_in_the_scroll_direction() {
2049        test_widgets(|tester| {
2050            let numbers = [0, 1, 2];
2051            let list = ListView::builder(move |_app, _context, index| {
2052                let number = numbers[index as usize];
2053                Some(
2054                    SizedBox::new()
2055                        .key(ValueKey::new(number).into())
2056                        // children with different heights
2057                        .height(20.0 + f64::from(number) * 10.0)
2058                        .child(ReorderableDragStartListener::new(
2059                            Text::new(number.to_string()),
2060                            index,
2061                        ))
2062                        .into_widget(),
2063                )
2064            })
2065            .item_count(numbers.len() as i32)
2066            .build()
2067            .prototype_item(SizedBox::new().height(30.0).child(Text::new("3")));
2068            tester.pump_widget(wrap_in_tester_view(list));
2069
2070            // Dart's finders are `hitTestable()`, which `waft_widgets::testing` does not have.
2071            assert_eq!(tester.get_size(find::text("0")).height(), 30.0);
2072            assert_eq!(tester.get_size(find::text("1")).height(), 30.0);
2073            assert_eq!(tester.get_size(find::text("2")).height(), 30.0);
2074        });
2075    }
2076
2077    #[test]
2078    fn a_list_view_separated_interleaves_items_and_separators() {
2079        let calls: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2080        let items = calls.clone();
2081        let separators = calls.clone();
2082        let list = ListView::separated(
2083            move |_app, _context, index| {
2084                items.borrow_mut().push(format!("item {index}"));
2085                Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
2086            },
2087            move |_app, _context, index| {
2088                separators.borrow_mut().push(format!("separator {index}"));
2089                Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
2090            },
2091            10,
2092        )
2093        .build();
2094        assert_eq!(list.scroll_view.semantic_child_count, Some(10));
2095
2096        let cell = AppCell::new();
2097        let mut app = cell.borrow_mut();
2098        let harness = Harness::mount(&mut app, wrap(list));
2099        harness.pump(&mut app);
2100
2101        let calls = calls.borrow();
2102        assert_eq!(calls[0], "item 0");
2103        assert_eq!(calls[1], "separator 0");
2104        assert_eq!(calls[2], "item 1");
2105        assert_eq!(calls[3], "separator 1");
2106    }
2107
2108    #[test]
2109    fn a_custom_scroll_view_lays_out_a_box_adapter_above_a_sliver_list() {
2110        use crate::widgets::basic::SliverToBoxAdapter;
2111
2112        let cell = AppCell::new();
2113        let mut app = cell.borrow_mut();
2114        let view = CustomScrollView::new().slivers([
2115            SliverToBoxAdapter::new()
2116                .child(SizedBox::new().height(120.0))
2117                .into_widget(),
2118            SliverList::list(boxes(10)).into_widget(),
2119        ]);
2120        let harness = Harness::mount(&mut app, wrap(view));
2121        harness.pump(&mut app);
2122
2123        let header = count_render_objects(
2124            &app,
2125            harness.render_root(&app).as_object(),
2126            &|app, object| {
2127                object
2128                    .as_box()
2129                    .is_some_and(|render_box| render_box.size(app).height() == 120.0)
2130            },
2131        );
2132        assert_eq!(header, 1, "the box adapter's child is laid out");
2133        assert!(
2134            item_count(&app, &harness) > 0,
2135            "the sliver list's children are laid out below it"
2136        );
2137    }
2138
2139    /// `GridView.count` sizes its tiles to fill each row and lays out only the rows in view
2140    /// and in the cache.
2141    #[test]
2142    fn a_grid_view_count_lays_out_the_rows_in_view() {
2143        let cell = AppCell::new();
2144        let mut app = cell.borrow_mut();
2145        let grid = GridView::count(3)
2146            .main_axis_spacing(10.0)
2147            .add_repaint_boundaries(false)
2148            .children(boxes(30))
2149            .build();
2150        assert_eq!(grid.scroll_view.semantic_child_count, Some(30));
2151        let harness = Harness::mount(&mut app, wrap(grid));
2152        harness.pump(&mut app);
2153
2154        // Tiles are 100 square in the 300 wide view, rows 110 apart: the 200 high view and its
2155        // 250 of cache reach into the fifth row.
2156        let tiles = count_render_objects(
2157            &app,
2158            harness.render_root(&app).as_object(),
2159            &|app, object| {
2160                !is_child_wrapper(app, object)
2161                    && object
2162                        .as_box()
2163                        .is_some_and(|render_box| render_box.size(app) == Size::new(100.0, 100.0))
2164            },
2165        );
2166        assert_eq!(tiles, 15);
2167    }
2168
2169    #[test]
2170    fn a_grid_view_builder_creates_its_tiles_lazily() {
2171        let built: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
2172        let recorded = built.clone();
2173        let tiles = SliverGridDelegateWithMaxCrossAxisExtent::new(150.0);
2174        let grid = GridView::builder(Rc::new(tiles), move |_app, _context, index| {
2175            recorded.borrow_mut().push(index);
2176            Some(SizedBox::new().into_widget())
2177        })
2178        .item_count(1000)
2179        .build();
2180
2181        let cell = AppCell::new();
2182        let mut app = cell.borrow_mut();
2183        let harness = Harness::mount(&mut app, wrap(grid));
2184        harness.pump(&mut app);
2185
2186        // Two columns of 150 square tiles: rows up to 450 are built, view and cache.
2187        let mut built = built.borrow().clone();
2188        built.sort();
2189        assert_eq!(built, (0..6).collect::<Vec<i32>>());
2190    }
2191
2192    /// `GridView.extent` and `GridView.builder` take `padding`, as Dart's constructors do, and
2193    /// the sliver gets it.
2194    #[test]
2195    fn a_grid_view_constructor_takes_padding() {
2196        let cell = AppCell::new();
2197        let mut app = cell.borrow_mut();
2198        let extent = GridView::extent(150.0)
2199            .padding(EdgeInsets::all(8.0))
2200            .children(boxes(4));
2201        let harness = Harness::mount(&mut app, wrap(extent));
2202        harness.pump(&mut app);
2203        let sliver_padding = find_sliver_padding(&app, harness.render_root(&app).as_object())
2204            .expect("the grid wraps its sliver in a SliverPadding");
2205        assert_eq!(
2206            sliver_padding.padding(&app).resolve(None),
2207            EdgeInsets::all(8.0)
2208        );
2209
2210        let delegate = Rc::new(SliverGridDelegateWithFixedCrossAxisCount::new(2));
2211        let built = GridView::builder(delegate, |_app, _context, _index| {
2212            Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
2213        })
2214        .item_count(4)
2215        .padding(EdgeInsetsDirectional::only(4.0, 0.0, 2.0, 0.0))
2216        .build();
2217        harness.set_child(&mut app, wrap(built));
2218        harness.pump(&mut app);
2219        let sliver_padding = find_sliver_padding(&app, harness.render_root(&app).as_object())
2220            .expect("the built grid wraps its sliver in a SliverPadding");
2221        assert_eq!(
2222            sliver_padding
2223                .padding(&app)
2224                .resolve(Some(TextDirection::Ltr)),
2225            EdgeInsets::from_ltrb(4.0, 0.0, 2.0, 0.0)
2226        );
2227    }
2228
2229    #[test]
2230    fn a_box_scroll_view_consumes_the_media_query_padding_along_the_scroll_axis() {
2231        let cell = AppCell::new();
2232        let mut app = cell.borrow_mut();
2233        let padding = EdgeInsets::from_ltrb(8.0, 16.0, 24.0, 32.0);
2234        let list = ListView::new().children(boxes(10));
2235        let harness = Harness::mount(
2236            &mut app,
2237            wrap_with(
2238                MediaQueryData::new()
2239                    .size(Size::new(300.0, VIEW_HEIGHT))
2240                    .padding(padding),
2241                list,
2242            ),
2243        );
2244        harness.pump(&mut app);
2245
2246        let sliver_padding = find_sliver_padding(&app, harness.render_root(&app).as_object())
2247            .expect("the list wraps its sliver in a SliverPadding");
2248        assert_eq!(
2249            sliver_padding.padding(&app).resolve(None),
2250            EdgeInsets::from_ltrb(0.0, 16.0, 0.0, 32.0),
2251            "the main axis padding is consumed by the SliverPadding"
2252        );
2253    }
2254
2255    fn find_sliver_padding(
2256        app: &App,
2257        object: AnyRenderObject,
2258    ) -> Option<waft_rendering::RenderHandle<RenderSliverPadding>> {
2259        if let Some(padding) = object.downcast::<RenderSliverPadding>(app) {
2260            return Some(padding);
2261        }
2262        let mut found = None;
2263        object.visit_children(app, &mut |child| {
2264            if found.is_none() {
2265                found = find_sliver_padding(app, child);
2266            }
2267        });
2268        found
2269    }
2270}