1use std::cell::RefCell;
2use std::rc::Rc;
3
4use gpui::{
5 App, Axis, BorderStyle, Bounds, ContentMask, Edges, Element, ElementId, GlobalElementId,
6 Hitbox, Hsla, InteractiveElement as _, IntoElement, IsZero as _, LayoutId, OngoingScroll,
7 PaintQuad, ParentElement as _, Point, Position, ScrollHandle, ScrollWheelEvent,
8 StatefulInteractiveElement as _, Style, StyleRefinement, Styled as _, Window, div, px,
9 relative,
10};
11use gpui::{Corners, Pixels};
12
13use super::scrollable::caller_id;
14use crate::{AxisExt, OngoingScrollExt as _, StyledExt as _};
15
16pub(crate) fn horizontal_scroll_area(
23 id: impl Into<ElementId>,
24 scroll_handle: &ScrollHandle,
25 style: &StyleRefinement,
26 child: impl IntoElement,
27) -> impl IntoElement {
28 let id = id.into();
29
30 div()
35 .w_full()
36 .relative()
37 .child(
38 div()
39 .id(id.clone())
40 .w_full()
41 .refine_style(style)
42 .overflow_hidden()
43 .track_scroll(scroll_handle)
44 .child(child),
45 )
46 .child(ScrollableMask::new(Axis::Horizontal, scroll_handle).id(id))
47}
48
49pub struct ScrollableMask {
70 axis: Axis,
71 id: ElementId,
72 scroll_handle: ScrollHandle,
73 debug: Option<Hsla>,
74}
75
76impl ScrollableMask {
77 #[track_caller]
79 pub fn new(axis: Axis, scroll_handle: &ScrollHandle) -> Self {
80 Self {
81 scroll_handle: scroll_handle.clone(),
82 axis,
83 id: caller_id(),
84 debug: None,
85 }
86 }
87
88 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
93 self.id = id.into();
94 self
95 }
96
97 #[allow(dead_code)]
99 pub fn debug(mut self) -> Self {
100 self.debug = Some(gpui::yellow());
101 self
102 }
103}
104
105impl IntoElement for ScrollableMask {
106 type Element = Self;
107
108 fn into_element(self) -> Self::Element {
109 self
110 }
111}
112
113impl Element for ScrollableMask {
114 type RequestLayoutState = ();
115 type PrepaintState = Hitbox;
116
117 fn id(&self) -> Option<ElementId> {
120 let axis = match self.axis {
121 Axis::Horizontal => "horizontal",
122 Axis::Vertical => "vertical",
123 };
124
125 Some((self.id.clone(), axis).into())
126 }
127
128 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
129 None
130 }
131
132 fn request_layout(
133 &mut self,
134 _: Option<&GlobalElementId>,
135 _: Option<&gpui::InspectorElementId>,
136 window: &mut Window,
137 cx: &mut App,
138 ) -> (LayoutId, Self::RequestLayoutState) {
139 let mut style = Style::default();
140 style.position = Position::Absolute;
142 style.flex_grow = 1.0;
143 style.flex_shrink = 1.0;
144 style.size.width = relative(1.).into();
145 style.size.height = relative(1.).into();
146
147 (window.request_layout(style, None, cx), ())
148 }
149
150 fn prepaint(
151 &mut self,
152 _: Option<&GlobalElementId>,
153 _: Option<&gpui::InspectorElementId>,
154 bounds: Bounds<Pixels>,
155 _: &mut Self::RequestLayoutState,
156 window: &mut Window,
157 _: &mut App,
158 ) -> Self::PrepaintState {
159 let cover_bounds = Bounds {
161 origin: Point {
162 x: bounds.origin.x,
163 y: bounds.origin.y - bounds.size.height,
164 },
165 size: bounds.size,
166 };
167
168 window.insert_hitbox(cover_bounds, gpui::HitboxBehavior::Normal)
169 }
170
171 fn paint(
172 &mut self,
173 global_id: Option<&GlobalElementId>,
174 _: Option<&gpui::InspectorElementId>,
175 _: Bounds<Pixels>,
176 _: &mut Self::RequestLayoutState,
177 hitbox: &mut Self::PrepaintState,
178 window: &mut Window,
179 _: &mut App,
180 ) {
181 let is_horizontal = self.axis.is_horizontal();
182 let line_height = window.line_height();
183 let bounds = hitbox.bounds;
184 let ongoing_scroll = global_id
185 .map(|global_id| {
186 window.with_element_state::<Rc<RefCell<OngoingScroll>>, _>(global_id, |state, _| {
187 let state = state.unwrap_or_default();
188 (state.clone(), state)
189 })
190 })
191 .unwrap_or_default();
192
193 window.with_content_mask(Some(ContentMask { bounds }), |window| {
194 if let Some(color) = self.debug {
195 window.paint_quad(PaintQuad {
196 bounds,
197 border_widths: Edges::all(px(1.0)),
198 border_color: color,
199 background: gpui::transparent_white().into(),
200 corner_radii: Corners::all(px(0.)),
201 border_style: BorderStyle::default(),
202 });
203 }
204
205 window.on_mouse_event({
206 let view_id = window.current_view();
207 let scroll_handle = self.scroll_handle.clone();
208 let hitbox_id = hitbox.id;
209 let ongoing_scroll = ongoing_scroll.clone();
210
211 move |event: &ScrollWheelEvent, phase, window, cx| {
212 if !(phase.capture() && hitbox_id.should_handle_scroll(window)) {
223 return;
224 }
225
226 let mut offset = scroll_handle.offset();
227 let mut delta = event.delta.pixel_delta(line_height);
228
229 if event.delta.precise() {
233 ongoing_scroll
234 .borrow_mut()
235 .lock_axis(&mut delta, event.touch_phase);
236 }
237
238 if !delta.x.is_zero() && !delta.y.is_zero() {
242 if delta.x.abs() > delta.y.abs() {
243 delta.y = px(0.);
244 } else {
245 delta.x = px(0.);
246 }
247 }
248
249 if !is_horizontal {
250 let axis_max = scroll_handle.max_offset().y.max(px(0.));
256 let current = offset.y.clamp(-axis_max, px(0.));
257 let new_offset = (current + delta.y).clamp(-axis_max, px(0.));
258 if new_offset == current {
259 return;
261 }
262
263 offset.y = new_offset;
264 scroll_handle.set_offset(offset);
265 cx.notify(view_id);
266 cx.stop_propagation();
267 return;
268 }
269
270 offset.x += delta.x;
271
272 if offset != scroll_handle.offset() {
278 scroll_handle.set_offset(offset);
279 cx.notify(view_id);
280 cx.stop_propagation();
281 }
282 }
283 });
284 });
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291 use gpui::{
292 Context, IntoElement, ListAlignment, ListState, Render, ScrollDelta, ScrollWheelEvent,
293 TestAppContext, VisualTestContext, Window, div, list, point, px,
294 };
295
296 struct HorizontalScrollAreaTest {
297 scroll_handle: ScrollHandle,
298 }
299
300 impl Render for HorizontalScrollAreaTest {
301 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
302 div().w(px(100.)).h(px(40.)).child(horizontal_scroll_area(
303 "horizontal-scroll-area",
304 &self.scroll_handle,
305 &Default::default(),
306 div().w(px(300.)).h(px(40.)),
307 ))
308 }
309 }
310
311 #[gpui::test]
312 fn horizontal_scroll_area_ignores_vertical_wheel(cx: &mut TestAppContext) {
313 let scroll_handle = ScrollHandle::new();
314 let (_, cx) = cx.add_window_view({
315 let scroll_handle = scroll_handle.clone();
316 move |_, _| HorizontalScrollAreaTest {
317 scroll_handle: scroll_handle.clone(),
318 }
319 });
320 let cx: &mut VisualTestContext = cx;
321 cx.run_until_parked();
322 cx.update(|window, cx| {
323 _ = window.draw(cx);
324 });
325
326 cx.simulate_event(ScrollWheelEvent {
327 position: point(px(10.), px(10.)),
328 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
329 ..Default::default()
330 });
331
332 assert_eq!(scroll_handle.offset().x, px(0.));
333 }
334
335 struct ListWithHorizontalAreaTest {
340 scroll_handle: ScrollHandle,
341 list_state: ListState,
342 occluded: bool,
343 }
344
345 impl Render for ListWithHorizontalAreaTest {
346 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
347 let scroll_handle = self.scroll_handle.clone();
348 let mut root = div().w(px(100.)).h(px(100.)).child(
349 list(self.list_state.clone(), move |ix, _, _| {
350 if ix == 0 {
351 horizontal_scroll_area(
352 "horizontal-scroll-area",
353 &scroll_handle,
354 &Default::default(),
355 div().w(px(300.)).h(px(40.)),
356 )
357 .into_any_element()
358 } else {
359 div().w(px(100.)).h(px(40.)).into_any_element()
360 }
361 })
362 .w_full()
363 .h_full(),
364 );
365 if self.occluded {
366 root = root.child(div().absolute().top_0().left_0().size_full().occlude());
368 }
369 root
370 }
371 }
372
373 fn setup_list_test<'a>(
374 cx: &'a mut TestAppContext,
375 scroll_handle: &ScrollHandle,
376 list_state: &ListState,
377 occluded: bool,
378 ) -> &'a mut VisualTestContext {
379 let (_, cx) = cx.add_window_view({
380 let scroll_handle = scroll_handle.clone();
381 let list_state = list_state.clone();
382 move |_, _| ListWithHorizontalAreaTest {
383 scroll_handle: scroll_handle.clone(),
384 list_state: list_state.clone(),
385 occluded,
386 }
387 });
388 cx.run_until_parked();
389 cx.update(|window, cx| {
390 _ = window.draw(cx);
391 });
392 cx
393 }
394
395 #[gpui::test]
396 fn horizontal_scroll_area_in_list_keeps_horizontal_dominant_wheel(cx: &mut TestAppContext) {
397 let scroll_handle = ScrollHandle::new();
398 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
399 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
400
401 cx.simulate_event(ScrollWheelEvent {
404 position: point(px(10.), px(10.)),
405 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
406 ..Default::default()
407 });
408
409 assert_eq!(scroll_handle.offset().x, px(-40.));
411 let scroll_top = list_state.logical_scroll_top();
413 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
414 }
415
416 #[gpui::test]
417 fn horizontal_scroll_area_in_list_bubbles_vertical_dominant_wheel(cx: &mut TestAppContext) {
418 let scroll_handle = ScrollHandle::new();
419 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
420 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
421
422 cx.simulate_event(ScrollWheelEvent {
423 position: point(px(10.), px(10.)),
424 delta: ScrollDelta::Pixels(point(px(-10.), px(-40.))),
425 ..Default::default()
426 });
427
428 assert_eq!(scroll_handle.offset().x, px(0.));
430 let scroll_top = list_state.logical_scroll_top();
431 assert_ne!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
432 }
433
434 #[gpui::test]
435 fn horizontal_scroll_area_covers_viewport_after_scrolled(cx: &mut TestAppContext) {
436 let scroll_handle = ScrollHandle::new();
437 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
438 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
439
440 scroll_handle.set_offset(point(px(-150.), px(0.)));
442 cx.update(|window, cx| {
443 _ = window.draw(cx);
444 });
445
446 cx.simulate_event(ScrollWheelEvent {
449 position: point(px(90.), px(10.)),
450 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
451 ..Default::default()
452 });
453
454 assert_eq!(scroll_handle.offset().x, px(-190.));
455 let scroll_top = list_state.logical_scroll_top();
456 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
457 }
458
459 #[gpui::test]
460 fn horizontal_scroll_area_traps_wheel_at_edge(cx: &mut TestAppContext) {
461 let scroll_handle = ScrollHandle::new();
462 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
463 let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
464
465 scroll_handle.set_offset(point(px(-200.), px(0.)));
467 cx.update(|window, cx| {
468 _ = window.draw(cx);
469 });
470
471 cx.simulate_event(ScrollWheelEvent {
472 position: point(px(10.), px(10.)),
473 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
474 ..Default::default()
475 });
476
477 let scroll_top = list_state.logical_scroll_top();
480 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
481 }
482
483 #[gpui::test]
484 fn horizontal_scroll_area_ignores_wheel_when_occluded(cx: &mut TestAppContext) {
485 let scroll_handle = ScrollHandle::new();
486 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
487 let cx = setup_list_test(cx, &scroll_handle, &list_state, true);
488
489 cx.simulate_event(ScrollWheelEvent {
490 position: point(px(10.), px(10.)),
491 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
492 ..Default::default()
493 });
494
495 assert_eq!(scroll_handle.offset().x, px(0.));
498 }
499
500 #[gpui::test]
501 fn horizontal_scroll_area_uses_horizontal_wheel(cx: &mut TestAppContext) {
502 let scroll_handle = ScrollHandle::new();
503 let (_, cx) = cx.add_window_view({
504 let scroll_handle = scroll_handle.clone();
505 move |_, _| HorizontalScrollAreaTest {
506 scroll_handle: scroll_handle.clone(),
507 }
508 });
509 let cx: &mut VisualTestContext = cx;
510 cx.run_until_parked();
511 cx.update(|window, cx| {
512 _ = window.draw(cx);
513 });
514
515 cx.simulate_event(ScrollWheelEvent {
516 position: point(px(10.), px(10.)),
517 delta: ScrollDelta::Pixels(point(px(-40.), px(0.))),
518 ..Default::default()
519 });
520
521 assert_eq!(scroll_handle.offset().x, px(-40.));
522 }
523
524 fn setup_horizontal_area_test<'a>(
525 cx: &'a mut TestAppContext,
526 scroll_handle: &ScrollHandle,
527 ) -> &'a mut VisualTestContext {
528 let (_, cx) = cx.add_window_view({
529 let scroll_handle = scroll_handle.clone();
530 move |_, _| HorizontalScrollAreaTest {
531 scroll_handle: scroll_handle.clone(),
532 }
533 });
534 let cx: &mut VisualTestContext = cx;
535 cx.run_until_parked();
536 cx.update(|window, cx| {
537 _ = window.draw(cx);
538 });
539 cx
540 }
541
542 #[gpui::test]
543 fn horizontal_mask_keeps_axis_lock_within_a_gesture(cx: &mut TestAppContext) {
544 let scroll_handle = ScrollHandle::new();
545 let cx = setup_horizontal_area_test(cx, &scroll_handle);
546
547 cx.simulate_event(ScrollWheelEvent {
548 position: point(px(10.), px(10.)),
549 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
550 ..Default::default()
551 });
552 assert_eq!(scroll_handle.offset().x, px(-40.));
553
554 cx.simulate_event(ScrollWheelEvent {
558 position: point(px(10.), px(10.)),
559 delta: ScrollDelta::Pixels(point(px(-10.), px(-15.))),
560 ..Default::default()
561 });
562 assert_eq!(scroll_handle.offset().x, px(-50.));
563 }
564
565 #[gpui::test]
566 fn horizontal_mask_releases_axis_lock_on_a_strong_turn(cx: &mut TestAppContext) {
567 let scroll_handle = ScrollHandle::new();
568 let cx = setup_horizontal_area_test(cx, &scroll_handle);
569
570 cx.simulate_event(ScrollWheelEvent {
571 position: point(px(10.), px(10.)),
572 delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
573 ..Default::default()
574 });
575 assert_eq!(scroll_handle.offset().x, px(-40.));
576
577 cx.simulate_event(ScrollWheelEvent {
580 position: point(px(10.), px(10.)),
581 delta: ScrollDelta::Pixels(point(px(-10.), px(-25.))),
582 ..Default::default()
583 });
584 assert_eq!(scroll_handle.offset().x, px(-40.));
585 }
586
587 struct NestedVerticalScrollTest {
590 outer_handle: ScrollHandle,
591 inner_handle: ScrollHandle,
592 inner_content_height: Pixels,
593 }
594
595 impl Render for NestedVerticalScrollTest {
596 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
597 div()
598 .id("outer")
599 .w(px(100.))
600 .h(px(100.))
601 .overflow_y_scroll()
602 .track_scroll(&self.outer_handle)
603 .child(
604 div()
605 .relative()
606 .w_full()
607 .h(px(60.))
608 .child(
609 div()
610 .id("inner")
611 .size_full()
612 .overflow_y_scroll()
613 .track_scroll(&self.inner_handle)
614 .child(div().w_full().h(self.inner_content_height)),
615 )
616 .child(ScrollableMask::new(Axis::Vertical, &self.inner_handle)),
617 )
618 .child(div().w_full().h(px(400.)))
619 }
620 }
621
622 fn setup_nested_vertical_test<'a>(
623 cx: &'a mut TestAppContext,
624 outer_handle: &ScrollHandle,
625 inner_handle: &ScrollHandle,
626 inner_content_height: Pixels,
627 ) -> &'a mut VisualTestContext {
628 let (_, cx) = cx.add_window_view({
629 let outer_handle = outer_handle.clone();
630 let inner_handle = inner_handle.clone();
631 move |_, _| NestedVerticalScrollTest {
632 outer_handle: outer_handle.clone(),
633 inner_handle: inner_handle.clone(),
634 inner_content_height,
635 }
636 });
637 cx.run_until_parked();
638 cx.update(|window, cx| {
639 _ = window.draw(cx);
640 });
641 cx
642 }
643
644 #[gpui::test]
645 fn vertical_mask_consumes_wheel_when_scrollable(cx: &mut TestAppContext) {
646 let outer_handle = ScrollHandle::new();
647 let inner_handle = ScrollHandle::new();
648 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
649
650 cx.simulate_event(ScrollWheelEvent {
651 position: point(px(10.), px(10.)),
652 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
653 ..Default::default()
654 });
655
656 assert_eq!(inner_handle.offset().y, px(-40.));
658 assert_eq!(outer_handle.offset().y, px(0.));
659 }
660
661 #[gpui::test]
662 fn vertical_mask_hands_off_to_parent_at_edge(cx: &mut TestAppContext) {
663 let outer_handle = ScrollHandle::new();
664 let inner_handle = ScrollHandle::new();
665 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
666
667 inner_handle.set_offset(point(px(0.), px(-240.)));
669 cx.update(|window, cx| {
670 _ = window.draw(cx);
671 });
672
673 cx.simulate_event(ScrollWheelEvent {
674 position: point(px(10.), px(10.)),
675 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
676 ..Default::default()
677 });
678
679 assert_eq!(outer_handle.offset().y, px(-40.));
681 cx.update(|window, cx| {
683 _ = window.draw(cx);
684 });
685 assert_eq!(inner_handle.offset().y, px(-240.));
686 }
687
688 #[gpui::test]
689 fn vertical_mask_bubbles_when_no_overflow(cx: &mut TestAppContext) {
690 let outer_handle = ScrollHandle::new();
691 let inner_handle = ScrollHandle::new();
692 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(40.));
694
695 cx.simulate_event(ScrollWheelEvent {
696 position: point(px(10.), px(10.)),
697 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
698 ..Default::default()
699 });
700
701 assert_eq!(outer_handle.offset().y, px(-40.));
702 cx.update(|window, cx| {
703 _ = window.draw(cx);
704 });
705 assert_eq!(inner_handle.offset().y, px(0.));
706 }
707
708 #[gpui::test]
709 fn vertical_mask_ignores_transient_overscroll(cx: &mut TestAppContext) {
710 let outer_handle = ScrollHandle::new();
711 let inner_handle = ScrollHandle::new();
712 let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
713
714 inner_handle.set_offset(point(px(0.), px(-240.)));
715 cx.update(|window, cx| {
716 _ = window.draw(cx);
717 });
718
719 for _ in 0..2 {
723 cx.simulate_event(ScrollWheelEvent {
724 position: point(px(10.), px(10.)),
725 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
726 ..Default::default()
727 });
728 }
729
730 assert_eq!(outer_handle.offset().y, px(-80.));
731 cx.update(|window, cx| {
732 _ = window.draw(cx);
733 });
734 assert_eq!(inner_handle.offset().y, px(-240.));
735 }
736
737 struct ListWithVerticalAreaTest {
741 scroll_handle: ScrollHandle,
742 list_state: ListState,
743 }
744
745 impl Render for ListWithVerticalAreaTest {
746 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
747 let scroll_handle = self.scroll_handle.clone();
748 div().w(px(100.)).h(px(100.)).child(
749 list(self.list_state.clone(), move |ix, _, _| {
750 if ix == 0 {
751 div()
752 .relative()
753 .w_full()
754 .h(px(60.))
755 .child(
756 div()
757 .id("inner")
758 .size_full()
759 .overflow_y_scroll()
760 .track_scroll(&scroll_handle)
761 .child(div().w_full().h(px(300.))),
762 )
763 .child(ScrollableMask::new(Axis::Vertical, &scroll_handle))
764 .into_any_element()
765 } else {
766 div().w(px(100.)).h(px(40.)).into_any_element()
767 }
768 })
769 .w_full()
770 .h_full(),
771 )
772 }
773 }
774
775 #[gpui::test]
776 fn vertical_mask_in_list_consumes_wheel_when_scrollable(cx: &mut TestAppContext) {
777 let scroll_handle = ScrollHandle::new();
778 let list_state = ListState::new(10, ListAlignment::Top, px(0.));
779 let (_, cx) = cx.add_window_view({
780 let scroll_handle = scroll_handle.clone();
781 let list_state = list_state.clone();
782 move |_, _| ListWithVerticalAreaTest {
783 scroll_handle: scroll_handle.clone(),
784 list_state: list_state.clone(),
785 }
786 });
787 cx.run_until_parked();
788 cx.update(|window, cx| {
789 _ = window.draw(cx);
790 });
791
792 cx.simulate_event(ScrollWheelEvent {
793 position: point(px(10.), px(10.)),
794 delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
795 ..Default::default()
796 });
797
798 assert_eq!(scroll_handle.offset().y, px(-40.));
800 let scroll_top = list_state.logical_scroll_top();
801 assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
802 }
803}