Skip to main content

repose_ui/
pager.rs

1//! Drag-following pagers with snapping.
2//!
3//! [`HorizontalPager`] and [`VerticalPager`] lay out the pages around the
4//! current continuous position, so a drag moves the pages under the finger and
5//! a release snaps to the nearest page (or one page further when the release
6//! velocity is high). [`PagerState`] exposes that position so indicators can
7//! follow the drag.
8
9use std::cell::{Cell, RefCell};
10use std::rc::Rc;
11use std::sync::atomic::{AtomicU64, Ordering};
12
13use repose_core::*;
14use web_time::Instant;
15
16use crate::ViewExt;
17use crate::subcompose::box_with_constraints_with_key;
18
19/// Configuration for [`HorizontalPager`] and [`VerticalPager`].
20#[derive(Clone)]
21pub struct PagerConfig {
22    pub modifier: Modifier,
23    pub page_spacing: Dp,
24    pub user_scroll_enabled: bool,
25    pub content_padding: PaddingValues,
26    /// How many pages to lay out on each side of the settled page.
27    pub beyond_viewport_page_count: usize,
28    /// Release speed in px/s above which a drag moves a whole page even when
29    /// the page has not travelled past its halfway point.
30    pub fling_velocity_threshold: f32,
31    /// Spec used when a release snaps to a page.
32    pub snap_spec: AnimationSpec,
33}
34
35impl Default for PagerConfig {
36    fn default() -> Self {
37        Self {
38            modifier: Modifier::new(),
39            page_spacing: Dp::ZERO,
40            user_scroll_enabled: true,
41            content_padding: PaddingValues::default(),
42            beyond_viewport_page_count: 1,
43            fling_velocity_threshold: 400.0,
44            snap_spec: AnimationSpec::spring_gentle(),
45        }
46    }
47}
48
49struct PagerInner {
50    position: Signal<f32>,
51    page_count: Signal<usize>,
52    animation: Option<AnimatedValue<f32>>,
53    animation_target: f32,
54}
55
56struct DragState {
57    active: bool,
58    /// `Some(true)` when the gesture is moving along the pager axis,
59    /// `Some(false)` when it was claimed by the cross axis.
60    along_axis: Option<bool>,
61    start_primary: f32,
62    start_cross: f32,
63    start_position: f32,
64    last_primary: f32,
65    last_time: Option<Instant>,
66    velocity: f32,
67}
68
69impl DragState {
70    fn new() -> Self {
71        Self {
72            active: false,
73            along_axis: None,
74            start_primary: 0.0,
75            start_cross: 0.0,
76            start_position: 0.0,
77            last_primary: 0.0,
78            last_time: None,
79            velocity: 0.0,
80        }
81    }
82}
83
84static NEXT_PAGER_ID: AtomicU64 = AtomicU64::new(0);
85
86/// Continuous position and snap animation of a pager.
87///
88/// `position` is measured in pages: `2.0` means page index 2 is settled at the
89/// viewport origin, `2.5` means the pager has been dragged half a page
90/// backwards. [`current_page`](Self::current_page) is the nearest page.
91pub struct PagerState {
92    inner: Rc<RefCell<PagerInner>>,
93    drag: Rc<RefCell<DragState>>,
94    /// Page extent along the scroll axis, in physical px, published by the
95    /// pager each time it measures itself.
96    page_extent: Rc<Cell<f32>>,
97    tick_key: String,
98}
99
100impl PagerState {
101    pub fn new(page_count: usize) -> Self {
102        Self {
103            inner: Rc::new(RefCell::new(PagerInner {
104                position: signal(0.0),
105                page_count: signal(page_count.max(1)),
106                animation: None,
107                animation_target: 0.0,
108            })),
109            drag: Rc::new(RefCell::new(DragState::new())),
110            page_extent: Rc::new(Cell::new(0.0)),
111            tick_key: format!(
112                "pager_tick:{}",
113                NEXT_PAGER_ID.fetch_add(1, Ordering::Relaxed)
114            ),
115        }
116    }
117
118    /// The continuous position in pages.
119    pub fn position(&self) -> f32 {
120        self.inner.borrow().position.get()
121    }
122
123    /// The page closest to the current position.
124    pub fn current_page(&self) -> usize {
125        let max = self.page_count().saturating_sub(1) as f32;
126        self.position().round().clamp(0.0, max) as usize
127    }
128
129    /// How far the pager sits from [`current_page`](Self::current_page), in
130    /// `-0.5..=0.5` pages. Negative means the next page is being revealed.
131    pub fn current_page_offset_fraction(&self) -> f32 {
132        let position = self.position();
133        position - position.round()
134    }
135
136    pub fn page_count(&self) -> usize {
137        self.inner.borrow().page_count.get()
138    }
139
140    /// Animate to `page`, clamped to the page range.
141    pub fn set_page(&self, page: usize) {
142        self.animate_scroll_to_page(page, AnimationSpec::spring_gentle());
143    }
144
145    /// Animate to `page` with an explicit spec.
146    pub fn animate_scroll_to_page(&self, page: usize, spec: AnimationSpec) {
147        let max = self.page_count().saturating_sub(1);
148        self.animate_to_position(page.min(max) as f32, spec);
149    }
150
151    /// Jump to `page` without animating.
152    pub fn scroll_to_page(&self, page: usize) {
153        let max = self.page_count().saturating_sub(1);
154        let target = page.min(max) as f32;
155        let mut inner = self.inner.borrow_mut();
156        inner.animation = None;
157        inner.animation_target = target;
158        inner.position.set_neq(target);
159    }
160
161    /// Update the page count, clamping the position into range.
162    pub fn set_page_count(&self, count: usize) {
163        let count = count.max(1);
164        let max = (count - 1) as f32;
165        let mut inner = self.inner.borrow_mut();
166        inner.page_count.set_neq(count);
167        let position = inner.position.get();
168        if position > max {
169            inner.animation = None;
170            inner.animation_target = max;
171            inner.position.set_neq(max);
172        }
173    }
174
175    /// Whether a snap animation is currently running.
176    pub fn is_animating(&self) -> bool {
177        self.inner.borrow().animation.is_some()
178    }
179
180    /// Move the pager by `delta_pages` pages without animating. Positive
181    /// values reveal later pages, negative earlier ones.
182    pub fn scroll_by_pages(&self, delta_pages: f32) {
183        if !delta_pages.is_finite() {
184            return;
185        }
186        let max = (self.page_count().saturating_sub(1)) as f32;
187        let mut inner = self.inner.borrow_mut();
188        inner.animation = None;
189        let position = (inner.position.get() + delta_pages).clamp(0.0, max);
190        inner.animation_target = position;
191        inner.position.set_neq(position);
192    }
193
194    fn begin_drag(&self, primary: f32, cross: f32) {
195        let mut inner = self.inner.borrow_mut();
196        inner.animation = None;
197        let position = inner.position.get();
198        drop(inner);
199
200        let mut drag = self.drag.borrow_mut();
201        drag.active = true;
202        drag.along_axis = None;
203        drag.start_primary = primary;
204        drag.start_cross = cross;
205        drag.start_position = position;
206        drag.last_primary = primary;
207        drag.last_time = Some(repose_core::animation::now());
208        drag.velocity = 0.0;
209    }
210
211    fn drag(&self, primary: f32, cross: f32) {
212        let extent = self.page_extent.get();
213        if extent <= 0.0 {
214            return;
215        }
216        let mut drag = self.drag.borrow_mut();
217        if !drag.active {
218            return;
219        }
220        if drag.along_axis.is_none() {
221            let along = (primary - drag.start_primary).abs();
222            let across = (cross - drag.start_cross).abs();
223            let slop = Dp(8.0).to_px().0.max(4.0);
224            if along.max(across) < slop {
225                return;
226            }
227            let claimed = along >= across;
228            drag.along_axis = Some(claimed);
229            if !claimed {
230                drag.active = false;
231                return;
232            }
233        }
234
235        let now = repose_core::animation::now();
236        if let Some(last) = drag.last_time {
237            let dt = now.duration_since(last).as_secs_f32();
238            if dt > 1e-4 {
239                let instant = (primary - drag.last_primary) / dt;
240                drag.velocity = drag.velocity * 0.6 + instant * 0.4;
241            }
242        }
243        drag.last_primary = primary;
244        drag.last_time = Some(now);
245
246        let max = (self.page_count().saturating_sub(1)) as f32;
247        let travelled = (primary - drag.start_primary) / extent;
248        let position = (drag.start_position - travelled).clamp(0.0, max);
249        drop(drag);
250
251        self.inner.borrow_mut().position.set_neq(position);
252    }
253
254    fn end_drag(&self, fling_threshold: f32, spec: AnimationSpec) {
255        let mut drag = self.drag.borrow_mut();
256        let was_along_axis = drag.along_axis == Some(true);
257        let velocity = drag.velocity;
258        drag.active = false;
259        drag.along_axis = None;
260        drop(drag);
261
262        if !was_along_axis {
263            self.snap_to_nearest(spec);
264            return;
265        }
266
267        let position = self.position();
268        let max = (self.page_count().saturating_sub(1)) as f32;
269        // Position grows when the finger moves toward the start edge, so the
270        // release velocity points the opposite way from the page it reveals.
271        let fling = if velocity.abs() > fling_threshold {
272            -velocity.signum()
273        } else {
274            0.0
275        };
276        let target = if fling == 0.0 {
277            position.round()
278        } else {
279            (position + fling).round()
280        };
281        // A single gesture moves at most one page, so a fast flick out of a
282        // half-dragged page cannot skip over the neighbour.
283        let anchor = position.round();
284        let target = target.clamp(anchor - 1.0, anchor + 1.0).clamp(0.0, max);
285        self.animate_to_position(target, spec);
286    }
287
288    fn cancel_drag(&self, spec: AnimationSpec) {
289        let mut drag = self.drag.borrow_mut();
290        drag.active = false;
291        drag.along_axis = None;
292        drop(drag);
293        self.snap_to_nearest(spec);
294    }
295
296    /// Settle on the closest page when a touch stopped a snap animation
297    /// without becoming a drag.
298    fn snap_to_nearest(&self, spec: AnimationSpec) {
299        let position = self.position();
300        if (position - position.round()).abs() < 1e-4 {
301            return;
302        }
303        let max = (self.page_count().saturating_sub(1)) as f32;
304        let target = position.round().clamp(0.0, max);
305        self.animate_to_position(target, spec);
306    }
307
308    fn animate_to_position(&self, target: f32, spec: AnimationSpec) {
309        let mut inner = self.inner.borrow_mut();
310        let current = inner.position.get();
311        if (current - target).abs() < 1e-4 {
312            inner.animation = None;
313            inner.animation_target = target;
314            inner.position.set_neq(target);
315            return;
316        }
317        let mut animation = AnimatedValue::new(current, spec);
318        animation.set_target(target);
319        inner.animation = Some(animation);
320        inner.animation_target = target;
321        drop(inner);
322        self.register_tick();
323        request_frame();
324    }
325
326    fn register_tick(&self) {
327        let inner = self.inner.clone();
328        let key = self.tick_key.clone();
329        animation_driver::register(
330            key,
331            Rc::new(RefCell::new(move || {
332                let mut inner = inner.borrow_mut();
333                let (still, value) = {
334                    let Some(animation) = inner.animation.as_mut() else {
335                        return false;
336                    };
337                    let still = animation.update();
338                    (still, *animation.get())
339                };
340                inner.position.set_neq(value);
341                if !still {
342                    inner.position.set_neq(inner.animation_target);
343                    inner.animation = None;
344                }
345                still
346            })),
347        );
348    }
349}
350
351impl PagerState {
352    fn set_page_extent(&self, px: f32) {
353        self.page_extent.set(px);
354    }
355}
356
357fn pager_pages(
358    state: &PagerState,
359    page_builder: &Rc<dyn Fn(usize) -> View>,
360    config: &PagerConfig,
361    scope: BoxWithConstraintsScope,
362    horizontal: bool,
363) -> View {
364    let padding = config.content_padding;
365    let (start_padding, end_padding, cross_padding) = if horizontal {
366        (padding.left, padding.right, (padding.top, padding.bottom))
367    } else {
368        (padding.top, padding.bottom, (padding.left, padding.right))
369    };
370    let (extent, cross) = if horizontal {
371        (scope.max_width, scope.max_height)
372    } else {
373        (scope.max_height, scope.max_width)
374    };
375    let extent = if extent.0.is_finite() {
376        extent
377    } else {
378        Dp::ZERO
379    };
380    let cross = if cross.0.is_finite() { cross } else { Dp::ZERO };
381
382    let page_extent = Dp((extent.0 - start_padding.0 - end_padding.0).max(0.0));
383    state.set_page_extent(page_extent.to_px().0);
384    let cross_extent = Dp((cross.0 - cross_padding.0.0 - cross_padding.1.0).max(0.0));
385    let stride = page_extent.0 + config.page_spacing.0;
386
387    let position = state.position();
388    let count = state.page_count();
389    let center = position.round() as isize;
390    let beyond = config.beyond_viewport_page_count as isize;
391
392    let mut pages = Vec::new();
393    for index in (center - beyond)..=(center + beyond) {
394        if index < 0 || index as usize >= count {
395            continue;
396        }
397        let offset = Dp(start_padding.0 + (index as f32 - position) * stride);
398        let placement = if horizontal {
399            Modifier::new()
400                .offset_left(offset)
401                .offset_top(cross_padding.0)
402                .width(page_extent)
403                .height(cross_extent)
404        } else {
405            Modifier::new()
406                .offset_left(cross_padding.0)
407                .offset_top(offset)
408                .width(cross_extent)
409                .height(page_extent)
410        };
411        pages.push(
412            crate::Box(placement.key(index as u64 + 1).absolute())
413                .child(page_builder(index as usize)),
414        );
415    }
416
417    crate::Box(Modifier::new().fill_max_size()).with_children(pages)
418}
419
420fn pager_handlers(
421    state: &Rc<PagerState>,
422    config: &PagerConfig,
423    horizontal: bool,
424) -> (
425    impl Fn(PointerEvent) + Clone + 'static,
426    impl Fn(PointerEvent) + Clone + 'static,
427    impl Fn(PointerEvent) + Clone + 'static,
428    impl Fn(PointerEvent) + Clone + 'static,
429) {
430    let threshold = config.fling_velocity_threshold;
431    let spec = config.snap_spec.clone();
432    let primary = move |event: &PointerEvent| {
433        let position = event.position_in_window();
434        if horizontal {
435            (position.x, position.y)
436        } else {
437            (position.y, position.x)
438        }
439    };
440
441    let down_state = state.clone();
442    let down_primary = primary;
443    let on_down = move |event: PointerEvent| {
444        let (primary, cross) = down_primary(&event);
445        down_state.begin_drag(primary, cross);
446    };
447
448    let move_state = state.clone();
449    let move_primary = primary;
450    let on_move = move |event: PointerEvent| {
451        let (primary, cross) = move_primary(&event);
452        move_state.drag(primary, cross);
453    };
454
455    let up_state = state.clone();
456    let up_primary = primary;
457    let up_spec = spec.clone();
458    let on_up = move |event: PointerEvent| {
459        let (primary, cross) = up_primary(&event);
460        up_state.drag(primary, cross);
461        up_state.end_drag(threshold, up_spec.clone());
462    };
463
464    let cancel_state = state.clone();
465    let cancel_spec = spec;
466    let on_cancel = move |_event: PointerEvent| {
467        cancel_state.cancel_drag(cancel_spec.clone());
468    };
469
470    (on_down, on_move, on_up, on_cancel)
471}
472
473fn pager_view(
474    state: Rc<PagerState>,
475    page_builder: impl Fn(usize) -> View + 'static,
476    config: PagerConfig,
477    horizontal: bool,
478) -> View {
479    let position = state.position();
480    let count = state.page_count();
481    let builder: Rc<dyn Fn(usize) -> View> = Rc::new(page_builder);
482
483    let mut modifier = Modifier::new()
484        .fill_max_size()
485        .then(config.modifier.clone());
486    if config.user_scroll_enabled {
487        let (on_down, on_move, on_up, on_cancel) = pager_handlers(&state, &config, horizontal);
488        modifier = modifier
489            .on_pointer_down(on_down)
490            .on_pointer_move(on_move)
491            .on_pointer_up(on_up)
492            .on_pointer_cancel(on_cancel);
493    }
494
495    let content_state = state.clone();
496    let content_config = config.clone();
497    box_with_constraints_with_key((position.to_bits(), count), modifier, move |scope| {
498        pager_pages(&content_state, &builder, &content_config, scope, horizontal)
499    })
500}
501
502/// A horizontally swipable pager with drag-following pages and snapping.
503///
504/// The pages around the settled page are laid out side by side and offset by
505/// the continuous [`PagerState::position`], so a drag moves them under the
506/// finger. Releasing snaps to the nearest page, or to the next one when the
507/// release velocity exceeds
508/// [`PagerConfig::fling_velocity_threshold`].
509///
510/// # Example
511/// ```ignore
512/// let state = Rc::new(PagerState::new(5));
513/// HorizontalPager(
514///     "demo",
515///     state.clone(),
516///     |page| Text(format!("Page {}", page + 1)).size(48.0),
517///     PagerConfig {
518///         modifier: Modifier::new().fill_max_width().height(300.0),
519///         ..Default::default()
520///     },
521/// )
522/// ```
523#[allow(non_snake_case)]
524pub fn HorizontalPager(
525    _key: impl Into<String>,
526    state: Rc<PagerState>,
527    page_builder: impl Fn(usize) -> View + 'static,
528    config: PagerConfig,
529) -> View {
530    pager_view(state, page_builder, config, true)
531}
532
533/// A vertically swipable pager with drag-following pages and snapping.
534#[allow(non_snake_case)]
535pub fn VerticalPager(
536    _key: impl Into<String>,
537    state: Rc<PagerState>,
538    page_builder: impl Fn(usize) -> View + 'static,
539    config: PagerConfig,
540) -> View {
541    pager_view(state, page_builder, config, false)
542}