Skip to main content

waft_widgets/widgets/
scroll_notification.rs

1//! Flutter counterpart: `widgets/scroll_notification.dart`.
2
3use std::any::Any;
4use std::cell::Cell;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_foundation::{App, Handle};
9use waft_gestures::{DragEndDetails, DragStartDetails, DragUpdateDetails};
10use waft_rendering::ScrollDirection;
11
12use crate::framework::{BuildContext, Element, Notification, NotificationNode, NotificationTarget};
13use crate::widgets::notification_listener::LayoutChangedNotification;
14use crate::widgets::scroll_metrics::ScrollMetrics;
15
16/// The fields of Dart's `ViewportNotificationMixin`.
17///
18/// The counter is a [`Cell`] because a notification bubbles as `&dyn Notification`: the
19/// element that increments it never holds the notification exclusively.
20#[derive(Debug, Default)]
21pub struct ViewportNotificationData {
22    depth: Cell<u32>,
23}
24
25impl ViewportNotificationData {
26    /// A notification that has not bubbled through any viewport yet.
27    pub fn new() -> ViewportNotificationData {
28        ViewportNotificationData::default()
29    }
30
31    /// Dart's `ScrollUpdateNotification(depth:)`, which seeds the counter.
32    pub fn with_depth(depth: u32) -> ViewportNotificationData {
33        ViewportNotificationData {
34            depth: Cell::new(depth),
35        }
36    }
37
38    /// The counter a viewport element increments, for
39    /// [`Notification::viewport_depth`](crate::Notification::viewport_depth).
40    pub fn depth_cell(&self) -> &Cell<u32> {
41        &self.depth
42    }
43}
44
45/// Mixin for [`Notification`]s that track how many `RenderAbstractViewport` they
46/// have bubbled through.
47///
48/// This is used by [`ScrollNotification`] and `OverscrollIndicatorNotification`.
49pub trait ViewportNotificationMixin: Notification {
50    /// Dart's mixin fields, held under the field `viewport_notification`.
51    fn viewport_notification_data(&self) -> &ViewportNotificationData;
52
53    /// The number of viewports that this notification has bubbled through.
54    ///
55    /// Typically listeners only respond to notifications with a
56    /// [`depth`](Self::depth) of zero.
57    ///
58    /// Specifically, this is the number of widgets representing
59    /// `RenderAbstractViewport` render objects through which this notification
60    /// has bubbled.
61    fn depth(&self) -> u32 {
62        self.viewport_notification_data().depth.get()
63    }
64
65    /// Dart's `debugFillDescription`, which [`Debug`] writes out.
66    fn debug_fill_description(&self, description: &mut Vec<String>) {
67        let depth = self.depth();
68        let locality = if depth == 0 { "local" } else { "remote" };
69        description.push(format!("depth: {depth} ({locality})"));
70    }
71}
72
73/// A mixin that allows [`Element`]s containing `Viewport`-like widgets to correctly
74/// modify the notification depth of a [`ViewportNotificationMixin`].
75///
76/// The two members are the `Element` virtuals Dart reaches through
77/// `NotifiableElementMixin`; an element that mixes this in forwards both from its
78/// `impl Element`.
79///
80/// See also:
81///   * `Viewport`, which creates a custom `MultiChildRenderObjectElement` that mixes
82///     this in.
83pub trait ViewportElementMixin: Element {
84    /// `NotifiableElementMixin.attachNotificationTree`: a node for this element.
85    fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
86        let this = self.as_element();
87        let parent_tree = this
88            .parent(app)
89            .and_then(|parent| parent.notification_tree(app));
90        this.set_notification_tree(app, Some(Rc::new(NotificationNode::new(parent_tree, this))));
91    }
92
93    /// Counts this viewport, then lets the notification keep bubbling.
94    fn on_notification(self: Handle<Self>, app: &mut App, notification: &dyn Notification) -> bool {
95        let _ = app;
96        if let Some(depth) = notification.viewport_depth() {
97            depth.set(depth.get() + 1);
98        }
99        false
100    }
101}
102
103/// The fields of Dart's `ScrollNotification` base class.
104pub struct ScrollNotificationData {
105    /// A description of a `Scrollable`'s contents, useful for modeling the state
106    /// of its viewport.
107    pub metrics: Rc<dyn ScrollMetrics>,
108
109    /// The build context of the widget that fired this notification.
110    ///
111    /// This can be used to find the scrollable's render objects to determine the
112    /// size of the viewport, for instance.
113    pub context: Option<BuildContext>,
114}
115
116/// A [`Notification`] related to scrolling.
117///
118/// `Scrollable` widgets notify their ancestors about scrolling-related changes.
119/// The notifications have the following lifecycle:
120///
121///  * A [`ScrollStartNotification`], which indicates that the widget has started
122///    scrolling.
123///  * Zero or more [`ScrollUpdateNotification`]s, which indicate that the widget
124///    has changed its scroll position, mixed with zero or more
125///    [`OverscrollNotification`]s, which indicate that the widget has not changed
126///    its scroll position because the change would have caused its scroll
127///    position to go outside its scroll bounds.
128///  * Interspersed with the [`ScrollUpdateNotification`]s and
129///    [`OverscrollNotification`]s are zero or more [`UserScrollNotification`]s,
130///    which indicate that the user has changed the direction in which they are
131///    scrolling.
132///  * A [`ScrollEndNotification`], which indicates that the widget has stopped
133///    scrolling.
134///  * A [`UserScrollNotification`], with a [`direction`](UserScrollNotification::direction)
135///    of [`ScrollDirection::Idle`].
136///
137/// Notifications bubble up through the tree, which means a given
138/// `NotificationListener` will receive notifications for all descendant
139/// `Scrollable` widgets. To focus on notifications from the nearest
140/// `Scrollable` descendant, check that the [`depth`](ViewportNotificationMixin::depth)
141/// of the notification is zero.
142///
143/// When a scroll notification is received by a `NotificationListener`, the
144/// listener will have already completed build and layout, and it is therefore
145/// too late for that widget to call `State::set_state`. Any attempt to adjust the
146/// build or layout based on a scroll notification would result in a layout that
147/// lagged one frame behind, which is a poor user experience. Scroll
148/// notifications are therefore primarily useful for paint effects (since paint
149/// happens after layout).
150///
151/// To drive layout based on the scroll position, consider listening to the
152/// `ScrollPosition` directly (or indirectly via a `ScrollController`).
153pub trait ScrollNotification: LayoutChangedNotification + ViewportNotificationMixin {
154    /// Dart's base-class fields, held under the field `scroll_notification`.
155    fn scroll_notification_data(&self) -> &ScrollNotificationData;
156
157    /// A description of a `Scrollable`'s contents, useful for modeling the state
158    /// of its viewport.
159    fn metrics(&self) -> &Rc<dyn ScrollMetrics> {
160        &self.scroll_notification_data().metrics
161    }
162
163    /// The build context of the widget that fired this notification.
164    fn context(&self) -> Option<BuildContext> {
165        self.scroll_notification_data().context
166    }
167}
168
169impl NotificationTarget for dyn ScrollNotification {
170    fn cast(notification: &dyn Notification) -> Option<&dyn ScrollNotification> {
171        notification.as_scroll_notification()
172    }
173}
174
175/// Dart's `ScrollNotification.debugFillDescription`: the mixin's depth, then the metrics.
176fn fill_scroll_description(notification: &dyn ScrollNotification, description: &mut Vec<String>) {
177    ViewportNotificationMixin::debug_fill_description(notification, description);
178    description.push(format!("{:?}", notification.metrics()));
179}
180
181/// A notification that a `Scrollable` widget has started scrolling.
182///
183/// See also:
184///
185///  * [`ScrollEndNotification`], which indicates that scrolling has stopped.
186///  * [`ScrollNotification`], which describes the notification lifecycle.
187pub struct ScrollStartNotification {
188    viewport_notification: ViewportNotificationData,
189    scroll_notification: ScrollNotificationData,
190
191    /// If the `Scrollable` started scrolling because of a drag, the details about
192    /// that drag start.
193    ///
194    /// Otherwise, null.
195    pub drag_details: Option<DragStartDetails>,
196}
197
198impl ScrollStartNotification {
199    /// Creates a notification that a `Scrollable` widget has started scrolling.
200    pub fn new(
201        metrics: Rc<dyn ScrollMetrics>,
202        context: Option<BuildContext>,
203    ) -> ScrollStartNotification {
204        ScrollStartNotification {
205            viewport_notification: ViewportNotificationData::new(),
206            scroll_notification: ScrollNotificationData { metrics, context },
207            drag_details: None,
208        }
209    }
210
211    /// Dart `ScrollStartNotification(dragDetails:)`.
212    pub fn drag_details(mut self, drag_details: DragStartDetails) -> ScrollStartNotification {
213        self.drag_details = Some(drag_details);
214        self
215    }
216}
217
218impl Notification for ScrollStartNotification {
219    fn as_any(&self) -> &dyn Any {
220        self
221    }
222
223    fn viewport_depth(&self) -> Option<&Cell<u32>> {
224        Some(&self.viewport_notification.depth)
225    }
226
227    fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
228        Some(self)
229    }
230
231    fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
232        Some(self)
233    }
234}
235
236impl LayoutChangedNotification for ScrollStartNotification {}
237
238impl ViewportNotificationMixin for ScrollStartNotification {
239    fn viewport_notification_data(&self) -> &ViewportNotificationData {
240        &self.viewport_notification
241    }
242}
243
244impl ScrollNotification for ScrollStartNotification {
245    fn scroll_notification_data(&self) -> &ScrollNotificationData {
246        &self.scroll_notification
247    }
248}
249
250impl Debug for ScrollStartNotification {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        let mut description = Vec::new();
253        fill_scroll_description(self, &mut description);
254        if let Some(drag_details) = &self.drag_details {
255            description.push(format!("{drag_details:?}"));
256        }
257        write!(f, "ScrollStartNotification({})", description.join(", "))
258    }
259}
260
261/// A notification that a `Scrollable` widget has changed its scroll position.
262///
263/// See also:
264///
265///  * [`OverscrollNotification`], which indicates that a `Scrollable` widget
266///    has not changed its scroll position because the change would have caused
267///    its scroll position to go outside its scroll bounds.
268///  * [`ScrollNotification`], which describes the notification lifecycle.
269pub struct ScrollUpdateNotification {
270    viewport_notification: ViewportNotificationData,
271    scroll_notification: ScrollNotificationData,
272
273    /// If the `Scrollable` changed its scroll position because of a drag, the
274    /// details about that drag update.
275    ///
276    /// Otherwise, null.
277    pub drag_details: Option<DragUpdateDetails>,
278
279    /// The distance by which the `Scrollable` was scrolled, in logical pixels.
280    pub scroll_delta: Option<f64>,
281}
282
283impl ScrollUpdateNotification {
284    /// Creates a notification that a `Scrollable` widget has changed its scroll
285    /// position.
286    pub fn new(metrics: Rc<dyn ScrollMetrics>, context: BuildContext) -> ScrollUpdateNotification {
287        ScrollUpdateNotification {
288            viewport_notification: ViewportNotificationData::new(),
289            scroll_notification: ScrollNotificationData {
290                metrics,
291                context: Some(context),
292            },
293            drag_details: None,
294            scroll_delta: None,
295        }
296    }
297
298    /// Dart `ScrollUpdateNotification(dragDetails:)`.
299    pub fn drag_details(mut self, drag_details: DragUpdateDetails) -> ScrollUpdateNotification {
300        self.drag_details = Some(drag_details);
301        self
302    }
303
304    /// Dart `ScrollUpdateNotification(scrollDelta:)`.
305    pub fn scroll_delta(mut self, scroll_delta: f64) -> ScrollUpdateNotification {
306        self.scroll_delta = Some(scroll_delta);
307        self
308    }
309
310    /// Dart `ScrollUpdateNotification(depth:)`, which seeds the viewport depth. Named
311    /// `with_depth` because `depth` is the mixin's getter.
312    pub fn with_depth(mut self, depth: u32) -> ScrollUpdateNotification {
313        self.viewport_notification = ViewportNotificationData::with_depth(depth);
314        self
315    }
316}
317
318impl Notification for ScrollUpdateNotification {
319    fn as_any(&self) -> &dyn Any {
320        self
321    }
322
323    fn viewport_depth(&self) -> Option<&Cell<u32>> {
324        Some(&self.viewport_notification.depth)
325    }
326
327    fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
328        Some(self)
329    }
330
331    fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
332        Some(self)
333    }
334}
335
336impl LayoutChangedNotification for ScrollUpdateNotification {}
337
338impl ViewportNotificationMixin for ScrollUpdateNotification {
339    fn viewport_notification_data(&self) -> &ViewportNotificationData {
340        &self.viewport_notification
341    }
342}
343
344impl ScrollNotification for ScrollUpdateNotification {
345    fn scroll_notification_data(&self) -> &ScrollNotificationData {
346        &self.scroll_notification
347    }
348}
349
350impl Debug for ScrollUpdateNotification {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        let mut description = Vec::new();
353        fill_scroll_description(self, &mut description);
354        description.push(match self.scroll_delta {
355            Some(scroll_delta) => format!("scrollDelta: {scroll_delta:?}"),
356            None => "scrollDelta: null".to_string(),
357        });
358        if let Some(drag_details) = &self.drag_details {
359            description.push(format!("{drag_details:?}"));
360        }
361        write!(f, "ScrollUpdateNotification({})", description.join(", "))
362    }
363}
364
365/// A notification that a `Scrollable` widget has not changed its scroll position
366/// because the change would have caused its scroll position to go outside of
367/// its scroll bounds.
368///
369/// See also:
370///
371///  * [`ScrollUpdateNotification`], which indicates that a `Scrollable` widget
372///    has changed its scroll position.
373///  * [`ScrollNotification`], which describes the notification lifecycle.
374pub struct OverscrollNotification {
375    viewport_notification: ViewportNotificationData,
376    scroll_notification: ScrollNotificationData,
377
378    /// If the `Scrollable` overscrolled because of a drag, the details about that
379    /// drag update.
380    ///
381    /// Otherwise, null.
382    pub drag_details: Option<DragUpdateDetails>,
383
384    /// The number of logical pixels that the `Scrollable` avoided scrolling.
385    ///
386    /// This will be negative for overscroll on the "start" side and positive for
387    /// overscroll on the "end" side.
388    pub overscroll: f64,
389
390    /// The velocity at which the `ScrollPosition` was changing when this
391    /// overscroll happened.
392    ///
393    /// This will typically be 0.0 for touch-driven overscrolls, and positive
394    /// for overscrolls that happened from a `BallisticScrollActivity` or
395    /// `DrivenScrollActivity`.
396    pub velocity: f64,
397}
398
399impl OverscrollNotification {
400    /// Creates a notification that a `Scrollable` widget has changed its scroll
401    /// position outside of its scroll bounds.
402    pub fn new(
403        metrics: Rc<dyn ScrollMetrics>,
404        context: BuildContext,
405        overscroll: f64,
406    ) -> OverscrollNotification {
407        debug_assert!(overscroll.is_finite());
408        debug_assert!(overscroll != 0.0);
409        OverscrollNotification {
410            viewport_notification: ViewportNotificationData::new(),
411            scroll_notification: ScrollNotificationData {
412                metrics,
413                context: Some(context),
414            },
415            drag_details: None,
416            overscroll,
417            velocity: 0.0,
418        }
419    }
420
421    /// Dart `OverscrollNotification(dragDetails:)`.
422    pub fn drag_details(mut self, drag_details: DragUpdateDetails) -> OverscrollNotification {
423        self.drag_details = Some(drag_details);
424        self
425    }
426
427    /// Dart `OverscrollNotification(velocity:)`.
428    pub fn velocity(mut self, velocity: f64) -> OverscrollNotification {
429        self.velocity = velocity;
430        self
431    }
432}
433
434impl Notification for OverscrollNotification {
435    fn as_any(&self) -> &dyn Any {
436        self
437    }
438
439    fn viewport_depth(&self) -> Option<&Cell<u32>> {
440        Some(&self.viewport_notification.depth)
441    }
442
443    fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
444        Some(self)
445    }
446
447    fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
448        Some(self)
449    }
450}
451
452impl LayoutChangedNotification for OverscrollNotification {}
453
454impl ViewportNotificationMixin for OverscrollNotification {
455    fn viewport_notification_data(&self) -> &ViewportNotificationData {
456        &self.viewport_notification
457    }
458}
459
460impl ScrollNotification for OverscrollNotification {
461    fn scroll_notification_data(&self) -> &ScrollNotificationData {
462        &self.scroll_notification
463    }
464}
465
466impl Debug for OverscrollNotification {
467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468        let mut description = Vec::new();
469        fill_scroll_description(self, &mut description);
470        description.push(format!("overscroll: {:.1}", self.overscroll));
471        description.push(format!("velocity: {:.1}", self.velocity));
472        if let Some(drag_details) = &self.drag_details {
473            description.push(format!("{drag_details:?}"));
474        }
475        write!(f, "OverscrollNotification({})", description.join(", "))
476    }
477}
478
479/// A notification that a `Scrollable` widget has stopped scrolling.
480///
481/// See also:
482///
483///  * [`ScrollStartNotification`], which indicates that scrolling has started.
484///  * [`ScrollNotification`], which describes the notification lifecycle.
485pub struct ScrollEndNotification {
486    viewport_notification: ViewportNotificationData,
487    scroll_notification: ScrollNotificationData,
488
489    /// If the `Scrollable` stopped scrolling because of a drag, the details about
490    /// that drag end.
491    ///
492    /// Otherwise, null.
493    ///
494    /// If a drag ends with some residual velocity, a typical [`ScrollPhysics`] will
495    /// start a ballistic scroll, which delays the [`ScrollEndNotification`] until
496    /// the ballistic simulation completes, at which time
497    /// [`drag_details`](Self::drag_details) will be null. If the residual velocity is too
498    /// small to trigger ballistic scrolling, then the [`ScrollEndNotification`] will be
499    /// dispatched immediately and [`drag_details`](Self::drag_details) will be non-null.
500    ///
501    /// [`ScrollPhysics`]: crate::widgets::scroll_physics::ScrollPhysics
502    pub drag_details: Option<DragEndDetails>,
503}
504
505impl ScrollEndNotification {
506    /// Creates a notification that a `Scrollable` widget has stopped scrolling.
507    pub fn new(metrics: Rc<dyn ScrollMetrics>, context: BuildContext) -> ScrollEndNotification {
508        ScrollEndNotification {
509            viewport_notification: ViewportNotificationData::new(),
510            scroll_notification: ScrollNotificationData {
511                metrics,
512                context: Some(context),
513            },
514            drag_details: None,
515        }
516    }
517
518    /// Dart `ScrollEndNotification(dragDetails:)`.
519    pub fn drag_details(mut self, drag_details: DragEndDetails) -> ScrollEndNotification {
520        self.drag_details = Some(drag_details);
521        self
522    }
523}
524
525impl Notification for ScrollEndNotification {
526    fn as_any(&self) -> &dyn Any {
527        self
528    }
529
530    fn viewport_depth(&self) -> Option<&Cell<u32>> {
531        Some(&self.viewport_notification.depth)
532    }
533
534    fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
535        Some(self)
536    }
537
538    fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
539        Some(self)
540    }
541}
542
543impl LayoutChangedNotification for ScrollEndNotification {}
544
545impl ViewportNotificationMixin for ScrollEndNotification {
546    fn viewport_notification_data(&self) -> &ViewportNotificationData {
547        &self.viewport_notification
548    }
549}
550
551impl ScrollNotification for ScrollEndNotification {
552    fn scroll_notification_data(&self) -> &ScrollNotificationData {
553        &self.scroll_notification
554    }
555}
556
557impl Debug for ScrollEndNotification {
558    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559        let mut description = Vec::new();
560        fill_scroll_description(self, &mut description);
561        if let Some(drag_details) = &self.drag_details {
562            description.push(format!("{drag_details:?}"));
563        }
564        write!(f, "ScrollEndNotification({})", description.join(", "))
565    }
566}
567
568/// A notification that the user has changed the [`ScrollDirection`] in which they
569/// are scrolling, or have stopped scrolling.
570///
571/// For the direction that the `ScrollView` is oriented to, and the direction
572/// contents are being laid out in, see `AxisDirection` and `GrowthDirection`.
573///
574/// See also:
575///
576///  * [`ScrollNotification`], which describes the notification lifecycle.
577pub struct UserScrollNotification {
578    viewport_notification: ViewportNotificationData,
579    scroll_notification: ScrollNotificationData,
580
581    /// The direction in which the user is scrolling.
582    ///
583    /// This does not represent the current `AxisDirection` or `GrowthDirection`
584    /// of the `Viewport`, which respectively represent the direction that the
585    /// scroll offset is increasing in, and the direction that contents are being
586    /// laid out in.
587    pub direction: ScrollDirection,
588}
589
590impl UserScrollNotification {
591    /// Creates a notification that the user has changed the direction in which
592    /// they are scrolling.
593    pub fn new(
594        metrics: Rc<dyn ScrollMetrics>,
595        context: BuildContext,
596        direction: ScrollDirection,
597    ) -> UserScrollNotification {
598        UserScrollNotification {
599            viewport_notification: ViewportNotificationData::new(),
600            scroll_notification: ScrollNotificationData {
601                metrics,
602                context: Some(context),
603            },
604            direction,
605        }
606    }
607}
608
609impl Notification for UserScrollNotification {
610    fn as_any(&self) -> &dyn Any {
611        self
612    }
613
614    fn viewport_depth(&self) -> Option<&Cell<u32>> {
615        Some(&self.viewport_notification.depth)
616    }
617
618    fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
619        Some(self)
620    }
621
622    fn as_layout_changed_notification(&self) -> Option<&dyn LayoutChangedNotification> {
623        Some(self)
624    }
625}
626
627impl LayoutChangedNotification for UserScrollNotification {}
628
629impl ViewportNotificationMixin for UserScrollNotification {
630    fn viewport_notification_data(&self) -> &ViewportNotificationData {
631        &self.viewport_notification
632    }
633}
634
635impl ScrollNotification for UserScrollNotification {
636    fn scroll_notification_data(&self) -> &ScrollNotificationData {
637        &self.scroll_notification
638    }
639}
640
641impl Debug for UserScrollNotification {
642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643        let mut description = Vec::new();
644        fill_scroll_description(self, &mut description);
645        description.push(format!("direction: {:?}", self.direction));
646        write!(f, "UserScrollNotification({})", description.join(", "))
647    }
648}
649
650/// A predicate for [`ScrollNotification`], used to customize widgets that
651/// listen to notifications from their children.
652pub type ScrollNotificationPredicate = Rc<dyn Fn(&dyn ScrollNotification) -> bool>;
653
654/// A [`ScrollNotificationPredicate`] that checks whether `notification.depth() == 0`,
655/// which means that the notification did not bubble through any intervening scrolling
656/// widgets.
657pub fn default_scroll_notification_predicate(notification: &dyn ScrollNotification) -> bool {
658    notification.depth() == 0
659}
660
661#[cfg(test)]
662mod tests {
663    use std::cell::RefCell;
664    use waft_foundation::AppCell;
665
666    use waft_painting::AxisDirection;
667
668    use super::*;
669    use crate::framework::{
670        AnyElement, ComponentElement, ComponentElementData, ElementData, IntoWidget, KeyRef,
671        ProxyElement, Slot, Widget, WidgetKind, WidgetRef, component_element_overrides,
672        downcast_widget,
673    };
674    use crate::test_harness::Harness;
675    use crate::widgets::basic::{Builder, SizedBox};
676    use crate::widgets::notification_listener::{
677        NotificationListener, PlainLayoutChangedNotification,
678    };
679    use crate::widgets::scroll_metrics::FixedScrollMetrics;
680
681    /// A stand-in for `Viewport`: a proxy whose element mixes in
682    /// [`ViewportElementMixin`], so a notification bubbling past it is one viewport deeper.
683    #[derive(Debug)]
684    struct TestViewport {
685        child: WidgetRef,
686    }
687
688    fn viewport<K>(child: impl IntoWidget<K>) -> WidgetRef {
689        Rc::new(TestViewport {
690            child: child.into_widget(),
691        })
692    }
693
694    impl Widget for TestViewport {
695        fn key(&self) -> Option<&KeyRef> {
696            None
697        }
698
699        fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
700            let element = app.create(TestViewportElement {
701                element: ElementData::new(this),
702                component: ComponentElementData::default(),
703            });
704            element.as_element()
705        }
706
707        fn as_any(&self) -> &dyn Any {
708            self
709        }
710
711        fn widget_type(&self) -> std::any::TypeId {
712            std::any::TypeId::of::<TestViewport>()
713        }
714
715        fn kind(&self) -> WidgetKind {
716            WidgetKind::Other
717        }
718    }
719
720    struct TestViewportElement {
721        element: ElementData,
722        component: ComponentElementData,
723    }
724
725    impl ComponentElement for TestViewportElement {
726        fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
727            &app.get(self).component
728        }
729
730        fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
731            &mut app.get_mut(self).component
732        }
733
734        fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
735            self.proxied_child(app)
736        }
737    }
738
739    impl ProxyElement for TestViewportElement {
740        fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
741            downcast_widget::<TestViewport>(&**self.as_element().widget(app))
742                .expect("a TestViewportElement holds its TestViewport")
743                .child
744                .clone()
745        }
746
747        fn notify_clients(self: Handle<Self>, _app: &mut App, _old_widget: WidgetRef) {}
748    }
749
750    impl ViewportElementMixin for TestViewportElement {}
751
752    impl Element for TestViewportElement {
753        crate::element_accessors!();
754        component_element_overrides!();
755
756        #[inline(always)]
757        fn mount(
758            self: Handle<Self>,
759            app: &mut App,
760            parent: Option<AnyElement>,
761            new_slot: Option<Slot>,
762        ) {
763            ComponentElement::mount(self, app, parent, new_slot);
764        }
765
766        #[inline(always)]
767        fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
768            ProxyElement::update(self, app, new_widget);
769        }
770
771        #[inline(always)]
772        fn perform_rebuild(self: Handle<Self>, app: &mut App) {
773            ComponentElement::perform_rebuild(self, app);
774        }
775
776        fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
777            ViewportElementMixin::attach_notification_tree(self, app);
778        }
779
780        fn on_notification(
781            self: Handle<Self>,
782            app: &mut App,
783            notification: &dyn Notification,
784        ) -> bool {
785            ViewportElementMixin::on_notification(self, app, notification)
786        }
787    }
788
789    fn test_metrics() -> Rc<dyn ScrollMetrics> {
790        Rc::new(FixedScrollMetrics::new(
791            Some(0.0),
792            Some(400.0),
793            Some(20.0),
794            Some(600.0),
795            AxisDirection::Down,
796            3.0,
797        ))
798    }
799
800    type Log = Rc<RefCell<Vec<(&'static str, u32)>>>;
801
802    fn listener(log: &Log, name: &'static str, child: WidgetRef) -> WidgetRef {
803        let log = Rc::clone(log);
804        NotificationListener::<ScrollUpdateNotification>::new(child)
805            .on_notification(move |_app, notification| {
806                log.borrow_mut().push((name, notification.depth()));
807                false
808            })
809            .into_widget()
810    }
811
812    #[test]
813    fn a_family_listener_receives_every_kind_of_scroll_notification() {
814        let cell = AppCell::new();
815        let mut app = cell.borrow_mut();
816        let seen: Rc<RefCell<Vec<String>>> = Rc::default();
817        let dispatcher = Builder::new(|app, context| {
818            ScrollStartNotification::new(test_metrics(), Some(context))
819                .dispatch(app, Some(context));
820            ScrollUpdateNotification::new(test_metrics(), context)
821                .scroll_delta(4.0)
822                .dispatch(app, Some(context));
823            ScrollEndNotification::new(test_metrics(), context).dispatch(app, Some(context));
824            SizedBox::shrink().into_widget()
825        });
826        let tree = NotificationListener::<dyn ScrollNotification>::new(dispatcher)
827            .on_notification({
828                let seen = Rc::clone(&seen);
829                move |_app, notification| {
830                    seen.borrow_mut().push(format!("{notification:?}"));
831                    false
832                }
833            })
834            .into_widget();
835        let harness = Harness::mount(&mut app, tree);
836        harness.pump(&mut app);
837        let seen = seen.borrow();
838        assert_eq!(seen.len(), 3);
839        assert!(
840            seen[0].starts_with("ScrollStartNotification"),
841            "{}",
842            seen[0]
843        );
844        assert!(
845            seen[1].starts_with("ScrollUpdateNotification"),
846            "{}",
847            seen[1]
848        );
849        assert!(seen[2].starts_with("ScrollEndNotification"), "{}", seen[2]);
850    }
851
852    #[test]
853    fn a_layout_changed_listener_receives_scroll_notifications_and_plain_layout_changes() {
854        let cell = AppCell::new();
855        let mut app = cell.borrow_mut();
856        let seen: Rc<RefCell<Vec<String>>> = Rc::default();
857        let dispatcher = Builder::new(|app, context| {
858            PlainLayoutChangedNotification.dispatch(app, Some(context));
859            ScrollUpdateNotification::new(test_metrics(), context)
860                .scroll_delta(4.0)
861                .dispatch(app, Some(context));
862            UserScrollNotification::new(test_metrics(), context, ScrollDirection::Idle)
863                .dispatch(app, Some(context));
864            SizedBox::shrink().into_widget()
865        });
866        let tree = NotificationListener::<dyn LayoutChangedNotification>::new(dispatcher)
867            .on_notification({
868                let seen = Rc::clone(&seen);
869                move |_app, notification| {
870                    seen.borrow_mut().push(format!("{notification:?}"));
871                    false
872                }
873            })
874            .into_widget();
875        let harness = Harness::mount(&mut app, tree);
876        harness.pump(&mut app);
877        let seen = seen.borrow();
878        assert_eq!(seen.len(), 3);
879        assert_eq!(seen[0], "PlainLayoutChangedNotification");
880        assert!(
881            seen[1].starts_with("ScrollUpdateNotification"),
882            "{}",
883            seen[1]
884        );
885        assert!(seen[2].starts_with("UserScrollNotification"), "{}", seen[2]);
886    }
887
888    #[test]
889    fn a_scroll_update_notification_bubbles_and_each_viewport_adds_to_its_depth() {
890        let cell = AppCell::new();
891        let mut app = cell.borrow_mut();
892        let log: Log = Rc::default();
893        let dispatcher = Builder::new(|app, context| {
894            ScrollUpdateNotification::new(test_metrics(), context)
895                .scroll_delta(4.0)
896                .dispatch(app, Some(context));
897            SizedBox::shrink().into_widget()
898        });
899        let tree = listener(
900            &log,
901            "outer",
902            viewport(listener(
903                &log,
904                "middle",
905                viewport(listener(&log, "inner", dispatcher.into_widget())),
906            )),
907        );
908        let harness = Harness::mount(&mut app, tree);
909        harness.pump(&mut app);
910
911        assert_eq!(
912            *log.borrow(),
913            vec![("inner", 0), ("middle", 1), ("outer", 2)]
914        );
915    }
916
917    #[test]
918    fn a_notification_reports_its_depth_and_its_metrics() {
919        let notification = ScrollUpdateNotification::new(
920            test_metrics(),
921            // A `BuildContext` is required; the element tree is not walked by `Debug`.
922            {
923                let cell = AppCell::new();
924                let mut app = cell.borrow_mut();
925                let harness = Harness::mount(&mut app, SizedBox::shrink().into_widget());
926                harness.root.as_element()
927            },
928        )
929        .scroll_delta(4.0)
930        .with_depth(2);
931
932        assert_eq!(notification.depth(), 2);
933        assert!(default_scroll_notification_predicate(
934            &ScrollUpdateNotification::new(
935                test_metrics(),
936                notification.context().expect("a context was given"),
937            )
938        ));
939        assert!(!default_scroll_notification_predicate(&notification));
940        assert_eq!(
941            format!("{notification:?}"),
942            "ScrollUpdateNotification(depth: 2 (remote), \
943             FixedScrollMetrics(20.0..[600.0]..380.0), scrollDelta: 4.0)"
944        );
945    }
946
947    #[test]
948    fn the_overscroll_notification_reports_its_overscroll_and_velocity() {
949        let cell = AppCell::new();
950        let mut app = cell.borrow_mut();
951        let harness = Harness::mount(&mut app, SizedBox::shrink().into_widget());
952        let context = harness.root.as_element();
953        let notification =
954            OverscrollNotification::new(test_metrics(), context, -12.0).velocity(3.0);
955        assert_eq!(notification.overscroll, -12.0);
956        assert_eq!(
957            format!("{notification:?}"),
958            "OverscrollNotification(depth: 0 (local), \
959             FixedScrollMetrics(20.0..[600.0]..380.0), overscroll: -12.0, velocity: 3.0)"
960        );
961
962        let user_scroll =
963            UserScrollNotification::new(test_metrics(), context, ScrollDirection::Reverse);
964        assert_eq!(
965            format!("{user_scroll:?}"),
966            "UserScrollNotification(depth: 0 (local), \
967             FixedScrollMetrics(20.0..[600.0]..380.0), direction: Reverse)"
968        );
969    }
970}