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 debug_fill_properties(
628                self: $crate::RenderHandle<Self>,
629                app: &::waft_foundation::App,
630                properties: &mut ::waft_foundation::DiagnosticPropertiesBuilder,
631            ) {
632                $crate::RenderSliverMultiBoxAdaptor::debug_fill_properties(self, app, properties)
633            }
634
635            fn debug_describe_children(
636                self: $crate::RenderHandle<Self>,
637                app: &::waft_foundation::App,
638            ) -> ::std::vec::Vec<::std::rc::Rc<dyn ::waft_foundation::DiagnosticsNode>> {
639                $crate::RenderSliverMultiBoxAdaptor::debug_describe_children(self, app)
640            }
641
642            fn paint(
643                self: $crate::RenderHandle<Self>,
644                app: &mut ::waft_foundation::App,
645                context: &mut $crate::PaintingContext,
646                offset: ::waft_embedder::Offset,
647            ) {
648                $crate::RenderSliverMultiBoxAdaptor::paint(self, app, context, offset)
649            }
650
651            fn perform_layout(self: $crate::RenderHandle<Self>, app: &mut ::waft_foundation::App) {
652                $crate::RenderSliverFixedExtentBoxAdaptor::perform_layout(self, app)
653            }
654        }
655
656        impl $crate::RenderSliver for $leaf {
657            $crate::render_sliver_accessors!();
658
659            fn hit_test_children(
660                self: $crate::RenderHandle<Self>,
661                app: &mut ::waft_foundation::App,
662                result: &mut $crate::SliverHitTestResult<'_>,
663                main_axis_position: f64,
664                cross_axis_position: f64,
665            ) -> bool {
666                $crate::RenderSliverMultiBoxAdaptor::hit_test_children(
667                    self,
668                    app,
669                    result,
670                    main_axis_position,
671                    cross_axis_position,
672                )
673            }
674
675            fn child_main_axis_position(
676                self: $crate::RenderHandle<Self>,
677                app: &::waft_foundation::App,
678                child: $crate::AnyRenderObject,
679            ) -> f64 {
680                $crate::RenderSliverMultiBoxAdaptor::child_main_axis_position(self, app, child)
681            }
682
683            fn child_scroll_offset(
684                self: $crate::RenderHandle<Self>,
685                app: &::waft_foundation::App,
686                child: $crate::AnyRenderObject,
687            ) -> Option<f64> {
688                $crate::RenderSliverMultiBoxAdaptor::child_scroll_offset(self, app, child)
689            }
690        }
691    };
692}
693
694pub use fixed_extent_box_adaptor_leaf;
695
696/// A sliver that places multiple box children with the same main axis extent in a linear array.
697///
698/// [`RenderSliverFixedExtentList`] places its children in a linear array along the main axis
699/// starting at offset zero and without gaps. Each child is forced to have the
700/// [`item_extent`](Self::item_extent) in the main axis and the
701/// [`crate::SliverConstraints::cross_axis_extent`] in the cross axis.
702///
703/// [`RenderSliverFixedExtentList`] is more efficient than [`crate::RenderSliverList`] because it
704/// does not need to perform layout on its children to obtain their extent in the main axis.
705pub struct RenderSliverFixedExtentList {
706    render_object: RenderObjectData,
707    render_sliver: RenderSliverData,
708    container: ContainerRenderObjectData<AnyRenderBox>,
709    adaptor: RenderSliverMultiBoxAdaptorData,
710    fixed_extent: RenderSliverFixedExtentBoxAdaptorData,
711    item_extent: f64,
712}
713
714impl RenderSliverFixedExtentList {
715    /// Creates a sliver that contains multiple box children that have a given extent in the main
716    /// axis.
717    pub fn new(
718        app: &mut App,
719        child_manager: Rc<dyn RenderSliverBoxChildManager>,
720        item_extent: f64,
721    ) -> RenderHandle<RenderSliverFixedExtentList> {
722        RenderHandle::new_sliver(
723            app,
724            RenderSliverFixedExtentList {
725                render_object: RenderObjectData::new(),
726                render_sliver: RenderSliverData::new(),
727                container: ContainerRenderObjectData::new(),
728                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
729                fixed_extent: RenderSliverFixedExtentBoxAdaptorData::new(),
730                item_extent,
731            },
732        )
733    }
734
735    /// Sets [`RenderSliverFixedExtentBoxAdaptor::item_extent`].
736    pub fn set_item_extent(self: RenderHandle<Self>, app: &mut App, value: f64) {
737        if self.get(app).item_extent == value {
738            return;
739        }
740        self.get_mut(app).item_extent = value;
741        self.mark_needs_layout(app);
742    }
743}
744
745impl RenderSliverFixedExtentBoxAdaptor for RenderSliverFixedExtentList {
746    crate::render_sliver_fixed_extent_accessors!();
747
748    fn item_extent(self: RenderHandle<Self>, app: &App) -> Option<f64> {
749        Some(self.get(app).item_extent)
750    }
751}
752
753fixed_extent_box_adaptor_leaf!(RenderSliverFixedExtentList);
754
755/// A sliver that places multiple box children with the corresponding main axis extent in a linear
756/// array.
757pub struct RenderSliverVariedExtentList {
758    render_object: RenderObjectData,
759    render_sliver: RenderSliverData,
760    container: ContainerRenderObjectData<AnyRenderBox>,
761    adaptor: RenderSliverMultiBoxAdaptorData,
762    fixed_extent: RenderSliverFixedExtentBoxAdaptorData,
763    item_extent_builder: ItemExtentBuilder,
764}
765
766impl RenderSliverVariedExtentList {
767    /// Creates a sliver that contains multiple box children that have an explicit extent in the
768    /// main axis.
769    pub fn new(
770        app: &mut App,
771        child_manager: Rc<dyn RenderSliverBoxChildManager>,
772        item_extent_builder: ItemExtentBuilder,
773    ) -> RenderHandle<RenderSliverVariedExtentList> {
774        RenderHandle::new_sliver(
775            app,
776            RenderSliverVariedExtentList {
777                render_object: RenderObjectData::new(),
778                render_sliver: RenderSliverData::new(),
779                container: ContainerRenderObjectData::new(),
780                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
781                fixed_extent: RenderSliverFixedExtentBoxAdaptorData::new(),
782                item_extent_builder,
783            },
784        )
785    }
786
787    /// Sets [`RenderSliverFixedExtentBoxAdaptor::item_extent_builder`].
788    pub fn set_item_extent_builder(
789        self: RenderHandle<Self>,
790        app: &mut App,
791        value: ItemExtentBuilder,
792    ) {
793        if Rc::ptr_eq(&self.get(app).item_extent_builder, &value) {
794            return;
795        }
796        self.get_mut(app).item_extent_builder = value;
797        self.mark_needs_layout(app);
798    }
799}
800
801impl RenderSliverFixedExtentBoxAdaptor for RenderSliverVariedExtentList {
802    crate::render_sliver_fixed_extent_accessors!();
803
804    fn item_extent(self: RenderHandle<Self>, _app: &App) -> Option<f64> {
805        let _ = self;
806        None
807    }
808
809    fn item_extent_builder(self: RenderHandle<Self>, app: &App) -> Option<ItemExtentBuilder> {
810        Some(Rc::clone(&self.get(app).item_extent_builder))
811    }
812}
813
814fixed_extent_box_adaptor_leaf!(RenderSliverVariedExtentList);
815
816#[cfg(test)]
817mod tests {
818    use waft_embedder::Size;
819    use waft_foundation::AppCell;
820    use waft_gestures::HitTestResult;
821
822    use super::*;
823    use crate::object::ContainerRenderObjectMixin;
824    use crate::sliver::SliverHitTestResult;
825    use crate::sliver_multi_box_adaptor::test_support::TestChildManager;
826    use crate::sliver_multi_box_adaptor::viewport_test_support::ScrollHarness;
827
828    const VIEWPORT: Size = Size::new(100.0, 200.0);
829
830    fn fixed_list(
831        app: &mut App,
832        extents: Vec<f64>,
833        item_extent: f64,
834    ) -> (
835        RenderHandle<RenderSliverFixedExtentList>,
836        Rc<TestChildManager<RenderSliverFixedExtentList>>,
837        ScrollHarness,
838    ) {
839        let manager = TestChildManager::new(extents);
840        let list = RenderSliverFixedExtentList::new(app, manager.clone(), item_extent);
841        manager.attach(list);
842        let harness = ScrollHarness::new(app, list.as_sliver(), VIEWPORT);
843        (list, manager, harness)
844    }
845
846    /// `sliver_fixed_extent_list_test.dart`: only the children that fall in the viewport (plus
847    /// the cache area) are reified, and they are placed at multiples of the item extent.
848    #[test]
849    fn a_fixed_extent_list_reifies_only_the_visible_children() {
850        let cell = AppCell::new();
851        let mut app = cell.borrow_mut();
852        let (list, _, _harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
853
854        assert_eq!(
855            list.index_of(&app, list.first_child(&app).expect("built")),
856            0
857        );
858        assert_eq!(list.index_to_layout_offset(&app, 3), 150.0);
859        let geometry = list.geometry(&app);
860        assert_eq!(geometry.scroll_extent, 2000.0);
861        assert_eq!(geometry.paint_extent, 200.0);
862        assert!(geometry.has_visual_overflow);
863        // 200 pixels of viewport plus 250 of cache, at 50 pixels each, is far short of 40.
864        assert!(list.child_count(&app) < 40);
865    }
866
867    /// Scrolling collects the children that left the viewport and creates the ones that entered.
868    #[test]
869    fn scrolling_collects_and_creates_children() {
870        let cell = AppCell::new();
871        let mut app = cell.borrow_mut();
872        let (list, _, harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
873        assert_eq!(
874            list.index_of(&app, list.first_child(&app).expect("built")),
875            0
876        );
877
878        harness.scroll_to(&mut app, 600.0);
879
880        let first = list.first_child(&app).expect("children were created");
881        // 600 - 250 of leading cache = 350, which is index 7.
882        assert_eq!(list.index_of(&app, first), 7);
883        assert_eq!(
884            RenderSliver::child_scroll_offset(list, &app, first.as_object()),
885            Some(350.0)
886        );
887        assert_eq!(
888            RenderSliver::child_main_axis_position(list, &app, first.as_object()),
889            -250.0
890        );
891    }
892
893    /// A hit inside a reified child lands on the child and the sliver.
894    #[test]
895    fn a_fixed_extent_list_hit_tests_its_children() {
896        let cell = AppCell::new();
897        let mut app = cell.borrow_mut();
898        let (list, _, _harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
899
900        let mut result = HitTestResult::new();
901        let hit = list.hit_test(
902            &mut app,
903            &mut SliverHitTestResult::wrap(&mut result),
904            75.0,
905            20.0,
906        );
907
908        assert!(hit);
909        assert_eq!(result.path().len(), 2);
910    }
911
912    /// A child whose parent data asks to be kept alive moves to the keep-alive bucket instead of
913    /// being destroyed, and comes back out of it when it is needed again.
914    #[test]
915    fn a_kept_alive_child_survives_leaving_the_viewport() {
916        let cell = AppCell::new();
917        let mut app = cell.borrow_mut();
918        let (list, manager, harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
919        let first = list.first_child(&app).expect("children were created");
920        first
921            .as_object()
922            .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(&mut app)
923            .set_keep_alive(true);
924
925        harness.scroll_to(&mut app, 1000.0);
926
927        // The child is out of the child list but still attached, in the keep-alive bucket.
928        assert_eq!(list.keep_alive_children(&app), vec![first]);
929        assert!(
930            first
931                .as_object()
932                .parent_data_of::<SliverMultiBoxAdaptorParentData>(&app)
933                .kept_alive()
934        );
935        assert!(!list.as_object().paints_child(&app, first.as_object()));
936        let created_before = manager.created.borrow().len();
937
938        harness.scroll_to(&mut app, 0.0);
939
940        // Index 0 came back from the bucket, so the manager was not asked to create it again.
941        assert_eq!(list.first_child(&app), Some(first));
942        assert!(list.keep_alive_children(&app).is_empty());
943        assert!(list.as_object().paints_child(&app, first.as_object()));
944        assert!(
945            !manager.created.borrow()[created_before..].contains(&0),
946            "the kept-alive child was rebuilt"
947        );
948    }
949
950    /// A list shorter than the viewport reports underflow and its precise extent.
951    #[test]
952    fn a_short_list_reports_underflow() {
953        let cell = AppCell::new();
954        let mut app = cell.borrow_mut();
955        let (list, manager, _harness) = fixed_list(&mut app, vec![50.0; 2], 50.0);
956
957        assert_eq!(list.geometry(&app).scroll_extent, 100.0);
958        assert_eq!(list.geometry(&app).paint_extent, 100.0);
959        assert!(manager.did_underflow.get());
960    }
961
962    /// `RenderSliverVariedExtentList` asks its builder for each item's extent.
963    #[test]
964    fn a_varied_extent_list_uses_its_builder() {
965        let cell = AppCell::new();
966        let mut app = cell.borrow_mut();
967        let manager = TestChildManager::<RenderSliverVariedExtentList>::new(vec![40.0; 10]);
968        let builder: ItemExtentBuilder =
969            Rc::new(|index, _| Some(if index % 2 == 0 { 40.0 } else { 20.0 }));
970        let list = RenderSliverVariedExtentList::new(&mut app, manager.clone(), builder);
971        manager.attach(list);
972        let _harness = ScrollHarness::new(&mut app, list.as_sliver(), VIEWPORT);
973
974        // 40 + 20 + 40 + 20 = 120.
975        assert_eq!(list.index_to_layout_offset(&app, 4), 120.0);
976        assert_eq!(list.item_extent(&app), None);
977        assert_eq!(list.geometry(&app).paint_extent, 200.0);
978        // The manager estimates the total extent of its ten items.
979        assert_eq!(list.geometry(&app).scroll_extent, 400.0);
980    }
981
982    /// The minimum and maximum child indices bracket the visible window.
983    #[test]
984    fn the_child_index_range_brackets_the_scroll_offset() {
985        let cell = AppCell::new();
986        let mut app = cell.borrow_mut();
987        let (list, _, _harness) = fixed_list(&mut app, vec![50.0; 40], 50.0);
988        let constraints = list.constraints(&app);
989
990        assert_eq!(list.get_min_child_index_for_scroll_offset(&app, 120.0), 2);
991        assert_eq!(list.get_max_child_index_for_scroll_offset(&app, 120.0), 2);
992        assert_eq!(list.get_max_child_index_for_scroll_offset(&app, 0.0), 0);
993        assert_eq!(
994            list.compute_max_scroll_offset(&mut app, constraints),
995            2000.0
996        );
997    }
998}