Skip to main content

waft_widgets/widgets/
sliver.rs

1//! Flutter counterpart: `widgets/sliver.dart`.
2//!
3//! The lazily built slivers and the element that manages their children. `SliverOpacity`,
4//! `SliverIgnorePointer`, `SliverOffstage`, `SliverConstrainedCrossAxis`, `SliverCrossAxisGroup`,
5//! `SliverMainAxisGroup` and `SliverEnsureSemantics` wait for their render objects; see
6//! `PORTING.md`. `SliverToBoxAdapter` and `SliverPadding` are Flutter's
7//! `basic.dart` and live in `widgets/basic.rs`.
8
9use std::any::{Any, TypeId};
10use std::collections::{BTreeMap, HashMap};
11use std::fmt::{self, Debug};
12use std::panic::Location;
13use std::rc::Rc;
14
15use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle};
16use waft_rendering::{
17    AnyRenderBox, AnyRenderObject, ItemExtentBuilder, KeepAliveParentData, RenderHandle,
18    RenderSliver, RenderSliverBoxChildManager, RenderSliverFixedExtentList, RenderSliverGrid,
19    RenderSliverList, RenderSliverMultiBoxAdaptor, RenderSliverVariedExtentList,
20    RenderSliverWithKeepAliveMixin, SliverConstraints, SliverGridDelegate,
21    SliverGridDelegateWithFixedCrossAxisCount, SliverGridDelegateWithMaxCrossAxisExtent,
22    SliverMultiBoxAdaptorParentData,
23};
24
25use crate::framework::{
26    AnyElement, BuildContext, CreationLocation, Element, ElementData, IntoWidget, KeyRef,
27    ParentDataWidget, RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget,
28    RenderObjectWidget, Slot, Widget, WidgetKind, WidgetRef, downcast_widget, short_type_name,
29};
30use crate::widgets::scroll_delegate::{
31    ChildIndexGetter, NullableIndexedWidgetBuilder, SemanticIndexCallback,
32    SliverChildBuilderDelegate, SliverChildDelegateRef, SliverChildListDelegate, same_delegate,
33};
34
35// ---------------------------------------------------------------------------------------------
36// The widget kinds
37
38/// A base class for slivers that have [`KeepAlive`] children.
39///
40/// See also:
41///
42/// * [`KeepAlive`], which marks whether its child widget should be kept alive.
43/// * `SliverChildBuilderDelegate` and `SliverChildListDelegate`, slivers which make use of the
44///   keep alive functionality through the `addAutomaticKeepAlives` property.
45/// * [`SliverList`], a sliver widget that is commonly wrapped with [`KeepAlive`] widgets to
46///   preserve its sliver child subtrees.
47pub trait SliverWithKeepAliveWidget: RenderObjectWidget
48where
49    Self::RenderObject: RenderSliverWithKeepAliveMixin,
50{
51}
52
53/// A base class for slivers that have multiple box children.
54///
55/// Helps implementors build their children lazily using a `SliverChildDelegate`.
56///
57/// The widgets returned by the [`delegate`](Self::delegate) are cached and the delegate is only
58/// consulted again if it changes and the new delegate's `SliverChildDelegate::should_rebuild`
59/// method returns true.
60pub trait SliverMultiBoxAdaptorWidget: SliverWithKeepAliveWidget
61where
62    Self::RenderObject: RenderSliverMultiBoxAdaptor,
63{
64    /// The delegate that provides the children for this widget.
65    ///
66    /// The children are constructed lazily using this delegate to avoid creating more children
67    /// than are visible through the `Viewport`.
68    ///
69    /// ## Using more than one delegate in a `Viewport`
70    ///
71    /// If multiple delegates are used in a single scroll view, the first child of each delegate
72    /// will always be laid out, even if it extends beyond the currently viewable area. This is
73    /// because at least one child is required in order to estimate the max scroll offset for the
74    /// whole scroll view, as it uses the currently built children to estimate the remaining
75    /// children's extent.
76    fn delegate(&self) -> &SliverChildDelegateRef;
77
78    /// Dart's `SliverMultiBoxAdaptorWidget.debugFillProperties`, which a subclass's own body
79    /// calls where Dart writes `super`.
80    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
81        properties.add(DiagnosticsProperty::<String>::new(
82            "delegate",
83            Some(format!("{:?}", self.delegate())),
84        ));
85    }
86
87    /// Creates the element that lazily builds this widget's children.
88    ///
89    /// Dart's `createElement`; an implementor that needs the moved children replaced passes
90    /// `true` (see [`SliverMultiBoxAdaptorElement::new`]).
91    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
92    where
93        Self: Sized,
94    {
95        SliverMultiBoxAdaptorElement::<Self>::new(app, this, false).as_element()
96    }
97
98    /// Returns an estimate of the max scroll extent for all the children.
99    ///
100    /// Implementors should override this function if they have additional information about
101    /// their max scroll extent.
102    ///
103    /// This is used by [`SliverMultiBoxAdaptorElement`] to implement part of the
104    /// `RenderSliverBoxChildManager` API.
105    ///
106    /// The default implementation defers to the [`delegate`](Self::delegate) via its
107    /// `SliverChildDelegate::estimate_max_scroll_offset` method.
108    fn estimate_max_scroll_offset(
109        &self,
110        constraints: Option<SliverConstraints>,
111        first_index: i32,
112        last_index: i32,
113        leading_scroll_offset: f64,
114        trailing_scroll_offset: f64,
115    ) -> Option<f64> {
116        let _ = constraints;
117        debug_assert!(last_index >= first_index);
118        self.delegate().estimate_max_scroll_offset(
119            first_index,
120            last_index,
121            leading_scroll_offset,
122            trailing_scroll_offset,
123        )
124    }
125}
126
127/// The kind tag of [`IntoWidget`] for a [`SliverMultiBoxAdaptorWidget`].
128pub struct SliverMultiBoxAdaptorKind;
129
130/// The erased form of a [`SliverMultiBoxAdaptorWidget`].
131pub struct SliverMultiBoxAdaptor<W: SliverMultiBoxAdaptorWidget>(
132    pub W,
133    pub(crate) CreationLocation,
134)
135where
136    W::RenderObject: RenderSliverMultiBoxAdaptor;
137
138impl<W: SliverMultiBoxAdaptorWidget> IntoWidget<SliverMultiBoxAdaptorKind> for W
139where
140    W::RenderObject: RenderSliverMultiBoxAdaptor,
141{
142    #[cfg_attr(debug_assertions, track_caller)]
143    fn into_widget(self) -> WidgetRef {
144        if cfg!(debug_assertions) {
145            RenderObjectWidget::debug_check_constructor(&self);
146        }
147        Rc::new(SliverMultiBoxAdaptor(self, CreationLocation::of_caller()))
148    }
149}
150
151impl<W: SliverMultiBoxAdaptorWidget> Widget for SliverMultiBoxAdaptor<W>
152where
153    W::RenderObject: RenderSliverMultiBoxAdaptor,
154{
155    fn key(&self) -> Option<&KeyRef> {
156        RenderObjectWidget::key(&self.0)
157    }
158
159    fn creation_location(&self) -> Option<&'static Location<'static>> {
160        self.1.location()
161    }
162
163    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
164        SliverMultiBoxAdaptorWidget::create_element(&self.0, app, this)
165    }
166
167    fn as_any(&self) -> &dyn Any {
168        &self.0
169    }
170
171    fn widget_type(&self) -> TypeId {
172        TypeId::of::<W>()
173    }
174
175    fn type_name(&self) -> &'static str {
176        short_type_name::<W>()
177    }
178
179    fn kind(&self) -> WidgetKind {
180        WidgetKind::Other
181    }
182
183    fn to_string_short(&self) -> String {
184        RenderObjectWidget::to_string_short(&self.0)
185    }
186
187    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
188        RenderObjectWidget::debug_fill_properties(&self.0, app, properties);
189    }
190}
191
192impl<W: SliverMultiBoxAdaptorWidget> Debug for SliverMultiBoxAdaptor<W>
193where
194    W::RenderObject: RenderSliverMultiBoxAdaptor,
195{
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        self.0.fmt(f)
198    }
199}
200
201// ---------------------------------------------------------------------------------------------
202// SliverList
203
204/// A sliver that places multiple box children in a linear array along the main axis.
205///
206/// _To learn more about slivers, see `CustomScrollView::slivers`._
207///
208/// Each child is forced to have the `SliverConstraints::cross_axis_extent` in the cross axis but
209/// determines its own main axis extent.
210///
211/// [`SliverList`] determines its scroll offset by "dead reckoning" because children outside the
212/// visible part of the sliver are not materialized, which means [`SliverList`] cannot learn their
213/// main axis extent. Instead, newly materialized children are placed adjacent to existing
214/// children.
215///
216/// If the children have a fixed extent in the main axis, consider using
217/// [`SliverFixedExtentList`] rather than [`SliverList`] because [`SliverFixedExtentList`] does
218/// not need to perform layout on its children to obtain their extent in the main axis and is
219/// therefore more efficient.
220///
221/// See also:
222///
223///  * `CustomScrollView`, which accepts slivers like [`SliverList`] to create custom scroll
224///    effects.
225///  * [`SliverFixedExtentList`], which is more efficient for children with the same extent in
226///    the main axis.
227///  * `SliverGrid`, which places multiple children in a two dimensional grid.
228#[derive(Debug)]
229pub struct SliverList {
230    pub key: Option<KeyRef>,
231    /// The delegate that provides the children for this widget.
232    pub delegate: SliverChildDelegateRef,
233}
234
235impl SliverList {
236    /// Creates a sliver that places box children in a linear array.
237    pub fn new(delegate: SliverChildDelegateRef) -> SliverList {
238        SliverList {
239            key: None,
240            delegate,
241        }
242    }
243
244    /// A sliver that places multiple box children in a linear array along the main axis.
245    ///
246    /// This constructor is appropriate for sliver lists with a large (or infinite) number of
247    /// children because the builder is called only for those children that are actually visible.
248    ///
249    /// Providing a non-`None` [`item_count`](SliverListBuilder::item_count) improves the ability
250    /// of the [`SliverList`] to estimate the maximum scroll extent.
251    ///
252    /// The item builder will be called only with indices greater than or equal to zero and less
253    /// than the item count.
254    pub fn builder(
255        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
256    ) -> SliverListBuilder {
257        SliverListBuilder::new(Rc::new(item_builder))
258    }
259
260    /// A sliver that places multiple box children, separated by box widgets, in a linear array
261    /// along the main axis.
262    ///
263    /// This constructor is appropriate for sliver lists with a large (or infinite) number of
264    /// children because the builder is called only for those children that are actually visible.
265    ///
266    /// The `separator_builder` is similar to `item_builder`, except it is the widget that gets
267    /// placed between `item_builder(context, index)` and `item_builder(context, index + 1)`.
268    pub fn separated(
269        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
270        separator_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
271    ) -> SliverListSeparated {
272        SliverListSeparated::new(Rc::new(item_builder), Rc::new(separator_builder))
273    }
274
275    /// A sliver that places multiple box children in a linear array along the main axis, built
276    /// from an explicit list of widgets.
277    pub fn list(children: Vec<WidgetRef>) -> SliverListList {
278        SliverListList::new(children)
279    }
280
281    /// Dart `SliverList(key:)`.
282    pub fn key(mut self, key: KeyRef) -> SliverList {
283        self.key = Some(key);
284        self
285    }
286}
287
288impl RenderObjectWidget for SliverList {
289    type RenderObject = RenderSliverList;
290
291    fn key(&self) -> Option<&KeyRef> {
292        self.key.as_ref()
293    }
294
295    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
296        SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
297    }
298
299    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
300        RenderSliverList::new(app, child_manager_of::<SliverList>(app, context)).as_object()
301    }
302}
303
304impl SliverWithKeepAliveWidget for SliverList {}
305
306impl SliverMultiBoxAdaptorWidget for SliverList {
307    fn delegate(&self) -> &SliverChildDelegateRef {
308        &self.delegate
309    }
310
311    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
312        SliverMultiBoxAdaptorElement::<SliverList>::new(app, this, true).as_element()
313    }
314}
315
316/// Dart's `SliverList.builder(..)` arguments; `into_widget` builds the [`SliverList`].
317pub struct SliverListBuilder {
318    key: Option<KeyRef>,
319    delegate: SliverChildBuilderDelegate,
320}
321
322/// The fluent `SliverChildBuilderDelegate` arguments the `builder` constructors share.
323macro_rules! builder_constructor_setters {
324    ($name:ident) => {
325        /// Dart `key:`.
326        pub fn key(mut self, key: KeyRef) -> $name {
327            self.key = Some(key);
328            self
329        }
330
331        /// Dart `itemCount:`.
332        pub fn item_count(mut self, item_count: i32) -> $name {
333            self.delegate = self.delegate.child_count(item_count);
334            self
335        }
336
337        /// Dart `addAutomaticKeepAlives:`.
338        pub fn add_automatic_keep_alives(mut self, value: bool) -> $name {
339            self.delegate = self.delegate.add_automatic_keep_alives(value);
340            self
341        }
342
343        /// Dart `addRepaintBoundaries:`.
344        pub fn add_repaint_boundaries(mut self, value: bool) -> $name {
345            self.delegate = self.delegate.add_repaint_boundaries(value);
346            self
347        }
348
349        /// Dart `addSemanticIndexes:`.
350        pub fn add_semantic_indexes(mut self, value: bool) -> $name {
351            self.delegate = self.delegate.add_semantic_indexes(value);
352            self
353        }
354    };
355}
356
357/// The fluent `SliverChildListDelegate` arguments the `list` constructors share.
358macro_rules! list_constructor_setters {
359    ($name:ident) => {
360        /// Dart `key:`.
361        pub fn key(mut self, key: KeyRef) -> $name {
362            self.key = Some(key);
363            self
364        }
365
366        /// Dart `addAutomaticKeepAlives:`.
367        pub fn add_automatic_keep_alives(mut self, value: bool) -> $name {
368            self.delegate = self.delegate.add_automatic_keep_alives(value);
369            self
370        }
371
372        /// Dart `addRepaintBoundaries:`.
373        pub fn add_repaint_boundaries(mut self, value: bool) -> $name {
374            self.delegate = self.delegate.add_repaint_boundaries(value);
375            self
376        }
377
378        /// Dart `addSemanticIndexes:`.
379        pub fn add_semantic_indexes(mut self, value: bool) -> $name {
380            self.delegate = self.delegate.add_semantic_indexes(value);
381            self
382        }
383    };
384}
385
386pub(crate) use builder_constructor_setters;
387pub(crate) use list_constructor_setters;
388
389impl SliverListBuilder {
390    fn new(item_builder: NullableIndexedWidgetBuilder) -> SliverListBuilder {
391        SliverListBuilder {
392            key: None,
393            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
394        }
395    }
396
397    builder_constructor_setters!(SliverListBuilder);
398
399    /// Dart `semanticIndexOffset:`.
400    pub fn semantic_index_offset(mut self, value: i32) -> SliverListBuilder {
401        self.delegate = self.delegate.semantic_index_offset(value);
402        self
403    }
404
405    /// Dart `findChildIndexCallback:`.
406    pub fn find_child_index_callback(mut self, value: ChildIndexGetter) -> SliverListBuilder {
407        self.delegate = self.delegate.find_child_index_callback(value);
408        self
409    }
410
411    /// The `SliverList` this constructor describes.
412    pub fn build(self) -> SliverList {
413        let mut list = SliverList::new(self.delegate.into_delegate());
414        if let Some(key) = self.key {
415            list = list.key(key);
416        }
417        list
418    }
419}
420
421impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverListBuilder {
422    #[cfg_attr(debug_assertions, track_caller)]
423    fn into_widget(self) -> WidgetRef {
424        self.build().into_widget()
425    }
426}
427
428/// Dart's `SliverList.separated(..)` arguments; `into_widget` builds the [`SliverList`].
429pub struct SliverListSeparated {
430    key: Option<KeyRef>,
431    item_builder: NullableIndexedWidgetBuilder,
432    separator_builder: NullableIndexedWidgetBuilder,
433    item_count: Option<i32>,
434    find_item_index_callback: Option<ChildIndexGetter>,
435    find_child_index_callback: Option<ChildIndexGetter>,
436    add_automatic_keep_alives: bool,
437    add_repaint_boundaries: bool,
438    add_semantic_indexes: bool,
439}
440
441impl SliverListSeparated {
442    fn new(
443        item_builder: NullableIndexedWidgetBuilder,
444        separator_builder: NullableIndexedWidgetBuilder,
445    ) -> SliverListSeparated {
446        SliverListSeparated {
447            key: None,
448            item_builder,
449            separator_builder,
450            item_count: None,
451            find_item_index_callback: None,
452            find_child_index_callback: None,
453            add_automatic_keep_alives: true,
454            add_repaint_boundaries: true,
455            add_semantic_indexes: true,
456        }
457    }
458
459    /// Dart `key:`.
460    pub fn key(mut self, key: KeyRef) -> SliverListSeparated {
461        self.key = Some(key);
462        self
463    }
464
465    /// Dart `itemCount:`.
466    pub fn item_count(mut self, item_count: i32) -> SliverListSeparated {
467        self.item_count = Some(item_count);
468        self
469    }
470
471    /// Dart `findItemIndexCallback:`.
472    pub fn find_item_index_callback(mut self, value: ChildIndexGetter) -> SliverListSeparated {
473        debug_assert!(
474            self.find_child_index_callback.is_none(),
475            "Cannot provide both findItemIndexCallback and findChildIndexCallback. Use \
476             findItemIndexCallback as findChildIndexCallback is deprecated."
477        );
478        self.find_item_index_callback = Some(value);
479        self
480    }
481
482    /// Dart `findChildIndexCallback:`.
483    #[deprecated(
484        note = "Use find_item_index_callback instead. find_child_index_callback returns child \
485                indices (which include separators), while find_item_index_callback returns item \
486                indices (which do not)."
487    )]
488    pub fn find_child_index_callback(mut self, value: ChildIndexGetter) -> SliverListSeparated {
489        debug_assert!(
490            self.find_item_index_callback.is_none(),
491            "Cannot provide both findItemIndexCallback and findChildIndexCallback. Use \
492             findItemIndexCallback as findChildIndexCallback is deprecated."
493        );
494        self.find_child_index_callback = Some(value);
495        self
496    }
497
498    /// Dart `addAutomaticKeepAlives:`.
499    pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverListSeparated {
500        self.add_automatic_keep_alives = value;
501        self
502    }
503
504    /// Dart `addRepaintBoundaries:`.
505    pub fn add_repaint_boundaries(mut self, value: bool) -> SliverListSeparated {
506        self.add_repaint_boundaries = value;
507        self
508    }
509
510    /// Dart `addSemanticIndexes:`.
511    pub fn add_semantic_indexes(mut self, value: bool) -> SliverListSeparated {
512        self.add_semantic_indexes = value;
513        self
514    }
515
516    /// The `SliverList` this constructor describes.
517    pub fn build(self) -> SliverList {
518        let (item_builder, separator_builder) = (self.item_builder, self.separator_builder);
519        let builder: NullableIndexedWidgetBuilder =
520            Rc::new(move |app: &mut App, context: BuildContext, index: i32| {
521                let item_index = index / 2;
522                if index % 2 == 0 {
523                    item_builder(app, context, item_index)
524                } else {
525                    let widget = separator_builder(app, context, item_index);
526                    debug_assert!(widget.is_some(), "separator_builder cannot return None.");
527                    widget
528                }
529            });
530        let semantic_index_callback: SemanticIndexCallback = Rc::new(|_widget, index| {
531            if index % 2 == 0 {
532                Some(index / 2)
533            } else {
534                None
535            }
536        });
537        let mut delegate = SliverChildBuilderDelegate::from_builder(builder)
538            .add_automatic_keep_alives(self.add_automatic_keep_alives)
539            .add_repaint_boundaries(self.add_repaint_boundaries)
540            .add_semantic_indexes(self.add_semantic_indexes)
541            .semantic_index_callback(semantic_index_callback);
542        if let Some(item_count) = self.item_count {
543            delegate = delegate.child_count(0.max(item_count * 2 - 1));
544        }
545        match (
546            self.find_item_index_callback,
547            self.find_child_index_callback,
548        ) {
549            (Some(find_item_index_callback), _) => {
550                delegate = delegate.find_child_index_callback(Rc::new(move |key| {
551                    find_item_index_callback(key).map(|item_index| item_index * 2)
552                }));
553            }
554            (None, Some(find_child_index_callback)) => {
555                delegate = delegate.find_child_index_callback(find_child_index_callback);
556            }
557            (None, None) => {}
558        }
559        let mut list = SliverList::new(delegate.into_delegate());
560        if let Some(key) = self.key {
561            list = list.key(key);
562        }
563        list
564    }
565}
566
567impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverListSeparated {
568    #[cfg_attr(debug_assertions, track_caller)]
569    fn into_widget(self) -> WidgetRef {
570        self.build().into_widget()
571    }
572}
573
574/// Dart's `SliverList.list(..)` arguments; `into_widget` builds the [`SliverList`].
575pub struct SliverListList {
576    key: Option<KeyRef>,
577    delegate: SliverChildListDelegate,
578}
579
580impl SliverListList {
581    fn new(children: Vec<WidgetRef>) -> SliverListList {
582        SliverListList {
583            key: None,
584            delegate: SliverChildListDelegate::new(children),
585        }
586    }
587
588    list_constructor_setters!(SliverListList);
589
590    /// The `SliverList` this constructor describes.
591    pub fn build(self) -> SliverList {
592        let mut list = SliverList::new(self.delegate.into_delegate());
593        if let Some(key) = self.key {
594            list = list.key(key);
595        }
596        list
597    }
598}
599
600impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverListList {
601    #[cfg_attr(debug_assertions, track_caller)]
602    fn into_widget(self) -> WidgetRef {
603        self.build().into_widget()
604    }
605}
606
607// ---------------------------------------------------------------------------------------------
608// SliverFixedExtentList
609
610/// A sliver that places multiple box children with the same main axis extent in a linear array.
611///
612/// _To learn more about slivers, see `CustomScrollView::slivers`._
613///
614/// [`SliverFixedExtentList`] places its children in a linear array along the main axis starting
615/// at offset zero and without gaps. Each child is forced to have the
616/// [`item_extent`](Self::item_extent) in the main axis and the
617/// `SliverConstraints::cross_axis_extent` in the cross axis.
618///
619/// [`SliverFixedExtentList`] is more efficient than [`SliverList`] because
620/// [`SliverFixedExtentList`] does not need to perform layout on its children to obtain their
621/// extent in the main axis.
622///
623/// See also:
624///
625///  * [`SliverVariedExtentList`], which supports children with varying (but known upfront)
626///    extents.
627///  * [`SliverList`], which does not require its children to have the same extent in the main
628///    axis.
629#[derive(Debug)]
630pub struct SliverFixedExtentList {
631    pub key: Option<KeyRef>,
632    /// The delegate that provides the children for this widget.
633    pub delegate: SliverChildDelegateRef,
634    /// The extent the children are forced to have in the main axis.
635    pub item_extent: f64,
636}
637
638impl SliverFixedExtentList {
639    /// Creates a sliver that places box children with the same main axis extent in a linear
640    /// array.
641    pub fn new(delegate: SliverChildDelegateRef, item_extent: f64) -> SliverFixedExtentList {
642        SliverFixedExtentList {
643            key: None,
644            delegate,
645            item_extent,
646        }
647    }
648
649    /// A sliver that places multiple box children in a linear array along the main axis, built
650    /// lazily.
651    ///
652    /// This constructor is appropriate for sliver lists with a large (or infinite) number of
653    /// children whose extent is already determined.
654    pub fn builder(
655        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
656        item_extent: f64,
657    ) -> SliverFixedExtentListBuilder {
658        SliverFixedExtentListBuilder::new(Rc::new(item_builder), item_extent)
659    }
660
661    /// A sliver that places multiple box children in a linear array along the main axis, built
662    /// from an explicit list of widgets.
663    pub fn list(children: Vec<WidgetRef>, item_extent: f64) -> SliverFixedExtentListList {
664        SliverFixedExtentListList::new(children, item_extent)
665    }
666
667    /// Dart `SliverFixedExtentList(key:)`.
668    pub fn key(mut self, key: KeyRef) -> SliverFixedExtentList {
669        self.key = Some(key);
670        self
671    }
672}
673
674impl RenderObjectWidget for SliverFixedExtentList {
675    type RenderObject = RenderSliverFixedExtentList;
676
677    fn key(&self) -> Option<&KeyRef> {
678        self.key.as_ref()
679    }
680
681    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
682        SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
683    }
684
685    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
686        RenderSliverFixedExtentList::new(
687            app,
688            child_manager_of::<SliverFixedExtentList>(app, context),
689            self.item_extent,
690        )
691        .as_object()
692    }
693
694    fn update_render_object(
695        &self,
696        app: &mut App,
697        _context: BuildContext,
698        render_object: RenderHandle<RenderSliverFixedExtentList>,
699    ) {
700        render_object.set_item_extent(app, self.item_extent);
701    }
702}
703
704impl SliverWithKeepAliveWidget for SliverFixedExtentList {}
705
706impl SliverMultiBoxAdaptorWidget for SliverFixedExtentList {
707    fn delegate(&self) -> &SliverChildDelegateRef {
708        &self.delegate
709    }
710}
711
712/// Dart's `SliverFixedExtentList.builder(..)` arguments.
713pub struct SliverFixedExtentListBuilder {
714    key: Option<KeyRef>,
715    delegate: SliverChildBuilderDelegate,
716    item_extent: f64,
717}
718
719impl SliverFixedExtentListBuilder {
720    fn new(
721        item_builder: NullableIndexedWidgetBuilder,
722        item_extent: f64,
723    ) -> SliverFixedExtentListBuilder {
724        SliverFixedExtentListBuilder {
725            key: None,
726            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
727            item_extent,
728        }
729    }
730
731    builder_constructor_setters!(SliverFixedExtentListBuilder);
732
733    /// Dart `semanticIndexOffset:`.
734    pub fn semantic_index_offset(mut self, value: i32) -> SliverFixedExtentListBuilder {
735        self.delegate = self.delegate.semantic_index_offset(value);
736        self
737    }
738
739    /// Dart `findChildIndexCallback:`.
740    pub fn find_child_index_callback(
741        mut self,
742        value: ChildIndexGetter,
743    ) -> SliverFixedExtentListBuilder {
744        self.delegate = self.delegate.find_child_index_callback(value);
745        self
746    }
747
748    /// The `SliverFixedExtentList` this constructor describes.
749    pub fn build(self) -> SliverFixedExtentList {
750        let mut list = SliverFixedExtentList::new(self.delegate.into_delegate(), self.item_extent);
751        if let Some(key) = self.key {
752            list = list.key(key);
753        }
754        list
755    }
756}
757
758impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverFixedExtentListBuilder {
759    #[cfg_attr(debug_assertions, track_caller)]
760    fn into_widget(self) -> WidgetRef {
761        self.build().into_widget()
762    }
763}
764
765/// Dart's `SliverFixedExtentList.list(..)` arguments.
766pub struct SliverFixedExtentListList {
767    key: Option<KeyRef>,
768    delegate: SliverChildListDelegate,
769    item_extent: f64,
770}
771
772impl SliverFixedExtentListList {
773    fn new(children: Vec<WidgetRef>, item_extent: f64) -> SliverFixedExtentListList {
774        SliverFixedExtentListList {
775            key: None,
776            delegate: SliverChildListDelegate::new(children),
777            item_extent,
778        }
779    }
780
781    list_constructor_setters!(SliverFixedExtentListList);
782
783    /// The `SliverFixedExtentList` this constructor describes.
784    pub fn build(self) -> SliverFixedExtentList {
785        let mut list = SliverFixedExtentList::new(self.delegate.into_delegate(), self.item_extent);
786        if let Some(key) = self.key {
787            list = list.key(key);
788        }
789        list
790    }
791}
792
793impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverFixedExtentListList {
794    #[cfg_attr(debug_assertions, track_caller)]
795    fn into_widget(self) -> WidgetRef {
796        self.build().into_widget()
797    }
798}
799
800// ---------------------------------------------------------------------------------------------
801// SliverVariedExtentList
802
803/// A sliver that places its box children in a linear array and constrains them to have the
804/// corresponding extent returned by [`item_extent_builder`](Self::item_extent_builder).
805///
806/// _To learn more about slivers, see `CustomScrollView::slivers`._
807///
808/// [`SliverVariedExtentList`] arranges its children in a line along the main axis starting at
809/// offset zero and without gaps. Each child is constrained to the corresponding extent along the
810/// main axis and the `SliverConstraints::cross_axis_extent` along the cross axis.
811///
812/// [`SliverVariedExtentList`] is more efficient than [`SliverList`] because it does not need to
813/// lay out its children to obtain their extent along the main axis. It's a little more flexible
814/// than [`SliverFixedExtentList`] because this allows the children to have different extents.
815pub struct SliverVariedExtentList {
816    pub key: Option<KeyRef>,
817    /// The delegate that provides the children for this widget.
818    pub delegate: SliverChildDelegateRef,
819    /// The children extent builder.
820    ///
821    /// Should return `None` if asked to build an item extent with a greater index than exists.
822    pub item_extent_builder: ItemExtentBuilder,
823}
824
825impl SliverVariedExtentList {
826    /// Creates a sliver that places box children with the corresponding main axis extent in a
827    /// linear array.
828    pub fn new(
829        delegate: SliverChildDelegateRef,
830        item_extent_builder: ItemExtentBuilder,
831    ) -> SliverVariedExtentList {
832        SliverVariedExtentList {
833            key: None,
834            delegate,
835            item_extent_builder,
836        }
837    }
838
839    /// A sliver that places multiple box children in a linear array along the main axis, built
840    /// lazily.
841    pub fn builder(
842        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
843        item_extent_builder: ItemExtentBuilder,
844    ) -> SliverVariedExtentListBuilder {
845        SliverVariedExtentListBuilder::new(Rc::new(item_builder), item_extent_builder)
846    }
847
848    /// A sliver that places multiple box children in a linear array along the main axis, built
849    /// from an explicit list of widgets.
850    pub fn list(
851        children: Vec<WidgetRef>,
852        item_extent_builder: ItemExtentBuilder,
853    ) -> SliverVariedExtentListList {
854        SliverVariedExtentListList::new(children, item_extent_builder)
855    }
856
857    /// Dart `SliverVariedExtentList(key:)`.
858    pub fn key(mut self, key: KeyRef) -> SliverVariedExtentList {
859        self.key = Some(key);
860        self
861    }
862}
863
864impl Debug for SliverVariedExtentList {
865    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
866        f.debug_struct("SliverVariedExtentList")
867            .field("key", &self.key)
868            .field("delegate", &self.delegate)
869            .finish_non_exhaustive()
870    }
871}
872
873impl RenderObjectWidget for SliverVariedExtentList {
874    type RenderObject = RenderSliverVariedExtentList;
875
876    fn key(&self) -> Option<&KeyRef> {
877        self.key.as_ref()
878    }
879
880    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
881        SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
882    }
883
884    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
885        RenderSliverVariedExtentList::new(
886            app,
887            child_manager_of::<SliverVariedExtentList>(app, context),
888            Rc::clone(&self.item_extent_builder),
889        )
890        .as_object()
891    }
892
893    fn update_render_object(
894        &self,
895        app: &mut App,
896        _context: BuildContext,
897        render_object: RenderHandle<RenderSliverVariedExtentList>,
898    ) {
899        render_object.set_item_extent_builder(app, Rc::clone(&self.item_extent_builder));
900    }
901}
902
903impl SliverWithKeepAliveWidget for SliverVariedExtentList {}
904
905impl SliverMultiBoxAdaptorWidget for SliverVariedExtentList {
906    fn delegate(&self) -> &SliverChildDelegateRef {
907        &self.delegate
908    }
909}
910
911/// Dart's `SliverVariedExtentList.builder(..)` arguments.
912pub struct SliverVariedExtentListBuilder {
913    key: Option<KeyRef>,
914    delegate: SliverChildBuilderDelegate,
915    item_extent_builder: ItemExtentBuilder,
916}
917
918impl SliverVariedExtentListBuilder {
919    fn new(
920        item_builder: NullableIndexedWidgetBuilder,
921        item_extent_builder: ItemExtentBuilder,
922    ) -> SliverVariedExtentListBuilder {
923        SliverVariedExtentListBuilder {
924            key: None,
925            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
926            item_extent_builder,
927        }
928    }
929
930    builder_constructor_setters!(SliverVariedExtentListBuilder);
931
932    /// Dart `findChildIndexCallback:`.
933    pub fn find_child_index_callback(
934        mut self,
935        value: ChildIndexGetter,
936    ) -> SliverVariedExtentListBuilder {
937        self.delegate = self.delegate.find_child_index_callback(value);
938        self
939    }
940
941    /// The `SliverVariedExtentList` this constructor describes.
942    pub fn build(self) -> SliverVariedExtentList {
943        let mut list =
944            SliverVariedExtentList::new(self.delegate.into_delegate(), self.item_extent_builder);
945        if let Some(key) = self.key {
946            list = list.key(key);
947        }
948        list
949    }
950}
951
952impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverVariedExtentListBuilder {
953    #[cfg_attr(debug_assertions, track_caller)]
954    fn into_widget(self) -> WidgetRef {
955        self.build().into_widget()
956    }
957}
958
959/// Dart's `SliverVariedExtentList.list(..)` arguments.
960pub struct SliverVariedExtentListList {
961    key: Option<KeyRef>,
962    delegate: SliverChildListDelegate,
963    item_extent_builder: ItemExtentBuilder,
964}
965
966impl SliverVariedExtentListList {
967    fn new(
968        children: Vec<WidgetRef>,
969        item_extent_builder: ItemExtentBuilder,
970    ) -> SliverVariedExtentListList {
971        SliverVariedExtentListList {
972            key: None,
973            delegate: SliverChildListDelegate::new(children),
974            item_extent_builder,
975        }
976    }
977
978    list_constructor_setters!(SliverVariedExtentListList);
979
980    /// The `SliverVariedExtentList` this constructor describes.
981    pub fn build(self) -> SliverVariedExtentList {
982        let mut list =
983            SliverVariedExtentList::new(self.delegate.into_delegate(), self.item_extent_builder);
984        if let Some(key) = self.key {
985            list = list.key(key);
986        }
987        list
988    }
989}
990
991impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverVariedExtentListList {
992    #[cfg_attr(debug_assertions, track_caller)]
993    fn into_widget(self) -> WidgetRef {
994        self.build().into_widget()
995    }
996}
997
998// ---------------------------------------------------------------------------------------------
999// SliverGrid
1000
1001/// A sliver that places multiple box children in a two dimensional arrangement.
1002///
1003/// _To learn more about slivers, see `CustomScrollView::slivers`._
1004///
1005/// [`SliverGrid`] places its children in arbitrary positions determined by
1006/// [`grid_delegate`](Self::grid_delegate). Each child is forced to have the size specified by the
1007/// `grid_delegate`.
1008///
1009/// The main axis direction of a grid is the direction in which it scrolls; the cross axis
1010/// direction is the orthogonal direction.
1011///
1012/// See also:
1013///
1014///  * [`SliverList`], which places its children in a linear array.
1015///  * [`SliverFixedExtentList`], which places its children in a linear array with a fixed extent
1016///    in the main axis.
1017#[derive(Debug)]
1018pub struct SliverGrid {
1019    pub key: Option<KeyRef>,
1020    /// The delegate that provides the children for this widget.
1021    pub delegate: SliverChildDelegateRef,
1022    /// The delegate that controls the size and position of the children.
1023    pub grid_delegate: Rc<dyn SliverGridDelegate>,
1024}
1025
1026impl SliverGrid {
1027    /// Creates a sliver that places multiple box children in a two dimensional arrangement.
1028    pub fn new(
1029        delegate: SliverChildDelegateRef,
1030        grid_delegate: Rc<dyn SliverGridDelegate>,
1031    ) -> SliverGrid {
1032        SliverGrid {
1033            key: None,
1034            delegate,
1035            grid_delegate,
1036        }
1037    }
1038
1039    /// A sliver that creates a 2D array of widgets that are created on demand.
1040    ///
1041    /// This constructor is appropriate for sliver grids with a large (or infinite) number of
1042    /// children because the builder is called only for those children that are actually visible.
1043    ///
1044    /// Providing a non-`None` [`item_count`](SliverGridBuilder::item_count) improves the ability
1045    /// of the [`SliverGrid`] to estimate the maximum scroll extent.
1046    ///
1047    /// The item builder will be called only with indices greater than or equal to zero and less
1048    /// than the item count.
1049    pub fn builder(
1050        grid_delegate: Rc<dyn SliverGridDelegate>,
1051        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1052    ) -> SliverGridBuilder {
1053        SliverGridBuilder::new(grid_delegate, Rc::new(item_builder))
1054    }
1055
1056    /// Creates a sliver that places multiple box children in a two dimensional arrangement with
1057    /// a fixed number of tiles in the cross axis.
1058    ///
1059    /// Uses a [`SliverGridDelegateWithFixedCrossAxisCount`] as the
1060    /// [`grid_delegate`](Self::grid_delegate), and a `SliverChildListDelegate` as the
1061    /// [`delegate`](Self::delegate).
1062    ///
1063    /// See also:
1064    ///
1065    ///  * `GridView::count`, the equivalent constructor for `GridView` widgets.
1066    pub fn count(cross_axis_count: i32) -> SliverGridCount {
1067        SliverGridCount {
1068            key: None,
1069            grid_delegate: SliverGridDelegateWithFixedCrossAxisCount::new(cross_axis_count),
1070            children: Vec::new(),
1071        }
1072    }
1073
1074    /// Creates a sliver that places multiple box children in a two dimensional arrangement with
1075    /// tiles that each have a maximum cross-axis extent.
1076    ///
1077    /// Uses a [`SliverGridDelegateWithMaxCrossAxisExtent`] as the
1078    /// [`grid_delegate`](Self::grid_delegate), and a `SliverChildListDelegate` as the
1079    /// [`delegate`](Self::delegate).
1080    ///
1081    /// See also:
1082    ///
1083    ///  * `GridView::extent`, the equivalent constructor for `GridView` widgets.
1084    pub fn extent(max_cross_axis_extent: f64) -> SliverGridExtent {
1085        SliverGridExtent {
1086            key: None,
1087            grid_delegate: SliverGridDelegateWithMaxCrossAxisExtent::new(max_cross_axis_extent),
1088            children: Vec::new(),
1089        }
1090    }
1091
1092    /// Creates a sliver that places multiple box children in a two dimensional arrangement.
1093    ///
1094    /// _To learn more about slivers, see `CustomScrollView::slivers`._
1095    ///
1096    /// Uses a `SliverChildListDelegate` as the [`delegate`](Self::delegate).
1097    pub fn list(
1098        grid_delegate: Rc<dyn SliverGridDelegate>,
1099        children: Vec<WidgetRef>,
1100    ) -> SliverGridList {
1101        SliverGridList {
1102            key: None,
1103            delegate: SliverChildListDelegate::new(children),
1104            grid_delegate,
1105        }
1106    }
1107
1108    /// Dart `SliverGrid(key:)`.
1109    pub fn key(mut self, key: KeyRef) -> SliverGrid {
1110        self.key = Some(key);
1111        self
1112    }
1113
1114    /// The [`SliverGrid`] with `key`, if given.
1115    fn keyed(self, key: Option<KeyRef>) -> SliverGrid {
1116        match key {
1117            Some(key) => self.key(key),
1118            None => self,
1119        }
1120    }
1121}
1122
1123impl RenderObjectWidget for SliverGrid {
1124    type RenderObject = RenderSliverGrid;
1125
1126    fn key(&self) -> Option<&KeyRef> {
1127        self.key.as_ref()
1128    }
1129
1130    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1131        SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
1132    }
1133
1134    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1135        RenderSliverGrid::new(
1136            app,
1137            child_manager_of::<SliverGrid>(app, context),
1138            Rc::clone(&self.grid_delegate),
1139        )
1140        .as_object()
1141    }
1142
1143    fn update_render_object(
1144        &self,
1145        app: &mut App,
1146        _context: BuildContext,
1147        render_object: RenderHandle<RenderSliverGrid>,
1148    ) {
1149        render_object.set_grid_delegate(app, Rc::clone(&self.grid_delegate));
1150    }
1151}
1152
1153impl SliverWithKeepAliveWidget for SliverGrid {}
1154
1155impl SliverMultiBoxAdaptorWidget for SliverGrid {
1156    fn delegate(&self) -> &SliverChildDelegateRef {
1157        &self.delegate
1158    }
1159
1160    fn estimate_max_scroll_offset(
1161        &self,
1162        constraints: Option<SliverConstraints>,
1163        first_index: i32,
1164        last_index: i32,
1165        leading_scroll_offset: f64,
1166        trailing_scroll_offset: f64,
1167    ) -> Option<f64> {
1168        debug_assert!(last_index >= first_index);
1169        self.delegate
1170            .estimate_max_scroll_offset(
1171                first_index,
1172                last_index,
1173                leading_scroll_offset,
1174                trailing_scroll_offset,
1175            )
1176            .or_else(|| {
1177                let constraints = constraints.expect("a grid estimates during its layout");
1178                let child_count = self
1179                    .delegate
1180                    .estimated_child_count()
1181                    .expect("a grid whose delegate cannot estimate counts its children");
1182                Some(
1183                    self.grid_delegate
1184                        .get_layout(constraints)
1185                        .compute_max_scroll_offset(child_count),
1186                )
1187            })
1188    }
1189}
1190
1191/// Dart's `SliverGrid.builder(..)` arguments; `into_widget` builds the [`SliverGrid`].
1192pub struct SliverGridBuilder {
1193    key: Option<KeyRef>,
1194    delegate: SliverChildBuilderDelegate,
1195    grid_delegate: Rc<dyn SliverGridDelegate>,
1196}
1197
1198impl SliverGridBuilder {
1199    fn new(
1200        grid_delegate: Rc<dyn SliverGridDelegate>,
1201        item_builder: NullableIndexedWidgetBuilder,
1202    ) -> SliverGridBuilder {
1203        SliverGridBuilder {
1204            key: None,
1205            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
1206            grid_delegate,
1207        }
1208    }
1209
1210    builder_constructor_setters!(SliverGridBuilder);
1211
1212    /// Dart `semanticIndexOffset:`.
1213    pub fn semantic_index_offset(mut self, value: i32) -> SliverGridBuilder {
1214        self.delegate = self.delegate.semantic_index_offset(value);
1215        self
1216    }
1217
1218    /// Dart `findChildIndexCallback:`.
1219    pub fn find_child_index_callback(mut self, value: ChildIndexGetter) -> SliverGridBuilder {
1220        self.delegate = self.delegate.find_child_index_callback(value);
1221        self
1222    }
1223
1224    /// The `SliverGrid` this constructor describes.
1225    pub fn build(self) -> SliverGrid {
1226        SliverGrid::new(self.delegate.into_delegate(), self.grid_delegate).keyed(self.key)
1227    }
1228}
1229
1230impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridBuilder {
1231    #[cfg_attr(debug_assertions, track_caller)]
1232    fn into_widget(self) -> WidgetRef {
1233        self.build().into_widget()
1234    }
1235}
1236
1237/// The fluent arguments `SliverGrid::count` and `SliverGrid::extent` share: their grid
1238/// delegate's spacing and aspect ratio, and the children.
1239macro_rules! tiles_constructor_setters {
1240    ($name:ident) => {
1241        /// Dart `key:`.
1242        pub fn key(mut self, key: KeyRef) -> $name {
1243            self.key = Some(key);
1244            self
1245        }
1246
1247        /// Dart `mainAxisSpacing:`.
1248        pub fn main_axis_spacing(mut self, value: f64) -> $name {
1249            self.grid_delegate = self.grid_delegate.main_axis_spacing(value);
1250            self
1251        }
1252
1253        /// Dart `crossAxisSpacing:`.
1254        pub fn cross_axis_spacing(mut self, value: f64) -> $name {
1255            self.grid_delegate = self.grid_delegate.cross_axis_spacing(value);
1256            self
1257        }
1258
1259        /// Dart `childAspectRatio:`.
1260        pub fn child_aspect_ratio(mut self, value: f64) -> $name {
1261            self.grid_delegate = self.grid_delegate.child_aspect_ratio(value);
1262            self
1263        }
1264
1265        /// Dart `children:`.
1266        pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
1267            self.children = children.into_iter().collect();
1268            self
1269        }
1270
1271        /// The `SliverGrid` this constructor describes.
1272        pub fn build(self) -> SliverGrid {
1273            SliverGrid::new(
1274                SliverChildListDelegate::new(self.children).into_delegate(),
1275                Rc::new(self.grid_delegate),
1276            )
1277            .keyed(self.key)
1278        }
1279    };
1280}
1281
1282/// Dart's `SliverGrid.count(..)` arguments; `into_widget` builds the [`SliverGrid`].
1283pub struct SliverGridCount {
1284    key: Option<KeyRef>,
1285    grid_delegate: SliverGridDelegateWithFixedCrossAxisCount,
1286    children: Vec<WidgetRef>,
1287}
1288
1289impl SliverGridCount {
1290    tiles_constructor_setters!(SliverGridCount);
1291}
1292
1293impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridCount {
1294    #[cfg_attr(debug_assertions, track_caller)]
1295    fn into_widget(self) -> WidgetRef {
1296        self.build().into_widget()
1297    }
1298}
1299
1300/// Dart's `SliverGrid.extent(..)` arguments; `into_widget` builds the [`SliverGrid`].
1301pub struct SliverGridExtent {
1302    key: Option<KeyRef>,
1303    grid_delegate: SliverGridDelegateWithMaxCrossAxisExtent,
1304    children: Vec<WidgetRef>,
1305}
1306
1307impl SliverGridExtent {
1308    tiles_constructor_setters!(SliverGridExtent);
1309}
1310
1311impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridExtent {
1312    #[cfg_attr(debug_assertions, track_caller)]
1313    fn into_widget(self) -> WidgetRef {
1314        self.build().into_widget()
1315    }
1316}
1317
1318/// Dart's `SliverGrid.list(..)` arguments; `into_widget` builds the [`SliverGrid`].
1319pub struct SliverGridList {
1320    key: Option<KeyRef>,
1321    delegate: SliverChildListDelegate,
1322    grid_delegate: Rc<dyn SliverGridDelegate>,
1323}
1324
1325impl SliverGridList {
1326    list_constructor_setters!(SliverGridList);
1327
1328    /// Dart `semanticIndexOffset:`.
1329    pub fn semantic_index_offset(mut self, value: i32) -> SliverGridList {
1330        self.delegate = self.delegate.semantic_index_offset(value);
1331        self
1332    }
1333
1334    /// The `SliverGrid` this constructor describes.
1335    pub fn build(self) -> SliverGrid {
1336        SliverGrid::new(self.delegate.into_delegate(), self.grid_delegate).keyed(self.key)
1337    }
1338}
1339
1340impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridList {
1341    #[cfg_attr(debug_assertions, track_caller)]
1342    fn into_widget(self) -> WidgetRef {
1343        self.build().into_widget()
1344    }
1345}
1346
1347// ---------------------------------------------------------------------------------------------
1348// SliverMultiBoxAdaptorElement
1349
1350/// Dart's `context as SliverMultiBoxAdaptorElement`, as the render object's child manager.
1351pub fn child_manager_of<W: SliverMultiBoxAdaptorWidget>(
1352    app: &App,
1353    context: BuildContext,
1354) -> Rc<dyn RenderSliverBoxChildManager>
1355where
1356    W::RenderObject: RenderSliverMultiBoxAdaptor,
1357{
1358    let element = context
1359        .downcast::<SliverMultiBoxAdaptorElement<W>>(app)
1360        .expect("a SliverMultiBoxAdaptorWidget creates its render object from its own element");
1361    element.as_child_manager()
1362}
1363
1364/// The fields of Dart's `SliverMultiBoxAdaptorElement`.
1365pub struct SliverMultiBoxAdaptorElementData {
1366    replace_moved_children: bool,
1367    child_elements: BTreeMap<i32, Option<AnyElement>>,
1368    current_before_child: Option<AnyRenderBox>,
1369    currently_updating_child_index: Option<i32>,
1370    did_underflow: bool,
1371}
1372
1373impl SliverMultiBoxAdaptorElementData {
1374    /// The fields of an element that has built no children yet; `replace_moved_children` is
1375    /// [`SliverMultiBoxAdaptorElement::new`]'s.
1376    pub fn new(replace_moved_children: bool) -> SliverMultiBoxAdaptorElementData {
1377        SliverMultiBoxAdaptorElementData {
1378            replace_moved_children,
1379            child_elements: BTreeMap::new(),
1380            current_before_child: None,
1381            currently_updating_child_index: None,
1382            did_underflow: false,
1383        }
1384    }
1385}
1386
1387/// The bodies of Dart's `SliverMultiBoxAdaptorElement`: an element that lazily builds children
1388/// for a [`SliverMultiBoxAdaptorWidget`].
1389///
1390/// Implements `RenderSliverBoxChildManager`, which lets this element manage the children of
1391/// implementors of `RenderSliverMultiBoxAdaptor`. The render object holds the manager as an
1392/// `Rc<dyn RenderSliverBoxChildManager>` ([`as_child_manager`](Self::as_child_manager)), which
1393/// the widget hands it in `create_render_object` after casting the [`BuildContext`] back to this
1394/// element.
1395///
1396/// Flutter's class is instantiable and also subclassed (`SliverPrototypeExtentList`'s element),
1397/// so the bodies live on this trait and [`SliverMultiBoxAdaptorElement`] is the plain leaf that
1398/// implements it; a subclass calls the body it overrides by name where Dart writes `super`.
1399pub trait SliverMultiBoxAdaptorElementBase:
1400    RenderObjectElement + RenderObjectElementWidget
1401where
1402    Self::Widget: SliverMultiBoxAdaptorWidget,
1403    <Self::Widget as RenderObjectWidget>::RenderObject: RenderSliverMultiBoxAdaptor,
1404{
1405    /// The lazily built children, held under the field `adaptor`.
1406    fn adaptor_data(self: Handle<Self>, app: &App) -> &SliverMultiBoxAdaptorElementData;
1407
1408    /// See [`adaptor_data`](Self::adaptor_data).
1409    fn adaptor_data_mut(self: Handle<Self>, app: &mut App)
1410    -> &mut SliverMultiBoxAdaptorElementData;
1411
1412    /// This element as the `RenderSliverBoxChildManager` its render object holds.
1413    fn as_child_manager(self: Handle<Self>) -> Rc<dyn RenderSliverBoxChildManager> {
1414        Rc::new(ChildManager(self))
1415    }
1416
1417    /// Flutter's `_build`.
1418    fn build(self: Handle<Self>, app: &mut App, index: i32) -> Option<WidgetRef> {
1419        let delegate = Rc::clone(Self::widget_of(self.as_element().widget(app)).delegate());
1420        delegate.build(app, self.as_element(), index)
1421    }
1422
1423    /// `SliverMultiBoxAdaptorElement.updateChild`: preserves the old layout offset when the
1424    /// render object was swapped out.
1425    fn update_child(
1426        self: Handle<Self>,
1427        app: &mut App,
1428        child: Option<AnyElement>,
1429        new_widget: Option<WidgetRef>,
1430        new_slot: Option<Slot>,
1431    ) -> Option<AnyElement> {
1432        let old = Self::adaptor_parent_data(app, child)
1433            .map(|object| (object, Self::layout_offset(app, object)));
1434        let new_child = self
1435            .as_element()
1436            .update_child(app, child, new_widget, new_slot);
1437        let new = Self::adaptor_parent_data(app, new_child);
1438
1439        // Preserve the old layoutOffset if the renderObject was swapped out.
1440        if let Some((old_object, layout_offset)) = old
1441            && let Some(new_object) = new
1442            && old_object != new_object
1443        {
1444            Self::set_layout_offset(app, new_object, layout_offset);
1445        }
1446        new_child
1447    }
1448
1449    /// The child's render object, when it carries a `SliverMultiBoxAdaptorParentData`.
1450    fn adaptor_parent_data(app: &App, child: Option<AnyElement>) -> Option<AnyRenderObject> {
1451        child
1452            .and_then(|child| child.render_object(app))
1453            .filter(|object| object.parent_data_is::<SliverMultiBoxAdaptorParentData>(app))
1454    }
1455
1456    /// The layout offset in the child's `SliverMultiBoxAdaptorParentData`.
1457    fn layout_offset(app: &App, object: AnyRenderObject) -> Option<f64> {
1458        object
1459            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
1460            .layout_offset()
1461    }
1462
1463    /// Sets the layout offset in the child's `SliverMultiBoxAdaptorParentData`.
1464    fn set_layout_offset(app: &mut App, object: AnyRenderObject, value: Option<f64>) {
1465        object
1466            .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
1467            .set_layout_offset(value);
1468    }
1469
1470    /// Flutter's `processElement` closure inside `performRebuild`.
1471    fn process_element(
1472        self: Handle<Self>,
1473        app: &mut App,
1474        index: i32,
1475        new_children: &BTreeMap<i32, Option<AnyElement>>,
1476        index_to_layout_offset: &HashMap<i32, f64>,
1477        children_updated: &mut bool,
1478    ) {
1479        self.adaptor_data_mut(app).currently_updating_child_index = Some(index);
1480        let existing = self
1481            .adaptor_data(app)
1482            .child_elements
1483            .get(&index)
1484            .copied()
1485            .flatten();
1486        let planned = new_children.get(&index).copied().flatten();
1487        if existing.is_some() && existing != planned {
1488            // This index has an old child that isn't used anywhere and should be deactivated.
1489            let deactivated = self.update_child(app, existing, None, Some(Slot::Index(index)));
1490            self.adaptor_data_mut(app)
1491                .child_elements
1492                .insert(index, deactivated);
1493            *children_updated = true;
1494        }
1495        let built = self.build(app, index);
1496        let new_child = self.update_child(app, planned, built, Some(Slot::Index(index)));
1497        match new_child {
1498            Some(new_child) => {
1499                *children_updated = *children_updated
1500                    || self
1501                        .adaptor_data(app)
1502                        .child_elements
1503                        .get(&index)
1504                        .copied()
1505                        .flatten()
1506                        != Some(new_child);
1507                self.adaptor_data_mut(app)
1508                    .child_elements
1509                    .insert(index, Some(new_child));
1510                let object = new_child
1511                    .render_object(app)
1512                    .expect("a built child has a render object");
1513                if index == 0 {
1514                    Self::set_layout_offset(app, object, Some(0.0));
1515                } else if let Some(offset) = index_to_layout_offset.get(&index) {
1516                    Self::set_layout_offset(app, object, Some(*offset));
1517                }
1518                let parent_data = object.parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
1519                if !parent_data.kept_alive() {
1520                    self.adaptor_data_mut(app).current_before_child =
1521                        Some(object.as_box().expect("a sliver child is a box"));
1522                }
1523            }
1524            None => {
1525                *children_updated = true;
1526                self.adaptor_data_mut(app).child_elements.remove(&index);
1527            }
1528        }
1529    }
1530
1531    /// Flutter's `_extrapolateMaxScrollOffset`.
1532    fn extrapolate_max_scroll_offset(
1533        first_index: i32,
1534        last_index: i32,
1535        leading_scroll_offset: f64,
1536        trailing_scroll_offset: f64,
1537        child_count: i32,
1538    ) -> f64 {
1539        if last_index == child_count - 1 {
1540            return trailing_scroll_offset;
1541        }
1542        let reified_count = last_index - first_index + 1;
1543        let average_extent =
1544            (trailing_scroll_offset - leading_scroll_offset) / f64::from(reified_count);
1545        let remaining_count = child_count - last_index - 1;
1546        trailing_scroll_offset + average_extent * f64::from(remaining_count)
1547    }
1548
1549    /// Dart's `owner!.buildScope(this, callback)`.
1550    fn in_build_scope(
1551        self: Handle<Self>,
1552        app: &mut App,
1553        callback: impl FnOnce(&mut App) + 'static,
1554    ) {
1555        let owner = self
1556            .as_element()
1557            .owner(app)
1558            .expect("a mounted element has an owner");
1559        owner.build_scope(app, self.as_element(), Some(Box::new(callback)));
1560    }
1561
1562    // ---- the `RenderSliverBoxChildManager` members, which Dart implements on the element ----
1563
1564    /// `RenderSliverBoxChildManager::create_child`.
1565    fn create_child(self: Handle<Self>, app: &mut App, index: i32, after: Option<AnyRenderBox>) {
1566        debug_assert!(
1567            self.adaptor_data(app)
1568                .currently_updating_child_index
1569                .is_none()
1570        );
1571        self.in_build_scope(app, move |app| {
1572            let insert_first = after.is_none();
1573            debug_assert!(
1574                insert_first
1575                    || self
1576                        .adaptor_data(app)
1577                        .child_elements
1578                        .get(&(index - 1))
1579                        .copied()
1580                        .flatten()
1581                        .is_some()
1582            );
1583            let before = if insert_first {
1584                None
1585            } else {
1586                self.adaptor_data(app).child_elements[&(index - 1)]
1587                    .expect("asserted above")
1588                    .render_object(app)
1589                    .map(|object| object.as_box().expect("a sliver child is a box"))
1590            };
1591            self.adaptor_data_mut(app).current_before_child = before;
1592            self.adaptor_data_mut(app).currently_updating_child_index = Some(index);
1593            let built = self.build(app, index);
1594            let existing = self
1595                .adaptor_data(app)
1596                .child_elements
1597                .get(&index)
1598                .copied()
1599                .flatten();
1600            let new_child = self.update_child(app, existing, built, Some(Slot::Index(index)));
1601            self.adaptor_data_mut(app).currently_updating_child_index = None;
1602            match new_child {
1603                Some(new_child) => {
1604                    self.adaptor_data_mut(app)
1605                        .child_elements
1606                        .insert(index, Some(new_child));
1607                }
1608                None => {
1609                    self.adaptor_data_mut(app).child_elements.remove(&index);
1610                }
1611            }
1612        });
1613    }
1614
1615    /// `RenderSliverBoxChildManager::remove_child`.
1616    fn remove_child(self: Handle<Self>, app: &mut App, child: AnyRenderBox) {
1617        let index = self.typed_render_object(app).index_of(app, child);
1618        debug_assert!(
1619            self.adaptor_data(app)
1620                .currently_updating_child_index
1621                .is_none()
1622        );
1623        debug_assert!(index >= 0);
1624        self.in_build_scope(app, move |app| {
1625            debug_assert!(self.adaptor_data(app).child_elements.contains_key(&index));
1626            self.adaptor_data_mut(app).currently_updating_child_index = Some(index);
1627            let existing = self
1628                .adaptor_data(app)
1629                .child_elements
1630                .get(&index)
1631                .copied()
1632                .flatten();
1633            let result = self.update_child(app, existing, None, Some(Slot::Index(index)));
1634            debug_assert!(result.is_none());
1635            self.adaptor_data_mut(app).currently_updating_child_index = None;
1636            self.adaptor_data_mut(app).child_elements.remove(&index);
1637            debug_assert!(!self.adaptor_data(app).child_elements.contains_key(&index));
1638        });
1639    }
1640
1641    /// `RenderSliverBoxChildManager::estimate_max_scroll_offset`.
1642    fn estimate_max_scroll_offset(
1643        self: Handle<Self>,
1644        app: &App,
1645        constraints: SliverConstraints,
1646        first_index: Option<i32>,
1647        last_index: Option<i32>,
1648        leading_scroll_offset: Option<f64>,
1649        trailing_scroll_offset: Option<f64>,
1650    ) -> f64 {
1651        let Some(child_count) = self.estimated_child_count(app) else {
1652            return f64::INFINITY;
1653        };
1654        let first_index = first_index.expect("a finite child list reports its window");
1655        let last_index = last_index.expect("a finite child list reports its window");
1656        let leading_scroll_offset =
1657            leading_scroll_offset.expect("a finite child list reports its window");
1658        let trailing_scroll_offset =
1659            trailing_scroll_offset.expect("a finite child list reports its window");
1660        Self::widget_of(self.as_element().widget(app))
1661            .estimate_max_scroll_offset(
1662                Some(constraints),
1663                first_index,
1664                last_index,
1665                leading_scroll_offset,
1666                trailing_scroll_offset,
1667            )
1668            .unwrap_or_else(|| {
1669                Self::extrapolate_max_scroll_offset(
1670                    first_index,
1671                    last_index,
1672                    leading_scroll_offset,
1673                    trailing_scroll_offset,
1674                    child_count,
1675                )
1676            })
1677    }
1678
1679    /// `RenderSliverBoxChildManager::estimated_child_count`.
1680    fn estimated_child_count(self: Handle<Self>, app: &App) -> Option<i32> {
1681        Self::widget_of(self.as_element().widget(app))
1682            .delegate()
1683            .estimated_child_count()
1684    }
1685
1686    /// `RenderSliverBoxChildManager::child_count`.
1687    fn child_count(self: Handle<Self>, app: &mut App) -> i32 {
1688        if let Some(result) = self.estimated_child_count(app) {
1689            return result;
1690        }
1691        // Since childCount was called, we know that we reached the end of the list (as in,
1692        // `build` returned None once), so we know that the list is finite. Let's do an
1693        // open-ended binary search to find the end of the list manually.
1694        let mut lo = 0;
1695        let mut hi = 1;
1696        let max = i32::MAX;
1697        while self.build(app, hi - 1).is_some() {
1698            lo = hi - 1;
1699            if hi < max / 2 {
1700                hi *= 2;
1701            } else if hi < max {
1702                hi = max;
1703            } else {
1704                panic!(
1705                    "Could not find the number of children in {:?}.\nThe child_count getter was \
1706                     called (implying that the delegate's builder returned None for a positive \
1707                     index), but even building the child with index {hi} (the maximum possible \
1708                     integer) did not return None. Consider implementing estimated_child_count to \
1709                     avoid the cost of searching for the final child.",
1710                    Self::widget_of(self.as_element().widget(app)).delegate()
1711                );
1712            }
1713        }
1714        while hi - lo > 1 {
1715            let mid = (hi - lo) / 2 + lo;
1716            if self.build(app, mid - 1).is_none() {
1717                hi = mid;
1718            } else {
1719                lo = mid;
1720            }
1721        }
1722        lo
1723    }
1724
1725    /// `RenderSliverBoxChildManager::did_start_layout`.
1726    fn did_start_layout(self: Handle<Self>, app: &App) {
1727        debug_assert!(self.debug_assert_child_list_locked(app));
1728    }
1729
1730    /// `RenderSliverBoxChildManager::did_finish_layout`.
1731    fn did_finish_layout(self: Handle<Self>, app: &App) {
1732        debug_assert!(self.debug_assert_child_list_locked(app));
1733        let first_index = self
1734            .adaptor_data(app)
1735            .child_elements
1736            .keys()
1737            .next()
1738            .copied()
1739            .unwrap_or(0);
1740        let last_index = self
1741            .adaptor_data(app)
1742            .child_elements
1743            .keys()
1744            .next_back()
1745            .copied()
1746            .unwrap_or(0);
1747        Self::widget_of(self.as_element().widget(app))
1748            .delegate()
1749            .did_finish_layout(first_index, last_index);
1750    }
1751
1752    /// `RenderSliverBoxChildManager::debug_assert_child_list_locked`.
1753    fn debug_assert_child_list_locked(self: Handle<Self>, app: &App) -> bool {
1754        debug_assert!(
1755            self.adaptor_data(app)
1756                .currently_updating_child_index
1757                .is_none()
1758        );
1759        true
1760    }
1761
1762    /// `RenderSliverBoxChildManager::did_adopt_child`.
1763    fn did_adopt_child(self: Handle<Self>, app: &mut App, child: AnyRenderBox) {
1764        debug_assert!(
1765            self.adaptor_data(app)
1766                .currently_updating_child_index
1767                .is_some()
1768        );
1769        let index = self.adaptor_data(app).currently_updating_child_index;
1770        child
1771            .as_object()
1772            .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
1773            .index = index;
1774    }
1775
1776    /// `RenderSliverBoxChildManager::set_did_underflow`.
1777    fn set_did_underflow(self: Handle<Self>, app: &mut App, value: bool) {
1778        self.adaptor_data_mut(app).did_underflow = value;
1779    }
1780
1781    // ---- the `Element` overrides ----
1782
1783    /// `SliverMultiBoxAdaptorElement.update`.
1784    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
1785        let old_widget = self.as_element().widget(app).clone();
1786        RenderObjectElement::update(self, app, new_widget.clone());
1787        let new_delegate = Rc::clone(Self::widget_of(&new_widget).delegate());
1788        let old_delegate = Rc::clone(Self::widget_of(&old_widget).delegate());
1789        if !same_delegate(&new_delegate, &old_delegate)
1790            && (new_delegate.delegate_type() != old_delegate.delegate_type()
1791                || new_delegate.should_rebuild(&*old_delegate))
1792        {
1793            Element::perform_rebuild(self, app);
1794        }
1795    }
1796
1797    /// `SliverMultiBoxAdaptorElement.performRebuild`.
1798    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
1799        RenderObjectElement::perform_rebuild(self, app);
1800        self.adaptor_data_mut(app).current_before_child = None;
1801        let mut children_updated = false;
1802        debug_assert!(
1803            self.adaptor_data(app)
1804                .currently_updating_child_index
1805                .is_none()
1806        );
1807
1808        let mut new_children: BTreeMap<i32, Option<AnyElement>> = BTreeMap::new();
1809        let mut index_to_layout_offset: HashMap<i32, f64> = HashMap::new();
1810        for index in self
1811            .adaptor_data(app)
1812            .child_elements
1813            .keys()
1814            .copied()
1815            .collect::<Vec<_>>()
1816        {
1817            let child = self.adaptor_data(app).child_elements[&index].expect("a live child");
1818            let key = child.widget(app).key().cloned();
1819            let new_index = key.and_then(|key| {
1820                Self::widget_of(self.as_element().widget(app))
1821                    .delegate()
1822                    .find_index_by_key(&key)
1823            });
1824            let child_parent_data = Self::adaptor_parent_data(app, Some(child));
1825
1826            if let Some(object) = child_parent_data
1827                && let Some(layout_offset) = Self::layout_offset(app, object)
1828            {
1829                index_to_layout_offset.insert(index, layout_offset);
1830            }
1831
1832            match new_index {
1833                Some(new_index) if new_index != index => {
1834                    // The layout offset of the child being moved is no longer accurate.
1835                    if let Some(object) = child_parent_data {
1836                        Self::set_layout_offset(app, object, None);
1837                    }
1838                    new_children.insert(new_index, Some(child));
1839                    if self.adaptor_data(app).replace_moved_children {
1840                        // We need to make sure the original index gets processed.
1841                        new_children.entry(index).or_insert(None);
1842                    }
1843                    // We do not want the remapped child to get deactivated during
1844                    // `process_element`.
1845                    self.adaptor_data_mut(app).child_elements.remove(&index);
1846                }
1847                _ => {
1848                    new_children.entry(index).or_insert(Some(child));
1849                }
1850            }
1851        }
1852
1853        // Moving children will temporarily violate the integrity.
1854        self.typed_render_object(app)
1855            .set_debug_child_integrity_enabled(app, false);
1856        for index in new_children.keys().copied().collect::<Vec<_>>() {
1857            self.process_element(
1858                app,
1859                index,
1860                &new_children,
1861                &index_to_layout_offset,
1862                &mut children_updated,
1863            );
1864        }
1865        // An element rebuild only updates existing children. The underflow check is here to make
1866        // sure we look ahead one more child if we were at the end of the child list before the
1867        // update. By doing so, we can update the max scroll offset during the layout phase.
1868        // Otherwise, the layout phase may be skipped, and the scroll view may be stuck at the
1869        // previous max scroll offset.
1870        //
1871        // This logic is not needed if any existing children has been updated, because we will not
1872        // skip the layout phase if that happens.
1873        if !children_updated && self.adaptor_data(app).did_underflow {
1874            let last_key = self
1875                .adaptor_data(app)
1876                .child_elements
1877                .keys()
1878                .next_back()
1879                .copied()
1880                .unwrap_or(-1);
1881            let right_boundary = last_key + 1;
1882            let existing = self
1883                .adaptor_data(app)
1884                .child_elements
1885                .get(&right_boundary)
1886                .copied()
1887                .flatten();
1888            new_children.insert(right_boundary, existing);
1889            self.process_element(
1890                app,
1891                right_boundary,
1892                &new_children,
1893                &index_to_layout_offset,
1894                &mut children_updated,
1895            );
1896        }
1897        self.adaptor_data_mut(app).currently_updating_child_index = None;
1898        self.typed_render_object(app)
1899            .set_debug_child_integrity_enabled(app, true);
1900    }
1901
1902    /// `SliverMultiBoxAdaptorElement.forgetChild`.
1903    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
1904        let slot = child.slot(app).expect("a lazily built child has an index");
1905        let Slot::Index(index) = slot else {
1906            unreachable!("a lazily built child has an index slot");
1907        };
1908        debug_assert!(self.adaptor_data(app).child_elements.contains_key(&index));
1909        self.adaptor_data_mut(app).child_elements.remove(&index);
1910    }
1911
1912    /// `SliverMultiBoxAdaptorElement.visitChildren`.
1913    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
1914        // The copy is so that the underlying map can be modified by the visitor.
1915        let children: Vec<AnyElement> = self
1916            .adaptor_data(app)
1917            .child_elements
1918            .values()
1919            .map(|child| child.expect("no child slot is empty outside a rebuild"))
1920            .collect();
1921        for child in children {
1922            visitor(child);
1923        }
1924    }
1925
1926    /// Dart's `SliverMultiBoxAdaptorElement.debugVisitOnstageChildren`: the children whose
1927    /// layout offset falls in the sliver's painted window, which a kept-alive child's does not.
1928    fn debug_visit_onstage_children(
1929        self: Handle<Self>,
1930        app: &App,
1931        visitor: &mut dyn FnMut(AnyElement),
1932    ) {
1933        let Some(sliver) = self
1934            .as_element()
1935            .render_object(app)
1936            .and_then(|render| render.as_sliver())
1937        else {
1938            return;
1939        };
1940        let constraints = sliver.constraints(app);
1941        let children: Vec<AnyElement> = self
1942            .adaptor_data(app)
1943            .child_elements
1944            .values()
1945            .map(|child| child.expect("no child slot is empty outside a rebuild"))
1946            .collect();
1947        for child in children {
1948            let Some(render) = child.render_object(app) else {
1949                continue;
1950            };
1951            let paint_bounds = render.paint_bounds(app);
1952            let item_extent = match constraints.axis() {
1953                waft_painting::Axis::Horizontal => paint_bounds.width(),
1954                waft_painting::Axis::Vertical => paint_bounds.height(),
1955            };
1956            let onstage = render
1957                .parent_data(app)
1958                .and_then(|data| data.part::<waft_rendering::SliverMultiBoxAdaptorParentData>())
1959                .and_then(|data| data.layout_offset())
1960                .is_some_and(|layout_offset| {
1961                    layout_offset < constraints.scroll_offset + constraints.remaining_paint_extent
1962                        && layout_offset + item_extent > constraints.scroll_offset
1963                });
1964            if onstage {
1965                visitor(child);
1966            }
1967        }
1968    }
1969
1970    /// `SliverMultiBoxAdaptorElement.insertRenderObjectChild`.
1971    fn insert_render_object_child(
1972        self: Handle<Self>,
1973        app: &mut App,
1974        child: AnyRenderObject,
1975        slot: Option<Slot>,
1976    ) {
1977        debug_assert!(
1978            slot == self
1979                .adaptor_data(app)
1980                .currently_updating_child_index
1981                .map(Slot::Index)
1982        );
1983        let render_object = self.typed_render_object(app);
1984        let before = self.adaptor_data(app).current_before_child;
1985        let child = child.as_box().expect("a sliver child is a box");
1986        RenderSliverMultiBoxAdaptor::insert(render_object, app, child, before);
1987        debug_assert!(
1988            slot == child
1989                .as_object()
1990                .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
1991                .index
1992                .map(Slot::Index)
1993        );
1994    }
1995
1996    /// `SliverMultiBoxAdaptorElement.moveRenderObjectChild`.
1997    fn move_render_object_child(
1998        self: Handle<Self>,
1999        app: &mut App,
2000        child: AnyRenderObject,
2001        _old_slot: Option<Slot>,
2002        new_slot: Option<Slot>,
2003    ) {
2004        debug_assert!(
2005            new_slot
2006                == self
2007                    .adaptor_data(app)
2008                    .currently_updating_child_index
2009                    .map(Slot::Index)
2010        );
2011        let render_object = self.typed_render_object(app);
2012        let before = self.adaptor_data(app).current_before_child;
2013        let child = child.as_box().expect("a sliver child is a box");
2014        RenderSliverMultiBoxAdaptor::move_child(render_object, app, child, before);
2015    }
2016
2017    /// `SliverMultiBoxAdaptorElement.removeRenderObjectChild`.
2018    fn remove_render_object_child(
2019        self: Handle<Self>,
2020        app: &mut App,
2021        child: AnyRenderObject,
2022        _slot: Option<Slot>,
2023    ) {
2024        debug_assert!(
2025            self.adaptor_data(app)
2026                .currently_updating_child_index
2027                .is_some()
2028        );
2029        let render_object = self.typed_render_object(app);
2030        let child = child.as_box().expect("a sliver child is a box");
2031        RenderSliverMultiBoxAdaptor::remove(render_object, app, child);
2032    }
2033}
2034
2035/// The element as the `Rc<dyn RenderSliverBoxChildManager>` its render object holds.
2036///
2037/// A local wrapper, because `impl RenderSliverBoxChildManager for Handle<..>` names two foreign
2038/// types.
2039struct ChildManager<E: SliverMultiBoxAdaptorElementBase>(Handle<E>)
2040where
2041    E::Widget: SliverMultiBoxAdaptorWidget,
2042    <E::Widget as RenderObjectWidget>::RenderObject: RenderSliverMultiBoxAdaptor;
2043
2044impl<E: SliverMultiBoxAdaptorElementBase> RenderSliverBoxChildManager for ChildManager<E>
2045where
2046    E::Widget: SliverMultiBoxAdaptorWidget,
2047    <E::Widget as RenderObjectWidget>::RenderObject: RenderSliverMultiBoxAdaptor,
2048{
2049    fn create_child(&self, app: &mut App, index: i32, after: Option<AnyRenderBox>) {
2050        self.0.create_child(app, index, after);
2051    }
2052
2053    fn remove_child(&self, app: &mut App, child: AnyRenderBox) {
2054        self.0.remove_child(app, child);
2055    }
2056
2057    fn estimate_max_scroll_offset(
2058        &self,
2059        app: &App,
2060        constraints: SliverConstraints,
2061        first_index: Option<i32>,
2062        last_index: Option<i32>,
2063        leading_scroll_offset: Option<f64>,
2064        trailing_scroll_offset: Option<f64>,
2065    ) -> f64 {
2066        self.0.estimate_max_scroll_offset(
2067            app,
2068            constraints,
2069            first_index,
2070            last_index,
2071            leading_scroll_offset,
2072            trailing_scroll_offset,
2073        )
2074    }
2075
2076    fn child_count(&self, app: &mut App) -> i32 {
2077        self.0.child_count(app)
2078    }
2079
2080    fn estimated_child_count(&self, app: &App) -> Option<i32> {
2081        self.0.estimated_child_count(app)
2082    }
2083
2084    fn did_adopt_child(&self, app: &mut App, child: AnyRenderBox) {
2085        self.0.did_adopt_child(app, child);
2086    }
2087
2088    fn set_did_underflow(&self, app: &mut App, value: bool) {
2089        self.0.set_did_underflow(app, value);
2090    }
2091
2092    fn did_start_layout(&self, app: &mut App) {
2093        self.0.did_start_layout(app);
2094    }
2095
2096    fn did_finish_layout(&self, app: &mut App) {
2097        self.0.did_finish_layout(app);
2098    }
2099
2100    fn debug_assert_child_list_locked(&self, app: &App) -> bool {
2101        self.0.debug_assert_child_list_locked(app)
2102    }
2103}
2104
2105/// An element that lazily builds children for a [`SliverMultiBoxAdaptorWidget`]: the leaf that
2106/// has no bodies of its own beyond [`SliverMultiBoxAdaptorElementBase`]'s.
2107pub struct SliverMultiBoxAdaptorElement<W: SliverMultiBoxAdaptorWidget>
2108where
2109    W::RenderObject: RenderSliverMultiBoxAdaptor,
2110{
2111    element: ElementData,
2112    render_object_element: RenderObjectElementData,
2113    adaptor: SliverMultiBoxAdaptorElementData,
2114    marker: std::marker::PhantomData<fn() -> W>,
2115}
2116
2117impl<W: SliverMultiBoxAdaptorWidget> SliverMultiBoxAdaptorElement<W>
2118where
2119    W::RenderObject: RenderSliverMultiBoxAdaptor,
2120{
2121    /// Creates an element that lazily builds children for the given widget.
2122    ///
2123    /// If `replace_moved_children` is true, a new child is proactively inflated for the index
2124    /// that was previously occupied by a child that moved to a new index. The layout offset of
2125    /// the moved child is copied over to the new child. Render objects that depend on the layout
2126    /// offset of existing children during `RenderObject::perform_layout` should set this to true
2127    /// (example: `RenderSliverList`). For render objects that figure out the layout offset of
2128    /// their children without looking at the layout offset of existing children this should be
2129    /// set to false (example: `RenderSliverFixedExtentList`) to avoid inflating unnecessary
2130    /// children.
2131    pub fn new(
2132        app: &mut App,
2133        widget: WidgetRef,
2134        replace_moved_children: bool,
2135    ) -> Handle<SliverMultiBoxAdaptorElement<W>> {
2136        debug_assert!(downcast_widget::<W>(&*widget).is_some());
2137        app.create(SliverMultiBoxAdaptorElement::<W> {
2138            element: ElementData::new(widget),
2139            render_object_element: RenderObjectElementData::default(),
2140            adaptor: SliverMultiBoxAdaptorElementData::new(replace_moved_children),
2141            marker: std::marker::PhantomData,
2142        })
2143        .into_tree_node(app)
2144    }
2145
2146    /// The render object this element manages the children of.
2147    pub fn render_object(self: Handle<Self>, app: &App) -> RenderHandle<W::RenderObject> {
2148        self.typed_render_object(app)
2149    }
2150}
2151
2152impl<W: SliverMultiBoxAdaptorWidget> SliverMultiBoxAdaptorElementBase
2153    for SliverMultiBoxAdaptorElement<W>
2154where
2155    W::RenderObject: RenderSliverMultiBoxAdaptor,
2156{
2157    fn adaptor_data(self: Handle<Self>, app: &App) -> &SliverMultiBoxAdaptorElementData {
2158        &app.get(self).adaptor
2159    }
2160
2161    fn adaptor_data_mut(
2162        self: Handle<Self>,
2163        app: &mut App,
2164    ) -> &mut SliverMultiBoxAdaptorElementData {
2165        &mut app.get_mut(self).adaptor
2166    }
2167}
2168
2169impl<W: SliverMultiBoxAdaptorWidget> RenderObjectElementWidget for SliverMultiBoxAdaptorElement<W>
2170where
2171    W::RenderObject: RenderSliverMultiBoxAdaptor,
2172{
2173    type Widget = W;
2174
2175    fn widget_of(widget: &WidgetRef) -> &W {
2176        downcast_widget::<W>(&**widget)
2177            .expect("a SliverMultiBoxAdaptorElement holds its SliverMultiBoxAdaptorWidget")
2178    }
2179}
2180
2181impl<W: SliverMultiBoxAdaptorWidget> RenderObjectElement for SliverMultiBoxAdaptorElement<W>
2182where
2183    W::RenderObject: RenderSliverMultiBoxAdaptor,
2184{
2185    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
2186        &app.get(self).render_object_element
2187    }
2188
2189    fn render_object_element_data_mut(
2190        self: Handle<Self>,
2191        app: &mut App,
2192    ) -> &mut RenderObjectElementData {
2193        &mut app.get_mut(self).render_object_element
2194    }
2195}
2196
2197impl<W: SliverMultiBoxAdaptorWidget> Element for SliverMultiBoxAdaptorElement<W>
2198where
2199    W::RenderObject: RenderSliverMultiBoxAdaptor,
2200{
2201    crate::element_accessors!();
2202
2203    const IS_RENDER_OBJECT_ELEMENT: bool = true;
2204
2205    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
2206        self.render_object_element_data(app).render_object()
2207    }
2208
2209    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
2210        None
2211    }
2212
2213    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
2214        self.render_object_element_data(app).debug_doing_build()
2215    }
2216
2217    fn mount(
2218        self: Handle<Self>,
2219        app: &mut App,
2220        parent: Option<AnyElement>,
2221        new_slot: Option<Slot>,
2222    ) {
2223        RenderObjectElement::mount(self, app, parent, new_slot);
2224    }
2225
2226    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
2227        SliverMultiBoxAdaptorElementBase::update(self, app, new_widget);
2228    }
2229
2230    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
2231        SliverMultiBoxAdaptorElementBase::perform_rebuild(self, app);
2232    }
2233
2234    fn deactivate(self: Handle<Self>, app: &mut App) {
2235        RenderObjectElement::deactivate(self, app);
2236    }
2237
2238    fn unmount(self: Handle<Self>, app: &mut App) {
2239        RenderObjectElement::unmount(self, app);
2240    }
2241
2242    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
2243        RenderObjectElement::update_parent_data(self, app, parent_data_element);
2244    }
2245
2246    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
2247        RenderObjectElement::update_slot(self, app, new_slot);
2248    }
2249
2250    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
2251        RenderObjectElement::attach_render_object(self, app, new_slot);
2252    }
2253
2254    fn detach_render_object(self: Handle<Self>, app: &mut App) {
2255        RenderObjectElement::detach_render_object(self, app);
2256    }
2257
2258    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
2259        SliverMultiBoxAdaptorElementBase::forget_child(self, app, child);
2260    }
2261
2262    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
2263        SliverMultiBoxAdaptorElementBase::visit_children(self, app, visitor);
2264    }
2265
2266    fn debug_visit_onstage_children(
2267        self: Handle<Self>,
2268        app: &App,
2269        visitor: &mut dyn FnMut(AnyElement),
2270    ) {
2271        SliverMultiBoxAdaptorElementBase::debug_visit_onstage_children(self, app, visitor);
2272    }
2273
2274    fn insert_render_object_child(
2275        self: Handle<Self>,
2276        app: &mut App,
2277        child: AnyRenderObject,
2278        slot: Option<Slot>,
2279    ) {
2280        SliverMultiBoxAdaptorElementBase::insert_render_object_child(self, app, child, slot);
2281    }
2282
2283    fn move_render_object_child(
2284        self: Handle<Self>,
2285        app: &mut App,
2286        child: AnyRenderObject,
2287        old_slot: Option<Slot>,
2288        new_slot: Option<Slot>,
2289    ) {
2290        SliverMultiBoxAdaptorElementBase::move_render_object_child(
2291            self, app, child, old_slot, new_slot,
2292        );
2293    }
2294
2295    fn remove_render_object_child(
2296        self: Handle<Self>,
2297        app: &mut App,
2298        child: AnyRenderObject,
2299        slot: Option<Slot>,
2300    ) {
2301        SliverMultiBoxAdaptorElementBase::remove_render_object_child(self, app, child, slot);
2302    }
2303}
2304
2305// ---------------------------------------------------------------------------------------------
2306// KeepAlive
2307
2308/// Mark a child as needing to stay alive even when it's in a lazy list that would otherwise
2309/// remove it.
2310///
2311/// This widget is for use in a `SliverWithKeepAliveWidget` (a [`SliverMultiBoxAdaptorWidget`],
2312/// for instance).
2313///
2314/// See also:
2315///
2316///  * `AutomaticKeepAlive`, which allows subtrees to request to be kept alive in lazy lists.
2317///  * `AutomaticKeepAliveClientMixin`, which is a mixin with convenience methods for clients of
2318///    `AutomaticKeepAlive`. Used with `State` subclasses.
2319#[derive(Debug)]
2320pub struct KeepAlive {
2321    pub key: Option<KeyRef>,
2322    /// Whether to keep the child alive.
2323    ///
2324    /// If this is false, it is as if this widget was omitted.
2325    pub keep_alive: bool,
2326    /// The widget below this widget in the tree.
2327    pub child: WidgetRef,
2328}
2329
2330impl KeepAlive {
2331    /// Marks a child as needing to remain alive.
2332    #[cfg_attr(debug_assertions, track_caller)]
2333    pub fn new<K>(keep_alive: bool, child: impl IntoWidget<K>) -> KeepAlive {
2334        KeepAlive {
2335            key: None,
2336            keep_alive,
2337            child: child.into_widget(),
2338        }
2339    }
2340
2341    /// Dart `KeepAlive(key:)`.
2342    pub fn key(mut self, key: KeyRef) -> KeepAlive {
2343        self.key = Some(key);
2344        self
2345    }
2346}
2347
2348impl ParentDataWidget for KeepAlive {
2349    type ParentData = SliverMultiBoxAdaptorParentData;
2350
2351    fn key(&self) -> Option<&KeyRef> {
2352        self.key.as_ref()
2353    }
2354
2355    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2356        properties.add(DiagnosticsProperty::new("keepAlive", self.keep_alive));
2357    }
2358
2359    fn child(&self) -> &WidgetRef {
2360        &self.child
2361    }
2362
2363    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
2364        let parent_data = render_object
2365            .parent_data_mut(app)
2366            .and_then(|parent_data| parent_data.part_mut::<KeepAliveParentData>())
2367            .expect("parent data does not embed a KeepAliveParentData");
2368        if parent_data.keep_alive != self.keep_alive {
2369            // No need to redo layout if it became true.
2370            parent_data.keep_alive = self.keep_alive;
2371            if !self.keep_alive
2372                && let Some(parent) = render_object.parent(app)
2373            {
2374                parent.mark_needs_layout(app);
2375            }
2376        }
2377    }
2378
2379    // We only return true if `keep_alive` is true, because turning _off_ keep alive requires a
2380    // layout to do the garbage collection (but turning it on requires nothing, since by
2381    // definition the widget is already alive and won't go away _unless_ we do a layout).
2382    fn debug_can_apply_out_of_turn(&self) -> bool {
2383        self.keep_alive
2384    }
2385}
2386
2387#[cfg(test)]
2388mod tests {
2389    use waft_embedder::TextDirection;
2390    use waft_foundation::AppCell;
2391    use waft_foundation::Ref;
2392    use waft_foundation::ValueKey;
2393    use waft_rendering::{
2394        ContainerRenderObjectMixin, FixedViewportOffset, RenderSliverList, ScrollCacheExtent,
2395        ViewportOffset,
2396    };
2397
2398    use super::*;
2399    use crate::test_harness::Harness;
2400    use crate::widgets::basic::{Directionality, SizedBox};
2401    use crate::widgets::viewport::Viewport;
2402
2403    fn key(value: u32) -> KeyRef {
2404        KeyRef::from(ValueKey::new(value))
2405    }
2406
2407    fn item(value: u32) -> WidgetRef {
2408        SizedBox::new().key(key(value)).height(40.0).into_widget()
2409    }
2410
2411    fn viewport_over(sliver: WidgetRef, offset: &Ref<FixedViewportOffset>) -> WidgetRef {
2412        Directionality::new(
2413            TextDirection::Ltr,
2414            Viewport::new(offset.erase())
2415                .scroll_cache_extent(ScrollCacheExtent::Pixels(0.0))
2416                .slivers(vec![sliver]),
2417        )
2418        .into_widget()
2419    }
2420
2421    fn first_sliver<T: waft_rendering::RenderObject>(
2422        harness: &Harness,
2423        app: &App,
2424    ) -> RenderHandle<T> {
2425        harness
2426            .render_root(app)
2427            .child(app)
2428            .expect("a child")
2429            .as_object()
2430            .downcast::<waft_rendering::RenderViewport>(app)
2431            .expect("a RenderViewport")
2432            .first_child(app)
2433            .expect("a sliver")
2434            .as_object()
2435            .downcast::<T>(app)
2436            .expect("the sliver under test")
2437    }
2438
2439    fn children_of<T>(list: RenderHandle<T>, app: &App) -> Vec<AnyRenderBox>
2440    where
2441        T: ContainerRenderObjectMixin<ChildType = AnyRenderBox>,
2442    {
2443        let mut children = Vec::new();
2444        let mut child = list.first_child(app);
2445        while let Some(current) = child {
2446            children.push(current);
2447            child = list.child_after(app, current);
2448        }
2449        children
2450    }
2451
2452    /// A keyed reorder moves the existing children to their new indices instead of rebuilding
2453    /// them: `SliverChildListDelegate.findIndexByKey` finds each child's new index.
2454    #[test]
2455    fn a_keyed_reorder_keeps_the_child_render_objects() {
2456        let cell = AppCell::new();
2457        let mut app = cell.borrow_mut();
2458        let offset = FixedViewportOffset::zero(&mut app);
2459        let ordered = |values: [u32; 3]| {
2460            SliverList::list(values.map(item).to_vec())
2461                .add_repaint_boundaries(false)
2462                .into_widget()
2463        };
2464        let harness = Harness::mount(&mut app, viewport_over(ordered([0, 1, 2]), &offset));
2465        harness.pump(&mut app);
2466
2467        let list: RenderHandle<RenderSliverList> = first_sliver(&harness, &app);
2468        let before = children_of(list, &app);
2469        assert_eq!(before.len(), 3);
2470
2471        harness.set_child(&mut app, viewport_over(ordered([2, 0, 1]), &offset));
2472        harness.pump(&mut app);
2473
2474        let after = children_of(list, &app);
2475        assert_eq!(after, vec![before[2], before[0], before[1]]);
2476    }
2477
2478    /// A `KeepAlive` child that scrolls out of view moves into the sliver's keep-alive bucket
2479    /// instead of being destroyed.
2480    #[test]
2481    fn keep_alive_holds_a_scrolled_off_child() {
2482        let cell = AppCell::new();
2483        let mut app = cell.borrow_mut();
2484        let offset = FixedViewportOffset::zero(&mut app);
2485        let mut children: Vec<WidgetRef> = vec![
2486            KeepAlive::new(true, SizedBox::new().key(key(0)).height(40.0))
2487                .key(key(100))
2488                .into_widget(),
2489        ];
2490        children.extend((1..8).map(item));
2491        let sliver = SliverList::list(children)
2492            .add_automatic_keep_alives(false)
2493            .add_repaint_boundaries(false)
2494            .add_semantic_indexes(false)
2495            .into_widget();
2496        let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
2497        harness.pump(&mut app);
2498
2499        let list: RenderHandle<RenderSliverList> = first_sliver(&harness, &app);
2500        let kept = children_of(list, &app)[0];
2501        assert!(list.keep_alive_children(&app).is_empty());
2502
2503        offset.correct_by(&mut app, 200.0);
2504        list.parent(&app)
2505            .expect("the viewport")
2506            .mark_needs_layout(&mut app);
2507        harness.pump(&mut app);
2508
2509        // The first child is out of view, but it was kept alive rather than destroyed.
2510        assert_eq!(list.keep_alive_children(&app), vec![kept]);
2511        assert!(!children_of(list, &app).contains(&kept));
2512    }
2513
2514    /// A `SliverFixedExtentList` forces its item extent on every child, whatever the child asked
2515    /// for.
2516    #[test]
2517    fn a_fixed_extent_list_forces_the_item_extent() {
2518        let cell = AppCell::new();
2519        let mut app = cell.borrow_mut();
2520        let offset = FixedViewportOffset::zero(&mut app);
2521        let sliver = SliverFixedExtentList::builder(
2522            |_app, _context, _index| Some(SizedBox::new().height(10.0).into_widget()),
2523            40.0,
2524        )
2525        .item_count(8)
2526        .into_widget();
2527        let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
2528        harness.pump(&mut app);
2529
2530        let list: RenderHandle<RenderSliverFixedExtentList> = first_sliver(&harness, &app);
2531        let children = children_of(list, &app);
2532        assert_eq!(children.len(), 5);
2533        for child in children {
2534            assert_eq!(child.size(&app).height(), 40.0);
2535        }
2536        assert_eq!(list.geometry(&app).scroll_extent, 320.0);
2537    }
2538
2539    /// A `SliverGrid` sizes every tile by its grid delegate and places them in rows, building
2540    /// only the rows in view; without an item count it estimates its extent from the rows built.
2541    #[test]
2542    fn a_sliver_grid_builds_only_the_rows_in_view() {
2543        let cell = AppCell::new();
2544        let mut app = cell.borrow_mut();
2545        let offset = FixedViewportOffset::zero(&mut app);
2546        let sliver = SliverGrid::builder(
2547            Rc::new(SliverGridDelegateWithFixedCrossAxisCount::new(3).main_axis_extent(50.0)),
2548            |_app, _context, _index| Some(SizedBox::new().into_widget()),
2549        )
2550        .item_count(30)
2551        .add_repaint_boundaries(false)
2552        .into_widget();
2553        let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
2554        harness.pump(&mut app);
2555
2556        let grid: RenderHandle<RenderSliverGrid> = first_sliver(&harness, &app);
2557        let tiles = children_of(grid, &app);
2558        // The harness's view is 300 by 200: four rows of three 100 by 50 tiles.
2559        assert_eq!(tiles.len(), 12);
2560        let width = harness.render_root(&app).size(&app).width() / 3.0;
2561        assert_eq!(tiles[4].size(&app), waft_embedder::Size::new(width, 50.0));
2562        let positions: Vec<(f64, f64)> = tiles[3..6]
2563            .iter()
2564            .map(|tile| {
2565                (
2566                    RenderSliver::child_main_axis_position(grid, &app, tile.as_object()),
2567                    RenderSliver::child_cross_axis_position(grid, &app, tile.as_object()),
2568                )
2569            })
2570            .collect();
2571        assert_eq!(positions, [(50.0, 0.0), (50.0, width), (50.0, 2.0 * width)]);
2572        assert_eq!(grid.geometry(&app).scroll_extent, 500.0, "ten rows of 50");
2573    }
2574
2575    /// A `KeepAlive` tile of a `SliverGrid` is kept, as a list's child is: the grid's parent data
2576    /// embeds the list's.
2577    #[test]
2578    fn keep_alive_holds_a_scrolled_off_grid_tile() {
2579        let cell = AppCell::new();
2580        let mut app = cell.borrow_mut();
2581        let offset = FixedViewportOffset::zero(&mut app);
2582        let mut children: Vec<WidgetRef> = vec![
2583            KeepAlive::new(true, SizedBox::new().key(key(0)))
2584                .key(key(100))
2585                .into_widget(),
2586        ];
2587        children.extend((1..40).map(item));
2588        let tiles = SliverGridDelegateWithFixedCrossAxisCount::new(2).child_aspect_ratio(3.0);
2589        let sliver = SliverGrid::list(Rc::new(tiles), children)
2590            .add_automatic_keep_alives(false)
2591            .add_repaint_boundaries(false)
2592            .add_semantic_indexes(false)
2593            .into_widget();
2594        let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
2595        harness.pump(&mut app);
2596
2597        let grid: RenderHandle<RenderSliverGrid> = first_sliver(&harness, &app);
2598        let kept = children_of(grid, &app)[0];
2599
2600        offset.correct_by(&mut app, 300.0);
2601        grid.parent(&app)
2602            .expect("the viewport")
2603            .mark_needs_layout(&mut app);
2604        harness.pump(&mut app);
2605
2606        assert_eq!(grid.keep_alive_children(&app), vec![kept]);
2607        assert!(!children_of(grid, &app).contains(&kept));
2608    }
2609}