Skip to main content

waft_widgets/widgets/
scroll_delegate.rs

1//! Flutter counterpart: `widgets/scroll_delegate.dart`.
2//!
3//! The delegates that supply children to a lazy sliver. `NullableIndexedWidgetBuilder` is
4//! Flutter's `framework.dart` typedef; the framework module does not export one, so it is
5//! defined here next to its callers.
6//!
7//! `TwoDimensionalChildDelegate` and its subclasses wait with `two_dimensional_viewport.dart`;
8//! see `PORTING.md`.
9
10use std::any::{Any, TypeId};
11use std::cell::RefCell;
12use std::collections::{HashMap, HashSet};
13use std::fmt::{self, Debug};
14use std::hash::Hasher;
15use std::rc::Rc;
16
17use waft_foundation::{App, Handle, Key, Listener, ValueKey};
18
19use waft_rendering::{AnySelectable, SelectionRegistrar, SelectionRegistrarRef};
20
21use crate::framework::{
22    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
23};
24use crate::widgets::automatic_keep_alive::{
25    AutomaticKeepAlive, AutomaticKeepAliveClientMixin, AutomaticKeepAliveClientMixinData,
26};
27use crate::widgets::basic::{IndexedSemantics, KeyedSubtree, RepaintBoundary};
28use crate::widgets::selection_container::{SelectionContainer, SelectionRegistrarScope};
29
30/// Signature for a function that creates a widget for a given index, e.g., in a list, but may
31/// return `None`.
32///
33/// Used by [`SliverChildBuilderDelegate::builder`] and `ListView.builder`. If a `builder`
34/// returns `None`, the sliver will stop building children.
35///
36/// Flutter's `Widget? Function(BuildContext context, int index)` from `framework.dart`;
37/// receives [`App`] because a Rust callback cannot capture what it mutates.
38pub type NullableIndexedWidgetBuilder =
39    Rc<dyn Fn(&mut App, BuildContext, i32) -> Option<WidgetRef>>;
40
41/// A callback which produces a semantic index given a widget and the local index.
42///
43/// Return `None` to prevent a widget from receiving an index.
44///
45/// A semantic index is used to tag child semantic nodes for accessibility announcements in
46/// scroll view.
47///
48/// See also:
49///
50///  * `CustomScrollView`, for an explanation of scroll semantics.
51///  * [`SliverChildBuilderDelegate`], for an explanation of how this is used to generate
52///    indexes.
53pub type SemanticIndexCallback = Rc<dyn Fn(&WidgetRef, i32) -> Option<i32>>;
54
55/// Flutter's `_kDefaultSemanticIndexCallback`.
56fn default_semantic_index_callback() -> SemanticIndexCallback {
57    Rc::new(|_widget, local_index| Some(local_index))
58}
59
60/// A delegate that supplies children for slivers.
61///
62/// Many slivers lazily construct their box children to avoid creating more children than are
63/// visible through the `Viewport`. Rather than receiving their children as an explicit
64/// [`Vec`], they receive their children using a [`SliverChildDelegate`].
65///
66/// It's uncommon to implement [`SliverChildDelegate`]. Instead, consider using one of the
67/// existing implementors that provide adaptors to builder callbacks or explicit child lists.
68///
69/// ## Child elements' lifecycle
70///
71/// ### Creation
72///
73/// While laying out the list, visible children's elements, states and render objects will be
74/// created lazily based on existing widgets (such as in the case of
75/// [`SliverChildListDelegate`]) or lazily provided ones (such as in the case of
76/// [`SliverChildBuilderDelegate`]).
77///
78/// ### Destruction
79///
80/// When a child is scrolled out of view, the associated element subtree, states and render
81/// objects are destroyed. A new child at the same position in the sliver will be lazily
82/// recreated along with new elements, states and render objects when it is scrolled back.
83///
84/// ### Destruction mitigation
85///
86/// In order to preserve state as child elements are scrolled in and out of view, the following
87/// options are possible:
88///
89///  * Moving the ownership of non-trivial UI-state-driving business logic out of the sliver
90///    child subtree. For instance, if a list contains posts with their number of upvotes coming
91///    from a cached network response, store the list of posts and upvote number in a data model
92///    outside the list. Let the sliver child UI subtree be easily recreate-able from the
93///    source-of-truth model object. Use `StatefulWidget`s in the child widget subtree to store
94///    instantaneous UI state only.
95///
96///  * Letting `KeepAlive` be the root widget of the sliver child widget subtree that needs to
97///    be preserved. The `KeepAlive` widget marks the child subtree's top render object child
98///    for keepalive. When the associated top render object is scrolled out of view, the sliver
99///    keeps the child's render object (and by extension, its associated elements and states) in
100///    a cache list instead of destroying them. When scrolled back into view, the render object
101///    is repainted as-is (if it wasn't marked dirty in the interim).
102///
103/// ## Using more than one delegate in a `Viewport`
104///
105/// If multiple delegates are used in a single scroll view, the first child of each delegate
106/// will always be laid out, even if it extends beyond the currently viewable area. This is
107/// because at least one child is required in order to
108/// [`estimate_max_scroll_offset`](Self::estimate_max_scroll_offset) for the whole scroll view,
109/// as it uses the currently built children to estimate the remaining children's extent.
110///
111/// See also:
112///
113///  * [`SliverChildBuilderDelegate`], which is a delegate that uses a builder callback to
114///    construct the children.
115///  * [`SliverChildListDelegate`], which is a delegate that has an explicit list of children.
116pub trait SliverChildDelegate: Debug + 'static {
117    /// Returns the child with the given index.
118    ///
119    /// Should return `None` if asked to build a widget with a greater index than exists. If
120    /// this returns `None`, [`estimated_child_count`](Self::estimated_child_count) must
121    /// subsequently return a precise non-`None` value (which is then used to implement
122    /// `RenderSliverBoxChildManager::child_count`).
123    ///
124    /// Implementors typically wrap their children in `AutomaticKeepAlive`, `IndexedSemantics`,
125    /// and [`RepaintBoundary`] widgets.
126    ///
127    /// The values returned by this method are cached. To indicate that the widgets have
128    /// changed, a new delegate must be provided, and the new delegate's
129    /// [`should_rebuild`](Self::should_rebuild) method must return true.
130    fn build(&self, app: &mut App, context: BuildContext, index: i32) -> Option<WidgetRef>;
131
132    /// Returns an estimate of the number of children this delegate will build.
133    ///
134    /// Used to estimate the maximum scroll offset if
135    /// [`estimate_max_scroll_offset`](Self::estimate_max_scroll_offset) returns `None`.
136    ///
137    /// Return `None` if there are an unbounded number of children or if it would be too
138    /// difficult to estimate the number of children.
139    ///
140    /// This must return a precise number once [`build`](Self::build) has returned `None`, as it
141    /// is used to implement `RenderSliverBoxChildManager::child_count`.
142    fn estimated_child_count(&self) -> Option<i32> {
143        None
144    }
145
146    /// Returns an estimate of the max scroll extent for all the children.
147    ///
148    /// Implementors should override this function if they have additional information about
149    /// their max scroll extent.
150    ///
151    /// The default implementation returns `None`, which causes the caller to extrapolate the
152    /// max scroll offset from the given parameters.
153    fn estimate_max_scroll_offset(
154        &self,
155        first_index: i32,
156        last_index: i32,
157        leading_scroll_offset: f64,
158        trailing_scroll_offset: f64,
159    ) -> Option<f64> {
160        let _ = (
161            first_index,
162            last_index,
163            leading_scroll_offset,
164            trailing_scroll_offset,
165        );
166        None
167    }
168
169    /// Called at the end of layout to indicate that layout is now complete.
170    ///
171    /// The `first_index` argument is the index of the first child that was included in the
172    /// current layout. The `last_index` argument is the index of the last child that was
173    /// included in the current layout.
174    ///
175    /// Useful for implementors that wish to track which children are included in the underlying
176    /// render tree.
177    fn did_finish_layout(&self, first_index: i32, last_index: i32) {
178        let _ = (first_index, last_index);
179    }
180
181    /// Called whenever a new instance of the child delegate class is provided to the sliver.
182    ///
183    /// If the new instance represents different information than the old instance, then the
184    /// method should return true, otherwise it should return false.
185    ///
186    /// If the method returns false, then the [`build`](Self::build) call might be optimized
187    /// away.
188    ///
189    /// Dart's `covariant SliverChildDelegate oldDelegate`: the caller has already compared
190    /// [`delegate_type`](Self::delegate_type), so the argument downcasts through
191    /// [`as_any`](Self::as_any).
192    fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool;
193
194    /// Find index of child element with associated key.
195    ///
196    /// This will be called during `perform_rebuild` in `SliverMultiBoxAdaptorElement` to check
197    /// if a child has moved to a different position. It should return the index of the child
198    /// element with associated key, `None` if not found.
199    ///
200    /// If not provided, a child widget may not map to its existing `RenderObject` when the
201    /// order of children returned from the children builder changes. This may result in
202    /// state-loss.
203    fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
204        let _ = key;
205        None
206    }
207
208    /// The concrete delegate, for Dart's `oldDelegate as Foo`.
209    fn as_any(&self) -> &dyn Any;
210
211    /// The concrete delegate's type, Dart's `runtimeType`.
212    fn delegate_type(&self) -> TypeId {
213        self.as_any().type_id()
214    }
215
216    /// Add additional information to the given description for use by `toString`.
217    fn debug_fill_description(&self, description: &mut Vec<String>) {
218        if let Some(children) = self.estimated_child_count() {
219            description.push(format!("estimated child count: {children}"));
220        }
221    }
222}
223
224/// A shared [`SliverChildDelegate`] (Dart's `SliverChildDelegate` reference).
225pub type SliverChildDelegateRef = Rc<dyn SliverChildDelegate>;
226
227/// Dart's `identical(a, b)` on two delegates: `SliverChildDelegate` does not override `==`.
228pub fn same_delegate(a: &SliverChildDelegateRef, b: &SliverChildDelegateRef) -> bool {
229    Rc::ptr_eq(a, b)
230}
231
232/// Flutter's `_SaltedValueKey`: a `ValueKey<Key>` that cannot collide with a key the child
233/// itself carries.
234#[derive(Clone, Debug)]
235struct SaltedValueKey(ValueKey<KeyRef>);
236
237impl SaltedValueKey {
238    fn new(value: KeyRef) -> SaltedValueKey {
239        SaltedValueKey(ValueKey::new(value))
240    }
241}
242
243impl Key for SaltedValueKey {
244    fn eq_key(&self, other: &dyn Key) -> bool {
245        (other as &dyn Any)
246            .downcast_ref::<SaltedValueKey>()
247            .is_some_and(|other| other.0.value == self.0.value)
248    }
249
250    fn hash_key(&self, mut state: &mut dyn Hasher) {
251        use std::hash::Hash;
252        TypeId::of::<SaltedValueKey>().hash(&mut state);
253        self.0.value.hash(&mut state);
254    }
255}
256
257/// Dart's `key is _SaltedValueKey ? key.value : key`.
258fn unsalt(key: &KeyRef) -> KeyRef {
259    match (key.key() as &dyn Any).downcast_ref::<SaltedValueKey>() {
260        Some(salted) => salted.0.value.clone(),
261        None => key.clone(),
262    }
263}
264
265/// Keeps alive the children whose selectables have a selection.
266///
267/// `_SelectionKeepAlive` in Dart: a registrar for one sliver child that stays between the parent
268/// registrar and the selectables below it, so a selection off screen keeps its child alive.
269struct SelectionKeepAlive {
270    key: Option<KeyRef>,
271    child: WidgetRef,
272}
273
274impl SelectionKeepAlive {
275    #[cfg_attr(debug_assertions, track_caller)]
276    fn new<K>(child: impl IntoWidget<K>) -> SelectionKeepAlive {
277        SelectionKeepAlive {
278            key: None,
279            child: child.into_widget(),
280        }
281    }
282}
283
284impl Debug for SelectionKeepAlive {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        f.debug_struct("SelectionKeepAlive").finish_non_exhaustive()
287    }
288}
289
290impl StatefulWidget for SelectionKeepAlive {
291    type State = SelectionKeepAliveState;
292
293    fn key(&self) -> Option<&KeyRef> {
294        self.key.as_ref()
295    }
296
297    fn create_state(&self) -> SelectionKeepAliveState {
298        SelectionKeepAliveState {
299            state: StateData::new(),
300            keep_alive: AutomaticKeepAliveClientMixinData::new(),
301            selectables_with_selections: None,
302            selectable_attachments: None,
303            registrar: None,
304            want_keep_alive: false,
305        }
306    }
307}
308
309struct SelectionKeepAliveState {
310    state: StateData<SelectionKeepAlive>,
311    keep_alive: AutomaticKeepAliveClientMixinData,
312    selectables_with_selections: Option<HashSet<AnySelectable>>,
313    selectable_attachments: Option<HashMap<AnySelectable, Listener>>,
314    registrar: Option<SelectionRegistrarRef>,
315    want_keep_alive: bool,
316}
317
318impl SelectionKeepAliveState {
319    fn registrar_handle(
320        self: Handle<Self>,
321        app: &App,
322    ) -> Option<waft_rendering::AnySelectionRegistrar> {
323        app.get(self)
324            .registrar
325            .as_ref()
326            .map(|registrar| registrar.handle())
327    }
328
329    fn listens_to(self: Handle<Self>, selectable: AnySelectable) -> Listener {
330        Listener::new(move |app| {
331            let add = selectable.value(app).has_selection();
332            SelectionKeepAliveState::update_selectables_with_selections(self, app, selectable, add);
333        })
334    }
335
336    fn update_selectables_with_selections(
337        self: Handle<Self>,
338        app: &mut App,
339        selectable: AnySelectable,
340        add: bool,
341    ) {
342        let has_selection = selectable.value(app).has_selection();
343        {
344            let this = app.get_mut(self);
345            if add {
346                debug_assert!(has_selection);
347                this.selectables_with_selections
348                    .get_or_insert_with(HashSet::new)
349                    .insert(selectable);
350            } else if let Some(selectables) = &mut this.selectables_with_selections {
351                selectables.remove(&selectable);
352            }
353        }
354        let want = app
355            .get(self)
356            .selectables_with_selections
357            .as_ref()
358            .is_some_and(|selectables| !selectables.is_empty());
359        self.set_want_keep_alive(app, want);
360    }
361
362    fn set_want_keep_alive(self: Handle<Self>, app: &mut App, value: bool) {
363        if app.get(self).want_keep_alive != value {
364            app.get_mut(self).want_keep_alive = value;
365            self.update_keep_alive(app);
366        }
367    }
368}
369
370impl State for SelectionKeepAliveState {
371    type Widget = SelectionKeepAlive;
372    crate::state_accessors!();
373
374    fn init_state(self: Handle<Self>, app: &mut App) {
375        AutomaticKeepAliveClientMixin::init_state(self, app);
376    }
377
378    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
379        let new_registrar = SelectionContainer::maybe_of(app, self.context(app));
380        let current = self.registrar_handle(app);
381        let new_handle = new_registrar.as_ref().map(|registrar| registrar.handle());
382        if current == new_handle {
383            return;
384        }
385        let attachments: Vec<AnySelectable> = app
386            .get(self)
387            .selectable_attachments
388            .as_ref()
389            .map(|attachments| attachments.keys().copied().collect())
390            .unwrap_or_default();
391        if let Some(registrar) = current {
392            for selectable in &attachments {
393                registrar.remove(app, *selectable);
394            }
395        }
396        app.get_mut(self).registrar = new_registrar;
397        if let Some(registrar) = self.registrar_handle(app) {
398            for selectable in &attachments {
399                registrar.add(app, *selectable);
400            }
401        }
402    }
403
404    fn deactivate(self: Handle<Self>, app: &mut App) {
405        AutomaticKeepAliveClientMixin::deactivate(self, app);
406    }
407
408    fn dispose(self: Handle<Self>, app: &mut App) {
409        let attachments = app.get_mut(self).selectable_attachments.take();
410        if let Some(attachments) = attachments {
411            let registrar = self.registrar_handle(app);
412            for (selectable, listener) in attachments {
413                if let Some(registrar) = registrar {
414                    registrar.remove(app, selectable);
415                }
416                selectable.remove_listener(app, &listener);
417            }
418        }
419        app.get_mut(self).selectables_with_selections = None;
420    }
421
422    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
423        let _ = AutomaticKeepAliveClientMixin::build(self, app);
424        if self.registrar_handle(app).is_none() {
425            let child = self.widget(app).child.clone();
426            return child;
427        }
428        let child = self.widget(app).child.clone();
429        SelectionRegistrarScope::new(self.as_selection_registrar().keep(app), child).into_widget()
430    }
431}
432
433impl AutomaticKeepAliveClientMixin for SelectionKeepAliveState {
434    fn automatic_keep_alive_client_data(
435        self: Handle<Self>,
436        app: &App,
437    ) -> &AutomaticKeepAliveClientMixinData {
438        &app.get(self).keep_alive
439    }
440
441    fn automatic_keep_alive_client_data_mut(
442        self: Handle<Self>,
443        app: &mut App,
444    ) -> &mut AutomaticKeepAliveClientMixinData {
445        &mut app.get_mut(self).keep_alive
446    }
447
448    fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
449        app.get(self).want_keep_alive
450    }
451}
452
453impl SelectionRegistrar for SelectionKeepAliveState {
454    fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
455        let attachment = self.listens_to(selectable);
456        selectable.add_listener(app, attachment.clone());
457        app.get_mut(self)
458            .selectable_attachments
459            .get_or_insert_with(HashMap::new)
460            .insert(selectable, attachment);
461        self.registrar_handle(app)
462            .expect("a sliver child with selectables is under a selection container")
463            .add(app, selectable);
464        if selectable.value(app).has_selection() {
465            self.update_selectables_with_selections(app, selectable, true);
466        }
467    }
468
469    fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
470        let Some(attachments) = app.get_mut(self).selectable_attachments.as_mut() else {
471            return;
472        };
473        let attachment = attachments
474            .remove(&selectable)
475            .expect("the selectable was attached");
476        selectable.remove_listener(app, &attachment);
477        self.registrar_handle(app)
478            .expect("a sliver child with selectables is under a selection container")
479            .remove(app, selectable);
480        self.update_selectables_with_selections(app, selectable, false);
481    }
482}
483
484/// Wraps a built child the way both delegates do: a repaint boundary, an [`IndexedSemantics`],
485/// an [`AutomaticKeepAlive`], then a [`KeyedSubtree`] carrying the salted key.
486///
487/// Flutter puts a [`SelectionKeepAlive`] inside the `AutomaticKeepAlive`.
488fn wrap_child(
489    child: WidgetRef,
490    index: i32,
491    add_automatic_keep_alives: bool,
492    add_repaint_boundaries: bool,
493    add_semantic_indexes: bool,
494    semantic_index_callback: &SemanticIndexCallback,
495    semantic_index_offset: i32,
496) -> WidgetRef {
497    let key = child
498        .key()
499        .map(|key| KeyRef::from(SaltedValueKey::new(key.clone())));
500    let mut child = if add_repaint_boundaries {
501        RepaintBoundary::new().child(child).into_widget()
502    } else {
503        child
504    };
505    if add_semantic_indexes && let Some(semantic_index) = semantic_index_callback(&child, index) {
506        child = IndexedSemantics::new(semantic_index + semantic_index_offset)
507            .child(child)
508            .into_widget();
509    }
510    if add_automatic_keep_alives {
511        child = AutomaticKeepAlive::new(SelectionKeepAlive::new(child)).into_widget();
512    }
513    let subtree = KeyedSubtree::new(child);
514    match key {
515        Some(key) => subtree.key(key).into_widget(),
516        None => subtree.into_widget(),
517    }
518}
519
520/// Called to find the new index of a child based on its `key` in case of reordering.
521///
522/// If the child with the `key` is no longer present, `None` is returned.
523///
524/// Used by [`SliverChildBuilderDelegate::find_child_index_callback`].
525pub type ChildIndexGetter = Rc<dyn Fn(&KeyRef) -> Option<i32>>;
526
527/// A delegate that supplies children for slivers using a builder callback.
528///
529/// Many slivers lazily construct their box children to avoid creating more children than are
530/// visible through the `Viewport`. This delegate provides children using a
531/// [`NullableIndexedWidgetBuilder`] callback, so that the children do not even have to be built
532/// until they are displayed.
533///
534/// The widgets returned from the builder callback are automatically wrapped in
535/// `AutomaticKeepAlive` widgets if [`add_automatic_keep_alives`](Self::add_automatic_keep_alives)
536/// is true (the default) and in [`RepaintBoundary`] widgets if
537/// [`add_repaint_boundaries`](Self::add_repaint_boundaries) is true (also the default).
538///
539/// ## Accessibility
540///
541/// `CustomScrollView` requires that its semantic children are annotated using
542/// `IndexedSemantics`. This is done by default in the delegate with the
543/// [`add_semantic_indexes`](Self::add_semantic_indexes) parameter set to true.
544///
545/// If multiple delegates are used in a single scroll view, then the indexes will not be correct
546/// by default. The [`semantic_index_offset`](Self::semantic_index_offset) can be used to offset
547/// the semantic indexes of each delegate so that the indexes are monotonically increasing. For
548/// example, if a scroll view contains two delegates where the first has 10 children
549/// contributing semantics, then the second delegate should offset its children by 10.
550///
551/// In certain cases, only a subset of child widgets should be annotated with a semantic index.
552/// For example, in `ListView.separated` the separators do not have an index associated with
553/// them. This is done by providing a
554/// [`semantic_index_callback`](Self::semantic_index_callback) which returns `None` for
555/// separators indexes and rounds the non-separator indexes down by half.
556///
557/// See also:
558///
559///  * [`SliverChildListDelegate`], which is a delegate that has an explicit list of children.
560#[derive(Clone)]
561pub struct SliverChildBuilderDelegate {
562    /// Called to build children for the sliver.
563    ///
564    /// Will be called only for indices greater than or equal to zero and less than
565    /// [`child_count`](Self::child_count) (if it is non-`None`).
566    ///
567    /// Should return `None` if asked to build a widget with a greater index than exists.
568    ///
569    /// May result in an infinite loop or run out of memory if
570    /// [`child_count`](Self::child_count) is `None` and the builder always provides a zero-size
571    /// widget (such as `SizedBox::shrink()`). If possible, provide children with non-zero size,
572    /// return `None` from the builder, or set a [`child_count`](Self::child_count).
573    ///
574    /// The delegate wraps the children returned by this builder in [`RepaintBoundary`] widgets.
575    pub builder: NullableIndexedWidgetBuilder,
576
577    /// The total number of children this delegate can provide.
578    ///
579    /// If `None`, the number of children is determined by the least index for which
580    /// [`builder`](Self::builder) returns `None`.
581    ///
582    /// May result in an infinite loop or run out of memory if it is `None` and the builder
583    /// always provides a zero-size widget. If possible, provide children with non-zero size,
584    /// return `None` from the builder, or set a child count.
585    pub child_count: Option<i32>,
586
587    /// Whether to wrap each child in an `AutomaticKeepAlive`.
588    ///
589    /// Typically, lazily laid out children are wrapped in `AutomaticKeepAlive` widgets so that
590    /// the children can use `KeepAliveNotification`s to preserve their state when they would
591    /// otherwise be garbage collected off-screen.
592    ///
593    /// This feature (and [`add_repaint_boundaries`](Self::add_repaint_boundaries)) must be
594    /// disabled if the children are going to manually maintain their `KeepAlive` state. It may
595    /// also be more efficient to disable this feature if it is known ahead of time that none of
596    /// the children will ever try to keep themselves alive.
597    ///
598    /// Defaults to true.
599    pub add_automatic_keep_alives: bool,
600
601    /// Whether to wrap each child in a [`RepaintBoundary`].
602    ///
603    /// Typically, children in a scrolling container are wrapped in repaint boundaries so that
604    /// they do not need to be repainted as the list scrolls. If the children are easy to
605    /// repaint (e.g., solid color blocks or a short snippet of text), it might be more
606    /// efficient to not add a repaint boundary and instead always repaint the children during
607    /// scrolling.
608    ///
609    /// Defaults to true.
610    pub add_repaint_boundaries: bool,
611
612    /// Whether to wrap each child in an `IndexedSemantics`.
613    ///
614    /// Typically, children in a scrolling container must be annotated with a semantic index in
615    /// order to generate the correct accessibility announcements. This should only be set to
616    /// false if the indexes have already been provided by an `IndexedSemantics` widget.
617    ///
618    /// Defaults to true.
619    pub add_semantic_indexes: bool,
620
621    /// An initial offset to add to the semantic indexes generated by this widget.
622    ///
623    /// Defaults to zero.
624    pub semantic_index_offset: i32,
625
626    /// A [`SemanticIndexCallback`] which is used when
627    /// [`add_semantic_indexes`](Self::add_semantic_indexes) is true.
628    ///
629    /// Defaults to providing an index for each widget.
630    pub semantic_index_callback: SemanticIndexCallback,
631
632    /// Called to find the new index of a child based on its key in case of reordering.
633    ///
634    /// If not provided, a child widget may not map to its existing `RenderObject` when the
635    /// order of children returned from the children builder changes. This may result in
636    /// state-loss.
637    ///
638    /// This callback should take an input `Key`, and it should return the index of the child
639    /// element with that associated key, or `None` if not found.
640    pub find_child_index_callback: Option<ChildIndexGetter>,
641}
642
643impl SliverChildBuilderDelegate {
644    /// Creates a delegate that supplies children for slivers using the given builder callback.
645    ///
646    /// If the order in which the builder returns children ever changes, consider providing a
647    /// [`find_child_index_callback`](Self::find_child_index_callback). This allows the delegate
648    /// to find the new index for a child that was previously located at a different index to
649    /// attach the existing state to the widget at its new location.
650    pub fn new(
651        builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
652    ) -> SliverChildBuilderDelegate {
653        SliverChildBuilderDelegate::from_builder(Rc::new(builder))
654    }
655
656    /// Creates the delegate from a shared builder, which the `builder` constructors of the
657    /// sliver widgets pass on.
658    pub fn from_builder(builder: NullableIndexedWidgetBuilder) -> SliverChildBuilderDelegate {
659        SliverChildBuilderDelegate {
660            builder,
661            child_count: None,
662            add_automatic_keep_alives: true,
663            add_repaint_boundaries: true,
664            add_semantic_indexes: true,
665            semantic_index_offset: 0,
666            semantic_index_callback: default_semantic_index_callback(),
667            find_child_index_callback: None,
668        }
669    }
670
671    /// Dart `SliverChildBuilderDelegate(childCount:)`.
672    pub fn child_count(mut self, child_count: i32) -> SliverChildBuilderDelegate {
673        self.child_count = Some(child_count);
674        self
675    }
676
677    /// Dart `SliverChildBuilderDelegate(addAutomaticKeepAlives:)`.
678    pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverChildBuilderDelegate {
679        self.add_automatic_keep_alives = value;
680        self
681    }
682
683    /// Dart `SliverChildBuilderDelegate(addRepaintBoundaries:)`.
684    pub fn add_repaint_boundaries(mut self, value: bool) -> SliverChildBuilderDelegate {
685        self.add_repaint_boundaries = value;
686        self
687    }
688
689    /// Dart `SliverChildBuilderDelegate(addSemanticIndexes:)`.
690    pub fn add_semantic_indexes(mut self, value: bool) -> SliverChildBuilderDelegate {
691        self.add_semantic_indexes = value;
692        self
693    }
694
695    /// Dart `SliverChildBuilderDelegate(semanticIndexOffset:)`.
696    pub fn semantic_index_offset(mut self, value: i32) -> SliverChildBuilderDelegate {
697        self.semantic_index_offset = value;
698        self
699    }
700
701    /// Dart `SliverChildBuilderDelegate(semanticIndexCallback:)`.
702    pub fn semantic_index_callback(
703        mut self,
704        value: SemanticIndexCallback,
705    ) -> SliverChildBuilderDelegate {
706        self.semantic_index_callback = value;
707        self
708    }
709
710    /// Dart `SliverChildBuilderDelegate(findChildIndexCallback:)`.
711    pub fn find_child_index_callback(
712        mut self,
713        value: ChildIndexGetter,
714    ) -> SliverChildBuilderDelegate {
715        self.find_child_index_callback = Some(value);
716        self
717    }
718
719    /// The delegate as the shared reference a sliver widget takes.
720    pub fn into_delegate(self) -> SliverChildDelegateRef {
721        Rc::new(self)
722    }
723}
724
725impl SliverChildDelegate for SliverChildBuilderDelegate {
726    fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
727        let find_child_index_callback = self.find_child_index_callback.as_ref()?;
728        find_child_index_callback(&unsalt(key))
729    }
730
731    fn build(&self, app: &mut App, context: BuildContext, index: i32) -> Option<WidgetRef> {
732        if index < 0 || self.child_count.is_some_and(|count| index >= count) {
733            return None;
734        }
735        // A panic in the builder unwinds; there is no `ErrorWidget`.
736        let child = (self.builder)(app, context, index)?;
737        Some(wrap_child(
738            child,
739            index,
740            self.add_automatic_keep_alives,
741            self.add_repaint_boundaries,
742            self.add_semantic_indexes,
743            &self.semantic_index_callback,
744            self.semantic_index_offset,
745        ))
746    }
747
748    fn estimated_child_count(&self) -> Option<i32> {
749        self.child_count
750    }
751
752    fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool {
753        let _ = old_delegate;
754        true
755    }
756
757    fn as_any(&self) -> &dyn Any {
758        self
759    }
760}
761
762impl Debug for SliverChildBuilderDelegate {
763    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764        let mut description = Vec::new();
765        self.debug_fill_description(&mut description);
766        write!(f, "SliverChildBuilderDelegate({})", description.join(", "))
767    }
768}
769
770/// A delegate that supplies children for slivers using an explicit list.
771///
772/// Many slivers lazily construct their box children to avoid creating more children than are
773/// visible through the `Viewport`. This delegate provides children using an explicit list, which
774/// is convenient but reduces the benefit of building children lazily.
775///
776/// In general building all the widgets in advance is not efficient. It is better to create a
777/// delegate that builds them on demand using [`SliverChildBuilderDelegate`] or by implementing
778/// [`SliverChildDelegate`] directly.
779///
780/// This type is provided for the cases where either the list of children is known well in
781/// advance, and therefore will not be built each time the delegate itself is created, or the
782/// list is small, such that it's likely always visible (and thus there is nothing to be gained
783/// by building it on demand). For example, the body of a dialog box might fit both of these
784/// conditions.
785///
786/// The widgets in the given [`children`](Self::children) list are automatically wrapped in
787/// `AutomaticKeepAlive` widgets if
788/// [`add_automatic_keep_alives`](Self::add_automatic_keep_alives) is true (the default) and in
789/// [`RepaintBoundary`] widgets if [`add_repaint_boundaries`](Self::add_repaint_boundaries) is
790/// true (also the default).
791///
792/// ## Accessibility
793///
794/// `CustomScrollView` requires that its semantic children are annotated using
795/// `IndexedSemantics`. This is done by default in the delegate with the
796/// [`add_semantic_indexes`](Self::add_semantic_indexes) parameter set to true.
797///
798/// See also:
799///
800///  * [`SliverChildBuilderDelegate`], which is a delegate that uses a builder callback to
801///    construct the children.
802pub struct SliverChildListDelegate {
803    /// Whether to wrap each child in an `AutomaticKeepAlive`.
804    pub add_automatic_keep_alives: bool,
805
806    /// Whether to wrap each child in a [`RepaintBoundary`].
807    pub add_repaint_boundaries: bool,
808
809    /// Whether to wrap each child in an `IndexedSemantics`.
810    pub add_semantic_indexes: bool,
811
812    /// An initial offset to add to the semantic indexes generated by this widget.
813    pub semantic_index_offset: i32,
814
815    /// A [`SemanticIndexCallback`] which is used when
816    /// [`add_semantic_indexes`](Self::add_semantic_indexes) is true.
817    pub semantic_index_callback: SemanticIndexCallback,
818
819    /// The widgets to display.
820    ///
821    /// If this list is going to be mutated, it is usually wise to put a `Key` on each of the
822    /// child widgets, so that the framework can match old configurations to new configurations
823    /// and maintain the underlying render objects.
824    ///
825    /// A widget is immutable, so a new list must be provided whenever the children change.
826    pub children: Vec<WidgetRef>,
827
828    // A map to cache key to index lookup for children, and the index the lazy fill has reached.
829    //
830    // `None` for the constant instance (Dart's `SliverChildListDelegate.fixed`), whose children
831    // never move.
832    key_to_index: Option<RefCell<KeyToIndex>>,
833}
834
835/// The lazily filled key-to-index cache of a [`SliverChildListDelegate`].
836///
837/// Dart keeps the fill cursor under the map's `null` key; it is a field here.
838#[derive(Default)]
839struct KeyToIndex {
840    map: HashMap<KeyRef, i32>,
841    /// The index [`SliverChildListDelegate::find_child_index`] has scanned up to.
842    cursor: usize,
843}
844
845impl SliverChildListDelegate {
846    /// Creates a delegate that supplies children for slivers using the given list.
847    ///
848    /// If the order of children never changes, consider using [`fixed`](Self::fixed).
849    pub fn new(children: Vec<WidgetRef>) -> SliverChildListDelegate {
850        SliverChildListDelegate {
851            add_automatic_keep_alives: true,
852            add_repaint_boundaries: true,
853            add_semantic_indexes: true,
854            semantic_index_offset: 0,
855            semantic_index_callback: default_semantic_index_callback(),
856            children,
857            key_to_index: Some(RefCell::default()),
858        }
859    }
860
861    /// Creates a constant version of the delegate that supplies children for slivers using the
862    /// given list.
863    ///
864    /// If the order of the children will change, consider using [`new`](Self::new).
865    pub fn fixed(children: Vec<WidgetRef>) -> SliverChildListDelegate {
866        SliverChildListDelegate {
867            key_to_index: None,
868            ..SliverChildListDelegate::new(children)
869        }
870    }
871
872    /// Dart `SliverChildListDelegate(addAutomaticKeepAlives:)`.
873    pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverChildListDelegate {
874        self.add_automatic_keep_alives = value;
875        self
876    }
877
878    /// Dart `SliverChildListDelegate(addRepaintBoundaries:)`.
879    pub fn add_repaint_boundaries(mut self, value: bool) -> SliverChildListDelegate {
880        self.add_repaint_boundaries = value;
881        self
882    }
883
884    /// Dart `SliverChildListDelegate(addSemanticIndexes:)`.
885    pub fn add_semantic_indexes(mut self, value: bool) -> SliverChildListDelegate {
886        self.add_semantic_indexes = value;
887        self
888    }
889
890    /// Dart `SliverChildListDelegate(semanticIndexOffset:)`.
891    pub fn semantic_index_offset(mut self, value: i32) -> SliverChildListDelegate {
892        self.semantic_index_offset = value;
893        self
894    }
895
896    /// Dart `SliverChildListDelegate(semanticIndexCallback:)`.
897    pub fn semantic_index_callback(
898        mut self,
899        value: SemanticIndexCallback,
900    ) -> SliverChildListDelegate {
901        self.semantic_index_callback = value;
902        self
903    }
904
905    /// The delegate as the shared reference a sliver widget takes.
906    pub fn into_delegate(self) -> SliverChildDelegateRef {
907        Rc::new(self)
908    }
909
910    /// Flutter's `_findChildIndex`.
911    fn find_child_index(&self, key: &KeyRef) -> Option<i32> {
912        // Dart's `_isConstantInstance`.
913        let cache = self.key_to_index.as_ref()?;
914        let mut cache = cache.borrow_mut();
915        if let Some(index) = cache.map.get(key) {
916            return Some(*index);
917        }
918        // Lazily fill the cache.
919        let mut index = cache.cursor;
920        while index < self.children.len() {
921            let child = &self.children[index];
922            if let Some(child_key) = child.key() {
923                cache.map.insert(child_key.clone(), index as i32);
924                if child_key == key {
925                    // Record current index for next function call.
926                    cache.cursor = index + 1;
927                    return Some(index as i32);
928                }
929            }
930            index += 1;
931        }
932        cache.cursor = index;
933        None
934    }
935}
936
937impl SliverChildDelegate for SliverChildListDelegate {
938    fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
939        self.find_child_index(&unsalt(key))
940    }
941
942    fn build(&self, _app: &mut App, _context: BuildContext, index: i32) -> Option<WidgetRef> {
943        let slot = usize::try_from(index).ok()?;
944        let child = self.children.get(slot)?.clone();
945        Some(wrap_child(
946            child,
947            index,
948            self.add_automatic_keep_alives,
949            self.add_repaint_boundaries,
950            self.add_semantic_indexes,
951            &self.semantic_index_callback,
952            self.semantic_index_offset,
953        ))
954    }
955
956    fn estimated_child_count(&self) -> Option<i32> {
957        Some(self.children.len() as i32)
958    }
959
960    fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool {
961        let old = old_delegate
962            .as_any()
963            .downcast_ref::<SliverChildListDelegate>()
964            .expect("the caller compared the delegate types first");
965        self.children.len() != old.children.len()
966            || std::iter::zip(&self.children, &old.children).any(|(a, b)| !Rc::ptr_eq(a, b))
967    }
968
969    fn as_any(&self) -> &dyn Any {
970        self
971    }
972}
973
974impl Debug for SliverChildListDelegate {
975    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976        let mut description = Vec::new();
977        self.debug_fill_description(&mut description);
978        write!(f, "SliverChildListDelegate({})", description.join(", "))
979    }
980}