Skip to main content

gpui_material_extras/data_views/
virtual_list.rs

1use std::{ops::Range, rc::Rc};
2
3use gpui::{
4    App, Axis, Bounds, Context, ElementId, Entity, FocusHandle, Hsla, InteractiveElement,
5    IntoElement, KeyDownEvent, ListSizingBehavior, ParentElement, Pixels, Point, Render,
6    RenderOnce, Role, ScrollHandle, ScrollStrategy, SharedString, Size, StatefulInteractiveElement,
7    StyleRefinement, Styled, Window, canvas, div, point, prelude::FluentBuilder, px,
8    transparent_black,
9};
10use gpui_base::{
11    StyledExt as _, TestSupportExt as _, VirtualList as BaseVirtualList,
12    VirtualListScrollHandle as BaseVirtualListScrollHandle, virtual_list as base_virtual_list,
13};
14use gpui_material_components::{
15    DisplayScrollbar, DisplayScrollbarFade, DisplayScrollbarStyle, ScrollbarHandle,
16};
17use gpui_material_foundation::{
18    FocusRingPlacement, InteractionFeedback, InteractionState, Shape, color,
19    current_material_theme, resolve_edges,
20};
21use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Density, Direction, LogicalEdges};
22
23const DEFAULT_KEYBOARD_STEP: f32 = 48.0;
24const MIN_KEYBOARD_STEP: f32 = 32.0;
25
26/// Retained scroll handle for [`VirtualList`].
27///
28/// Wraps `gpui-base`'s virtual list scroll state and implements [`ScrollbarHandle`]
29/// so it integrates directly with [`DisplayScrollbar`] and programmatic scrolling.
30#[derive(Clone)]
31pub struct VirtualListScrollHandle {
32    inner: BaseVirtualListScrollHandle,
33}
34
35impl Default for VirtualListScrollHandle {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl From<ScrollHandle> for VirtualListScrollHandle {
42    fn from(handle: ScrollHandle) -> Self {
43        Self {
44            inner: BaseVirtualListScrollHandle::from(handle),
45        }
46    }
47}
48
49impl AsRef<ScrollHandle> for VirtualListScrollHandle {
50    fn as_ref(&self) -> &ScrollHandle {
51        self.inner.as_ref()
52    }
53}
54
55impl ScrollbarHandle for VirtualListScrollHandle {
56    fn viewport_bounds(&self) -> Bounds<Pixels> {
57        self.inner.viewport_bounds()
58    }
59
60    fn offset(&self) -> Point<Pixels> {
61        self.inner.offset()
62    }
63
64    fn set_offset(&self, offset: Point<Pixels>) {
65        self.inner.set_offset(offset);
66    }
67
68    fn content_size(&self) -> Size<Pixels> {
69        self.inner.content_size()
70    }
71}
72
73impl VirtualListScrollHandle {
74    /// Creates a new scroll handle for a [`VirtualList`].
75    pub fn new() -> Self {
76        Self {
77            inner: BaseVirtualListScrollHandle::new(),
78        }
79    }
80
81    /// Returns the underlying GPUI [`ScrollHandle`].
82    pub fn base_handle(&self) -> &ScrollHandle {
83        self.inner.base_handle()
84    }
85
86    /// Scrolls the list so the item at `index` is positioned according to `strategy`.
87    pub fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy) {
88        self.inner.scroll_to_item(index, strategy);
89    }
90
91    /// Scrolls to the end of the list.
92    pub fn scroll_to_bottom(&self) {
93        self.inner.scroll_to_bottom();
94    }
95
96    /// Returns the current scroll offset in logical pixels.
97    pub fn offset(&self) -> Point<Pixels> {
98        self.inner.offset()
99    }
100
101    /// Sets the scroll offset in logical pixels.
102    pub fn set_offset(&self, offset: Point<Pixels>) {
103        self.inner.set_offset(offset);
104    }
105
106    /// Returns the measured total content size in logical pixels.
107    pub fn content_size(&self) -> Size<Pixels> {
108        self.inner.content_size()
109    }
110
111    /// Returns the viewport bounds from the most recent frame.
112    pub fn viewport_bounds(&self) -> Bounds<Pixels> {
113        self.inner.viewport_bounds()
114    }
115}
116
117/// Surface presentation variant for [`VirtualList`].
118#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
119pub enum VirtualListVariant {
120    /// Transparent scroll container suitable for embedding inside an existing surface (default).
121    #[default]
122    Standard,
123    /// Material 3 container with `SurfaceContainerLow` fill, `OutlineVariant` border, and `Medium` rounded corners.
124    Contained,
125}
126
127/// Optional per-instance color overrides for [`VirtualList`].
128#[derive(Clone, Copy, Debug, Default, PartialEq)]
129pub struct VirtualListColors {
130    /// Container background fill (defaults to transparent for `Standard` or `SurfaceContainerLow` for `Contained`).
131    pub container: Option<Hsla>,
132    /// Container border color (defaults to transparent for `Standard` or `OutlineVariant` for `Contained`).
133    pub border: Option<Hsla>,
134}
135
136/// Material 3 Expressive virtualized list container over `gpui-base`'s variable-size [`BaseVirtualList`].
137///
138/// Automatically mounts a Material [`DisplayScrollbar`] along the active scroll axis, respects
139/// `theme.layout.direction` (RTL scrollbar placement and horizontal keyboard scrolling) and
140/// `theme.layout.density`, and provides keyboard scrolling (`Up`/`Down`/`PageUp`/`PageDown`/`Home`/`End`
141/// vertically, `Left`/`Right`/`Home`/`End` horizontally) with a Material keyboard focus ring.
142#[derive(IntoElement)]
143pub struct VirtualList {
144    id: ElementId,
145    axis: Axis,
146    base: BaseVirtualList,
147    scroll_handle: Option<VirtualListScrollHandle>,
148    focus_handle: Option<FocusHandle>,
149    variant: VirtualListVariant,
150    shape: Option<CornerShape>,
151    colors: VirtualListColors,
152    content_padding: LogicalEdges,
153    item_gap: Pixels,
154    show_scrollbar: bool,
155    scrollbar_style: DisplayScrollbarStyle,
156    scrollbar_fade: DisplayScrollbarFade,
157    accessible_label: Option<SharedString>,
158    keyboard_scroll_step: Option<Pixels>,
159    style: StyleRefinement,
160}
161
162impl VirtualList {
163    /// Creates a vertical [`VirtualList`] for variable-height rows.
164    pub fn vertical<R, V>(
165        view: Entity<V>,
166        id: impl Into<ElementId>,
167        item_sizes: Rc<Vec<Size<Pixels>>>,
168        render_range: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
169    ) -> Self
170    where
171        R: IntoElement,
172        V: Render,
173    {
174        Self::new(view, id, Axis::Vertical, item_sizes, render_range)
175    }
176
177    /// Creates a horizontal [`VirtualList`] for variable-width columns.
178    pub fn horizontal<R, V>(
179        view: Entity<V>,
180        id: impl Into<ElementId>,
181        item_sizes: Rc<Vec<Size<Pixels>>>,
182        render_range: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
183    ) -> Self
184    where
185        R: IntoElement,
186        V: Render,
187    {
188        Self::new(view, id, Axis::Horizontal, item_sizes, render_range)
189    }
190
191    /// Creates a [`VirtualList`] along `axis` for variable-size items.
192    pub fn new<R, V>(
193        view: Entity<V>,
194        id: impl Into<ElementId>,
195        axis: Axis,
196        item_sizes: Rc<Vec<Size<Pixels>>>,
197        render_range: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
198    ) -> Self
199    where
200        R: IntoElement,
201        V: Render,
202    {
203        let id: ElementId = id.into();
204        let inner_id = ElementId::from((id.clone(), "viewport"));
205        let base = base_virtual_list(view, inner_id, axis, item_sizes, render_range);
206        Self {
207            id,
208            axis,
209            base,
210            scroll_handle: None,
211            focus_handle: None,
212            variant: VirtualListVariant::Standard,
213            shape: None,
214            colors: VirtualListColors::default(),
215            content_padding: LogicalEdges::ZERO,
216            item_gap: px(0.),
217            show_scrollbar: true,
218            scrollbar_style: DisplayScrollbarStyle::default(),
219            scrollbar_fade: DisplayScrollbarFade::default(),
220            accessible_label: None,
221            keyboard_scroll_step: None,
222            style: StyleRefinement::default(),
223        }
224    }
225
226    /// Binds a caller-retained [`VirtualListScrollHandle`] for programmatic scrolling and observation.
227    pub fn track_scroll(mut self, scroll_handle: &VirtualListScrollHandle) -> Self {
228        self.scroll_handle = Some(scroll_handle.clone());
229        self
230    }
231
232    /// Attaches a caller-owned [`FocusHandle`] for keyboard scrolling and focus management.
233    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
234        self.focus_handle = Some(focus.clone());
235        self
236    }
237
238    /// Sets the surface presentation variant (`Standard` or `Contained`).
239    pub fn variant(mut self, variant: VirtualListVariant) -> Self {
240        self.variant = variant;
241        self
242    }
243
244    /// Sets the container corner shape (defaults to `CornerRole::None` for `Standard` or
245    /// `CornerRole::Medium` for `Contained`).
246    pub fn shape(mut self, shape: CornerShape) -> Self {
247        self.shape = Some(shape);
248        self
249    }
250
251    /// Applies per-instance container and border color overrides.
252    pub fn colors(mut self, colors: VirtualListColors) -> Self {
253        self.colors = colors;
254        self
255    }
256
257    /// Sets direction-aware inner padding inside the scrolling viewport.
258    pub fn content_padding(mut self, padding: LogicalEdges) -> Self {
259        self.content_padding = padding.sanitize();
260        self
261    }
262
263    /// Sets the spacing gap between virtualized items along the scroll axis.
264    pub fn item_gap(mut self, gap: Pixels) -> Self {
265        if f32::from(gap).is_finite() && gap >= px(0.) {
266            self.item_gap = gap;
267        }
268        self
269    }
270
271    /// Configures how the underlying virtual list sizes itself when unconstrained.
272    pub fn sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
273        self.base = self.base.with_sizing_behavior(behavior);
274        self
275    }
276
277    /// Sets the item index measured to infer cross-axis content extent.
278    pub fn item_to_measure_index(mut self, index: usize) -> Self {
279        self.base = self.base.with_item_to_measure_index(index);
280        self
281    }
282
283    /// Shows or hides the Material [`DisplayScrollbar`] overlay (defaults to `true`).
284    pub fn show_scrollbar(mut self, show: bool) -> Self {
285        self.show_scrollbar = show;
286        self
287    }
288
289    /// Customizes the [`DisplayScrollbar`] dimensions and colors.
290    pub fn scrollbar_style(mut self, style: DisplayScrollbarStyle) -> Self {
291        self.scrollbar_style = style;
292        self
293    }
294
295    /// Customizes the [`DisplayScrollbar`] auto-hide fade behavior.
296    pub fn scrollbar_fade(mut self, fade: DisplayScrollbarFade) -> Self {
297        self.scrollbar_fade = fade;
298        self
299    }
300
301    /// Sets the accessible name announced for the `Role::List` container.
302    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
303        self.accessible_label = Some(label.into());
304        self
305    }
306
307    /// Overrides the per-keypress scroll distance for arrow keys (defaults to a density-aware step).
308    pub fn keyboard_scroll_step(mut self, step: Pixels) -> Self {
309        if f32::from(step).is_finite() && step > px(0.) {
310            self.keyboard_scroll_step = Some(step);
311        }
312        self
313    }
314}
315
316impl Styled for VirtualList {
317    fn style(&mut self) -> &mut StyleRefinement {
318        &mut self.style
319    }
320}
321
322fn keyboard_step(density: Density, override_step: Option<Pixels>) -> Pixels {
323    override_step.unwrap_or_else(|| {
324        px(density
325            .visual_size(DEFAULT_KEYBOARD_STEP)
326            .max(MIN_KEYBOARD_STEP))
327    })
328}
329
330fn compute_keyboard_scroll_offset(
331    axis: Axis,
332    direction: Direction,
333    key: &str,
334    current: Point<Pixels>,
335    viewport: Size<Pixels>,
336    content: Size<Pixels>,
337    step: Pixels,
338) -> Option<Point<Pixels>> {
339    match axis {
340        Axis::Vertical => {
341            let max_scroll = (content.height - viewport.height).max(px(0.));
342            let min_offset = -max_scroll;
343            let page = (viewport.height * 0.85).max(step);
344            let next_y = match key {
345                "up" => (current.y + step).min(px(0.)),
346                "down" => (current.y - step).max(min_offset),
347                "pageup" => (current.y + page).min(px(0.)),
348                "pagedown" => (current.y - page).max(min_offset),
349                "home" => px(0.),
350                "end" => min_offset,
351                _ => return None,
352            };
353            Some(point(current.x, next_y.clamp(min_offset, px(0.))))
354        }
355        Axis::Horizontal => {
356            let max_scroll = (content.width - viewport.width).max(px(0.));
357            let min_offset = -max_scroll;
358            let rtl = direction == Direction::Rtl;
359            let page = (viewport.width * 0.85).max(step);
360            let backward = (key == "left" && !rtl) || (key == "right" && rtl);
361            let forward = (key == "right" && !rtl) || (key == "left" && rtl);
362            let next_x = if backward {
363                (current.x + step).min(px(0.))
364            } else if forward {
365                (current.x - step).max(min_offset)
366            } else {
367                match key {
368                    "pageup" => (current.x + page).min(px(0.)),
369                    "pagedown" => (current.x - page).max(min_offset),
370                    "home" => px(0.),
371                    "end" => min_offset,
372                    _ => return None,
373                }
374            };
375            Some(point(next_x.clamp(min_offset, px(0.)), current.y))
376        }
377    }
378}
379
380impl RenderOnce for VirtualList {
381    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
382        let theme = current_material_theme(window, cx).clone();
383        let direction = theme.layout.direction;
384        let density = theme.layout.density;
385        let reduced_motion = cx.reduce_motion();
386        let tone = |role| color(theme.colors.color(role));
387
388        let (default_bg, default_border, default_shape) = match self.variant {
389            VirtualListVariant::Standard => (
390                transparent_black(),
391                transparent_black(),
392                CornerRole::None.shape(),
393            ),
394            VirtualListVariant::Contained => (
395                tone(ColorRole::SurfaceContainerLow),
396                tone(ColorRole::OutlineVariant),
397                CornerRole::Medium.shape(),
398            ),
399        };
400        let bg = self.colors.container.unwrap_or(default_bg);
401        let border = self.colors.border.unwrap_or(default_border);
402        let has_border = border.a > 0.0;
403        let shape = self.shape.unwrap_or(default_shape);
404        let radii = shape.radii(100.0, 100.0, direction);
405        let focus_ring_color = tone(ColorRole::Secondary);
406
407        let scroll_handle = self.scroll_handle.unwrap_or_else(|| {
408            window
409                .use_keyed_state((self.id.clone(), "virtual-list-scroll"), cx, |_, _| {
410                    VirtualListScrollHandle::new()
411                })
412                .read(cx)
413                .clone()
414        });
415        let focus_handle = self.focus_handle.unwrap_or_else(|| {
416            window
417                .use_keyed_state((self.id.clone(), "virtual-list-focus"), cx, |_, cx| {
418                    cx.focus_handle()
419                })
420                .read(cx)
421                .clone()
422        });
423        let focus_visible = focus_handle.is_focused(window) && window.last_input_was_keyboard();
424
425        let padding = resolve_edges(self.content_padding, direction);
426        let mut inner = self
427            .base
428            .track_scroll(&scroll_handle.inner)
429            .size_full()
430            .pt(padding.top)
431            .pb(padding.bottom)
432            .pl(padding.left)
433            .pr(padding.right);
434        if self.item_gap > px(0.) {
435            inner = inner.gap(self.item_gap);
436        }
437
438        let axis = self.axis;
439        let step = keyboard_step(density, self.keyboard_scroll_step);
440        let key_scroll = scroll_handle.clone();
441        let key_focus = focus_handle.clone();
442
443        let focus_ring_overlay = focus_visible.then(|| {
444            canvas(
445                move |bounds, _, _| Shape::rounded(bounds, shape, direction),
446                move |_, prepared, window, cx| {
447                    let Some(shape) = prepared else {
448                        return;
449                    };
450                    let mut interaction = InteractionState::default();
451                    interaction.focus_visible = true;
452                    InteractionFeedback::new(interaction, transparent_black(), focus_ring_color)
453                        .focus_ring_placement(FocusRingPlacement::Inset)
454                        .paint(
455                            &shape,
456                            None,
457                            cx.background_executor().now(),
458                            reduced_motion,
459                            window,
460                        );
461                },
462            )
463            .absolute()
464            .inset_0()
465        });
466
467        let mut container = div()
468            .id(self.id.clone())
469            .test_support()
470            .role(Role::List)
471            .when_some(self.accessible_label, |el, label| el.aria_label(label))
472            .track_focus(&focus_handle)
473            .tab_stop(true)
474            .relative()
475            .w_full()
476            .bg(bg)
477            .when(has_border, |el| el.border_1().border_color(border))
478            .rounded_tl(px(radii[0]))
479            .rounded_tr(px(radii[1]))
480            .rounded_br(px(radii[2]))
481            .rounded_bl(px(radii[3]))
482            .overflow_hidden()
483            .on_key_down(move |event: &KeyDownEvent, window, cx| {
484                if event.keystroke.modifiers.modified() || !key_focus.is_focused(window) {
485                    return;
486                }
487                let viewport = key_scroll.viewport_bounds().size;
488                let content = key_scroll.content_size();
489                if let Some(next) = compute_keyboard_scroll_offset(
490                    axis,
491                    direction,
492                    &event.keystroke.key,
493                    key_scroll.offset(),
494                    viewport,
495                    content,
496                    step,
497                ) {
498                    key_scroll.set_offset(next);
499                    cx.stop_propagation();
500                    window.refresh();
501                }
502            })
503            .child(inner);
504
505        if self.show_scrollbar {
506            container = container.child(
507                DisplayScrollbar::new((self.id, "scrollbar"), axis, &scroll_handle)
508                    .style(self.scrollbar_style)
509                    .fade(self.scrollbar_fade),
510            );
511        }
512
513        container
514            .children(focus_ring_overlay)
515            .refine_style(&self.style)
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522    use gpui::size;
523
524    #[test]
525    fn vertical_keyboard_scroll_clamps_to_content_extent() {
526        let viewport = size(px(300.), px(200.));
527        let content = size(px(300.), px(1000.));
528        let step = px(48.);
529
530        let down = compute_keyboard_scroll_offset(
531            Axis::Vertical,
532            Direction::Ltr,
533            "down",
534            point(px(0.), px(0.)),
535            viewport,
536            content,
537            step,
538        );
539        assert_eq!(down, Some(point(px(0.), px(-48.))));
540
541        let up_clamped = compute_keyboard_scroll_offset(
542            Axis::Vertical,
543            Direction::Ltr,
544            "up",
545            point(px(0.), px(-20.)),
546            viewport,
547            content,
548            step,
549        );
550        assert_eq!(up_clamped, Some(point(px(0.), px(0.))));
551
552        let end = compute_keyboard_scroll_offset(
553            Axis::Vertical,
554            Direction::Ltr,
555            "end",
556            point(px(0.), px(0.)),
557            viewport,
558            content,
559            step,
560        );
561        assert_eq!(end, Some(point(px(0.), px(-800.))));
562
563        let home = compute_keyboard_scroll_offset(
564            Axis::Vertical,
565            Direction::Ltr,
566            "home",
567            point(px(0.), px(-500.)),
568            viewport,
569            content,
570            step,
571        );
572        assert_eq!(home, Some(point(px(0.), px(0.))));
573    }
574
575    #[test]
576    fn horizontal_keyboard_scroll_mirrors_in_rtl() {
577        let viewport = size(px(200.), px(100.));
578        let content = size(px(600.), px(100.));
579        let step = px(40.);
580
581        let ltr_right = compute_keyboard_scroll_offset(
582            Axis::Horizontal,
583            Direction::Ltr,
584            "right",
585            point(px(0.), px(0.)),
586            viewport,
587            content,
588            step,
589        );
590        assert_eq!(ltr_right, Some(point(px(-40.), px(0.))));
591
592        let rtl_left = compute_keyboard_scroll_offset(
593            Axis::Horizontal,
594            Direction::Rtl,
595            "left",
596            point(px(0.), px(0.)),
597            viewport,
598            content,
599            step,
600        );
601        assert_eq!(rtl_left, Some(point(px(-40.), px(0.))));
602
603        let rtl_right = compute_keyboard_scroll_offset(
604            Axis::Horizontal,
605            Direction::Rtl,
606            "right",
607            point(px(-100.), px(0.)),
608            viewport,
609            content,
610            step,
611        );
612        assert_eq!(rtl_right, Some(point(px(-60.), px(0.))));
613    }
614}