Skip to main content

waft_widgets/widgets/
viewport.rs

1//! Flutter counterpart: `widgets/viewport.dart`.
2//!
3//! `_ViewportElement.debugVisitOnstageChildren` waits with the other diagnostics; see
4//! `PORTING.md`.
5
6use std::fmt::Debug;
7
8use waft_embedder::Clip;
9use waft_foundation::{
10    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty, Handle,
11};
12use waft_painting::{AxisDirection, text_direction_to_axis_direction};
13use waft_rendering::{
14    AnyRenderObject, AnyRenderSliver, CacheExtentStyle, ErasedRenderObject, RenderBox,
15    RenderHandle, RenderShrinkWrappingViewport, RenderViewport, RenderViewportBase,
16    ScrollCacheExtent, SliverPaintOrder, ViewportOffsetRef,
17};
18
19use crate::framework::{
20    AnyElement, BuildContext, Element, ElementData, KeyRef, MultiChildRenderObjectElementBase,
21    MultiChildRenderObjectElementData, MultiChildRenderObjectWidget, RenderObjectElement,
22    RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget, Slot, WidgetRef,
23    downcast_widget, keys_equal,
24};
25use crate::widgets::basic::Directionality;
26use crate::widgets::scroll_notification::ViewportElementMixin;
27
28/// A widget through which a portion of larger content can be viewed, typically in combination
29/// with a `Scrollable`.
30///
31/// [`Viewport`] is the visual workhorse of the scrolling machinery. It displays a subset of its
32/// children according to its own dimensions and the given [`offset`](Self::offset). As the offset
33/// varies, different children are visible through the viewport.
34///
35/// [`Viewport`] hosts a bidirectional list of slivers, anchored on a [`center`](Self::center)
36/// sliver, which is placed at the zero scroll offset. The center widget is displayed in the
37/// viewport according to the [`anchor`](Self::anchor) property.
38///
39/// Slivers that are earlier in the child list than [`center`](Self::center) are displayed in
40/// reverse order in the reverse [`axis_direction`](Self::axis_direction) starting from the
41/// [`center`](Self::center). For example, if the axis direction is [`AxisDirection::Down`], the
42/// first sliver before the center is placed above the center. The slivers that are later in the
43/// child list than the center are placed in order in the axis direction.
44///
45/// [`Viewport`] cannot contain box children directly. Instead, use a `SliverList`,
46/// `SliverFixedExtentList`, or a `SliverToBoxAdapter`, for example.
47///
48/// See also:
49///
50///  * `SliverToBoxAdapter`, which allows a box widget to be placed inside a sliver context (the
51///    opposite of this widget).
52///  * [`ShrinkWrappingViewport`], a variant of [`Viewport`] that shrink-wraps its contents along
53///    the main axis.
54///  * `ViewportElementMixin`, which should be mixed in to the `Element` type used by
55///    viewport-like widgets to correctly handle scroll notifications.
56#[derive(Debug)]
57pub struct Viewport {
58    pub key: Option<KeyRef>,
59    /// The direction in which the [`offset`](Self::offset)'s `ViewportOffset::pixels` increases.
60    ///
61    /// For example, if the axis direction is [`AxisDirection::Down`], a scroll offset of zero is
62    /// at the top of the viewport and increases towards the bottom of the viewport.
63    pub axis_direction: AxisDirection,
64    /// The direction in which child should be laid out in the cross axis.
65    ///
66    /// If the [`axis_direction`](Self::axis_direction) is [`AxisDirection::Down`] or
67    /// [`AxisDirection::Up`], this property defaults to [`AxisDirection::Left`] if the ambient
68    /// [`Directionality`] is right-to-left and [`AxisDirection::Right`] if it is left-to-right.
69    ///
70    /// If the axis direction is [`AxisDirection::Left`] or [`AxisDirection::Right`], this
71    /// property defaults to [`AxisDirection::Down`].
72    pub cross_axis_direction: Option<AxisDirection>,
73    /// The relative position of the zero scroll offset.
74    ///
75    /// For example, if the anchor is 0.5 and the [`axis_direction`](Self::axis_direction) is
76    /// [`AxisDirection::Down`] or [`AxisDirection::Up`], then the zero scroll offset is
77    /// vertically centered within the viewport. If the anchor is 1.0, and the axis direction is
78    /// [`AxisDirection::Right`], then the zero scroll offset is on the left edge of the viewport.
79    pub anchor: f64,
80    /// Which part of the content inside the viewport should be visible.
81    ///
82    /// The `ViewportOffset::pixels` value determines the scroll offset that the viewport uses to
83    /// select which part of its content to display. As the user scrolls the viewport, this value
84    /// changes, which changes the content that is displayed.
85    ///
86    /// Typically a `ScrollPosition`.
87    pub offset: ViewportOffsetRef,
88    /// The first child in the `GrowthDirection::Forward` growth direction.
89    ///
90    /// Children after the center will be placed in the [`axis_direction`](Self::axis_direction)
91    /// relative to the center. Children before it will be placed in the opposite of the axis
92    /// direction relative to the center.
93    ///
94    /// The center must be the key of a child of the viewport.
95    pub center: Option<KeyRef>,
96    /// The viewport has an area before and after the visible area to cache items that are about
97    /// to become visible when the user scrolls.
98    ///
99    /// See also:
100    ///
101    ///  * [`cache_extent_style`](Self::cache_extent_style), which controls the units of the cache
102    ///    extent.
103    #[deprecated(note = "Use scroll_cache_extent instead.")]
104    pub cache_extent: Option<f64>,
105    /// The unit of measurement of [`cache_extent`](Self::cache_extent).
106    #[deprecated(note = "Use scroll_cache_extent instead.")]
107    pub cache_extent_style: CacheExtentStyle,
108    /// The amount of additional content to display and lay out around the viewport.
109    pub scroll_cache_extent: Option<ScrollCacheExtent>,
110    /// The order in which to paint the slivers.
111    ///
112    /// Defaults to [`SliverPaintOrder::FirstIsTop`].
113    pub paint_order: SliverPaintOrder,
114    /// Defaults to [`Clip::HardEdge`].
115    pub clip_behavior: Clip,
116    /// The slivers to place inside the viewport.
117    pub slivers: Vec<WidgetRef>,
118}
119
120impl Viewport {
121    /// Creates a widget that is bigger on the inside.
122    ///
123    /// The viewport listens to the [`offset`](Self::offset), which means you do not need to
124    /// rebuild this widget when the offset changes.
125    #[expect(deprecated, reason = "the deprecated fields have Dart's defaults")]
126    pub fn new(offset: ViewportOffsetRef) -> Viewport {
127        Viewport {
128            key: None,
129            axis_direction: AxisDirection::Down,
130            cross_axis_direction: None,
131            anchor: 0.0,
132            offset,
133            center: None,
134            cache_extent: None,
135            cache_extent_style: CacheExtentStyle::Pixel,
136            scroll_cache_extent: None,
137            paint_order: SliverPaintOrder::FirstIsTop,
138            clip_behavior: Clip::HardEdge,
139            slivers: Vec::new(),
140        }
141    }
142
143    /// Dart `Viewport(key:)`.
144    pub fn key(mut self, key: KeyRef) -> Viewport {
145        self.key = Some(key);
146        self
147    }
148
149    /// Dart `Viewport(axisDirection:)`.
150    pub fn axis_direction(mut self, axis_direction: AxisDirection) -> Viewport {
151        self.axis_direction = axis_direction;
152        self
153    }
154
155    /// Dart `Viewport(crossAxisDirection:)`.
156    pub fn cross_axis_direction(mut self, cross_axis_direction: AxisDirection) -> Viewport {
157        self.cross_axis_direction = Some(cross_axis_direction);
158        self
159    }
160
161    /// Dart `Viewport(anchor:)`.
162    pub fn anchor(mut self, anchor: f64) -> Viewport {
163        self.anchor = anchor;
164        self
165    }
166
167    /// Dart `Viewport(center:)`.
168    pub fn center(mut self, center: KeyRef) -> Viewport {
169        self.center = Some(center);
170        self.debug_assert_center_is_a_sliver();
171        self
172    }
173
174    /// Dart `Viewport(cacheExtent:)`.
175    #[deprecated(note = "Use scroll_cache_extent instead.")]
176    pub fn cache_extent(mut self, cache_extent: f64) -> Viewport {
177        #[expect(deprecated, reason = "the deprecated field this setter writes")]
178        {
179            self.cache_extent = Some(cache_extent);
180        }
181        self
182    }
183
184    /// Dart `Viewport(cacheExtentStyle:)`.
185    #[deprecated(note = "Use scroll_cache_extent instead.")]
186    pub fn cache_extent_style(mut self, cache_extent_style: CacheExtentStyle) -> Viewport {
187        #[expect(deprecated, reason = "the deprecated fields this setter guards")]
188        {
189            self.cache_extent_style = cache_extent_style;
190            debug_assert!(
191                self.cache_extent_style != CacheExtentStyle::Viewport
192                    || self.cache_extent.is_some()
193            );
194        }
195        self
196    }
197
198    /// Dart `Viewport(scrollCacheExtent:)`.
199    pub fn scroll_cache_extent(mut self, scroll_cache_extent: ScrollCacheExtent) -> Viewport {
200        self.scroll_cache_extent = Some(scroll_cache_extent);
201        self
202    }
203
204    /// Dart `Viewport(paintOrder:)`.
205    pub fn paint_order(mut self, paint_order: SliverPaintOrder) -> Viewport {
206        self.paint_order = paint_order;
207        self
208    }
209
210    /// Dart `Viewport(clipBehavior:)`.
211    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Viewport {
212        self.clip_behavior = clip_behavior;
213        self
214    }
215
216    /// Dart `Viewport(slivers:)`.
217    pub fn slivers(mut self, slivers: Vec<WidgetRef>) -> Viewport {
218        self.slivers = slivers;
219        self.debug_assert_center_is_a_sliver();
220        self
221    }
222
223    /// Dart's `assert(center == null || slivers.where((child) => child.key == center).length == 1)`.
224    fn debug_assert_center_is_a_sliver(&self) {
225        if cfg!(debug_assertions)
226            && let Some(center) = &self.center
227        {
228            let matches = self
229                .slivers
230                .iter()
231                .filter(|child| keys_equal(child.key(), Some(center)))
232                .count();
233            assert!(matches == 1, "the center must be the key of one sliver");
234        }
235    }
236
237    /// Flutter's `_effectiveScrollCacheExtent`.
238    fn effective_scroll_cache_extent(&self) -> Option<ScrollCacheExtent> {
239        if self.scroll_cache_extent.is_some() {
240            return self.scroll_cache_extent;
241        }
242        #[expect(deprecated, reason = "the deprecated fields this getter folds in")]
243        let (cache_extent, cache_extent_style) = (self.cache_extent, self.cache_extent_style);
244        let cache_extent = cache_extent?;
245        Some(match cache_extent_style {
246            CacheExtentStyle::Pixel => ScrollCacheExtent::Pixels(cache_extent),
247            CacheExtentStyle::Viewport => ScrollCacheExtent::Viewport(cache_extent),
248        })
249    }
250
251    /// Given a [`BuildContext`] and an [`AxisDirection`], determine the correct cross axis
252    /// direction.
253    ///
254    /// This depends on the [`Directionality`] if the `axis_direction` is vertical; otherwise, the
255    /// default cross axis direction is downwards.
256    pub fn get_default_cross_axis_direction(
257        app: &mut App,
258        context: BuildContext,
259        axis_direction: AxisDirection,
260    ) -> AxisDirection {
261        match axis_direction {
262            AxisDirection::Up | AxisDirection::Down => {
263                text_direction_to_axis_direction(Directionality::of(app, context))
264            }
265            AxisDirection::Right | AxisDirection::Left => AxisDirection::Down,
266        }
267    }
268
269    fn resolved_cross_axis_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
270        self.cross_axis_direction.unwrap_or_else(|| {
271            Viewport::get_default_cross_axis_direction(app, context, self.axis_direction)
272        })
273    }
274}
275
276impl RenderObjectWidget for Viewport {
277    type RenderObject = RenderViewport;
278
279    fn key(&self) -> Option<&KeyRef> {
280        self.key.as_ref()
281    }
282
283    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
284        properties.add(EnumProperty::new("axisDirection", self.axis_direction));
285        properties.add(
286            EnumProperty::<AxisDirection>::new("crossAxisDirection", self.cross_axis_direction)
287                .default_value(None),
288        );
289        properties.add(DoubleProperty::new("anchor", self.anchor));
290        properties.add(DiagnosticsProperty::<String>::new(
291            "offset",
292            Some(self.offset.to_string_with_app(app)),
293        ));
294        if let Some(center) = &self.center {
295            properties.add(DiagnosticsProperty::<String>::new(
296                "center",
297                Some(format!("{center:?}")),
298            ));
299        } else if let Some(first) = self.slivers.first()
300            && let Some(key) = first.key()
301        {
302            properties.add(
303                DiagnosticsProperty::<String>::new("center", Some(format!("{key:?}")))
304                    .tooltip("implicit"),
305            );
306        }
307        properties.add(DiagnosticsProperty::<ScrollCacheExtent>::new(
308            "scrollCacheExtent",
309            self.scroll_cache_extent,
310        ));
311    }
312
313    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
314        let cross_axis_direction = self.resolved_cross_axis_direction(app, context);
315        let viewport =
316            RenderViewport::new(app, cross_axis_direction, self.offset.clone(), None, None);
317        viewport.set_axis_direction(app, self.axis_direction);
318        viewport.set_anchor(app, self.anchor);
319        viewport.set_scroll_cache_extent(app, self.effective_scroll_cache_extent());
320        viewport.set_paint_order(app, self.paint_order);
321        viewport.set_clip_behavior(app, self.clip_behavior);
322        viewport.as_object()
323    }
324
325    fn update_render_object(
326        &self,
327        app: &mut App,
328        context: BuildContext,
329        render_object: RenderHandle<RenderViewport>,
330    ) {
331        let cross_axis_direction = self.resolved_cross_axis_direction(app, context);
332        render_object.set_axis_direction(app, self.axis_direction);
333        render_object.set_cross_axis_direction(app, cross_axis_direction);
334        render_object.set_anchor(app, self.anchor);
335        render_object.set_offset(app, self.offset.clone());
336        render_object.set_scroll_cache_extent(app, self.effective_scroll_cache_extent());
337        render_object.set_paint_order(app, self.paint_order);
338        render_object.set_clip_behavior(app, self.clip_behavior);
339    }
340}
341
342impl MultiChildRenderObjectWidget for Viewport {
343    fn children(&self) -> &[WidgetRef] {
344        &self.slivers
345    }
346
347    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
348        ViewportElement::new(app, this).as_element()
349    }
350}
351
352/// Dart's `_ViewportElement`: the [`Viewport`]'s element, which keeps the render object's
353/// `center` in step with the child list.
354pub struct ViewportElement {
355    element: ElementData,
356    render_object_element: RenderObjectElementData,
357    multi_child: MultiChildRenderObjectElementData,
358    doing_mount_or_update: bool,
359    center_slot_index: Option<usize>,
360}
361
362impl ViewportElement {
363    /// Creates an element that uses the given widget as its configuration.
364    pub fn new(app: &mut App, widget: WidgetRef) -> Handle<ViewportElement> {
365        debug_assert!(downcast_widget::<Viewport>(&*widget).is_some());
366        app.create(ViewportElement {
367            element: ElementData::new(widget),
368            render_object_element: RenderObjectElementData::default(),
369            multi_child: MultiChildRenderObjectElementData::default(),
370            doing_mount_or_update: false,
371            center_slot_index: None,
372        })
373        .into_tree_node(app)
374    }
375
376    /// The viewport this element manages.
377    pub fn render_object(self: Handle<Self>, app: &App) -> RenderHandle<RenderViewport> {
378        self.typed_render_object(app)
379    }
380
381    /// Flutter's `_updateCenter`.
382    fn update_center(self: Handle<Self>, app: &mut App) {
383        let center = Self::widget_of(self.as_element().widget(app))
384            .center
385            .clone();
386        let children = MultiChildRenderObjectElementBase::children(self, app);
387        let render_object = self.render_object(app);
388        match center {
389            Some(center) => {
390                let mut element_index = 0;
391                for child in &children {
392                    if keys_equal(child.widget(app).key(), Some(&center)) {
393                        let sliver = child.render_object(app).map(AnyRenderSliver::from_object);
394                        render_object.set_center(app, sliver);
395                        break;
396                    }
397                    element_index += 1;
398                }
399                debug_assert!(element_index < children.len());
400                app.get_mut(self).center_slot_index = Some(element_index);
401            }
402            None if !children.is_empty() => {
403                let sliver = children[0]
404                    .render_object(app)
405                    .map(AnyRenderSliver::from_object);
406                render_object.set_center(app, sliver);
407                app.get_mut(self).center_slot_index = Some(0);
408            }
409            None => {
410                render_object.set_center(app, None);
411                app.get_mut(self).center_slot_index = None;
412            }
413        }
414    }
415}
416
417impl RenderObjectElementWidget for ViewportElement {
418    type Widget = Viewport;
419
420    fn widget_of(widget: &WidgetRef) -> &Viewport {
421        downcast_widget::<Viewport>(&**widget).expect("a ViewportElement holds its Viewport")
422    }
423}
424
425impl RenderObjectElement for ViewportElement {
426    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
427        &app.get(self).render_object_element
428    }
429
430    fn render_object_element_data_mut(
431        self: Handle<Self>,
432        app: &mut App,
433    ) -> &mut RenderObjectElementData {
434        &mut app.get_mut(self).render_object_element
435    }
436}
437
438impl MultiChildRenderObjectElementBase for ViewportElement {
439    fn multi_child_data(self: Handle<Self>, app: &App) -> &MultiChildRenderObjectElementData {
440        &app.get(self).multi_child
441    }
442
443    fn multi_child_data_mut(
444        self: Handle<Self>,
445        app: &mut App,
446    ) -> &mut MultiChildRenderObjectElementData {
447        &mut app.get_mut(self).multi_child
448    }
449}
450
451impl ViewportElementMixin for ViewportElement {}
452
453impl Element for ViewportElement {
454    crate::element_accessors!();
455
456    const IS_RENDER_OBJECT_ELEMENT: bool = true;
457
458    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
459        self.render_object_element_data(app).render_object()
460    }
461
462    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
463        None
464    }
465
466    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
467        self.render_object_element_data(app).debug_doing_build()
468    }
469
470    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
471        MultiChildRenderObjectElementBase::visit_children(self, app, visitor);
472    }
473
474    /// Dart's `_ViewportElement.debugVisitOnstageChildren`: the slivers whose geometry is
475    /// visible.
476    fn debug_visit_onstage_children(
477        self: Handle<Self>,
478        app: &App,
479        visitor: &mut dyn FnMut(AnyElement),
480    ) {
481        let mut children = Vec::new();
482        MultiChildRenderObjectElementBase::visit_children(self, app, &mut |child| {
483            children.push(child);
484        });
485        children
486            .into_iter()
487            .filter(|child| {
488                child
489                    .render_object(app)
490                    .and_then(|render| render.as_sliver())
491                    .is_some_and(|sliver| sliver.geometry(app).visible)
492            })
493            .for_each(visitor);
494    }
495
496    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
497        MultiChildRenderObjectElementBase::forget_child(self, app, child);
498    }
499
500    fn mount(
501        self: Handle<Self>,
502        app: &mut App,
503        parent: Option<AnyElement>,
504        new_slot: Option<Slot>,
505    ) {
506        debug_assert!(!app.get(self).doing_mount_or_update);
507        app.get_mut(self).doing_mount_or_update = true;
508        MultiChildRenderObjectElementBase::mount(self, app, parent, new_slot);
509        self.update_center(app);
510        debug_assert!(app.get(self).doing_mount_or_update);
511        app.get_mut(self).doing_mount_or_update = false;
512    }
513
514    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
515        debug_assert!(!app.get(self).doing_mount_or_update);
516        app.get_mut(self).doing_mount_or_update = true;
517        MultiChildRenderObjectElementBase::update(self, app, new_widget);
518        self.update_center(app);
519        debug_assert!(app.get(self).doing_mount_or_update);
520        app.get_mut(self).doing_mount_or_update = false;
521    }
522
523    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
524        RenderObjectElement::perform_rebuild(self, app);
525    }
526
527    fn deactivate(self: Handle<Self>, app: &mut App) {
528        RenderObjectElement::deactivate(self, app);
529    }
530
531    fn unmount(self: Handle<Self>, app: &mut App) {
532        RenderObjectElement::unmount(self, app);
533    }
534
535    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
536        RenderObjectElement::update_parent_data(self, app, parent_data_element);
537    }
538
539    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
540        RenderObjectElement::update_slot(self, app, new_slot);
541    }
542
543    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
544        RenderObjectElement::attach_render_object(self, app, new_slot);
545    }
546
547    fn detach_render_object(self: Handle<Self>, app: &mut App) {
548        RenderObjectElement::detach_render_object(self, app);
549    }
550
551    fn insert_render_object_child(
552        self: Handle<Self>,
553        app: &mut App,
554        child: AnyRenderObject,
555        slot: Option<Slot>,
556    ) {
557        MultiChildRenderObjectElementBase::insert_render_object_child(
558            self,
559            app,
560            child,
561            slot.clone(),
562        );
563        // Once `mount` / `update` are done, the render object's center will be updated in
564        // `update_center`.
565        let index = Self::indexed_slot(slot.as_ref()).index;
566        if !app.get(self).doing_mount_or_update && Some(index) == app.get(self).center_slot_index {
567            let center = AnyRenderSliver::from_object(child);
568            self.render_object(app).set_center(app, Some(center));
569        }
570    }
571
572    fn move_render_object_child(
573        self: Handle<Self>,
574        app: &mut App,
575        child: AnyRenderObject,
576        old_slot: Option<Slot>,
577        new_slot: Option<Slot>,
578    ) {
579        MultiChildRenderObjectElementBase::move_render_object_child(
580            self, app, child, old_slot, new_slot,
581        );
582        debug_assert!(app.get(self).doing_mount_or_update);
583    }
584
585    fn remove_render_object_child(
586        self: Handle<Self>,
587        app: &mut App,
588        child: AnyRenderObject,
589        slot: Option<Slot>,
590    ) {
591        MultiChildRenderObjectElementBase::remove_render_object_child(self, app, child, slot);
592        let render_object = self.render_object(app);
593        if !app.get(self).doing_mount_or_update
594            && render_object.center(app) == Some(AnyRenderSliver::from_object(child))
595        {
596            render_object.set_center(app, None);
597        }
598    }
599
600    fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
601        ViewportElementMixin::attach_notification_tree(self, app);
602    }
603
604    fn on_notification(
605        self: Handle<Self>,
606        app: &mut App,
607        notification: &dyn crate::framework::Notification,
608    ) -> bool {
609        ViewportElementMixin::on_notification(self, app, notification)
610    }
611}
612
613/// A widget that is bigger on the inside and shrink wraps its children in the main axis.
614///
615/// [`ShrinkWrappingViewport`] displays a subset of its children according to its own dimensions
616/// and the given [`offset`](Self::offset). As the offset varies, different children are visible
617/// through the viewport.
618///
619/// [`ShrinkWrappingViewport`] differs from [`Viewport`] in that [`Viewport`] expands to fill the
620/// main axis whereas [`ShrinkWrappingViewport`] sizes itself to match its children in the main
621/// axis. This shrink wrapping behavior is expensive because the children, and hence the viewport,
622/// could potentially change size whenever the offset changes (e.g., because of a collapsing
623/// header).
624///
625/// [`ShrinkWrappingViewport`] cannot contain box children directly. Instead, use a `SliverList`,
626/// `SliverFixedExtentList`, or a `SliverToBoxAdapter`, for example.
627///
628/// See also:
629///
630///  * `SliverToBoxAdapter`, which allows a box widget to be placed inside a sliver context (the
631///    opposite of this widget).
632///  * [`Viewport`], a viewport that does not shrink-wrap its contents.
633#[derive(Debug)]
634pub struct ShrinkWrappingViewport {
635    pub key: Option<KeyRef>,
636    /// The direction in which the [`offset`](Self::offset)'s `ViewportOffset::pixels` increases.
637    pub axis_direction: AxisDirection,
638    /// The direction in which child should be laid out in the cross axis.
639    pub cross_axis_direction: Option<AxisDirection>,
640    /// Which part of the content inside the viewport should be visible.
641    ///
642    /// Typically a `ScrollPosition`.
643    pub offset: ViewportOffsetRef,
644    /// The order in which to paint the slivers.
645    ///
646    /// Defaults to [`SliverPaintOrder::FirstIsTop`].
647    pub paint_order: SliverPaintOrder,
648    /// Defaults to [`Clip::HardEdge`].
649    pub clip_behavior: Clip,
650    /// The viewport has an area before and after the visible area to cache items that are about
651    /// to become visible when the user scrolls.
652    #[deprecated(note = "Use scroll_cache_extent instead.")]
653    pub cache_extent: Option<f64>,
654    /// The unit of measurement of [`cache_extent`](Self::cache_extent).
655    #[deprecated(note = "Use scroll_cache_extent instead.")]
656    pub cache_extent_style: CacheExtentStyle,
657    /// The amount of additional content to display and lay out around the viewport.
658    pub scroll_cache_extent: Option<ScrollCacheExtent>,
659    /// The slivers to place inside the viewport.
660    pub slivers: Vec<WidgetRef>,
661}
662
663impl ShrinkWrappingViewport {
664    /// Creates a widget that is bigger on the inside and shrink wraps its children in the main
665    /// axis.
666    ///
667    /// The viewport listens to the [`offset`](Self::offset), which means you do not need to
668    /// rebuild this widget when the offset changes.
669    #[expect(deprecated, reason = "the deprecated fields have Dart's defaults")]
670    pub fn new(offset: ViewportOffsetRef) -> ShrinkWrappingViewport {
671        ShrinkWrappingViewport {
672            key: None,
673            axis_direction: AxisDirection::Down,
674            cross_axis_direction: None,
675            offset,
676            paint_order: SliverPaintOrder::FirstIsTop,
677            clip_behavior: Clip::HardEdge,
678            cache_extent: None,
679            cache_extent_style: CacheExtentStyle::Pixel,
680            scroll_cache_extent: None,
681            slivers: Vec::new(),
682        }
683    }
684
685    /// Dart `ShrinkWrappingViewport(key:)`.
686    pub fn key(mut self, key: KeyRef) -> ShrinkWrappingViewport {
687        self.key = Some(key);
688        self
689    }
690
691    /// Dart `ShrinkWrappingViewport(axisDirection:)`.
692    pub fn axis_direction(mut self, axis_direction: AxisDirection) -> ShrinkWrappingViewport {
693        self.axis_direction = axis_direction;
694        self
695    }
696
697    /// Dart `ShrinkWrappingViewport(crossAxisDirection:)`.
698    pub fn cross_axis_direction(
699        mut self,
700        cross_axis_direction: AxisDirection,
701    ) -> ShrinkWrappingViewport {
702        self.cross_axis_direction = Some(cross_axis_direction);
703        self
704    }
705
706    /// Dart `ShrinkWrappingViewport(paintOrder:)`.
707    pub fn paint_order(mut self, paint_order: SliverPaintOrder) -> ShrinkWrappingViewport {
708        self.paint_order = paint_order;
709        self
710    }
711
712    /// Dart `ShrinkWrappingViewport(clipBehavior:)`.
713    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ShrinkWrappingViewport {
714        self.clip_behavior = clip_behavior;
715        self
716    }
717
718    /// Dart `ShrinkWrappingViewport(cacheExtent:)`.
719    #[deprecated(note = "Use scroll_cache_extent instead.")]
720    pub fn cache_extent(mut self, cache_extent: f64) -> ShrinkWrappingViewport {
721        #[expect(deprecated, reason = "the deprecated field this setter writes")]
722        {
723            self.cache_extent = Some(cache_extent);
724        }
725        self
726    }
727
728    /// Dart `ShrinkWrappingViewport(cacheExtentStyle:)`.
729    #[deprecated(note = "Use scroll_cache_extent instead.")]
730    pub fn cache_extent_style(
731        mut self,
732        cache_extent_style: CacheExtentStyle,
733    ) -> ShrinkWrappingViewport {
734        #[expect(deprecated, reason = "the deprecated field this setter writes")]
735        {
736            self.cache_extent_style = cache_extent_style;
737        }
738        self
739    }
740
741    /// Dart `ShrinkWrappingViewport(scrollCacheExtent:)`.
742    pub fn scroll_cache_extent(
743        mut self,
744        scroll_cache_extent: ScrollCacheExtent,
745    ) -> ShrinkWrappingViewport {
746        self.scroll_cache_extent = Some(scroll_cache_extent);
747        self
748    }
749
750    /// Dart `ShrinkWrappingViewport(slivers:)`.
751    pub fn slivers(mut self, slivers: Vec<WidgetRef>) -> ShrinkWrappingViewport {
752        self.slivers = slivers;
753        self
754    }
755
756    /// Flutter's `_effectiveScrollCacheExtent`.
757    fn effective_scroll_cache_extent(&self) -> Option<ScrollCacheExtent> {
758        if self.scroll_cache_extent.is_some() {
759            return self.scroll_cache_extent;
760        }
761        #[expect(deprecated, reason = "the deprecated fields this getter folds in")]
762        let (cache_extent, cache_extent_style) = (self.cache_extent, self.cache_extent_style);
763        let cache_extent = cache_extent?;
764        Some(match cache_extent_style {
765            CacheExtentStyle::Pixel => ScrollCacheExtent::Pixels(cache_extent),
766            CacheExtentStyle::Viewport => ScrollCacheExtent::Viewport(cache_extent),
767        })
768    }
769
770    fn resolved_cross_axis_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
771        self.cross_axis_direction.unwrap_or_else(|| {
772            Viewport::get_default_cross_axis_direction(app, context, self.axis_direction)
773        })
774    }
775}
776
777impl RenderObjectWidget for ShrinkWrappingViewport {
778    type RenderObject = RenderShrinkWrappingViewport;
779
780    fn key(&self) -> Option<&KeyRef> {
781        self.key.as_ref()
782    }
783
784    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
785        properties.add(EnumProperty::new("axisDirection", self.axis_direction));
786        properties.add(
787            EnumProperty::<AxisDirection>::new("crossAxisDirection", self.cross_axis_direction)
788                .default_value(None),
789        );
790        properties.add(DiagnosticsProperty::<String>::new(
791            "offset",
792            Some(self.offset.to_string_with_app(app)),
793        ));
794        properties.add(
795            DiagnosticsProperty::<ScrollCacheExtent>::new(
796                "scrollCacheExtent",
797                self.scroll_cache_extent,
798            )
799            .default_value(None),
800        );
801    }
802
803    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
804        let cross_axis_direction = self.resolved_cross_axis_direction(app, context);
805        let viewport =
806            RenderShrinkWrappingViewport::new(app, cross_axis_direction, self.offset.clone(), None);
807        viewport.set_axis_direction(app, self.axis_direction);
808        viewport.set_paint_order(app, self.paint_order);
809        viewport.set_clip_behavior(app, self.clip_behavior);
810        viewport.set_scroll_cache_extent(app, self.effective_scroll_cache_extent());
811        viewport.as_object()
812    }
813
814    fn update_render_object(
815        &self,
816        app: &mut App,
817        context: BuildContext,
818        render_object: RenderHandle<RenderShrinkWrappingViewport>,
819    ) {
820        let cross_axis_direction = self.resolved_cross_axis_direction(app, context);
821        render_object.set_axis_direction(app, self.axis_direction);
822        render_object.set_cross_axis_direction(app, cross_axis_direction);
823        render_object.set_offset(app, self.offset.clone());
824        render_object.set_paint_order(app, self.paint_order);
825        render_object.set_clip_behavior(app, self.clip_behavior);
826        render_object.set_scroll_cache_extent(app, self.effective_scroll_cache_extent());
827    }
828}
829
830impl MultiChildRenderObjectWidget for ShrinkWrappingViewport {
831    fn children(&self) -> &[WidgetRef] {
832        &self.slivers
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use std::cell::RefCell;
839    use std::rc::Rc;
840    use waft_foundation::AppCell;
841    use waft_foundation::Ref;
842
843    use waft_embedder::TextDirection;
844    use waft_rendering::{
845        ContainerRenderObjectMixin, FixedViewportOffset, RenderObjectWithChildMixin,
846        RenderPositionedBox, RenderSliverList, SliverMultiBoxAdaptorParentData, ViewportOffset,
847    };
848
849    use super::*;
850    use crate::framework::IntoWidget;
851    use crate::test_harness::Harness;
852    use crate::widgets::basic::{Center, Directionality, SizedBox, SliverToBoxAdapter};
853    use crate::widgets::sliver::SliverList;
854
855    /// The indices the list's item builder was asked for, in order.
856    type Built = Rc<RefCell<Vec<i32>>>;
857
858    fn item_list(built: &Built, item_count: i32) -> WidgetRef {
859        let built = Rc::clone(built);
860        SliverList::builder(move |_app, _context, index| {
861            built.borrow_mut().push(index);
862            Some(SizedBox::new().height(40.0).into_widget())
863        })
864        .item_count(item_count)
865        .into_widget()
866    }
867
868    fn viewport_tree(offset: &Ref<FixedViewportOffset>, built: &Built) -> WidgetRef {
869        Directionality::new(
870            TextDirection::Ltr,
871            Viewport::new(offset.erase())
872                .scroll_cache_extent(ScrollCacheExtent::Pixels(0.0))
873                .slivers(vec![
874                    SliverToBoxAdapter::new()
875                        .child(SizedBox::new().height(50.0))
876                        .into_widget(),
877                    item_list(built, 20),
878                ]),
879        )
880        .into_widget()
881    }
882
883    fn render_viewport(harness: &Harness, app: &App) -> RenderHandle<RenderViewport> {
884        harness
885            .render_root(app)
886            .child(app)
887            .expect("a child")
888            .as_object()
889            .downcast::<RenderViewport>(app)
890            .expect("a RenderViewport")
891    }
892
893    fn sliver_list(
894        viewport: RenderHandle<RenderViewport>,
895        app: &App,
896    ) -> RenderHandle<RenderSliverList> {
897        let adapter = viewport.first_child(app).expect("the box adapter");
898        viewport
899            .child_after(app, adapter)
900            .expect("the list")
901            .as_object()
902            .downcast::<RenderSliverList>(app)
903            .expect("a RenderSliverList")
904    }
905
906    /// The indices of the list's reified children, in child order.
907    fn child_indices(list: RenderHandle<RenderSliverList>, app: &App) -> Vec<i32> {
908        let mut indices = Vec::new();
909        let mut child = list.first_child(app);
910        while let Some(current) = child {
911            indices.push(
912                current
913                    .as_object()
914                    .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
915                    .index
916                    .expect("a reified child has an index"),
917            );
918            child = list.child_after(app, current);
919        }
920        indices
921    }
922
923    #[test]
924    fn a_viewport_builds_only_the_visible_children_and_more_when_the_offset_moves() {
925        let cell = AppCell::new();
926        let mut app = cell.borrow_mut();
927        let offset = FixedViewportOffset::zero(&mut app);
928        let built: Built = Rc::default();
929        let harness = Harness::mount(&mut app, viewport_tree(&offset, &built));
930        harness.pump(&mut app);
931
932        let viewport = render_viewport(&harness, &app);
933        let list = sliver_list(viewport, &app);
934        // The box adapter takes the first 50 pixels; the 200-pixel viewport fits four more
935        // 40-pixel children with no cache extent.
936        assert_eq!(child_indices(list, &app), vec![0, 1, 2, 3]);
937        assert_eq!(*built.borrow(), vec![0, 1, 2, 3]);
938
939        offset.correct_by(&mut app, 200.0);
940        viewport.mark_needs_layout(&mut app);
941        harness.pump(&mut app);
942
943        // The window 200..400 covers the list items that start at 50: indices 3 through 8.
944        assert_eq!(child_indices(list, &app), vec![3, 4, 5, 6, 7, 8]);
945        // The children that scrolled off were destroyed; only the new ones were built.
946        assert_eq!(*built.borrow(), vec![0, 1, 2, 3, 4, 5, 6, 7, 8]);
947    }
948
949    #[test]
950    fn a_shrink_wrapping_viewport_sizes_itself_to_its_content() {
951        let cell = AppCell::new();
952        let mut app = cell.borrow_mut();
953        let offset = FixedViewportOffset::zero(&mut app);
954        let built: Built = Rc::default();
955        let tree = Directionality::new(
956            TextDirection::Ltr,
957            Center::new().child(ShrinkWrappingViewport::new(offset.erase()).slivers(vec![
958                    SliverToBoxAdapter::new()
959                        .child(SizedBox::new().height(50.0))
960                        .into_widget(),
961                    item_list(&built, 2),
962                ])),
963        )
964        .into_widget();
965        let harness = Harness::mount(&mut app, tree);
966        harness.pump(&mut app);
967
968        let center = harness
969            .render_root(&app)
970            .child(&app)
971            .expect("a child")
972            .as_object()
973            .downcast::<RenderPositionedBox>(&app)
974            .expect("a RenderPositionedBox");
975        let viewport = center
976            .child(&app)
977            .expect("the viewport")
978            .as_object()
979            .downcast::<RenderShrinkWrappingViewport>(&app)
980            .expect("a RenderShrinkWrappingViewport");
981        // 50 for the box adapter plus two 40-pixel list items.
982        assert_eq!(viewport.size(&app).height(), 130.0);
983    }
984}