Skip to main content

gpui_base/
scroll_bounce.rs

1//! Boundary displacement only: the list keeps its clamped logical position.
2
3use crate::overscroll::Overscroll;
4use crate::{OngoingScrollExt as _, ScrollbarHandle};
5use gpui::{
6    AnyElement, App, Bounds, ContentMask, DispatchPhase, Element, ElementId, Global,
7    GlobalElementId, Hitbox, HitboxBehavior, HitboxId, InspectorElementId, IntoElement, LayoutId,
8    OngoingScroll, Pixels, ScrollDelta, ScrollEvent, TouchPhase, Window, point, px,
9};
10#[cfg(not(target_family = "wasm"))]
11use std::time::Instant;
12use std::{cell::RefCell, rc::Rc, time::Duration};
13#[cfg(target_family = "wasm")]
14use web_time::Instant;
15
16/// Motion tokens for [`ScrollBounce`]: how far a drag stretches the viewport
17/// past an edge, and how quickly a released edge returns.
18///
19/// Base plays the stretch and the return; the feel belongs to the caller.
20/// The default is tuned to feel like a `UIScrollView` bounce on iOS and
21/// Android, and like an `NSScrollView` bounce elsewhere.
22#[derive(Clone, Copy, Debug, PartialEq)]
23pub struct ScrollBounceMotion {
24    tracking: f32,
25    response: Duration,
26    max_stretch: Option<f32>,
27}
28
29impl Default for ScrollBounceMotion {
30    /// Tuned to feel like a `UIScrollView` bounce on touch platforms; these
31    /// are not UIKit constants. Elsewhere the input is a trackpad, whose
32    /// accelerated deltas run far past a finger's travel, so the default is
33    /// fitted to an `NSScrollView` measured on macOS: the stretch follows
34    /// about 0.075 of the travel, the return decays at 12.5 per second, and
35    /// the edge stops 36 px out. AppKit stretches by the unaccelerated
36    /// travel, which GPUI does not report; the limit keeps a hard swipe as
37    /// short as Finder's.
38    fn default() -> Self {
39        if cfg!(any(target_os = "ios", target_os = "android")) {
40            Self {
41                tracking: 0.55,
42                response: Duration::from_millis(524),
43                max_stretch: None,
44            }
45        } else {
46            Self {
47                tracking: 0.075,
48                // 2π / 12.5
49                response: Duration::from_micros(502_655),
50                max_stretch: Some(36.),
51            }
52        }
53    }
54}
55
56impl ScrollBounceMotion {
57    /// Fraction of finger travel the stretched edge follows at first.
58    ///
59    /// The edge follows less and less as it approaches the viewport height,
60    /// which it never reaches. Tracking is independent of the return, so
61    /// slowing the return does not change how the finger feels.
62    ///
63    /// # Panics
64    ///
65    /// Panics when `tracking` is not finite or not positive.
66    pub fn with_tracking(mut self, tracking: f32) -> Self {
67        assert!(
68            tracking.is_finite() && tracking > 0.,
69            "scroll bounce tracking must be finite and positive"
70        );
71        self.tracking = tracking;
72        self
73    }
74
75    /// Time scale of the return once the finger lifts.
76    ///
77    /// Read the way [`crate::Spring::new`] reads its response: the period one
78    /// full oscillation would take without damping, which is the scale the
79    /// return is felt at rather than the moment it stops. The return is
80    /// critically damped, so it never crosses the edge. A zero response snaps
81    /// the edge back on the spot.
82    pub fn with_response(mut self, response: Duration) -> Self {
83        self.response = response;
84        self
85    }
86
87    /// The farthest the edge goes past its end, in pixels, whether stretched
88    /// or thrown by a fling. The stretch eases into it rather than stopping
89    /// at it.
90    ///
91    /// # Panics
92    ///
93    /// Panics when `max_stretch` is not finite or not positive.
94    pub fn with_max_stretch(mut self, max_stretch: f32) -> Self {
95        assert!(
96            max_stretch.is_finite() && max_stretch > 0.,
97            "scroll bounce max stretch must be finite and positive"
98        );
99        self.max_stretch = Some(max_stretch);
100        self
101    }
102
103    /// Fraction of finger travel the stretched edge follows at first.
104    pub fn tracking(&self) -> f32 {
105        self.tracking
106    }
107
108    /// Time scale of the return once the finger lifts.
109    pub fn response(&self) -> Duration {
110        self.response
111    }
112
113    /// The farthest the edge goes past its end, or `None` when only the
114    /// viewport height bounds it.
115    pub fn max_stretch(&self) -> Option<f32> {
116        self.max_stretch
117    }
118
119    /// Undamped angular frequency of the return, or `None` when it snaps.
120    fn omega(&self) -> Option<f32> {
121        let seconds = self.response.as_secs_f32();
122        (seconds > 0.).then(|| std::f32::consts::TAU / seconds)
123    }
124}
125
126/// Adds vertical touch overscroll to an existing scroll viewport.
127///
128/// The child owns layout, content, and ordinary scrolling; `handle` must be the
129/// child's scroll handle. Only unused vertical deltas stretch the viewport.
130/// The stable `id` owns gesture and spring state. Change it when replacing the
131/// document. Put fixed chrome (scrollbars, toolbars) outside this wrapper.
132///
133/// Enabled by default where the platform's own scroll views bounce: iOS,
134/// Android and macOS. Reduced motion disables displacement. Keyboard and
135/// focus remain owned by the child. No colors, padding, or dimensions are
136/// imposed.
137///
138/// Nested scroll areas follow the platform: the innermost one under the
139/// pointer takes the whole gesture, at its ends too, and bounces there
140/// rather than handing the rest to the area around it. A disabled
141/// `ScrollBounce` still scrolls its child and keeps the gesture from the
142/// areas around it; it only stops at the ends instead of stretching.
143pub struct ScrollBounce {
144    id: ElementId,
145    handle: Rc<dyn ScrollbarHandle>,
146    child: AnyElement,
147    enabled: bool,
148    scroll_wheel: bool,
149    motion: ScrollBounceMotion,
150    on_scroll: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
151}
152
153impl ScrollBounce {
154    pub fn new<H: ScrollbarHandle + Clone>(
155        id: impl Into<ElementId>,
156        handle: &H,
157        child: impl IntoElement,
158    ) -> Self {
159        Self {
160            id: id.into(),
161            handle: Rc::new(handle.clone()),
162            child: child.into_any_element(),
163            enabled: Self::enabled_by_default(),
164            scroll_wheel: true,
165            motion: ScrollBounceMotion::default(),
166            on_scroll: None,
167        }
168    }
169
170    /// Whether scroll areas bounce on this platform unless told otherwise:
171    /// on iOS, Android and macOS, whose own scroll views do.
172    pub const fn enabled_by_default() -> bool {
173        cfg!(any(
174            target_os = "ios",
175            target_os = "android",
176            target_os = "macos"
177        ))
178    }
179
180    /// Turn the bounce on or off. Defaults to [`Self::enabled_by_default`].
181    pub fn enabled(mut self, enabled: bool) -> Self {
182        self.enabled = enabled;
183        self
184    }
185
186    /// Own vertical scrolling using the shared input overscroll engine.
187    /// Precise pixel input can bounce; ordinary line-wheel input only scrolls
188    /// and cancels any existing displacement. Keep fixed chrome outside it.
189    ///
190    /// On by default. Turned off, the child scrolls itself and only its
191    /// unused deltas stretch the edge; that needs input that emits `Ended`
192    /// at finger release, before momentum, as touch does.
193    pub fn scroll_wheel(mut self, enabled: bool) -> Self {
194        self.scroll_wheel = enabled;
195        self
196    }
197
198    /// Set how far a drag stretches past an edge and how the edge returns.
199    pub fn motion(mut self, motion: ScrollBounceMotion) -> Self {
200        self.motion = motion;
201        self
202    }
203
204    /// Observe a logical scroll performed when a reverse drag leaves the stretched
205    /// region. Runs after the handle update, with no internal state borrowed.
206    /// Ordinary child scrolling continues to use the child's own notifications.
207    pub fn on_scroll(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
208        self.on_scroll = Some(Rc::new(handler));
209        self
210    }
211}
212
213#[derive(Default)]
214struct State {
215    physics: Physics,
216    overscroll: Overscroll,
217    sampled_at: Option<Instant>,
218    ongoing_scroll: OngoingScroll,
219    short_drag_distance: Option<f32>,
220    last_wheel_at: Option<Instant>,
221    /// Sign of the stream being suppressed, when it is known to be momentum
222    /// that cannot reverse. `None` suppresses both directions.
223    suppressed_direction: Option<f32>,
224}
225
226impl State {
227    /// Release the edge. A stretch made outside a gesture is momentum (or a
228    /// phaseless wheel) hitting the edge; that stream only pushes outward,
229    /// so an inward packet is a new scroll and ends the suppression. After a
230    /// gesture's own release the suppressed momentum may point either way.
231    fn release(&mut self, from_rest: bool) {
232        self.physics.release();
233        self.suppressed_direction =
234            (from_rest && self.physics.suppress_momentum).then(|| self.physics.offset().signum());
235    }
236}
237
238// GPUI starts a normal touch pan only after its 8 px touch slop, but a touch
239// catching a fling starts at zero displacement. A short catch should stop the
240// old fling rather than turn a few fast pixels into a new one.
241const CATCH_DRAG_SLOP: f32 = 8.;
242
243// Momentum arrives once per frame until it stops, so a longer silence means
244// the suppressed stream has ended. Smooth-scrolling mouse drivers on macOS
245// send precise deltas with no phase: they never send the `Started` that
246// otherwise ends suppression, and would stay locked after one bounce.
247const MOMENTUM_GAP: Duration = Duration::from_millis(250);
248
249/// Which scroll area under the pointer takes the current wheel event.
250///
251/// Capture runs from the outside in, so every area that could scroll writes
252/// itself here before its child paints, and the innermost one is the last
253/// to write. Each then acts, from the inside out, only if it is still the
254/// one written.
255#[derive(Default)]
256struct ScrollOwner(Option<HitboxId>);
257
258impl Global for ScrollOwner {}
259
260/// Take the current wheel event from the scroll areas around `hitbox`.
261/// Call it in the capture phase, from a listener registered before the
262/// children paint, whenever the area would scroll for the event.
263pub(crate) fn claim_scroll(hitbox: HitboxId, cx: &mut App) {
264    cx.default_global::<ScrollOwner>().0 = Some(hitbox);
265}
266
267fn owns_scroll(hitbox: HitboxId, cx: &App) -> bool {
268    cx.try_global::<ScrollOwner>()
269        .is_some_and(|owner| owner.0 == Some(hitbox))
270}
271
272/// `ScrollbarHandle` has no `max_offset`; recover it from the definition
273/// `content_size = viewport + max_offset`. Both dispatch phases clamp against
274/// this bound and must agree on it.
275fn max_scroll_extent(handle: &dyn ScrollbarHandle) -> Pixels {
276    (handle.content_size().height - handle.viewport_bounds().size.height).max(px(0.))
277}
278
279#[doc(hidden)]
280pub struct ScrollBouncePrepaintState {
281    state: Rc<RefCell<State>>,
282    hitbox: Hitbox,
283}
284
285#[cfg(not(feature = "gpui-fast"))]
286impl IntoElement for ScrollBounce {
287    type Element = Self;
288    fn into_element(self) -> Self {
289        self
290    }
291}
292
293impl Element for ScrollBounce {
294    type RequestLayoutState = ();
295    type PrepaintState = ScrollBouncePrepaintState;
296
297    fn id(&self) -> Option<ElementId> {
298        Some(self.id.clone())
299    }
300    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
301        None
302    }
303
304    fn request_layout(
305        &mut self,
306        _: Option<&GlobalElementId>,
307        _: Option<&InspectorElementId>,
308        window: &mut Window,
309        cx: &mut App,
310    ) -> (LayoutId, ()) {
311        (self.child.request_layout(window, cx), ())
312    }
313
314    fn prepaint(
315        &mut self,
316        id: Option<&GlobalElementId>,
317        _: Option<&InspectorElementId>,
318        bounds: Bounds<Pixels>,
319        _: &mut (),
320        window: &mut Window,
321        cx: &mut App,
322    ) -> Self::PrepaintState {
323        let state = window.with_element_state(
324            id.expect("ScrollBounce has an id"),
325            |state: Option<Rc<RefCell<State>>>, _| {
326                let state = state.unwrap_or_default();
327                (state.clone(), state)
328            },
329        );
330        let offset = {
331            let mut state = state.borrow_mut();
332            if !self.enabled || cx.reduce_motion() {
333                *state = State::default();
334            }
335            if self.scroll_wheel {
336                state.overscroll.set_motion(self.motion);
337                if max_scroll_extent(self.handle.as_ref()) <= px(0.) {
338                    state.overscroll.reset();
339                }
340                if state.overscroll.step(cx.background_executor().now()) {
341                    window.request_animation_frame();
342                }
343                state.overscroll.offset()
344            } else {
345                state.physics.motion = self.motion;
346                let now = Instant::now();
347                let elapsed = state
348                    .sampled_at
349                    .replace(now)
350                    .map_or(0., |at| now.duration_since(at).as_secs_f32());
351                if state.physics.step(elapsed) {
352                    window.request_animation_frame();
353                }
354                state.physics.offset()
355            }
356        };
357        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
358        window.with_content_mask(Some(ContentMask { bounds }), |window| {
359            window.with_element_offset(point(px(0.), px(offset)), |window| {
360                self.child.prepaint(window, cx);
361            });
362        });
363        // The child's fresh metrics can remove overflow during a drag.
364        // Reset against those metrics as well, and repaint any displaced frame.
365        if self.scroll_wheel && max_scroll_extent(self.handle.as_ref()) <= px(0.) {
366            let mut state = state.borrow_mut();
367            let displaced = state.overscroll.offset() != 0.;
368            state.overscroll.reset();
369            if displaced {
370                window.request_animation_frame();
371            }
372        }
373        ScrollBouncePrepaintState { state, hitbox }
374    }
375
376    fn paint(
377        &mut self,
378        _: Option<&GlobalElementId>,
379        _: Option<&InspectorElementId>,
380        bounds: Bounds<Pixels>,
381        _: &mut (),
382        prepaint: &mut Self::PrepaintState,
383        window: &mut Window,
384        cx: &mut App,
385    ) {
386        if self.scroll_wheel {
387            let hitbox = prepaint.hitbox.id;
388            let handle = self.handle.clone();
389            window.on_mouse_event(move |_: &ScrollEvent, phase, window, cx| {
390                if phase == DispatchPhase::Capture
391                    && hitbox.should_handle_scroll(window)
392                    && max_scroll_extent(handle.as_ref()) > px(0.)
393                {
394                    claim_scroll(hitbox, cx);
395                }
396            });
397        }
398        if self.enabled && !self.scroll_wheel && !cx.reduce_motion() {
399            let state = prepaint.state.clone();
400            let hitbox = prepaint.hitbox.id;
401            let handle = self.handle.clone();
402            let view = window.current_view();
403            let on_scroll = self.on_scroll.clone();
404            let mut before = 0.;
405            let mut allow_end_bounce = false;
406            window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
407                let ScrollDelta::Pixels(mut delta) = event.delta else {
408                    if phase == DispatchPhase::Capture && hitbox.should_handle_scroll(window) {
409                        let mut state = state.borrow_mut();
410                        let displaced = state.physics.offset() != 0.;
411                        *state = State::default();
412                        drop(state);
413                        if displaced {
414                            cx.notify(view);
415                        }
416                    }
417                    return;
418                };
419                if !hitbox.should_handle_scroll(window) {
420                    return;
421                }
422                let mut state = state.borrow_mut();
423                // Lock the gesture to the axis it started on, so a diagonal
424                // swipe cannot wobble out of the stretch from one packet to
425                // the next. Both dispatch phases see the same packet, and the
426                // lock gives both the same answer.
427                state
428                    .ongoing_scroll
429                    .lock_axis(&mut delta, event.touch_phase);
430                if delta.x.abs() > delta.y.abs() {
431                    return;
432                }
433                let ended = matches!(event.touch_phase, TouchPhase::Ended | TouchPhase::Cancelled);
434                let mut scrolled = false;
435                let mut changed = false;
436                if phase == DispatchPhase::Capture {
437                    before = handle.offset().y.as_f32();
438                    if event.touch_phase == TouchPhase::Started {
439                        state.short_drag_distance = (delta.y == px(0.)).then_some(0.);
440                        state.physics.begin(bounds.size.height.as_f32());
441                    } else if let Some(distance) = state.short_drag_distance.as_mut() {
442                        *distance += delta.y.as_f32().abs();
443                        if *distance > CATCH_DRAG_SLOP {
444                            state.short_drag_distance = None;
445                        }
446                    }
447                    let suppress_short_drag_momentum = if ended {
448                        state.short_drag_distance.take().is_some()
449                            && event.touch_phase == TouchPhase::Ended
450                    } else {
451                        false
452                    };
453                    // The current Ended packet may still cross an edge; only
454                    // momentum packets after it should be suppressed.
455                    allow_end_bounce = suppress_short_drag_momentum;
456                    let now = cx.background_executor().now();
457                    let paused = state
458                        .last_wheel_at
459                        .replace(now)
460                        .is_some_and(|at| now.saturating_duration_since(at) >= MOMENTUM_GAP);
461                    let reversed = state.suppressed_direction.is_some_and(|direction| {
462                        delta.y != px(0.) && delta.y.as_f32().signum() != direction
463                    });
464                    if paused || reversed {
465                        state.physics.suppress_momentum = false;
466                    }
467                    if state.physics.suppress_momentum {
468                        cx.stop_propagation();
469                        return;
470                    }
471                    if state.physics.offset() != 0. {
472                        // Outside a gesture (a phaseless wheel once suppression
473                        // lifts) a packet grabs the returning edge and lets it
474                        // go again, as it would at rest.
475                        let from_rest = !state.physics.dragging;
476                        if from_rest {
477                            state.physics.begin(bounds.size.height.as_f32());
478                        }
479                        let remainder = state.physics.pull(delta.y.as_f32());
480                        if remainder != 0. {
481                            let max = max_scroll_extent(handle.as_ref());
482                            let mut offset = handle.offset();
483                            offset.y = px(before + remainder).clamp(-max, px(0.));
484                            handle.set_offset(offset);
485                            scrolled = true;
486                        }
487                        if ended || from_rest {
488                            state.release(from_rest);
489                        }
490                        changed = true;
491                        cx.stop_propagation();
492                    } else if ended {
493                        state.physics.release();
494                    }
495                    if suppress_short_drag_momentum {
496                        state.physics.suppress_momentum = true;
497                        state.suppressed_direction = None;
498                    }
499                } else {
500                    // Div applies deltas immediately but clamps during its next
501                    // prepaint. Clamp here so that boundary deltas are not
502                    // mistaken for consumed scrolling (ListState clamps eagerly).
503                    let mut offset = handle.offset();
504                    let max = max_scroll_extent(handle.as_ref());
505                    let clamped = offset.y.clamp(-max, px(0.));
506                    if clamped != offset.y {
507                        offset.y = clamped;
508                        handle.set_offset(offset);
509                    }
510                    let after = offset.y.as_f32();
511                    let requested = delta.y.as_f32();
512                    // A List can coalesce several packets against one painted
513                    // scroll position. Their offset difference alone does not
514                    // prove overscroll, especially after direction changes or
515                    // a zero-delta Ended packet from a trackpad.
516                    let at_outward_edge = (requested > 0. && offset.y == px(0.))
517                        || (requested < 0. && offset.y == -max);
518                    let residual =
519                        (requested - (after - before)).clamp(requested.min(0.), requested.max(0.));
520                    if at_outward_edge
521                        && residual.abs() > 0.01
522                        && (!state.physics.suppress_momentum || allow_end_bounce)
523                    {
524                        let dragging = state.physics.dragging;
525                        if !dragging {
526                            state.physics.begin(bounds.size.height.as_f32());
527                        }
528                        state.physics.pull(residual);
529                        if !dragging || ended {
530                            state.release(!dragging);
531                        }
532                        changed = true;
533                    }
534                }
535                if changed {
536                    state.sampled_at = Some(Instant::now());
537                }
538                drop(state);
539                if changed {
540                    cx.notify(view);
541                }
542                if scrolled && let Some(handler) = &on_scroll {
543                    handler(window, cx);
544                }
545            });
546        }
547        window.with_content_mask(Some(ContentMask { bounds }), |window| {
548            self.child.paint(window, cx)
549        });
550        // After the children, so that the areas inside act first.
551        if self.scroll_wheel {
552            let bounces = self.enabled && !cx.reduce_motion();
553            let state = prepaint.state.clone();
554            let hitbox = prepaint.hitbox.id;
555            let handle = self.handle.clone();
556            let view = window.current_view();
557            let on_scroll = self.on_scroll.clone();
558            window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
559                if phase != DispatchPhase::Capture
560                    || !hitbox.should_handle_scroll(window)
561                    || !owns_scroll(hitbox, cx)
562                {
563                    return;
564                }
565                let mut delta = event.delta.pixel_delta(window.line_height());
566                let mut state = state.borrow_mut();
567                state
568                    .ongoing_scroll
569                    .lock_axis(&mut delta, event.touch_phase);
570                let max = max_scroll_extent(handle.as_ref());
571                if max <= px(0.) {
572                    state.overscroll.reset();
573                    return;
574                }
575                if delta.x.abs() > delta.y.abs() {
576                    state
577                        .overscroll
578                        .touch_phase(event.touch_phase, cx.background_executor().now());
579                    return;
580                }
581                let before = handle.offset();
582                let changed = if !bounces || matches!(event.delta, ScrollDelta::Lines(_)) {
583                    let displaced = state.overscroll.offset() != 0.;
584                    state.overscroll.reset();
585                    let mut offset = before;
586                    offset.y = (before.y + delta.y).clamp(-max, px(0.));
587                    handle.set_offset(offset);
588                    displaced
589                } else {
590                    state.overscroll.packet(
591                        delta.y.as_f32(),
592                        event.touch_phase,
593                        bounds.size.height.as_f32(),
594                        cx.background_executor().now(),
595                        |dy| {
596                            let before = handle.offset();
597                            let mut offset = before;
598                            let requested = before.y + px(dy);
599                            offset.y = requested.clamp(-max, px(0.));
600                            handle.set_offset(offset);
601                            // Only clamping leaves unused input; subtraction
602                            // can leave a rounding residue inside the list.
603                            if offset.y == requested {
604                                dy
605                            } else {
606                                (offset.y - before.y).as_f32()
607                            }
608                        },
609                    )
610                };
611                let scrolled = handle.offset() != before;
612                drop(state);
613                cx.stop_propagation();
614                if changed || scrolled {
615                    cx.notify(view);
616                }
617                if scrolled && let Some(handler) = &on_scroll {
618                    handler(window, cx);
619                }
620            });
621        }
622    }
623}
624
625/// The largest outward speed, at most `speed`, that lets an edge at
626/// `position` go no farther out than `max`.
627///
628/// The edge then follows `(position + speed * t) * e^(-ωt)`, which peaks at
629/// `speed / ω * e^(ω * position / speed - 1)` when the speed is enough to
630/// carry it outward at all.
631fn limit_throw(position: f32, speed: f32, omega: f32, max: f32) -> f32 {
632    let peak = |speed: f32| {
633        if speed <= omega * position {
634            position
635        } else {
636            speed / omega * (omega * position / speed - 1.).exp()
637        }
638    };
639    if peak(speed) <= max {
640        return speed;
641    }
642    let (mut low, mut high) = (0., speed);
643    for _ in 0..24 {
644        let mid = (low + high) / 2.;
645        if peak(mid) <= max {
646            low = mid;
647        } else {
648            high = mid;
649        }
650    }
651    low
652}
653
654/// The stretch past an edge and its return, shared with the input's own
655/// scrolling.
656#[derive(Default)]
657pub(crate) struct Physics {
658    position: f32,
659    velocity: f32,
660    dragging: bool,
661    suppress_momentum: bool,
662    extent: f32,
663    motion: ScrollBounceMotion,
664}
665
666impl Physics {
667    pub(crate) fn set_motion(&mut self, motion: ScrollBounceMotion) {
668        self.motion = motion;
669    }
670
671    pub(crate) fn reset(&mut self) {
672        *self = Self {
673            motion: self.motion,
674            ..Self::default()
675        };
676    }
677    pub(crate) fn is_dragging(&self) -> bool {
678        self.dragging
679    }
680
681    /// Whether a released edge is still on its way.
682    pub(crate) fn is_moving(&self) -> bool {
683        !self.dragging && (self.position != 0. || self.velocity != 0.)
684    }
685
686    pub(crate) fn offset(&self) -> f32 {
687        if self.dragging {
688            let d = self.extent.max(1.);
689            let tracking = self.motion.tracking;
690            let stretch = self.position * tracking / (1. + tracking * self.position.abs() / d);
691            match self.motion.max_stretch {
692                // Follows the stretch closely at first, then eases into the limit.
693                Some(max) => max * (stretch / max).tanh(),
694                None => stretch,
695            }
696        } else {
697            self.position
698        }
699    }
700
701    pub(crate) fn begin(&mut self, extent: f32) {
702        let offset = self.offset();
703        // A displaced edge keeps the extent it was stretched under. The
704        // rubber-band curve saturates at the extent, so re-reading a viewport
705        // that shrank mid-return (rotation, keyboard) could not place the
706        // finger where the edge is: it would snap, then need a long pull back.
707        if offset == 0. || self.extent <= 0. {
708            self.extent = extent.max(1.);
709        }
710        // Invert the curves so grabbing a returning edge is continuous.
711        let stretch = match self.motion.max_stretch {
712            Some(max) => max * (offset / max).clamp(-0.999, 0.999).atanh(),
713            None => offset,
714        };
715        let tracking = self.motion.tracking;
716        self.position = stretch / (tracking * (1. - stretch.abs() / self.extent).max(0.01));
717        self.velocity = 0.;
718        self.dragging = true;
719        self.suppress_momentum = false;
720    }
721
722    /// Apply finger displacement. Return the part that crosses back into the list.
723    pub(crate) fn pull(&mut self, delta: f32) -> f32 {
724        let previous = self.position;
725        let next = previous + delta;
726        if previous != 0. && previous.signum() != next.signum() {
727            self.position = 0.;
728            next
729        } else {
730            self.position = next;
731            0.
732        }
733    }
734
735    pub(crate) fn release(&mut self) {
736        self.position = self.offset();
737        self.dragging = false;
738        if self.position != 0. {
739            self.suppress_momentum = true;
740        }
741    }
742
743    /// Let go of the edge the way AppKit does: from wherever it is, it
744    /// returns at full speed, and it carries `velocity` outward on the way.
745    /// Its path is `(x + velocity * t) * e^(-ωt)`, so an edge at rest is
746    /// thrown out and back, and an edge let go while still being pushed
747    /// returns a little later. It never crosses the boundary: velocity
748    /// pointing back inward is dropped.
749    pub(crate) fn let_go(&mut self, velocity: f32) {
750        self.position = self.offset();
751        self.dragging = false;
752        let Some(omega) = self.motion.omega() else {
753            self.position = 0.;
754            self.velocity = 0.;
755            return;
756        };
757        let mut outward = if self.position * velocity >= 0. {
758            velocity
759        } else {
760            0.
761        };
762        if let Some(max) = self.motion.max_stretch {
763            outward =
764                outward.signum() * limit_throw(self.position.abs(), outward.abs(), omega, max);
765        }
766        self.velocity = outward - omega * self.position;
767    }
768
769    /// Exact critically damped spring integration, independent of refresh rate.
770    pub(crate) fn step(&mut self, seconds: f32) -> bool {
771        if self.dragging || (self.position == 0. && self.velocity == 0.) {
772            return false;
773        }
774        let Some(omega) = self.motion.omega() else {
775            self.position = 0.;
776            self.velocity = 0.;
777            return false;
778        };
779        let decay = (-omega * seconds).exp();
780        let c = self.velocity + omega * self.position;
781        self.position = (self.position + c * seconds) * decay;
782        self.velocity = (self.velocity - omega * c * seconds) * decay;
783        if self.position.abs() < 0.1 && self.velocity.abs() < 1. {
784            self.position = 0.;
785            self.velocity = 0.;
786            false
787        } else {
788            true
789        }
790    }
791}
792
793#[cfg(test)]
794mod tests {
795    use super::*;
796    use gpui::{
797        Context, InteractiveElement as _, ParentElement as _, Render, ScrollHandle,
798        StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext, div,
799    };
800
801    struct ScrollTest {
802        handle: ScrollHandle,
803        enabled: bool,
804    }
805
806    impl Render for ScrollTest {
807        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
808            div().p(px(20.)).child(
809                ScrollBounce::new(
810                    "bounce",
811                    &self.handle,
812                    div()
813                        .id("viewport")
814                        .w(px(200.))
815                        .h(px(200.))
816                        .overflow_y_scroll()
817                        .track_scroll(&self.handle)
818                        .child(div().h(px(600.)).w_full()),
819                )
820                .enabled(self.enabled)
821                .scroll_wheel(false),
822            )
823        }
824    }
825
826    fn draw(cx: &mut VisualTestContext) {
827        cx.update(|window, cx| window.draw(cx).clear(cx));
828    }
829
830    fn scroll(cx: &mut VisualTestContext, delta: f32, phase: TouchPhase) {
831        cx.simulate_event(ScrollEvent {
832            position: point(px(100.), px(100.)),
833            delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
834            touch_phase: phase,
835            ..Default::default()
836        });
837    }
838
839    struct WheelViewport(ScrollHandle, Pixels);
840
841    impl Render for WheelViewport {
842        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
843            ScrollBounce::new(
844                "wheel-bounce",
845                &self.0,
846                div()
847                    .id("wheel-viewport")
848                    .w(px(200.))
849                    .h(px(200.))
850                    .overflow_y_scroll()
851                    .track_scroll(&self.0)
852                    .child(div().h(self.1).w_full()),
853            )
854            .enabled(true)
855            .scroll_wheel(true)
856        }
857    }
858
859    #[gpui::test]
860    fn fractional_wheel_input_keeps_scrolling_deep_in_a_long_list(cx: &mut TestAppContext) {
861        for delta in [-0.09_f32, 0.09] {
862            let mut app = cx.new_app();
863            let handle = ScrollHandle::new();
864            let (_, cx) = app.add_window_view({
865                let handle = handle.clone();
866                move |_, _| WheelViewport(handle, px(2_000_000.))
867            });
868            draw(cx);
869            handle.set_offset(point(px(0.), px(-1_000_000.)));
870            draw(cx);
871            let origin = handle.bounds().origin;
872            scroll(cx, delta, TouchPhase::Started);
873            scroll(cx, delta.signum() * 20., TouchPhase::Moved);
874            scroll(cx, 0., TouchPhase::Ended);
875            cx.executor().advance_clock(Duration::from_millis(16));
876            draw(cx);
877            scroll(cx, delta, TouchPhase::Moved);
878            scroll(cx, 0., TouchPhase::Started);
879            scroll(cx, delta.signum() * 20., TouchPhase::Moved);
880            draw(cx);
881            // Here each 0.09px delta rounds to 0.0625px in the stored offset.
882            let expected = -1_000_000. + delta.signum() * 40.125;
883            assert!((handle.offset().y.as_f32() - expected).abs() < 0.001);
884            assert_eq!(handle.bounds().origin, origin);
885        }
886    }
887
888    #[gpui::test]
889    fn ordinary_mouse_wheel_keeps_the_shared_viewport_undisplaced(cx: &mut TestAppContext) {
890        let handle = ScrollHandle::new();
891        let (_, cx) = cx.add_window_view({
892            let handle = handle.clone();
893            move |_, _| WheelViewport(handle, px(600.))
894        });
895        draw(cx);
896        let origin = handle.bounds().origin;
897        cx.simulate_event(ScrollEvent {
898            position: point(px(100.), px(100.)),
899            delta: ScrollDelta::Lines(point(0., -100.)),
900            ..Default::default()
901        });
902        draw(cx);
903        cx.executor().advance_clock(Duration::from_millis(16));
904        draw(cx);
905        assert_eq!(handle.offset().y, -handle.max_offset().y);
906        assert_eq!(handle.bounds().origin, origin);
907    }
908
909    #[gpui::test]
910    fn wheel_scrolling_interrupts_the_shared_return(cx: &mut TestAppContext) {
911        let handle = ScrollHandle::new();
912        let (_, cx) = cx.add_window_view({
913            let handle = handle.clone();
914            move |_, _| WheelViewport(handle, px(600.))
915        });
916        draw(cx);
917        let wheel = |cx: &mut VisualTestContext, dy| {
918            cx.simulate_event(ScrollEvent {
919                position: point(px(100.), px(100.)),
920                delta: ScrollDelta::Lines(point(0., dy)),
921                ..Default::default()
922            });
923        };
924        scroll(cx, -1000., TouchPhase::Started);
925        scroll(cx, 0., TouchPhase::Ended);
926        draw(cx);
927        assert_eq!(handle.offset().y, -handle.max_offset().y);
928        cx.executor().advance_clock(Duration::from_millis(200));
929        draw(cx);
930        let end = handle.offset().y;
931        wheel(cx, 2.);
932        assert!(
933            handle.offset().y > end,
934            "the new wheel input scrolls before the next frame"
935        );
936        draw(cx);
937    }
938
939    /// A scroll area with a shorter one inside it, 100 px down.
940    struct Nested {
941        outer: ScrollHandle,
942        inner: ScrollHandle,
943        inner_enabled: bool,
944    }
945
946    impl Render for Nested {
947        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
948            ScrollBounce::new(
949                "outer",
950                &self.outer,
951                div()
952                    .id("outer-viewport")
953                    .w(px(200.))
954                    .h(px(300.))
955                    .overflow_y_scroll()
956                    .track_scroll(&self.outer)
957                    .child(div().h(px(100.)).w_full())
958                    .child(
959                        ScrollBounce::new(
960                            "inner",
961                            &self.inner,
962                            div()
963                                .id("inner-viewport")
964                                .w(px(200.))
965                                .h(px(100.))
966                                .overflow_y_scroll()
967                                .track_scroll(&self.inner)
968                                .child(div().h(px(400.)).w_full()),
969                        )
970                        .enabled(self.inner_enabled),
971                    )
972                    .child(div().h(px(600.)).w_full()),
973            )
974            .enabled(true)
975        }
976    }
977
978    fn nested(cx: &mut TestAppContext, inner_enabled: bool) -> (Nested, &mut VisualTestContext) {
979        let (outer, inner) = (ScrollHandle::new(), ScrollHandle::new());
980        let (_, cx) = cx.add_window_view({
981            let (outer, inner) = (outer.clone(), inner.clone());
982            move |_, _| Nested {
983                outer,
984                inner,
985                inner_enabled,
986            }
987        });
988        draw(cx);
989        (
990            Nested {
991                outer,
992                inner,
993                inner_enabled,
994            },
995            cx,
996        )
997    }
998
999    fn scroll_at(cx: &mut VisualTestContext, y: f32, delta: f32, phase: TouchPhase) {
1000        cx.simulate_event(ScrollEvent {
1001            position: point(px(100.), px(y)),
1002            delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1003            touch_phase: phase,
1004            ..Default::default()
1005        });
1006        draw(cx);
1007    }
1008
1009    #[gpui::test]
1010    fn the_innermost_area_takes_the_whole_gesture(cx: &mut TestAppContext) {
1011        let (areas, cx) = nested(cx, true);
1012        let inner_origin = areas.inner.bounds().origin.y;
1013        scroll_at(cx, 150., 0., TouchPhase::Started);
1014        scroll_at(cx, 150., -200., TouchPhase::Moved);
1015        assert_eq!(areas.inner.offset().y, px(-200.), "the inner area scrolls");
1016        assert_eq!(areas.outer.offset().y, px(0.), "the outer one does not");
1017        // At its end the inner area stretches instead of handing over.
1018        scroll_at(cx, 150., -200., TouchPhase::Moved);
1019        assert_eq!(areas.inner.offset().y, px(-300.));
1020        assert_eq!(areas.outer.offset().y, px(0.));
1021        assert!(areas.inner.bounds().origin.y < inner_origin);
1022        // Outside the inner area, the outer one scrolls.
1023        scroll_at(cx, 150., 0., TouchPhase::Ended);
1024        scroll_at(cx, 20., -50., TouchPhase::Moved);
1025        assert_eq!(areas.outer.offset().y, px(-50.));
1026    }
1027
1028    #[gpui::test]
1029    fn a_disabled_inner_area_still_keeps_its_scroll(cx: &mut TestAppContext) {
1030        let (areas, cx) = nested(cx, false);
1031        let inner_origin = areas.inner.bounds().origin.y;
1032        scroll_at(cx, 150., -50., TouchPhase::Moved);
1033        assert_eq!(areas.inner.offset().y, px(-50.), "the inner area scrolls");
1034        assert_eq!(areas.outer.offset().y, px(0.), "the outer one does not");
1035        // At its end it stops without stretching.
1036        scroll_at(cx, 150., -500., TouchPhase::Moved);
1037        assert_eq!(areas.inner.offset().y, px(-300.));
1038        assert_eq!(areas.inner.bounds().origin.y, inner_origin);
1039        assert_eq!(areas.outer.offset().y, px(0.));
1040    }
1041
1042    struct ListTest(gpui::ListState);
1043
1044    impl Render for ListTest {
1045        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1046            ScrollBounce::new(
1047                "bounce-list",
1048                &self.0,
1049                gpui::list(self.0.clone(), |_, _, _| {
1050                    div().h(px(40.)).into_any_element()
1051                })
1052                .w(px(200.))
1053                .h(px(200.)),
1054            )
1055            .enabled(true)
1056            .scroll_wheel(false)
1057        }
1058    }
1059
1060    #[gpui::test]
1061    fn list_reverse_drag_preserves_events_before_the_next_frame(cx: &mut TestAppContext) {
1062        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1063        let (_, cx) = cx.add_window_view({
1064            let handle = handle.clone();
1065            move |_, _| ListTest(handle)
1066        });
1067        draw(cx);
1068        scroll(cx, 100., TouchPhase::Started);
1069        scroll(cx, -140., TouchPhase::Moved);
1070        assert_eq!(handle.offset().y, px(-40.));
1071        scroll(cx, -10., TouchPhase::Moved);
1072        draw(cx);
1073        assert_eq!(handle.offset().y, px(-50.));
1074    }
1075
1076    #[gpui::test]
1077    fn trackpad_release_between_frames_does_not_bounce_in_the_middle(cx: &mut TestAppContext) {
1078        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1079        let (_, cx) = cx.add_window_view({
1080            let handle = handle.clone();
1081            move |_, _| ListTest(handle)
1082        });
1083        draw(cx);
1084        handle.set_offset(point(px(0.), px(-400.)));
1085        draw(cx);
1086        let origin = handle.viewport_bounds().origin.y;
1087        // Unlike simulate_event (which may draw after each event), dispatch
1088        // both packets within one update to exercise native input coalescing.
1089        cx.update(|window, cx| {
1090            for (delta, phase) in [(-30., TouchPhase::Started), (0., TouchPhase::Ended)] {
1091                window.dispatch_event(
1092                    gpui::PlatformInput::Scroll(ScrollEvent {
1093                        position: point(px(100.), px(100.)),
1094                        delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1095                        touch_phase: phase,
1096                        ..Default::default()
1097                    }),
1098                    cx,
1099                );
1100            }
1101        });
1102        draw(cx);
1103        assert_eq!(handle.viewport_bounds().origin.y, origin);
1104        assert!(handle.offset().y < px(-300.) && handle.offset().y > px(-500.));
1105    }
1106
1107    #[gpui::test]
1108    fn trackpad_direction_change_between_frames_does_not_bounce_in_the_middle(
1109        cx: &mut TestAppContext,
1110    ) {
1111        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1112        let (_, cx) = cx.add_window_view({
1113            let handle = handle.clone();
1114            move |_, _| ListTest(handle)
1115        });
1116        draw(cx);
1117        handle.set_offset(point(px(0.), px(-400.)));
1118        draw(cx);
1119        let origin = handle.viewport_bounds().origin.y;
1120        cx.update(|window, cx| {
1121            for (delta, phase) in [(-30., TouchPhase::Started), (5., TouchPhase::Moved)] {
1122                window.dispatch_event(
1123                    gpui::PlatformInput::Scroll(ScrollEvent {
1124                        position: point(px(100.), px(100.)),
1125                        delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1126                        touch_phase: phase,
1127                        ..Default::default()
1128                    }),
1129                    cx,
1130                );
1131            }
1132        });
1133        draw(cx);
1134        assert!(handle.offset().y < px(-300.) && handle.offset().y > px(-500.));
1135        assert_eq!(handle.viewport_bounds().origin.y, origin);
1136    }
1137
1138    #[gpui::test]
1139    fn list_stretches_only_the_distance_past_either_edge(cx: &mut TestAppContext) {
1140        for (start, delta, end) in [(-30., 50., 0.), (-970., -50., -1000.)] {
1141            let mut app = cx.new_app();
1142            let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1143            let (_, cx) = app.add_window_view({
1144                let handle = handle.clone();
1145                move |_, _| ListTest(handle)
1146            });
1147            draw(cx);
1148            handle.set_offset(point(px(0.), px(start)));
1149            draw(cx);
1150            let origin = handle.viewport_bounds().origin.y;
1151            scroll(cx, delta, TouchPhase::Started);
1152            draw(cx);
1153            assert_eq!(handle.offset().y, px(end));
1154            let stretch = (handle.viewport_bounds().origin.y - origin).as_f32();
1155            assert_eq!(stretch.signum(), delta.signum());
1156            // Of the 50 px input, 30 px is ordinary scrolling. Only the
1157            // remaining 20 px may be rubber-banded (resistance reduces it).
1158            assert!(stretch.abs() > 0. && stretch.abs() < 20.);
1159        }
1160    }
1161
1162    #[gpui::test]
1163    fn reverse_drag_consumes_stretch_before_scrolling_content(cx: &mut TestAppContext) {
1164        let handle = ScrollHandle::new();
1165        let (_, cx) = cx.add_window_view({
1166            let handle = handle.clone();
1167            move |_, _| ScrollTest {
1168                handle,
1169                enabled: true,
1170            }
1171        });
1172        draw(cx);
1173        let origin = handle.bounds().origin.y;
1174        assert_eq!(origin, px(20.));
1175        scroll(cx, 100., TouchPhase::Started);
1176        draw(cx);
1177        assert_eq!(handle.offset().y, px(0.));
1178        assert!(handle.bounds().origin.y > origin);
1179        scroll(cx, -140., TouchPhase::Moved);
1180        draw(cx);
1181        assert_eq!(handle.offset().y, px(-40.));
1182        assert_eq!(handle.bounds().origin.y, origin);
1183    }
1184
1185    #[gpui::test]
1186    fn touch_release_ignores_momentum_until_a_new_touch_takes_over(cx: &mut TestAppContext) {
1187        let handle = ScrollHandle::new();
1188        let (_, cx) = cx.add_window_view({
1189            let handle = handle.clone();
1190            move |_, _| ScrollTest {
1191                handle,
1192                enabled: true,
1193            }
1194        });
1195        draw(cx);
1196        let origin = handle.bounds().origin.y;
1197        scroll(cx, 100., TouchPhase::Started);
1198        draw(cx);
1199        assert!(handle.bounds().origin.y > origin);
1200        scroll(cx, 0., TouchPhase::Ended);
1201        draw(cx);
1202        let released = handle.bounds().origin.y;
1203        // The iOS backend emits Moved packets for momentum after finger-up.
1204        // Even a large inward packet must not move the logical list while
1205        // the returning edge owns this gesture.
1206        scroll(cx, -400., TouchPhase::Moved);
1207        draw(cx);
1208        assert_eq!(handle.offset().y, px(0.));
1209        assert!(handle.bounds().origin.y <= released);
1210        // A new finger-down must end suppression and take over immediately.
1211        scroll(cx, 0., TouchPhase::Started);
1212        scroll(cx, -250., TouchPhase::Moved);
1213        draw(cx);
1214        assert!(handle.offset().y < px(0.));
1215        assert_eq!(handle.bounds().origin.y, origin);
1216    }
1217
1218    #[gpui::test]
1219    fn phaseless_wheel_scrolls_back_right_after_bouncing(cx: &mut TestAppContext) {
1220        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1221        let (_, cx) = cx.add_window_view({
1222            let handle = handle.clone();
1223            move |_, _| ListTest(handle)
1224        });
1225        draw(cx);
1226        handle.set_offset(point(px(0.), px(-1000.)));
1227        draw(cx);
1228        let origin = handle.viewport_bounds().origin.y;
1229        // Smooth-scrolling mouse drivers on macOS: precise deltas, no phase.
1230        scroll(cx, -50., TouchPhase::Moved);
1231        draw(cx);
1232        assert!(handle.viewport_bounds().origin.y < origin);
1233        scroll(cx, 200., TouchPhase::Moved);
1234        draw(cx);
1235        assert!(handle.offset().y > px(-1000.));
1236        assert_eq!(handle.viewport_bounds().origin.y, origin);
1237    }
1238
1239    #[gpui::test]
1240    fn phaseless_wheel_bounces_again_only_after_a_pause(cx: &mut TestAppContext) {
1241        let handle = ScrollHandle::new();
1242        let (_, cx) = cx.add_window_view({
1243            let handle = handle.clone();
1244            move |_, _| ScrollTest {
1245                handle,
1246                enabled: true,
1247            }
1248        });
1249        draw(cx);
1250        scroll(cx, 50., TouchPhase::Moved);
1251        draw(cx);
1252        let bounced = handle.bounds().origin.y;
1253        // Momentum after an edge hit keeps pushing outward; it must not
1254        // stretch further.
1255        scroll(cx, 50., TouchPhase::Moved);
1256        draw(cx);
1257        assert!(handle.bounds().origin.y <= bounced);
1258        cx.executor().advance_clock(MOMENTUM_GAP);
1259        scroll(cx, 50., TouchPhase::Moved);
1260        draw(cx);
1261        assert!(handle.bounds().origin.y > bounced);
1262        assert_eq!(handle.offset().y, px(0.));
1263    }
1264
1265    #[gpui::test]
1266    fn tiny_drag_catching_momentum_does_not_start_a_reverse_fling(cx: &mut TestAppContext) {
1267        let handle = ScrollHandle::new();
1268        let (_, cx) = cx.add_window_view({
1269            let handle = handle.clone();
1270            move |_, _| ScrollTest {
1271                handle,
1272                enabled: true,
1273            }
1274        });
1275        draw(cx);
1276        handle.set_offset(point(px(0.), px(-200.)));
1277        draw(cx);
1278
1279        // GPUI ends the old momentum stream, then starts a drag at zero
1280        // displacement when a finger catches the moving content.
1281        scroll(cx, -60., TouchPhase::Started);
1282        scroll(cx, 0., TouchPhase::Ended);
1283        draw(cx);
1284        scroll(cx, -100., TouchPhase::Moved);
1285        draw(cx);
1286        scroll(cx, 0., TouchPhase::Ended);
1287        draw(cx);
1288        let before_catch = handle.offset().y;
1289        assert!(before_catch < px(0.));
1290        scroll(cx, 0., TouchPhase::Started);
1291        scroll(cx, 8., TouchPhase::Moved);
1292        scroll(cx, 0., TouchPhase::Ended);
1293        draw(cx);
1294        let stopped = handle.offset().y;
1295        assert_eq!(stopped, before_catch + px(8.));
1296
1297        // The recognizer can synthesize a large reverse momentum packet from
1298        // that 8 px movement. It must not move the logical viewport.
1299        scroll(cx, 100., TouchPhase::Moved);
1300        draw(cx);
1301        assert_eq!(handle.offset().y, stopped);
1302
1303        // A fresh gesture restores ordinary scrolling and momentum.
1304        scroll(cx, -20., TouchPhase::Started);
1305        scroll(cx, 0., TouchPhase::Ended);
1306        scroll(cx, -10., TouchPhase::Moved);
1307        draw(cx);
1308        assert_eq!(handle.offset().y, stopped - px(30.));
1309    }
1310
1311    #[gpui::test]
1312    fn deliberate_drag_after_catching_momentum_can_fling(cx: &mut TestAppContext) {
1313        let handle = ScrollHandle::new();
1314        let (_, cx) = cx.add_window_view({
1315            let handle = handle.clone();
1316            move |_, _| ScrollTest {
1317                handle,
1318                enabled: true,
1319            }
1320        });
1321        draw(cx);
1322        handle.set_offset(point(px(0.), px(-200.)));
1323        draw(cx);
1324
1325        scroll(cx, 0., TouchPhase::Started);
1326        scroll(cx, 24., TouchPhase::Moved);
1327        scroll(cx, 0., TouchPhase::Ended);
1328        draw(cx);
1329        assert_eq!(handle.offset().y, px(-176.));
1330        scroll(cx, 40., TouchPhase::Moved);
1331        draw(cx);
1332        assert_eq!(handle.offset().y, px(-136.));
1333    }
1334
1335    #[gpui::test]
1336    fn short_catch_release_still_stretches_past_the_edge(cx: &mut TestAppContext) {
1337        let handle = ScrollHandle::new();
1338        let (_, cx) = cx.add_window_view({
1339            let handle = handle.clone();
1340            move |_, _| ScrollTest {
1341                handle,
1342                enabled: true,
1343            }
1344        });
1345        draw(cx);
1346        handle.set_offset(point(px(0.), px(-4.)));
1347        draw(cx);
1348        let origin = handle.bounds().origin.y;
1349
1350        scroll(cx, 0., TouchPhase::Started);
1351        scroll(cx, 8., TouchPhase::Ended);
1352        draw(cx);
1353        assert_eq!(handle.offset().y, px(0.));
1354        assert!(handle.bounds().origin.y > origin);
1355    }
1356
1357    #[gpui::test]
1358    fn disabled_and_reduced_motion_leave_the_viewport_fixed(cx: &mut TestAppContext) {
1359        for enabled in [false, true] {
1360            let mut app = cx.new_app();
1361            if enabled {
1362                app.update(|cx| cx.set_reduce_motion(true));
1363            }
1364            let handle = ScrollHandle::new();
1365            let (_, cx) = app.add_window_view({
1366                let handle = handle.clone();
1367                move |_, _| ScrollTest { handle, enabled }
1368            });
1369            draw(cx);
1370            let origin = handle.bounds().origin.y;
1371            scroll(cx, 100., TouchPhase::Started);
1372            draw(cx);
1373            assert_eq!(handle.bounds().origin.y, origin);
1374            scroll(cx, -40., TouchPhase::Moved);
1375            draw(cx);
1376            assert_eq!(handle.offset().y, px(-40.));
1377        }
1378    }
1379
1380    #[test]
1381    fn resistance_and_reverse_preserve_unconsumed_distance() {
1382        let mut scroll = Physics::default();
1383        scroll.begin(600.);
1384        assert_eq!(scroll.pull(100.), 0.);
1385        assert!(scroll.offset() > 0. && scroll.offset() < 55.);
1386        assert_eq!(scroll.pull(-130.), -30.);
1387        assert_eq!(scroll.offset(), 0.);
1388    }
1389
1390    #[gpui::test]
1391    fn diagonal_wobble_stays_with_the_stretch(cx: &mut TestAppContext) {
1392        let handle = ScrollHandle::new();
1393        let (_, cx) = cx.add_window_view({
1394            let handle = handle.clone();
1395            move |_, _| ScrollTest {
1396                handle,
1397                enabled: true,
1398            }
1399        });
1400        draw(cx);
1401        let origin = handle.bounds().origin.y;
1402        scroll(cx, 100., TouchPhase::Started);
1403        draw(cx);
1404        let stretched = handle.bounds().origin.y;
1405        assert!(stretched > origin);
1406        // A trackpad swipe that started vertical wobbles horizontal-dominant
1407        // for a packet. Dispatch within one update so the packets stay within
1408        // the axis lock's gesture separation.
1409        cx.update(|window, cx| {
1410            for delta in [point(px(30.), px(-20.)), point(px(0.), px(-20.))] {
1411                window.dispatch_event(
1412                    gpui::PlatformInput::Scroll(ScrollEvent {
1413                        position: point(px(100.), px(100.)),
1414                        delta: ScrollDelta::Pixels(delta),
1415                        touch_phase: TouchPhase::Moved,
1416                        ..Default::default()
1417                    }),
1418                    cx,
1419                );
1420            }
1421        });
1422        draw(cx);
1423        // Both packets shrink the stretch; neither scrolls the list.
1424        assert!(handle.bounds().origin.y < stretched);
1425        assert!(handle.bounds().origin.y > origin);
1426        assert_eq!(handle.offset(), point(px(0.), px(0.)));
1427    }
1428
1429    #[test]
1430    fn motion_builder_configures_tracking_and_response() {
1431        let motion = ScrollBounceMotion::default()
1432            .with_tracking(0.4)
1433            .with_response(Duration::from_millis(300))
1434            .with_max_stretch(24.);
1435        assert_eq!(motion.tracking(), 0.4);
1436        assert_eq!(motion.response(), Duration::from_millis(300));
1437        assert_eq!(motion.max_stretch(), Some(24.));
1438    }
1439
1440    #[test]
1441    fn tracking_scales_the_first_stretch() {
1442        let stretch = |tracking: f32| {
1443            let mut scroll = Physics {
1444                motion: ScrollBounceMotion::default().with_tracking(tracking),
1445                ..Physics::default()
1446            };
1447            scroll.begin(600.);
1448            scroll.pull(100.);
1449            scroll.offset()
1450        };
1451        assert!(stretch(0.3) < stretch(0.55));
1452        assert!(stretch(0.55) < stretch(0.8));
1453    }
1454
1455    #[test]
1456    fn response_scales_the_return_and_zero_snaps() {
1457        let remaining = |response: Duration| {
1458            let mut scroll = Physics {
1459                motion: ScrollBounceMotion::default().with_response(response),
1460                ..Physics::default()
1461            };
1462            scroll.begin(600.);
1463            scroll.pull(180.);
1464            scroll.release();
1465            scroll.step(0.25);
1466            scroll.offset()
1467        };
1468        assert!(remaining(Duration::from_secs(1)) > remaining(Duration::from_millis(524)));
1469        assert!(remaining(Duration::from_millis(524)) > remaining(Duration::from_millis(200)));
1470        assert_eq!(remaining(Duration::ZERO), 0.);
1471    }
1472
1473    #[test]
1474    fn regrabbing_a_displaced_edge_keeps_its_extent() {
1475        let mut scroll = Physics::default();
1476        scroll.begin(600.);
1477        scroll.pull(-150.);
1478        scroll.release();
1479        scroll.step(0.08);
1480        let before = scroll.offset();
1481        // The viewport shrank below the displacement while the edge was
1482        // returning. The finger still lands on the edge where it is.
1483        scroll.begin(40.);
1484        assert!((scroll.offset() - before).abs() < 0.001);
1485        // And a short pull inward moves the edge right away.
1486        scroll.pull(10.);
1487        assert!(scroll.offset() > before);
1488        assert!(scroll.offset() < before + 10.);
1489    }
1490
1491    #[test]
1492    fn a_gesture_from_rest_adopts_the_current_extent() {
1493        let mut scroll = Physics::default();
1494        scroll.begin(600.);
1495        scroll.begin(40.);
1496        scroll.pull(-100.);
1497        // The stretch saturates below the 40 px viewport, not the 600 px one.
1498        assert!(scroll.offset() > -40.);
1499    }
1500
1501    #[test]
1502    fn grabbing_the_spring_does_not_jump() {
1503        let mut scroll = Physics::default();
1504        scroll.begin(600.);
1505        scroll.pull(-150.);
1506        scroll.release();
1507        scroll.step(0.08);
1508        let before = scroll.offset();
1509        scroll.begin(600.);
1510        assert!((scroll.offset() - before).abs() < 0.001);
1511        let held = scroll.offset();
1512        assert!(!scroll.step(0.1));
1513        assert_eq!(scroll.offset(), held);
1514    }
1515
1516    #[test]
1517    fn spring_has_the_same_trajectory_at_60_and_120_hz() {
1518        let at = |hz: usize| {
1519            let mut scroll = Physics::default();
1520            scroll.begin(600.);
1521            scroll.pull(180.);
1522            scroll.release();
1523            for _ in 0..hz / 4 {
1524                scroll.step(1. / hz as f32);
1525            }
1526            scroll.offset()
1527        };
1528        assert!((at(60) - at(120)).abs() < 0.001);
1529    }
1530
1531    #[test]
1532    fn return_keeps_a_visible_tail_after_a_quarter_second() {
1533        let mut scroll = Physics {
1534            position: 100.,
1535            ..Physics::default()
1536        };
1537        assert!(scroll.step(0.25));
1538        // A 100 px release should still have a visible, decelerating tail
1539        // after 250 ms instead of snapping almost completely back by then.
1540        assert!(scroll.offset() > 10. && scroll.offset() < 30.);
1541        assert!(scroll.velocity < 0.);
1542    }
1543
1544    #[test]
1545    fn spring_settles_without_crossing_the_boundary() {
1546        let mut scroll = Physics::default();
1547        scroll.begin(600.);
1548        scroll.pull(-200.);
1549        scroll.release();
1550        let mut previous = scroll.offset();
1551        for _ in 0..120 {
1552            scroll.step(1. / 120.);
1553            assert!(scroll.offset() >= previous && scroll.offset() <= 0.);
1554            previous = scroll.offset();
1555        }
1556        assert_eq!(scroll.offset(), 0.);
1557        assert!(scroll.suppress_momentum);
1558        scroll.begin(600.);
1559        assert!(!scroll.suppress_momentum);
1560    }
1561}