Skip to main content

waft_rendering/
sliver_fixed_extent_list.rs

1//! Flutter counterpart: `rendering/sliver_fixed_extent_list.dart`.
2
3use std::rc::Rc;
4
5use waft_foundation::{App, PRECISION_ERROR_TOLERANCE};
6
7use crate::box_::{AnyRenderBox, BoxConstraints};
8use crate::object::{ContainerRenderObjectData, RenderHandle, RenderObjectData};
9use crate::sliver::{
10    ItemExtentBuilder, RenderSliver, RenderSliverData, SliverConstraints, SliverGeometry,
11    SliverLayoutDimensions, calculate_cache_offset, calculate_paint_offset,
12};
13use crate::sliver_multi_box_adaptor::{
14    RenderSliverBoxChildManager, RenderSliverMultiBoxAdaptor, RenderSliverMultiBoxAdaptorData,
15    SliverMultiBoxAdaptorParentData,
16};
17
18/// Flutter's `RenderSliverFixedExtentBoxAdaptor` field.
19#[derive(Debug, Default)]
20pub struct RenderSliverFixedExtentBoxAdaptorData {
21    current_layout_dimensions: Option<SliverLayoutDimensions>,
22}
23
24impl RenderSliverFixedExtentBoxAdaptorData {
25    /// Creates the state of a fixed-extent box adaptor that has not been laid out.
26    pub const fn new() -> RenderSliverFixedExtentBoxAdaptorData {
27        RenderSliverFixedExtentBoxAdaptorData {
28            current_layout_dimensions: None,
29        }
30    }
31}
32
33/// Implements [`RenderSliverFixedExtentBoxAdaptor`] field accessors for a `fixed_extent` field.
34#[macro_export]
35macro_rules! render_sliver_fixed_extent_accessors {
36    () => {
37        fn fixed_extent_data(
38            self: $crate::RenderHandle<Self>,
39            app: &::waft_foundation::App,
40        ) -> &$crate::RenderSliverFixedExtentBoxAdaptorData {
41            &self.get(app).fixed_extent
42        }
43        fn fixed_extent_data_mut(
44            self: $crate::RenderHandle<Self>,
45            app: &mut ::waft_foundation::App,
46        ) -> &mut $crate::RenderSliverFixedExtentBoxAdaptorData {
47            &mut self.get_mut(app).fixed_extent
48        }
49    };
50}
51
52/// A sliver that contains multiple box children that have the same extent in the main axis.
53///
54/// Flutter's `RenderSliverFixedExtentBoxAdaptor`. An implementor answers either
55/// [`item_extent`](Self::item_extent) or [`item_extent_builder`](Self::item_extent_builder).
56pub trait RenderSliverFixedExtentBoxAdaptor: RenderSliverMultiBoxAdaptor {
57    /// Mixin field access.
58    fn fixed_extent_data(
59        self: RenderHandle<Self>,
60        app: &App,
61    ) -> &RenderSliverFixedExtentBoxAdaptorData;
62
63    /// See [`fixed_extent_data`](Self::fixed_extent_data).
64    fn fixed_extent_data_mut(
65        self: RenderHandle<Self>,
66        app: &mut App,
67    ) -> &mut RenderSliverFixedExtentBoxAdaptorData;
68
69    /// The main-axis extent of each item.
70    ///
71    /// If this is `Some`, [`item_extent_builder`](Self::item_extent_builder) must be `None`.
72    /// If this is `None`, `item_extent_builder` must be `Some`.
73    fn item_extent(self: RenderHandle<Self>, app: &App) -> Option<f64>;
74
75    /// The main-axis extent builder of each item.
76    ///
77    /// If this is `Some`, [`item_extent`](Self::item_extent) must be `None`.
78    /// If this is `None`, `item_extent` must be `Some`.
79    fn item_extent_builder(self: RenderHandle<Self>, app: &App) -> Option<ItemExtentBuilder> {
80        let _ = app;
81        let _ = self;
82        None
83    }
84
85    /// The layout dimensions for the sliver.
86    ///
87    /// If the sliver has not been laid out yet, this returns a [`SliverLayoutDimensions`] based
88    /// on the current constraints.
89    fn layout_dimensions(self: RenderHandle<Self>, app: &App) -> SliverLayoutDimensions {
90        self.fixed_extent_data(app)
91            .current_layout_dimensions
92            .unwrap_or_else(|| {
93                let constraints = self.constraints(app);
94                SliverLayoutDimensions::new(
95                    constraints.scroll_offset,
96                    constraints.preceding_scroll_extent,
97                    constraints.viewport_main_axis_extent,
98                    constraints.cross_axis_extent,
99                )
100            })
101    }
102
103    /// The layout offset for the child with the given index.
104    ///
105    /// This function uses the returned value of
106    /// [`item_extent_builder`](Self::item_extent_builder) or the
107    /// [`item_extent`](Self::item_extent) to avoid recomputing item size repeatedly during
108    /// layout.
109    ///
110    /// By default, places the children in order, without gaps, starting from layout offset zero.
111    fn index_to_layout_offset(self: RenderHandle<Self>, app: &App, index: i32) -> f64 {
112        let Some(builder) = self.item_extent_builder(app) else {
113            let item_extent = self.item_extent(app).expect("one of the two is set");
114            return item_extent * f64::from(index);
115        };
116        let mut offset = 0.0;
117        let dimensions = self.layout_dimensions(app);
118        let child_manager = self.child_manager(app);
119        for i in 0..index {
120            let child_count = child_manager.estimated_child_count(app);
121            if child_count.is_some_and(|count| i > count - 1) {
122                break;
123            }
124            let Some(item_extent) = builder(i, dimensions) else {
125                break;
126            };
127            offset += item_extent;
128        }
129        offset
130    }
131
132    /// The minimum child index that is visible at the given scroll offset.
133    ///
134    /// By default, returns a value consistent with the children being placed in order, without
135    /// gaps, starting from layout offset zero.
136    fn get_min_child_index_for_scroll_offset(
137        self: RenderHandle<Self>,
138        app: &App,
139        scroll_offset: f64,
140    ) -> i32 {
141        let Some(builder) = self.item_extent_builder(app) else {
142            let item_extent = self.item_extent(app).expect("one of the two is set");
143            if item_extent <= 0.0 {
144                return 0;
145            }
146            let actual = scroll_offset / item_extent;
147            let round = actual.round();
148            if (actual * item_extent - round * item_extent).abs() < PRECISION_ERROR_TOLERANCE {
149                return round as i32;
150            }
151            return actual.floor() as i32;
152        };
153        self.child_index_for_scroll_offset(app, scroll_offset, &builder)
154    }
155
156    /// The maximum child index that is visible at the given scroll offset.
157    ///
158    /// By default, returns a value consistent with the children being placed in order, without
159    /// gaps, starting from layout offset zero.
160    fn get_max_child_index_for_scroll_offset(
161        self: RenderHandle<Self>,
162        app: &App,
163        scroll_offset: f64,
164    ) -> i32 {
165        let Some(builder) = self.item_extent_builder(app) else {
166            let item_extent = self.item_extent(app).expect("one of the two is set");
167            if item_extent <= 0.0 {
168                return 0;
169            }
170            let actual = scroll_offset / item_extent - 1.0;
171            let round = actual.round();
172            if (actual * item_extent - round * item_extent).abs() < PRECISION_ERROR_TOLERANCE {
173                return (round as i32).max(0);
174            }
175            return (actual.ceil() as i32).max(0);
176        };
177        self.child_index_for_scroll_offset(app, scroll_offset, &builder)
178    }
179
180    /// Flutter's `_getChildIndexForScrollOffset`.
181    fn child_index_for_scroll_offset(
182        self: RenderHandle<Self>,
183        app: &App,
184        scroll_offset: f64,
185        builder: &ItemExtentBuilder,
186    ) -> i32 {
187        if scroll_offset == 0.0 {
188            return 0;
189        }
190        let dimensions = self.layout_dimensions(app);
191        let child_manager = self.child_manager(app);
192        let mut position = 0.0;
193        let mut index = 0;
194        while position < scroll_offset {
195            let child_count = child_manager.estimated_child_count(app);
196            if child_count.is_some_and(|count| index > count - 1) {
197                break;
198            }
199            let Some(item_extent) = builder(index, dimensions) else {
200                break;
201            };
202            position += item_extent;
203            index += 1;
204        }
205        index - 1
206    }
207
208    /// Called to estimate the total scrollable extents of this object.
209    ///
210    /// Must return the total distance from the start of the child with the earliest possible
211    /// index to the end of the child with the last possible index.
212    ///
213    /// By default, defers to [`RenderSliverBoxChildManager::estimate_max_scroll_offset`].
214    fn estimate_max_scroll_offset(
215        self: RenderHandle<Self>,
216        app: &App,
217        constraints: SliverConstraints,
218        first_index: Option<i32>,
219        last_index: Option<i32>,
220        leading_scroll_offset: Option<f64>,
221        trailing_scroll_offset: Option<f64>,
222    ) -> f64 {
223        self.child_manager(app).estimate_max_scroll_offset(
224            app,
225            constraints,
226            first_index,
227            last_index,
228            leading_scroll_offset,
229            trailing_scroll_offset,
230        )
231    }
232
233    /// Called to obtain a precise measure of the total scrollable extents of this object.
234    ///
235    /// This is used when no child is available for the index corresponding to the current scroll
236    /// offset, to determine the precise dimensions of the sliver.
237    ///
238    /// If [`item_extent_builder`](Self::item_extent_builder) is `None`, multiplies the
239    /// [`item_extent`](Self::item_extent) by the number of children reported by
240    /// [`RenderSliverBoxChildManager::child_count`]. Otherwise, sums the extents of the first
241    /// `child_count` children.
242    fn compute_max_scroll_offset(
243        self: RenderHandle<Self>,
244        app: &mut App,
245        _constraints: SliverConstraints,
246    ) -> f64 {
247        let child_manager = self.child_manager(app);
248        let Some(builder) = self.item_extent_builder(app) else {
249            let item_extent = self.item_extent(app).expect("one of the two is set");
250            return f64::from(child_manager.child_count(app)) * item_extent;
251        };
252        let dimensions = self.layout_dimensions(app);
253        let mut offset = 0.0;
254        for i in 0..child_manager.child_count(app) {
255            let Some(item_extent) = builder(i, dimensions) else {
256                break;
257            };
258            offset += item_extent;
259        }
260        offset
261    }
262
263    /// Flutter's `_getChildConstraints`.
264    fn child_constraints(self: RenderHandle<Self>, app: &App, index: i32) -> BoxConstraints {
265        let extent = match self.item_extent_builder(app) {
266            None => self.item_extent(app).expect("one of the two is set"),
267            Some(builder) => builder(index, self.layout_dimensions(app))
268                .expect("the builder must report an extent for a reified child"),
269        };
270        self.constraints(app)
271            .as_box_constraints(extent, extent, None)
272    }
273
274    /// The body of Flutter's `paintExtentOf` override.
275    fn paint_extent_of(self: RenderHandle<Self>, app: &App, child: AnyRenderBox) -> f64 {
276        match self.item_extent_builder(app) {
277            None => self.item_extent(app).expect("one of the two is set"),
278            Some(builder) => builder(self.index_of(app, child), self.layout_dimensions(app))
279                .expect("the builder must report an extent for a reified child"),
280        }
281    }
282
283    /// The body of Flutter's `performLayout` override.
284    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
285        debug_assert!(
286            self.item_extent(app).is_some() != self.item_extent_builder(app).is_some(),
287            "exactly one of item_extent and item_extent_builder must be set"
288        );
289        debug_assert!(
290            self.item_extent_builder(app).is_some()
291                || self
292                    .item_extent(app)
293                    .is_some_and(|extent| extent.is_finite() && extent >= 0.0)
294        );
295
296        let constraints = self.constraints(app);
297        let child_manager = self.child_manager(app);
298        child_manager.did_start_layout(app);
299        child_manager.set_did_underflow(app, false);
300
301        let scroll_offset = constraints.scroll_offset + constraints.cache_origin;
302        debug_assert!(scroll_offset >= 0.0);
303        let remaining_extent = constraints.remaining_cache_extent;
304        debug_assert!(remaining_extent >= 0.0);
305        let target_end_scroll_offset = scroll_offset + remaining_extent;
306
307        self.fixed_extent_data_mut(app).current_layout_dimensions =
308            Some(SliverLayoutDimensions::new(
309                constraints.scroll_offset,
310                constraints.preceding_scroll_extent,
311                constraints.viewport_main_axis_extent,
312                constraints.cross_axis_extent,
313            ));
314
315        let first_index = self.get_min_child_index_for_scroll_offset(app, scroll_offset);
316        let target_last_index = target_end_scroll_offset
317            .is_finite()
318            .then(|| self.get_max_child_index_for_scroll_offset(app, target_end_scroll_offset));
319
320        if self.first_child(app).is_some() {
321            let leading_garbage = self.calculate_leading_garbage(app, first_index);
322            let trailing_garbage = match target_last_index {
323                Some(last_index) => self.calculate_trailing_garbage(app, last_index),
324                None => 0,
325            };
326            self.collect_garbage(app, leading_garbage, trailing_garbage);
327        } else {
328            self.collect_garbage(app, 0, 0);
329        }
330
331        if self.first_child(app).is_none() {
332            let layout_offset = self.index_to_layout_offset(app, first_index);
333            if !self.add_initial_child(app, first_index, layout_offset) {
334                // There are either no children, or we are past the end of all our children.
335                let max = if first_index <= 0 {
336                    0.0
337                } else {
338                    self.compute_max_scroll_offset(app, constraints)
339                };
340                self.set_geometry(
341                    app,
342                    SliverGeometry::builder()
343                        .scroll_extent(max)
344                        .max_paint_extent(max)
345                        .build(),
346                );
347                child_manager.did_finish_layout(app);
348                return;
349            }
350        }
351
352        let mut trailing_child_with_layout: Option<AnyRenderBox> = None;
353
354        let first_child = self.first_child(app).expect("added above");
355        let mut index = self.index_of(app, first_child) - 1;
356        while index >= first_index {
357            let child_constraints = self.child_constraints(app, index);
358            let Some(child) = self.insert_and_layout_leading_child(app, child_constraints, false)
359            else {
360                // Items before the previously first child are no longer present. Reset the scroll
361                // offset to offset all items prior and up to the missing item. Let the parent
362                // re-lay-out everything.
363                let correction = self.index_to_layout_offset(app, index);
364                self.set_geometry(
365                    app,
366                    SliverGeometry::builder()
367                        .scroll_offset_correction(correction)
368                        .build(),
369                );
370                return;
371            };
372            let layout_offset = self.index_to_layout_offset(app, index);
373            let child_parent_data = child
374                .as_object()
375                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app);
376            child_parent_data.set_layout_offset(Some(layout_offset));
377            debug_assert_eq!(child_parent_data.index, Some(index));
378            trailing_child_with_layout.get_or_insert(child);
379            index -= 1;
380        }
381
382        if trailing_child_with_layout.is_none() {
383            let first_child = self.first_child(app).expect("the child list is not empty");
384            let child_constraints = self.child_constraints(app, self.index_of(app, first_child));
385            first_child.layout(app, child_constraints, false);
386            let layout_offset = self.index_to_layout_offset(app, first_index);
387            first_child
388                .as_object()
389                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
390                .set_layout_offset(Some(layout_offset));
391            trailing_child_with_layout = Some(first_child);
392        }
393
394        let mut estimated_max_scroll_offset = f64::INFINITY;
395        let mut index = self.index_of(app, trailing_child_with_layout.expect("set above")) + 1;
396        while target_last_index.is_none_or(|last_index| index <= last_index) {
397            let after = trailing_child_with_layout.expect("set above");
398            let mut child = self.child_after(app, after);
399            if child.is_none_or(|current| self.index_of(app, current) != index) {
400                let child_constraints = self.child_constraints(app, index);
401                child = self.insert_and_layout_child(app, child_constraints, Some(after), false);
402                if child.is_none() {
403                    // We have run out of children.
404                    estimated_max_scroll_offset = self.index_to_layout_offset(app, index);
405                    break;
406                }
407            } else {
408                let child_constraints = self.child_constraints(app, index);
409                child
410                    .expect("checked")
411                    .layout(app, child_constraints, false);
412            }
413            let child = child.expect("set above");
414            trailing_child_with_layout = Some(child);
415            debug_assert_eq!(
416                child
417                    .as_object()
418                    .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
419                    .index,
420                Some(index)
421            );
422            let layout_offset = self.index_to_layout_offset(app, index);
423            child
424                .as_object()
425                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
426                .set_layout_offset(Some(layout_offset));
427            index += 1;
428        }
429
430        let last_child = self.last_child(app).expect("the child list is not empty");
431        let last_index = self.index_of(app, last_child);
432        let leading_scroll_offset = self.index_to_layout_offset(app, first_index);
433        let trailing_scroll_offset = self.index_to_layout_offset(app, last_index + 1);
434
435        debug_assert!(
436            first_index == 0
437                || RenderSliver::child_scroll_offset(
438                    self,
439                    app,
440                    self.first_child(app).expect("not empty").as_object()
441                )
442                .expect("laid out")
443                    - scroll_offset
444                    <= PRECISION_ERROR_TOLERANCE
445        );
446        debug_assert!(self.debug_assert_child_list_is_non_empty_and_contiguous(app));
447        debug_assert_eq!(
448            self.index_of(app, self.first_child(app).expect("not empty")),
449            first_index
450        );
451        debug_assert!(target_last_index.is_none_or(|target| last_index <= target));
452
453        estimated_max_scroll_offset =
454            estimated_max_scroll_offset.min(self.estimate_max_scroll_offset(
455                app,
456                constraints,
457                Some(first_index),
458                Some(last_index),
459                Some(leading_scroll_offset),
460                Some(trailing_scroll_offset),
461            ));
462
463        let paint_extent =
464            calculate_paint_offset(constraints, leading_scroll_offset, trailing_scroll_offset);
465        let cache_extent =
466            calculate_cache_offset(constraints, leading_scroll_offset, trailing_scroll_offset);
467
468        let target_end_scroll_offset_for_paint =
469            constraints.scroll_offset + constraints.remaining_paint_extent;
470        let target_last_index_for_paint =
471            target_end_scroll_offset_for_paint.is_finite().then(|| {
472                self.get_max_child_index_for_scroll_offset(app, target_end_scroll_offset_for_paint)
473            });
474
475        self.set_geometry(
476            app,
477            SliverGeometry::builder()
478                .scroll_extent(estimated_max_scroll_offset)
479                .paint_extent(paint_extent)
480                .cache_extent(cache_extent)
481                .max_paint_extent(estimated_max_scroll_offset)
482                // Conservative to avoid flickering away the clip during scroll.
483                .has_visual_overflow(
484                    target_last_index_for_paint.is_some_and(|target| last_index >= target)
485                        || constraints.scroll_offset > 0.0,
486                )
487                .build(),
488        );
489
490        // We may have started the layout while scrolled to the end, which would not expose a new
491        // child.
492        if estimated_max_scroll_offset == trailing_scroll_offset {
493            child_manager.set_did_underflow(app, true);
494        }
495        child_manager.did_finish_layout(app);
496    }
497}
498
499/// Declares the [`ContainerRenderObjectMixin`], [`RenderObject`] and [`RenderSliver`] impls that
500/// a [`RenderSliverFixedExtentBoxAdaptor`] leaf forwards to its base traits.
501#[macro_export]
502macro_rules! fixed_extent_box_adaptor_leaf {
503    ($leaf:ty) => {
504        impl $crate::ContainerRenderObjectMixin for $leaf {
505            type ChildType = $crate::AnyRenderBox;
506            type ParentDataType = $crate::SliverMultiBoxAdaptorParentData;
507
508            fn container_data(
509                self: $crate::RenderHandle<Self>,
510                app: &::waft_foundation::App,
511            ) -> &$crate::ContainerRenderObjectData<$crate::AnyRenderBox> {
512                &self.get(app).container
513            }
514
515            fn container_data_mut(
516                self: $crate::RenderHandle<Self>,
517                app: &mut ::waft_foundation::App,
518            ) -> &mut $crate::ContainerRenderObjectData<$crate::AnyRenderBox> {
519                &mut self.get_mut(app).container
520            }
521
522            fn insert(
523                self: $crate::RenderHandle<Self>,
524                app: &mut ::waft_foundation::App,
525                child: $crate::AnyRenderBox,
526                after: Option<$crate::AnyRenderBox>,
527            ) {
528                $crate::RenderSliverMultiBoxAdaptor::insert(self, app, child, after)
529            }
530
531            fn move_child(
532                self: $crate::RenderHandle<Self>,
533                app: &mut ::waft_foundation::App,
534                child: $crate::AnyRenderBox,
535                after: Option<$crate::AnyRenderBox>,
536            ) {
537                $crate::RenderSliverMultiBoxAdaptor::move_child(self, app, child, after)
538            }
539
540            fn remove(
541                self: $crate::RenderHandle<Self>,
542                app: &mut ::waft_foundation::App,
543                child: $crate::AnyRenderBox,
544            ) {
545                $crate::RenderSliverMultiBoxAdaptor::remove(self, app, child)
546            }
547
548            fn remove_all(self: $crate::RenderHandle<Self>, app: &mut ::waft_foundation::App) {
549                $crate::RenderSliverMultiBoxAdaptor::remove_all(self, app)
550            }
551        }
552
553        impl $crate::RenderSliverHelpers for $leaf {}
554
555        impl $crate::RenderSliverWithKeepAliveMixin for $leaf {}
556
557        impl $crate::RenderSliverMultiBoxAdaptor for $leaf {
558            $crate::render_sliver_multi_box_adaptor_accessors!();
559
560            fn paint_extent_of(
561                self: $crate::RenderHandle<Self>,
562                app: &::waft_foundation::App,
563                child: $crate::AnyRenderBox,
564            ) -> f64 {
565                $crate::RenderSliverFixedExtentBoxAdaptor::paint_extent_of(self, app, child)
566            }
567        }
568
569        impl $crate::RenderObject for $leaf {
570            $crate::render_object_accessors!();
571
572            fn setup_parent_data(
573                self: $crate::RenderHandle<Self>,
574                app: &mut ::waft_foundation::App,
575                child: $crate::AnyRenderObject,
576            ) {
577                $crate::RenderSliverMultiBoxAdaptor::setup_parent_data(self, app, child);
578                $crate::RenderSliverWithKeepAliveMixin::setup_parent_data(self, app, child);
579            }
580
581            fn visit_children(
582                self: $crate::RenderHandle<Self>,
583                app: &::waft_foundation::App,
584                visitor: &mut dyn FnMut($crate::AnyRenderObject),
585            ) {
586                $crate::RenderSliverMultiBoxAdaptor::visit_children(self, app, visitor)
587            }
588
589            fn did_attach(
590                self: $crate::RenderHandle<Self>,
591                app: &mut ::waft_foundation::App,
592                owner: ::waft_foundation::Handle<$crate::PipelineOwner>,
593            ) {
594                $crate::RenderSliverMultiBoxAdaptor::did_attach(self, app, owner)
595            }
596
597            fn did_detach(self: $crate::RenderHandle<Self>, app: &mut ::waft_foundation::App) {
598                $crate::RenderSliverMultiBoxAdaptor::did_detach(self, app)
599            }
600
601            fn redepth_children(
602                self: $crate::RenderHandle<Self>,
603                app: &mut ::waft_foundation::App,
604            ) {
605                $crate::RenderSliverMultiBoxAdaptor::redepth_children(self, app)
606            }
607
608            fn apply_paint_transform(
609                self: $crate::RenderHandle<Self>,
610                app: &::waft_foundation::App,
611                child: $crate::AnyRenderObject,
612                transform: &mut ::waft_embedder::Matrix4,
613            ) {
614                $crate::RenderSliverMultiBoxAdaptor::apply_paint_transform(
615                    self, app, child, transform,
616                )
617            }
618
619            fn paints_child(
620                self: $crate::RenderHandle<Self>,
621                app: &::waft_foundation::App,
622                child: $crate::AnyRenderObject,
623            ) -> bool {
624                $crate::RenderSliverMultiBoxAdaptor::paints_child(self, app, child)
625            }
626
627            fn paint(
628                self: $crate::RenderHandle<Self>,
629                app: &mut ::waft_foundation::App,
630                context: &mut $crate::PaintingContext,
631                offset: ::waft_embedder::Offset,
632            ) {
633                $crate::RenderSliverMultiBoxAdaptor::paint(self, app, context, offset)
634            }
635
636            fn perform_layout(self: $crate::RenderHandle<Self>, app: &mut ::waft_foundation::App) {
637                $crate::RenderSliverFixedExtentBoxAdaptor::perform_layout(self, app)
638            }
639        }
640
641        impl $crate::RenderSliver for $leaf {
642            $crate::render_sliver_accessors!();
643
644            fn hit_test_children(
645                self: $crate::RenderHandle<Self>,
646                app: &mut ::waft_foundation::App,
647                result: &mut $crate::SliverHitTestResult<'_>,
648                main_axis_position: f64,
649                cross_axis_position: f64,
650            ) -> bool {
651                $crate::RenderSliverMultiBoxAdaptor::hit_test_children(
652                    self,
653                    app,
654                    result,
655                    main_axis_position,
656                    cross_axis_position,
657                )
658            }
659
660            fn child_main_axis_position(
661                self: $crate::RenderHandle<Self>,
662                app: &::waft_foundation::App,
663                child: $crate::AnyRenderObject,
664            ) -> f64 {
665                $crate::RenderSliverMultiBoxAdaptor::child_main_axis_position(self, app, child)
666            }
667
668            fn child_scroll_offset(
669                self: $crate::RenderHandle<Self>,
670                app: &::waft_foundation::App,
671                child: $crate::AnyRenderObject,
672            ) -> Option<f64> {
673                $crate::RenderSliverMultiBoxAdaptor::child_scroll_offset(self, app, child)
674            }
675        }
676    };
677}
678
679pub use fixed_extent_box_adaptor_leaf;
680
681/// A sliver that places multiple box children with the same main axis extent in a linear array.
682///
683/// [`RenderSliverFixedExtentList`] places its children in a linear array along the main axis
684/// starting at offset zero and without gaps. Each child is forced to have the
685/// [`item_extent`](Self::item_extent) in the main axis and the
686/// [`crate::SliverConstraints::cross_axis_extent`] in the cross axis.
687///
688/// [`RenderSliverFixedExtentList`] is more efficient than [`crate::RenderSliverList`] because it
689/// does not need to perform layout on its children to obtain their extent in the main axis.
690pub struct RenderSliverFixedExtentList {
691    render_object: RenderObjectData,
692    render_sliver: RenderSliverData,
693    container: ContainerRenderObjectData<AnyRenderBox>,
694    adaptor: RenderSliverMultiBoxAdaptorData,
695    fixed_extent: RenderSliverFixedExtentBoxAdaptorData,
696    item_extent: f64,
697}
698
699impl RenderSliverFixedExtentList {
700    /// Creates a sliver that contains multiple box children that have a given extent in the main
701    /// axis.
702    pub fn new(
703        app: &mut App,
704        child_manager: Rc<dyn RenderSliverBoxChildManager>,
705        item_extent: f64,
706    ) -> RenderHandle<RenderSliverFixedExtentList> {
707        RenderHandle::new_sliver(
708            app,
709            RenderSliverFixedExtentList {
710                render_object: RenderObjectData::new(),
711                render_sliver: RenderSliverData::new(),
712                container: ContainerRenderObjectData::new(),
713                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
714                fixed_extent: RenderSliverFixedExtentBoxAdaptorData::new(),
715                item_extent,
716            },
717        )
718    }
719
720    /// Sets [`RenderSliverFixedExtentBoxAdaptor::item_extent`].
721    pub fn set_item_extent(self: RenderHandle<Self>, app: &mut App, value: f64) {
722        if self.get(app).item_extent == value {
723            return;
724        }
725        self.get_mut(app).item_extent = value;
726        self.mark_needs_layout(app);
727    }
728}
729
730impl RenderSliverFixedExtentBoxAdaptor for RenderSliverFixedExtentList {
731    crate::render_sliver_fixed_extent_accessors!();
732
733    fn item_extent(self: RenderHandle<Self>, app: &App) -> Option<f64> {
734        Some(self.get(app).item_extent)
735    }
736}
737
738fixed_extent_box_adaptor_leaf!(RenderSliverFixedExtentList);
739
740/// A sliver that places multiple box children with the corresponding main axis extent in a linear
741/// array.
742pub struct RenderSliverVariedExtentList {
743    render_object: RenderObjectData,
744    render_sliver: RenderSliverData,
745    container: ContainerRenderObjectData<AnyRenderBox>,
746    adaptor: RenderSliverMultiBoxAdaptorData,
747    fixed_extent: RenderSliverFixedExtentBoxAdaptorData,
748    item_extent_builder: ItemExtentBuilder,
749}
750
751impl RenderSliverVariedExtentList {
752    /// Creates a sliver that contains multiple box children that have an explicit extent in the
753    /// main axis.
754    pub fn new(
755        app: &mut App,
756        child_manager: Rc<dyn RenderSliverBoxChildManager>,
757        item_extent_builder: ItemExtentBuilder,
758    ) -> RenderHandle<RenderSliverVariedExtentList> {
759        RenderHandle::new_sliver(
760            app,
761            RenderSliverVariedExtentList {
762                render_object: RenderObjectData::new(),
763                render_sliver: RenderSliverData::new(),
764                container: ContainerRenderObjectData::new(),
765                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
766                fixed_extent: RenderSliverFixedExtentBoxAdaptorData::new(),
767                item_extent_builder,
768            },
769        )
770    }
771
772    /// Sets [`RenderSliverFixedExtentBoxAdaptor::item_extent_builder`].
773    pub fn set_item_extent_builder(
774        self: RenderHandle<Self>,
775        app: &mut App,
776        value: ItemExtentBuilder,
777    ) {
778        if Rc::ptr_eq(&self.get(app).item_extent_builder, &value) {
779            return;
780        }
781        self.get_mut(app).item_extent_builder = value;
782        self.mark_needs_layout(app);
783    }
784}
785
786impl RenderSliverFixedExtentBoxAdaptor for RenderSliverVariedExtentList {
787    crate::render_sliver_fixed_extent_accessors!();
788
789    fn item_extent(self: RenderHandle<Self>, _app: &App) -> Option<f64> {
790        let _ = self;
791        None
792    }
793
794    fn item_extent_builder(self: RenderHandle<Self>, app: &App) -> Option<ItemExtentBuilder> {
795        Some(Rc::clone(&self.get(app).item_extent_builder))
796    }
797}
798
799fixed_extent_box_adaptor_leaf!(RenderSliverVariedExtentList);
800
801#[cfg(test)]
802mod tests {
803    use waft_embedder::Size;
804    use waft_foundation::AppCell;
805    use waft_gestures::HitTestResult;
806
807    use super::*;
808    use crate::object::ContainerRenderObjectMixin;
809    use crate::sliver::SliverHitTestResult;
810    use crate::sliver_multi_box_adaptor::test_support::TestChildManager;
811    use crate::sliver_multi_box_adaptor::viewport_test_support::ScrollHarness;
812
813    const VIEWPORT: Size = Size::new(100.0, 200.0);
814
815    fn fixed_list(
816        app: &mut App,
817        extents: Vec<f64>,
818        item_extent: f64,
819    ) -> (
820        RenderHandle<RenderSliverFixedExtentList>,
821        Rc<TestChildManager<RenderSliverFixedExtentList>>,
822        ScrollHarness,
823    ) {
824        let manager = TestChildManager::new(extents);
825        let list = RenderSliverFixedExtentList::new(app, manager.clone(), item_extent);
826        manager.attach(list);
827        let harness = ScrollHarness::new(app, list.as_sliver(), VIEWPORT);
828        (list, manager, harness)
829    }
830
831    /// `sliver_fixed_extent_list_test.dart`: only the children that fall in the viewport (plus
832    /// the cache area) are reified, and they are placed at multiples of the item extent.
833    #[test]
834    fn a_fixed_extent_list_reifies_only_the_visible_children() {
835        let cell = AppCell::new();
836        let mut app = cell.borrow_mut();
837        let (list, _, _harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
838
839        assert_eq!(
840            list.index_of(&app, list.first_child(&app).expect("built")),
841            0
842        );
843        assert_eq!(list.index_to_layout_offset(&app, 3), 150.0);
844        let geometry = list.geometry(&app);
845        assert_eq!(geometry.scroll_extent, 2000.0);
846        assert_eq!(geometry.paint_extent, 200.0);
847        assert!(geometry.has_visual_overflow);
848        // 200 pixels of viewport plus 250 of cache, at 50 pixels each, is far short of 40.
849        assert!(list.child_count(&app) < 40);
850    }
851
852    /// Scrolling collects the children that left the viewport and creates the ones that entered.
853    #[test]
854    fn scrolling_collects_and_creates_children() {
855        let cell = AppCell::new();
856        let mut app = cell.borrow_mut();
857        let (list, _, harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
858        assert_eq!(
859            list.index_of(&app, list.first_child(&app).expect("built")),
860            0
861        );
862
863        harness.scroll_to(&mut app, 600.0);
864
865        let first = list.first_child(&app).expect("children were created");
866        // 600 - 250 of leading cache = 350, which is index 7.
867        assert_eq!(list.index_of(&app, first), 7);
868        assert_eq!(
869            RenderSliver::child_scroll_offset(list, &app, first.as_object()),
870            Some(350.0)
871        );
872        assert_eq!(
873            RenderSliver::child_main_axis_position(list, &app, first.as_object()),
874            -250.0
875        );
876    }
877
878    /// A hit inside a reified child lands on the child and the sliver.
879    #[test]
880    fn a_fixed_extent_list_hit_tests_its_children() {
881        let cell = AppCell::new();
882        let mut app = cell.borrow_mut();
883        let (list, _, _harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
884
885        let mut result = HitTestResult::new();
886        let hit = list.hit_test(
887            &mut app,
888            &mut SliverHitTestResult::wrap(&mut result),
889            75.0,
890            20.0,
891        );
892
893        assert!(hit);
894        assert_eq!(result.path().len(), 2);
895    }
896
897    /// A child whose parent data asks to be kept alive moves to the keep-alive bucket instead of
898    /// being destroyed, and comes back out of it when it is needed again.
899    #[test]
900    fn a_kept_alive_child_survives_leaving_the_viewport() {
901        let cell = AppCell::new();
902        let mut app = cell.borrow_mut();
903        let (list, manager, harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
904        let first = list.first_child(&app).expect("children were created");
905        first
906            .as_object()
907            .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(&mut app)
908            .set_keep_alive(true);
909
910        harness.scroll_to(&mut app, 1000.0);
911
912        // The child is out of the child list but still attached, in the keep-alive bucket.
913        assert_eq!(list.keep_alive_children(&app), vec![first]);
914        assert!(
915            first
916                .as_object()
917                .parent_data_of::<SliverMultiBoxAdaptorParentData>(&app)
918                .kept_alive()
919        );
920        assert!(!list.as_object().paints_child(&app, first.as_object()));
921        let created_before = manager.created.borrow().len();
922
923        harness.scroll_to(&mut app, 0.0);
924
925        // Index 0 came back from the bucket, so the manager was not asked to create it again.
926        assert_eq!(list.first_child(&app), Some(first));
927        assert!(list.keep_alive_children(&app).is_empty());
928        assert!(list.as_object().paints_child(&app, first.as_object()));
929        assert!(
930            !manager.created.borrow()[created_before..].contains(&0),
931            "the kept-alive child was rebuilt"
932        );
933    }
934
935    /// A list shorter than the viewport reports underflow and its precise extent.
936    #[test]
937    fn a_short_list_reports_underflow() {
938        let cell = AppCell::new();
939        let mut app = cell.borrow_mut();
940        let (list, manager, _harness) = fixed_list(&mut app, vec![50.0; 2], 50.0);
941
942        assert_eq!(list.geometry(&app).scroll_extent, 100.0);
943        assert_eq!(list.geometry(&app).paint_extent, 100.0);
944        assert!(manager.did_underflow.get());
945    }
946
947    /// `RenderSliverVariedExtentList` asks its builder for each item's extent.
948    #[test]
949    fn a_varied_extent_list_uses_its_builder() {
950        let cell = AppCell::new();
951        let mut app = cell.borrow_mut();
952        let manager = TestChildManager::<RenderSliverVariedExtentList>::new(vec![40.0; 10]);
953        let builder: ItemExtentBuilder =
954            Rc::new(|index, _| Some(if index % 2 == 0 { 40.0 } else { 20.0 }));
955        let list = RenderSliverVariedExtentList::new(&mut app, manager.clone(), builder);
956        manager.attach(list);
957        let _harness = ScrollHarness::new(&mut app, list.as_sliver(), VIEWPORT);
958
959        // 40 + 20 + 40 + 20 = 120.
960        assert_eq!(list.index_to_layout_offset(&app, 4), 120.0);
961        assert_eq!(list.item_extent(&app), None);
962        assert_eq!(list.geometry(&app).paint_extent, 200.0);
963        // The manager estimates the total extent of its ten items.
964        assert_eq!(list.geometry(&app).scroll_extent, 400.0);
965    }
966
967    /// The minimum and maximum child indices bracket the visible window.
968    #[test]
969    fn the_child_index_range_brackets_the_scroll_offset() {
970        let cell = AppCell::new();
971        let mut app = cell.borrow_mut();
972        let (list, _, _harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
973        let constraints = list.constraints(&app);
974
975        assert_eq!(list.get_min_child_index_for_scroll_offset(&app, 120.0), 2);
976        assert_eq!(list.get_max_child_index_for_scroll_offset(&app, 120.0), 2);
977        assert_eq!(list.get_max_child_index_for_scroll_offset(&app, 0.0), 0);
978        assert_eq!(
979            list.compute_max_scroll_offset(&mut app, constraints),
980            2000.0
981        );
982    }
983}