Skip to main content

gpui_component/scroll/
scrollable_mask.rs

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
16/// A horizontal scroll viewport that only consumes horizontal wheel deltas.
17///
18/// GPUI's native `overflow_x_scroll` maps vertical wheel input onto horizontal
19/// scrolling when there is no vertical overflow. This wrapper keeps the visual
20/// clipping and scroll offset, while delegating wheel input to [`ScrollableMask`]
21/// so vertical wheel events can continue bubbling to the parent scroller.
22pub(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    // The mask must be a sibling of the scrolled element (like in Table), not
31    // a child of it: children are prepainted with the scroll offset applied,
32    // which would slide the mask away from the viewport as the content
33    // scrolls, leaving the uncovered part to the parent scroller.
34    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
49/// Make a scrollable mask element to cover the parent view with the mouse wheel event listening.
50///
51/// When the mouse wheel is scrolled, will move the `scroll_handle` scrolling with the `axis` direction.
52/// You can use this `scroll_handle` to control what you want to scroll.
53/// This is only can handle once axis scrolling.
54///
55/// Axis-dominant wheel events are consumed in the capture phase, so the mask
56/// wins over ancestor scrollers (e.g. `gpui::list`) that register their
57/// listeners after their children; events dominated by the other axis keep
58/// propagating. The mask stays inert while occluded.
59///
60/// Dominance is decided per gesture, not per event: a precise (trackpad) delta
61/// locks onto the axis its gesture started on, so mid-swipe wobble cannot flip
62/// which mask consumes the events. Line deltas keep the per-event comparison.
63///
64/// At the scroll edge the two axes differ, matching platform scrollers:
65/// a vertical mask hands the event over to the ancestor scroller (CSS
66/// `overscroll-behavior: auto` chaining), while a horizontal mask keeps
67/// consuming it — a bubbled horizontal delta would get mapped onto a
68/// vertical-only ancestor by gpui's own wheel listener (see #2468).
69pub struct ScrollableMask {
70    axis: Axis,
71    id: ElementId,
72    scroll_handle: ScrollHandle,
73    debug: Option<Hsla>,
74}
75
76impl ScrollableMask {
77    /// Create a new scrollable mask element.
78    #[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    /// Set a specific element id, default is the [`std::panic::Location::caller`].
89    ///
90    /// Only needed when one call site creates several masks of the same axis,
91    /// which would otherwise share their gesture axis lock.
92    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
93        self.id = id.into();
94        self
95    }
96
97    /// Enable the debug border, to show the mask bounds.
98    #[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    // An id is needed to keep the gesture's axis lock across frames. The axis
118    // suffix keeps both masks of one scroller apart when they share an id.
119    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        // Set the layout style relative to the table view to get same size.
141        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        // Move y to bounds height to cover the parent view.
160        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                    // Handle in the capture phase: ancestor scrollers such as
213                    // `gpui::list` register their wheel listeners after their
214                    // children paint, so in the bubble phase (reverse
215                    // registration order) they run first and would consume the
216                    // vertical component of a trackpad swipe before this mask
217                    // could stop the propagation.
218                    //
219                    // `should_handle_scroll` (instead of a raw bounds check)
220                    // keeps the mask inert when it is occluded, e.g. below an
221                    // open dialog or context menu.
222                    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                    // Lock the gesture to the axis it started on, so a diagonal
230                    // trackpad swipe cannot flip which mask consumes it from one
231                    // event to the next. Line deltas carry no touch phase.
232                    if event.delta.precise() {
233                        ongoing_scroll
234                            .borrow_mut()
235                            .lock_axis(&mut delta, event.touch_phase);
236                    }
237
238                    // Limit for only one way scrolling at same time.
239                    // When use MacBook touchpad we may get both x and y delta,
240                    // only allows the one that more to scroll.
241                    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                        // The current offset must be clamped too: after a
251                        // bubbled event, the scrolled element's own listener
252                        // pushes the shared offset beyond the edge unclamped
253                        // (the div only clamps on prepaint), and that
254                        // transient overscroll would read as "room to scroll".
255                        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                            // At the edge or no overflow: bubble to the parent.
260                            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                    // NOTE: `set_offset` does not clamp (clamping happens in
273                    // the div's prepaint), so any non-zero horizontal-dominant
274                    // delta passes this guard — even at the scroll edge the
275                    // event is consumed rather than turned into a parent
276                    // scroll.
277                    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    /// Reproduces the markdown table case: the scroll area lives inside a
336    /// `gpui::list` item. The list registers its wheel listener after its
337    /// items paint, so in the bubble phase (reverse registration order) the
338    /// list runs first and consumes `delta.y` of every trackpad swipe.
339    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                // An overlay above the list, like an open dialog or menu.
367                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        // A trackpad swipe is rarely axis-pure: horizontal dominant with a
402        // small vertical component.
403        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        // The area consumes the horizontal delta...
410        assert_eq!(scroll_handle.offset().x, px(-40.));
411        // ...and the outer list must not scroll vertically.
412        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        // Vertical dominant: the list scrolls, the area does not.
429        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 the area to the middle, then repaint.
441        scroll_handle.set_offset(point(px(-150.), px(0.)));
442        cx.update(|window, cx| {
443            _ = window.draw(cx);
444        });
445
446        // Swipe over the right side of the viewport. The mask must still
447        // cover it — it must not slide away with the scrolled content.
448        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 the area to its right edge (300 - 100 = 200).
466        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        // A horizontal mask consumes even at the edge: a bubbled horizontal
478        // delta would be axis-mapped onto the vertical list (#2468).
479        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        // An overlay (dialog, context menu) occludes the area: the area
496        // must not scroll underneath it.
497        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        // Same gesture, now leaning vertical but under the unlock ratio: the
555        // lock holds and the horizontal offset keeps moving. Comparing this
556        // event alone would zero `delta.x` and stall the scroller at -40.
557        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        // Past the unlock ratio the gesture is no longer horizontal, so the
578        // event stops driving this scroller.
579        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    /// Reproduces the DataTable case: a vertically scrollable element
588    /// nested inside an outer vertical scroller.
589    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        // The inner scroller consumes the event; the outer one must not move.
657        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        // Scroll the inner element to its bottom edge (300 - 60 = 240).
668        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        // At the edge the event bubbles: the outer scroller takes over.
680        assert_eq!(outer_handle.offset().y, px(-40.));
681        // The inner offset is clamped back to the edge on the next prepaint.
682        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        // Inner content (40) fits its 60px viewport: nothing to scroll.
693        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        // Two wheel events at the edge with no redraw in between: the first
720        // one leaves the inner offset beyond the edge unclamped, which must
721        // not read as "room to scroll" and swallow the second event.
722        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    /// The vertical mask nested in a `gpui::list` ancestor: the list
738    /// registers its wheel listener after its items paint, so only a
739    /// capture-phase mask can stop it from scrolling on the same event.
740    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        // The inner scroller consumes the event; the list must not scroll.
799        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}