Skip to main content

waft_rendering/
sliver_fill.rs

1//! Flutter counterpart: `rendering/sliver_fill.dart`.
2//!
3//! `RenderSliverFillViewport.visitChildrenForSemantics` and the semantics update its
4//! `allowImplicitScrolling` setter asks for wait for accessibility.
5
6use std::rc::Rc;
7
8use waft_embedder::{Matrix4, Offset};
9use waft_foundation::App;
10use waft_painting::{Axis, AxisDirection};
11
12use crate::box_::AnyRenderBox;
13use crate::object::{
14    AnyRenderObject, ContainerRenderObjectData, RenderHandle, RenderObject, RenderObjectData,
15    RenderObjectWithChildData, RenderObjectWithChildMixin,
16};
17use crate::painting_context::PaintingContext;
18use crate::sliver::{
19    RenderSliver, RenderSliverData, RenderSliverHelpers, RenderSliverSingleBoxAdapter,
20    RenderSliverSingleBoxAdapterBase, SliverConstraints, SliverGeometry, SliverHitTestResult,
21    SliverPhysicalParentData, apply_growth_direction_to_axis_direction, calculate_cache_offset,
22    calculate_paint_offset,
23};
24use crate::sliver_fixed_extent_list::{
25    RenderSliverFixedExtentBoxAdaptor, RenderSliverFixedExtentBoxAdaptorData,
26    fixed_extent_box_adaptor_leaf,
27};
28use crate::sliver_multi_box_adaptor::{
29    RenderSliverBoxChildManager, RenderSliverMultiBoxAdaptorData,
30};
31
32/// A sliver that contains multiple box children that each fill the viewport.
33///
34/// [`RenderSliverFillViewport`] places its children in a linear array along the main axis. Each
35/// child is sized to fill the viewport, both in the main and cross axis. A
36/// [`viewport_fraction`](Self::viewport_fraction) factor can be provided to size the children to
37/// a multiple of the viewport's main axis dimension (typically a fraction less than 1.0).
38///
39/// See also:
40///
41///  * [`RenderSliverFillRemaining`], which sizes the children based on the remaining space rather
42///    than the viewport itself.
43///  * [`crate::RenderSliverFixedExtentList`], which has a configurable item extent.
44///  * [`crate::RenderSliverList`], which does not require its children to have the same extent
45///    in the main axis.
46pub struct RenderSliverFillViewport {
47    render_object: RenderObjectData,
48    render_sliver: RenderSliverData,
49    container: ContainerRenderObjectData<AnyRenderBox>,
50    adaptor: RenderSliverMultiBoxAdaptorData,
51    fixed_extent: RenderSliverFixedExtentBoxAdaptorData,
52    viewport_fraction: f64,
53    allow_implicit_scrolling: bool,
54}
55
56impl RenderSliverFillViewport {
57    /// Creates a sliver that contains multiple box children that each fill the viewport.
58    ///
59    /// Dart's defaults: `viewport_fraction` 1.0, `allow_implicit_scrolling` true.
60    pub fn new(
61        app: &mut App,
62        child_manager: Rc<dyn RenderSliverBoxChildManager>,
63        viewport_fraction: f64,
64        allow_implicit_scrolling: bool,
65    ) -> RenderHandle<RenderSliverFillViewport> {
66        debug_assert!(viewport_fraction > 0.0);
67        RenderHandle::new_sliver(
68            app,
69            RenderSliverFillViewport {
70                render_object: RenderObjectData::new(),
71                render_sliver: RenderSliverData::new(),
72                container: ContainerRenderObjectData::new(),
73                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
74                fixed_extent: RenderSliverFixedExtentBoxAdaptorData::new(),
75                viewport_fraction,
76                allow_implicit_scrolling,
77            },
78        )
79    }
80
81    /// The fraction of the viewport that each child should fill in the main axis.
82    ///
83    /// If this fraction is less than 1.0, more than one child will be visible at once. If this
84    /// fraction is greater than 1.0, each child will be larger than the viewport in the main
85    /// axis.
86    pub fn viewport_fraction(self: RenderHandle<Self>, app: &App) -> f64 {
87        self.get(app).viewport_fraction
88    }
89
90    /// See [`viewport_fraction`](Self::viewport_fraction).
91    pub fn set_viewport_fraction(self: RenderHandle<Self>, app: &mut App, value: f64) {
92        if self.get(app).viewport_fraction == value {
93            return;
94        }
95        self.get_mut(app).viewport_fraction = value;
96        self.mark_needs_layout(app);
97    }
98
99    /// Whether the pages answer implicit scrolling, as `PageView::allow_implicit_scrolling`
100    /// describes.
101    ///
102    /// This is typically used by assistive technologies, such as screen readers.
103    pub fn allow_implicit_scrolling(self: RenderHandle<Self>, app: &App) -> bool {
104        self.get(app).allow_implicit_scrolling
105    }
106
107    /// See [`allow_implicit_scrolling`](Self::allow_implicit_scrolling).
108    pub fn set_allow_implicit_scrolling(self: RenderHandle<Self>, app: &mut App, value: bool) {
109        if self.get(app).allow_implicit_scrolling == value {
110            return;
111        }
112        self.get_mut(app).allow_implicit_scrolling = value;
113    }
114}
115
116impl RenderSliverFixedExtentBoxAdaptor for RenderSliverFillViewport {
117    crate::render_sliver_fixed_extent_accessors!();
118
119    fn item_extent(self: RenderHandle<Self>, app: &App) -> Option<f64> {
120        Some(self.constraints(app).viewport_main_axis_extent * self.get(app).viewport_fraction)
121    }
122}
123
124fixed_extent_box_adaptor_leaf!(RenderSliverFillViewport);
125
126/// Declares the fields, the constructor and the [`RenderObjectWithChildMixin`],
127/// [`RenderSliverHelpers`] and [`RenderSliver`] impls that every [`RenderSliverSingleBoxAdapter`]
128/// leaf of this file shares; each leaf writes its own `impl RenderObject` for its layout.
129macro_rules! single_box_adapter_leaf {
130    ($(#[$doc:meta])* $leaf:ident, $(#[$new_doc:meta])* new) => {
131        $(#[$doc])*
132        pub struct $leaf {
133            render_object: RenderObjectData,
134            render_sliver: RenderSliverData,
135            child: RenderObjectWithChildData<AnyRenderBox>,
136        }
137
138        impl $leaf {
139            $(#[$new_doc])*
140            pub fn new(app: &mut App, child: Option<AnyRenderBox>) -> RenderHandle<$leaf> {
141                let this = RenderHandle::new_sliver(
142                    app,
143                    $leaf {
144                        render_object: RenderObjectData::new(),
145                        render_sliver: RenderSliverData::new(),
146                        child: RenderObjectWithChildData::new(),
147                    },
148                );
149                this.set_child(app, child);
150                this
151            }
152        }
153
154        impl RenderObjectWithChildMixin for $leaf {
155            type ChildType = AnyRenderBox;
156
157            fn child_data(
158                self: RenderHandle<Self>,
159                app: &App,
160            ) -> &RenderObjectWithChildData<AnyRenderBox> {
161                &self.get(app).child
162            }
163
164            fn child_data_mut(
165                self: RenderHandle<Self>,
166                app: &mut App,
167            ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
168                &mut self.get_mut(app).child
169            }
170        }
171
172        impl RenderSliverHelpers for $leaf {}
173
174        impl RenderSliver for $leaf {
175            crate::render_sliver_accessors!();
176
177            fn hit_test_children(
178                self: RenderHandle<Self>,
179                app: &mut App,
180                result: &mut SliverHitTestResult<'_>,
181                main_axis_position: f64,
182                cross_axis_position: f64,
183            ) -> bool {
184                RenderSliverSingleBoxAdapter::hit_test_children(
185                    self,
186                    app,
187                    result,
188                    main_axis_position,
189                    cross_axis_position,
190                )
191            }
192
193            fn child_main_axis_position(
194                self: RenderHandle<Self>,
195                app: &App,
196                child: AnyRenderObject,
197            ) -> f64 {
198                RenderSliverSingleBoxAdapter::child_main_axis_position(self, app, child)
199            }
200        }
201    };
202}
203
204/// The [`RenderObject`] members a [`RenderSliverSingleBoxAdapter`] leaf of this file inherits,
205/// other than its layout. Write it inside the leaf's `impl RenderObject`.
206macro_rules! single_box_adapter_object_overrides {
207    () => {
208        crate::render_object_accessors!();
209
210        fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
211            RenderSliverSingleBoxAdapter::setup_parent_data(self, app, child)
212        }
213
214        fn visit_children(
215            self: RenderHandle<Self>,
216            app: &App,
217            visitor: &mut dyn FnMut(AnyRenderObject),
218        ) {
219            if let Some(child) = self.child(app) {
220                visitor(child.as_object());
221            }
222        }
223
224        fn apply_paint_transform(
225            self: RenderHandle<Self>,
226            app: &App,
227            child: AnyRenderObject,
228            transform: &mut Matrix4,
229        ) {
230            RenderSliverSingleBoxAdapter::apply_paint_transform(self, app, child, transform)
231        }
232
233        fn paint(
234            self: RenderHandle<Self>,
235            app: &mut App,
236            context: &mut PaintingContext,
237            offset: Offset,
238        ) {
239            RenderSliverSingleBoxAdapter::paint(self, app, context, offset)
240        }
241    };
242}
243
244/// The child's extent in the main axis when it lays out at its maximum intrinsic size.
245fn max_intrinsic_main_axis_extent(
246    app: &mut App,
247    child: AnyRenderBox,
248    constraints: SliverConstraints,
249) -> f64 {
250    match constraints.axis() {
251        Axis::Horizontal => child.get_max_intrinsic_width(app, constraints.cross_axis_extent),
252        Axis::Vertical => child.get_max_intrinsic_height(app, constraints.cross_axis_extent),
253    }
254}
255
256single_box_adapter_leaf!(
257    /// A sliver that contains a single box child that contains a scrollable and fills the
258    /// viewport.
259    ///
260    /// [`RenderSliverFillRemainingWithScrollable`] sizes its child to fill the viewport in the
261    /// cross axis and to fill the remaining space in the viewport in the main axis.
262    ///
263    /// Typically this will be the last sliver in a viewport, since (by definition) there is
264    /// never any room for anything beyond this sliver.
265    ///
266    /// See also:
267    ///
268    ///  * `NestedScrollView`, which uses this sliver for the inner scrollable.
269    ///  * [`RenderSliverFillRemaining`], which lays out its non-scrollable child slightly
270    ///    different than this widget.
271    ///  * [`RenderSliverFillRemainingAndOverscroll`], which incorporates the overscroll into the
272    ///    remaining space to fill.
273    ///  * [`RenderSliverFillViewport`], which sizes its children based on the size of the
274    ///    viewport, regardless of what else is in the scroll view.
275    ///  * [`crate::RenderSliverList`], which shows a list of variable-sized children in a
276    ///    viewport.
277    RenderSliverFillRemainingWithScrollable,
278    /// Creates a [`RenderSliver`] that wraps a scrollable [`crate::RenderBox`] which is sized to
279    /// fit the remaining space in the viewport.
280    new
281);
282
283impl RenderSliverSingleBoxAdapter for RenderSliverFillRemainingWithScrollable {}
284
285impl RenderObject for RenderSliverFillRemainingWithScrollable {
286    single_box_adapter_object_overrides!();
287
288    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
289        let constraints = self.constraints(app);
290        let extent = constraints.remaining_paint_extent - constraints.overlap.min(0.0);
291
292        let cache_extent =
293            calculate_cache_offset(constraints, 0.0, constraints.viewport_main_axis_extent);
294        if let Some(child) = self.child(app) {
295            let mut max_extent = extent;
296
297            // If sliver has no extent, but is within viewport's cacheExtent, use the
298            // sliver's cacheExtent as the maxExtent so that it does not get dropped
299            // from the semantic tree.
300            if extent == 0.0 && cache_extent > 0.0 {
301                max_extent = cache_extent;
302            }
303            child.layout(
304                app,
305                constraints.as_box_constraints(extent, max_extent, None),
306                false,
307            );
308        }
309
310        let painted_child_size = calculate_paint_offset(constraints, 0.0, extent);
311        debug_assert!(painted_child_size.is_finite());
312        debug_assert!(painted_child_size >= 0.0);
313
314        let geometry = SliverGeometry::builder()
315            .scroll_extent(constraints.viewport_main_axis_extent)
316            .paint_extent(painted_child_size)
317            .max_paint_extent(painted_child_size)
318            .has_visual_overflow(
319                extent > constraints.remaining_paint_extent || constraints.scroll_offset > 0.0,
320            )
321            .cache_extent(cache_extent)
322            .build();
323        self.set_geometry(app, geometry);
324        if let Some(child) = self.child(app) {
325            RenderSliverSingleBoxAdapter::set_child_parent_data(
326                self,
327                app,
328                child.as_object(),
329                constraints,
330                geometry,
331            );
332        }
333    }
334}
335
336single_box_adapter_leaf!(
337    /// A sliver that contains a single box child that is non-scrollable and fills the remaining
338    /// space in the viewport.
339    ///
340    /// [`RenderSliverFillRemaining`] sizes its child to fill the viewport in the cross axis and
341    /// to fill the remaining space in the viewport in the main axis.
342    ///
343    /// Typically this will be the last sliver in a viewport, since (by definition) there is
344    /// never any room for anything beyond this sliver.
345    ///
346    /// See also:
347    ///
348    ///  * [`RenderSliverFillRemainingWithScrollable`], which lays out its scrollable child
349    ///    slightly different than this widget.
350    ///  * [`RenderSliverFillRemainingAndOverscroll`], which incorporates the overscroll into the
351    ///    remaining space to fill.
352    ///  * [`RenderSliverFillViewport`], which sizes its children based on the size of the
353    ///    viewport, regardless of what else is in the scroll view.
354    ///  * [`crate::RenderSliverList`], which shows a list of variable-sized children in a
355    ///    viewport.
356    RenderSliverFillRemaining,
357    /// Creates a [`RenderSliver`] that wraps a non-scrollable [`crate::RenderBox`] which is sized
358    /// to fit the remaining space in the viewport.
359    new
360);
361
362impl RenderSliverSingleBoxAdapter for RenderSliverFillRemaining {}
363
364impl RenderObject for RenderSliverFillRemaining {
365    single_box_adapter_object_overrides!();
366
367    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
368        let constraints = self.constraints(app);
369        // The remaining space in the viewportMainAxisExtent. Can be <= 0 if we have
370        // scrolled beyond the extent of the screen.
371        let mut extent =
372            constraints.viewport_main_axis_extent - constraints.preceding_scroll_extent;
373
374        if let Some(child) = self.child(app) {
375            let child_extent = max_intrinsic_main_axis_extent(app, child, constraints);
376
377            // If the childExtent is greater than the computed extent, we want to use
378            // that instead of potentially cutting off the child. This allows us to
379            // safely specify a maxExtent.
380            extent = extent.max(child_extent);
381            child.layout(
382                app,
383                constraints.as_box_constraints(extent, extent, None),
384                false,
385            );
386        }
387
388        debug_assert!(
389            extent.is_finite(),
390            "The calculated extent for the child of SliverFillRemaining is not finite. This can \
391             happen if the child is a scrollable, in which case, the hasScrollBody property of \
392             SliverFillRemaining should not be set to false."
393        );
394        let painted_child_size = calculate_paint_offset(constraints, 0.0, extent);
395        debug_assert!(painted_child_size.is_finite());
396        debug_assert!(painted_child_size >= 0.0);
397
398        let cache_extent = calculate_cache_offset(constraints, 0.0, extent);
399        let geometry = SliverGeometry::builder()
400            .scroll_extent(extent)
401            .paint_extent(painted_child_size)
402            .max_paint_extent(painted_child_size)
403            .has_visual_overflow(
404                extent > constraints.remaining_paint_extent || constraints.scroll_offset > 0.0,
405            )
406            .cache_extent(cache_extent)
407            .build();
408        self.set_geometry(app, geometry);
409        if let Some(child) = self.child(app) {
410            RenderSliverSingleBoxAdapter::set_child_parent_data(
411                self,
412                app,
413                child.as_object(),
414                constraints,
415                geometry,
416            );
417        }
418    }
419}
420
421single_box_adapter_leaf!(
422    /// A sliver that contains a single box child that is non-scrollable and fills the remaining
423    /// space in the viewport including any overscrolled area.
424    ///
425    /// [`RenderSliverFillRemainingAndOverscroll`] sizes its child to fill the viewport in the
426    /// cross axis and to fill the remaining space in the viewport in the main axis with the
427    /// overscroll area included.
428    ///
429    /// Typically this will be the last sliver in a viewport, since (by definition) there is
430    /// never any room for anything beyond this sliver.
431    ///
432    /// See also:
433    ///
434    ///  * [`RenderSliverFillRemainingWithScrollable`], which lays out its scrollable child
435    ///    without overscroll.
436    ///  * [`RenderSliverFillRemaining`], which lays out its non-scrollable child without
437    ///    overscroll.
438    ///  * [`RenderSliverFillViewport`], which sizes its children based on the size of the
439    ///    viewport, regardless of what else is in the scroll view.
440    ///  * [`crate::RenderSliverList`], which shows a list of variable-sized children in a
441    ///    viewport.
442    RenderSliverFillRemainingAndOverscroll,
443    /// Creates a [`RenderSliver`] that wraps a non-scrollable [`crate::RenderBox`] which is sized
444    /// to fit the remaining space plus any overscroll in the viewport.
445    new
446);
447
448impl RenderSliverSingleBoxAdapter for RenderSliverFillRemainingAndOverscroll {
449    fn set_child_parent_data(
450        self: RenderHandle<Self>,
451        app: &mut App,
452        child: AnyRenderObject,
453        constraints: SliverConstraints,
454        geometry: SliverGeometry,
455    ) {
456        RenderSliverSingleBoxAdapterBase::set_child_parent_data(
457            self,
458            app,
459            child,
460            constraints,
461            geometry,
462        );
463        let Some(child_box) = child.as_box().filter(|child_box| child_box.has_size(app)) else {
464            return;
465        };
466        // A child stretched into the overscroll area is larger than the
467        // scrollExtent, so for reversed axis directions it must be anchored by its
468        // actual size to keep its leading edge glued to the viewport's edge.
469        let child_size = child_box.size(app);
470        let paint_offset = match apply_growth_direction_to_axis_direction(
471            constraints.axis_direction,
472            constraints.growth_direction,
473        ) {
474            AxisDirection::Up => Offset::new(
475                0.0,
476                geometry.paint_extent + constraints.scroll_offset - child_size.height(),
477            ),
478            AxisDirection::Left => Offset::new(
479                geometry.paint_extent + constraints.scroll_offset - child_size.width(),
480                0.0,
481            ),
482            AxisDirection::Right | AxisDirection::Down => return,
483        };
484        child
485            .parent_data_of_mut::<SliverPhysicalParentData>(app)
486            .paint_offset = paint_offset;
487    }
488}
489
490impl RenderObject for RenderSliverFillRemainingAndOverscroll {
491    single_box_adapter_object_overrides!();
492
493    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
494        let constraints = self.constraints(app);
495        // The remaining space in the viewportMainAxisExtent. Can be <= 0 if we have
496        // scrolled beyond the extent of the screen.
497        let mut extent =
498            constraints.viewport_main_axis_extent - constraints.preceding_scroll_extent;
499        // The maxExtent includes any overscrolled area. Can be < 0 if we have
500        // overscroll in the opposite direction, away from the end of the list.
501        //
502        // When overscrolling past this sliver, the viewport clamps
503        // remainingPaintExtent to the viewport extent and delivers the
504        // overscrolled distance as this sliver's scrollOffset, so the
505        // scrollOffset term is needed for the stretched child to still reach the
506        // viewport's trailing edge.
507        let mut max_extent = constraints.remaining_paint_extent - constraints.overlap.min(0.0)
508            + constraints.scroll_offset;
509
510        if let Some(child) = self.child(app) {
511            let child_extent = max_intrinsic_main_axis_extent(app, child, constraints);
512
513            // If the childExtent is greater than the computed extent, we want to use
514            // that instead of potentially cutting off the child. This allows us to
515            // safely specify a maxExtent.
516            extent = extent.max(child_extent);
517            // The extent could be larger than the maxExtent due to a larger child
518            // size or overscrolling at the top of the scrollable (rather than at the
519            // end where this sliver is).
520            max_extent = extent.max(max_extent);
521            child.layout(
522                app,
523                constraints.as_box_constraints(extent, max_extent, None),
524                true,
525            );
526        }
527
528        debug_assert!(
529            extent.is_finite(),
530            "The calculated extent for the child of SliverFillRemaining is not finite. This can \
531             happen if the child is a scrollable, in which case, the hasScrollBody property of \
532             SliverFillRemaining should not be set to false."
533        );
534        let painted_child_size = calculate_paint_offset(constraints, 0.0, extent);
535        debug_assert!(painted_child_size.is_finite());
536        debug_assert!(painted_child_size >= 0.0);
537
538        let cache_extent = calculate_cache_offset(constraints, 0.0, extent);
539        let geometry = SliverGeometry::builder()
540            .scroll_extent(extent)
541            .paint_extent(max_extent.min(constraints.remaining_paint_extent))
542            .max_paint_extent(max_extent)
543            .has_visual_overflow(
544                extent > constraints.remaining_paint_extent || constraints.scroll_offset > 0.0,
545            )
546            .cache_extent(cache_extent)
547            .build();
548        self.set_geometry(app, geometry);
549        if let Some(child) = self.child(app) {
550            RenderSliverSingleBoxAdapter::set_child_parent_data(
551                self,
552                app,
553                child.as_object(),
554                constraints,
555                geometry,
556            );
557        }
558    }
559}