Skip to main content

waft_widgets/widgets/
single_child_scroll_view.rs

1//! Flutter counterpart: `widgets/single_child_scroll_view.dart`.
2//!
3//! Semantics and diagnostics wait; see `PORTING.md`.
4
5use std::any::{Any, TypeId};
6use std::fmt::Debug;
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_animation::Curve;
11use waft_embedder::{Clip, Matrix4, Offset, Rect, Size};
12use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listener};
13use waft_gestures::DragStartBehavior;
14use waft_painting::{
15    Axis, AxisDirection, EdgeInsetsGeometry, axis_direction_to_axis, transform_rect,
16};
17use waft_rendering::{
18    AnyRenderAbstractViewport, AnyRenderBox, AnyRenderObject, AnyViewportOffset, BoxConstraints,
19    BoxHitTestResult, ClipRectLayer, EmptyParentData, HitTestBehavior, LayerHandle,
20    PaintingContext, PipelineOwner, RenderAbstractViewport, RenderBox, RenderBoxData, RenderHandle,
21    RenderObject, RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
22    RevealedOffset, ViewportOffsetRef, show_in_viewport,
23};
24
25use crate::framework::{
26    AnyElement, BuildContext, Element, ElementData, IntoWidget, KeyRef, RenderObjectElement,
27    RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
28    SingleChildRenderObjectElementBase, SingleChildRenderObjectElementData,
29    SingleChildRenderObjectWidget, Slot, StatelessWidget, WidgetRef, downcast_widget,
30};
31use crate::widgets::basic::{Padding, get_axis_direction_from_axis_reverse_and_directionality};
32use crate::widgets::focus_manager::{FocusNodeLeaf, UnfocusDisposition, primary_focus};
33use crate::widgets::focus_scope::FocusScope;
34use crate::widgets::notification_listener::NotificationListener;
35use crate::widgets::primary_scroll_controller::PrimaryScrollController;
36use crate::widgets::scroll_configuration::ScrollConfiguration;
37use crate::widgets::scroll_controller::ScrollControllerRef;
38use crate::widgets::scroll_notification::{ScrollUpdateNotification, ViewportElementMixin};
39use crate::widgets::scroll_physics::ScrollPhysicsRef;
40use crate::widgets::scroll_view::ScrollViewKeyboardDismissBehavior;
41use crate::widgets::scrollable::{Scrollable, ViewportBuilder};
42
43/// A box in which a single widget can be scrolled.
44///
45/// This widget is useful when you have a single box that will normally be
46/// entirely visible, for example a clock face in a time picker, but you need to
47/// make sure it can be scrolled if the container gets too small in one axis
48/// (the scroll direction).
49///
50/// It is also useful if you need to shrink-wrap in both axes (the main
51/// scrolling direction as well as the cross axis), as one might see in a dialog
52/// or pop-up menu. In that case, you might pair the [`SingleChildScrollView`]
53/// with a `ListBody` child.
54///
55/// When you have a list of children and do not require cross-axis
56/// shrink-wrapping behavior, for example a scrolling list that is always the
57/// width of the screen, consider [`ListView`](crate::ListView), which is vastly
58/// more efficient than a [`SingleChildScrollView`] containing a `ListBody` or
59/// `Column` with many children.
60///
61/// See also:
62///
63///  * [`ListView`](crate::ListView), which handles multiple children in a scrolling list.
64///  * `Scrollable`, which handles arbitrary scrolling effects.
65#[derive(Clone, Debug)]
66pub struct SingleChildScrollView {
67    pub key: Option<KeyRef>,
68
69    /// The [`Axis`] along which the scroll view's offset increases.
70    ///
71    /// Defaults to [`Axis::Vertical`].
72    pub scroll_direction: Axis,
73
74    /// Whether the scroll view scrolls in the reading direction.
75    ///
76    /// For example, if the reading direction is left-to-right and
77    /// [`scroll_direction`](Self::scroll_direction) is [`Axis::Horizontal`], then the scroll
78    /// view scrolls from left to right when [`reverse`](Self::reverse) is false and from right
79    /// to left when it is true.
80    ///
81    /// Defaults to false.
82    pub reverse: bool,
83
84    /// The amount of space by which to inset the child.
85    pub padding: Option<EdgeInsetsGeometry>,
86
87    /// An object that can be used to control the position to which this scroll
88    /// view is scrolled.
89    ///
90    /// Must be `None` if [`primary`](Self::primary) is true.
91    pub controller: Option<ScrollControllerRef>,
92
93    /// Whether this is the primary scroll view associated with the parent
94    /// [`PrimaryScrollController`].
95    pub primary: Option<bool>,
96
97    /// How the scroll view should respond to user input.
98    ///
99    /// For example, determines how the scroll view continues to animate after the
100    /// user stops dragging the scroll view.
101    ///
102    /// Defaults to matching platform conventions.
103    pub physics: Option<ScrollPhysicsRef>,
104
105    /// The widget that scrolls.
106    pub child: Option<WidgetRef>,
107
108    /// Determines the way that drag start behavior is handled.
109    pub drag_start_behavior: DragStartBehavior,
110
111    /// The content will be clipped (or not) according to this option.
112    ///
113    /// Defaults to [`Clip::HardEdge`].
114    pub clip_behavior: Clip,
115
116    /// How to behave during hit testing when deciding how the hit test propagates to children
117    /// and whether to consider targets behind this scroll view.
118    ///
119    /// Defaults to [`HitTestBehavior::Opaque`].
120    pub hit_test_behavior: HitTestBehavior,
121
122    /// Restoration ID to save and restore the scroll offset of the scrollable.
123    pub restoration_id: Option<String>,
124
125    /// How this scroll view will dismiss the keyboard automatically.
126    ///
127    /// If `None` then it falls back to the inherited
128    /// [`ScrollBehavior::get_keyboard_dismiss_behavior`](crate::ScrollBehavior::get_keyboard_dismiss_behavior).
129    pub keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,
130}
131
132impl Default for SingleChildScrollView {
133    fn default() -> SingleChildScrollView {
134        SingleChildScrollView {
135            key: None,
136            scroll_direction: Axis::Vertical,
137            reverse: false,
138            padding: None,
139            controller: None,
140            primary: None,
141            physics: None,
142            child: None,
143            drag_start_behavior: DragStartBehavior::Start,
144            clip_behavior: Clip::HardEdge,
145            hit_test_behavior: HitTestBehavior::Opaque,
146            restoration_id: None,
147            keyboard_dismiss_behavior: None,
148        }
149    }
150}
151
152impl SingleChildScrollView {
153    /// Creates a box in which a single widget can be scrolled.
154    pub fn new() -> SingleChildScrollView {
155        SingleChildScrollView::default()
156    }
157
158    /// Dart `SingleChildScrollView(key:)`.
159    pub fn key(mut self, key: KeyRef) -> SingleChildScrollView {
160        self.key = Some(key);
161        self
162    }
163
164    /// Dart `SingleChildScrollView(scrollDirection:)`.
165    pub fn scroll_direction(mut self, scroll_direction: Axis) -> SingleChildScrollView {
166        self.scroll_direction = scroll_direction;
167        self
168    }
169
170    /// Dart `SingleChildScrollView(reverse:)`.
171    pub fn reverse(mut self, reverse: bool) -> SingleChildScrollView {
172        self.reverse = reverse;
173        self
174    }
175
176    /// Dart `SingleChildScrollView(padding:)`.
177    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> SingleChildScrollView {
178        let padding = padding.into();
179        self.padding = Some(padding);
180        self
181    }
182
183    /// Dart `SingleChildScrollView(controller:)`.
184    pub fn controller(mut self, controller: ScrollControllerRef) -> SingleChildScrollView {
185        debug_assert!(
186            !self.primary.unwrap_or(false),
187            "Primary ScrollViews obtain their ScrollController via inheritance from a \
188             PrimaryScrollController widget. You cannot both set primary to true and pass an \
189             explicit controller."
190        );
191        self.controller = Some(controller);
192        self
193    }
194
195    /// Dart `SingleChildScrollView(primary:)`.
196    pub fn primary(mut self, primary: bool) -> SingleChildScrollView {
197        debug_assert!(
198            !(self.controller.is_some() && primary),
199            "Primary ScrollViews obtain their ScrollController via inheritance from a \
200             PrimaryScrollController widget. You cannot both set primary to true and pass an \
201             explicit controller."
202        );
203        self.primary = Some(primary);
204        self
205    }
206
207    /// Dart `SingleChildScrollView(physics:)`.
208    pub fn physics(mut self, physics: ScrollPhysicsRef) -> SingleChildScrollView {
209        self.physics = Some(physics);
210        self
211    }
212
213    /// Dart `SingleChildScrollView(child:)`.
214    #[cfg_attr(debug_assertions, track_caller)]
215    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SingleChildScrollView {
216        self.child = Some(child.into_widget());
217        self
218    }
219
220    /// Dart `SingleChildScrollView(dragStartBehavior:)`.
221    pub fn drag_start_behavior(
222        mut self,
223        drag_start_behavior: DragStartBehavior,
224    ) -> SingleChildScrollView {
225        self.drag_start_behavior = drag_start_behavior;
226        self
227    }
228
229    /// Dart `SingleChildScrollView(clipBehavior:)`.
230    pub fn clip_behavior(mut self, clip_behavior: Clip) -> SingleChildScrollView {
231        self.clip_behavior = clip_behavior;
232        self
233    }
234
235    /// Dart `SingleChildScrollView(hitTestBehavior:)`.
236    pub fn hit_test_behavior(
237        mut self,
238        hit_test_behavior: HitTestBehavior,
239    ) -> SingleChildScrollView {
240        self.hit_test_behavior = hit_test_behavior;
241        self
242    }
243
244    /// Dart `SingleChildScrollView(restorationId:)`.
245    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> SingleChildScrollView {
246        self.restoration_id = Some(restoration_id.into());
247        self
248    }
249
250    /// Dart `SingleChildScrollView(keyboardDismissBehavior:)`.
251    pub fn keyboard_dismiss_behavior(
252        mut self,
253        keyboard_dismiss_behavior: ScrollViewKeyboardDismissBehavior,
254    ) -> SingleChildScrollView {
255        self.keyboard_dismiss_behavior = Some(keyboard_dismiss_behavior);
256        self
257    }
258
259    fn get_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
260        get_axis_direction_from_axis_reverse_and_directionality(
261            app,
262            context,
263            self.scroll_direction,
264            self.reverse,
265        )
266    }
267
268    /// Dart's `contents`: the child, inset by [`padding`](Self::padding) when there is one.
269    fn contents(&self) -> Option<WidgetRef> {
270        let contents = self.child.clone();
271        let Some(padding) = self.padding else {
272            return contents;
273        };
274        let mut inset = Padding::new(padding);
275        if let Some(child) = contents {
276            inset = inset.child(child);
277        }
278        Some(inset.into_widget())
279    }
280}
281
282impl StatelessWidget for SingleChildScrollView {
283    fn key(&self) -> Option<&KeyRef> {
284        self.key.as_ref()
285    }
286
287    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
288        let axis_direction = self.get_direction(app, context);
289        let contents = self.contents();
290        let effective_primary = self.primary.unwrap_or_else(|| {
291            self.controller.is_none()
292                && PrimaryScrollController::should_inherit(app, context, self.scroll_direction)
293        });
294
295        let scroll_controller = if effective_primary {
296            PrimaryScrollController::maybe_of(app, context)
297        } else {
298            self.controller.clone()
299        };
300
301        let clip_behavior = self.clip_behavior;
302        let viewport_builder: ViewportBuilder = Rc::new(move |_app, _context, offset| {
303            let mut viewport =
304                SingleChildViewport::new(offset, clip_behavior).axis_direction(axis_direction);
305            if let Some(contents) = contents.clone() {
306                viewport = viewport.child(contents);
307            }
308            viewport.into_widget()
309        });
310
311        let mut scrollable = Scrollable::new(viewport_builder)
312            .drag_start_behavior(self.drag_start_behavior)
313            .axis_direction(axis_direction)
314            .clip_behavior(self.clip_behavior)
315            .hit_test_behavior(self.hit_test_behavior);
316        let has_scroll_controller = scroll_controller.is_some();
317        if let Some(controller) = scroll_controller {
318            scrollable = scrollable.controller(controller);
319        }
320        if let Some(physics) = self.physics.clone() {
321            scrollable = scrollable.physics(physics);
322        }
323        if let Some(restoration_id) = self.restoration_id.clone() {
324            scrollable = scrollable.restoration_id(restoration_id);
325        }
326        let mut scrollable = scrollable.into_widget();
327
328        let effective_keyboard_dismiss_behavior =
329            self.keyboard_dismiss_behavior.unwrap_or_else(|| {
330                ScrollConfiguration::of(app, context).get_keyboard_dismiss_behavior(app, context)
331            });
332
333        if effective_keyboard_dismiss_behavior == ScrollViewKeyboardDismissBehavior::OnDrag {
334            scrollable = NotificationListener::<ScrollUpdateNotification>::new(scrollable)
335                .on_notification(move |app, notification: &ScrollUpdateNotification| {
336                    let current_scope = FocusScope::of(app, context, true).as_node();
337                    if notification.drag_details.is_some()
338                        && !current_scope.has_primary_focus(app)
339                        && current_scope.has_focus(app)
340                        && let Some(primary) = primary_focus(app)
341                    {
342                        primary.unfocus(app, UnfocusDisposition::Scope);
343                    }
344                    false
345                })
346                .into_widget();
347        }
348
349        if effective_primary && has_scroll_controller {
350            // Further descendant scroll views will not inherit the same
351            // `PrimaryScrollController`.
352            PrimaryScrollController::none(scrollable).into_widget()
353        } else {
354            scrollable
355        }
356    }
357}
358
359/// Dart's `_SingleChildViewport`: the box viewport a [`SingleChildScrollView`] scrolls.
360#[derive(Debug)]
361pub struct SingleChildViewport {
362    /// The direction in which the [`offset`](Self::offset)'s pixels increase.
363    pub axis_direction: AxisDirection,
364    /// Which part of the content inside the viewport should be visible.
365    pub offset: ViewportOffsetRef,
366    /// The content will be clipped (or not) according to this option.
367    pub clip_behavior: Clip,
368    /// The widget that scrolls.
369    pub child: Option<WidgetRef>,
370}
371
372impl SingleChildViewport {
373    /// Creates a viewport for a single box child.
374    pub fn new(offset: ViewportOffsetRef, clip_behavior: Clip) -> SingleChildViewport {
375        SingleChildViewport {
376            axis_direction: AxisDirection::Down,
377            offset,
378            clip_behavior,
379            child: None,
380        }
381    }
382
383    /// Dart `_SingleChildViewport(axisDirection:)`.
384    pub fn axis_direction(mut self, axis_direction: AxisDirection) -> SingleChildViewport {
385        self.axis_direction = axis_direction;
386        self
387    }
388
389    /// Dart `_SingleChildViewport(child:)`.
390    #[cfg_attr(debug_assertions, track_caller)]
391    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SingleChildViewport {
392        self.child = Some(child.into_widget());
393        self
394    }
395}
396
397impl RenderObjectWidget for SingleChildViewport {
398    type RenderObject = RenderSingleChildViewport;
399
400    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
401        RenderSingleChildViewport::new(
402            app,
403            self.axis_direction,
404            self.offset.clone(),
405            None,
406            self.clip_behavior,
407        )
408        .as_object()
409    }
410
411    fn update_render_object(
412        &self,
413        app: &mut App,
414        _context: BuildContext,
415        render_object: RenderHandle<RenderSingleChildViewport>,
416    ) {
417        // Order dependency: the offset setter reads the axis direction.
418        render_object.set_axis_direction(app, self.axis_direction);
419        render_object.set_offset(app, self.offset.clone());
420        render_object.set_clip_behavior(app, self.clip_behavior);
421    }
422}
423
424impl SingleChildRenderObjectWidget for SingleChildViewport {
425    fn child(&self) -> Option<&WidgetRef> {
426        self.child.as_ref()
427    }
428
429    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
430        SingleChildViewportElement::new(app, this).as_element()
431    }
432}
433
434/// Dart's `_SingleChildViewportElement`: a single-child render object element that is also a
435/// notification node, so a `ScrollNotification` bubbling past it counts one viewport deeper.
436pub struct SingleChildViewportElement {
437    element: ElementData,
438    render_object_element: RenderObjectElementData,
439    single_child: SingleChildRenderObjectElementData,
440}
441
442impl SingleChildViewportElement {
443    /// Creates an element that uses the given widget as its configuration.
444    pub fn new(app: &mut App, widget: WidgetRef) -> Handle<SingleChildViewportElement> {
445        debug_assert!(downcast_widget::<SingleChildViewport>(&*widget).is_some());
446        app.create(SingleChildViewportElement {
447            element: ElementData::new(widget),
448            render_object_element: RenderObjectElementData::default(),
449            single_child: SingleChildRenderObjectElementData::default(),
450        })
451        .into_tree_node(app)
452    }
453}
454
455impl RenderObjectElementWidget for SingleChildViewportElement {
456    type Widget = SingleChildViewport;
457
458    fn widget_of(widget: &WidgetRef) -> &SingleChildViewport {
459        downcast_widget::<SingleChildViewport>(&**widget)
460            .expect("a SingleChildViewportElement holds its SingleChildViewport")
461    }
462}
463
464impl RenderObjectElement for SingleChildViewportElement {
465    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
466        &app.get(self).render_object_element
467    }
468
469    fn render_object_element_data_mut(
470        self: Handle<Self>,
471        app: &mut App,
472    ) -> &mut RenderObjectElementData {
473        &mut app.get_mut(self).render_object_element
474    }
475}
476
477impl SingleChildRenderObjectElementBase for SingleChildViewportElement {
478    fn single_child_data(self: Handle<Self>, app: &App) -> &SingleChildRenderObjectElementData {
479        &app.get(self).single_child
480    }
481
482    fn single_child_data_mut(
483        self: Handle<Self>,
484        app: &mut App,
485    ) -> &mut SingleChildRenderObjectElementData {
486        &mut app.get_mut(self).single_child
487    }
488}
489
490impl ViewportElementMixin for SingleChildViewportElement {}
491
492impl Element for SingleChildViewportElement {
493    crate::element_accessors!();
494
495    const IS_RENDER_OBJECT_ELEMENT: bool = true;
496
497    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
498        self.render_object_element_data(app).render_object()
499    }
500
501    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
502        None
503    }
504
505    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
506        self.render_object_element_data(app).debug_doing_build()
507    }
508
509    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
510        SingleChildRenderObjectElementBase::visit_children(self, app, visitor);
511    }
512
513    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
514        SingleChildRenderObjectElementBase::forget_child(self, app, child);
515    }
516
517    fn mount(
518        self: Handle<Self>,
519        app: &mut App,
520        parent: Option<AnyElement>,
521        new_slot: Option<Slot>,
522    ) {
523        SingleChildRenderObjectElementBase::mount(self, app, parent, new_slot);
524    }
525
526    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
527        SingleChildRenderObjectElementBase::update(self, app, new_widget);
528    }
529
530    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
531        RenderObjectElement::perform_rebuild(self, app);
532    }
533
534    fn deactivate(self: Handle<Self>, app: &mut App) {
535        RenderObjectElement::deactivate(self, app);
536    }
537
538    fn unmount(self: Handle<Self>, app: &mut App) {
539        RenderObjectElement::unmount(self, app);
540    }
541
542    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
543        RenderObjectElement::update_parent_data(self, app, parent_data_element);
544    }
545
546    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
547        RenderObjectElement::update_slot(self, app, new_slot);
548    }
549
550    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
551        RenderObjectElement::attach_render_object(self, app, new_slot);
552    }
553
554    fn detach_render_object(self: Handle<Self>, app: &mut App) {
555        RenderObjectElement::detach_render_object(self, app);
556    }
557
558    fn insert_render_object_child(
559        self: Handle<Self>,
560        app: &mut App,
561        child: AnyRenderObject,
562        slot: Option<Slot>,
563    ) {
564        SingleChildRenderObjectElementBase::insert_render_object_child(self, app, child, slot);
565    }
566
567    fn move_render_object_child(
568        self: Handle<Self>,
569        app: &mut App,
570        child: AnyRenderObject,
571        old_slot: Option<Slot>,
572        new_slot: Option<Slot>,
573    ) {
574        SingleChildRenderObjectElementBase::move_render_object_child(
575            self, app, child, old_slot, new_slot,
576        );
577    }
578
579    fn remove_render_object_child(
580        self: Handle<Self>,
581        app: &mut App,
582        child: AnyRenderObject,
583        slot: Option<Slot>,
584    ) {
585        SingleChildRenderObjectElementBase::remove_render_object_child(self, app, child, slot);
586    }
587
588    fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
589        ViewportElementMixin::attach_notification_tree(self, app);
590    }
591
592    fn on_notification(
593        self: Handle<Self>,
594        app: &mut App,
595        notification: &dyn crate::framework::Notification,
596    ) -> bool {
597        ViewportElementMixin::on_notification(self, app, notification)
598    }
599}
600
601/// Dart's `_RenderSingleChildViewport`: a viewport that shows one box child, moved by a
602/// `ViewportOffset` and sized to that child in the cross axis.
603pub struct RenderSingleChildViewport {
604    render_object: RenderObjectData,
605    render_box: RenderBoxData,
606    child: RenderObjectWithChildData<AnyRenderBox>,
607    axis_direction: AxisDirection,
608    offset: ViewportOffsetRef,
609    clip_behavior: Clip,
610    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
611}
612
613impl RenderSingleChildViewport {
614    /// Creates a viewport for a single box child.
615    pub fn new(
616        app: &mut App,
617        axis_direction: AxisDirection,
618        offset: ViewportOffsetRef,
619        child: Option<AnyRenderBox>,
620        clip_behavior: Clip,
621    ) -> RenderHandle<RenderSingleChildViewport> {
622        let this = RenderHandle::new_box(
623            app,
624            RenderSingleChildViewport {
625                render_object: RenderObjectData::new(),
626                render_box: RenderBoxData::new(),
627                child: RenderObjectWithChildData::new(),
628                axis_direction,
629                offset,
630                clip_behavior,
631                clip_rect_layer: LayerHandle::new(),
632            },
633        );
634        this.set_child(app, child);
635        this
636    }
637
638    /// The direction in which the [`offset`](Self::offset)'s pixels increase.
639    pub fn axis_direction(self: RenderHandle<Self>, app: &App) -> AxisDirection {
640        self.get(app).axis_direction
641    }
642
643    /// Sets [`axis_direction`](Self::axis_direction).
644    pub fn set_axis_direction(self: RenderHandle<Self>, app: &mut App, value: AxisDirection) {
645        if value == self.get(app).axis_direction {
646            return;
647        }
648        self.get_mut(app).axis_direction = value;
649        self.mark_needs_layout(app);
650    }
651
652    /// The axis along which the viewport scrolls.
653    pub fn axis(self: RenderHandle<Self>, app: &App) -> Axis {
654        axis_direction_to_axis(self.axis_direction(app))
655    }
656
657    /// Which part of the content inside the viewport should be visible.
658    pub fn offset(self: RenderHandle<Self>, app: &App) -> AnyViewportOffset {
659        self.get(app).offset.handle()
660    }
661
662    /// Sets [`offset`](Self::offset).
663    pub fn set_offset(self: RenderHandle<Self>, app: &mut App, value: ViewportOffsetRef) {
664        let old = self.offset(app);
665        if value == old {
666            return;
667        }
668        if self.attached(app) {
669            old.remove_listener(app, &self.has_scrolled_listener());
670        }
671        let new = value.handle();
672        // The old offset goes when this local does, after the listener moved off it.
673        let _old = std::mem::replace(&mut self.get_mut(app).offset, value);
674        if self.attached(app) {
675            new.add_listener(app, self.has_scrolled_listener());
676        }
677        self.mark_needs_layout(app);
678    }
679
680    /// The content will be clipped (or not) according to this option.
681    ///
682    /// Defaults to [`Clip::None`].
683    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
684        self.get(app).clip_behavior
685    }
686
687    /// Sets [`clip_behavior`](Self::clip_behavior).
688    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
689        if value == self.get(app).clip_behavior {
690            return;
691        }
692        self.get_mut(app).clip_behavior = value;
693        self.mark_needs_paint(app);
694    }
695
696    /// Dart's `_offset.addListener(_hasScrolled)` tear-off.
697    fn has_scrolled_listener(self: RenderHandle<Self>) -> Listener {
698        Listener::handle_method(self.handle(), has_scrolled)
699    }
700
701    fn viewport_extent(self: RenderHandle<Self>, app: &App) -> f64 {
702        debug_assert!(self.has_size(app));
703        match self.axis(app) {
704            Axis::Horizontal => self.size(app).width(),
705            Axis::Vertical => self.size(app).height(),
706        }
707    }
708
709    fn min_scroll_extent(self: RenderHandle<Self>, app: &App) -> f64 {
710        debug_assert!(self.has_size(app));
711        0.0
712    }
713
714    fn max_scroll_extent(self: RenderHandle<Self>, app: &App) -> f64 {
715        debug_assert!(self.has_size(app));
716        let Some(child) = self.child(app) else {
717            return 0.0;
718        };
719        let extent = match self.axis(app) {
720            Axis::Horizontal => child.size(app).width() - self.size(app).width(),
721            Axis::Vertical => child.size(app).height() - self.size(app).height(),
722        };
723        extent.max(0.0)
724    }
725
726    fn get_inner_constraints(
727        self: RenderHandle<Self>,
728        app: &App,
729        constraints: BoxConstraints,
730    ) -> BoxConstraints {
731        match self.axis(app) {
732            Axis::Horizontal => constraints.height_constraints(),
733            Axis::Vertical => constraints.width_constraints(),
734        }
735    }
736
737    /// The offset the child is painted at, for the offset's current pixels.
738    fn paint_offset(self: RenderHandle<Self>, app: &App) -> Offset {
739        self.paint_offset_for_position(app, self.offset(app).pixels(app))
740    }
741
742    fn paint_offset_for_position(self: RenderHandle<Self>, app: &App, position: f64) -> Offset {
743        let child = self.child(app).expect("a paint offset needs the content");
744        let child_size = child.size(app);
745        let size = self.size(app);
746        match self.axis_direction(app) {
747            AxisDirection::Up => Offset::new(0.0, position - child_size.height() + size.height()),
748            AxisDirection::Left => Offset::new(position - child_size.width() + size.width(), 0.0),
749            AxisDirection::Right => Offset::new(-position, 0.0),
750            AxisDirection::Down => Offset::new(0.0, -position),
751        }
752    }
753
754    fn should_clip_at_paint_offset(
755        self: RenderHandle<Self>,
756        app: &App,
757        paint_offset: Offset,
758    ) -> bool {
759        let child = self.child(app).expect("the clip test needs the content");
760        match self.clip_behavior(app) {
761            Clip::None => false,
762            Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => {
763                let child_size = child.size(app);
764                let size = self.size(app);
765                paint_offset.dx() < 0.0
766                    || paint_offset.dy() < 0.0
767                    || paint_offset.dx() + child_size.width() > size.width()
768                    || paint_offset.dy() + child_size.height() > size.height()
769            }
770        }
771    }
772
773    fn paint_contents(
774        self: RenderHandle<Self>,
775        app: &mut App,
776        context: &mut PaintingContext,
777        offset: Offset,
778    ) {
779        let child = self.child(app).expect("checked by the caller");
780        let paint_offset = self.paint_offset(app);
781        context.paint_child(app, child.as_object(), offset + paint_offset);
782    }
783}
784
785/// Dart's `_hasScrolled`: a named function so that the listener added on attach compares equal
786/// to the one removed on detach.
787fn has_scrolled(this: Handle<RenderSingleChildViewport>, app: &mut App) {
788    RenderHandle::from_handle(this).mark_needs_paint(app);
789}
790
791/// Dart's `transform.translateByDouble(dx, dy, 0, 1)`.
792fn translate(transform: &mut Matrix4, offset: Offset) {
793    *transform = transform.then(&Matrix4::translation(
794        offset.dx() as f32,
795        offset.dy() as f32,
796    ));
797}
798
799impl RenderObjectWithChildMixin for RenderSingleChildViewport {
800    type ChildType = AnyRenderBox;
801
802    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
803        &self.get(app).child
804    }
805
806    fn child_data_mut(
807        self: RenderHandle<Self>,
808        app: &mut App,
809    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
810        &mut self.get_mut(app).child
811    }
812}
813
814impl RenderObject for RenderSingleChildViewport {
815    waft_rendering::render_object_accessors!();
816
817    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
818        true
819    }
820
821    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
822        if let Some(child) = self.child(app) {
823            child.as_object().attach(app, owner);
824        }
825        self.offset(app)
826            .add_listener(app, self.has_scrolled_listener());
827    }
828
829    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
830        self.offset(app)
831            .remove_listener(app, &self.has_scrolled_listener());
832        if let Some(child) = self.child(app) {
833            child.as_object().detach(app);
834        }
835    }
836
837    fn visit_children(
838        self: RenderHandle<Self>,
839        app: &App,
840        visitor: &mut dyn FnMut(AnyRenderObject),
841    ) {
842        if let Some(child) = self.child(app) {
843            visitor(child.as_object());
844        }
845    }
846
847    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
848        let constraints = self.constraints(app);
849        match self.child(app) {
850            None => self.set_size(app, constraints.smallest()),
851            Some(child) => {
852                let inner_constraints = self.get_inner_constraints(app, constraints);
853                child.layout(app, inner_constraints, true);
854                let size = constraints.constrain(child.size(app));
855                self.set_size(app, size);
856            }
857        }
858
859        let offset = self.offset(app);
860        if offset.has_pixels(app) {
861            let pixels = offset.pixels(app);
862            let max_scroll_extent = self.max_scroll_extent(app);
863            let min_scroll_extent = self.min_scroll_extent(app);
864            if pixels > max_scroll_extent {
865                offset.correct_by(app, max_scroll_extent - pixels);
866            } else if pixels < min_scroll_extent {
867                offset.correct_by(app, min_scroll_extent - pixels);
868            }
869        }
870
871        let viewport_extent = self.viewport_extent(app);
872        offset.apply_viewport_dimension(app, viewport_extent);
873        let (min_scroll_extent, max_scroll_extent) =
874            (self.min_scroll_extent(app), self.max_scroll_extent(app));
875        offset.apply_content_dimensions(app, min_scroll_extent, max_scroll_extent);
876    }
877
878    fn paint(
879        self: RenderHandle<Self>,
880        app: &mut App,
881        context: &mut PaintingContext,
882        offset: Offset,
883    ) {
884        if self.child(app).is_none() {
885            return;
886        }
887        let paint_offset = self.paint_offset(app);
888        if self.should_clip_at_paint_offset(app, paint_offset) {
889            let bounds = Offset::ZERO & self.size(app);
890            let clip_behavior = self.clip_behavior(app);
891            let old = self.get(app).clip_rect_layer.layer();
892            let layer = context.push_clip_rect(
893                app,
894                self.as_object().needs_compositing(app),
895                offset,
896                bounds,
897                |app, context, offset| self.paint_contents(app, context, offset),
898                clip_behavior,
899                old,
900            );
901            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
902        } else {
903            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
904            self.paint_contents(app, context, offset);
905        }
906    }
907
908    fn dispose(self: RenderHandle<Self>, app: &mut App) {
909        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
910        waft_rendering::RenderObjectBase::dispose(self, app);
911    }
912
913    /// Dart's `describeApproximatePaintClip`: the content is clipped to the viewport when the
914    /// paint offset takes it past an edge.
915    fn describe_approximate_paint_clip(
916        self: RenderHandle<Self>,
917        app: &App,
918        _child: AnyRenderObject,
919    ) -> Option<Rect> {
920        // Dart's `child != null` is the erased child the caller visits.
921        if self.child(app).is_some()
922            && self.should_clip_at_paint_offset(app, self.paint_offset(app))
923        {
924            Some(Offset::ZERO & self.size(app))
925        } else {
926            None
927        }
928    }
929
930    fn show_on_screen(
931        self: RenderHandle<Self>,
932        app: &mut App,
933        descendant: Option<AnyRenderObject>,
934        rect: Option<Rect>,
935        duration: Duration,
936        curve: Rc<dyn Curve>,
937    ) {
938        let offset = self.offset(app);
939        if !offset.allow_implicit_scrolling(app) {
940            return waft_rendering::RenderObjectBase::show_on_screen(
941                self, app, descendant, rect, duration, curve,
942            );
943        }
944
945        let new_rect = show_in_viewport(
946            app,
947            descendant,
948            rect,
949            self.as_abstract_viewport(),
950            offset,
951            duration,
952            Rc::clone(&curve),
953        );
954        waft_rendering::RenderObjectBase::show_on_screen(
955            self, app, None, new_rect, duration, curve,
956        );
957    }
958
959    fn debug_fill_properties(
960        self: RenderHandle<Self>,
961        app: &App,
962        properties: &mut DiagnosticPropertiesBuilder,
963    ) {
964        properties.add(DiagnosticsProperty::<Offset>::new(
965            "offset",
966            Some(self.paint_offset(app)),
967        ));
968    }
969
970    fn interface(self: RenderHandle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
971        (id == TypeId::of::<AnyRenderAbstractViewport>())
972            .then(|| Box::new(self.as_abstract_viewport()) as Box<dyn Any>)
973    }
974}
975
976impl RenderBox for RenderSingleChildViewport {
977    waft_rendering::render_box_accessors!();
978
979    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
980        // We don't actually use the offset argument in `BoxParentData`, so let's avoid
981        // allocating it at all.
982        if child.parent_data(app).is_none() {
983            child.set_parent_data(app, EmptyParentData);
984        }
985    }
986
987    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
988        match self.child(app) {
989            Some(child) => child.get_min_intrinsic_width(app, height),
990            None => 0.0,
991        }
992    }
993
994    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
995        match self.child(app) {
996            Some(child) => child.get_max_intrinsic_width(app, height),
997            None => 0.0,
998        }
999    }
1000
1001    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1002        match self.child(app) {
1003            Some(child) => child.get_min_intrinsic_height(app, width),
1004            None => 0.0,
1005        }
1006    }
1007
1008    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1009        match self.child(app) {
1010            Some(child) => child.get_max_intrinsic_height(app, width),
1011            None => 0.0,
1012        }
1013    }
1014
1015    // We don't override `compute_distance_to_actual_baseline`, because we want the default
1016    // behavior (returning none). Otherwise, as you scroll, it would shift in its parent if the
1017    // parent was baseline-aligned, which makes no sense.
1018
1019    fn compute_dry_layout(
1020        self: RenderHandle<Self>,
1021        app: &mut App,
1022        constraints: BoxConstraints,
1023    ) -> Size {
1024        let Some(child) = self.child(app) else {
1025            return constraints.smallest();
1026        };
1027        let inner_constraints = self.get_inner_constraints(app, constraints);
1028        let child_size = child.get_dry_layout(app, inner_constraints);
1029        constraints.constrain(child_size)
1030    }
1031
1032    fn apply_paint_transform(
1033        self: RenderHandle<Self>,
1034        app: &App,
1035        _child: AnyRenderObject,
1036        transform: &mut Matrix4,
1037    ) {
1038        translate(transform, self.paint_offset(app));
1039    }
1040
1041    fn hit_test_children(
1042        self: RenderHandle<Self>,
1043        app: &mut App,
1044        result: &mut BoxHitTestResult<'_>,
1045        position: Offset,
1046    ) -> bool {
1047        let Some(child) = self.child(app) else {
1048            return false;
1049        };
1050        let paint_offset = self.paint_offset(app);
1051        result.add_with_paint_offset(Some(paint_offset), position, |result, transformed| {
1052            debug_assert_eq!(transformed, position + -paint_offset);
1053            child.hit_test(app, result, transformed)
1054        })
1055    }
1056}
1057
1058impl RenderAbstractViewport for RenderSingleChildViewport {
1059    fn get_offset_to_reveal(
1060        self: RenderHandle<Self>,
1061        app: &App,
1062        target: AnyRenderObject,
1063        alignment: f64,
1064        rect: Option<Rect>,
1065        _axis: Option<Axis>,
1066    ) -> RevealedOffset {
1067        let rect = rect.unwrap_or_else(|| target.paint_bounds(app));
1068        let Some(target_box) = target.as_box() else {
1069            return RevealedOffset::new(self.offset(app).pixels(app), rect);
1070        };
1071
1072        let child = self.child(app).expect("the content is revealed in");
1073        let transform = target_box
1074            .as_object()
1075            .get_transform_to(app, Some(child.as_object()));
1076        let bounds = transform_rect(&transform, rect);
1077        let content_size = child.size(app);
1078        let size = self.size(app);
1079
1080        let (main_axis_extent, leading_scroll_offset, target_main_axis_extent) =
1081            match self.axis_direction(app) {
1082                AxisDirection::Up => (
1083                    size.height(),
1084                    content_size.height() - bounds.bottom,
1085                    bounds.height(),
1086                ),
1087                AxisDirection::Left => (
1088                    size.width(),
1089                    content_size.width() - bounds.right,
1090                    bounds.width(),
1091                ),
1092                AxisDirection::Right => (size.width(), bounds.left, bounds.width()),
1093                AxisDirection::Down => (size.height(), bounds.top, bounds.height()),
1094            };
1095
1096        let target_offset =
1097            leading_scroll_offset - (main_axis_extent - target_main_axis_extent) * alignment;
1098        let target_rect = bounds.shift(self.paint_offset_for_position(app, target_offset));
1099        RevealedOffset::new(target_offset, target_rect)
1100    }
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105    use std::any::Any;
1106
1107    use waft_embedder::{SceneBuilder, Size, TextDirection, valo::Op};
1108    use waft_foundation::DiagnosticLevel;
1109    use waft_gestures::{HitTestEntry, HitTestResult};
1110    use waft_painting::{EdgeInsets, transform_point};
1111    use waft_rendering::{BoxHitTestEntry, RenderPadding};
1112
1113    use super::*;
1114    use crate::testing::{WidgetTester, test_widgets};
1115    use crate::widgets::basic::{Directionality, Listener, SizedBox};
1116    use crate::widgets::media_query::{MediaQuery, MediaQueryData};
1117    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
1118
1119    const VIEW_WIDTH: f64 = WidgetTester::SIZE.width();
1120    const VIEW_HEIGHT: f64 = WidgetTester::SIZE.height();
1121    const CONTENT_WIDTH: f64 = 100.0;
1122    /// Longer than the view is wide and high.
1123    const CONTENT_HEIGHT: f64 = 1000.0;
1124    /// The height of the target inside the content, and the space above it, which puts the
1125    /// target below the view at scroll offset zero.
1126    const TARGET_EXTENT: f64 = 50.0;
1127    const LEADING_EXTENT: f64 = 700.0;
1128
1129    /// The tree every test mounts: a text direction and a media query, which a `Scrollable`
1130    /// reads for its gesture settings.
1131    fn wrap<K>(child: impl IntoWidget<K>) -> WidgetRef {
1132        let query: WidgetRef =
1133            MediaQuery::new(MediaQueryData::new().size(WidgetTester::SIZE), child).into_widget();
1134        Directionality::new(TextDirection::Ltr, query).into_widget()
1135    }
1136
1137    /// A box that answers a hit test, so a hit can tell which child was reached.
1138    fn opaque(width: f64, height: f64) -> WidgetRef {
1139        Listener {
1140            behavior: HitTestBehavior::Opaque,
1141            child: Some(SizedBox::new().width(width).height(height).into_widget()),
1142            ..Default::default()
1143        }
1144        .into_widget()
1145    }
1146
1147    /// Content taller than the viewport, with an opaque target `LEADING_EXTENT` down it.
1148    fn tall_content() -> WidgetRef {
1149        Padding::new(EdgeInsetsGeometry::Insets(EdgeInsets::only(
1150            0.0,
1151            LEADING_EXTENT,
1152            0.0,
1153            CONTENT_HEIGHT - LEADING_EXTENT - TARGET_EXTENT,
1154        )))
1155        .child(opaque(CONTENT_WIDTH, TARGET_EXTENT))
1156        .into_widget()
1157    }
1158
1159    fn find<T: RenderObject>(app: &App, object: AnyRenderObject) -> Option<RenderHandle<T>> {
1160        if let Some(found) = object.downcast::<T>(app) {
1161            return Some(found);
1162        }
1163        let mut found = None;
1164        object.visit_children(app, &mut |child| {
1165            found = found.or_else(|| find::<T>(app, child));
1166        });
1167        found
1168    }
1169
1170    fn mount(
1171        tester: &mut WidgetTester,
1172        view: SingleChildScrollView,
1173    ) -> RenderHandle<RenderSingleChildViewport> {
1174        tester.pump_widget(wrap(view));
1175        tester.first::<RenderSingleChildViewport>()
1176    }
1177
1178    /// The offset the viewport paints its content at.
1179    fn content_offset(app: &App, viewport: RenderHandle<RenderSingleChildViewport>) -> Offset {
1180        let child = viewport.child(app).expect("the content");
1181        let mut transform = Matrix4::IDENTITY;
1182        viewport
1183            .as_object()
1184            .apply_paint_transform(app, child.as_object(), &mut transform);
1185        transform_point(&transform, Offset::ZERO)
1186    }
1187
1188    /// The boxes a hit test at `position` walked, innermost first.
1189    fn hit_boxes(
1190        app: &mut App,
1191        viewport: RenderHandle<RenderSingleChildViewport>,
1192        position: Offset,
1193    ) -> Vec<AnyRenderBox> {
1194        let mut result = HitTestResult::new();
1195        viewport
1196            .as_box()
1197            .hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
1198        result
1199            .path()
1200            .iter()
1201            .filter_map(|entry: &HitTestEntry| {
1202                let target: &dyn Any = entry.target();
1203                target
1204                    .downcast_ref::<BoxHitTestEntry>()
1205                    .map(BoxHitTestEntry::target)
1206            })
1207            .collect()
1208    }
1209
1210    /// The valo ops the viewport's own layer records.
1211    fn scene_ops(app: &mut App, viewport: RenderHandle<RenderSingleChildViewport>) -> Vec<Op> {
1212        let scene = viewport
1213            .as_object()
1214            .debug_layer(app)
1215            .expect("painted")
1216            .build_scene(app, SceneBuilder::new());
1217        waft_embedder::flattened_ops(&waft_embedder::slices(&scene, |_| None).picture_with_room())
1218    }
1219
1220    #[test]
1221    fn a_vertical_view_gives_its_child_unbounded_height_and_keeps_the_viewport_height() {
1222        test_widgets(|tester| {
1223            let controller = tester.update(ScrollController::default);
1224            let viewport = mount(
1225                tester,
1226                SingleChildScrollView::new()
1227                    .controller(controller.erase())
1228                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
1229            );
1230            let app = tester.cell.borrow();
1231
1232            // The view's constraints are tight, as flutter_test's are, so the cross axis is
1233            // the view's width.
1234            let child = viewport.child(&app).expect("the content");
1235            assert_eq!(child.size(&app), Size::new(VIEW_WIDTH, CONTENT_HEIGHT));
1236            assert_eq!(viewport.size(&app), WidgetTester::SIZE);
1237            assert_eq!(
1238                controller.position(&app).max_scroll_extent(&app),
1239                CONTENT_HEIGHT - VIEW_HEIGHT
1240            );
1241        });
1242    }
1243
1244    #[test]
1245    fn a_horizontal_view_gives_its_child_unbounded_width_and_keeps_the_viewport_width() {
1246        test_widgets(|tester| {
1247            let controller = tester.update(ScrollController::default);
1248            let viewport = mount(
1249                tester,
1250                SingleChildScrollView::new()
1251                    .scroll_direction(Axis::Horizontal)
1252                    .controller(controller.erase())
1253                    .child(SizedBox::new().width(CONTENT_HEIGHT).height(CONTENT_WIDTH)),
1254            );
1255            let app = tester.cell.borrow();
1256
1257            // The view's constraints are tight, as flutter_test's are, so the cross axis is
1258            // the view's height.
1259            let child = viewport.child(&app).expect("the content");
1260            assert_eq!(child.size(&app), Size::new(CONTENT_HEIGHT, VIEW_HEIGHT));
1261            assert_eq!(viewport.size(&app), WidgetTester::SIZE);
1262            assert_eq!(
1263                controller.position(&app).max_scroll_extent(&app),
1264                CONTENT_HEIGHT - VIEW_WIDTH
1265            );
1266        });
1267    }
1268
1269    #[test]
1270    fn the_content_offset_follows_the_controller() {
1271        test_widgets(|tester| {
1272            let controller = tester.update(ScrollController::default);
1273            let viewport = mount(
1274                tester,
1275                SingleChildScrollView::new()
1276                    .controller(controller.erase())
1277                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
1278            );
1279            assert_eq!(
1280                content_offset(&tester.cell.borrow(), viewport),
1281                Offset::ZERO
1282            );
1283
1284            tester.update(|app| controller.jump_to(app, 120.0));
1285            tester.pump();
1286            assert_eq!(
1287                content_offset(&tester.cell.borrow(), viewport),
1288                Offset::new(0.0, -120.0)
1289            );
1290        });
1291    }
1292
1293    /// `single_child_scroll_view.dart`'s `_RenderSingleChildViewport.debugFillProperties`: the
1294    /// offset the child is painted at.
1295    #[test]
1296    fn a_viewport_dump_shows_the_paint_offset() {
1297        test_widgets(|tester| {
1298            let controller = tester.update(ScrollController::default);
1299            let viewport = mount(
1300                tester,
1301                SingleChildScrollView::new()
1302                    .controller(controller.erase())
1303                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
1304            );
1305            tester.update(|app| controller.jump_to(app, 120.0));
1306            tester.pump();
1307
1308            let dump = viewport
1309                .as_object()
1310                .to_string_deep_with(&tester.cell.borrow(), DiagnosticLevel::Info);
1311            assert!(dump.contains("offset: Offset(0.0, -120.0)"), "{dump}");
1312        });
1313    }
1314
1315    #[test]
1316    fn a_reversed_view_starts_at_the_end_of_its_content() {
1317        test_widgets(|tester| {
1318            let controller = tester.update(ScrollController::default);
1319            let viewport = mount(
1320                tester,
1321                SingleChildScrollView::new()
1322                    .reverse(true)
1323                    .controller(controller.erase())
1324                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
1325            );
1326            {
1327                let app = tester.cell.borrow();
1328                assert_eq!(viewport.axis_direction(&app), AxisDirection::Up);
1329                // At scroll offset zero the content's trailing edge sits on the viewport's.
1330                assert_eq!(
1331                    content_offset(&app, viewport),
1332                    Offset::new(0.0, VIEW_HEIGHT - CONTENT_HEIGHT)
1333                );
1334            }
1335
1336            tester.update(|app| controller.jump_to(app, 120.0));
1337            tester.pump();
1338            assert_eq!(
1339                content_offset(&tester.cell.borrow(), viewport),
1340                Offset::new(0.0, VIEW_HEIGHT - CONTENT_HEIGHT + 120.0)
1341            );
1342        });
1343    }
1344
1345    #[test]
1346    fn get_offset_to_reveal_answers_the_offset_that_brings_a_descendant_to_an_edge() {
1347        test_widgets(|tester| {
1348            let viewport = mount(tester, SingleChildScrollView::new().child(tall_content()));
1349            let app = tester.cell.borrow();
1350            let padding = find::<RenderPadding>(&app, viewport.as_object()).expect("the padding");
1351            let target = padding.child(&app).expect("the target").as_object();
1352
1353            // The view's tight constraints make the target as wide as the view.
1354            let leading = viewport.get_offset_to_reveal(&app, target, 0.0, None, None);
1355            assert_eq!(leading.offset, LEADING_EXTENT);
1356            assert_eq!(
1357                leading.rect,
1358                Rect::from_ltwh(0.0, 0.0, VIEW_WIDTH, TARGET_EXTENT)
1359            );
1360
1361            let trailing = viewport.get_offset_to_reveal(&app, target, 1.0, None, None);
1362            assert_eq!(
1363                trailing.offset,
1364                LEADING_EXTENT - (VIEW_HEIGHT - TARGET_EXTENT)
1365            );
1366            assert_eq!(
1367                trailing.rect,
1368                Rect::from_ltwh(0.0, VIEW_HEIGHT - TARGET_EXTENT, VIEW_WIDTH, TARGET_EXTENT)
1369            );
1370        });
1371    }
1372
1373    #[test]
1374    fn a_hit_test_reaches_the_content_through_the_scroll_offset() {
1375        test_widgets(|tester| {
1376            let controller = tester.update(ScrollController::default);
1377            let viewport = mount(
1378                tester,
1379                SingleChildScrollView::new()
1380                    .controller(controller.erase())
1381                    .child(tall_content()),
1382            );
1383            let target = {
1384                let app = tester.cell.borrow();
1385                let padding =
1386                    find::<RenderPadding>(&app, viewport.as_object()).expect("the padding");
1387                padding.child(&app).expect("the target")
1388            };
1389
1390            let near_the_top = Offset::new(50.0, 10.0);
1391            assert!(
1392                !tester
1393                    .update(|app| hit_boxes(app, viewport, near_the_top))
1394                    .contains(&target),
1395                "the target is scrolled out of view"
1396            );
1397
1398            tester.update(|app| controller.jump_to(app, LEADING_EXTENT));
1399            tester.pump();
1400            assert!(
1401                tester
1402                    .update(|app| hit_boxes(app, viewport, near_the_top))
1403                    .contains(&target),
1404                "scrolling the target to the leading edge puts it under the pointer"
1405            );
1406        });
1407    }
1408
1409    /// Content that paints, so a clip around it reaches the scene: valo drops a scope that
1410    /// draws nothing.
1411    fn painted(width: f64, height: f64) -> SizedBox {
1412        SizedBox::new()
1413            .width(width)
1414            .height(height)
1415            .child(crate::widgets::basic::ColoredBox::new(
1416                waft_embedder::Color::new(0xFF00FF00),
1417            ))
1418    }
1419
1420    #[test]
1421    fn overflowing_content_is_clipped_unless_the_clip_behavior_says_otherwise() {
1422        test_widgets(|tester| {
1423            let viewport = mount(
1424                tester,
1425                SingleChildScrollView::new().child(painted(CONTENT_WIDTH, CONTENT_HEIGHT)),
1426            );
1427            let ops = tester.update(|app| scene_ops(app, viewport));
1428            assert!(
1429                ops.iter().any(|op| matches!(op, Op::ClipPath { .. })),
1430                "content taller than the viewport is clipped: {ops:?}"
1431            );
1432        });
1433
1434        test_widgets(|tester| {
1435            let viewport = mount(
1436                tester,
1437                SingleChildScrollView::new()
1438                    .clip_behavior(Clip::None)
1439                    .child(painted(CONTENT_WIDTH, CONTENT_HEIGHT)),
1440            );
1441            assert!(
1442                !tester
1443                    .update(|app| scene_ops(app, viewport))
1444                    .iter()
1445                    .any(|op| matches!(op, Op::ClipPath { .. })),
1446                "Clip::None paints the content unclipped"
1447            );
1448        });
1449
1450        test_widgets(|tester| {
1451            let viewport = mount(
1452                tester,
1453                SingleChildScrollView::new().child(painted(CONTENT_WIDTH, VIEW_HEIGHT)),
1454            );
1455            assert!(
1456                !tester
1457                    .update(|app| scene_ops(app, viewport))
1458                    .iter()
1459                    .any(|op| matches!(op, Op::ClipPath { .. })),
1460                "content that fits needs no clip"
1461            );
1462        });
1463    }
1464
1465    /// `_RenderSingleChildViewport.describeApproximatePaintClip`: content that overflows is
1466    /// described as clipped to the viewport, and `Clip::None` or content that fits as not
1467    /// clipped.
1468    #[test]
1469    fn describe_approximate_paint_clip_answers_the_viewports_clip() {
1470        for (clip_behavior, content_height, clipped) in [
1471            (Clip::HardEdge, CONTENT_HEIGHT, true),
1472            (Clip::None, CONTENT_HEIGHT, false),
1473            (Clip::HardEdge, VIEW_HEIGHT, false),
1474        ] {
1475            test_widgets(|tester| {
1476                let viewport = mount(
1477                    tester,
1478                    SingleChildScrollView::new()
1479                        .clip_behavior(clip_behavior)
1480                        .child(painted(CONTENT_WIDTH, content_height)),
1481                );
1482                let app = tester.cell.borrow();
1483                let child = viewport.child(&app).expect("the content");
1484                let expected = clipped.then(|| Offset::ZERO & viewport.size(&app));
1485                assert_eq!(
1486                    viewport
1487                        .as_object()
1488                        .describe_approximate_paint_clip(&app, child.as_object()),
1489                    expected,
1490                    "{clip_behavior:?}, content {content_height}"
1491                );
1492            });
1493        }
1494    }
1495}