Skip to main content

gpui_base/
scrollable_mask.rs

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
22/// Offsets closer than this count as unchanged, so a sub-pixel residue left at
23/// an edge does not read as room to scroll.
24const CLAIM_EPSILON: Pixels = px(0.5);
25
26/// A scroll step that a horizontal [`ScrollableMask`] used to move its content.
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct HorizontalScrollClaim {
29    /// When the step was handled.
30    at: Instant,
31    /// How far the content moved: positive moves it right (reveals what is on
32    /// the left), negative moves it left.
33    delta_x: Pixels,
34}
35
36impl HorizontalScrollClaim {
37    /// When the step was handled.
38    pub fn at(&self) -> Instant {
39        self.at
40    }
41
42    /// How far the content moved: positive moves it right, negative moves it left.
43    pub fn delta_x(&self) -> Pixels {
44        self.delta_x
45    }
46}
47
48/// The last scroll step a horizontal [`ScrollableMask`] used to move its
49/// content, i.e. one that changed the clamped offset rather than pushing
50/// against an edge.
51///
52/// Hosts that put their own pan gesture over GPUI content (e.g. a swipe that
53/// opens a side drawer on mobile) use it to let a horizontal strip such as a
54/// markdown table scroll first: while the strip still has room in the swipe's
55/// direction it claims the swipe; once it reaches that edge the claims stop and
56/// the host may take over. Read on the thread that dispatches input.
57pub fn last_horizontal_scroll_claim() -> Option<HorizontalScrollClaim> {
58    LAST_HORIZONTAL_SCROLL_CLAIM.get()
59}
60
61/// Default element id for a mask: the call site, so two masks built in
62/// different places never share their per-gesture axis lock.
63#[inline]
64#[track_caller]
65fn caller_id() -> ElementId {
66    ElementId::CodeLocation(*std::panic::Location::caller())
67}
68
69/// A horizontal scroll viewport that only consumes horizontal wheel deltas.
70///
71/// GPUI's native `overflow_x_scroll` maps vertical wheel input onto horizontal
72/// scrolling when there is no vertical overflow. This wrapper keeps the visual
73/// clipping and scroll offset, while delegating wheel input to [`ScrollableMask`]
74/// so vertical wheel events can continue bubbling to the parent scroller.
75pub(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    // The mask must be a sibling of the scrolled element (like in Table), not
84    // a child of it: children are prepainted with the scroll offset applied,
85    // which would slide the mask away from the viewport as the content
86    // scrolls, leaving the uncovered part to the parent scroller.
87    //
88    // The frame cover is a sibling for the same reason: it keeps the rounded
89    // corners clean at every scroll offset (see [`RoundedFrameCover`]).
90    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
117/// Keeps a rounded scroll viewport's corners clean at every scroll offset.
118///
119/// GPUI clips children with a rectangular content mask, so content scrolled
120/// under a rounded frame paints square into the corner notches — the regions
121/// inside the frame's rect corners but outside its border arcs. Rounding the
122/// content itself (e.g. a table's first row) only helps while its own corners
123/// sit at the viewport corners; once the content scrolls, the clipped edge
124/// meets the notch square again. The cover fills each notch with the backdrop
125/// color, which reads as a rounded clip. The frame's own border needs no help:
126/// gpui paints an element's border after its children, so it already draws
127/// over both the scrolled content and these covers.
128///
129/// Like [`ScrollableMask`], it must be a sibling of the scrolled element so it
130/// does not move with the scroll offset.
131pub struct RoundedFrameCover {
132    corner_radii: Corners<Option<gpui::AbsoluteLength>>,
133    backdrop: Option<Hsla>,
134    frame_border: Pixels,
135}
136
137impl RoundedFrameCover {
138    /// A frame with the same radius on all four corners.
139    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    /// The frame's border width, when the cover is a child of the bordered
154    /// element itself: the cover's bounds are then the content box, so the
155    /// painted notches are grown outward by this width to reach the border
156    /// box. The border itself needs no repaint — gpui paints an element's
157    /// border after its children, so the frame's own border already draws
158    /// over the covers.
159    pub fn frame_border(mut self, width: Pixels) -> Self {
160        self.frame_border = width;
161        self
162    }
163
164    /// The color behind the frame, used to fill the corner notches.
165    /// Defaults to the theme background.
166    pub fn backdrop(mut self, color: Hsla) -> Self {
167        self.backdrop = Some(color);
168        self
169    }
170}
171
172impl Element for RoundedFrameCover {
173    type RequestLayoutState = ();
174    type PrepaintState = Bounds<Pixels>;
175
176    fn id(&self) -> Option<ElementId> {
177        None
178    }
179
180    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
181        None
182    }
183
184    fn request_layout(
185        &mut self,
186        _: Option<&GlobalElementId>,
187        _: Option<&gpui::InspectorElementId>,
188        window: &mut Window,
189        cx: &mut App,
190    ) -> (LayoutId, Self::RequestLayoutState) {
191        // Same layout trick as `ScrollableMask`: absolute and parent-sized.
192        let mut style = Style::default();
193        style.position = Position::Absolute;
194        style.flex_grow = 1.0;
195        style.flex_shrink = 1.0;
196        style.size.width = relative(1.).into();
197        style.size.height = relative(1.).into();
198
199        (window.request_layout(style, None, cx), ())
200    }
201
202    fn prepaint(
203        &mut self,
204        _: Option<&GlobalElementId>,
205        _: Option<&gpui::InspectorElementId>,
206        bounds: Bounds<Pixels>,
207        _: &mut Self::RequestLayoutState,
208        _: &mut Window,
209        _: &mut App,
210    ) -> Self::PrepaintState {
211        // Shift up by one height to cover the viewport, like `ScrollableMask`.
212        Bounds {
213            origin: Point {
214                x: bounds.origin.x,
215                y: bounds.origin.y - bounds.size.height,
216            },
217            size: bounds.size,
218        }
219    }
220
221    fn paint(
222        &mut self,
223        _: Option<&GlobalElementId>,
224        _: Option<&gpui::InspectorElementId>,
225        _: Bounds<Pixels>,
226        _: &mut Self::RequestLayoutState,
227        cover_bounds: &mut Self::PrepaintState,
228        window: &mut Window,
229        cx: &mut App,
230    ) {
231        use crate::theme::ActiveTheme as _;
232
233        let mut bounds = *cover_bounds;
234        if !self.frame_border.is_zero() {
235            bounds.origin.x -= self.frame_border;
236            bounds.origin.y -= self.frame_border;
237            bounds.size.width += self.frame_border * 2.;
238            bounds.size.height += self.frame_border * 2.;
239        }
240        let rem_size = window.rem_size();
241        let resolve = |corner: Option<gpui::AbsoluteLength>| {
242            corner
243                .map(|radius| radius.to_pixels(rem_size))
244                .filter(|radius| !radius.is_zero())
245        };
246        let radii = Corners {
247            top_left: resolve(self.corner_radii.top_left),
248            top_right: resolve(self.corner_radii.top_right),
249            bottom_left: resolve(self.corner_radii.bottom_left),
250            bottom_right: resolve(self.corner_radii.bottom_right),
251        };
252        if radii.top_left.is_none()
253            && radii.top_right.is_none()
254            && radii.bottom_left.is_none()
255            && radii.bottom_right.is_none()
256        {
257            return;
258        }
259
260        let backdrop = self.backdrop.unwrap_or(cx.theme().tokens.colors.background);
261        let corners = [
262            (bounds.origin, 1., 1., radii.top_left),
263            (bounds.top_right(), -1., 1., radii.top_right),
264            (bounds.bottom_right(), -1., -1., radii.bottom_right),
265            (
266                Point {
267                    x: bounds.origin.x,
268                    y: bounds.bottom_right().y,
269                },
270                1.,
271                -1.,
272                radii.bottom_left,
273            ),
274        ];
275        for (corner, x_dir, y_dir, radius) in corners {
276            let Some(radius) = radius else { continue };
277            if let Some(path) = corner_notch_path(corner, x_dir, y_dir, radius) {
278                window.paint_path(path, backdrop);
279            }
280        }
281    }
282}
283
284/// The notch at one frame corner: the square of side `radius` anchored at
285/// `corner`, minus the quarter disc of the border arc. `x_dir`/`y_dir` point
286/// from the corner toward the frame's inside (`±1`).
287fn corner_notch_path(
288    corner: Point<Pixels>,
289    x_dir: f32,
290    y_dir: f32,
291    radius: Pixels,
292) -> Option<gpui::Path> {
293    let mut builder = gpui::PathBuilder::fill();
294    builder.move_to(corner);
295    builder.line_to(Point {
296        x: corner.x + radius * x_dir,
297        y: corner.y,
298    });
299    builder.arc_to(
300        Point {
301            x: radius,
302            y: radius,
303        },
304        px(0.),
305        false,
306        // The quarter arc nearest the corner: counterclockwise when the two
307        // inward directions agree in sign, clockwise otherwise.
308        x_dir * y_dir < 0.,
309        Point {
310            x: corner.x,
311            y: corner.y + radius * y_dir,
312        },
313    );
314    builder.close();
315    builder.build().ok()
316}
317
318/// Make a scrollable mask element to cover the parent view with the mouse wheel event listening.
319///
320/// When the mouse wheel is scrolled, will move the `scroll_handle` scrolling with the `axis` direction.
321/// You can use this `scroll_handle` to control what you want to scroll.
322/// This is only can handle once axis scrolling.
323///
324/// Axis-dominant wheel events are consumed in the capture phase, so the mask
325/// wins over ancestor scrollers (e.g. `gpui::list`) that register their
326/// listeners after their children; events dominated by the other axis keep
327/// propagating. The mask stays inert while occluded.
328///
329/// Dominance is decided per gesture, not per event: a precise (trackpad) delta
330/// locks onto the axis its gesture started on, so mid-swipe wobble cannot flip
331/// which mask consumes the events. Line deltas keep the per-event comparison.
332///
333/// At the scroll edge the two axes differ, matching platform scrollers:
334/// a vertical mask hands the event over to the ancestor scroller (CSS
335/// `overscroll-behavior: auto` chaining), while a horizontal mask keeps
336/// consuming it — a bubbled horizontal delta would get mapped onto a
337/// vertical-only ancestor by gpui's own wheel listener (see #2468).
338///
339/// A mouse wheel has no horizontal axis, so a horizontal mask leaves it to the
340/// parent. Over a native horizontal scroller, [`Self::vertical_wheel`] scrolls
341/// sideways with it instead.
342pub struct ScrollableMask<H: ScrollbarHandle + Clone = ScrollHandle> {
343    axis: Axis,
344    id: ElementId,
345    scroll_handle: H,
346    /// Only turn a plain wheel's vertical lines into horizontal scrolling,
347    /// leaving every other event to the scroller below.
348    vertical_wheel: bool,
349    debug: Option<Hsla>,
350}
351
352impl<H: ScrollbarHandle + Clone> ScrollableMask<H> {
353    /// Create a new scrollable mask element.
354    #[track_caller]
355    pub fn new(axis: Axis, scroll_handle: &H) -> Self {
356        Self {
357            scroll_handle: scroll_handle.clone(),
358            axis,
359            id: caller_id(),
360            vertical_wheel: false,
361            debug: None,
362        }
363    }
364
365    /// Create a mask over a native horizontal scroller — one with
366    /// `overflow_x_scroll` and a locked scroll axis, such as a strip of tabs —
367    /// that scrolls it sideways with a plain mouse wheel's vertical lines, the
368    /// only axis such a wheel has.
369    ///
370    /// Once the scroller cannot move that way, the wheel goes on to the parent,
371    /// so a page still scrolls past the strip. Trackpad gestures and
372    /// horizontal wheels are left to the scroller, with its own axis lock and
373    /// bounce.
374    #[track_caller]
375    pub fn vertical_wheel(scroll_handle: &H) -> Self {
376        Self {
377            vertical_wheel: true,
378            ..Self::new(Axis::Horizontal, scroll_handle)
379        }
380    }
381
382    /// Set a specific element id, default is the [`std::panic::Location::caller`].
383    ///
384    /// Only needed when one call site creates several masks of the same axis,
385    /// which would otherwise share their gesture axis lock.
386    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
387        self.id = id.into();
388        self
389    }
390
391    /// Enable the debug border, to show the mask bounds.
392    #[allow(dead_code)]
393    pub fn debug(mut self) -> Self {
394        self.debug = Some(gpui::yellow());
395        self
396    }
397}
398
399impl<H: ScrollbarHandle + Clone> Element for ScrollableMask<H> {
400    type RequestLayoutState = ();
401    type PrepaintState = Hitbox;
402
403    // An id is needed to keep the gesture's axis lock across frames. The axis
404    // suffix keeps both masks of one scroller apart when they share an id.
405    fn id(&self) -> Option<ElementId> {
406        let axis = match self.axis {
407            Axis::Horizontal => "horizontal",
408            Axis::Vertical => "vertical",
409        };
410
411        Some((self.id.clone(), axis).into())
412    }
413
414    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
415        None
416    }
417
418    fn request_layout(
419        &mut self,
420        _: Option<&GlobalElementId>,
421        _: Option<&gpui::InspectorElementId>,
422        window: &mut Window,
423        cx: &mut App,
424    ) -> (LayoutId, Self::RequestLayoutState) {
425        let mut style = Style::default();
426        // Cover the parent whatever its layout: pinned to its top-left corner
427        // rather than left at a static position that depends on whether the
428        // parent stacks its children in a column or a row.
429        style.position = Position::Absolute;
430        style.inset.top = px(0.).into();
431        style.inset.left = px(0.).into();
432        style.flex_grow = 1.0;
433        style.flex_shrink = 1.0;
434        style.size.width = relative(1.).into();
435        style.size.height = relative(1.).into();
436
437        (window.request_layout(style, None, cx), ())
438    }
439
440    fn prepaint(
441        &mut self,
442        _: Option<&GlobalElementId>,
443        _: Option<&gpui::InspectorElementId>,
444        bounds: Bounds<Pixels>,
445        _: &mut Self::RequestLayoutState,
446        window: &mut Window,
447        _: &mut App,
448    ) -> Self::PrepaintState {
449        window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal)
450    }
451
452    fn paint(
453        &mut self,
454        global_id: Option<&GlobalElementId>,
455        _: Option<&gpui::InspectorElementId>,
456        _: Bounds<Pixels>,
457        _: &mut Self::RequestLayoutState,
458        hitbox: &mut Self::PrepaintState,
459        window: &mut Window,
460        _: &mut App,
461    ) {
462        let is_horizontal = self.axis.is_horizontal();
463        let vertical_wheel = self.vertical_wheel;
464        let line_height = window.line_height();
465        let bounds = hitbox.bounds;
466        let ongoing_scroll = global_id
467            .map(|global_id| {
468                window.with_element_state::<Rc<RefCell<OngoingScroll>>, _>(global_id, |state, _| {
469                    let state = state.unwrap_or_default();
470                    (state.clone(), state)
471                })
472            })
473            .unwrap_or_default();
474
475        window.with_content_mask(Some(ContentMask { bounds }), |window| {
476            if let Some(color) = self.debug {
477                window.paint_quad(PaintQuad {
478                    bounds,
479                    border_widths: Edges::all(px(1.0)),
480                    border_color: color,
481                    background: gpui::transparent_white().into(),
482                    corner_radii: Corners::all(px(0.)),
483                    border_style: BorderStyle::default(),
484                });
485            }
486
487            window.on_mouse_event({
488                let view_id = window.current_view();
489                let scroll_handle = self.scroll_handle.clone();
490                let hitbox_id = hitbox.id;
491                let ongoing_scroll = ongoing_scroll.clone();
492
493                move |event: &ScrollEvent, phase, window, cx| {
494                    // Handle in the capture phase: ancestor scrollers such as
495                    // `gpui::list` register their wheel listeners after their
496                    // children paint, so in the bubble phase (reverse
497                    // registration order) they run first and would consume the
498                    // vertical component of a trackpad swipe before this mask
499                    // could stop the propagation.
500                    //
501                    // `should_handle_scroll` (instead of a raw bounds check)
502                    // keeps the mask inert when it is occluded, e.g. below an
503                    // open dialog or context menu.
504                    if !(phase.capture() && hitbox_id.should_handle_scroll(window)) {
505                        return;
506                    }
507
508                    let mut offset = scroll_handle.offset();
509                    let mut delta = event.delta.pixel_delta(line_height);
510
511                    // A plain mouse wheel's vertical lines move the scroller
512                    // sideways; once it is at its edge the parent scrolls
513                    // instead, as for a vertical mask.
514                    if vertical_wheel {
515                        let ScrollDelta::Lines(lines) = event.delta else {
516                            return;
517                        };
518                        if lines.x != 0. || lines.y == 0. || !lines.y.is_finite() {
519                            return;
520                        }
521                        let axis_max = (scroll_handle.content_size().width
522                            - scroll_handle.viewport_bounds().size.width)
523                            .max(px(0.));
524                        let current = offset.x.clamp(-axis_max, px(0.));
525                        let new_offset = (current + delta.y).clamp(-axis_max, px(0.));
526                        if new_offset == current {
527                            return;
528                        }
529
530                        offset.x = new_offset;
531                        scroll_handle.set_offset(offset);
532                        cx.notify(view_id);
533                        cx.stop_propagation();
534                        return;
535                    }
536
537                    // With nothing to scroll sideways, a swipe that moves
538                    // vertically at all belongs to the parent scroller.
539                    if is_horizontal
540                        && !delta.y.is_zero()
541                        && scroll_handle.content_size().width
542                            <= scroll_handle.viewport_bounds().size.width
543                    {
544                        return;
545                    }
546
547                    // Lock the gesture to the axis it started on, so a diagonal
548                    // trackpad swipe cannot flip which mask consumes it from one
549                    // event to the next. Line deltas carry no touch phase.
550                    if event.delta.precise() {
551                        ongoing_scroll
552                            .borrow_mut()
553                            .lock_axis(&mut delta, event.touch_phase);
554                    }
555
556                    // Limit for only one way scrolling at same time.
557                    // When use MacBook touchpad we may get both x and y delta,
558                    // only allows the one that more to scroll.
559                    if !delta.x.is_zero() && !delta.y.is_zero() {
560                        if delta.x.abs() > delta.y.abs() {
561                            delta.y = px(0.);
562                        } else {
563                            delta.x = px(0.);
564                        }
565                    }
566
567                    if !is_horizontal {
568                        // The current offset must be clamped too: after a
569                        // bubbled event, the scrolled element's own listener
570                        // pushes the shared offset beyond the edge unclamped
571                        // (the div only clamps on prepaint), and that
572                        // transient overscroll would read as "room to scroll".
573                        // `ScrollbarHandle` has no `max_offset`; recover it from
574                        // the definition `content_size = viewport + max_offset`.
575                        let axis_max = (scroll_handle.content_size().height
576                            - scroll_handle.viewport_bounds().size.height)
577                            .max(px(0.));
578                        let current = offset.y.clamp(-axis_max, px(0.));
579                        let new_offset = (current + delta.y).clamp(-axis_max, px(0.));
580                        if new_offset == current {
581                            // At the edge or no overflow: bubble to the parent.
582                            return;
583                        }
584
585                        offset.y = new_offset;
586                        scroll_handle.set_offset(offset);
587                        cx.notify(view_id);
588                        cx.stop_propagation();
589                        return;
590                    }
591
592                    // Record whether this step actually moves the content
593                    // (see [`last_horizontal_scroll_claim`]). The current offset
594                    // is clamped for comparison only: the next offset must use
595                    // the raw value, which may sit past the edge until prepaint.
596                    if !delta.x.is_zero() {
597                        let axis_max = (scroll_handle.content_size().width
598                            - scroll_handle.viewport_bounds().size.width)
599                            .max(px(0.));
600                        let current = offset.x.clamp(-axis_max, px(0.));
601                        let moved = (offset.x + delta.x).clamp(-axis_max, px(0.)) - current;
602                        if moved.abs() >= CLAIM_EPSILON {
603                            LAST_HORIZONTAL_SCROLL_CLAIM.set(Some(HorizontalScrollClaim {
604                                at: Instant::now(),
605                                delta_x: moved,
606                            }));
607                        }
608                    }
609
610                    offset.x += delta.x;
611
612                    // NOTE: `set_offset` does not clamp (clamping happens in
613                    // the div's prepaint), so any non-zero horizontal-dominant
614                    // delta passes this guard — even at the scroll edge the
615                    // event is consumed rather than turned into a parent
616                    // scroll.
617                    if offset != scroll_handle.offset() {
618                        scroll_handle.set_offset(offset);
619                        cx.notify(view_id);
620                        cx.stop_propagation();
621                    }
622                }
623            });
624        });
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use gpui::{
632        Context, IntoElement, ListAlignment, ListState, Render, ScrollDelta, ScrollEvent,
633        TestAppContext, VisualTestContext, Window, div, list, point, px,
634    };
635
636    // A built `Path` no longer exposes its bounds, so only check that every
637    // corner's notch builds.
638    #[test]
639    fn corner_notch_paths_build_for_every_corner() {
640        let width = px(200.);
641        let height = px(100.);
642        let radius = px(8.);
643        let cases = [
644            ("top left", point(px(0.), px(0.)), 1., 1.),
645            ("top right", point(width, px(0.)), -1., 1.),
646            ("bottom right", point(width, height), -1., -1.),
647            ("bottom left", point(px(0.), height), 1., -1.),
648        ];
649        for (name, corner, x_dir, y_dir) in cases {
650            assert!(
651                corner_notch_path(corner, x_dir, y_dir, radius).is_some(),
652                "{name}: the notch must build"
653            );
654        }
655    }
656
657    struct HorizontalScrollAreaTest {
658        scroll_handle: ScrollHandle,
659    }
660
661    impl Render for HorizontalScrollAreaTest {
662        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
663            div().w(px(100.)).h(px(40.)).child(horizontal_scroll_area(
664                "horizontal-scroll-area",
665                &self.scroll_handle,
666                &Default::default(),
667                div().w(px(300.)).h(px(40.)),
668            ))
669        }
670    }
671
672    #[gpui::test]
673    fn horizontal_scroll_area_ignores_vertical_wheel(cx: &mut TestAppContext) {
674        let scroll_handle = ScrollHandle::new();
675        let (_, cx) = cx.add_window_view({
676            let scroll_handle = scroll_handle.clone();
677            move |_, _| HorizontalScrollAreaTest { scroll_handle }
678        });
679        let cx: &mut VisualTestContext = cx;
680        cx.run_until_parked();
681        cx.update(|window, cx| {
682            _ = window.draw(cx);
683        });
684
685        cx.simulate_event(ScrollEvent {
686            position: point(px(10.), px(10.)),
687            delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
688            ..Default::default()
689        });
690
691        assert_eq!(scroll_handle.offset().x, px(0.));
692    }
693
694    /// Reproduces the markdown table case: the scroll area lives inside a
695    /// `gpui::list` item. The list registers its wheel listener after its
696    /// items paint, so in the bubble phase (reverse registration order) the
697    /// list runs first and consumes `delta.y` of every trackpad swipe.
698    struct ListWithHorizontalAreaTest {
699        scroll_handle: ScrollHandle,
700        list_state: ListState,
701        occluded: bool,
702    }
703
704    impl Render for ListWithHorizontalAreaTest {
705        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
706            let scroll_handle = self.scroll_handle.clone();
707            let mut root = div().w(px(100.)).h(px(100.)).child(
708                list(self.list_state.clone(), move |ix, _, _| {
709                    if ix == 0 {
710                        horizontal_scroll_area(
711                            "horizontal-scroll-area",
712                            &scroll_handle,
713                            &Default::default(),
714                            div().w(px(300.)).h(px(40.)),
715                        )
716                        .into_any_element()
717                    } else {
718                        div().w(px(100.)).h(px(40.)).into_any_element()
719                    }
720                })
721                .w_full()
722                .h_full(),
723            );
724            if self.occluded {
725                // An overlay above the list, like an open dialog or menu.
726                root = root.child(div().absolute().top_0().left_0().size_full().occlude());
727            }
728            root
729        }
730    }
731
732    fn setup_list_test<'a>(
733        cx: &'a mut TestAppContext,
734        scroll_handle: &ScrollHandle,
735        list_state: &ListState,
736        occluded: bool,
737    ) -> &'a mut VisualTestContext {
738        let (_, cx) = cx.add_window_view({
739            let scroll_handle = scroll_handle.clone();
740            let list_state = list_state.clone();
741            move |_, _| ListWithHorizontalAreaTest {
742                scroll_handle: scroll_handle.clone(),
743                list_state: list_state.clone(),
744                occluded,
745            }
746        });
747        cx.run_until_parked();
748        cx.update(|window, cx| {
749            _ = window.draw(cx);
750        });
751        cx
752    }
753
754    #[gpui::test]
755    fn horizontal_scroll_area_in_list_keeps_horizontal_dominant_wheel(cx: &mut TestAppContext) {
756        let scroll_handle = ScrollHandle::new();
757        let list_state = ListState::new(10, ListAlignment::Top, px(0.));
758        let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
759
760        // A trackpad swipe is rarely axis-pure: horizontal dominant with a
761        // small vertical component.
762        cx.simulate_event(ScrollEvent {
763            position: point(px(10.), px(10.)),
764            delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
765            ..Default::default()
766        });
767
768        // The area consumes the horizontal delta...
769        assert_eq!(scroll_handle.offset().x, px(-40.));
770        // ...and the outer list must not scroll vertically.
771        let scroll_top = list_state.logical_scroll_top();
772        assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
773    }
774
775    #[gpui::test]
776    fn horizontal_scroll_area_in_list_bubbles_vertical_dominant_wheel(cx: &mut TestAppContext) {
777        let scroll_handle = ScrollHandle::new();
778        let list_state = ListState::new(10, ListAlignment::Top, px(0.));
779        let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
780
781        cx.simulate_event(ScrollEvent {
782            position: point(px(10.), px(10.)),
783            delta: ScrollDelta::Pixels(point(px(-10.), px(-40.))),
784            ..Default::default()
785        });
786
787        // Vertical dominant: the list scrolls, the area does not.
788        assert_eq!(scroll_handle.offset().x, px(0.));
789        let scroll_top = list_state.logical_scroll_top();
790        assert_ne!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
791    }
792
793    /// A list whose first row is a horizontal scroll area with content that
794    /// fits, like a narrow Markdown table.
795    struct ListWithFittingAreaTest(ListState);
796
797    impl Render for ListWithFittingAreaTest {
798        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
799            div().w(px(100.)).h(px(100.)).child(
800                list(self.0.clone(), |ix, _, _| {
801                    if ix == 0 {
802                        horizontal_scroll_area(
803                            "fitting-area",
804                            &ScrollHandle::new(),
805                            &Default::default(),
806                            div().w(px(50.)).h(px(40.)),
807                        )
808                        .into_any_element()
809                    } else {
810                        div().w(px(100.)).h(px(40.)).into_any_element()
811                    }
812                })
813                .w_full()
814                .h_full(),
815            )
816        }
817    }
818
819    #[gpui::test]
820    fn horizontal_scroll_area_that_fits_bubbles_horizontal_dominant_wheel(cx: &mut TestAppContext) {
821        let list_state = ListState::new(10, ListAlignment::Top, px(0.));
822        let (_, cx) = cx.add_window_view({
823            let list_state = list_state.clone();
824            move |_, _| ListWithFittingAreaTest(list_state)
825        });
826        cx.update(|window, cx| {
827            _ = window.draw(cx);
828        });
829
830        cx.simulate_event(ScrollEvent {
831            position: point(px(10.), px(10.)),
832            delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
833            ..Default::default()
834        });
835        // Nothing to scroll sideways: the list takes the swipe.
836        let scroll_top = list_state.logical_scroll_top();
837        assert_ne!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
838    }
839
840    /// A `MessageScroller`-shaped nesting: a `gpui::list` with a vertical
841    /// mask bound to its `ListState`, inside an ancestor vertical scroller.
842    struct ListWithVerticalMaskTest {
843        outer_handle: ScrollHandle,
844        list_state: ListState,
845    }
846
847    impl Render for ListWithVerticalMaskTest {
848        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
849            div()
850                .id("outer")
851                .w(px(100.))
852                .h(px(100.))
853                .overflow_y_scroll()
854                .track_scroll(&self.outer_handle)
855                .child(
856                    div().w_full().h(px(400.)).child(
857                        div()
858                            .relative()
859                            .w_full()
860                            .h(px(80.))
861                            .overflow_hidden()
862                            .child(
863                                list(self.list_state.clone(), |_, _, _| {
864                                    div().w_full().h(px(40.)).into_any_element()
865                                })
866                                .w_full()
867                                .h_full(),
868                            )
869                            .child(ScrollableMask::new(Axis::Vertical, &self.list_state)),
870                    ),
871                )
872        }
873    }
874
875    fn setup_vertical_mask_test<'a>(
876        cx: &'a mut TestAppContext,
877        outer_handle: &ScrollHandle,
878        list_state: &ListState,
879    ) -> &'a mut VisualTestContext {
880        let (_, cx) = cx.add_window_view({
881            let outer_handle = outer_handle.clone();
882            let list_state = list_state.clone();
883            move |_, _| ListWithVerticalMaskTest {
884                outer_handle: outer_handle.clone(),
885                list_state,
886            }
887        });
888        cx.run_until_parked();
889        cx.update(|window, cx| {
890            _ = window.draw(cx);
891        });
892        cx
893    }
894
895    #[gpui::test]
896    fn vertical_mask_contains_wheel_inside_the_list(cx: &mut TestAppContext) {
897        let outer_handle = ScrollHandle::new();
898        // A large overdraw measures every row up front, so the mask sees the
899        // full content height.
900        let list_state = ListState::new(10, ListAlignment::Top, px(1000.));
901        let cx = setup_vertical_mask_test(cx, &outer_handle, &list_state);
902
903        cx.simulate_event(ScrollEvent {
904            position: point(px(10.), px(10.)),
905            delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
906            ..Default::default()
907        });
908
909        // The inner list consumes the wheel; the ancestor must not move.
910        assert_eq!(list_state.scroll_px_offset_for_scrollbar().y, px(-40.));
911        assert_eq!(outer_handle.offset().y, px(0.));
912    }
913
914    #[gpui::test]
915    fn vertical_mask_chains_to_the_ancestor_at_the_edge(cx: &mut TestAppContext) {
916        let outer_handle = ScrollHandle::new();
917        let list_state = ListState::new(10, ListAlignment::Top, px(1000.));
918        // Start the inner list at its bottom edge (400 - 80 = 320).
919        list_state.scroll_to(gpui::ListOffset {
920            item_ix: 8,
921            offset_in_item: px(0.),
922        });
923        let cx = setup_vertical_mask_test(cx, &outer_handle, &list_state);
924
925        cx.simulate_event(ScrollEvent {
926            position: point(px(10.), px(10.)),
927            delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
928            ..Default::default()
929        });
930
931        // At the edge the mask lets the event bubble to the ancestor.
932        assert_eq!(list_state.scroll_px_offset_for_scrollbar().y, px(-320.));
933        assert_eq!(outer_handle.offset().y, px(-40.));
934    }
935
936    #[gpui::test]
937    fn horizontal_scroll_area_covers_viewport_after_scrolled(cx: &mut TestAppContext) {
938        let scroll_handle = ScrollHandle::new();
939        let list_state = ListState::new(10, ListAlignment::Top, px(0.));
940        let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
941
942        // Scroll the area to the middle, then repaint.
943        scroll_handle.set_offset(point(px(-150.), px(0.)));
944        cx.update(|window, cx| {
945            _ = window.draw(cx);
946        });
947
948        // Swipe over the right side of the viewport. The mask must still
949        // cover it — it must not slide away with the scrolled content.
950        cx.simulate_event(ScrollEvent {
951            position: point(px(90.), px(10.)),
952            delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
953            ..Default::default()
954        });
955
956        assert_eq!(scroll_handle.offset().x, px(-190.));
957        let scroll_top = list_state.logical_scroll_top();
958        assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
959    }
960
961    #[gpui::test]
962    fn horizontal_scroll_area_traps_wheel_at_edge(cx: &mut TestAppContext) {
963        let scroll_handle = ScrollHandle::new();
964        let list_state = ListState::new(10, ListAlignment::Top, px(0.));
965        let cx = setup_list_test(cx, &scroll_handle, &list_state, false);
966
967        // Scroll the area to its right edge (300 - 100 = 200).
968        scroll_handle.set_offset(point(px(-200.), px(0.)));
969        cx.update(|window, cx| {
970            _ = window.draw(cx);
971        });
972
973        cx.simulate_event(ScrollEvent {
974            position: point(px(10.), px(10.)),
975            delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
976            ..Default::default()
977        });
978
979        // A horizontal mask consumes even at the edge: a bubbled horizontal
980        // delta would be axis-mapped onto the vertical list (#2468).
981        let scroll_top = list_state.logical_scroll_top();
982        assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
983    }
984
985    #[gpui::test]
986    fn horizontal_scroll_area_ignores_wheel_when_occluded(cx: &mut TestAppContext) {
987        let scroll_handle = ScrollHandle::new();
988        let list_state = ListState::new(10, ListAlignment::Top, px(0.));
989        let cx = setup_list_test(cx, &scroll_handle, &list_state, true);
990
991        cx.simulate_event(ScrollEvent {
992            position: point(px(10.), px(10.)),
993            delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
994            ..Default::default()
995        });
996
997        // An overlay (dialog, context menu) occludes the area: the area
998        // must not scroll underneath it.
999        assert_eq!(scroll_handle.offset().x, px(0.));
1000    }
1001
1002    #[gpui::test]
1003    fn horizontal_scroll_area_uses_horizontal_wheel(cx: &mut TestAppContext) {
1004        let scroll_handle = ScrollHandle::new();
1005        let (_, cx) = cx.add_window_view({
1006            let scroll_handle = scroll_handle.clone();
1007            move |_, _| HorizontalScrollAreaTest { scroll_handle }
1008        });
1009        let cx: &mut VisualTestContext = cx;
1010        cx.run_until_parked();
1011        cx.update(|window, cx| {
1012            _ = window.draw(cx);
1013        });
1014
1015        cx.simulate_event(ScrollEvent {
1016            position: point(px(10.), px(10.)),
1017            delta: ScrollDelta::Pixels(point(px(-40.), px(0.))),
1018            ..Default::default()
1019        });
1020
1021        assert_eq!(scroll_handle.offset().x, px(-40.));
1022    }
1023
1024    #[gpui::test]
1025    fn horizontal_scroll_area_claims_only_steps_that_move(cx: &mut TestAppContext) {
1026        let scroll_handle = ScrollHandle::new();
1027        let (_, cx) = cx.add_window_view({
1028            let scroll_handle = scroll_handle.clone();
1029            move |_, _| HorizontalScrollAreaTest { scroll_handle }
1030        });
1031        let cx: &mut VisualTestContext = cx;
1032        cx.run_until_parked();
1033        cx.update(|window, cx| {
1034            _ = window.draw(cx);
1035        });
1036
1037        // At the left edge, a swipe toward the start has no room: no claim.
1038        LAST_HORIZONTAL_SCROLL_CLAIM.set(None);
1039        cx.simulate_event(ScrollEvent {
1040            position: point(px(10.), px(10.)),
1041            delta: ScrollDelta::Pixels(point(px(40.), px(0.))),
1042            ..Default::default()
1043        });
1044        assert!(last_horizontal_scroll_claim().is_none());
1045
1046        // The overscroll only lasts until the next prepaint clamps it, and
1047        // `simulate_event` draws after each event, so dispatch these steps
1048        // within one update.
1049        cx.update(|window, cx| {
1050            let mut dispatch = |delta_x: f32| {
1051                window.dispatch_event(
1052                    gpui::PlatformInput::Scroll(ScrollEvent {
1053                        position: point(px(10.), px(10.)),
1054                        delta: ScrollDelta::Pixels(point(px(delta_x), px(0.))),
1055                        ..Default::default()
1056                    }),
1057                    cx,
1058                );
1059            };
1060
1061            // Reversing an overscroll without re-entering the range does not
1062            // move content.
1063            scroll_handle.set_offset(point(px(40.), px(0.)));
1064            dispatch(-10.);
1065            assert!(last_horizontal_scroll_claim().is_none());
1066            assert_eq!(scroll_handle.offset().x, px(30.));
1067
1068            // Only the part of a step that re-enters the range counts as movement.
1069            dispatch(-40.);
1070        });
1071        let claim = last_horizontal_scroll_claim().expect("a moving step claims");
1072        assert_eq!(claim.delta_x(), px(-10.));
1073        assert_eq!(scroll_handle.offset().x, px(-10.));
1074
1075        // Ignored input keeps the last meaningful claim intact.
1076        for delta in [point(px(0.), px(-40.)), point(px(-0.25), px(0.))] {
1077            cx.simulate_event(ScrollEvent {
1078                position: point(px(10.), px(10.)),
1079                delta: ScrollDelta::Pixels(delta),
1080                ..Default::default()
1081            });
1082            assert_eq!(last_horizontal_scroll_claim(), Some(claim));
1083        }
1084    }
1085
1086    fn setup_horizontal_area_test<'a>(
1087        cx: &'a mut TestAppContext,
1088        scroll_handle: &ScrollHandle,
1089    ) -> &'a mut VisualTestContext {
1090        let (_, cx) = cx.add_window_view({
1091            let scroll_handle = scroll_handle.clone();
1092            move |_, _| HorizontalScrollAreaTest { scroll_handle }
1093        });
1094        let cx: &mut VisualTestContext = cx;
1095        cx.run_until_parked();
1096        cx.update(|window, cx| {
1097            _ = window.draw(cx);
1098        });
1099        cx
1100    }
1101
1102    #[gpui::test]
1103    fn horizontal_mask_keeps_axis_lock_within_a_gesture(cx: &mut TestAppContext) {
1104        let scroll_handle = ScrollHandle::new();
1105        let cx = setup_horizontal_area_test(cx, &scroll_handle);
1106
1107        cx.simulate_event(ScrollEvent {
1108            position: point(px(10.), px(10.)),
1109            delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
1110            ..Default::default()
1111        });
1112        assert_eq!(scroll_handle.offset().x, px(-40.));
1113
1114        // Same gesture, now leaning vertical but under the unlock ratio: the
1115        // lock holds and the horizontal offset keeps moving. Comparing this
1116        // event alone would zero `delta.x` and stall the scroller at -40.
1117        cx.simulate_event(ScrollEvent {
1118            position: point(px(10.), px(10.)),
1119            delta: ScrollDelta::Pixels(point(px(-10.), px(-15.))),
1120            ..Default::default()
1121        });
1122        assert_eq!(scroll_handle.offset().x, px(-50.));
1123    }
1124
1125    #[gpui::test]
1126    fn horizontal_mask_releases_axis_lock_on_a_strong_turn(cx: &mut TestAppContext) {
1127        let scroll_handle = ScrollHandle::new();
1128        let cx = setup_horizontal_area_test(cx, &scroll_handle);
1129
1130        cx.simulate_event(ScrollEvent {
1131            position: point(px(10.), px(10.)),
1132            delta: ScrollDelta::Pixels(point(px(-40.), px(-10.))),
1133            ..Default::default()
1134        });
1135        assert_eq!(scroll_handle.offset().x, px(-40.));
1136
1137        // Past the unlock ratio the gesture is no longer horizontal, so the
1138        // event stops driving this scroller.
1139        cx.simulate_event(ScrollEvent {
1140            position: point(px(10.), px(10.)),
1141            delta: ScrollDelta::Pixels(point(px(-10.), px(-25.))),
1142            ..Default::default()
1143        });
1144        assert_eq!(scroll_handle.offset().x, px(-40.));
1145    }
1146
1147    /// Reproduces the DataTable case: a vertically scrollable element
1148    /// nested inside an outer vertical scroller.
1149    struct NestedVerticalScrollTest {
1150        outer_handle: ScrollHandle,
1151        inner_handle: ScrollHandle,
1152        inner_content_height: Pixels,
1153    }
1154
1155    impl Render for NestedVerticalScrollTest {
1156        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1157            div()
1158                .id("outer")
1159                .w(px(100.))
1160                .h(px(100.))
1161                .overflow_y_scroll()
1162                .track_scroll(&self.outer_handle)
1163                .child(
1164                    div()
1165                        .relative()
1166                        .w_full()
1167                        .h(px(60.))
1168                        .child(
1169                            div()
1170                                .id("inner")
1171                                .size_full()
1172                                .overflow_y_scroll()
1173                                .track_scroll(&self.inner_handle)
1174                                .child(div().w_full().h(self.inner_content_height)),
1175                        )
1176                        .child(ScrollableMask::new(Axis::Vertical, &self.inner_handle)),
1177                )
1178                .child(div().w_full().h(px(400.)))
1179        }
1180    }
1181
1182    fn setup_nested_vertical_test<'a>(
1183        cx: &'a mut TestAppContext,
1184        outer_handle: &ScrollHandle,
1185        inner_handle: &ScrollHandle,
1186        inner_content_height: Pixels,
1187    ) -> &'a mut VisualTestContext {
1188        let (_, cx) = cx.add_window_view({
1189            let outer_handle = outer_handle.clone();
1190            let inner_handle = inner_handle.clone();
1191            move |_, _| NestedVerticalScrollTest {
1192                outer_handle: outer_handle.clone(),
1193                inner_handle: inner_handle.clone(),
1194                inner_content_height,
1195            }
1196        });
1197        cx.run_until_parked();
1198        cx.update(|window, cx| {
1199            _ = window.draw(cx);
1200        });
1201        cx
1202    }
1203
1204    #[gpui::test]
1205    fn vertical_mask_consumes_wheel_when_scrollable(cx: &mut TestAppContext) {
1206        let outer_handle = ScrollHandle::new();
1207        let inner_handle = ScrollHandle::new();
1208        let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
1209
1210        cx.simulate_event(ScrollEvent {
1211            position: point(px(10.), px(10.)),
1212            delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1213            ..Default::default()
1214        });
1215
1216        // The inner scroller consumes the event; the outer one must not move.
1217        assert_eq!(inner_handle.offset().y, px(-40.));
1218        assert_eq!(outer_handle.offset().y, px(0.));
1219    }
1220
1221    #[gpui::test]
1222    fn vertical_mask_hands_off_to_parent_at_edge(cx: &mut TestAppContext) {
1223        let outer_handle = ScrollHandle::new();
1224        let inner_handle = ScrollHandle::new();
1225        let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
1226
1227        // Scroll the inner element to its bottom edge (300 - 60 = 240).
1228        inner_handle.set_offset(point(px(0.), px(-240.)));
1229        cx.update(|window, cx| {
1230            _ = window.draw(cx);
1231        });
1232
1233        cx.simulate_event(ScrollEvent {
1234            position: point(px(10.), px(10.)),
1235            delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1236            ..Default::default()
1237        });
1238
1239        // At the edge the event bubbles: the outer scroller takes over.
1240        assert_eq!(outer_handle.offset().y, px(-40.));
1241        // The inner offset is clamped back to the edge on the next prepaint.
1242        cx.update(|window, cx| {
1243            _ = window.draw(cx);
1244        });
1245        assert_eq!(inner_handle.offset().y, px(-240.));
1246    }
1247
1248    #[gpui::test]
1249    fn vertical_mask_bubbles_when_no_overflow(cx: &mut TestAppContext) {
1250        let outer_handle = ScrollHandle::new();
1251        let inner_handle = ScrollHandle::new();
1252        // Inner content (40) fits its 60px viewport: nothing to scroll.
1253        let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(40.));
1254
1255        cx.simulate_event(ScrollEvent {
1256            position: point(px(10.), px(10.)),
1257            delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1258            ..Default::default()
1259        });
1260
1261        assert_eq!(outer_handle.offset().y, px(-40.));
1262        cx.update(|window, cx| {
1263            _ = window.draw(cx);
1264        });
1265        assert_eq!(inner_handle.offset().y, px(0.));
1266    }
1267
1268    #[gpui::test]
1269    fn vertical_mask_ignores_transient_overscroll(cx: &mut TestAppContext) {
1270        let outer_handle = ScrollHandle::new();
1271        let inner_handle = ScrollHandle::new();
1272        let cx = setup_nested_vertical_test(cx, &outer_handle, &inner_handle, px(300.));
1273
1274        inner_handle.set_offset(point(px(0.), px(-240.)));
1275        cx.update(|window, cx| {
1276            _ = window.draw(cx);
1277        });
1278
1279        // Two wheel events at the edge with no redraw in between: the first
1280        // one leaves the inner offset beyond the edge unclamped, which must
1281        // not read as "room to scroll" and swallow the second event.
1282        for _ in 0..2 {
1283            cx.simulate_event(ScrollEvent {
1284                position: point(px(10.), px(10.)),
1285                delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1286                ..Default::default()
1287            });
1288        }
1289
1290        assert_eq!(outer_handle.offset().y, px(-80.));
1291        cx.update(|window, cx| {
1292            _ = window.draw(cx);
1293        });
1294        assert_eq!(inner_handle.offset().y, px(-240.));
1295    }
1296
1297    /// The vertical mask nested in a `gpui::list` ancestor: the list
1298    /// registers its wheel listener after its items paint, so only a
1299    /// capture-phase mask can stop it from scrolling on the same event.
1300    struct ListWithVerticalAreaTest {
1301        scroll_handle: ScrollHandle,
1302        list_state: ListState,
1303    }
1304
1305    impl Render for ListWithVerticalAreaTest {
1306        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1307            let scroll_handle = self.scroll_handle.clone();
1308            div().w(px(100.)).h(px(100.)).child(
1309                list(self.list_state.clone(), move |ix, _, _| {
1310                    if ix == 0 {
1311                        div()
1312                            .relative()
1313                            .w_full()
1314                            .h(px(60.))
1315                            .child(
1316                                div()
1317                                    .id("inner")
1318                                    .size_full()
1319                                    .overflow_y_scroll()
1320                                    .track_scroll(&scroll_handle)
1321                                    .child(div().w_full().h(px(300.))),
1322                            )
1323                            .child(ScrollableMask::new(Axis::Vertical, &scroll_handle))
1324                            .into_any_element()
1325                    } else {
1326                        div().w(px(100.)).h(px(40.)).into_any_element()
1327                    }
1328                })
1329                .w_full()
1330                .h_full(),
1331            )
1332        }
1333    }
1334
1335    #[gpui::test]
1336    fn vertical_mask_in_list_consumes_wheel_when_scrollable(cx: &mut TestAppContext) {
1337        let scroll_handle = ScrollHandle::new();
1338        let list_state = ListState::new(10, ListAlignment::Top, px(0.));
1339        let (_, cx) = cx.add_window_view({
1340            let scroll_handle = scroll_handle.clone();
1341            let list_state = list_state.clone();
1342            move |_, _| ListWithVerticalAreaTest {
1343                scroll_handle: scroll_handle.clone(),
1344                list_state,
1345            }
1346        });
1347        cx.run_until_parked();
1348        cx.update(|window, cx| {
1349            _ = window.draw(cx);
1350        });
1351
1352        cx.simulate_event(ScrollEvent {
1353            position: point(px(10.), px(10.)),
1354            delta: ScrollDelta::Pixels(point(px(0.), px(-40.))),
1355            ..Default::default()
1356        });
1357
1358        // The inner scroller consumes the event; the list must not scroll.
1359        assert_eq!(scroll_handle.offset().y, px(-40.));
1360        let scroll_top = list_state.logical_scroll_top();
1361        assert_eq!((scroll_top.item_ix, scroll_top.offset_in_item), (0, px(0.)));
1362    }
1363
1364    /// A 100px strip of 300px content, locked to its axis like a tab strip,
1365    /// with a vertical-wheel mask, inside a vertical scroller.
1366    struct VerticalWheelTest {
1367        strip: ScrollHandle,
1368        page: ScrollHandle,
1369    }
1370
1371    impl Render for VerticalWheelTest {
1372        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1373            div()
1374                .id("page")
1375                .w(px(100.))
1376                .h(px(60.))
1377                .overflow_y_scroll()
1378                .track_scroll(&self.page)
1379                .child(
1380                    div()
1381                        .relative()
1382                        .w(px(100.))
1383                        .h(px(40.))
1384                        .child(
1385                            div()
1386                                .id("strip")
1387                                .size_full()
1388                                .flex()
1389                                .overflow_x_scroll()
1390                                .restrict_scroll_to_axis()
1391                                .track_scroll(&self.strip)
1392                                .child(div().flex_none().w(px(300.)).h(px(40.))),
1393                        )
1394                        .child(ScrollableMask::vertical_wheel(&self.strip)),
1395                )
1396                .child(div().h(px(200.)))
1397        }
1398    }
1399
1400    fn vertical_wheel_test(
1401        cx: &mut TestAppContext,
1402    ) -> (&mut VisualTestContext, ScrollHandle, ScrollHandle) {
1403        let (strip, page) = (ScrollHandle::new(), ScrollHandle::new());
1404        let (_, cx) = cx.add_window_view({
1405            let (strip, page) = (strip.clone(), page.clone());
1406            move |_, _| VerticalWheelTest { strip, page }
1407        });
1408        cx.run_until_parked();
1409        cx.update(|window, cx| window.draw(cx).clear(cx));
1410        (cx, strip, page)
1411    }
1412
1413    fn wheel(cx: &mut VisualTestContext, delta: ScrollDelta) {
1414        cx.simulate_event(ScrollEvent {
1415            position: point(px(10.), px(10.)),
1416            delta,
1417            ..Default::default()
1418        });
1419        cx.update(|window, cx| window.draw(cx).clear(cx));
1420    }
1421
1422    #[gpui::test]
1423    fn vertical_wheel_scrolls_the_strip_and_then_the_parent(cx: &mut TestAppContext) {
1424        let (cx, strip, page) = vertical_wheel_test(cx);
1425        let line_height = cx.update(|window, _| window.line_height());
1426
1427        wheel(cx, ScrollDelta::Lines(point(0., -1.)));
1428        assert_eq!(strip.offset().x, -line_height);
1429        assert_eq!(page.offset().y, px(0.));
1430
1431        // Past the strip's end, the wheel scrolls the page.
1432        wheel(cx, ScrollDelta::Lines(point(0., -100.)));
1433        assert_eq!(strip.offset().x, px(-200.));
1434        assert_eq!(page.offset().y, px(0.));
1435        wheel(cx, ScrollDelta::Lines(point(0., -1.)));
1436        assert_eq!(strip.offset().x, px(-200.));
1437        assert!(page.offset().y < px(0.));
1438
1439        // A delta that is no number does not move the strip.
1440        wheel(cx, ScrollDelta::Lines(point(0., f32::NAN)));
1441        assert_eq!(strip.offset().x, px(-200.));
1442    }
1443
1444    #[gpui::test]
1445    fn vertical_wheel_leaves_trackpads_and_horizontal_wheels_to_the_scroller(
1446        cx: &mut TestAppContext,
1447    ) {
1448        let (cx, strip, page) = vertical_wheel_test(cx);
1449        let line_height = cx.update(|window, _| window.line_height());
1450
1451        // A vertical trackpad swipe keeps the strip's axis lock.
1452        wheel(cx, ScrollDelta::Pixels(point(px(0.), px(-20.))));
1453        assert_eq!(strip.offset().x, px(0.));
1454        assert_eq!(page.offset().y, px(-20.));
1455
1456        // A horizontal wheel reaches the strip's own listener.
1457        wheel(cx, ScrollDelta::Lines(point(-1., 0.)));
1458        assert_eq!(strip.offset().x, -line_height);
1459    }
1460}