Skip to main content

gpui_deck/
scroll_area.rs

1//! A native GPUI viewport composed with the existing overlay scrollbar.
2
3use gpui::{
4    AnyElement, App, Bounds, Div, Element, ElementId, GlobalElementId, InspectorElementId,
5    InteractiveElement as _, IntoElement, LayoutId, Overflow, ParentElement, Pixels,
6    Refineable as _, RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement as _,
7    StyleRefinement, Styled, Window, div, px,
8};
9
10use crate::{
11    Scrollbar, ScrollbarAxis, ScrollbarMode, ScrollbarStyles, StateStyle, TestSupportExt as _,
12};
13
14/// A scrollable viewport with application-owned content and presentation.
15///
16/// Retain the supplied [`ScrollHandle`] in the application. Ordinary GPUI styles
17/// size and decorate the frame; [`Self::content_styles`] sets its viewport's
18/// child layout and padding. Give each scrolling axis a bounded size and keep
19/// children from shrinking when necessary. The existing [`Scrollbar`] overlays
20/// that viewport without contributing to its content size or reserving a
21/// gutter. Its styles and visibility mode can be configured independently.
22///
23/// The viewport keeps GPUI's wheel/trackpad handling and the scrollbar's pointer
24/// interaction. It adds no focus stop or key bindings, so descendant controls
25/// keep their own keyboard behavior. Native autoscroll requests from those
26/// descendants, including focused Input and Textarea, reveal the requested
27/// region on enabled axes. Nested areas pass the adjusted request to their
28/// ancestors; requests from siblings do not scroll this viewport.
29///
30/// This component does not virtualize children or pin streaming content to an
31/// edge. Its native role is [`Role::ScrollView`]; provide a descriptive label for
32/// a distinct application region with [`Self::accessibility_label`].
33#[derive(IntoElement)]
34pub struct ScrollArea {
35    base: crate::ObservedElement<gpui::Stateful<Div>>,
36    viewport: gpui::Stateful<Div>,
37    handle: ScrollHandle,
38    scrollbar: Scrollbar,
39    axis: ScrollbarAxis,
40}
41
42impl ScrollArea {
43    /// Creates a vertical scroll area using the application's retained handle.
44    pub fn new(id: impl Into<ElementId>, handle: &ScrollHandle) -> Self {
45        let id = id.into();
46        Self {
47            base: div()
48                .id(id.clone())
49                .test_support()
50                .role(Role::ScrollView)
51                .relative()
52                .flex()
53                .flex_col()
54                .min_w_0()
55                .min_h_0(),
56            viewport: div()
57                .id((id.clone(), "viewport"))
58                .track_scroll(handle)
59                .flex_1()
60                .min_w_0()
61                .min_h_0(),
62            handle: handle.clone(),
63            scrollbar: Scrollbar::vertical(handle).id((id, "scrollbar")),
64            axis: ScrollbarAxis::Vertical,
65        }
66    }
67
68    /// Enables the corresponding native overflow and overlay scrollbar axes.
69    pub fn axis(mut self, axis: impl Into<ScrollbarAxis>) -> Self {
70        self.axis = axis.into();
71        self.scrollbar = self.scrollbar.axis(self.axis);
72        self
73    }
74
75    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
76        self.base = self.base.aria_label(label);
77        self
78    }
79
80    /// Styles the viewport's layout and padding; children are added here.
81    ///
82    /// For example, use `|style| style.flex().flex_col().gap_2()` for a vertical
83    /// form. Set the area's bounded size on the ScrollArea itself.
84    pub fn content_styles(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
85        self.viewport
86            .style()
87            .refine(&build(StateStyle::default()).into_refinement());
88        self
89    }
90
91    /// Overrides the application's default scrollbar visibility mode.
92    pub fn scrollbar_mode(mut self, mode: ScrollbarMode) -> Self {
93        self.scrollbar = self.scrollbar.mode(mode);
94        self
95    }
96
97    pub fn scrollbar_styles(
98        mut self,
99        build: impl FnOnce(ScrollbarStyles) -> ScrollbarStyles,
100    ) -> Self {
101        self.scrollbar = self.scrollbar.styles(build);
102        self
103    }
104}
105
106impl Styled for ScrollArea {
107    fn style(&mut self) -> &mut StyleRefinement {
108        self.base.style()
109    }
110}
111
112impl ParentElement for ScrollArea {
113    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
114        self.viewport.extend(elements);
115    }
116}
117
118impl RenderOnce for ScrollArea {
119    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
120        let viewport = self.viewport.overflow_hidden();
121        let viewport = match self.axis {
122            ScrollbarAxis::Vertical => viewport.overflow_y_scroll(),
123            ScrollbarAxis::Horizontal => viewport.overflow_x_scroll(),
124            ScrollbarAxis::Both => viewport.overflow_scroll(),
125        };
126        self.base
127            .child(RevealViewport::new(viewport, self.handle, self.axis))
128            .child(self.scrollbar)
129    }
130}
131
132// A transparent prepaint scope keeps reveal requests attached to the viewport
133// whose children produced them. Layout, clipping, drawing, and pointer scrolling
134// remain owned by the ordinary GPUI div.
135pub(crate) struct RevealViewport {
136    viewport: gpui::Stateful<Div>,
137    handle: ScrollHandle,
138    axis: ScrollbarAxis,
139    popup: bool,
140}
141
142impl RevealViewport {
143    fn new(viewport: gpui::Stateful<Div>, handle: ScrollHandle, axis: ScrollbarAxis) -> Self {
144        Self {
145            viewport,
146            handle,
147            axis,
148            popup: false,
149        }
150    }
151
152    pub(crate) fn popup(
153        id: &'static str,
154        height: Pixels,
155        handle: ScrollHandle,
156        content: Option<AnyElement>,
157    ) -> Self {
158        let viewport = div()
159            .id(id)
160            .max_h(height)
161            .overflow_y_scroll()
162            .track_scroll(&handle)
163            .children(content);
164        Self {
165            viewport,
166            handle,
167            axis: ScrollbarAxis::Vertical,
168            popup: true,
169        }
170    }
171
172    fn reveal(&self, mut request: Bounds<Pixels>, window: &mut Window) {
173        let viewport = self.handle.bounds();
174        let old_offset = self.handle.offset();
175        let mut offset = old_offset;
176        let maximum = self.handle.max_offset();
177        if self.axis.has_horizontal() {
178            offset.x = (offset.x
179                + reveal_delta(
180                    request.left(),
181                    request.right(),
182                    viewport.left(),
183                    viewport.right(),
184                ))
185            .clamp(-maximum.x, px(0.));
186        }
187        if self.axis.has_vertical() {
188            offset.y = (offset.y
189                + reveal_delta(
190                    request.top(),
191                    request.bottom(),
192                    viewport.top(),
193                    viewport.bottom(),
194                ))
195            .clamp(-maximum.y, px(0.));
196        }
197        if offset != old_offset {
198            self.handle.set_offset(offset);
199            // The viewport's children have already prepainted. Apply the new
200            // offset on the next frame and forward their resulting position
201            // now so an enclosing ScrollArea can reveal the same region.
202            request.origin += offset - old_offset;
203            window.request_animation_frame();
204        }
205        window.request_autoscroll(request);
206    }
207}
208
209fn reveal_delta(
210    start: Pixels,
211    end: Pixels,
212    viewport_start: Pixels,
213    viewport_end: Pixels,
214) -> Pixels {
215    if start < viewport_start {
216        viewport_start - start
217    } else if end > viewport_end {
218        // A request larger than the viewport aligns its leading edge instead
219        // of hiding that edge in an attempt to show the impossible full extent.
220        (viewport_end - end).max(viewport_start - start)
221    } else {
222        px(0.)
223    }
224}
225
226impl IntoElement for RevealViewport {
227    type Element = Self;
228
229    fn into_element(self) -> Self {
230        self
231    }
232}
233
234impl Element for RevealViewport {
235    type RequestLayoutState = <gpui::Stateful<Div> as Element>::RequestLayoutState;
236    type PrepaintState = <gpui::Stateful<Div> as Element>::PrepaintState;
237
238    fn id(&self) -> Option<ElementId> {
239        Element::id(&self.viewport)
240    }
241
242    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
243        self.viewport.source_location()
244    }
245
246    fn request_layout(
247        &mut self,
248        id: Option<&GlobalElementId>,
249        inspector: Option<&InspectorElementId>,
250        window: &mut Window,
251        cx: &mut App,
252    ) -> (LayoutId, Self::RequestLayoutState) {
253        self.viewport.request_layout(id, inspector, window, cx)
254    }
255
256    fn prepaint(
257        &mut self,
258        id: Option<&GlobalElementId>,
259        inspector: Option<&InspectorElementId>,
260        bounds: Bounds<Pixels>,
261        layout: &mut Self::RequestLayoutState,
262        window: &mut Window,
263        cx: &mut App,
264    ) -> Self::PrepaintState {
265        let mut offset = self.handle.offset();
266        if !self.axis.has_horizontal() {
267            offset.x = px(0.);
268        }
269        if !self.axis.has_vertical() {
270            offset.y = px(0.);
271        }
272        self.handle.set_offset(offset);
273
274        // Scope requests to the children being prepainted, while preserving a
275        // prior sibling's request for the actual enclosing scroll container.
276        let pending = window.take_autoscroll();
277        let viewport = self
278            .viewport
279            .prepaint(id, inspector, bounds, layout, window, cx);
280        if let Some(request) = window.take_autoscroll() {
281            self.reveal(request, window);
282        } else if let Some(pending) = pending {
283            window.request_autoscroll(pending);
284        }
285
286        viewport
287    }
288
289    fn paint(
290        &mut self,
291        id: Option<&GlobalElementId>,
292        inspector: Option<&InspectorElementId>,
293        bounds: Bounds<Pixels>,
294        layout: &mut Self::RequestLayoutState,
295        prepaint: &mut Self::PrepaintState,
296        window: &mut Window,
297        cx: &mut App,
298    ) {
299        // GPUI measures the scroll range in prepaint. Allow a fitted popup's
300        // surface to paint its own shadow outside the list's bounds.
301        if self.popup {
302            self.viewport.style().overflow.y = Some(if self.handle.max_offset().y > px(0.) {
303                Overflow::Scroll
304            } else {
305                Overflow::Visible
306            });
307        }
308        self.viewport
309            .paint(id, inspector, bounds, layout, prepaint, window, cx);
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use std::{cell::Cell, rc::Rc};
316
317    use gpui::{
318        AppContext as _, Context, Entity, Focusable as _, Modifiers, MouseButton, Point, Render,
319        ScrollDelta, ScrollEvent, TestAppContext, accesskit, point,
320    };
321
322    use super::*;
323    use crate::{ElementExt as _, Input, InputBase, InputState};
324
325    struct SizingHarness {
326        vertical: ScrollHandle,
327        horizontal: ScrollHandle,
328        both: ScrollHandle,
329        extent: Pixels,
330    }
331
332    impl Render for SizingHarness {
333        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
334            div()
335                .w(px(200.))
336                .flex()
337                .flex_col()
338                .items_start()
339                .child(
340                    div()
341                        .w_full()
342                        .max_h(px(140.))
343                        .flex()
344                        .flex_col()
345                        .flex_shrink_0()
346                        .child(div().h(px(20.)).flex_shrink_0())
347                        .child(
348                            ScrollArea::new("form", &self.vertical)
349                                .accessibility_label("Form fields")
350                                .scrollbar_mode(ScrollbarMode::Always)
351                                .content_styles(|style| style.flex().flex_col())
352                                .child(div().h(self.extent).w_full().flex_shrink_0()),
353                        ),
354                )
355                .child(
356                    ScrollArea::new("table", &self.horizontal)
357                        .axis(ScrollbarAxis::Horizontal)
358                        .w_full()
359                        .flex_shrink_0()
360                        .scrollbar_mode(ScrollbarMode::Always)
361                        .child(div().w(self.extent).h(px(72.)).flex_shrink_0()),
362                )
363                .child(
364                    ScrollArea::new("canvas", &self.both)
365                        .axis(ScrollbarAxis::Both)
366                        .size(px(100.))
367                        .flex_shrink_0()
368                        .scrollbar_mode(ScrollbarMode::Always)
369                        .child(div().size(self.extent).flex_shrink_0()),
370                )
371        }
372    }
373
374    #[gpui::test]
375    fn natural_sizing_wheel_and_overlay_drag_share_the_viewport_handles(cx: &mut TestAppContext) {
376        cx.update(crate::init);
377        let vertical = ScrollHandle::new();
378        let horizontal = ScrollHandle::new();
379        let both = ScrollHandle::new();
380        let (view, cx) = cx.add_window_view({
381            let vertical = vertical.clone();
382            let horizontal = horizontal.clone();
383            let both = both.clone();
384            move |_, _| SizingHarness {
385                vertical,
386                horizontal,
387                both,
388                extent: px(400.),
389            }
390        });
391        cx.update(|window, cx| {
392            let area = ScrollArea::new("semantics", &vertical)
393                .accessibility_label("Form fields")
394                .render(window, cx)
395                .into_element();
396            assert_eq!(area.a11y_role(), Some(Role::ScrollView));
397            let mut node = accesskit::Node::new(Role::ScrollView);
398            area.write_a11y_info(&mut node);
399            assert_eq!(node.label(), Some("Form fields"));
400            assert!(!node.supports_action(accesskit::Action::Focus));
401            window.draw(cx).clear(cx);
402        });
403
404        // A form body shrinks under its parent's max-height without a fixed
405        // height. A horizontally scrolling table retains its content height.
406        assert_eq!(vertical.bounds().size.height, px(120.));
407        assert_eq!(horizontal.bounds().size.height, px(72.));
408        assert_eq!(vertical.max_offset().y, px(280.));
409        assert_eq!(horizontal.max_offset().x, px(200.));
410        for (handle, delta) in [
411            (&vertical, point(px(0.), px(-40.))),
412            (&horizontal, point(px(-30.), px(0.))),
413            (&both, point(px(-30.), px(0.))),
414            (&both, point(px(0.), px(-40.))),
415        ] {
416            cx.simulate_event(ScrollEvent {
417                position: handle.bounds().center(),
418                delta: ScrollDelta::Pixels(delta),
419                ..Default::default()
420            });
421            cx.update(|window, cx| window.draw(cx).clear(cx));
422        }
423        assert_eq!(vertical.offset(), point(px(0.), px(-40.)));
424        assert_eq!(horizontal.offset(), point(px(-30.), px(0.)));
425        assert_eq!(both.offset(), point(px(-30.), px(-40.)));
426
427        // The overlay stays on the viewport while its content moves, and its
428        // existing drag behavior reaches the same native handle's exact end.
429        vertical.set_offset(Point::default());
430        cx.update(|window, cx| window.draw(cx).clear(cx));
431        let bounds = vertical.bounds();
432        let start = point(bounds.right() - px(6.), bounds.top() + px(12.));
433        let end = point(start.x, bounds.bottom() - px(1.));
434        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
435        cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default());
436        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
437        cx.update(|window, cx| window.draw(cx).clear(cx));
438        assert_eq!(vertical.offset().y, -vertical.max_offset().y);
439        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
440
441        view.update(cx, |view, cx| {
442            view.extent = px(40.);
443            cx.notify();
444        });
445        cx.update(|window, cx| window.draw(cx).clear(cx));
446        assert_eq!(vertical.bounds().size.height, px(40.));
447        assert_eq!(horizontal.bounds().size.height, px(72.));
448        for handle in [&vertical, &horizontal, &both] {
449            assert_eq!(handle.offset(), Point::default());
450        }
451    }
452
453    struct RevealHarness {
454        outer: ScrollHandle,
455        inner: ScrollHandle,
456        sibling: ScrollHandle,
457        input: Entity<InputState>,
458        input_bounds: Rc<Cell<Bounds<Pixels>>>,
459    }
460
461    impl Render for RevealHarness {
462        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
463            let input_bounds = self.input_bounds.clone();
464            ScrollArea::new("outer", &self.outer)
465                .w(px(160.))
466                .h(px(120.))
467                .content_styles(|style| style.flex().flex_col())
468                .child(div().h(px(240.)).flex_shrink_0())
469                .child(
470                    ScrollArea::new("inner", &self.inner)
471                        .h(px(80.))
472                        .flex_shrink_0()
473                        .content_styles(|style| style.flex().flex_col())
474                        .child(div().h(px(140.)).flex_shrink_0())
475                        .child(
476                            div()
477                                .relative()
478                                .h(px(32.))
479                                .flex_shrink_0()
480                                .child(
481                                    InputBase::new("reveal-input")
482                                        .w_full()
483                                        .h(px(32.))
484                                        .child(Input::new(&self.input)),
485                                )
486                                .on_prepaint(move |bounds, _, _| input_bounds.set(bounds)),
487                        )
488                        .child(div().h(px(40.)).flex_shrink_0()),
489                )
490                .child(
491                    ScrollArea::new("sibling", &self.sibling)
492                        .h(px(80.))
493                        .flex_shrink_0()
494                        .child(div().h(px(400.))),
495                )
496        }
497    }
498
499    #[gpui::test]
500    fn focused_input_reveals_through_nested_areas_without_scrolling_its_sibling(
501        cx: &mut TestAppContext,
502    ) {
503        cx.update(crate::init);
504        let outer = ScrollHandle::new();
505        let inner = ScrollHandle::new();
506        let sibling = ScrollHandle::new();
507        let input_bounds = Rc::new(Cell::new(Bounds::default()));
508        let (view, cx) = cx.add_window_view({
509            let outer = outer.clone();
510            let inner = inner.clone();
511            let sibling = sibling.clone();
512            let input_bounds = input_bounds.clone();
513            move |window, cx| RevealHarness {
514                outer,
515                inner,
516                sibling,
517                input: cx.new(|cx| InputState::new(window, cx)),
518                input_bounds,
519            }
520        });
521        let input = view.read_with(cx, |view, _| view.input.clone());
522        cx.update(|window, cx| {
523            window.draw(cx).clear(cx);
524            input.update(cx, |state, cx| state.focus(window, cx));
525            window.draw(cx).clear(cx);
526            window.simulate_next_frame(cx);
527            window.draw(cx).clear(cx);
528        });
529
530        assert!(inner.offset().y < px(0.));
531        assert!(outer.offset().y < px(0.));
532        assert_eq!(sibling.offset(), Point::default());
533        let field = input_bounds.get();
534        for viewport in [outer.bounds(), inner.bounds()] {
535            assert!(
536                field.top() >= viewport.top(),
537                "{field:?} above {viewport:?}"
538            );
539            assert!(
540                field.bottom() <= viewport.bottom(),
541                "{field:?} below {viewport:?}"
542            );
543        }
544        cx.update(|window, cx| assert!(input.focus_handle(cx).is_focused(window)));
545
546        // Once revealed, manual movement remains under application/user control
547        // until a new native reveal request, rather than snapping to focus.
548        outer.set_offset(point(px(0.), px(-10.)));
549        cx.update(|window, cx| window.draw(cx).clear(cx));
550        assert_eq!(outer.offset().y, px(-10.));
551    }
552}