Skip to main content

waft_widgets/widgets/
primary_scroll_controller.rs

1//! Flutter counterpart: `widgets/primary_scroll_controller.dart`.
2
3use std::collections::HashSet;
4
5use waft_embedder::TargetPlatform;
6use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty};
7use waft_painting::Axis;
8
9use crate::framework::{BuildContext, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
10use crate::widgets::scroll_configuration::ScrollConfiguration;
11use crate::widgets::scroll_controller::ScrollControllerRef;
12
13/// Dart's `_kMobilePlatforms`, a function because a `HashSet` has no `const` constructor.
14fn k_mobile_platforms() -> HashSet<TargetPlatform> {
15    HashSet::from([
16        TargetPlatform::Android,
17        TargetPlatform::IOS,
18        TargetPlatform::Fuchsia,
19    ])
20}
21
22/// Associates a `ScrollController` with a subtree.
23///
24/// When a `ScrollView` has `primary` set to true, the `ScrollView`
25/// uses [`of`](Self::of) to inherit the [`PrimaryScrollController`] associated with its
26/// subtree.
27///
28/// A scroll view that doesn't have a controller or the primary flag set will
29/// inherit the primary scroll controller, if [`should_inherit`](Self::should_inherit) allows
30/// it. By default [`should_inherit`](Self::should_inherit) is true for mobile platforms when
31/// the scroll view has a scroll direction of [`Axis::Vertical`]. This automatic inheritance
32/// can be configured with
33/// [`automatically_inherit_for_platforms`](Self::automatically_inherit_for_platforms) and
34/// [`scroll_direction`](Self::scroll_direction).
35///
36/// Inheriting this scroll controller can provide default behavior for scroll
37/// views in a subtree. For example, the `Scaffold` uses this mechanism to
38/// implement the scroll-to-top gesture on iOS.
39///
40/// Another default behavior handled by the [`PrimaryScrollController`] is default
41/// [`crate::ScrollAction`]s. If a scroll action is not handled by an otherwise focused
42/// part of the application, the scroll action will be evaluated using the scroll
43/// view associated with a [`PrimaryScrollController`], for example, when executing
44/// `Shortcuts` key events like page up and down.
45///
46/// See also:
47///   * [`crate::ScrollAction`], an [`crate::Action`] that scrolls the `Scrollable` that
48///     encloses the current primary focus or is attached to the primary scroll controller.
49///   * `Shortcuts`, a widget that establishes a `ShortcutManager` to be used
50///     by its descendants when invoking an [`crate::Action`] via a keyboard key
51///     combination that maps to an [`crate::Intent`].
52#[derive(Debug)]
53pub struct PrimaryScrollController {
54    pub key: Option<KeyRef>,
55
56    /// The `ScrollController` associated with the subtree.
57    ///
58    /// See also:
59    ///
60    ///  * `ScrollView.controller`, which discusses the purpose of specifying a
61    ///    scroll controller.
62    pub controller: Option<ScrollControllerRef>,
63
64    /// The [`Axis`] this controller is configured for scroll views to
65    /// automatically inherit.
66    ///
67    /// Used in conjunction with
68    /// [`automatically_inherit_for_platforms`](Self::automatically_inherit_for_platforms). If
69    /// the current [`TargetPlatform`] is not included there, this is ignored.
70    ///
71    /// When `None`, no scroll view in any axis will automatically inherit this
72    /// controller. This is dissimilar to [`PrimaryScrollController::none`]. When a
73    /// primary scroll controller is inherited, `ScrollView` will insert
74    /// [`PrimaryScrollController::none`] into the tree to prevent further descendant
75    /// scroll views from inheriting the current primary scroll controller.
76    ///
77    /// For the direction in which active scrolling may be occurring, see
78    /// [`waft_rendering::ScrollDirection`].
79    ///
80    /// Defaults to [`Axis::Vertical`].
81    pub scroll_direction: Option<Axis>,
82
83    /// The [`TargetPlatform`]s this controller is configured for scroll views to
84    /// automatically inherit.
85    ///
86    /// Used in conjunction with [`scroll_direction`](Self::scroll_direction). If the [`Axis`]
87    /// provided to [`should_inherit`](Self::should_inherit) is not
88    /// [`scroll_direction`](Self::scroll_direction), this is ignored.
89    ///
90    /// When empty, no scroll view in any axis will automatically inherit this
91    /// controller. Defaults to the mobile platforms.
92    pub automatically_inherit_for_platforms: HashSet<TargetPlatform>,
93
94    /// The widget below this widget in the tree.
95    pub child: WidgetRef,
96}
97
98impl PrimaryScrollController {
99    /// Creates a widget that associates a `ScrollController` with a subtree.
100    #[cfg_attr(debug_assertions, track_caller)]
101    pub fn new<K>(
102        controller: ScrollControllerRef,
103        child: impl IntoWidget<K>,
104    ) -> PrimaryScrollController {
105        PrimaryScrollController {
106            key: None,
107            controller: Some(controller),
108            scroll_direction: Some(Axis::Vertical),
109            automatically_inherit_for_platforms: k_mobile_platforms(),
110            child: child.into_widget(),
111        }
112    }
113
114    /// Creates a subtree without an associated `ScrollController`.
115    #[cfg_attr(debug_assertions, track_caller)]
116    pub fn none<K>(child: impl IntoWidget<K>) -> PrimaryScrollController {
117        PrimaryScrollController {
118            key: None,
119            controller: None,
120            scroll_direction: None,
121            automatically_inherit_for_platforms: HashSet::new(),
122            child: child.into_widget(),
123        }
124    }
125
126    /// Dart `PrimaryScrollController(key:)`.
127    pub fn key(mut self, key: KeyRef) -> PrimaryScrollController {
128        self.key = Some(key);
129        self
130    }
131
132    /// Dart `PrimaryScrollController(scrollDirection:)`.
133    pub fn scroll_direction(mut self, scroll_direction: Axis) -> PrimaryScrollController {
134        self.scroll_direction = Some(scroll_direction);
135        self
136    }
137
138    /// Dart `PrimaryScrollController(automaticallyInheritForPlatforms:)`.
139    pub fn automatically_inherit_for_platforms(
140        mut self,
141        automatically_inherit_for_platforms: HashSet<TargetPlatform>,
142    ) -> PrimaryScrollController {
143        self.automatically_inherit_for_platforms = automatically_inherit_for_platforms;
144        self
145    }
146
147    /// Returns true if this [`PrimaryScrollController`] is configured to be
148    /// automatically inherited for the current [`TargetPlatform`] and the given
149    /// [`Axis`].
150    ///
151    /// This method is typically not called directly. `ScrollView` will call this
152    /// method if it has not been provided a `ScrollController` and
153    /// `ScrollView.primary` is unset.
154    pub fn should_inherit(app: &mut App, context: BuildContext, scroll_direction: Axis) -> bool {
155        let Some(result) =
156            context.find_ancestor_widget_of_exact_type::<PrimaryScrollController>(app)
157        else {
158            return false;
159        };
160        let inherit_for_platforms = result.automatically_inherit_for_platforms.clone();
161        let inherited_direction = result.scroll_direction;
162
163        let platform = ScrollConfiguration::of(app, context).get_platform(app, context);
164        if inherit_for_platforms.contains(&platform) {
165            return inherited_direction == Some(scroll_direction);
166        }
167        false
168    }
169
170    /// Returns the `ScrollController` most closely associated with the given
171    /// context.
172    ///
173    /// Returns `None` if there is no `ScrollController` associated with the given
174    /// context.
175    ///
176    /// Calling this method will create a dependency on the closest
177    /// [`PrimaryScrollController`] in the `context`, if there is one.
178    ///
179    /// See also:
180    ///
181    /// * [`PrimaryScrollController::of`], which is similar to this method, but
182    ///   panics if no [`PrimaryScrollController`] ancestor is found.
183    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<ScrollControllerRef> {
184        context
185            .depend_on_inherited_widget_of_exact_type::<PrimaryScrollController>(app)
186            .and_then(|result| result.controller.clone())
187    }
188
189    /// Returns the `ScrollController` most closely associated with the given
190    /// context.
191    ///
192    /// Calling this method will create a dependency on the closest
193    /// [`PrimaryScrollController`] in the `context`.
194    ///
195    /// # Panics
196    ///
197    /// If no [`PrimaryScrollController`] ancestor is found.
198    ///
199    /// See also:
200    ///
201    /// * [`PrimaryScrollController::maybe_of`], which is similar to this method, but
202    ///   returns `None` if no [`PrimaryScrollController`] ancestor is found.
203    pub fn of(app: &mut App, context: BuildContext) -> ScrollControllerRef {
204        PrimaryScrollController::maybe_of(app, context).expect(
205            "PrimaryScrollController.of() was called with a context that does not contain a \
206             PrimaryScrollController widget.\n\
207             No PrimaryScrollController widget ancestor could be found starting from the \
208             context that was passed to PrimaryScrollController.of(). This can happen because \
209             you are using a widget that looks for a PrimaryScrollController ancestor, but no \
210             such ancestor exists.",
211        )
212    }
213}
214
215impl InheritedWidget for PrimaryScrollController {
216    fn key(&self) -> Option<&KeyRef> {
217        self.key.as_ref()
218    }
219
220    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
221        properties.add(
222            DiagnosticsProperty::<String>::new(
223                "controller",
224                self.controller
225                    .as_ref()
226                    .map(|controller| controller.to_string(app)),
227            )
228            .if_null("no controller")
229            .with_show_name(false),
230        );
231    }
232
233    fn child(&self) -> &WidgetRef {
234        &self.child
235    }
236
237    fn update_should_notify(&self, old_widget: &PrimaryScrollController) -> bool {
238        self.controller != old_widget.controller
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245    use crate::framework::{AnyElement, Element, IntoWidget};
246    use crate::test_harness::Harness;
247    use crate::widgets::basic::SizedBox;
248    use crate::widgets::scroll_controller::ScrollController;
249    use waft_foundation::AppCell;
250
251    /// The element under the test root at `depth` levels down.
252    fn descendant(harness: &Harness, app: &App, depth: usize) -> AnyElement {
253        let mut element = harness.root.as_element();
254        for _ in 0..=depth {
255            element = element.children(app)[0];
256        }
257        element
258    }
259
260    fn mount(app: &mut App, widget: crate::framework::WidgetRef) -> Harness {
261        let harness = Harness::mount(app, widget);
262        harness.pump(app);
263        harness
264    }
265
266    #[test]
267    fn of_finds_the_controller_the_subtree_is_associated_with() {
268        let cell = AppCell::new();
269        let mut app = cell.borrow_mut();
270        let controller = ScrollController::default(&mut app);
271        let harness = mount(
272            &mut app,
273            PrimaryScrollController::new(controller.erase(), SizedBox::shrink()).into_widget(),
274        );
275
276        let inner = descendant(&harness, &app, 1);
277        assert_eq!(
278            PrimaryScrollController::of(&mut app, inner),
279            controller.erase()
280        );
281        assert_eq!(
282            PrimaryScrollController::maybe_of(&mut app, inner),
283            Some(controller.erase())
284        );
285    }
286
287    #[test]
288    fn none_hides_the_controller_from_its_subtree() {
289        let cell = AppCell::new();
290        let mut app = cell.borrow_mut();
291        let controller = ScrollController::default(&mut app);
292        let harness = mount(
293            &mut app,
294            PrimaryScrollController::new(
295                controller.erase(),
296                PrimaryScrollController::none(SizedBox::shrink()),
297            )
298            .into_widget(),
299        );
300
301        let inner = descendant(&harness, &app, 2);
302        assert_eq!(PrimaryScrollController::maybe_of(&mut app, inner), None);
303    }
304
305    #[test]
306    fn should_inherit_follows_the_platform_and_the_axis() {
307        let cell = AppCell::new();
308        let mut app = cell.borrow_mut();
309        let controller = ScrollController::default(&mut app);
310        let harness = mount(
311            &mut app,
312            PrimaryScrollController::new(controller.erase(), SizedBox::shrink()).into_widget(),
313        );
314
315        let inner = descendant(&harness, &app, 1);
316        // `App::new` runs on the host's platform; the default set covers the mobile ones.
317        let mobile = k_mobile_platforms().contains(&app.platform().target_platform());
318        assert_eq!(
319            PrimaryScrollController::should_inherit(&mut app, inner, Axis::Vertical),
320            mobile
321        );
322        assert!(!PrimaryScrollController::should_inherit(
323            &mut app,
324            inner,
325            Axis::Horizontal
326        ));
327    }
328}