Skip to main content

waft_rendering/
sliver_list.rs

1//! Flutter counterpart: `rendering/sliver_list.dart`.
2
3use std::rc::Rc;
4
5use waft_embedder::{Matrix4, Offset};
6use waft_foundation::{
7    App, DiagnosticPropertiesBuilder, DiagnosticsNode, Handle, PRECISION_ERROR_TOLERANCE,
8};
9
10use crate::box_::AnyRenderBox;
11use crate::object::{
12    AnyRenderObject, ContainerRenderObjectData, ContainerRenderObjectMixin, RenderHandle,
13    RenderObject, RenderObjectData,
14};
15use crate::painting_context::PaintingContext;
16use crate::pipeline_owner::PipelineOwner;
17use crate::sliver::{
18    RenderSliver, RenderSliverData, RenderSliverHelpers, SliverGeometry, SliverHitTestResult,
19};
20use crate::sliver_multi_box_adaptor::{
21    RenderSliverBoxChildManager, RenderSliverMultiBoxAdaptor, RenderSliverMultiBoxAdaptorData,
22    RenderSliverWithKeepAliveMixin, SliverMultiBoxAdaptorParentData,
23};
24
25/// A sliver that places multiple box children in a linear array along the main axis.
26///
27/// Each child is forced to have the [`crate::SliverConstraints::cross_axis_extent`] in the cross
28/// axis but determines its own main axis extent.
29///
30/// [`RenderSliverList`] determines its scroll offset by "dead reckoning" because children outside
31/// the visible part of the sliver are not materialized, which means [`RenderSliverList`] cannot
32/// learn their main axis extent. Instead, newly materialized children are placed adjacent to
33/// existing children.
34pub struct RenderSliverList {
35    render_object: RenderObjectData,
36    render_sliver: RenderSliverData,
37    container: ContainerRenderObjectData<AnyRenderBox>,
38    adaptor: RenderSliverMultiBoxAdaptorData,
39}
40
41impl RenderSliverList {
42    /// Creates a sliver that places multiple box children in a linear array along the main axis.
43    pub fn new(
44        app: &mut App,
45        child_manager: Rc<dyn RenderSliverBoxChildManager>,
46    ) -> RenderHandle<RenderSliverList> {
47        RenderHandle::new_sliver(
48            app,
49            RenderSliverList {
50                render_object: RenderObjectData::new(),
51                render_sliver: RenderSliverData::new(),
52                container: ContainerRenderObjectData::new(),
53                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
54            },
55        )
56    }
57}
58
59impl ContainerRenderObjectMixin for RenderSliverList {
60    type ChildType = AnyRenderBox;
61    type ParentDataType = SliverMultiBoxAdaptorParentData;
62
63    fn container_data(
64        self: RenderHandle<Self>,
65        app: &App,
66    ) -> &ContainerRenderObjectData<AnyRenderBox> {
67        &self.get(app).container
68    }
69
70    fn container_data_mut(
71        self: RenderHandle<Self>,
72        app: &mut App,
73    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
74        &mut self.get_mut(app).container
75    }
76
77    fn insert(
78        self: RenderHandle<Self>,
79        app: &mut App,
80        child: AnyRenderBox,
81        after: Option<AnyRenderBox>,
82    ) {
83        RenderSliverMultiBoxAdaptor::insert(self, app, child, after)
84    }
85
86    fn move_child(
87        self: RenderHandle<Self>,
88        app: &mut App,
89        child: AnyRenderBox,
90        after: Option<AnyRenderBox>,
91    ) {
92        RenderSliverMultiBoxAdaptor::move_child(self, app, child, after)
93    }
94
95    fn remove(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
96        RenderSliverMultiBoxAdaptor::remove(self, app, child)
97    }
98
99    fn remove_all(self: RenderHandle<Self>, app: &mut App) {
100        RenderSliverMultiBoxAdaptor::remove_all(self, app)
101    }
102}
103
104impl RenderSliverHelpers for RenderSliverList {}
105
106impl RenderSliverWithKeepAliveMixin for RenderSliverList {}
107
108impl RenderSliverMultiBoxAdaptor for RenderSliverList {
109    crate::render_sliver_multi_box_adaptor_accessors!();
110}
111
112impl RenderObject for RenderSliverList {
113    crate::render_object_accessors!();
114
115    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
116        RenderSliverMultiBoxAdaptor::setup_parent_data(self, app, child);
117        RenderSliverWithKeepAliveMixin::setup_parent_data(self, app, child);
118    }
119
120    fn visit_children(
121        self: RenderHandle<Self>,
122        app: &App,
123        visitor: &mut dyn FnMut(AnyRenderObject),
124    ) {
125        RenderSliverMultiBoxAdaptor::visit_children(self, app, visitor)
126    }
127
128    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
129        RenderSliverMultiBoxAdaptor::did_attach(self, app, owner)
130    }
131
132    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
133        RenderSliverMultiBoxAdaptor::did_detach(self, app)
134    }
135
136    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
137        RenderSliverMultiBoxAdaptor::redepth_children(self, app)
138    }
139
140    fn apply_paint_transform(
141        self: RenderHandle<Self>,
142        app: &App,
143        child: AnyRenderObject,
144        transform: &mut Matrix4,
145    ) {
146        RenderSliverMultiBoxAdaptor::apply_paint_transform(self, app, child, transform)
147    }
148
149    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
150        RenderSliverMultiBoxAdaptor::paints_child(self, app, child)
151    }
152
153    fn debug_fill_properties(
154        self: RenderHandle<Self>,
155        app: &App,
156        properties: &mut DiagnosticPropertiesBuilder,
157    ) {
158        RenderSliverMultiBoxAdaptor::debug_fill_properties(self, app, properties)
159    }
160
161    fn debug_describe_children(
162        self: RenderHandle<Self>,
163        app: &App,
164    ) -> Vec<Rc<dyn DiagnosticsNode>> {
165        RenderSliverMultiBoxAdaptor::debug_describe_children(self, app)
166    }
167
168    fn paint(
169        self: RenderHandle<Self>,
170        app: &mut App,
171        context: &mut PaintingContext,
172        offset: Offset,
173    ) {
174        RenderSliverMultiBoxAdaptor::paint(self, app, context, offset)
175    }
176
177    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
178        let constraints = self.constraints(app);
179        let child_manager = self.child_manager(app);
180        child_manager.did_start_layout(app);
181        child_manager.set_did_underflow(app, false);
182
183        let scroll_offset = constraints.scroll_offset + constraints.cache_origin;
184        debug_assert!(scroll_offset >= 0.0);
185        let remaining_extent = constraints.remaining_cache_extent;
186        debug_assert!(remaining_extent >= 0.0);
187        let target_end_scroll_offset = scroll_offset + remaining_extent;
188        let child_constraints = constraints.as_box_constraints(0.0, f64::INFINITY, None);
189        let mut leading_garbage = 0;
190        let mut trailing_garbage = 0;
191        let mut reached_end = false;
192
193        // This algorithm in principle is straight-forward: find the first child that overlaps the
194        // given scroll_offset, creating more children at the top of the list if necessary, then
195        // walk down the list updating and laying out each child and adding more at the end if
196        // necessary until we have enough children to cover the entire viewport.
197        //
198        // It is complicated by one minor issue, which is that any time you update or create a
199        // child, it's possible that some of the children that haven't yet been laid out will be
200        // removed, leaving the list in an inconsistent state, and requiring that missing nodes be
201        // recreated.
202        //
203        // To keep this mess tractable, this algorithm starts from what is currently the first
204        // child, if any, and then walks up and/or down from there, so that the nodes that might
205        // get removed are always at the edges of what has already been laid out.
206
207        // Make sure we have at least one child to start from.
208        if self.first_child(app).is_none() && !self.add_initial_child(app, 0, 0.0) {
209            // There are no children.
210            self.set_geometry(app, SliverGeometry::ZERO);
211            child_manager.did_finish_layout(app);
212            return;
213        }
214
215        // We have at least one child.
216
217        // These variables track the range of children that we have laid out. Within this range,
218        // the children have consecutive indices. Outside this range, it's possible for a child to
219        // get removed without notice.
220        let mut leading_child_with_layout: Option<AnyRenderBox> = None;
221        let mut trailing_child_with_layout: Option<AnyRenderBox> = None;
222
223        let mut earliest_useful_child = self.first_child(app);
224
225        // A first child with no layout offset is likely a result of children reordering.
226        //
227        // We rely on the first child to have an accurate layout offset. In the case of no layout
228        // offset, we have to find the first child that has a valid layout offset.
229        let first_child = self.first_child(app).expect("checked above");
230        if RenderSliver::child_scroll_offset(self, app, first_child.as_object()).is_none() {
231            let mut leading_children_without_layout_offset = 0;
232            while let Some(current) = earliest_useful_child {
233                if RenderSliver::child_scroll_offset(self, app, current.as_object()).is_some() {
234                    break;
235                }
236                earliest_useful_child = self.child_after(app, current);
237                leading_children_without_layout_offset += 1;
238            }
239            // We should be able to destroy children with no layout offset safely, because they
240            // are likely outside of the viewport.
241            self.collect_garbage(app, leading_children_without_layout_offset, 0);
242            // If we cannot find a valid layout offset, start from the initial child.
243            if self.first_child(app).is_none() && !self.add_initial_child(app, 0, 0.0) {
244                // There are no children.
245                self.set_geometry(app, SliverGeometry::ZERO);
246                child_manager.did_finish_layout(app);
247                return;
248            }
249        }
250
251        // Find the last child that is at or before the scroll offset.
252        earliest_useful_child = self.first_child(app);
253        loop {
254            let current = earliest_useful_child.expect("the child list is not empty");
255            let earliest_scroll_offset =
256                RenderSliver::child_scroll_offset(self, app, current.as_object())
257                    .expect("a laid-out child has a scroll offset");
258            if earliest_scroll_offset <= scroll_offset {
259                break;
260            }
261            // We have to add children before the earliest useful child.
262            earliest_useful_child =
263                self.insert_and_layout_leading_child(app, child_constraints, true);
264            let Some(inserted) = earliest_useful_child else {
265                let first_child = self.first_child(app).expect("the child list is not empty");
266                first_child
267                    .as_object()
268                    .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
269                    .set_layout_offset(Some(0.0));
270
271                if scroll_offset == 0.0 {
272                    // insert_and_layout_leading_child only lays out the children before the first
273                    // child. In this case, nothing has been laid out. We have to lay out the
274                    // first child manually.
275                    first_child.layout(app, child_constraints, true);
276                    leading_child_with_layout = Some(first_child);
277                    trailing_child_with_layout.get_or_insert(first_child);
278                    break;
279                }
280                // We ran out of children before reaching the scroll offset. We must inform our
281                // parent that this sliver cannot fulfill its contract and that we need a scroll
282                // offset correction.
283                self.set_geometry(
284                    app,
285                    SliverGeometry::builder()
286                        .scroll_offset_correction(-scroll_offset)
287                        .build(),
288                );
289                return;
290            };
291
292            let first_child = self.first_child(app).expect("the child list is not empty");
293            let first_child_scroll_offset =
294                earliest_scroll_offset - self.paint_extent_of(app, first_child);
295            // first_child_scroll_offset may contain double precision error
296            if first_child_scroll_offset < -PRECISION_ERROR_TOLERANCE {
297                // Let's assume there is no child before the first child. We will correct it on
298                // the next layout if it is not.
299                self.set_geometry(
300                    app,
301                    SliverGeometry::builder()
302                        .scroll_offset_correction(-first_child_scroll_offset)
303                        .build(),
304                );
305                first_child
306                    .as_object()
307                    .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
308                    .set_layout_offset(Some(0.0));
309                return;
310            }
311
312            inserted
313                .as_object()
314                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
315                .set_layout_offset(Some(first_child_scroll_offset));
316            debug_assert_eq!(Some(inserted), self.first_child(app));
317            leading_child_with_layout = Some(inserted);
318            trailing_child_with_layout.get_or_insert(inserted);
319        }
320
321        debug_assert!(
322            RenderSliver::child_scroll_offset(
323                self,
324                app,
325                self.first_child(app).expect("not empty").as_object()
326            )
327            .expect("laid out")
328                > -PRECISION_ERROR_TOLERANCE
329        );
330
331        // If the scroll offset is at zero, we should make sure we are actually at the beginning
332        // of the list.
333        if scroll_offset < PRECISION_ERROR_TOLERANCE {
334            // We iterate from the first child in case the leading child has a 0 paint extent.
335            loop {
336                let first_child = self.first_child(app).expect("the child list is not empty");
337                if self.index_of(app, first_child) <= 0 {
338                    break;
339                }
340                let earliest_scroll_offset =
341                    RenderSliver::child_scroll_offset(self, app, first_child.as_object())
342                        .expect("laid out");
343                // We correct one child at a time. If there are more children before the earliest
344                // useful child, we will correct it once the scroll offset reaches zero again.
345                let inserted = self.insert_and_layout_leading_child(app, child_constraints, true);
346                debug_assert!(inserted.is_some());
347                let first_child = self.first_child(app).expect("the child list is not empty");
348                let first_child_scroll_offset =
349                    earliest_scroll_offset - self.paint_extent_of(app, first_child);
350                first_child
351                    .as_object()
352                    .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
353                    .set_layout_offset(Some(0.0));
354                // We only need to correct if the leading child actually has a paint extent.
355                if first_child_scroll_offset < -PRECISION_ERROR_TOLERANCE {
356                    self.set_geometry(
357                        app,
358                        SliverGeometry::builder()
359                            .scroll_offset_correction(-first_child_scroll_offset)
360                            .build(),
361                    );
362                    return;
363                }
364            }
365        }
366
367        // At this point, the earliest useful child is the first child, and is a child whose
368        // scroll offset is at or before the scroll offset, and leading_child_with_layout and
369        // trailing_child_with_layout are either None or cover a range of render boxes that we
370        // have laid out with the first being the same as the earliest useful child and the last
371        // being either at or after the scroll offset.
372        let earliest_useful_child = self.first_child(app).expect("the child list is not empty");
373
374        // Make sure we've laid out at least one child. Dart also assigns
375        // `leadingChildWithLayout` here; nothing reads it after this point.
376        if leading_child_with_layout.is_none() {
377            earliest_useful_child.layout(app, child_constraints, true);
378            trailing_child_with_layout = Some(earliest_useful_child);
379        }
380
381        // Here, the earliest useful child is still the first child, it's got a scroll offset that
382        // is at or before our actual scroll offset, and it has been laid out, and is in fact our
383        // leading child with layout. It's possible that some children beyond that one have also
384        // been laid out.
385        let mut in_layout_range = true;
386        let mut child = Some(earliest_useful_child);
387        let mut index = self.index_of(app, earliest_useful_child);
388        let mut end_scroll_offset =
389            RenderSliver::child_scroll_offset(self, app, earliest_useful_child.as_object())
390                .expect("laid out")
391                + self.paint_extent_of(app, earliest_useful_child);
392
393        // Dart's local `advance()`, which is used in two different places below.
394        let advance = |app: &mut App,
395                       child: &mut Option<AnyRenderBox>,
396                       index: &mut i32,
397                       end_scroll_offset: &mut f64,
398                       in_layout_range: &mut bool,
399                       trailing_child_with_layout: &mut Option<AnyRenderBox>|
400         -> bool {
401            // returns true if we advanced, false if we have no more children
402            let current = child.expect("advance is only called with a child");
403            if Some(current) == *trailing_child_with_layout {
404                *in_layout_range = false;
405            }
406            *child = self.child_after(app, current);
407            if child.is_none() {
408                *in_layout_range = false;
409            }
410            *index += 1;
411            if !*in_layout_range {
412                if child.is_none_or(|current| self.index_of(app, current) != *index) {
413                    // We are missing a child. Insert it (and lay it out) if possible.
414                    *child = self.insert_and_layout_child(
415                        app,
416                        child_constraints,
417                        *trailing_child_with_layout,
418                        true,
419                    );
420                    if child.is_none() {
421                        // We have run out of children.
422                        return false;
423                    }
424                } else {
425                    // Lay out the child.
426                    child.expect("checked").layout(app, child_constraints, true);
427                }
428                *trailing_child_with_layout = *child;
429            }
430            let current = child.expect("set above");
431            let child_parent_data = current
432                .as_object()
433                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app);
434            child_parent_data.set_layout_offset(Some(*end_scroll_offset));
435            debug_assert_eq!(child_parent_data.index, Some(*index));
436            *end_scroll_offset = RenderSliver::child_scroll_offset(self, app, current.as_object())
437                .expect("just set")
438                + self.paint_extent_of(app, current);
439            true
440        };
441
442        // Find the first child that ends after the scroll offset.
443        while end_scroll_offset < scroll_offset {
444            leading_garbage += 1;
445            if !advance(
446                app,
447                &mut child,
448                &mut index,
449                &mut end_scroll_offset,
450                &mut in_layout_range,
451                &mut trailing_child_with_layout,
452            ) {
453                debug_assert_eq!(leading_garbage, self.child_count(app));
454                debug_assert!(child.is_none());
455                // we want to make sure we keep the last child around so we know the end scroll
456                // offset
457                self.collect_garbage(app, leading_garbage - 1, 0);
458                debug_assert_eq!(self.first_child(app), self.last_child(app));
459                let last_child = self.last_child(app).expect("one child is kept");
460                let extent = RenderSliver::child_scroll_offset(self, app, last_child.as_object())
461                    .expect("laid out")
462                    + self.paint_extent_of(app, last_child);
463                self.set_geometry(
464                    app,
465                    SliverGeometry::builder()
466                        .scroll_extent(extent)
467                        .max_paint_extent(extent)
468                        .build(),
469                );
470                return;
471            }
472        }
473
474        // Now find the first child that ends after our end.
475        while end_scroll_offset < target_end_scroll_offset {
476            if !advance(
477                app,
478                &mut child,
479                &mut index,
480                &mut end_scroll_offset,
481                &mut in_layout_range,
482                &mut trailing_child_with_layout,
483            ) {
484                reached_end = true;
485                break;
486            }
487        }
488
489        // Finally count up all the remaining children and label them as garbage.
490        if let Some(current) = child {
491            let mut walker = self.child_after(app, current);
492            while let Some(current) = walker {
493                trailing_garbage += 1;
494                walker = self.child_after(app, current);
495            }
496        }
497
498        // At this point everything should be good to go, we just have to clean up the garbage and
499        // report the geometry.
500        self.collect_garbage(app, leading_garbage, trailing_garbage);
501
502        debug_assert!(self.debug_assert_child_list_is_non_empty_and_contiguous(app));
503        let first_child = self.first_child(app).expect("not empty");
504        let last_child = self.last_child(app).expect("not empty");
505        let leading_scroll_offset =
506            RenderSliver::child_scroll_offset(self, app, first_child.as_object())
507                .expect("laid out");
508        let estimated_max_scroll_offset = if reached_end {
509            end_scroll_offset
510        } else {
511            let estimated = child_manager.estimate_max_scroll_offset(
512                app,
513                constraints,
514                Some(self.index_of(app, first_child)),
515                Some(self.index_of(app, last_child)),
516                Some(leading_scroll_offset),
517                Some(end_scroll_offset),
518            );
519            debug_assert!(estimated >= end_scroll_offset - leading_scroll_offset);
520            estimated
521        };
522        let paint_extent =
523            self.calculate_paint_offset(app, constraints, leading_scroll_offset, end_scroll_offset);
524        let cache_extent =
525            self.calculate_cache_offset(app, constraints, leading_scroll_offset, end_scroll_offset);
526        let target_end_scroll_offset_for_paint =
527            constraints.scroll_offset + constraints.remaining_paint_extent;
528        self.set_geometry(
529            app,
530            SliverGeometry::builder()
531                .scroll_extent(estimated_max_scroll_offset)
532                .paint_extent(paint_extent)
533                .cache_extent(cache_extent)
534                .max_paint_extent(estimated_max_scroll_offset)
535                // Conservative to avoid flickering away the clip during scroll.
536                .has_visual_overflow(
537                    end_scroll_offset > target_end_scroll_offset_for_paint
538                        || constraints.scroll_offset > 0.0,
539                )
540                .build(),
541        );
542
543        // We may have started the layout while scrolled to the end, which would not expose a new
544        // child.
545        if estimated_max_scroll_offset == end_scroll_offset {
546            child_manager.set_did_underflow(app, true);
547        }
548        child_manager.did_finish_layout(app);
549    }
550}
551
552impl RenderSliver for RenderSliverList {
553    crate::render_sliver_accessors!();
554
555    fn hit_test_children(
556        self: RenderHandle<Self>,
557        app: &mut App,
558        result: &mut SliverHitTestResult<'_>,
559        main_axis_position: f64,
560        cross_axis_position: f64,
561    ) -> bool {
562        RenderSliverMultiBoxAdaptor::hit_test_children(
563            self,
564            app,
565            result,
566            main_axis_position,
567            cross_axis_position,
568        )
569    }
570
571    fn child_main_axis_position(
572        self: RenderHandle<Self>,
573        app: &App,
574        child: AnyRenderObject,
575    ) -> f64 {
576        RenderSliverMultiBoxAdaptor::child_main_axis_position(self, app, child)
577    }
578
579    fn child_scroll_offset(
580        self: RenderHandle<Self>,
581        app: &App,
582        child: AnyRenderObject,
583    ) -> Option<f64> {
584        RenderSliverMultiBoxAdaptor::child_scroll_offset(self, app, child)
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use waft_embedder::Size;
591    use waft_foundation::AppCell;
592    use waft_gestures::HitTestResult;
593
594    use super::*;
595    use crate::sliver_multi_box_adaptor::test_support::TestChildManager;
596    use crate::sliver_multi_box_adaptor::viewport_test_support::ScrollHarness;
597
598    const VIEWPORT: Size = Size::new(100.0, 200.0);
599
600    fn sliver_list(
601        app: &mut App,
602        extents: Vec<f64>,
603    ) -> (
604        RenderHandle<RenderSliverList>,
605        Rc<TestChildManager<RenderSliverList>>,
606        ScrollHarness,
607    ) {
608        let manager = TestChildManager::new(extents);
609        let list = RenderSliverList::new(app, manager.clone());
610        manager.attach(list);
611        let harness = ScrollHarness::new(app, list.as_sliver(), VIEWPORT);
612        (list, manager, harness)
613    }
614
615    /// `sliver_list_test.dart`: children of differing extents are placed one after the other, and
616    /// each child's layout offset is the sum of the extents before it.
617    #[test]
618    fn a_sliver_list_stacks_children_of_differing_extents() {
619        let cell = AppCell::new();
620        let mut app = cell.borrow_mut();
621        let (list, _, _harness) = sliver_list(&mut app, vec![40.0, 60.0, 80.0, 100.0, 120.0]);
622
623        let first = list.first_child(&app).expect("children were created");
624        let second = list.child_after(&app, first).expect("two children");
625        let third = list.child_after(&app, second).expect("three children");
626        assert_eq!(
627            RenderSliver::child_scroll_offset(list, &app, first.as_object()),
628            Some(0.0)
629        );
630        assert_eq!(
631            RenderSliver::child_scroll_offset(list, &app, second.as_object()),
632            Some(40.0)
633        );
634        assert_eq!(
635            RenderSliver::child_scroll_offset(list, &app, third.as_object()),
636            Some(100.0)
637        );
638        assert_eq!(list.geometry(&app).paint_extent, 200.0);
639        assert!(list.geometry(&app).has_visual_overflow);
640    }
641
642    /// A list that fits inside the viewport reports its exact extent and no overflow.
643    #[test]
644    fn a_short_sliver_list_reports_its_exact_extent() {
645        let cell = AppCell::new();
646        let mut app = cell.borrow_mut();
647        let (list, manager, _harness) = sliver_list(&mut app, vec![40.0, 60.0]);
648
649        let geometry = list.geometry(&app);
650        assert_eq!(geometry.scroll_extent, 100.0);
651        assert_eq!(geometry.paint_extent, 100.0);
652        assert!(!geometry.has_visual_overflow);
653        assert_eq!(list.child_count(&app), 2);
654        assert!(manager.did_underflow.get());
655    }
656
657    /// Scrolling drops the children that left the cache area and creates the ones that entered.
658    #[test]
659    fn scrolling_a_sliver_list_replaces_its_children() {
660        let cell = AppCell::new();
661        let mut app = cell.borrow_mut();
662        let (list, _, harness) = sliver_list(&mut app, vec![100.0; 30]);
663        assert_eq!(
664            list.index_of(&app, list.first_child(&app).expect("built")),
665            0
666        );
667
668        harness.scroll_to(&mut app, 1500.0);
669
670        let first = list.first_child(&app).expect("children were created");
671        // 1500 - 250 of leading cache = 1250, which is inside index 12.
672        assert_eq!(list.index_of(&app, first), 12);
673        assert!(list.geometry(&app).has_visual_overflow);
674    }
675
676    /// A hit inside a reified child lands on the child and the sliver.
677    #[test]
678    fn a_sliver_list_hit_tests_its_children() {
679        let cell = AppCell::new();
680        let mut app = cell.borrow_mut();
681        let (list, _, _harness) = sliver_list(&mut app, vec![50.0; 20]);
682
683        let mut result = HitTestResult::new();
684        let hit = list.hit_test(
685            &mut app,
686            &mut SliverHitTestResult::wrap(&mut result),
687            120.0,
688            10.0,
689        );
690
691        assert!(hit);
692        assert_eq!(result.path().len(), 2);
693    }
694
695    /// A kept-alive child is moved to the bucket rather than destroyed when it scrolls away.
696    #[test]
697    fn a_sliver_list_keeps_a_child_alive() {
698        let cell = AppCell::new();
699        let mut app = cell.borrow_mut();
700        let (list, _, harness) = sliver_list(&mut app, vec![100.0; 30]);
701        let first = list.first_child(&app).expect("children were created");
702        first
703            .as_object()
704            .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(&mut app)
705            .set_keep_alive(true);
706
707        harness.scroll_to(&mut app, 2000.0);
708
709        assert_eq!(list.keep_alive_children(&app), vec![first]);
710        assert!(first.as_object().attached(&app));
711
712        // `keep_alive_test.dart`: live children are named by index, and a kept-alive child is
713        // named by index after them, marked with the offstage style (`╌`).
714        let dump = list
715            .as_object()
716            .to_string_deep_with(&app, waft_foundation::DiagnosticLevel::Info);
717        assert!(dump.contains("currently live children: "), "{dump}");
718        assert!(
719            dump.lines()
720                .any(|line| line.contains("child with index 24: TestChild#")),
721            "{dump}"
722        );
723        assert!(
724            dump.lines().any(|line| line
725                .contains("╌child with index 0 (kept alive but not laid out): TestChild#")),
726            "{dump}"
727        );
728    }
729}