1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3
4use instant::Instant;
5
6use gpui::{
7 App, Axis, BorderStyle, Bounds, ContentMask, Edges, Element, ElementId, GlobalElementId,
8 Hitbox, Hsla, InteractiveElement as _, IntoElement, IsZero as _, LayoutId, OngoingScroll,
9 PaintQuad, ParentElement as _, Point, Position, ScrollDelta, ScrollEvent, ScrollHandle,
10 StatefulInteractiveElement as _, Style, StyleRefinement, Styled as _, Window, div, px,
11 relative,
12};
13use gpui::{Corners, Pixels};
14
15use crate::{AxisExt, OngoingScrollExt as _, ScrollbarHandle, StyledExt as _};
16
17thread_local! {
18 static LAST_HORIZONTAL_SCROLL_CLAIM: Cell<Option<HorizontalScrollClaim>> =
19 const { Cell::new(None) };
20}
21
22const CLAIM_EPSILON: Pixels = px(0.5);
25
26#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct HorizontalScrollClaim {
29 at: Instant,
31 delta_x: Pixels,
34}
35
36impl HorizontalScrollClaim {
37 pub fn at(&self) -> Instant {
39 self.at
40 }
41
42 pub fn delta_x(&self) -> Pixels {
44 self.delta_x
45 }
46}
47
48pub fn last_horizontal_scroll_claim() -> Option<HorizontalScrollClaim> {
58 LAST_HORIZONTAL_SCROLL_CLAIM.get()
59}
60
61#[inline]
64#[track_caller]
65fn caller_id() -> ElementId {
66 ElementId::CodeLocation(*std::panic::Location::caller())
67}
68
69pub(crate) fn horizontal_scroll_area(
76 id: impl Into<ElementId>,
77 scroll_handle: &ScrollHandle,
78 style: &StyleRefinement,
79 child: impl IntoElement,
80) -> impl IntoElement {
81 let id = id.into();
82
83 let frame = RoundedFrameCover {
91 corner_radii: Corners {
92 top_left: style.corner_radii.top_left,
93 top_right: style.corner_radii.top_right,
94 bottom_left: style.corner_radii.bottom_left,
95 bottom_right: style.corner_radii.bottom_right,
96 },
97 backdrop: None,
98 frame_border: px(0.),
99 };
100
101 div()
102 .w_full()
103 .relative()
104 .child(
105 div()
106 .id(id.clone())
107 .w_full()
108 .refine_style(style)
109 .overflow_hidden()
110 .track_scroll(scroll_handle)
111 .child(child),
112 )
113 .child(ScrollableMask::new(Axis::Horizontal, scroll_handle).id(id))
114 .child(frame)
115}
116
117pub struct RoundedFrameCover {
132 corner_radii: Corners<Option<gpui::AbsoluteLength>>,
133 backdrop: Option<Hsla>,
134 frame_border: Pixels,
135}
136
137impl RoundedFrameCover {
138 pub fn uniform(radius: Pixels) -> Self {
140 let radius = Some(radius.into());
141 Self {
142 corner_radii: Corners {
143 top_left: radius,
144 top_right: radius,
145 bottom_left: radius,
146 bottom_right: radius,
147 },
148 backdrop: None,
149 frame_border: px(0.),
150 }
151 }
152
153 pub fn frame_border(mut self, width: Pixels) -> Self {
160 self.frame_border = width;
161 self
162 }
163
164 pub fn backdrop(mut self, color: Hsla) -> Self {
167 self.backdrop = Some(color);
168 self
169 }
170}
171
172#[cfg(not(feature = "gpui-fast"))]
173impl IntoElement for RoundedFrameCover {
174 type Element = Self;
175
176 fn into_element(self) -> Self::Element {
177 self
178 }
179}
180
181impl Element for RoundedFrameCover {
182 type RequestLayoutState = ();
183 type PrepaintState = Bounds<Pixels>;
184
185 fn id(&self) -> Option<ElementId> {
186 None
187 }
188
189 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
190 None
191 }
192
193 fn request_layout(
194 &mut self,
195 _: Option<&GlobalElementId>,
196 _: Option<&gpui::InspectorElementId>,
197 window: &mut Window,
198 cx: &mut App,
199 ) -> (LayoutId, Self::RequestLayoutState) {
200 let mut style = Style::default();
202 style.position = Position::Absolute;
203 style.flex_grow = 1.0;
204 style.flex_shrink = 1.0;
205 style.size.width = relative(1.).into();
206 style.size.height = relative(1.).into();
207
208 (window.request_layout(style, None, cx), ())
209 }
210
211 fn prepaint(
212 &mut self,
213 _: Option<&GlobalElementId>,
214 _: Option<&gpui::InspectorElementId>,
215 bounds: Bounds<Pixels>,
216 _: &mut Self::RequestLayoutState,
217 _: &mut Window,
218 _: &mut App,
219 ) -> Self::PrepaintState {
220 Bounds {
222 origin: Point {
223 x: bounds.origin.x,
224 y: bounds.origin.y - bounds.size.height,
225 },
226 size: bounds.size,
227 }
228 }
229
230 fn paint(
231 &mut self,
232 _: Option<&GlobalElementId>,
233 _: Option<&gpui::InspectorElementId>,
234 _: Bounds<Pixels>,
235 _: &mut Self::RequestLayoutState,
236 cover_bounds: &mut Self::PrepaintState,
237 window: &mut Window,
238 cx: &mut App,
239 ) {
240 use crate::theme::ActiveTheme as _;
241
242 let mut bounds = *cover_bounds;
243 if !self.frame_border.is_zero() {
244 bounds.origin.x -= self.frame_border;
245 bounds.origin.y -= self.frame_border;
246 bounds.size.width += self.frame_border * 2.;
247 bounds.size.height += self.frame_border * 2.;
248 }
249 let rem_size = window.rem_size();
250 let resolve = |corner: Option<gpui::AbsoluteLength>| {
251 corner
252 .map(|radius| radius.to_pixels(rem_size))
253 .filter(|radius| !radius.is_zero())
254 };
255 let radii = Corners {
256 top_left: resolve(self.corner_radii.top_left),
257 top_right: resolve(self.corner_radii.top_right),
258 bottom_left: resolve(self.corner_radii.bottom_left),
259 bottom_right: resolve(self.corner_radii.bottom_right),
260 };
261 if radii.top_left.is_none()
262 && radii.top_right.is_none()
263 && radii.bottom_left.is_none()
264 && radii.bottom_right.is_none()
265 {
266 return;
267 }
268
269 let backdrop = self.backdrop.unwrap_or(cx.theme().tokens.colors.background);
270 let corners = [
271 (bounds.origin, 1., 1., radii.top_left),
272 (bounds.top_right(), -1., 1., radii.top_right),
273 (bounds.bottom_right(), -1., -1., radii.bottom_right),
274 (
275 Point {
276 x: bounds.origin.x,
277 y: bounds.bottom_right().y,
278 },
279 1.,
280 -1.,
281 radii.bottom_left,
282 ),
283 ];
284 for (corner, x_dir, y_dir, radius) in corners {
285 let Some(radius) = radius else { continue };
286 if let Some(path) = corner_notch_path(corner, x_dir, y_dir, radius) {
287 window.paint_path(path, backdrop);
288 }
289 }
290 }
291}
292
293fn corner_notch_path(
297 corner: Point<Pixels>,
298 x_dir: f32,
299 y_dir: f32,
300 radius: Pixels,
301) -> Option<gpui::Path<Pixels>> {
302 let mut builder = gpui::PathBuilder::fill();
303 builder.move_to(corner);
304 builder.line_to(Point {
305 x: corner.x + radius * x_dir,
306 y: corner.y,
307 });
308 builder.arc_to(
309 Point {
310 x: radius,
311 y: radius,
312 },
313 px(0.),
314 false,
315 x_dir * y_dir < 0.,
318 Point {
319 x: corner.x,
320 y: corner.y + radius * y_dir,
321 },
322 );
323 builder.close();
324 builder.build().ok()
325}
326
327pub struct ScrollableMask<H: ScrollbarHandle + Clone = ScrollHandle> {
352 axis: Axis,
353 id: ElementId,
354 scroll_handle: H,
355 vertical_wheel: bool,
358 debug: Option<Hsla>,
359}
360
361impl<H: ScrollbarHandle + Clone> ScrollableMask<H> {
362 #[track_caller]
364 pub fn new(axis: Axis, scroll_handle: &H) -> Self {
365 Self {
366 scroll_handle: scroll_handle.clone(),
367 axis,
368 id: caller_id(),
369 vertical_wheel: false,
370 debug: None,
371 }
372 }
373
374 #[track_caller]
384 pub fn vertical_wheel(scroll_handle: &H) -> Self {
385 Self {
386 vertical_wheel: true,
387 ..Self::new(Axis::Horizontal, scroll_handle)
388 }
389 }
390
391 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
396 self.id = id.into();
397 self
398 }
399
400 #[allow(dead_code)]
402 pub fn debug(mut self) -> Self {
403 self.debug = Some(gpui::yellow());
404 self
405 }
406}
407
408#[cfg(not(feature = "gpui-fast"))]
409impl<H: ScrollbarHandle + Clone> IntoElement for ScrollableMask<H> {
410 type Element = Self;
411
412 fn into_element(self) -> Self::Element {
413 self
414 }
415}
416
417impl<H: ScrollbarHandle + Clone> Element for ScrollableMask<H> {
418 type RequestLayoutState = ();
419 type PrepaintState = Hitbox;
420
421 fn id(&self) -> Option<ElementId> {
424 let axis = match self.axis {
425 Axis::Horizontal => "horizontal",
426 Axis::Vertical => "vertical",
427 };
428
429 Some((self.id.clone(), axis).into())
430 }
431
432 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
433 None
434 }
435
436 fn request_layout(
437 &mut self,
438 _: Option<&GlobalElementId>,
439 _: Option<&gpui::InspectorElementId>,
440 window: &mut Window,
441 cx: &mut App,
442 ) -> (LayoutId, Self::RequestLayoutState) {
443 let mut style = Style::default();
444 style.position = Position::Absolute;
448 style.inset.top = px(0.).into();
449 style.inset.left = px(0.).into();
450 style.flex_grow = 1.0;
451 style.flex_shrink = 1.0;
452 style.size.width = relative(1.).into();
453 style.size.height = relative(1.).into();
454
455 (window.request_layout(style, None, cx), ())
456 }
457
458 fn prepaint(
459 &mut self,
460 _: Option<&GlobalElementId>,
461 _: Option<&gpui::InspectorElementId>,
462 bounds: Bounds<Pixels>,
463 _: &mut Self::RequestLayoutState,
464 window: &mut Window,
465 _: &mut App,
466 ) -> Self::PrepaintState {
467 window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal)
468 }
469
470 fn paint(
471 &mut self,
472 global_id: Option<&GlobalElementId>,
473 _: Option<&gpui::InspectorElementId>,
474 _: Bounds<Pixels>,
475 _: &mut Self::RequestLayoutState,
476 hitbox: &mut Self::PrepaintState,
477 window: &mut Window,
478 _: &mut App,
479 ) {
480 let is_horizontal = self.axis.is_horizontal();
481 let vertical_wheel = self.vertical_wheel;
482 let line_height = window.line_height();
483 let bounds = hitbox.bounds;
484 let ongoing_scroll = global_id
485 .map(|global_id| {
486 window.with_element_state::<Rc<RefCell<OngoingScroll>>, _>(global_id, |state, _| {
487 let state = state.unwrap_or_default();
488 (state.clone(), state)
489 })
490 })
491 .unwrap_or_default();
492
493 window.with_content_mask(Some(ContentMask { bounds }), |window| {
494 if let Some(color) = self.debug {
495 window.paint_quad(PaintQuad {
496 bounds,
497 border_widths: Edges::all(px(1.0)),
498 border_color: color,
499 background: gpui::transparent_white().into(),
500 corner_radii: Corners::all(px(0.)),
501 border_style: BorderStyle::default(),
502 });
503 }
504
505 window.on_mouse_event({
506 let view_id = window.current_view();
507 let scroll_handle = self.scroll_handle.clone();
508 let hitbox_id = hitbox.id;
509 let ongoing_scroll = ongoing_scroll.clone();
510
511 move |event: &ScrollEvent, phase, window, cx| {
512 if !(phase.capture() && hitbox_id.should_handle_scroll(window)) {
523 return;
524 }
525
526 let mut offset = scroll_handle.offset();
527 let mut delta = event.delta.pixel_delta(line_height);
528
529 if vertical_wheel {
533 let ScrollDelta::Lines(lines) = event.delta else {
534 return;
535 };
536 if lines.x != 0. || lines.y == 0. || !lines.y.is_finite() {
537 return;
538 }
539 let axis_max = (scroll_handle.content_size().width
540 - scroll_handle.viewport_bounds().size.width)
541 .max(px(0.));
542 let current = offset.x.clamp(-axis_max, px(0.));
543 let new_offset = (current + delta.y).clamp(-axis_max, px(0.));
544 if new_offset == current {
545 return;
546 }
547
548 offset.x = new_offset;
549 scroll_handle.set_offset(offset);
550 cx.notify(view_id);
551 cx.stop_propagation();
552 return;
553 }
554
555 if is_horizontal
558 && !delta.y.is_zero()
559 && scroll_handle.content_size().width
560 <= scroll_handle.viewport_bounds().size.width
561 {
562 return;
563 }
564
565 if event.delta.precise() {
569 ongoing_scroll
570 .borrow_mut()
571 .lock_axis(&mut delta, event.touch_phase);
572 }
573
574 if !delta.x.is_zero() && !delta.y.is_zero() {
578 if delta.x.abs() > delta.y.abs() {
579 delta.y = px(0.);
580 } else {
581 delta.x = px(0.);
582 }
583 }
584
585 if !is_horizontal {
586 let axis_max = (scroll_handle.content_size().height
594 - scroll_handle.viewport_bounds().size.height)
595 .max(px(0.));
596 let current = offset.y.clamp(-axis_max, px(0.));
597 let new_offset = (current + delta.y).clamp(-axis_max, px(0.));
598 if new_offset == current {
599 return;
601 }
602
603 offset.y = new_offset;
604 scroll_handle.set_offset(offset);
605 cx.notify(view_id);
606 cx.stop_propagation();
607 return;
608 }
609
610 if !delta.x.is_zero() {
615 let axis_max = (scroll_handle.content_size().width
616 - scroll_handle.viewport_bounds().size.width)
617 .max(px(0.));
618 let current = offset.x.clamp(-axis_max, px(0.));
619 let moved = (offset.x + delta.x).clamp(-axis_max, px(0.)) - current;
620 if moved.abs() >= CLAIM_EPSILON {
621 LAST_HORIZONTAL_SCROLL_CLAIM.set(Some(HorizontalScrollClaim {
622 at: Instant::now(),
623 delta_x: moved,
624 }));
625 }
626 }
627
628 offset.x += delta.x;
629
630 if offset != scroll_handle.offset() {
636 scroll_handle.set_offset(offset);
637 cx.notify(view_id);
638 cx.stop_propagation();
639 }
640 }
641 });
642 });
643 }
644}
645
646#[cfg(test)]
647mod tests {
648 use super::*;
649 use gpui::{
650 Context, IntoElement, ListAlignment, ListState, Render, ScrollDelta, ScrollEvent,
651 TestAppContext, VisualTestContext, Window, div, list, point, px,
652 };
653
654 #[test]
655 fn corner_notch_paths_stay_inside_their_corner_squares() {
656 let width = px(200.);
657 let height = px(100.);
658 let radius = px(8.);
659 let cases = [
660 ("top left", point(px(0.), px(0.)), 1., 1.),
661 ("top right", point(width, px(0.)), -1., 1.),
662 ("bottom right", point(width, height), -1., -1.),
663 ("bottom left", point(px(0.), height), 1., -1.),
664 ];
665 for (name, corner, x_dir, y_dir) in cases {
666 let path =
667 corner_notch_path(corner, x_dir, y_dir, radius).expect("the notch tessellates");
668 let bounds = path.bounds;
669 let tolerance = 1.0;
671 assert!(
672 (f32::from(bounds.size.width) - f32::from(radius)).abs() <= tolerance
673 && (f32::from(bounds.size.height) - f32::from(radius)).abs() <= tolerance,
674 "{name}: notch size {:?} must stay a {radius:?} square",
675 bounds.size,
676 );
677 let expected_origin = point(
678 if x_dir > 0. {
679 corner.x
680 } else {
681 corner.x - radius
682 },
683 if y_dir > 0. {
684 corner.y
685 } else {
686 corner.y - radius
687 },
688 );
689 assert!(
690 (f32::from(bounds.origin.x) - f32::from(expected_origin.x)).abs() <= tolerance
691 && (f32::from(bounds.origin.y) - f32::from(expected_origin.y)).abs()
692 <= tolerance,
693 "{name}: notch bounds {bounds:?} must anchor at the frame corner",
694 );
695 }
696 }
697
698 struct HorizontalScrollAreaTest {
699 scroll_handle: ScrollHandle,
700 }
701
702 impl Render for HorizontalScrollAreaTest {
703 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
704 div().w(px(100.)).h(px(40.)).child(horizontal_scroll_area(
705 "horizontal-scroll-area",
706 &self.scroll_handle,
707 &Default::default(),
708 div().w(px(300.)).h(px(40.)),
709 ))
710 }
711 }
712
713 #[gpui::test]
714 fn horizontal_scroll_area_ignores_vertical_wheel(cx: &mut TestAppContext) {
715 let scroll_handle = ScrollHandle::new();
716 let (_, cx) = cx.add_window_view({
717 let scroll_handle = scroll_handle.clone();
718 move |_, _| HorizontalScrollAreaTest { scroll_handle }
719 });
720 let cx: &mut VisualTestContext = cx;
721 cx.run_until_parked();
722 cx.update(|window, cx| {
723 _ = window.draw(cx);
724 });
725
726 cx.simulate_event(ScrollEvent {
727 position: point(px(10.), px(10.)),
728 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
729 ..Default::default()
730 });
731
732 assert_eq!(scroll_handle.offset().x, px(0.));
733 }
734
735 struct ListWithHorizontalAreaTest {
740 scroll_handle: ScrollHandle,
741 list_state: ListState,
742 occluded: bool,
743 }
744
745 impl Render for ListWithHorizontalAreaTest {
746 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
747 let scroll_handle = self.scroll_handle.clone();
748 let mut root = div().w(px(100.)).h(px(100.)).child(
749 list(self.list_state.clone(), move |ix, _, _| {
750 if ix == 0 {
751 horizontal_scroll_area(
752 "horizontal-scroll-area",
753 &scroll_handle,
754 &Default::default(),
755 div().w(px(300.)).h(px(40.)),
756 )
757 .into_any_element()
758 } else {
759 div().w(px(100.)).h(px(40.)).into_any_element()
760 }
761 })
762 .w_full()
763 .h_full(),
764 );
765 if self.occluded {
766 root = root.child(div().absolute().top_0().left_0().size_full().occlude());
768 }
769 root
770 }
771 }
772
773 fn setup_list_test<'a>(
774 cx: &'a mut TestAppContext,
775 scroll_handle: &ScrollHandle,
776 list_state: &ListState,
777 occluded: bool,
778 ) -> &'a mut VisualTestContext {
779 let (_, cx) = cx.add_window_view({
780 let scroll_handle = scroll_handle.clone();
781 let list_state = list_state.clone();
782 move |_, _| ListWithHorizontalAreaTest {
783 scroll_handle: scroll_handle.clone(),
784 list_state: list_state.clone(),
785 occluded,
786 }
787 });
788 cx.run_until_parked();
789 cx.update(|window, cx| {
790 _ = window.draw(cx);
791 });
792 cx
793 }
794
795 #[gpui::test]
796 fn horizontal_scroll_area_in_list_keeps_horizontal_dominant_wheel(cx: &mut TestAppContext) {
797 let scroll_handle = ScrollHandle::new();
798 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
799 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
800
801 cx.simulate_event(ScrollEvent {
804 position: point(px(10.), px(10.)),
805 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
806 ..Default::default()
807 });
808
809 assert_eq!(scroll_handle.offset().x, px(-40.));
811 let scroll_top = list_state.logical_scroll_top();
813 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
814 }
815
816 #[gpui::test]
817 fn horizontal_scroll_area_in_list_bubbles_vertical_dominant_wheel(cx: &mut TestAppContext) {
818 let scroll_handle = ScrollHandle::new();
819 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
820 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
821
822 cx.simulate_event(ScrollEvent {
823 position: point(px(10.), px(10.)),
824 delta: ScrollDelta::Pixels(point(px(-10.), px(-40.))),
825 ..Default::default()
826 });
827
828 assert_eq!(scroll_handle.offset().x, px(0.));
830 let scroll_top = list_state.logical_scroll_top();
831 assert_ne!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
832 }
833
834 struct ListWithFittingAreaTest(ListState);
837
838 impl Render for ListWithFittingAreaTest {
839 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
840 div().w(px(100.)).h(px(100.)).child(
841 list(self.0.clone(), |ix, _, _| {
842 if ix == 0 {
843 horizontal_scroll_area(
844 "fitting-area",
845 &ScrollHandle::new(),
846 &Default::default(),
847 div().w(px(50.)).h(px(40.)),
848 )
849 .into_any_element()
850 } else {
851 div().w(px(100.)).h(px(40.)).into_any_element()
852 }
853 })
854 .w_full()
855 .h_full(),
856 )
857 }
858 }
859
860 #[gpui::test]
861 fn horizontal_scroll_area_that_fits_bubbles_horizontal_dominant_wheel(cx: &mut TestAppContext) {
862 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
863 let (_, cx) = cx.add_window_view({
864 let list_state = list_state.clone();
865 move |_, _| ListWithFittingAreaTest(list_state)
866 });
867 cx.update(|window, cx| {
868 _ = window.draw(cx);
869 });
870
871 cx.simulate_event(ScrollEvent {
872 position: point(px(10.), px(10.)),
873 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
874 ..Default::default()
875 });
876 let scroll_top = list_state.logical_scroll_top();
878 assert_ne!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
879 }
880
881 struct ListWithVerticalMaskTest {
884 outer_handle: ScrollHandle,
885 list_state: ListState,
886 }
887
888 impl Render for ListWithVerticalMaskTest {
889 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
890 div()
891 .id("outer")
892 .w(px(100.))
893 .h(px(100.))
894 .overflow_y_scroll()
895 .track_scroll(&self.outer_handle)
896 .child(
897 div().w_full().h(px(400.)).child(
898 div()
899 .relative()
900 .w_full()
901 .h(px(80.))
902 .overflow_hidden()
903 .child(
904 list(self.list_state.clone(), |_, _, _| {
905 div().w_full().h(px(40.)).into_any_element()
906 })
907 .w_full()
908 .h_full(),
909 )
910 .child(ScrollableMask::new(Axis::Vertical, &self.list_state)),
911 ),
912 )
913 }
914 }
915
916 fn setup_vertical_mask_test<'a>(
917 cx: &'a mut TestAppContext,
918 outer_handle: &ScrollHandle,
919 list_state: &ListState,
920 ) -> &'a mut VisualTestContext {
921 let (_, cx) = cx.add_window_view({
922 let outer_handle = outer_handle.clone();
923 let list_state = list_state.clone();
924 move |_, _| ListWithVerticalMaskTest {
925 outer_handle: outer_handle.clone(),
926 list_state,
927 }
928 });
929 cx.run_until_parked();
930 cx.update(|window, cx| {
931 _ = window.draw(cx);
932 });
933 cx
934 }
935
936 #[gpui::test]
937 fn vertical_mask_contains_wheel_inside_the_list(cx: &mut TestAppContext) {
938 let outer_handle = ScrollHandle::new();
939 let list_state = ListState::new(10, ListAlignment::Top, px(1000.));
942 let cx = setup_vertical_mask_test(cx, &outer_handle, &list_state);
943
944 cx.simulate_event(ScrollEvent {
945 position: point(px(10.), px(10.)),
946 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
947 ..Default::default()
948 });
949
950 assert_eq!(list_state.scroll_px_offset_for_scrollbar().y, px(-40.));
952 assert_eq!(outer_handle.offset().y, px(0.));
953 }
954
955 #[gpui::test]
956 fn vertical_mask_chains_to_the_ancestor_at_the_edge(cx: &mut TestAppContext) {
957 let outer_handle = ScrollHandle::new();
958 let list_state = ListState::new(10, ListAlignment::Top, px(1000.));
959 list_state.scroll_to(gpui::ListOffset {
961 item_ix: 8,
962 offset_in_item: px(0.),
963 });
964 let cx = setup_vertical_mask_test(cx, &outer_handle, &list_state);
965
966 cx.simulate_event(ScrollEvent {
967 position: point(px(10.), px(10.)),
968 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
969 ..Default::default()
970 });
971
972 assert_eq!(list_state.scroll_px_offset_for_scrollbar().y, px(-320.));
974 assert_eq!(outer_handle.offset().y, px(-40.));
975 }
976
977 #[gpui::test]
978 fn horizontal_scroll_area_covers_viewport_after_scrolled(cx: &mut TestAppContext) {
979 let scroll_handle = ScrollHandle::new();
980 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
981 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
982
983 scroll_handle.set_offset(point(px(-150.), px(0.)));
985 cx.update(|window, cx| {
986 _ = window.draw(cx);
987 });
988
989 cx.simulate_event(ScrollEvent {
992 position: point(px(90.), px(10.)),
993 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
994 ..Default::default()
995 });
996
997 assert_eq!(scroll_handle.offset().x, px(-190.));
998 let scroll_top = list_state.logical_scroll_top();
999 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
1000 }
1001
1002 #[gpui::test]
1003 fn horizontal_scroll_area_traps_wheel_at_edge(cx: &mut TestAppContext) {
1004 let scroll_handle = ScrollHandle::new();
1005 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
1006 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
1007
1008 scroll_handle.set_offset(point(px(-200.), px(0.)));
1010 cx.update(|window, cx| {
1011 _ = window.draw(cx);
1012 });
1013
1014 cx.simulate_event(ScrollEvent {
1015 position: point(px(10.), px(10.)),
1016 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
1017 ..Default::default()
1018 });
1019
1020 let scroll_top = list_state.logical_scroll_top();
1023 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
1024 }
1025
1026 #[gpui::test]
1027 fn horizontal_scroll_area_ignores_wheel_when_occluded(cx: &mut TestAppContext) {
1028 let scroll_handle = ScrollHandle::new();
1029 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
1030 let cx = setup_list_test(cx, &scroll_handle, &list_state, true);
1031
1032 cx.simulate_event(ScrollEvent {
1033 position: point(px(10.), px(10.)),
1034 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
1035 ..Default::default()
1036 });
1037
1038 assert_eq!(scroll_handle.offset().x, px(0.));
1041 }
1042
1043 #[gpui::test]
1044 fn horizontal_scroll_area_uses_horizontal_wheel(cx: &mut TestAppContext) {
1045 let scroll_handle = ScrollHandle::new();
1046 let (_, cx) = cx.add_window_view({
1047 let scroll_handle = scroll_handle.clone();
1048 move |_, _| HorizontalScrollAreaTest { scroll_handle }
1049 });
1050 let cx: &mut VisualTestContext = cx;
1051 cx.run_until_parked();
1052 cx.update(|window, cx| {
1053 _ = window.draw(cx);
1054 });
1055
1056 cx.simulate_event(ScrollEvent {
1057 position: point(px(10.), px(10.)),
1058 delta: ScrollDelta::Pixels(point(px(-40.), px(0.))),
1059 ..Default::default()
1060 });
1061
1062 assert_eq!(scroll_handle.offset().x, px(-40.));
1063 }
1064
1065 #[gpui::test]
1066 fn horizontal_scroll_area_claims_only_steps_that_move(cx: &mut TestAppContext) {
1067 let scroll_handle = ScrollHandle::new();
1068 let (_, cx) = cx.add_window_view({
1069 let scroll_handle = scroll_handle.clone();
1070 move |_, _| HorizontalScrollAreaTest { scroll_handle }
1071 });
1072 let cx: &mut VisualTestContext = cx;
1073 cx.run_until_parked();
1074 cx.update(|window, cx| {
1075 _ = window.draw(cx);
1076 });
1077
1078 LAST_HORIZONTAL_SCROLL_CLAIM.set(None);
1080 cx.simulate_event(ScrollEvent {
1081 position: point(px(10.), px(10.)),
1082 delta: ScrollDelta::Pixels(point(px(40.), px(0.))),
1083 ..Default::default()
1084 });
1085 assert!(last_horizontal_scroll_claim().is_none());
1086
1087 cx.update(|window, cx| {
1091 let mut dispatch = |delta_x: f32| {
1092 window.dispatch_event(
1093 gpui::PlatformInput::Scroll(ScrollEvent {
1094 position: point(px(10.), px(10.)),
1095 delta: ScrollDelta::Pixels(point(px(delta_x), px(0.))),
1096 ..Default::default()
1097 }),
1098 cx,
1099 );
1100 };
1101
1102 scroll_handle.set_offset(point(px(40.), px(0.)));
1105 dispatch(-10.);
1106 assert!(last_horizontal_scroll_claim().is_none());
1107 assert_eq!(scroll_handle.offset().x, px(30.));
1108
1109 dispatch(-40.);
1111 });
1112 let claim = last_horizontal_scroll_claim().expect("a moving step claims");
1113 assert_eq!(claim.delta_x(), px(-10.));
1114 assert_eq!(scroll_handle.offset().x, px(-10.));
1115
1116 for delta in [point(px(0.), px(-40.)), point(px(-0.25), px(0.))] {
1118 cx.simulate_event(ScrollEvent {
1119 position: point(px(10.), px(10.)),
1120 delta: ScrollDelta::Pixels(delta),
1121 ..Default::default()
1122 });
1123 assert_eq!(last_horizontal_scroll_claim(), Some(claim));
1124 }
1125 }
1126
1127 fn setup_horizontal_area_test<'a>(
1128 cx: &'a mut TestAppContext,
1129 scroll_handle: &ScrollHandle,
1130 ) -> &'a mut VisualTestContext {
1131 let (_, cx) = cx.add_window_view({
1132 let scroll_handle = scroll_handle.clone();
1133 move |_, _| HorizontalScrollAreaTest { scroll_handle }
1134 });
1135 let cx: &mut VisualTestContext = cx;
1136 cx.run_until_parked();
1137 cx.update(|window, cx| {
1138 _ = window.draw(cx);
1139 });
1140 cx
1141 }
1142
1143 #[gpui::test]
1144 fn horizontal_mask_keeps_axis_lock_within_a_gesture(cx: &mut TestAppContext) {
1145 let scroll_handle = ScrollHandle::new();
1146 let cx = setup_horizontal_area_test(cx, &scroll_handle);
1147
1148 cx.simulate_event(ScrollEvent {
1149 position: point(px(10.), px(10.)),
1150 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
1151 ..Default::default()
1152 });
1153 assert_eq!(scroll_handle.offset().x, px(-40.));
1154
1155 cx.simulate_event(ScrollEvent {
1159 position: point(px(10.), px(10.)),
1160 delta: ScrollDelta::Pixels(point(px(-10.), px(-15.))),
1161 ..Default::default()
1162 });
1163 assert_eq!(scroll_handle.offset().x, px(-50.));
1164 }
1165
1166 #[gpui::test]
1167 fn horizontal_mask_releases_axis_lock_on_a_strong_turn(cx: &mut TestAppContext) {
1168 let scroll_handle = ScrollHandle::new();
1169 let cx = setup_horizontal_area_test(cx, &scroll_handle);
1170
1171 cx.simulate_event(ScrollEvent {
1172 position: point(px(10.), px(10.)),
1173 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
1174 ..Default::default()
1175 });
1176 assert_eq!(scroll_handle.offset().x, px(-40.));
1177
1178 cx.simulate_event(ScrollEvent {
1181 position: point(px(10.), px(10.)),
1182 delta: ScrollDelta::Pixels(point(px(-10.), px(-25.))),
1183 ..Default::default()
1184 });
1185 assert_eq!(scroll_handle.offset().x, px(-40.));
1186 }
1187
1188 struct NestedVerticalScrollTest {
1191 outer_handle: ScrollHandle,
1192 inner_handle: ScrollHandle,
1193 inner_content_height: Pixels,
1194 }
1195
1196 impl Render for NestedVerticalScrollTest {
1197 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1198 div()
1199 .id("outer")
1200 .w(px(100.))
1201 .h(px(100.))
1202 .overflow_y_scroll()
1203 .track_scroll(&self.outer_handle)
1204 .child(
1205 div()
1206 .relative()
1207 .w_full()
1208 .h(px(60.))
1209 .child(
1210 div()
1211 .id("inner")
1212 .size_full()
1213 .overflow_y_scroll()
1214 .track_scroll(&self.inner_handle)
1215 .child(div().w_full().h(self.inner_content_height)),
1216 )
1217 .child(ScrollableMask::new(Axis::Vertical, &self.inner_handle)),
1218 )
1219 .child(div().w_full().h(px(400.)))
1220 }
1221 }
1222
1223 fn setup_nested_vertical_test<'a>(
1224 cx: &'a mut TestAppContext,
1225 outer_handle: &ScrollHandle,
1226 inner_handle: &ScrollHandle,
1227 inner_content_height: Pixels,
1228 ) -> &'a mut VisualTestContext {
1229 let (_, cx) = cx.add_window_view({
1230 let outer_handle = outer_handle.clone();
1231 let inner_handle = inner_handle.clone();
1232 move |_, _| NestedVerticalScrollTest {
1233 outer_handle: outer_handle.clone(),
1234 inner_handle: inner_handle.clone(),
1235 inner_content_height,
1236 }
1237 });
1238 cx.run_until_parked();
1239 cx.update(|window, cx| {
1240 _ = window.draw(cx);
1241 });
1242 cx
1243 }
1244
1245 #[gpui::test]
1246 fn vertical_mask_consumes_wheel_when_scrollable(cx: &mut TestAppContext) {
1247 let outer_handle = ScrollHandle::new();
1248 let inner_handle = ScrollHandle::new();
1249 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
1250
1251 cx.simulate_event(ScrollEvent {
1252 position: point(px(10.), px(10.)),
1253 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1254 ..Default::default()
1255 });
1256
1257 assert_eq!(inner_handle.offset().y, px(-40.));
1259 assert_eq!(outer_handle.offset().y, px(0.));
1260 }
1261
1262 #[gpui::test]
1263 fn vertical_mask_hands_off_to_parent_at_edge(cx: &mut TestAppContext) {
1264 let outer_handle = ScrollHandle::new();
1265 let inner_handle = ScrollHandle::new();
1266 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
1267
1268 inner_handle.set_offset(point(px(0.), px(-240.)));
1270 cx.update(|window, cx| {
1271 _ = window.draw(cx);
1272 });
1273
1274 cx.simulate_event(ScrollEvent {
1275 position: point(px(10.), px(10.)),
1276 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1277 ..Default::default()
1278 });
1279
1280 assert_eq!(outer_handle.offset().y, px(-40.));
1282 cx.update(|window, cx| {
1284 _ = window.draw(cx);
1285 });
1286 assert_eq!(inner_handle.offset().y, px(-240.));
1287 }
1288
1289 #[gpui::test]
1290 fn vertical_mask_bubbles_when_no_overflow(cx: &mut TestAppContext) {
1291 let outer_handle = ScrollHandle::new();
1292 let inner_handle = ScrollHandle::new();
1293 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(40.));
1295
1296 cx.simulate_event(ScrollEvent {
1297 position: point(px(10.), px(10.)),
1298 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1299 ..Default::default()
1300 });
1301
1302 assert_eq!(outer_handle.offset().y, px(-40.));
1303 cx.update(|window, cx| {
1304 _ = window.draw(cx);
1305 });
1306 assert_eq!(inner_handle.offset().y, px(0.));
1307 }
1308
1309 #[gpui::test]
1310 fn vertical_mask_ignores_transient_overscroll(cx: &mut TestAppContext) {
1311 let outer_handle = ScrollHandle::new();
1312 let inner_handle = ScrollHandle::new();
1313 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
1314
1315 inner_handle.set_offset(point(px(0.), px(-240.)));
1316 cx.update(|window, cx| {
1317 _ = window.draw(cx);
1318 });
1319
1320 for _ in 0..2 {
1324 cx.simulate_event(ScrollEvent {
1325 position: point(px(10.), px(10.)),
1326 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1327 ..Default::default()
1328 });
1329 }
1330
1331 assert_eq!(outer_handle.offset().y, px(-80.));
1332 cx.update(|window, cx| {
1333 _ = window.draw(cx);
1334 });
1335 assert_eq!(inner_handle.offset().y, px(-240.));
1336 }
1337
1338 struct ListWithVerticalAreaTest {
1342 scroll_handle: ScrollHandle,
1343 list_state: ListState,
1344 }
1345
1346 impl Render for ListWithVerticalAreaTest {
1347 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1348 let scroll_handle = self.scroll_handle.clone();
1349 div().w(px(100.)).h(px(100.)).child(
1350 list(self.list_state.clone(), move |ix, _, _| {
1351 if ix == 0 {
1352 div()
1353 .relative()
1354 .w_full()
1355 .h(px(60.))
1356 .child(
1357 div()
1358 .id("inner")
1359 .size_full()
1360 .overflow_y_scroll()
1361 .track_scroll(&scroll_handle)
1362 .child(div().w_full().h(px(300.))),
1363 )
1364 .child(ScrollableMask::new(Axis::Vertical, &scroll_handle))
1365 .into_any_element()
1366 } else {
1367 div().w(px(100.)).h(px(40.)).into_any_element()
1368 }
1369 })
1370 .w_full()
1371 .h_full(),
1372 )
1373 }
1374 }
1375
1376 #[gpui::test]
1377 fn vertical_mask_in_list_consumes_wheel_when_scrollable(cx: &mut TestAppContext) {
1378 let scroll_handle = ScrollHandle::new();
1379 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
1380 let (_, cx) = cx.add_window_view({
1381 let scroll_handle = scroll_handle.clone();
1382 let list_state = list_state.clone();
1383 move |_, _| ListWithVerticalAreaTest {
1384 scroll_handle: scroll_handle.clone(),
1385 list_state,
1386 }
1387 });
1388 cx.run_until_parked();
1389 cx.update(|window, cx| {
1390 _ = window.draw(cx);
1391 });
1392
1393 cx.simulate_event(ScrollEvent {
1394 position: point(px(10.), px(10.)),
1395 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1396 ..Default::default()
1397 });
1398
1399 assert_eq!(scroll_handle.offset().y, px(-40.));
1401 let scroll_top = list_state.logical_scroll_top();
1402 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
1403 }
1404
1405 struct VerticalWheelTest {
1408 strip: ScrollHandle,
1409 page: ScrollHandle,
1410 }
1411
1412 impl Render for VerticalWheelTest {
1413 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1414 div()
1415 .id("page")
1416 .w(px(100.))
1417 .h(px(60.))
1418 .overflow_y_scroll()
1419 .track_scroll(&self.page)
1420 .child(
1421 div()
1422 .relative()
1423 .w(px(100.))
1424 .h(px(40.))
1425 .child(
1426 div()
1427 .id("strip")
1428 .size_full()
1429 .flex()
1430 .overflow_x_scroll()
1431 .restrict_scroll_to_axis()
1432 .track_scroll(&self.strip)
1433 .child(div().flex_none().w(px(300.)).h(px(40.))),
1434 )
1435 .child(ScrollableMask::vertical_wheel(&self.strip)),
1436 )
1437 .child(div().h(px(200.)))
1438 }
1439 }
1440
1441 fn vertical_wheel_test(
1442 cx: &mut TestAppContext,
1443 ) -> (&mut VisualTestContext, ScrollHandle, ScrollHandle) {
1444 let (strip, page) = (ScrollHandle::new(), ScrollHandle::new());
1445 let (_, cx) = cx.add_window_view({
1446 let (strip, page) = (strip.clone(), page.clone());
1447 move |_, _| VerticalWheelTest { strip, page }
1448 });
1449 cx.run_until_parked();
1450 cx.update(|window, cx| window.draw(cx).clear(cx));
1451 (cx, strip, page)
1452 }
1453
1454 fn wheel(cx: &mut VisualTestContext, delta: ScrollDelta) {
1455 cx.simulate_event(ScrollEvent {
1456 position: point(px(10.), px(10.)),
1457 delta,
1458 ..Default::default()
1459 });
1460 cx.update(|window, cx| window.draw(cx).clear(cx));
1461 }
1462
1463 #[gpui::test]
1464 fn vertical_wheel_scrolls_the_strip_and_then_the_parent(cx: &mut TestAppContext) {
1465 let (cx, strip, page) = vertical_wheel_test(cx);
1466 let line_height = cx.update(|window, _| window.line_height());
1467
1468 wheel(cx, ScrollDelta::Lines(point(0., -1.)));
1469 assert_eq!(strip.offset().x, -line_height);
1470 assert_eq!(page.offset().y, px(0.));
1471
1472 wheel(cx, ScrollDelta::Lines(point(0., -100.)));
1474 assert_eq!(strip.offset().x, px(-200.));
1475 assert_eq!(page.offset().y, px(0.));
1476 wheel(cx, ScrollDelta::Lines(point(0., -1.)));
1477 assert_eq!(strip.offset().x, px(-200.));
1478 assert!(page.offset().y < px(0.));
1479
1480 wheel(cx, ScrollDelta::Lines(point(0., f32::NAN)));
1482 assert_eq!(strip.offset().x, px(-200.));
1483 }
1484
1485 #[gpui::test]
1486 fn vertical_wheel_leaves_trackpads_and_horizontal_wheels_to_the_scroller(
1487 cx: &mut TestAppContext,
1488 ) {
1489 let (cx, strip, page) = vertical_wheel_test(cx);
1490 let line_height = cx.update(|window, _| window.line_height());
1491
1492 wheel(cx, ScrollDelta::Pixels(point(px(0.), px(-20.))));
1494 assert_eq!(strip.offset().x, px(0.));
1495 assert_eq!(page.offset().y, px(-20.));
1496
1497 wheel(cx, ScrollDelta::Lines(point(-1., 0.)));
1499 assert_eq!(strip.offset().x, -line_height);
1500 }
1501}