Skip to main content

gpui_material_extras/date_time/scroll_field/
state.rs

1use std::{cell::Cell, rc::Rc, time::Duration};
2
3use gpui::{BackgroundExecutor, Context, FocusHandle, ScrollEvent, Task, TouchPhase, Window, px};
4
5pub(super) const HEIGHT: f32 = 200.;
6pub(super) const ROW_HEIGHT: f32 = HEIGHT / 3.;
7const PRECISE_SCROLL_SETTLE: Duration = Duration::from_millis(120);
8// Move near a distant destination before animating the last few rows.
9const ANIMATED_ROWS: usize = 3;
10
11struct SettleTimer {
12    _task: Task<()>,
13    bump: Box<dyn Fn(&BackgroundExecutor)>,
14}
15
16/// Caller-owned position and focus for one Material scroll field.
17pub struct ScrollFieldState {
18    pub(super) item_count: usize,
19    pub(super) position: Position,
20    pub(super) target: usize,
21    pub(super) motion: Option<Motion>,
22    pub(super) gesture_start: Option<usize>,
23    settle: Option<SettleTimer>,
24    pub(super) focus: FocusHandle,
25}
26
27#[derive(Clone, Copy, PartialEq)]
28pub(super) struct Position {
29    pub(super) index: usize,
30    pub(super) fraction: f32,
31}
32
33impl Position {
34    fn at(index: usize) -> Self {
35        Self {
36            index,
37            fraction: 0.,
38        }
39    }
40
41    fn shift(self, rows: f32, item_count: usize) -> Self {
42        let offset = self.fraction + rows;
43        let shift = offset.round();
44        Self {
45            index: wrap(self.index, shift as isize, item_count),
46            fraction: offset - shift,
47        }
48    }
49
50    fn offset_from(self, target: usize) -> f32 {
51        let distance = self.index.abs_diff(target).min(ANIMATED_ROWS) as f32;
52        self.fraction
53            + if self.index < target {
54                -distance
55            } else {
56                distance
57            }
58    }
59}
60
61pub(super) fn wrap(index: usize, rows: isize, count: usize) -> usize {
62    if count == 0 {
63        return 0;
64    }
65    let index = index % count;
66    let step = rows.unsigned_abs() % count;
67    if rows < 0 {
68        index
69            .checked_sub(step)
70            .unwrap_or_else(|| count - (step - index))
71    } else if step >= count - index {
72        step - (count - index)
73    } else {
74        index + step
75    }
76}
77
78#[derive(Clone, Copy)]
79pub(super) struct Motion {
80    pub(super) start: f32,
81    pub(super) restart: bool,
82    origin: ScrollOrigin,
83}
84
85#[derive(Clone, Copy, PartialEq, Eq)]
86pub(super) enum ScrollOrigin {
87    Application,
88    Interaction,
89}
90
91impl ScrollFieldState {
92    /// Creates a position at the requested option, clamped to the available indices.
93    pub fn new(item_count: usize, index: usize, cx: &mut Context<Self>) -> Self {
94        let index = index.min(item_count.saturating_sub(1));
95        Self {
96            item_count,
97            position: Position::at(index),
98            target: index,
99            motion: None,
100            gesture_start: None,
101            settle: None,
102            focus: cx.focus_handle(),
103        }
104    }
105
106    /// Returns the total number of selectable options in this scroll field.
107    pub fn item_count(&self) -> usize {
108        self.item_count
109    }
110
111    /// Updates the options and centers the clamped destination immediately.
112    pub fn set_item_count(&mut self, count: usize, cx: &mut Context<Self>) {
113        if self.item_count != count {
114            self.item_count = count;
115            self.scroll_to_option(self.target, cx);
116        }
117    }
118
119    /// Reads the nearest option or `None` when the field is empty.
120    pub fn selected_option(&self) -> Option<usize> {
121        (self.item_count > 0).then_some(self.position.index)
122    }
123
124    /// Reads the destination, including while the wheel is settling.
125    pub fn target_option(&self) -> Option<usize> {
126        (self.item_count > 0).then_some(self.target)
127    }
128
129    /// Returns whether a scroll gesture or settling animation is currently active.
130    pub fn is_scroll_in_progress(&self) -> bool {
131        self.motion.is_some() || self.gesture_start.is_some()
132    }
133
134    /// Returns the retained focus handle for this scroll field.
135    pub fn focus_handle(&self) -> &FocusHandle {
136        &self.focus
137    }
138
139    /// Centers the clamped option without animation.
140    pub fn scroll_to_option(&mut self, index: usize, cx: &mut Context<Self>) {
141        let target = index.min(self.item_count.saturating_sub(1));
142        let position = Position::at(target);
143        if self.target == target
144            && self.position == position
145            && self.gesture_start.is_none()
146            && self.settle.is_none()
147            && self.motion.is_none()
148        {
149            return;
150        }
151        self.target = target;
152        self.gesture_start = None;
153        self.settle = None;
154        self.motion = None;
155        self.position = position;
156        cx.notify();
157    }
158
159    /// Scrolls to the clamped option using the window's motion policy.
160    pub fn animate_scroll_to_option(&mut self, index: usize, cx: &mut Context<Self>) {
161        self.animate_to(index, ScrollOrigin::Application, cx);
162    }
163
164    pub(super) fn animate_to(
165        &mut self,
166        index: usize,
167        origin: ScrollOrigin,
168        cx: &mut Context<Self>,
169    ) {
170        let index = index.min(self.item_count.saturating_sub(1));
171        if self.item_count > 0 && (self.target != index || self.gesture_start.is_some()) {
172            self.snap(index, self.position.offset_from(index), origin, cx);
173        }
174    }
175
176    fn snap(&mut self, index: usize, start: f32, origin: ScrollOrigin, cx: &mut Context<Self>) {
177        if start == 0. || cx.reduce_motion() {
178            self.scroll_to_option(index, cx);
179        } else {
180            self.target = index;
181            self.gesture_start = None;
182            self.settle = None;
183            self.motion = Some(Motion {
184                start,
185                restart: true,
186                origin,
187            });
188            cx.notify();
189        }
190    }
191
192    pub(super) fn sample(&mut self, offset: f32, cx: &mut Context<Self>) {
193        let position = Position::at(self.target).shift(offset, self.item_count);
194        let changed = self.position.index != position.index || offset == 0.;
195        self.position = position;
196        self.motion = self.motion.filter(|_| offset != 0.).map(|mut motion| {
197            motion.restart = false;
198            motion
199        });
200        if changed {
201            cx.notify();
202        }
203    }
204
205    pub(super) fn step(&mut self, delta: isize, cx: &mut Context<Self>) {
206        if self.item_count < 2 {
207            return;
208        }
209        let index = wrap(self.target, delta, self.item_count);
210        let (origin, destination) = if delta > 0 {
211            (self.position.index, index)
212        } else {
213            (index, self.position.index)
214        };
215        let distance = if destination >= origin {
216            destination - origin
217        } else {
218            self.item_count - (origin - destination)
219        };
220        let start =
221            self.position.fraction - delta.signum() as f32 * distance.min(ANIMATED_ROWS) as f32;
222        self.snap(index, start, ScrollOrigin::Interaction, cx);
223    }
224
225    pub(super) fn select_row(&mut self, row: isize, cx: &mut Context<Self>) {
226        if self.item_count > 0 {
227            let index = wrap(self.position.index, row, self.item_count);
228            self.snap(
229                index,
230                self.position.fraction - row as f32,
231                ScrollOrigin::Interaction,
232                cx,
233            );
234        }
235    }
236
237    pub(super) fn scroll(
238        &mut self,
239        event: &ScrollEvent,
240        window: &mut Window,
241        cx: &mut Context<Self>,
242    ) -> bool {
243        if self.item_count < 2 {
244            return false;
245        }
246        let delta = event.delta.pixel_delta(px(ROW_HEIGHT));
247        let x = f32::from(delta.x);
248        let y = f32::from(delta.y);
249        let vertical = y.is_finite() && x.abs() <= y.abs() && y != 0.;
250        if !event.delta.precise() {
251            if vertical {
252                self.step(if y < 0. { 1 } else { -1 }, cx);
253            }
254            return vertical;
255        }
256        if event.touch_phase == TouchPhase::Cancelled {
257            return self.finish_gesture(true, cx);
258        }
259        if vertical {
260            self.gesture_start.get_or_insert(self.position.index);
261            self.motion = None;
262            self.position = self.position.shift(-y / ROW_HEIGHT, self.item_count);
263            self.target = self.position.index;
264            cx.notify();
265        }
266        if event.touch_phase == TouchPhase::Ended {
267            return self.finish_gesture(false, cx);
268        }
269        if vertical {
270            // Some discrete touchpad updates omit a terminal phase. Reuse the
271            // active settle timer across rapid scroll updates instead of
272            // spawning and cancelling a task on every event.
273            if let Some(settle) = &self.settle {
274                (settle.bump)(cx.background_executor());
275            } else {
276                let origin = cx.background_executor().now();
277                let last_offset = Rc::new(Cell::new(Duration::ZERO));
278                let bump_offset = last_offset.clone();
279                let bump = Box::new(move |executor: &BackgroundExecutor| {
280                    bump_offset.set(executor.now().saturating_duration_since(origin));
281                });
282                let state = cx.weak_entity();
283                let task = window.spawn(cx, async move |cx| {
284                    let mut wait = PRECISE_SCROLL_SETTLE;
285                    loop {
286                        let Ok(timer) = cx.update(|_, cx| cx.background_executor().timer(wait))
287                        else {
288                            return;
289                        };
290                        timer.await;
291                        let next_wait = cx.update(|_, cx| {
292                            let elapsed = cx
293                                .background_executor()
294                                .now()
295                                .saturating_duration_since(origin);
296                            let deadline = last_offset.get() + PRECISE_SCROLL_SETTLE;
297                            if elapsed < deadline {
298                                Some(deadline - elapsed)
299                            } else {
300                                let _ =
301                                    state.update(cx, |state, cx| state.finish_gesture(false, cx));
302                                None
303                            }
304                        });
305                        match next_wait {
306                            Ok(Some(remaining)) => wait = remaining,
307                            _ => return,
308                        }
309                    }
310                });
311                self.settle = Some(SettleTimer { _task: task, bump });
312            }
313        }
314        vertical
315    }
316
317    fn finish_gesture(&mut self, cancelled: bool, cx: &mut Context<Self>) -> bool {
318        let Some(start) = self.gesture_start else {
319            return false;
320        };
321        let index = if cancelled {
322            start
323        } else {
324            self.position.index
325        };
326        self.snap(
327            index,
328            self.position.offset_from(index),
329            ScrollOrigin::Interaction,
330            cx,
331        );
332        true
333    }
334
335    pub(super) fn has_pending_interaction(&self) -> bool {
336        self.gesture_start.is_some()
337            || self
338                .motion
339                .is_some_and(|motion| motion.origin == ScrollOrigin::Interaction)
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use super::wrap;
346
347    #[test]
348    fn wrap_guards_against_zero_count_and_wraps_around_bounds() {
349        assert_eq!(wrap(0, 0, 0), 0);
350        assert_eq!(wrap(5, 3, 0), 0);
351        assert_eq!(wrap(5, -3, 0), 0);
352        assert_eq!(wrap(0, -1, 12), 11);
353        assert_eq!(wrap(11, 1, 12), 0);
354        assert_eq!(wrap(2, 25, 12), 3);
355        assert_eq!(wrap(2, -25, 12), 1);
356    }
357}