Skip to main content

nsh_core/element/
scrollable.rs

1//! How scroll views and lists scroll ([`Scrollable`]): the behavior props
2//! and scroll events `Scroll` and `List` share in TS
3//! (`ScrollingHostProps`).
4
5use super::{
6    AnimatedValue, Element, IntoListener, IntoReactive, Listener, ScrollEvent,
7    events::{self, Decode},
8    host,
9};
10use crate::{
11    EdgeInsets, EventKind, KeyboardDismissMode, KeyboardTaps, Prop, ScrollProp, SnapAlignment,
12    geometry::{Point, Points},
13};
14
15/// How an element scrolls: [`super::Scroll`], [`super::VirtualList`] and
16/// [`super::ListElement`] (the app's rows a component places). The
17/// direction and the indicator are [`super::Scroll::horizontal`] /
18/// [`super::ListLayout::horizontal`] and their `scrollbar`.
19pub trait Scrollable: Element {
20    #[doc(hidden)]
21    fn set_scroll_prop(mut self, prop: Prop) -> Self {
22        host::set(self.node(), prop);
23        self
24    }
25
26    #[doc(hidden)]
27    fn listen_scroll<T: ?Sized + ToOwned + 'static>(
28        mut self,
29        kind: EventKind,
30        listener: Listener<T>,
31        decode: Decode<T>,
32    ) -> Self {
33        self.node()
34            .handlers
35            .push((kind, events::typed(listener, decode)));
36        self
37    }
38
39    /// Stops on multiples of its size (TS: `pagingEnabled`).
40    fn paging(mut self, paging: impl IntoReactive<bool>) -> Self {
41        host::bind_prop(self.node(), paging, |paging| {
42            Prop::Scroll(ScrollProp::Paging(paging))
43        });
44        self
45    }
46
47    /// Stops on multiples of `interval` (TS: `snapToInterval`; 0: off).
48    fn snap_interval(mut self, interval: impl IntoReactive<Points>) -> Self {
49        host::bind_prop(self.node(), interval, |interval: Points| {
50            Prop::Scroll(ScrollProp::SnapInterval(interval))
51        });
52        self
53    }
54
55    /// Stops at these offsets (TS: `snapToOffsets`).
56    fn snap_offsets(mut self, offsets: impl IntoReactive<Vec<Points>>) -> Self {
57        host::bind_prop(self.node(), offsets, |offsets: Vec<Points>| {
58            Prop::Scroll(ScrollProp::SnapOffsets(offsets))
59        });
60        self
61    }
62
63    /// Where a snapped item sits in the viewport (TS: `snapToAlignment`).
64    fn snap_alignment(mut self, alignment: impl IntoReactive<SnapAlignment>) -> Self {
65        host::bind_prop(self.node(), alignment, |alignment| {
66            Prop::Scroll(ScrollProp::SnapAlignment(alignment))
67        });
68        self
69    }
70
71    /// A fling moves one snap point at most (TS: `disableIntervalMomentum`).
72    fn disable_interval_momentum(mut self, disable: impl IntoReactive<bool>) -> Self {
73        host::bind_prop(self.node(), disable, |disable| {
74            Prop::Scroll(ScrollProp::DisableIntervalMomentum(disable))
75        });
76        self
77    }
78
79    /// How fast a fling slows down: the velocity kept per millisecond (TS:
80    /// `decelerationRate`; 0.99 is `"fast"`, 0.998 `"normal"`).
81    fn deceleration(mut self, rate: impl IntoReactive<f32>) -> Self {
82        host::bind_prop(self.node(), rate, |rate| {
83            Prop::Scroll(ScrollProp::Deceleration(rate))
84        });
85        self
86    }
87
88    /// The user can scroll it (default yes; TS: `scrollable`).
89    fn scrollable(mut self, enabled: impl IntoReactive<bool>) -> Self {
90        host::bind_prop(self.node(), enabled, |enabled| {
91            Prop::Native(crate::NativeProp::Scrollable(enabled))
92        });
93        self
94    }
95
96    /// Bounces at the ends (default yes).
97    fn bounces(mut self, bounces: impl IntoReactive<bool>) -> Self {
98        host::bind_prop(self.node(), bounces, |bounces| {
99            Prop::Scroll(ScrollProp::Bounces(bounces))
100        });
101        self
102    }
103
104    /// A tap at the top of the window (the status bar's) scrolls it to its
105    /// top (default yes; iOS and Mac Catalyst only; TS: `scrollsToTop`).
106    fn scrolls_to_top(mut self, on: impl IntoReactive<bool>) -> Self {
107        host::bind_prop(self.node(), on, |on| {
108            Prop::Scroll(ScrollProp::ScrollsToTop(on))
109        });
110        self
111    }
112
113    /// A mouse wheel's notches glide, eased as Chromium's do, instead of the
114    /// platform's own step (default no; the desktops; TS: `smoothWheel`).
115    fn smooth_wheel(mut self, on: impl IntoReactive<bool>) -> Self {
116        host::bind_prop(self.node(), on, |on| {
117            Prop::Scroll(ScrollProp::SmoothWheel(on))
118        });
119        self
120    }
121
122    /// How far a mouse wheel's line scrolls (0, the default: the platform's
123    /// own; the desktops; TS: `wheelLineHeight`).
124    fn wheel_line_height(mut self, height: impl IntoReactive<Points>) -> Self {
125        host::bind_prop(self.node(), height, |height| {
126            Prop::Scroll(ScrollProp::WheelLineHeight(height))
127        });
128        self
129    }
130
131    /// Space around the content that scrolls with it.
132    fn content_inset(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
133        host::bind_prop(self.node(), insets, |insets| {
134            Prop::Scroll(ScrollProp::ContentInset(insets))
135        });
136        self
137    }
138
139    /// How far the scroll indicator keeps from each edge, so that it stays
140    /// clear of bars floating over the view (TS: `scrollbarInset`).
141    fn scrollbar_inset(mut self, insets: impl IntoReactive<EdgeInsets>) -> Self {
142        host::bind_prop(self.node(), insets, |insets| {
143            Prop::Scroll(ScrollProp::ScrollbarInset(insets))
144        });
145        self
146    }
147
148    /// Where it starts (set once).
149    fn content_offset(self, offset: Point<Points>) -> Self {
150        self.set_scroll_prop(Prop::Scroll(ScrollProp::ContentOffset(offset)))
151    }
152
153    /// Taps while the keyboard shows: dismiss it, or reach the content (TS:
154    /// `keyboardShouldPersistTaps`).
155    fn keyboard_taps(mut self, taps: impl IntoReactive<KeyboardTaps>) -> Self {
156        host::bind_prop(self.node(), taps, |taps| {
157            Prop::Scroll(ScrollProp::KeyboardTaps(taps))
158        });
159        self
160    }
161
162    /// Dragging dismisses the keyboard (TS: `keyboardDismissMode`).
163    fn keyboard_dismiss_mode(mut self, mode: impl IntoReactive<KeyboardDismissMode>) -> Self {
164        host::bind_prop(self.node(), mode, Prop::KeyboardDismissMode);
165        self
166    }
167
168    /// At most one `on_scroll` per `ms` milliseconds (default: every frame;
169    /// TS: `scrollEventThrottle`).
170    fn event_throttle(mut self, ms: impl IntoReactive<f32>) -> Self {
171        host::bind_prop(self.node(), ms, |ms| {
172            Prop::Scroll(ScrollProp::EventThrottle(ms))
173        });
174        self
175    }
176
177    /// Shows the pull-to-refresh spinner (start it from
178    /// [`Self::on_refresh`], clear it when done).
179    fn refreshing(mut self, refreshing: impl IntoReactive<bool>) -> Self {
180        host::bind_prop(self.node(), refreshing, |refreshing| {
181            Prop::Refreshing(refreshing)
182        });
183        self
184    }
185
186    /// Follows the scroll offset (along its axis) with an animated value:
187    /// headers that shrink or fade, parallax, with no engine work per frame
188    /// (TS: `scrollValue`).
189    fn scroll_value(mut self, value: &AnimatedValue) -> Self {
190        if let Some(node) = value.node().live() {
191            host::set(self.node(), Prop::ScrollValue(Some(node.id())));
192            self.node().attrs.rare_mut().bound.push(node);
193        }
194        self
195    }
196
197    /// Follows how far it is pulled past its top with an animated value (0
198    /// at rest, growing with the pull; the room kept above the content
199    /// while it refreshes): an app's own pull-to-refresh indicator, with no
200    /// engine work per frame (TS: `pullValue`).
201    fn pull_value(mut self, value: &AnimatedValue) -> Self {
202        if let Some(node) = value.node().live() {
203            host::set(self.node(), Prop::PullValue(Some(node.id())));
204            self.node().attrs.rare_mut().bound.push(node);
205        }
206        self
207    }
208
209    /// The app draws its own pull-to-refresh indicator, `height` points
210    /// tall (from [`Self::pull_value`]): the platform's spinner is hidden, a
211    /// pull refreshes once it reaches `height`, and refreshing keeps `height`
212    /// above the content (`None`: the platform's spinner; TS:
213    /// `refreshIndicator`).
214    fn refresh_indicator(mut self, height: impl IntoReactive<Option<Points>>) -> Self {
215        host::bind_prop(self.node(), height, |height: Option<Points>| {
216            Prop::Scroll(ScrollProp::RefreshIndicator(height))
217        });
218        self
219    }
220
221    /// Pulled down to refresh (enables pull to refresh).
222    fn on_refresh<M>(self, listener: impl IntoListener<(), M>) -> Self {
223        self.listen_scroll(EventKind::Refresh, listener.into_listener(), events::unit)
224    }
225
226    /// It moved (at most once per frame, [`Self::event_throttle`]).
227    fn on_scroll<M>(self, listener: impl IntoListener<ScrollEvent, M>) -> Self {
228        self.listen_scroll(EventKind::Scroll, listener.into_listener(), events::scroll)
229    }
230
231    /// The user started dragging it.
232    fn on_scroll_drag_start<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
233        self.listen_scroll(
234            EventKind::ScrollDragStart,
235            listener.into_listener(),
236            events::offset,
237        )
238    }
239
240    /// The user let go.
241    fn on_scroll_drag_end<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
242        self.listen_scroll(
243            EventKind::ScrollDragEnd,
244            listener.into_listener(),
245            events::offset,
246        )
247    }
248
249    /// It started gliding after a fling.
250    fn on_momentum_start<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
251        self.listen_scroll(
252            EventKind::MomentumStart,
253            listener.into_listener(),
254            events::offset,
255        )
256    }
257
258    /// It stopped gliding.
259    fn on_momentum_end<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
260        self.listen_scroll(
261            EventKind::MomentumEnd,
262            listener.into_listener(),
263            events::offset,
264        )
265    }
266
267    /// It came to rest.
268    fn on_scroll_end<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
269        self.listen_scroll(
270            EventKind::ScrollEnd,
271            listener.into_listener(),
272            events::offset,
273        )
274    }
275}
276
277crate::static_reactive!(SnapAlignment: SnapAlignment);
278crate::static_reactive!(KeyboardTaps: KeyboardTaps);
279crate::static_reactive!(KeyboardDismissMode: KeyboardDismissMode);
280crate::static_reactive!(Vec<f32>: Vec<f32>);
281crate::static_reactive!(Vec<Points>: Vec<Points>);