Skip to main content

freya_components/scrollviews/
use_scroll_controller.rs

1use std::time::{
2    Duration,
3    Instant,
4};
5
6use freya_core::prelude::*;
7use torin::{
8    geometry::{
9        Point2D,
10        Size2D,
11        Vector2D,
12    },
13    prelude::Direction,
14};
15
16use crate::scrollviews::shared::get_corrected_scroll_position;
17
18/// Where along an axis a scroll should land, the beginning or the end.
19#[derive(Default, PartialEq, Eq)]
20pub enum ScrollPosition {
21    #[default]
22    Start,
23    End,
24}
25
26impl ScrollPosition {
27    /// Scroll offset in pixels of this position.
28    fn offset(&self) -> i32 {
29        match self {
30            Self::Start => 0,
31            Self::End => ScrollController::END,
32        }
33    }
34}
35
36/// Initial configuration for a [`ScrollController`] created with [`use_scroll_controller`].
37#[derive(Default)]
38pub struct ScrollConfig {
39    /// Where the vertical axis starts scrolled to when first laid out.
40    pub default_vertical_position: ScrollPosition,
41    /// Where the horizontal axis starts scrolled to when first laid out.
42    pub default_horizontal_position: ScrollPosition,
43}
44
45/// Handle to drive a scrollview programmatically.
46///
47/// By default a scrollview owns its scroll position and only the user can move it, through the
48/// wheel, the scrollbar, arrow keys or dragging. A [`ScrollController`] lets your own code read and
49/// change that position instead. Create one with [`use_scroll_controller`] and hand it to a
50/// scrollview through its `new_controlled` constructor.
51///
52/// Some cases where a controller is needed:
53///
54/// - Jumping to the top or bottom in response to an action, for example scrolling a chat to the
55///   newest message after sending one.
56/// - Keeping several scrollviews in sync, like a diff view with two panes that move together.
57/// - Reading the current scroll position to drive something else, such as a "scroll to top" button
58///   that only appears once the user has scrolled down.
59///
60/// # Scrolling from code
61///
62/// [`scroll_to`](ScrollController::scroll_to) jumps to the start or end of an axis, with the end
63/// resolved against the content on the next layout. This is the common way to snap a list to its
64/// top or bottom.
65///
66/// ```rust
67/// # use freya::prelude::*;
68/// fn app() -> impl IntoElement {
69///     let mut scroll_controller = use_scroll_controller(ScrollConfig::default);
70///
71///     rect()
72///         .child(
73///             Button::new()
74///                 .on_press(move |_| {
75///                     scroll_controller.scroll_to(ScrollPosition::End, Direction::Vertical);
76///                 })
77///                 .child("Scroll to bottom"),
78///         )
79///         .child(
80///             ScrollView::new_controlled(scroll_controller)
81///                 .children((0..100).map(|i| label().key(i).text(format!("Item {i}")))),
82///         )
83/// }
84/// ```
85///
86/// For an exact pixel offset use [`scroll_to_y`](ScrollController::scroll_to_y) or
87/// [`scroll_to_x`](ScrollController::scroll_to_x). The current position is available by converting
88/// the controller into a `(i32, i32)` tuple of `(x, y)` pixels, or calling
89/// [`position`](ScrollController::position).
90///
91/// # Animated scrolling
92///
93/// Scrolling to a position is instant by default. To animate, call
94/// [`animate_from`](ScrollController::animate_from) with the current position before setting
95/// the target offset.
96///
97/// ```rust
98/// # use freya::prelude::*;
99/// fn app() -> impl IntoElement {
100///     let mut scroll_controller = use_scroll_controller(ScrollConfig::default);
101///
102///     rect()
103///         .child(
104///             Button::new()
105///                 .on_press(move |_| {
106///                     let current = scroll_controller.position();
107///                     scroll_controller.animate_from(current);
108///                     scroll_controller.scroll_to_y(-500);
109///                 })
110///                 .child("Animate scroll"),
111///         )
112///         .child(
113///             ScrollView::new_controlled(scroll_controller)
114///                 .children((0..100).map(|i| label().key(i).text(format!("Item {i}")))),
115///         )
116/// }
117/// ```
118///
119/// # Keeping scrollviews in sync
120///
121/// Pass the same [`ScrollController`] to several scrollviews to share a single scroll position.
122/// Moving any of them moves the rest.
123///
124/// ```rust
125/// # use freya::prelude::*;
126/// fn app() -> impl IntoElement {
127///     let scroll_controller = use_scroll_controller(ScrollConfig::default);
128///
129///     rect()
130///         .horizontal()
131///         .spacing(6.)
132///         .child(
133///             ScrollView::new_controlled(scroll_controller)
134///                 .width(Size::flex(1.))
135///                 .children((0..30).map(|i| label().key(i).text(format!("Left {i}")))),
136///         )
137///         .child(
138///             ScrollView::new_controlled(scroll_controller)
139///                 .width(Size::flex(1.))
140///                 .children((0..30).map(|i| label().key(i).text(format!("Right {i}")))),
141///         )
142/// }
143/// ```
144///
145/// # Starting position
146///
147/// The [`ScrollConfig`] passed to [`use_scroll_controller`] also decides where each axis starts.
148/// Set [`default_vertical_position`](ScrollConfig::default_vertical_position) to
149/// [`ScrollPosition::End`] to open a list already scrolled to the bottom.
150///
151/// ```rust
152/// # use freya::prelude::*;
153/// fn app() -> impl IntoElement {
154///     let scroll_controller = use_scroll_controller(|| ScrollConfig {
155///         default_vertical_position: ScrollPosition::End,
156///         ..Default::default()
157///     });
158///
159///     ScrollView::new_controlled(scroll_controller)
160///         .children((0..100).map(|i| label().key(i).text(format!("Item {i}"))))
161/// }
162/// ```
163#[derive(PartialEq, Clone, Copy)]
164pub struct ScrollController {
165    pub(crate) scroll: State<(i32, i32)>,
166    pub bounds: State<Option<(Size2D, Size2D)>>,
167    pub(crate) damp: State<SmoothDamp>,
168    pub(crate) drag: State<Drag>,
169    pub(crate) task: State<Option<TaskHandle>>,
170}
171
172impl From<ScrollController> for (i32, i32) {
173    /// Reads the current `(x, y)` scroll position in pixels.
174    fn from(val: ScrollController) -> Self {
175        *val.scroll.read()
176    }
177}
178
179impl ScrollController {
180    /// Offset of an axis scrolled to its end, resolved against the content size on the next layout.
181    const END: i32 = i32::MIN;
182
183    /// Creates a controller starting at the scroll position `(x, y)`.
184    pub fn new(x: i32, y: i32) -> Self {
185        Self {
186            scroll: State::create((x, y)),
187            bounds: State::create(None),
188            damp: State::create(SmoothDamp::new()),
189            drag: State::create(Drag::default()),
190            task: State::create(None),
191        }
192    }
193
194    /// Updates the content and viewport bounds used to clamp scroll positions.
195    pub fn apply_layout(&mut self, content_size: Size2D, viewport_size: Size2D) {
196        self.bounds
197            .set_if_modified(Some((content_size, viewport_size)));
198
199        let (x, y) = *self.scroll.peek();
200        self.scroll_to_x(x);
201        self.scroll_to_y(y);
202    }
203
204    /// Reads the current scroll position in pixels.
205    pub fn position(self) -> Point2D {
206        let (x, y): (i32, i32) = self.into();
207        Point2D::new(x as f32, y as f32)
208    }
209
210    /// Scrolls the horizontal axis to `to` pixels. Returns whether the position actually changed.
211    pub fn scroll_to_x(&mut self, to: i32) -> bool {
212        let to = self.bounded_position(to, Direction::Horizontal);
213        let changed = self.scroll.peek().0 != to;
214        if changed {
215            self.scroll.write().0 = to;
216        }
217        changed
218    }
219
220    /// Scrolls the vertical axis to `to` pixels. Returns whether the position actually changed.
221    pub fn scroll_to_y(&mut self, to: i32) -> bool {
222        let to = self.bounded_position(to, Direction::Vertical);
223        let changed = self.scroll.peek().1 != to;
224        if changed {
225            self.scroll.write().1 = to;
226        }
227        changed
228    }
229
230    fn bounded_position(&self, position: i32, direction: Direction) -> i32 {
231        let Some((content_size, viewport_size)) = *self.bounds.read() else {
232            return position;
233        };
234
235        let (content_size, viewport_size) = match direction {
236            Direction::Horizontal => (content_size.width, viewport_size.width),
237            Direction::Vertical => (content_size.height, viewport_size.height),
238        };
239        get_corrected_scroll_position(content_size, viewport_size, position as f32) as i32
240    }
241
242    /// Scrolls `scroll_direction` to `scroll_position`.
243    pub fn scroll_to(&mut self, scroll_position: ScrollPosition, scroll_direction: Direction) {
244        let to = scroll_position.offset();
245        match scroll_direction {
246            Direction::Vertical => self.scroll_to_y(to),
247            Direction::Horizontal => self.scroll_to_x(to),
248        };
249    }
250}
251
252/// Creates a [`ScrollController`], configured by the returned [`ScrollConfig`].
253pub fn use_scroll_controller(config: impl FnOnce() -> ScrollConfig) -> ScrollController {
254    use_hook(|| {
255        let config = config();
256
257        ScrollController::new(
258            config.default_horizontal_position.offset(),
259            config.default_vertical_position.offset(),
260        )
261    })
262}
263
264/// Distance under which the animation is close enough to snap, in pixels.
265const SETTLE_DISTANCE: f32 = 0.5;
266
267/// Speed under which the animation is slow enough to stop, in pixels per second.
268const SETTLE_SPEED: f32 = 20.0;
269
270/// Slowest drag release speed that still starts a fling, in pixels per second.
271const FLING_MIN_SPEED: f32 = 50.0;
272
273/// Fastest drag release speed, in pixels per second.
274const FLING_MAX_SPEED: f32 = 8000.0;
275
276/// Minimum sample interval for touch events delivered together.
277/// 120 is rather a workaround right now, its requires an integration that winit doesnt expose yet.
278const DRAG_MIN_SAMPLE_TIME: f32 = 1.0 / 120.0;
279
280/// Maximum time since the last drag movement that still allows a fling.
281const FLING_RELEASE_TIMEOUT: Duration = Duration::from_millis(100);
282
283/// Scrolling feel of a [`TargetPlatform`].
284pub(crate) trait ScrollFeel {
285    /// Seconds wheel and keyboard scrolls take to reach their destination.
286    fn scroll_smoothing_time(&self) -> f32;
287    /// Seconds a fling takes to stop, which also scales how far it travels.
288    fn scroll_fling_time(&self) -> f32;
289}
290
291impl ScrollFeel for TargetPlatform {
292    fn scroll_smoothing_time(&self) -> f32 {
293        if self.is_mobile() { 0.1 } else { 0.06 }
294    }
295
296    fn scroll_fling_time(&self) -> f32 {
297        if self.is_mobile() { 0.35 } else { 0.5 }
298    }
299}
300
301/// Moves a value towards a target with a smooth and continuous animation.
302#[derive(Clone, Copy, Default)]
303pub(crate) struct SmoothDamp {
304    position: Point2D,
305    velocity: Vector2D,
306    smooth_time: f32,
307}
308
309impl SmoothDamp {
310    pub(crate) fn new() -> Self {
311        Self {
312            position: Point2D::zero(),
313            velocity: Vector2D::zero(),
314            smooth_time: TargetPlatform::Unknown.scroll_smoothing_time(),
315        }
316    }
317
318    /// Returns whether it has settled onto `target`.
319    fn advance(&mut self, target: Point2D, elapsed_seconds: f32) -> bool {
320        let omega = 2.0 / self.smooth_time;
321        let decay = (-omega * elapsed_seconds).exp();
322        let change = self.position - target;
323        let linear_term = (self.velocity + change * omega) * elapsed_seconds;
324
325        let velocity = (self.velocity - linear_term * omega) * decay;
326        let position = target + (change + linear_term) * decay;
327
328        if (target - position).length() < SETTLE_DISTANCE && velocity.length() < SETTLE_SPEED {
329            self.position = target;
330            self.velocity = Vector2D::zero();
331            return true;
332        }
333
334        self.position = position;
335        self.velocity = velocity;
336        false
337    }
338}
339
340/// Velocity tracked while the content is dragged, to fling with on release.
341#[derive(Clone, Copy)]
342pub(crate) struct Drag {
343    velocity: Vector2D,
344    last_move: Instant,
345}
346
347impl Default for Drag {
348    fn default() -> Self {
349        Self {
350            velocity: Vector2D::zero(),
351            last_move: Instant::now(),
352        }
353    }
354}
355
356impl Drag {
357    fn track(&mut self, delta: Vector2D) {
358        let now = Instant::now();
359        let elapsed_seconds = now
360            .duration_since(self.last_move)
361            .as_secs_f32()
362            .max(DRAG_MIN_SAMPLE_TIME);
363
364        let velocity = (-delta / elapsed_seconds).with_max_length(FLING_MAX_SPEED);
365        self.velocity = self.velocity.lerp(velocity, 0.5);
366        self.last_move = now;
367    }
368}
369
370/// Follows the target held by a [`ScrollController`].
371impl ScrollController {
372    /// Position to render, the animated one while a scroll animation is running.
373    pub fn animated_position(&self, target: Point2D) -> Point2D {
374        if self.task.read().is_some() {
375            self.damp.read().position
376        } else {
377            target
378        }
379    }
380
381    /// Chases the controller position from `current`, keeping the current velocity.
382    pub fn animate_from(&mut self, current: Point2D) {
383        self.start(current, None, TargetPlatform::get().scroll_smoothing_time());
384    }
385
386    /// Like [`Self::animate_from`] but launched at `velocity` and slower to stop.
387    fn fling_from(&mut self, current: Point2D, velocity: Vector2D) {
388        self.start(
389            current,
390            Some(velocity),
391            TargetPlatform::get().scroll_fling_time(),
392        );
393    }
394
395    fn start(&mut self, current: Point2D, velocity: Option<Vector2D>, smooth_time: f32) {
396        let is_animating = self.task.read().is_some();
397        {
398            let mut damp = self.damp.write();
399            damp.smooth_time = smooth_time;
400            if let Some(velocity) = velocity {
401                damp.velocity = velocity;
402            }
403            if !is_animating {
404                damp.position = current;
405            }
406        }
407        if is_animating {
408            return;
409        }
410
411        let ticker = RenderingTicker::get();
412        let platform = Platform::get().current_window();
413        let animation_clock = AnimationClock::get();
414        let scroll_controller = *self;
415        let mut damp = self.damp;
416        let mut task = self.task;
417
418        let animation_task = spawn(async move {
419            platform.send(UserEvent::RequestRedraw);
420            let mut previous_frame = Instant::now();
421
422            loop {
423                ticker.tick().await;
424
425                let elapsed_seconds = animation_clock
426                    .correct_elapsed_duration(previous_frame.elapsed())
427                    .as_secs_f32();
428                previous_frame = Instant::now();
429
430                let target = scroll_controller.position();
431                if damp.write().advance(target, elapsed_seconds) {
432                    break;
433                }
434
435                platform.send(UserEvent::RequestRedraw);
436            }
437
438            task.write().take();
439        });
440        task.write().replace(animation_task);
441    }
442
443    /// Returns whether the gesture ended or was cancelled, so callers skip applying the scroll delta.
444    pub(crate) fn scroll_gesture_phase(&mut self, phase: TouchPhase, delta: Vector2D) -> bool {
445        match phase {
446            TouchPhase::Started => {
447                self.stop();
448                self.drag.set(Drag::default());
449            }
450            TouchPhase::Moved => self.drag.write().track(-delta),
451            TouchPhase::Ended => {
452                let bounds = *self.bounds.peek();
453                if self.drag.peek().last_move.elapsed() < FLING_RELEASE_TIMEOUT
454                    && let Some((content, viewport)) = bounds
455                {
456                    self.release_drag(self.animated_position(self.position()), content, viewport);
457                }
458                self.drag.set(Drag::default());
459                return true;
460            }
461            TouchPhase::Cancelled => {
462                self.stop();
463                self.drag.set(Drag::default());
464                return true;
465            }
466        }
467        false
468    }
469
470    /// Freezes the animation and starts a drag from the momentum it caught.
471    pub fn begin_drag(&mut self) {
472        let caught_velocity = self.stop();
473        self.drag.set(Drag {
474            velocity: caught_velocity,
475            last_move: Instant::now(),
476        });
477    }
478
479    /// Feeds a drag movement into the tracked velocity.
480    pub fn drag(&mut self, delta: Vector2D) {
481        self.stop();
482        self.drag.write().track(delta);
483    }
484
485    /// Ends a drag, flinging when it was fast enough to be a flick.
486    pub fn release_drag(&mut self, from: Point2D, content: Size2D, viewport: Size2D) {
487        let velocity = self.drag.peek().velocity;
488        if velocity.length() < FLING_MIN_SPEED {
489            return;
490        }
491
492        let projected = from + velocity * TargetPlatform::get().scroll_fling_time();
493        let target_x = get_corrected_scroll_position(content.width, viewport.width, projected.x);
494        let target_y = get_corrected_scroll_position(content.height, viewport.height, projected.y);
495
496        self.fling_from(from, velocity);
497        self.scroll_to_x(target_x as i32);
498        self.scroll_to_y(target_y as i32);
499    }
500
501    /// Freezes the scroll where it is, returning the velocity it was moving at.
502    pub fn stop(&mut self) -> Vector2D {
503        let task = self.task.write().take();
504        if let Some(task) = task {
505            task.cancel();
506
507            let position = self.damp.peek().position.to_i32();
508            self.scroll_to_x(position.x);
509            self.scroll_to_y(position.y);
510        }
511
512        let velocity = self.damp.peek().velocity;
513        self.damp.write().velocity = Vector2D::zero();
514        velocity
515    }
516}