Skip to main content

gpui_component/scroll/
scrollable.rs

1use std::{panic::Location, rc::Rc};
2
3use crate::InteractiveElementExt as _;
4
5use super::{Scrollbar, ScrollbarAxis, ScrollbarHandle};
6use gpui::{
7    App, Div, Element, ElementId, InteractiveElement, IntoElement, Overflow, ParentElement,
8    PointRefinement, RenderOnce, ScrollHandle, Stateful, StatefulInteractiveElement,
9    StyleRefinement, Styled, Window, div, prelude::FluentBuilder,
10};
11
12/// A trait for elements that can be made scrollable with scrollbars.
13///
14/// The wrapped element is the scroll area itself, rather than being inserted as
15/// a child of a new scroll area.
16pub trait ScrollableElement: InteractiveElement + Styled + ParentElement + Element {
17    /// Adds a scrollbar to the element.
18    #[track_caller]
19    fn scrollbar<H: ScrollbarHandle + Clone>(
20        self,
21        scroll_handle: &H,
22        axis: impl Into<ScrollbarAxis>,
23    ) -> Self {
24        self.child(ScrollbarLayer {
25            id: caller_id(),
26            axis: axis.into(),
27            scroll_handle: Rc::new(scroll_handle.clone()),
28        })
29    }
30
31    /// Adds a vertical scrollbar to the element.
32    #[track_caller]
33    fn vertical_scrollbar<H: ScrollbarHandle + Clone>(self, scroll_handle: &H) -> Self {
34        self.scrollbar(scroll_handle, ScrollbarAxis::Vertical)
35    }
36
37    /// Adds a horizontal scrollbar to the element.
38    #[track_caller]
39    fn horizontal_scrollbar<H: ScrollbarHandle + Clone>(self, scroll_handle: &H) -> Self {
40        self.scrollbar(scroll_handle, ScrollbarAxis::Horizontal)
41    }
42
43    /// Almost equivalent to [`StatefulInteractiveElement::overflow_scroll`], but adds scrollbars.
44    /// Preserves the source element as the scrollable container.
45    #[track_caller]
46    fn overflow_scrollbar(self) -> Scrollable<Self> {
47        Scrollable::new(self, ScrollbarAxis::Both)
48    }
49
50    /// Almost equivalent to [`StatefulInteractiveElement::overflow_x_scroll`], but adds Horizontal scrollbar.
51    /// Preserves the source element as the scrollable container.
52    #[track_caller]
53    fn overflow_x_scrollbar(self) -> Scrollable<Self> {
54        Scrollable::new(self, ScrollbarAxis::Horizontal)
55    }
56
57    /// Almost equivalent to [`StatefulInteractiveElement::overflow_y_scroll`], but adds Vertical scrollbar.
58    /// Preserves the source element as the scrollable container.
59    #[track_caller]
60    fn overflow_y_scrollbar(self) -> Scrollable<Self> {
61        Scrollable::new(self, ScrollbarAxis::Vertical)
62    }
63}
64
65/// A scrollable element wrapper that renders the original element as the scroll area and overlays scrollbars.
66#[derive(IntoElement)]
67pub struct Scrollable<E: InteractiveElement + Styled + ParentElement + Element> {
68    id: ElementId,
69    element: E,
70    axis: ScrollbarAxis,
71}
72
73impl<E> Scrollable<E>
74where
75    E: InteractiveElement + Styled + ParentElement + Element,
76{
77    #[track_caller]
78    fn new(element: E, axis: impl Into<ScrollbarAxis>) -> Self {
79        Self {
80            id: caller_id(),
81            element,
82            axis: axis.into(),
83        }
84    }
85
86    /// Set a specific element id, default is the [`std::panic::Location::caller`].
87    ///
88    /// Only needed when one call site creates several scrollables, which would
89    /// otherwise share a single scroll position.
90    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
91        self.id = id.into();
92        self
93    }
94}
95
96impl<E> Styled for Scrollable<E>
97where
98    E: InteractiveElement + Styled + ParentElement + Element,
99{
100    fn style(&mut self) -> &mut StyleRefinement {
101        self.element.style()
102    }
103}
104
105impl<E> ParentElement for Scrollable<E>
106where
107    E: InteractiveElement + Styled + ParentElement + Element,
108{
109    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
110        self.element.extend(elements)
111    }
112}
113
114impl<E> InteractiveElement for Scrollable<E>
115where
116    E: InteractiveElement + Styled + ParentElement + Element,
117{
118    fn interactivity(&mut self) -> &mut gpui::Interactivity {
119        self.element.interactivity()
120    }
121
122    fn track_focus(mut self, focus: &gpui::FocusHandle) -> Self {
123        self.element = self.element.track_focus(focus);
124        self
125    }
126}
127
128impl<E> RenderOnce for Scrollable<E>
129where
130    E: InteractiveElement + Styled + ParentElement + Element + 'static,
131{
132    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
133        let scroll_handle = scroll_handle_for(&self.id, window, cx);
134
135        // Preserve the caller-requested size on the wrapper, while keeping the
136        // caller's element as the actual scroll-tracked layout container.
137        let root_style = root_style_from(&mut self.element, self.axis);
138
139        let root_id = self.id.clone();
140        let area_id = (self.id.clone(), "area");
141        let content_id = (self.id.clone(), "content");
142        let scrollbar_id = (self.id.clone(), "scrollbar");
143
144        let content = self
145            .element
146            .id(content_id)
147            .flex_none()
148            .map(|this| match self.axis {
149                ScrollbarAxis::Vertical => this.h_auto().min_h_full(),
150                ScrollbarAxis::Horizontal => this.w_auto().min_w_full(),
151                ScrollbarAxis::Both => this.size_auto().min_size_full(),
152            });
153
154        // Keep the scroll area in the normal flow: its content size must
155        // propagate to auto-sized ancestors (e.g. a Dialog that grows with
156        // its content). An absolutely positioned scroll area would collapse
157        // such ancestors to zero height.
158        let scroll_area = div()
159            .id(area_id)
160            .size_full()
161            .flex()
162            .track_scroll(&scroll_handle)
163            .map(|this| match self.axis {
164                ScrollbarAxis::Vertical => this.flex_col().overflow_y_scroll(),
165                ScrollbarAxis::Horizontal => this.flex_row().overflow_x_scroll(),
166                ScrollbarAxis::Both => this.overflow_scroll(),
167            })
168            // On a single-axis area gpui otherwise remaps the other axis' delta
169            // onto ours, so a purely horizontal swipe scrolls this vertically.
170            .lock_scroll_axis()
171            .child(content);
172
173        div()
174            .id(root_id)
175            .size_full()
176            .refine_style(&root_style)
177            .relative()
178            .child(scroll_area)
179            .child(render_scrollbar(
180                scrollbar_id,
181                &scroll_handle,
182                self.axis,
183                window,
184                cx,
185            ))
186    }
187}
188
189impl ScrollableElement for Div {}
190impl<E> ScrollableElement for Stateful<E>
191where
192    E: ParentElement + Styled + Element,
193    Self: InteractiveElement,
194{
195}
196
197#[derive(IntoElement)]
198struct ScrollbarLayer<H: ScrollbarHandle + Clone> {
199    id: ElementId,
200    axis: ScrollbarAxis,
201    scroll_handle: Rc<H>,
202}
203
204impl<H> RenderOnce for ScrollbarLayer<H>
205where
206    H: ScrollbarHandle + Clone + 'static,
207{
208    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
209        render_scrollbar(self.id, self.scroll_handle.as_ref(), self.axis, window, cx)
210    }
211}
212
213#[inline]
214#[track_caller]
215fn caller_id() -> ElementId {
216    ElementId::CodeLocation(*Location::caller())
217}
218
219#[inline]
220fn scroll_handle_for(id: &ElementId, window: &mut Window, cx: &mut App) -> ScrollHandle {
221    window
222        .use_keyed_state(id.clone(), cx, |_, _| ScrollHandle::default())
223        .read(cx)
224        .clone()
225}
226
227/// Copies the outer layout styles from the element, so the wrapper can
228/// participate in the parent's layout the same way the source element would.
229///
230/// A flex item only drops its content-based automatic minimum size when its own
231/// overflow is not [`Overflow::Visible`]; otherwise the item refuses to shrink
232/// around its content. The scrolled overflow lives on the inner scroll area, so
233/// the wrapper has to declare the scrolled axis clipped itself — without it a
234/// scroll region used as a flex item pushes its siblings out of the container
235/// instead of scrolling, and every call site has to remember `min_h_0()` /
236/// `min_w_0()`.
237///
238/// [`Overflow::Hidden`] rather than a zero minimum: it is the axis' real
239/// behavior, it leaves an explicit `min_size` from the caller in charge, and it
240/// keeps the region's content size contributing to an auto-sized ancestor such
241/// as a Dialog that grows with its body. The mask it installs matches the inner
242/// scroll area's own mask, so nothing new is clipped.
243#[inline]
244fn root_style_from<E>(element: &mut E, axis: ScrollbarAxis) -> StyleRefinement
245where
246    E: Styled,
247{
248    let style = element.style();
249    StyleRefinement {
250        size: style.size.clone(),
251        min_size: style.min_size.clone(),
252        max_size: style.max_size.clone(),
253        flex_grow: style.flex_grow,
254        flex_shrink: style.flex_shrink,
255        flex_basis: style.flex_basis,
256        align_self: style.align_self,
257        overflow: PointRefinement {
258            x: axis.has_horizontal().then_some(Overflow::Hidden),
259            y: axis.has_vertical().then_some(Overflow::Hidden),
260        },
261        ..Default::default()
262    }
263}
264
265#[inline]
266fn render_scrollbar<H: ScrollbarHandle + Clone>(
267    id: impl Into<ElementId>,
268    scroll_handle: &H,
269    axis: ScrollbarAxis,
270    window: &mut Window,
271    cx: &mut App,
272) -> Div {
273    // Do not render scrollbar when inspector is picking elements,
274    // to allow us to pick the background elements.
275    let is_inspector_picking = window.is_inspector_picking(cx);
276    if is_inspector_picking {
277        return div();
278    }
279
280    div()
281        .absolute()
282        .inset_0()
283        .debug_selector(|| "scrollbar-overlay".to_string())
284        .child(
285            Scrollbar::new(scroll_handle)
286                .id(id)
287                .axis(axis)
288                .viewport_from_layout(),
289        )
290}
291
292#[cfg(feature = "test-support")]
293impl<E> ScrollableElement for gpui_base::test_support::Observed<E> where
294    E: ScrollableElement + Element<PrepaintState = Option<gpui::Hitbox>>
295{
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use gpui::{
302        Context, Render, ScrollDelta, ScrollWheelEvent, TestAppContext, VisualTestContext, point,
303        px,
304    };
305
306    fn draw(cx: &mut VisualTestContext) {
307        cx.run_until_parked();
308        cx.update(|window, cx| {
309            _ = window.draw(cx);
310        });
311    }
312
313    fn scroll(cx: &mut VisualTestContext, x: f32, y: f32, dx: f32, dy: f32) {
314        cx.simulate_event(ScrollWheelEvent {
315            position: point(px(x), px(y)),
316            delta: ScrollDelta::Pixels(point(px(dx), px(dy))),
317            ..Default::default()
318        });
319        draw(cx);
320    }
321
322    fn row(selector: &'static str, height: f32) -> Div {
323        div()
324            .h(px(height))
325            .flex_shrink_0()
326            .debug_selector(move || selector.to_string())
327    }
328
329    fn plain_row(height: f32) -> Div {
330        div().h(px(height)).flex_shrink_0()
331    }
332
333    fn item(selector: &'static str, width: f32) -> Div {
334        div()
335            .w(px(width))
336            .h(px(20.))
337            .flex_shrink_0()
338            .debug_selector(move || selector.to_string())
339    }
340
341    fn plain_item(width: f32) -> Div {
342        div().w(px(width)).h(px(20.)).flex_shrink_0()
343    }
344
345    struct SizeFullChildTest;
346
347    impl Render for SizeFullChildTest {
348        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
349            div()
350                .w(px(100.))
351                .h(px(100.))
352                .overflow_y_scrollbar()
353                .child(
354                    div()
355                        .size_full()
356                        .child(crate::v_flex().children((0..4).map(|ix| {
357                            div().h(px(50.)).flex_shrink_0().when(ix == 3, |this| {
358                                this.debug_selector(|| "last-row".to_string())
359                            })
360                        }))),
361                )
362        }
363    }
364
365    struct AutoHeightParentTest;
366
367    impl Render for AutoHeightParentTest {
368        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
369            // Mimics Dialog: the panel height is auto (content-driven), the
370            // body is flex_1 + overflow_hidden, and the scrollable content
371            // should give the panel its intrinsic height.
372            // GPUI window roots with auto dimensions stretch to the viewport,
373            // so keep the auto-height panel below an explicit viewport root.
374            div().size_full().child(
375                crate::v_flex()
376                    .w(px(200.))
377                    .child(
378                        crate::v_flex().flex_1().overflow_hidden().child(
379                            crate::v_flex().flex_1().overflow_hidden().child(
380                                crate::v_flex()
381                                    .size_full()
382                                    .overflow_y_scrollbar()
383                                    .child(plain_row(50.))
384                                    .child(plain_row(50.)),
385                            ),
386                        ),
387                    )
388                    .child(row("auto-height-footer", 10.)),
389            )
390        }
391    }
392
393    struct MaxHeightParentTest;
394
395    impl Render for MaxHeightParentTest {
396        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
397            // Mimics a Dialog with `max_h`: the panel grows with content up
398            // to the max height, then the body starts scrolling.
399            div().size_full().child(
400                crate::v_flex()
401                    .w(px(200.))
402                    .max_h(px(100.))
403                    .child(
404                        crate::v_flex().flex_1().overflow_hidden().child(
405                            crate::v_flex().flex_1().overflow_hidden().child(
406                                crate::v_flex()
407                                    .size_full()
408                                    .overflow_y_scrollbar()
409                                    .child(plain_row(50.))
410                                    .child(plain_row(50.))
411                                    .child(row("max-height-last-row", 50.)),
412                            ),
413                        ),
414                    )
415                    .child(row("max-height-footer", 10.)),
416            )
417        }
418    }
419
420    #[gpui::test]
421    fn auto_height_parent_gets_content_height(cx: &mut TestAppContext) {
422        cx.update(crate::init);
423        let (_, cx) = cx.add_window_view(|_, _| AutoHeightParentTest);
424        let cx: &mut VisualTestContext = cx;
425        draw(cx);
426
427        // The two 50px rows should push the footer down to y = 100.
428        let footer = cx.debug_bounds("auto-height-footer").unwrap();
429        assert_eq!(footer.top(), px(100.));
430    }
431
432    #[gpui::test]
433    fn max_height_parent_clamps_and_scrolls(cx: &mut TestAppContext) {
434        cx.update(crate::init);
435        let (_, cx) = cx.add_window_view(|_, _| MaxHeightParentTest);
436        cx.simulate_resize(gpui::size(px(200.), px(100.)));
437        let cx: &mut VisualTestContext = cx;
438        draw(cx);
439
440        // Content (150) + footer (10) exceeds max_h(100): the footer is
441        // pinned at the bottom and the body gets the remaining 90px viewport.
442        let footer = cx.debug_bounds("max-height-footer").unwrap();
443        assert_eq!(footer.top(), px(90.));
444
445        let last_initial_y = cx.debug_bounds("max-height-last-row").unwrap().origin.y;
446        scroll(cx, 10., 10., 0., -50.);
447        assert!(cx.debug_bounds("max-height-last-row").unwrap().origin.y < last_initial_y);
448    }
449
450    struct FlexItemScrollableTest;
451
452    impl Render for FlexItemScrollableTest {
453        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
454            // A fixed-height column of header, flexible scroll area, footer.
455            // The content is far taller than the room left for the area, so
456            // the area must shrink into the remaining 60px and scroll.
457            crate::v_flex()
458                .w(px(100.))
459                .h(px(100.))
460                .child(row("flex-item-header", 20.))
461                .child(
462                    crate::v_flex()
463                        .flex_1()
464                        .overflow_y_scrollbar()
465                        .children((0..6).map(|ix| {
466                            div().h(px(50.)).flex_shrink_0().when(ix == 0, |this| {
467                                this.debug_selector(|| "flex-item-first-row".to_string())
468                            })
469                        })),
470                )
471                .child(row("flex-item-footer", 20.))
472        }
473    }
474
475    #[gpui::test]
476    fn scrollable_flex_item_shrinks_below_its_content(cx: &mut TestAppContext) {
477        cx.update(crate::init);
478        let (_, cx) = cx.add_window_view(|_, _| FlexItemScrollableTest);
479        let cx: &mut VisualTestContext = cx;
480        draw(cx);
481
482        // Header and footer stay inside the 100px column, so the area took
483        // the 60px left over instead of its content height.
484        assert_eq!(cx.debug_bounds("flex-item-header").unwrap().top(), px(0.));
485        assert_eq!(cx.debug_bounds("flex-item-footer").unwrap().top(), px(80.));
486
487        // And the shrunken area really scrolls.
488        let initial_y = cx.debug_bounds("flex-item-first-row").unwrap().origin.y;
489        scroll(cx, 10., 50., 0., -50.);
490        assert!(cx.debug_bounds("flex-item-first-row").unwrap().origin.y < initial_y);
491    }
492
493    struct HorizontalFlexItemScrollableTest;
494
495    impl Render for HorizontalFlexItemScrollableTest {
496        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
497            crate::h_flex()
498                .w(px(100.))
499                .h(px(40.))
500                .child(item("horizontal-flex-item-leading", 20.))
501                .child(
502                    crate::h_flex()
503                        .flex_1()
504                        .overflow_x_scrollbar()
505                        .children((0..6).map(|ix| {
506                            div()
507                                .w(px(50.))
508                                .h(px(20.))
509                                .flex_shrink_0()
510                                .when(ix == 0, |this| {
511                                    this.debug_selector(|| {
512                                        "horizontal-flex-item-first-item".to_string()
513                                    })
514                                })
515                        })),
516                )
517                .child(item("horizontal-flex-item-trailing", 20.))
518        }
519    }
520
521    #[gpui::test]
522    fn horizontal_scrollable_flex_item_shrinks_below_its_content(cx: &mut TestAppContext) {
523        cx.update(crate::init);
524        let (_, cx) = cx.add_window_view(|_, _| HorizontalFlexItemScrollableTest);
525        let cx: &mut VisualTestContext = cx;
526        draw(cx);
527
528        assert_eq!(
529            cx.debug_bounds("horizontal-flex-item-leading")
530                .unwrap()
531                .left(),
532            px(0.)
533        );
534        assert_eq!(
535            cx.debug_bounds("horizontal-flex-item-trailing")
536                .unwrap()
537                .left(),
538            px(80.)
539        );
540
541        let initial_x = cx
542            .debug_bounds("horizontal-flex-item-first-item")
543            .unwrap()
544            .origin
545            .x;
546        scroll(cx, 50., 10., -50., 0.);
547        assert!(
548            cx.debug_bounds("horizontal-flex-item-first-item")
549                .unwrap()
550                .origin
551                .x
552                < initial_x
553        );
554    }
555
556    struct ExplicitMinHeightScrollableTest;
557
558    impl Render for ExplicitMinHeightScrollableTest {
559        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
560            // An explicit `min_h` is the caller's decision and must survive.
561            crate::v_flex()
562                .w(px(100.))
563                .h(px(100.))
564                .child(row("explicit-min-header", 20.))
565                .child(
566                    crate::v_flex()
567                        .flex_1()
568                        .min_h(px(70.))
569                        .overflow_y_scrollbar()
570                        .children((0..6).map(|_| plain_row(50.))),
571                )
572                .child(row("explicit-min-footer", 20.))
573        }
574    }
575
576    #[gpui::test]
577    fn explicit_min_size_survives_the_scrollable_wrapper(cx: &mut TestAppContext) {
578        cx.update(crate::init);
579        let (_, cx) = cx.add_window_view(|_, _| ExplicitMinHeightScrollableTest);
580        let cx: &mut VisualTestContext = cx;
581        draw(cx);
582
583        // The area cannot shrink past the requested 70px, so the footer is
584        // pushed to 20 + 70 instead of being clamped into the column.
585        assert_eq!(
586            cx.debug_bounds("explicit-min-header").unwrap().top(),
587            px(0.)
588        );
589        assert_eq!(
590            cx.debug_bounds("explicit-min-footer").unwrap().top(),
591            px(90.)
592        );
593    }
594
595    struct GapLayoutTest;
596
597    struct PaddedScrollbarOverlayTest;
598
599    impl Render for PaddedScrollbarOverlayTest {
600        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
601            crate::v_flex()
602                .w(px(100.))
603                .h(px(100.))
604                .p(px(20.))
605                .overflow_y_scrollbar()
606                .children((0..4).map(|_| plain_row(50.)))
607        }
608    }
609
610    #[gpui::test]
611    fn scrollbar_overlay_ignores_content_padding(cx: &mut TestAppContext) {
612        cx.update(crate::init);
613        let (_, cx) = cx.add_window_view(|_, _| PaddedScrollbarOverlayTest);
614        let cx: &mut VisualTestContext = cx;
615        draw(cx);
616
617        let overlay = cx.debug_bounds("scrollbar-overlay").unwrap();
618        assert_eq!(overlay.origin, point(px(0.), px(0.)));
619        assert_eq!(overlay.size, gpui::size(px(100.), px(100.)));
620    }
621
622    impl Render for GapLayoutTest {
623        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
624            crate::v_flex()
625                .w(px(100.))
626                .h(px(100.))
627                .gap(px(10.))
628                .overflow_y_scrollbar()
629                .child(row("first-row", 20.))
630                .child(row("second-row", 20.))
631        }
632    }
633
634    struct IssueGapRegressionTest;
635
636    impl Render for IssueGapRegressionTest {
637        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
638            div().w(px(100.)).h(px(100.)).child(
639                crate::v_flex()
640                    .flex_1()
641                    .gap(px(30.))
642                    .overflow_y_scrollbar()
643                    .px(px(12.))
644                    .pb(px(16.))
645                    .children((0..5).map(|ix| {
646                        div()
647                            .h(px(20.))
648                            .flex_shrink_0()
649                            .when(ix == 0, |this| {
650                                this.debug_selector(|| "issue-first-card".to_string())
651                            })
652                            .when(ix == 1, |this| {
653                                this.debug_selector(|| "issue-second-card".to_string())
654                            })
655                            .when(ix == 4, |this| {
656                                this.debug_selector(|| "issue-last-card".to_string())
657                            })
658                    })),
659            )
660        }
661    }
662
663    struct HorizontalGapLayoutTest;
664
665    impl Render for HorizontalGapLayoutTest {
666        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
667            crate::h_flex()
668                .w(px(100.))
669                .h(px(40.))
670                .gap(px(10.))
671                .overflow_x_scrollbar()
672                .child(item("horizontal-first-item", 50.))
673                .child(item("horizontal-second-item", 50.))
674                .child(item("horizontal-last-item", 50.))
675        }
676    }
677
678    struct OverflowScrollbarVerticalTest;
679
680    impl Render for OverflowScrollbarVerticalTest {
681        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
682            crate::v_flex()
683                .w(px(100.))
684                .h(px(100.))
685                .gap(px(10.))
686                .overflow_scrollbar()
687                .child(row("both-axis-vertical-first-row", 50.))
688                .child(row("both-axis-vertical-second-row", 50.))
689                .child(row("both-axis-vertical-last-row", 50.))
690        }
691    }
692
693    struct OverflowScrollbarHorizontalTest;
694
695    impl Render for OverflowScrollbarHorizontalTest {
696        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
697            crate::h_flex()
698                .w(px(100.))
699                .h(px(40.))
700                .gap(px(10.))
701                .overflow_scrollbar()
702                .child(item("both-axis-horizontal-first-item", 50.))
703                .child(item("both-axis-horizontal-second-item", 50.))
704                .child(item("both-axis-horizontal-last-item", 50.))
705        }
706    }
707
708    struct IndependentScrollablesTest;
709
710    impl Render for IndependentScrollablesTest {
711        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
712            crate::h_flex()
713                .w(px(220.))
714                .h(px(100.))
715                .gap(px(20.))
716                .child(
717                    div().w(px(100.)).h(px(100.)).overflow_y_scrollbar().child(
718                        crate::v_flex()
719                            .child(plain_row(50.))
720                            .child(plain_row(50.))
721                            .child(row("left-scrollable-last-row", 50.)),
722                    ),
723                )
724                .child(
725                    div().w(px(100.)).h(px(100.)).overflow_y_scrollbar().child(
726                        crate::v_flex()
727                            .child(plain_row(50.))
728                            .child(plain_row(50.))
729                            .child(row("right-scrollable-last-row", 50.)),
730                    ),
731                )
732        }
733    }
734
735    struct NoOverflowTest;
736
737    impl Render for NoOverflowTest {
738        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
739            crate::v_flex()
740                .w(px(100.))
741                .h(px(100.))
742                .gap(px(10.))
743                .overflow_y_scrollbar()
744                .child(row("no-overflow-first-row", 20.))
745                .child(row("no-overflow-second-row", 20.))
746        }
747    }
748
749    #[gpui::test]
750    fn vertical_scrollbar_scrolls_past_a_size_full_child(cx: &mut TestAppContext) {
751        cx.update(crate::init);
752        let (_, cx) = cx.add_window_view(|_, _| SizeFullChildTest);
753        let cx: &mut VisualTestContext = cx;
754        draw(cx);
755
756        let initial_y = cx.debug_bounds("last-row").unwrap().origin.y;
757        scroll(cx, 10., 10., 0., -50.);
758
759        assert!(cx.debug_bounds("last-row").unwrap().origin.y < initial_y);
760    }
761
762    #[gpui::test]
763    fn vertical_scrollbar_preserves_source_gap(cx: &mut TestAppContext) {
764        cx.update(crate::init);
765        let (_, cx) = cx.add_window_view(|_, _| GapLayoutTest);
766        let cx: &mut VisualTestContext = cx;
767        draw(cx);
768
769        let first = cx.debug_bounds("first-row").unwrap();
770        let second = cx.debug_bounds("second-row").unwrap();
771        assert_eq!(second.top() - first.bottom(), px(10.));
772    }
773
774    #[gpui::test]
775    fn overflow_y_scrollbar_preserves_gap_for_exact_issue_chain(cx: &mut TestAppContext) {
776        cx.update(crate::init);
777        let (_, cx) = cx.add_window_view(|_, _| IssueGapRegressionTest);
778        let cx: &mut VisualTestContext = cx;
779        draw(cx);
780
781        let first = cx.debug_bounds("issue-first-card").unwrap();
782        let second = cx.debug_bounds("issue-second-card").unwrap();
783        let last_initial_y = cx.debug_bounds("issue-last-card").unwrap().origin.y;
784
785        assert_eq!(second.top() - first.bottom(), px(30.));
786        assert_eq!(first.left(), px(12.));
787
788        scroll(cx, 10., 10., 0., -50.);
789
790        let first_after_scroll = cx.debug_bounds("issue-first-card").unwrap();
791        let second_after_scroll = cx.debug_bounds("issue-second-card").unwrap();
792        let last_after_scroll_y = cx.debug_bounds("issue-last-card").unwrap().origin.y;
793
794        assert_eq!(
795            second_after_scroll.top() - first_after_scroll.bottom(),
796            px(30.)
797        );
798        assert_eq!(first_after_scroll.left(), px(12.));
799        assert!(last_after_scroll_y < last_initial_y);
800    }
801
802    #[gpui::test]
803    fn horizontal_scrollbar_preserves_source_gap_and_scrolls(cx: &mut TestAppContext) {
804        cx.update(crate::init);
805        let (_, cx) = cx.add_window_view(|_, _| HorizontalGapLayoutTest);
806        let cx: &mut VisualTestContext = cx;
807        draw(cx);
808
809        let first = cx.debug_bounds("horizontal-first-item").unwrap();
810        let second = cx.debug_bounds("horizontal-second-item").unwrap();
811        let last_initial_x = cx.debug_bounds("horizontal-last-item").unwrap().origin.x;
812
813        assert_eq!(second.left() - first.right(), px(10.));
814
815        scroll(cx, 10., 10., -50., 0.);
816
817        let first_after_scroll = cx.debug_bounds("horizontal-first-item").unwrap();
818        let second_after_scroll = cx.debug_bounds("horizontal-second-item").unwrap();
819        let last_after_scroll_x = cx.debug_bounds("horizontal-last-item").unwrap().origin.x;
820
821        assert_eq!(
822            second_after_scroll.left() - first_after_scroll.right(),
823            px(10.)
824        );
825        assert!(last_after_scroll_x < last_initial_x);
826    }
827
828    #[gpui::test]
829    fn overflow_scrollbar_preserves_vertical_source_gap(cx: &mut TestAppContext) {
830        cx.update(crate::init);
831        let (_, cx) = cx.add_window_view(|_, _| OverflowScrollbarVerticalTest);
832        let cx: &mut VisualTestContext = cx;
833        draw(cx);
834
835        let first = cx.debug_bounds("both-axis-vertical-first-row").unwrap();
836        let second = cx.debug_bounds("both-axis-vertical-second-row").unwrap();
837
838        assert_eq!(second.top() - first.bottom(), px(10.));
839    }
840
841    #[gpui::test]
842    fn overflow_scrollbar_preserves_gap_and_scrolls_horizontally(cx: &mut TestAppContext) {
843        cx.update(crate::init);
844        let (_, cx) = cx.add_window_view(|_, _| OverflowScrollbarHorizontalTest);
845        let cx: &mut VisualTestContext = cx;
846        draw(cx);
847
848        let first = cx.debug_bounds("both-axis-horizontal-first-item").unwrap();
849        let second = cx.debug_bounds("both-axis-horizontal-second-item").unwrap();
850        let last_initial_x = cx
851            .debug_bounds("both-axis-horizontal-last-item")
852            .unwrap()
853            .origin
854            .x;
855
856        assert_eq!(second.left() - first.right(), px(10.));
857
858        scroll(cx, 10., 10., -50., 0.);
859
860        let first_after_scroll = cx.debug_bounds("both-axis-horizontal-first-item").unwrap();
861        let second_after_scroll = cx.debug_bounds("both-axis-horizontal-second-item").unwrap();
862        let last_after_scroll_x = cx
863            .debug_bounds("both-axis-horizontal-last-item")
864            .unwrap()
865            .origin
866            .x;
867
868        assert_eq!(
869            second_after_scroll.left() - first_after_scroll.right(),
870            px(10.)
871        );
872        assert!(last_after_scroll_x < last_initial_x);
873    }
874
875    #[gpui::test]
876    fn multiple_scrollables_keep_independent_scroll_state(cx: &mut TestAppContext) {
877        cx.update(crate::init);
878        let (_, cx) = cx.add_window_view(|_, _| IndependentScrollablesTest);
879        let cx: &mut VisualTestContext = cx;
880        draw(cx);
881
882        let left_initial = cx.debug_bounds("left-scrollable-last-row").unwrap();
883        let right_initial = cx.debug_bounds("right-scrollable-last-row").unwrap();
884
885        scroll(cx, 10., 10., 0., -50.);
886
887        let left_after_scroll = cx.debug_bounds("left-scrollable-last-row").unwrap();
888        let right_after_scroll = cx.debug_bounds("right-scrollable-last-row").unwrap();
889
890        assert!(left_after_scroll.top() < left_initial.top());
891        assert_eq!(right_after_scroll.top(), right_initial.top());
892    }
893
894    #[gpui::test]
895    fn vertical_scrollbar_does_not_scroll_when_content_does_not_overflow(cx: &mut TestAppContext) {
896        cx.update(crate::init);
897        let (_, cx) = cx.add_window_view(|_, _| NoOverflowTest);
898        let cx: &mut VisualTestContext = cx;
899        draw(cx);
900
901        let first = cx.debug_bounds("no-overflow-first-row").unwrap();
902        let second = cx.debug_bounds("no-overflow-second-row").unwrap();
903
904        assert_eq!(second.top() - first.bottom(), px(10.));
905
906        scroll(cx, 10., 10., 0., -50.);
907
908        let first_after_scroll = cx.debug_bounds("no-overflow-first-row").unwrap();
909        let second_after_scroll = cx.debug_bounds("no-overflow-second-row").unwrap();
910
911        assert_eq!(first_after_scroll.top(), first.top());
912        assert_eq!(second_after_scroll.top(), second.top());
913        assert_eq!(
914            second_after_scroll.top() - first_after_scroll.bottom(),
915            px(10.)
916        );
917    }
918
919    #[gpui::test]
920    fn horizontal_scrollbar_does_not_scroll_when_content_does_not_overflow(
921        cx: &mut TestAppContext,
922    ) {
923        struct HorizontalNoOverflowTest;
924
925        impl Render for HorizontalNoOverflowTest {
926            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
927                crate::h_flex()
928                    .w(px(100.))
929                    .h(px(40.))
930                    .gap(px(10.))
931                    .overflow_x_scrollbar()
932                    .child(item("no-overflow-first-item", 20.))
933                    .child(item("no-overflow-second-item", 20.))
934                    .child(plain_item(20.))
935            }
936        }
937
938        cx.update(crate::init);
939        let (_, cx) = cx.add_window_view(|_, _| HorizontalNoOverflowTest);
940        let cx: &mut VisualTestContext = cx;
941        draw(cx);
942
943        let first = cx.debug_bounds("no-overflow-first-item").unwrap();
944        let second = cx.debug_bounds("no-overflow-second-item").unwrap();
945
946        assert_eq!(second.left() - first.right(), px(10.));
947
948        scroll(cx, 10., 10., -50., 0.);
949
950        let first_after_scroll = cx.debug_bounds("no-overflow-first-item").unwrap();
951        let second_after_scroll = cx.debug_bounds("no-overflow-second-item").unwrap();
952
953        assert_eq!(first_after_scroll.left(), first.left());
954        assert_eq!(second_after_scroll.left(), second.left());
955        assert_eq!(
956            second_after_scroll.left() - first_after_scroll.right(),
957            px(10.)
958        );
959    }
960    struct IndependentDynamicScrollablesTest;
961
962    impl Render for IndependentDynamicScrollablesTest {
963        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
964            crate::v_flex().w(px(100.)).children((0..2).map(|ix| {
965                crate::h_flex()
966                    .w(px(100.))
967                    .h(px(40.))
968                    .overflow_x_scrollbar()
969                    .id(format!("dynamic-scroll-{ix}"))
970                    .child(
971                        div()
972                            .w(px(200.))
973                            .h(px(20.))
974                            .flex_shrink_0()
975                            .when(ix == 0, |this| {
976                                this.debug_selector(|| "dynamic-scroll-first".to_string())
977                            })
978                            .when(ix == 1, |this| {
979                                this.debug_selector(|| "dynamic-scroll-second".to_string())
980                            }),
981                    )
982            }))
983        }
984    }
985
986    #[gpui::test]
987    fn dynamic_scrollables_with_unique_scroll_ids_keep_independent_state(cx: &mut TestAppContext) {
988        cx.update(crate::init);
989
990        let (_, cx) = cx.add_window_view(|_, _| IndependentDynamicScrollablesTest);
991        let cx: &mut VisualTestContext = cx;
992
993        draw(cx);
994
995        let first_initial = cx.debug_bounds("dynamic-scroll-first").unwrap();
996
997        let second_initial = cx.debug_bounds("dynamic-scroll-second").unwrap();
998
999        // Scroll horizontally inside the first row.
1000        scroll(cx, 10., 10., -50., 0.);
1001
1002        let first_after_scroll = cx.debug_bounds("dynamic-scroll-first").unwrap();
1003
1004        let second_after_scroll = cx.debug_bounds("dynamic-scroll-second").unwrap();
1005
1006        // First scrollable should move horizontally.
1007        assert!(first_after_scroll.left() < first_initial.left());
1008
1009        // Second scrollable must keep its own independent scroll state.
1010        assert_eq!(second_after_scroll.left(), second_initial.left());
1011    }
1012}