1use std::cell::Cell;
4
5use gpui_kit::{App, ScrollEvent, ScrollHandle, Window, point, px};
6
7pub fn scroll_chain_handler(
15 handle: &ScrollHandle,
16 horizontal: bool,
17) -> impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static {
18 let handle = handle.clone();
19 let previous = Cell::new(handle.offset());
20 move |event, window, cx| {
21 let max = handle.max_offset();
22 let min = point((-max.x).min(px(0.0)), (-max.y).min(px(0.0)));
23 let before = previous.get();
24 let before = point(
25 before.x.clamp(min.x, px(0.0)),
26 before.y.clamp(min.y, px(0.0)),
27 );
28 let raw = handle.offset();
29 let delta = event.delta.pixel_delta(window.line_height());
30 let next = if horizontal && event.modifiers.shift && delta.x == px(0.0) {
31 point((before.x + delta.y).clamp(min.x, px(0.0)), before.y)
32 } else {
33 point(raw.x.clamp(min.x, px(0.0)), raw.y.clamp(min.y, px(0.0)))
34 };
35 if next != raw {
36 handle.set_offset(next);
37 window.refresh();
38 }
39 previous.set(next);
40 if next != before {
41 cx.stop_propagation();
42 }
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49 use gpui_kit::test::TestWindowExt as _;
50 use gpui_kit::{
51 Context, IntoElement, ParentElement, Render, ScrollDelta, Styled, TestAppContext,
52 TouchPhase, div, prelude::*,
53 };
54
55 struct Host(ScrollHandle);
56 impl Render for Host {
57 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
58 div()
59 .id("scroll-test")
60 .w(px(120.0))
61 .h(px(120.0))
62 .overflow_scroll()
63 .track_scroll(&self.0)
64 .child(div().w(px(600.0)).h(px(600.0)).flex_none())
65 }
66 }
67
68 #[gpui_kit::test]
69 fn chain_clamps_overshoot_and_tracks_multiple_events_per_frame(cx: &mut TestAppContext) {
70 let handle = ScrollHandle::new();
71 let (_, window) = cx.add_window_view(|_, _| Host(handle.clone()));
72 window.update(|w, cx| {
73 w.render_frame(cx);
74 let callback = scroll_chain_handler(&handle, true);
75 let event = |dx, dy, shift| {
76 let modifiers = gpui_kit::Modifiers {
77 shift,
78 ..Default::default()
79 };
80 ScrollEvent {
81 position: point(px(10.0), px(10.0)),
82 delta: ScrollDelta::Pixels(point(px(dx), px(dy))),
83 modifiers,
84 touch_phase: TouchPhase::Moved,
85 source: Default::default(),
86 }
87 };
88 for dy in [-30.0, -10000.0, 20.0] {
90 let before = handle.offset();
91 handle.set_offset(point(before.x, before.y + px(dy)));
92 callback(&event(0.0, dy, false), w, cx);
93 assert!(handle.offset().y >= -handle.max_offset().y);
94 assert!(handle.offset().y <= px(0.0));
95 }
96 let before = handle.offset();
97 handle.set_offset(point(before.x, before.y - px(40.0)));
98 callback(&event(0.0, -40.0, true), w, cx);
99 assert_eq!(handle.offset().x, px(-40.0));
100 assert_eq!(
101 handle.offset().y,
102 before.y,
103 "Shift 横向滚动不能重复移动纵轴"
104 );
105 });
106 }
107}