Skip to main content

wgpui_component/scroll/
scrollable.rs

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