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
285impl Element for ScrollBounce {
286    type RequestLayoutState = ();
287    type PrepaintState = ScrollBouncePrepaintState;
288
289    fn id(&self) -> Option<ElementId> {
290        Some(self.id.clone())
291    }
292    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
293        None
294    }
295
296    fn request_layout(
297        &mut self,
298        _: Option<&GlobalElementId>,
299        _: Option<&InspectorElementId>,
300        window: &mut Window,
301        cx: &mut App,
302    ) -> (LayoutId, ()) {
303        (self.child.request_layout(window, cx), ())
304    }
305
306    fn prepaint(
307        &mut self,
308        id: Option<&GlobalElementId>,
309        _: Option<&InspectorElementId>,
310        bounds: Bounds<Pixels>,
311        _: &mut (),
312        window: &mut Window,
313        cx: &mut App,
314    ) -> Self::PrepaintState {
315        let state = window.with_element_state(
316            id.expect("ScrollBounce has an id"),
317            |state: Option<Rc<RefCell<State>>>, _| {
318                let state = state.unwrap_or_default();
319                (state.clone(), state)
320            },
321        );
322        let offset = {
323            let mut state = state.borrow_mut();
324            if !self.enabled || cx.reduce_motion() {
325                *state = State::default();
326            }
327            if self.scroll_wheel {
328                state.overscroll.set_motion(self.motion);
329                if max_scroll_extent(self.handle.as_ref()) <= px(0.) {
330                    state.overscroll.reset();
331                }
332                if state.overscroll.step(cx.background_executor().now()) {
333                    window.request_animation_frame();
334                }
335                state.overscroll.offset()
336            } else {
337                state.physics.motion = self.motion;
338                let now = Instant::now();
339                let elapsed = state
340                    .sampled_at
341                    .replace(now)
342                    .map_or(0., |at| now.duration_since(at).as_secs_f32());
343                if state.physics.step(elapsed) {
344                    window.request_animation_frame();
345                }
346                state.physics.offset()
347            }
348        };
349        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
350        window.with_content_mask(Some(ContentMask { bounds }), |window| {
351            window.with_element_offset(point(px(0.), px(offset)), |window| {
352                self.child.prepaint(window, cx);
353            });
354        });
355        // The child's fresh metrics can remove overflow during a drag.
356        // Reset against those metrics as well, and repaint any displaced frame.
357        if self.scroll_wheel && max_scroll_extent(self.handle.as_ref()) <= px(0.) {
358            let mut state = state.borrow_mut();
359            let displaced = state.overscroll.offset() != 0.;
360            state.overscroll.reset();
361            if displaced {
362                window.request_animation_frame();
363            }
364        }
365        ScrollBouncePrepaintState { state, hitbox }
366    }
367
368    fn paint(
369        &mut self,
370        _: Option<&GlobalElementId>,
371        _: Option<&InspectorElementId>,
372        bounds: Bounds<Pixels>,
373        _: &mut (),
374        prepaint: &mut Self::PrepaintState,
375        window: &mut Window,
376        cx: &mut App,
377    ) {
378        if self.scroll_wheel {
379            let hitbox = prepaint.hitbox.id;
380            let handle = self.handle.clone();
381            window.on_mouse_event(move |_: &ScrollEvent, phase, window, cx| {
382                if phase == DispatchPhase::Capture
383                    && hitbox.should_handle_scroll(window)
384                    && max_scroll_extent(handle.as_ref()) > px(0.)
385                {
386                    claim_scroll(hitbox, cx);
387                }
388            });
389        }
390        if self.enabled && !self.scroll_wheel && !cx.reduce_motion() {
391            let state = prepaint.state.clone();
392            let hitbox = prepaint.hitbox.id;
393            let handle = self.handle.clone();
394            let view = window.current_view();
395            let on_scroll = self.on_scroll.clone();
396            let mut before = 0.;
397            let mut allow_end_bounce = false;
398            window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
399                let ScrollDelta::Pixels(mut delta) = event.delta else {
400                    if phase == DispatchPhase::Capture && hitbox.should_handle_scroll(window) {
401                        let mut state = state.borrow_mut();
402                        let displaced = state.physics.offset() != 0.;
403                        *state = State::default();
404                        drop(state);
405                        if displaced {
406                            cx.notify(view);
407                        }
408                    }
409                    return;
410                };
411                if !hitbox.should_handle_scroll(window) {
412                    return;
413                }
414                let mut state = state.borrow_mut();
415                // Lock the gesture to the axis it started on, so a diagonal
416                // swipe cannot wobble out of the stretch from one packet to
417                // the next. Both dispatch phases see the same packet, and the
418                // lock gives both the same answer.
419                state
420                    .ongoing_scroll
421                    .lock_axis(&mut delta, event.touch_phase);
422                if delta.x.abs() > delta.y.abs() {
423                    return;
424                }
425                let ended = matches!(event.touch_phase, TouchPhase::Ended | TouchPhase::Cancelled);
426                let mut scrolled = false;
427                let mut changed = false;
428                if phase == DispatchPhase::Capture {
429                    before = handle.offset().y.as_f32();
430                    if event.touch_phase == TouchPhase::Started {
431                        state.short_drag_distance = (delta.y == px(0.)).then_some(0.);
432                        state.physics.begin(bounds.size.height.as_f32());
433                    } else if let Some(distance) = state.short_drag_distance.as_mut() {
434                        *distance += delta.y.as_f32().abs();
435                        if *distance > CATCH_DRAG_SLOP {
436                            state.short_drag_distance = None;
437                        }
438                    }
439                    let suppress_short_drag_momentum = if ended {
440                        state.short_drag_distance.take().is_some()
441                            && event.touch_phase == TouchPhase::Ended
442                    } else {
443                        false
444                    };
445                    // The current Ended packet may still cross an edge; only
446                    // momentum packets after it should be suppressed.
447                    allow_end_bounce = suppress_short_drag_momentum;
448                    let now = cx.background_executor().now();
449                    let paused = state
450                        .last_wheel_at
451                        .replace(now)
452                        .is_some_and(|at| now.saturating_duration_since(at) >= MOMENTUM_GAP);
453                    let reversed = state.suppressed_direction.is_some_and(|direction| {
454                        delta.y != px(0.) && delta.y.as_f32().signum() != direction
455                    });
456                    if paused || reversed {
457                        state.physics.suppress_momentum = false;
458                    }
459                    if state.physics.suppress_momentum {
460                        cx.stop_propagation();
461                        return;
462                    }
463                    if state.physics.offset() != 0. {
464                        // Outside a gesture (a phaseless wheel once suppression
465                        // lifts) a packet grabs the returning edge and lets it
466                        // go again, as it would at rest.
467                        let from_rest = !state.physics.dragging;
468                        if from_rest {
469                            state.physics.begin(bounds.size.height.as_f32());
470                        }
471                        let remainder = state.physics.pull(delta.y.as_f32());
472                        if remainder != 0. {
473                            let max = max_scroll_extent(handle.as_ref());
474                            let mut offset = handle.offset();
475                            offset.y = px(before + remainder).clamp(-max, px(0.));
476                            handle.set_offset(offset);
477                            scrolled = true;
478                        }
479                        if ended || from_rest {
480                            state.release(from_rest);
481                        }
482                        changed = true;
483                        cx.stop_propagation();
484                    } else if ended {
485                        state.physics.release();
486                    }
487                    if suppress_short_drag_momentum {
488                        state.physics.suppress_momentum = true;
489                        state.suppressed_direction = None;
490                    }
491                } else {
492                    // Div applies deltas immediately but clamps during its next
493                    // prepaint. Clamp here so that boundary deltas are not
494                    // mistaken for consumed scrolling (ListState clamps eagerly).
495                    let mut offset = handle.offset();
496                    let max = max_scroll_extent(handle.as_ref());
497                    let clamped = offset.y.clamp(-max, px(0.));
498                    if clamped != offset.y {
499                        offset.y = clamped;
500                        handle.set_offset(offset);
501                    }
502                    let after = offset.y.as_f32();
503                    let requested = delta.y.as_f32();
504                    // A List can coalesce several packets against one painted
505                    // scroll position. Their offset difference alone does not
506                    // prove overscroll, especially after direction changes or
507                    // a zero-delta Ended packet from a trackpad.
508                    let at_outward_edge = (requested > 0. && offset.y == px(0.))
509                        || (requested < 0. && offset.y == -max);
510                    let residual =
511                        (requested - (after - before)).clamp(requested.min(0.), requested.max(0.));
512                    if at_outward_edge
513                        && residual.abs() > 0.01
514                        && (!state.physics.suppress_momentum || allow_end_bounce)
515                    {
516                        let dragging = state.physics.dragging;
517                        if !dragging {
518                            state.physics.begin(bounds.size.height.as_f32());
519                        }
520                        state.physics.pull(residual);
521                        if !dragging || ended {
522                            state.release(!dragging);
523                        }
524                        changed = true;
525                    }
526                }
527                if changed {
528                    state.sampled_at = Some(Instant::now());
529                }
530                drop(state);
531                if changed {
532                    cx.notify(view);
533                }
534                if scrolled && let Some(handler) = &on_scroll {
535                    handler(window, cx);
536                }
537            });
538        }
539        window.with_content_mask(Some(ContentMask { bounds }), |window| {
540            self.child.paint(window, cx)
541        });
542        // After the children, so that the areas inside act first.
543        if self.scroll_wheel {
544            let bounces = self.enabled && !cx.reduce_motion();
545            let state = prepaint.state.clone();
546            let hitbox = prepaint.hitbox.id;
547            let handle = self.handle.clone();
548            let view = window.current_view();
549            let on_scroll = self.on_scroll.clone();
550            window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
551                if phase != DispatchPhase::Capture
552                    || !hitbox.should_handle_scroll(window)
553                    || !owns_scroll(hitbox, cx)
554                {
555                    return;
556                }
557                let mut delta = event.delta.pixel_delta(window.line_height());
558                let mut state = state.borrow_mut();
559                state
560                    .ongoing_scroll
561                    .lock_axis(&mut delta, event.touch_phase);
562                let max = max_scroll_extent(handle.as_ref());
563                if max <= px(0.) {
564                    state.overscroll.reset();
565                    return;
566                }
567                if delta.x.abs() > delta.y.abs() {
568                    state
569                        .overscroll
570                        .touch_phase(event.touch_phase, cx.background_executor().now());
571                    return;
572                }
573                let before = handle.offset();
574                let changed = if !bounces || matches!(event.delta, ScrollDelta::Lines(_)) {
575                    let displaced = state.overscroll.offset() != 0.;
576                    state.overscroll.reset();
577                    let mut offset = before;
578                    offset.y = (before.y + delta.y).clamp(-max, px(0.));
579                    handle.set_offset(offset);
580                    displaced
581                } else {
582                    state.overscroll.packet(
583                        delta.y.as_f32(),
584                        event.touch_phase,
585                        bounds.size.height.as_f32(),
586                        cx.background_executor().now(),
587                        |dy| {
588                            let before = handle.offset();
589                            let mut offset = before;
590                            let requested = before.y + px(dy);
591                            offset.y = requested.clamp(-max, px(0.));
592                            handle.set_offset(offset);
593                            // Only clamping leaves unused input; subtraction
594                            // can leave a rounding residue inside the list.
595                            if offset.y == requested {
596                                dy
597                            } else {
598                                (offset.y - before.y).as_f32()
599                            }
600                        },
601                    )
602                };
603                let scrolled = handle.offset() != before;
604                drop(state);
605                cx.stop_propagation();
606                if changed || scrolled {
607                    cx.notify(view);
608                }
609                if scrolled && let Some(handler) = &on_scroll {
610                    handler(window, cx);
611                }
612            });
613        }
614    }
615}
616
617/// The largest outward speed, at most `speed`, that lets an edge at
618/// `position` go no farther out than `max`.
619///
620/// The edge then follows `(position + speed * t) * e^(-ωt)`, which peaks at
621/// `speed / ω * e^(ω * position / speed - 1)` when the speed is enough to
622/// carry it outward at all.
623fn limit_throw(position: f32, speed: f32, omega: f32, max: f32) -> f32 {
624    let peak = |speed: f32| {
625        if speed <= omega * position {
626            position
627        } else {
628            speed / omega * (omega * position / speed - 1.).exp()
629        }
630    };
631    if peak(speed) <= max {
632        return speed;
633    }
634    let (mut low, mut high) = (0., speed);
635    for _ in 0..24 {
636        let mid = (low + high) / 2.;
637        if peak(mid) <= max {
638            low = mid;
639        } else {
640            high = mid;
641        }
642    }
643    low
644}
645
646/// The stretch past an edge and its return, shared with the input's own
647/// scrolling.
648#[derive(Default)]
649pub(crate) struct Physics {
650    position: f32,
651    velocity: f32,
652    dragging: bool,
653    suppress_momentum: bool,
654    extent: f32,
655    motion: ScrollBounceMotion,
656}
657
658impl Physics {
659    pub(crate) fn set_motion(&mut self, motion: ScrollBounceMotion) {
660        self.motion = motion;
661    }
662
663    pub(crate) fn reset(&mut self) {
664        *self = Self {
665            motion: self.motion,
666            ..Self::default()
667        };
668    }
669    pub(crate) fn is_dragging(&self) -> bool {
670        self.dragging
671    }
672
673    /// Whether a released edge is still on its way.
674    pub(crate) fn is_moving(&self) -> bool {
675        !self.dragging && (self.position != 0. || self.velocity != 0.)
676    }
677
678    pub(crate) fn offset(&self) -> f32 {
679        if self.dragging {
680            let d = self.extent.max(1.);
681            let tracking = self.motion.tracking;
682            let stretch = self.position * tracking / (1. + tracking * self.position.abs() / d);
683            match self.motion.max_stretch {
684                // Follows the stretch closely at first, then eases into the limit.
685                Some(max) => max * (stretch / max).tanh(),
686                None => stretch,
687            }
688        } else {
689            self.position
690        }
691    }
692
693    pub(crate) fn begin(&mut self, extent: f32) {
694        let offset = self.offset();
695        // A displaced edge keeps the extent it was stretched under. The
696        // rubber-band curve saturates at the extent, so re-reading a viewport
697        // that shrank mid-return (rotation, keyboard) could not place the
698        // finger where the edge is: it would snap, then need a long pull back.
699        if offset == 0. || self.extent <= 0. {
700            self.extent = extent.max(1.);
701        }
702        // Invert the curves so grabbing a returning edge is continuous.
703        let stretch = match self.motion.max_stretch {
704            Some(max) => max * (offset / max).clamp(-0.999, 0.999).atanh(),
705            None => offset,
706        };
707        let tracking = self.motion.tracking;
708        self.position = stretch / (tracking * (1. - stretch.abs() / self.extent).max(0.01));
709        self.velocity = 0.;
710        self.dragging = true;
711        self.suppress_momentum = false;
712    }
713
714    /// Apply finger displacement. Return the part that crosses back into the list.
715    pub(crate) fn pull(&mut self, delta: f32) -> f32 {
716        let previous = self.position;
717        let next = previous + delta;
718        if previous != 0. && previous.signum() != next.signum() {
719            self.position = 0.;
720            next
721        } else {
722            self.position = next;
723            0.
724        }
725    }
726
727    pub(crate) fn release(&mut self) {
728        self.position = self.offset();
729        self.dragging = false;
730        if self.position != 0. {
731            self.suppress_momentum = true;
732        }
733    }
734
735    /// Let go of the edge the way AppKit does: from wherever it is, it
736    /// returns at full speed, and it carries `velocity` outward on the way.
737    /// Its path is `(x + velocity * t) * e^(-ωt)`, so an edge at rest is
738    /// thrown out and back, and an edge let go while still being pushed
739    /// returns a little later. It never crosses the boundary: velocity
740    /// pointing back inward is dropped.
741    pub(crate) fn let_go(&mut self, velocity: f32) {
742        self.position = self.offset();
743        self.dragging = false;
744        let Some(omega) = self.motion.omega() else {
745            self.position = 0.;
746            self.velocity = 0.;
747            return;
748        };
749        let mut outward = if self.position * velocity >= 0. {
750            velocity
751        } else {
752            0.
753        };
754        if let Some(max) = self.motion.max_stretch {
755            outward =
756                outward.signum() * limit_throw(self.position.abs(), outward.abs(), omega, max);
757        }
758        self.velocity = outward - omega * self.position;
759    }
760
761    /// Exact critically damped spring integration, independent of refresh rate.
762    pub(crate) fn step(&mut self, seconds: f32) -> bool {
763        if self.dragging || (self.position == 0. && self.velocity == 0.) {
764            return false;
765        }
766        let Some(omega) = self.motion.omega() else {
767            self.position = 0.;
768            self.velocity = 0.;
769            return false;
770        };
771        let decay = (-omega * seconds).exp();
772        let c = self.velocity + omega * self.position;
773        self.position = (self.position + c * seconds) * decay;
774        self.velocity = (self.velocity - omega * c * seconds) * decay;
775        if self.position.abs() < 0.1 && self.velocity.abs() < 1. {
776            self.position = 0.;
777            self.velocity = 0.;
778            false
779        } else {
780            true
781        }
782    }
783}
784
785#[cfg(test)]
786mod tests {
787    use super::*;
788    use gpui::{
789        Context, InteractiveElement as _, ParentElement as _, Render, ScrollHandle,
790        StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext, div,
791    };
792
793    struct ScrollTest {
794        handle: ScrollHandle,
795        enabled: bool,
796    }
797
798    impl Render for ScrollTest {
799        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
800            div().p(px(20.)).child(
801                ScrollBounce::new(
802                    "bounce",
803                    &self.handle,
804                    div()
805                        .id("viewport")
806                        .w(px(200.))
807                        .h(px(200.))
808                        .overflow_y_scroll()
809                        .track_scroll(&self.handle)
810                        .child(div().h(px(600.)).w_full()),
811                )
812                .enabled(self.enabled)
813                .scroll_wheel(false),
814            )
815        }
816    }
817
818    fn draw(cx: &mut VisualTestContext) {
819        cx.update(|window, cx| window.draw(cx).clear(cx));
820    }
821
822    fn scroll(cx: &mut VisualTestContext, delta: f32, phase: TouchPhase) {
823        cx.simulate_event(ScrollEvent {
824            position: point(px(100.), px(100.)),
825            delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
826            touch_phase: phase,
827            ..Default::default()
828        });
829    }
830
831    struct WheelViewport(ScrollHandle, Pixels);
832
833    impl Render for WheelViewport {
834        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
835            ScrollBounce::new(
836                "wheel-bounce",
837                &self.0,
838                div()
839                    .id("wheel-viewport")
840                    .w(px(200.))
841                    .h(px(200.))
842                    .overflow_y_scroll()
843                    .track_scroll(&self.0)
844                    .child(div().h(self.1).w_full()),
845            )
846            .enabled(true)
847            .scroll_wheel(true)
848        }
849    }
850
851    #[gpui::test]
852    fn fractional_wheel_input_keeps_scrolling_deep_in_a_long_list(cx: &mut TestAppContext) {
853        for delta in [-0.09_f32, 0.09] {
854            let mut app = cx.new_app();
855            let handle = ScrollHandle::new();
856            let (_, cx) = app.add_window_view({
857                let handle = handle.clone();
858                move |_, _| WheelViewport(handle, px(2_000_000.))
859            });
860            draw(cx);
861            handle.set_offset(point(px(0.), px(-1_000_000.)));
862            draw(cx);
863            let origin = handle.bounds().origin;
864            scroll(cx, delta, TouchPhase::Started);
865            scroll(cx, delta.signum() * 20., TouchPhase::Moved);
866            scroll(cx, 0., TouchPhase::Ended);
867            cx.executor().advance_clock(Duration::from_millis(16));
868            draw(cx);
869            scroll(cx, delta, TouchPhase::Moved);
870            scroll(cx, 0., TouchPhase::Started);
871            scroll(cx, delta.signum() * 20., TouchPhase::Moved);
872            draw(cx);
873            // Here each 0.09px delta rounds to 0.0625px in the stored offset.
874            let expected = -1_000_000. + delta.signum() * 40.125;
875            assert!((handle.offset().y.as_f32() - expected).abs() < 0.001);
876            assert_eq!(handle.bounds().origin, origin);
877        }
878    }
879
880    #[gpui::test]
881    fn ordinary_mouse_wheel_keeps_the_shared_viewport_undisplaced(cx: &mut TestAppContext) {
882        let handle = ScrollHandle::new();
883        let (_, cx) = cx.add_window_view({
884            let handle = handle.clone();
885            move |_, _| WheelViewport(handle, px(600.))
886        });
887        draw(cx);
888        let origin = handle.bounds().origin;
889        cx.simulate_event(ScrollEvent {
890            position: point(px(100.), px(100.)),
891            delta: ScrollDelta::Lines(point(0., -100.)),
892            ..Default::default()
893        });
894        draw(cx);
895        cx.executor().advance_clock(Duration::from_millis(16));
896        draw(cx);
897        assert_eq!(handle.offset().y, -handle.max_offset().y);
898        assert_eq!(handle.bounds().origin, origin);
899    }
900
901    #[gpui::test]
902    fn wheel_scrolling_interrupts_the_shared_return(cx: &mut TestAppContext) {
903        let handle = ScrollHandle::new();
904        let (_, cx) = cx.add_window_view({
905            let handle = handle.clone();
906            move |_, _| WheelViewport(handle, px(600.))
907        });
908        draw(cx);
909        let wheel = |cx: &mut VisualTestContext, dy| {
910            cx.simulate_event(ScrollEvent {
911                position: point(px(100.), px(100.)),
912                delta: ScrollDelta::Lines(point(0., dy)),
913                ..Default::default()
914            });
915        };
916        scroll(cx, -1000., TouchPhase::Started);
917        scroll(cx, 0., TouchPhase::Ended);
918        draw(cx);
919        assert_eq!(handle.offset().y, -handle.max_offset().y);
920        cx.executor().advance_clock(Duration::from_millis(200));
921        draw(cx);
922        let end = handle.offset().y;
923        wheel(cx, 2.);
924        assert!(
925            handle.offset().y > end,
926            "the new wheel input scrolls before the next frame"
927        );
928        draw(cx);
929    }
930
931    /// A scroll area with a shorter one inside it, 100 px down.
932    struct Nested {
933        outer: ScrollHandle,
934        inner: ScrollHandle,
935        inner_enabled: bool,
936    }
937
938    impl Render for Nested {
939        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
940            ScrollBounce::new(
941                "outer",
942                &self.outer,
943                div()
944                    .id("outer-viewport")
945                    .w(px(200.))
946                    .h(px(300.))
947                    .overflow_y_scroll()
948                    .track_scroll(&self.outer)
949                    .child(div().h(px(100.)).w_full())
950                    .child(
951                        ScrollBounce::new(
952                            "inner",
953                            &self.inner,
954                            div()
955                                .id("inner-viewport")
956                                .w(px(200.))
957                                .h(px(100.))
958                                .overflow_y_scroll()
959                                .track_scroll(&self.inner)
960                                .child(div().h(px(400.)).w_full()),
961                        )
962                        .enabled(self.inner_enabled),
963                    )
964                    .child(div().h(px(600.)).w_full()),
965            )
966            .enabled(true)
967        }
968    }
969
970    fn nested(cx: &mut TestAppContext, inner_enabled: bool) -> (Nested, &mut VisualTestContext) {
971        let (outer, inner) = (ScrollHandle::new(), ScrollHandle::new());
972        let (_, cx) = cx.add_window_view({
973            let (outer, inner) = (outer.clone(), inner.clone());
974            move |_, _| Nested {
975                outer,
976                inner,
977                inner_enabled,
978            }
979        });
980        draw(cx);
981        (
982            Nested {
983                outer,
984                inner,
985                inner_enabled,
986            },
987            cx,
988        )
989    }
990
991    fn scroll_at(cx: &mut VisualTestContext, y: f32, delta: f32, phase: TouchPhase) {
992        cx.simulate_event(ScrollEvent {
993            position: point(px(100.), px(y)),
994            delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
995            touch_phase: phase,
996            ..Default::default()
997        });
998        draw(cx);
999    }
1000
1001    #[gpui::test]
1002    fn the_innermost_area_takes_the_whole_gesture(cx: &mut TestAppContext) {
1003        let (areas, cx) = nested(cx, true);
1004        let inner_origin = areas.inner.bounds().origin.y;
1005        scroll_at(cx, 150., 0., TouchPhase::Started);
1006        scroll_at(cx, 150., -200., TouchPhase::Moved);
1007        assert_eq!(areas.inner.offset().y, px(-200.), "the inner area scrolls");
1008        assert_eq!(areas.outer.offset().y, px(0.), "the outer one does not");
1009        // At its end the inner area stretches instead of handing over.
1010        scroll_at(cx, 150., -200., TouchPhase::Moved);
1011        assert_eq!(areas.inner.offset().y, px(-300.));
1012        assert_eq!(areas.outer.offset().y, px(0.));
1013        assert!(areas.inner.bounds().origin.y < inner_origin);
1014        // Outside the inner area, the outer one scrolls.
1015        scroll_at(cx, 150., 0., TouchPhase::Ended);
1016        scroll_at(cx, 20., -50., TouchPhase::Moved);
1017        assert_eq!(areas.outer.offset().y, px(-50.));
1018    }
1019
1020    #[gpui::test]
1021    fn a_disabled_inner_area_still_keeps_its_scroll(cx: &mut TestAppContext) {
1022        let (areas, cx) = nested(cx, false);
1023        let inner_origin = areas.inner.bounds().origin.y;
1024        scroll_at(cx, 150., -50., TouchPhase::Moved);
1025        assert_eq!(areas.inner.offset().y, px(-50.), "the inner area scrolls");
1026        assert_eq!(areas.outer.offset().y, px(0.), "the outer one does not");
1027        // At its end it stops without stretching.
1028        scroll_at(cx, 150., -500., TouchPhase::Moved);
1029        assert_eq!(areas.inner.offset().y, px(-300.));
1030        assert_eq!(areas.inner.bounds().origin.y, inner_origin);
1031        assert_eq!(areas.outer.offset().y, px(0.));
1032    }
1033
1034    struct ListTest(gpui::ListState);
1035
1036    impl Render for ListTest {
1037        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1038            ScrollBounce::new(
1039                "bounce-list",
1040                &self.0,
1041                gpui::list(self.0.clone(), |_, _, _| {
1042                    div().h(px(40.)).into_any_element()
1043                })
1044                .w(px(200.))
1045                .h(px(200.)),
1046            )
1047            .enabled(true)
1048            .scroll_wheel(false)
1049        }
1050    }
1051
1052    #[gpui::test]
1053    fn list_reverse_drag_preserves_events_before_the_next_frame(cx: &mut TestAppContext) {
1054        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1055        let (_, cx) = cx.add_window_view({
1056            let handle = handle.clone();
1057            move |_, _| ListTest(handle)
1058        });
1059        draw(cx);
1060        scroll(cx, 100., TouchPhase::Started);
1061        scroll(cx, -140., TouchPhase::Moved);
1062        assert_eq!(handle.offset().y, px(-40.));
1063        scroll(cx, -10., TouchPhase::Moved);
1064        draw(cx);
1065        assert_eq!(handle.offset().y, px(-50.));
1066    }
1067
1068    #[gpui::test]
1069    fn trackpad_release_between_frames_does_not_bounce_in_the_middle(cx: &mut TestAppContext) {
1070        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1071        let (_, cx) = cx.add_window_view({
1072            let handle = handle.clone();
1073            move |_, _| ListTest(handle)
1074        });
1075        draw(cx);
1076        handle.set_offset(point(px(0.), px(-400.)));
1077        draw(cx);
1078        let origin = handle.viewport_bounds().origin.y;
1079        // Unlike simulate_event (which may draw after each event), dispatch
1080        // both packets within one update to exercise native input coalescing.
1081        cx.update(|window, cx| {
1082            for (delta, phase) in [(-30., TouchPhase::Started), (0., TouchPhase::Ended)] {
1083                window.dispatch_event(
1084                    gpui::PlatformInput::Scroll(ScrollEvent {
1085                        position: point(px(100.), px(100.)),
1086                        delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1087                        touch_phase: phase,
1088                        ..Default::default()
1089                    }),
1090                    cx,
1091                );
1092            }
1093        });
1094        draw(cx);
1095        assert_eq!(handle.viewport_bounds().origin.y, origin);
1096        assert!(handle.offset().y < px(-300.) && handle.offset().y > px(-500.));
1097    }
1098
1099    #[gpui::test]
1100    fn trackpad_direction_change_between_frames_does_not_bounce_in_the_middle(
1101        cx: &mut TestAppContext,
1102    ) {
1103        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1104        let (_, cx) = cx.add_window_view({
1105            let handle = handle.clone();
1106            move |_, _| ListTest(handle)
1107        });
1108        draw(cx);
1109        handle.set_offset(point(px(0.), px(-400.)));
1110        draw(cx);
1111        let origin = handle.viewport_bounds().origin.y;
1112        cx.update(|window, cx| {
1113            for (delta, phase) in [(-30., TouchPhase::Started), (5., TouchPhase::Moved)] {
1114                window.dispatch_event(
1115                    gpui::PlatformInput::Scroll(ScrollEvent {
1116                        position: point(px(100.), px(100.)),
1117                        delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1118                        touch_phase: phase,
1119                        ..Default::default()
1120                    }),
1121                    cx,
1122                );
1123            }
1124        });
1125        draw(cx);
1126        assert!(handle.offset().y < px(-300.) && handle.offset().y > px(-500.));
1127        assert_eq!(handle.viewport_bounds().origin.y, origin);
1128    }
1129
1130    #[gpui::test]
1131    fn list_stretches_only_the_distance_past_either_edge(cx: &mut TestAppContext) {
1132        for (start, delta, end) in [(-30., 50., 0.), (-970., -50., -1000.)] {
1133            let mut app = cx.new_app();
1134            let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1135            let (_, cx) = app.add_window_view({
1136                let handle = handle.clone();
1137                move |_, _| ListTest(handle)
1138            });
1139            draw(cx);
1140            handle.set_offset(point(px(0.), px(start)));
1141            draw(cx);
1142            let origin = handle.viewport_bounds().origin.y;
1143            scroll(cx, delta, TouchPhase::Started);
1144            draw(cx);
1145            assert_eq!(handle.offset().y, px(end));
1146            let stretch = (handle.viewport_bounds().origin.y - origin).as_f32();
1147            assert_eq!(stretch.signum(), delta.signum());
1148            // Of the 50 px input, 30 px is ordinary scrolling. Only the
1149            // remaining 20 px may be rubber-banded (resistance reduces it).
1150            assert!(stretch.abs() > 0. && stretch.abs() < 20.);
1151        }
1152    }
1153
1154    #[gpui::test]
1155    fn reverse_drag_consumes_stretch_before_scrolling_content(cx: &mut TestAppContext) {
1156        let handle = ScrollHandle::new();
1157        let (_, cx) = cx.add_window_view({
1158            let handle = handle.clone();
1159            move |_, _| ScrollTest {
1160                handle,
1161                enabled: true,
1162            }
1163        });
1164        draw(cx);
1165        let origin = handle.bounds().origin.y;
1166        assert_eq!(origin, px(20.));
1167        scroll(cx, 100., TouchPhase::Started);
1168        draw(cx);
1169        assert_eq!(handle.offset().y, px(0.));
1170        assert!(handle.bounds().origin.y > origin);
1171        scroll(cx, -140., TouchPhase::Moved);
1172        draw(cx);
1173        assert_eq!(handle.offset().y, px(-40.));
1174        assert_eq!(handle.bounds().origin.y, origin);
1175    }
1176
1177    #[gpui::test]
1178    fn touch_release_ignores_momentum_until_a_new_touch_takes_over(cx: &mut TestAppContext) {
1179        let handle = ScrollHandle::new();
1180        let (_, cx) = cx.add_window_view({
1181            let handle = handle.clone();
1182            move |_, _| ScrollTest {
1183                handle,
1184                enabled: true,
1185            }
1186        });
1187        draw(cx);
1188        let origin = handle.bounds().origin.y;
1189        scroll(cx, 100., TouchPhase::Started);
1190        draw(cx);
1191        assert!(handle.bounds().origin.y > origin);
1192        scroll(cx, 0., TouchPhase::Ended);
1193        draw(cx);
1194        let released = handle.bounds().origin.y;
1195        // The iOS backend emits Moved packets for momentum after finger-up.
1196        // Even a large inward packet must not move the logical list while
1197        // the returning edge owns this gesture.
1198        scroll(cx, -400., TouchPhase::Moved);
1199        draw(cx);
1200        assert_eq!(handle.offset().y, px(0.));
1201        assert!(handle.bounds().origin.y <= released);
1202        // A new finger-down must end suppression and take over immediately.
1203        scroll(cx, 0., TouchPhase::Started);
1204        scroll(cx, -250., TouchPhase::Moved);
1205        draw(cx);
1206        assert!(handle.offset().y < px(0.));
1207        assert_eq!(handle.bounds().origin.y, origin);
1208    }
1209
1210    #[gpui::test]
1211    fn phaseless_wheel_scrolls_back_right_after_bouncing(cx: &mut TestAppContext) {
1212        let handle = gpui::ListState::new(30, gpui::ListAlignment::Top, px(0.)).measure_all();
1213        let (_, cx) = cx.add_window_view({
1214            let handle = handle.clone();
1215            move |_, _| ListTest(handle)
1216        });
1217        draw(cx);
1218        handle.set_offset(point(px(0.), px(-1000.)));
1219        draw(cx);
1220        let origin = handle.viewport_bounds().origin.y;
1221        // Smooth-scrolling mouse drivers on macOS: precise deltas, no phase.
1222        scroll(cx, -50., TouchPhase::Moved);
1223        draw(cx);
1224        assert!(handle.viewport_bounds().origin.y < origin);
1225        scroll(cx, 200., TouchPhase::Moved);
1226        draw(cx);
1227        assert!(handle.offset().y > px(-1000.));
1228        assert_eq!(handle.viewport_bounds().origin.y, origin);
1229    }
1230
1231    #[gpui::test]
1232    fn phaseless_wheel_bounces_again_only_after_a_pause(cx: &mut TestAppContext) {
1233        let handle = ScrollHandle::new();
1234        let (_, cx) = cx.add_window_view({
1235            let handle = handle.clone();
1236            move |_, _| ScrollTest {
1237                handle,
1238                enabled: true,
1239            }
1240        });
1241        draw(cx);
1242        scroll(cx, 50., TouchPhase::Moved);
1243        draw(cx);
1244        let bounced = handle.bounds().origin.y;
1245        // Momentum after an edge hit keeps pushing outward; it must not
1246        // stretch further.
1247        scroll(cx, 50., TouchPhase::Moved);
1248        draw(cx);
1249        assert!(handle.bounds().origin.y <= bounced);
1250        cx.executor().advance_clock(MOMENTUM_GAP);
1251        scroll(cx, 50., TouchPhase::Moved);
1252        draw(cx);
1253        assert!(handle.bounds().origin.y > bounced);
1254        assert_eq!(handle.offset().y, px(0.));
1255    }
1256
1257    #[gpui::test]
1258    fn tiny_drag_catching_momentum_does_not_start_a_reverse_fling(cx: &mut TestAppContext) {
1259        let handle = ScrollHandle::new();
1260        let (_, cx) = cx.add_window_view({
1261            let handle = handle.clone();
1262            move |_, _| ScrollTest {
1263                handle,
1264                enabled: true,
1265            }
1266        });
1267        draw(cx);
1268        handle.set_offset(point(px(0.), px(-200.)));
1269        draw(cx);
1270
1271        // GPUI ends the old momentum stream, then starts a drag at zero
1272        // displacement when a finger catches the moving content.
1273        scroll(cx, -60., TouchPhase::Started);
1274        scroll(cx, 0., TouchPhase::Ended);
1275        draw(cx);
1276        scroll(cx, -100., TouchPhase::Moved);
1277        draw(cx);
1278        scroll(cx, 0., TouchPhase::Ended);
1279        draw(cx);
1280        let before_catch = handle.offset().y;
1281        assert!(before_catch < px(0.));
1282        scroll(cx, 0., TouchPhase::Started);
1283        scroll(cx, 8., TouchPhase::Moved);
1284        scroll(cx, 0., TouchPhase::Ended);
1285        draw(cx);
1286        let stopped = handle.offset().y;
1287        assert_eq!(stopped, before_catch + px(8.));
1288
1289        // The recognizer can synthesize a large reverse momentum packet from
1290        // that 8 px movement. It must not move the logical viewport.
1291        scroll(cx, 100., TouchPhase::Moved);
1292        draw(cx);
1293        assert_eq!(handle.offset().y, stopped);
1294
1295        // A fresh gesture restores ordinary scrolling and momentum.
1296        scroll(cx, -20., TouchPhase::Started);
1297        scroll(cx, 0., TouchPhase::Ended);
1298        scroll(cx, -10., TouchPhase::Moved);
1299        draw(cx);
1300        assert_eq!(handle.offset().y, stopped - px(30.));
1301    }
1302
1303    #[gpui::test]
1304    fn deliberate_drag_after_catching_momentum_can_fling(cx: &mut TestAppContext) {
1305        let handle = ScrollHandle::new();
1306        let (_, cx) = cx.add_window_view({
1307            let handle = handle.clone();
1308            move |_, _| ScrollTest {
1309                handle,
1310                enabled: true,
1311            }
1312        });
1313        draw(cx);
1314        handle.set_offset(point(px(0.), px(-200.)));
1315        draw(cx);
1316
1317        scroll(cx, 0., TouchPhase::Started);
1318        scroll(cx, 24., TouchPhase::Moved);
1319        scroll(cx, 0., TouchPhase::Ended);
1320        draw(cx);
1321        assert_eq!(handle.offset().y, px(-176.));
1322        scroll(cx, 40., TouchPhase::Moved);
1323        draw(cx);
1324        assert_eq!(handle.offset().y, px(-136.));
1325    }
1326
1327    #[gpui::test]
1328    fn short_catch_release_still_stretches_past_the_edge(cx: &mut TestAppContext) {
1329        let handle = ScrollHandle::new();
1330        let (_, cx) = cx.add_window_view({
1331            let handle = handle.clone();
1332            move |_, _| ScrollTest {
1333                handle,
1334                enabled: true,
1335            }
1336        });
1337        draw(cx);
1338        handle.set_offset(point(px(0.), px(-4.)));
1339        draw(cx);
1340        let origin = handle.bounds().origin.y;
1341
1342        scroll(cx, 0., TouchPhase::Started);
1343        scroll(cx, 8., TouchPhase::Ended);
1344        draw(cx);
1345        assert_eq!(handle.offset().y, px(0.));
1346        assert!(handle.bounds().origin.y > origin);
1347    }
1348
1349    #[gpui::test]
1350    fn disabled_and_reduced_motion_leave_the_viewport_fixed(cx: &mut TestAppContext) {
1351        for enabled in [false, true] {
1352            let mut app = cx.new_app();
1353            if enabled {
1354                app.update(|cx| cx.set_reduce_motion(true));
1355            }
1356            let handle = ScrollHandle::new();
1357            let (_, cx) = app.add_window_view({
1358                let handle = handle.clone();
1359                move |_, _| ScrollTest { handle, enabled }
1360            });
1361            draw(cx);
1362            let origin = handle.bounds().origin.y;
1363            scroll(cx, 100., TouchPhase::Started);
1364            draw(cx);
1365            assert_eq!(handle.bounds().origin.y, origin);
1366            scroll(cx, -40., TouchPhase::Moved);
1367            draw(cx);
1368            assert_eq!(handle.offset().y, px(-40.));
1369        }
1370    }
1371
1372    #[test]
1373    fn resistance_and_reverse_preserve_unconsumed_distance() {
1374        let mut scroll = Physics::default();
1375        scroll.begin(600.);
1376        assert_eq!(scroll.pull(100.), 0.);
1377        assert!(scroll.offset() > 0. && scroll.offset() < 55.);
1378        assert_eq!(scroll.pull(-130.), -30.);
1379        assert_eq!(scroll.offset(), 0.);
1380    }
1381
1382    #[gpui::test]
1383    fn diagonal_wobble_stays_with_the_stretch(cx: &mut TestAppContext) {
1384        let handle = ScrollHandle::new();
1385        let (_, cx) = cx.add_window_view({
1386            let handle = handle.clone();
1387            move |_, _| ScrollTest {
1388                handle,
1389                enabled: true,
1390            }
1391        });
1392        draw(cx);
1393        let origin = handle.bounds().origin.y;
1394        scroll(cx, 100., TouchPhase::Started);
1395        draw(cx);
1396        let stretched = handle.bounds().origin.y;
1397        assert!(stretched > origin);
1398        // A trackpad swipe that started vertical wobbles horizontal-dominant
1399        // for a packet. Dispatch within one update so the packets stay within
1400        // the axis lock's gesture separation.
1401        cx.update(|window, cx| {
1402            for delta in [point(px(30.), px(-20.)), point(px(0.), px(-20.))] {
1403                window.dispatch_event(
1404                    gpui::PlatformInput::Scroll(ScrollEvent {
1405                        position: point(px(100.), px(100.)),
1406                        delta: ScrollDelta::Pixels(delta),
1407                        touch_phase: TouchPhase::Moved,
1408                        ..Default::default()
1409                    }),
1410                    cx,
1411                );
1412            }
1413        });
1414        draw(cx);
1415        // Both packets shrink the stretch; neither scrolls the list.
1416        assert!(handle.bounds().origin.y < stretched);
1417        assert!(handle.bounds().origin.y > origin);
1418        assert_eq!(handle.offset(), point(px(0.), px(0.)));
1419    }
1420
1421    #[test]
1422    fn motion_builder_configures_tracking_and_response() {
1423        let motion = ScrollBounceMotion::default()
1424            .with_tracking(0.4)
1425            .with_response(Duration::from_millis(300))
1426            .with_max_stretch(24.);
1427        assert_eq!(motion.tracking(), 0.4);
1428        assert_eq!(motion.response(), Duration::from_millis(300));
1429        assert_eq!(motion.max_stretch(), Some(24.));
1430    }
1431
1432    #[test]
1433    fn tracking_scales_the_first_stretch() {
1434        let stretch = |tracking: f32| {
1435            let mut scroll = Physics {
1436                motion: ScrollBounceMotion::default().with_tracking(tracking),
1437                ..Physics::default()
1438            };
1439            scroll.begin(600.);
1440            scroll.pull(100.);
1441            scroll.offset()
1442        };
1443        assert!(stretch(0.3) < stretch(0.55));
1444        assert!(stretch(0.55) < stretch(0.8));
1445    }
1446
1447    #[test]
1448    fn response_scales_the_return_and_zero_snaps() {
1449        let remaining = |response: Duration| {
1450            let mut scroll = Physics {
1451                motion: ScrollBounceMotion::default().with_response(response),
1452                ..Physics::default()
1453            };
1454            scroll.begin(600.);
1455            scroll.pull(180.);
1456            scroll.release();
1457            scroll.step(0.25);
1458            scroll.offset()
1459        };
1460        assert!(remaining(Duration::from_secs(1)) > remaining(Duration::from_millis(524)));
1461        assert!(remaining(Duration::from_millis(524)) > remaining(Duration::from_millis(200)));
1462        assert_eq!(remaining(Duration::ZERO), 0.);
1463    }
1464
1465    #[test]
1466    fn regrabbing_a_displaced_edge_keeps_its_extent() {
1467        let mut scroll = Physics::default();
1468        scroll.begin(600.);
1469        scroll.pull(-150.);
1470        scroll.release();
1471        scroll.step(0.08);
1472        let before = scroll.offset();
1473        // The viewport shrank below the displacement while the edge was
1474        // returning. The finger still lands on the edge where it is.
1475        scroll.begin(40.);
1476        assert!((scroll.offset() - before).abs() < 0.001);
1477        // And a short pull inward moves the edge right away.
1478        scroll.pull(10.);
1479        assert!(scroll.offset() > before);
1480        assert!(scroll.offset() < before + 10.);
1481    }
1482
1483    #[test]
1484    fn a_gesture_from_rest_adopts_the_current_extent() {
1485        let mut scroll = Physics::default();
1486        scroll.begin(600.);
1487        scroll.begin(40.);
1488        scroll.pull(-100.);
1489        // The stretch saturates below the 40 px viewport, not the 600 px one.
1490        assert!(scroll.offset() > -40.);
1491    }
1492
1493    #[test]
1494    fn grabbing_the_spring_does_not_jump() {
1495        let mut scroll = Physics::default();
1496        scroll.begin(600.);
1497        scroll.pull(-150.);
1498        scroll.release();
1499        scroll.step(0.08);
1500        let before = scroll.offset();
1501        scroll.begin(600.);
1502        assert!((scroll.offset() - before).abs() < 0.001);
1503        let held = scroll.offset();
1504        assert!(!scroll.step(0.1));
1505        assert_eq!(scroll.offset(), held);
1506    }
1507
1508    #[test]
1509    fn spring_has_the_same_trajectory_at_60_and_120_hz() {
1510        let at = |hz: usize| {
1511            let mut scroll = Physics::default();
1512            scroll.begin(600.);
1513            scroll.pull(180.);
1514            scroll.release();
1515            for _ in 0..hz / 4 {
1516                scroll.step(1. / hz as f32);
1517            }
1518            scroll.offset()
1519        };
1520        assert!((at(60) - at(120)).abs() < 0.001);
1521    }
1522
1523    #[test]
1524    fn return_keeps_a_visible_tail_after_a_quarter_second() {
1525        let mut scroll = Physics {
1526            position: 100.,
1527            ..Physics::default()
1528        };
1529        assert!(scroll.step(0.25));
1530        // A 100 px release should still have a visible, decelerating tail
1531        // after 250 ms instead of snapping almost completely back by then.
1532        assert!(scroll.offset() > 10. && scroll.offset() < 30.);
1533        assert!(scroll.velocity < 0.);
1534    }
1535
1536    #[test]
1537    fn spring_settles_without_crossing_the_boundary() {
1538        let mut scroll = Physics::default();
1539        scroll.begin(600.);
1540        scroll.pull(-200.);
1541        scroll.release();
1542        let mut previous = scroll.offset();
1543        for _ in 0..120 {
1544            scroll.step(1. / 120.);
1545            assert!(scroll.offset() >= previous && scroll.offset() <= 0.);
1546            previous = scroll.offset();
1547        }
1548        assert_eq!(scroll.offset(), 0.);
1549        assert!(scroll.suppress_momentum);
1550        scroll.begin(600.);
1551        assert!(!scroll.suppress_momentum);
1552    }
1553}