Skip to main content

gpui_base/
virtual_list.rs

1//! Virtual List for render a large number of differently sized rows/columns.
2//!
3//! > NOTE: This must ensure each column width or row height.
4//!
5//! Only visible range are rendered for performance reasons.
6//!
7//! Inspired by `gpui::uniform_list`.
8//! https://github.com/zed-industries/zed/blob/0ae1603610ab6b265bdfbee7b8dbc23c5ab06edc/crates/gpui/src/elements/uniform_list.rs
9//!
10//! Unlike the `uniform_list`, the each item can have different size.
11//!
12//! This is useful for more complex layout, for example, a table with different row height.
13use std::{
14    cell::RefCell,
15    ops::{Deref, Range},
16    rc::Rc,
17};
18
19use gpui::{
20    Along, AnyElement, App, AvailableSpace, Axis, Bounds, ContentMask, Context,
21    DeferredScrollToItem, Div, Element, ElementId, Entity, GlobalElementId, Half, Hitbox,
22    InteractiveElement, IntoElement, IsZero as _, ListSizingBehavior, Pixels, Point, Render,
23    ScrollHandle, ScrollStrategy, Size, Stateful, StatefulInteractiveElement, StyleRefinement,
24    Styled, Window, div, point, px, size,
25};
26use smallvec::SmallVec;
27
28use crate::{AxisExt, InteractiveElementExt as _};
29
30struct VirtualListScrollHandleState {
31    axis: Axis,
32    items_count: usize,
33    /// Content bounds size (excluding padding and border) from the last frame.
34    last_content_size: Option<Size<Pixels>>,
35    pub deferred_scroll_to_item: Option<DeferredScrollToItem>,
36}
37
38/// A scroll handle for [`VirtualList`].
39///
40/// See also [`ScrollHandle`].
41#[derive(Clone)]
42pub struct VirtualListScrollHandle {
43    state: Rc<RefCell<VirtualListScrollHandleState>>,
44    base_handle: ScrollHandle,
45}
46
47impl From<ScrollHandle> for VirtualListScrollHandle {
48    fn from(handle: ScrollHandle) -> Self {
49        let mut this = VirtualListScrollHandle::new();
50        this.base_handle = handle;
51        this
52    }
53}
54
55impl AsRef<ScrollHandle> for VirtualListScrollHandle {
56    fn as_ref(&self) -> &ScrollHandle {
57        &self.base_handle
58    }
59}
60
61impl crate::ScrollbarHandle for VirtualListScrollHandle {
62    fn viewport_bounds(&self) -> Bounds<Pixels> {
63        self.base_handle.bounds()
64    }
65
66    fn offset(&self) -> Point<Pixels> {
67        self.base_handle.offset()
68    }
69
70    fn set_offset(&self, offset: Point<Pixels>) {
71        self.base_handle.set_offset(offset);
72    }
73
74    fn content_size(&self) -> Size<Pixels> {
75        self.base_handle.content_size()
76    }
77}
78
79impl Deref for VirtualListScrollHandle {
80    type Target = ScrollHandle;
81
82    fn deref(&self) -> &Self::Target {
83        &self.base_handle
84    }
85}
86
87impl VirtualListScrollHandle {
88    /// Create a new VirtualListScrollHandle.
89    pub fn new() -> Self {
90        VirtualListScrollHandle {
91            state: Rc::new(RefCell::new(VirtualListScrollHandleState {
92                axis: Axis::Vertical,
93                items_count: 0,
94                last_content_size: None,
95                deferred_scroll_to_item: None,
96            })),
97            base_handle: ScrollHandle::default(),
98        }
99    }
100
101    /// Get the base scroll handle.
102    pub fn base_handle(&self) -> &ScrollHandle {
103        &self.base_handle
104    }
105
106    /// Scroll to the item at the given index.
107    pub fn scroll_to_item(&self, ix: usize, strategy: ScrollStrategy) {
108        self.scroll_to_item_with_offset(ix, strategy, 0);
109    }
110
111    /// Scroll to the item at the given index, with an additional offset items.
112    fn scroll_to_item_with_offset(&self, ix: usize, strategy: ScrollStrategy, offset: usize) {
113        let mut state = self.state.borrow_mut();
114        state.deferred_scroll_to_item = Some(DeferredScrollToItem {
115            item_index: ix,
116            strategy,
117            offset,
118            scroll_strict: false,
119        });
120    }
121
122    /// Scrolls to the bottom of the list.
123    pub fn scroll_to_bottom(&self) {
124        let items_count = self.state.borrow().items_count;
125        self.scroll_to_item(items_count.saturating_sub(1), ScrollStrategy::Top);
126    }
127}
128
129/// Create a [`VirtualList`] in vertical direction.
130///
131/// This is like `uniform_list` in GPUI, but support two axis.
132///
133/// The `item_sizes` is the size of each row. Only the `height` is used; `width` is inferred
134/// by measuring the item selected with [`VirtualList::with_item_to_measure_index`], defaulting
135/// to the first item.
136///
137/// See also [`h_virtual_list`]
138#[inline]
139pub fn v_virtual_list<R, V>(
140    view: Entity<V>,
141    id: impl Into<ElementId>,
142    item_sizes: Rc<Vec<Size<Pixels>>>,
143    f: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
144) -> VirtualList
145where
146    R: IntoElement,
147    V: Render,
148{
149    virtual_list(view, id, Axis::Vertical, item_sizes, f)
150}
151
152/// Create a [`VirtualList`] in horizontal direction.
153///
154/// The `item_sizes` is the size of each column. Only the `width` is used; `height` is inferred
155/// by measuring the item selected with [`VirtualList::with_item_to_measure_index`], defaulting
156/// to the first item.
157///
158/// See also [`v_virtual_list`]
159#[inline]
160pub fn h_virtual_list<R, V>(
161    view: Entity<V>,
162    id: impl Into<ElementId>,
163    item_sizes: Rc<Vec<Size<Pixels>>>,
164    f: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
165) -> VirtualList
166where
167    R: IntoElement,
168    V: Render,
169{
170    virtual_list(view, id, Axis::Horizontal, item_sizes, f)
171}
172
173#[doc(hidden)]
174pub fn virtual_list<R, V>(
175    view: Entity<V>,
176    id: impl Into<ElementId>,
177    axis: Axis,
178    item_sizes: Rc<Vec<Size<Pixels>>>,
179    f: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
180) -> VirtualList
181where
182    R: IntoElement,
183    V: Render,
184{
185    let id: ElementId = id.into();
186    let scroll_handle = VirtualListScrollHandle::new();
187    let render_range = move |visible_range, window: &mut Window, cx: &mut App| {
188        view.update(cx, |this, cx| {
189            f(this, visible_range, window, cx)
190                .into_iter()
191                .map(|component| component.into_any_element())
192                .collect()
193        })
194    };
195
196    VirtualList {
197        id: id.clone(),
198        axis,
199        base: div()
200            .id(id)
201            .size_full()
202            .overflow_scroll()
203            .lock_scroll_axis()
204            .track_scroll(&scroll_handle),
205        scroll_handle,
206        items_count: item_sizes.len(),
207        item_sizes,
208        render_items: Box::new(render_range),
209        sizing_behavior: ListSizingBehavior::default(),
210        item_to_measure_index: 0,
211        measure_cross_axis: true,
212    }
213}
214
215/// VirtualList component for rendering a large number of differently sized items.
216pub struct VirtualList {
217    id: ElementId,
218    axis: Axis,
219    base: Stateful<Div>,
220    scroll_handle: VirtualListScrollHandle,
221    items_count: usize,
222    item_sizes: Rc<Vec<Size<Pixels>>>,
223    render_items: Box<
224        dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
225    >,
226    sizing_behavior: ListSizingBehavior,
227    item_to_measure_index: usize,
228    /// Whether to render and lay out an item each frame to infer the
229    /// cross-axis content size.
230    measure_cross_axis: bool,
231}
232
233impl Styled for VirtualList {
234    fn style(&mut self) -> &mut StyleRefinement {
235        self.base.style()
236    }
237}
238
239impl VirtualList {
240    pub fn track_scroll(mut self, scroll_handle: &VirtualListScrollHandle) -> Self {
241        self.base = self.base.track_scroll(&scroll_handle);
242        self.scroll_handle = scroll_handle.clone();
243        self
244    }
245
246    /// Set the sizing behavior for the list.
247    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
248        self.sizing_behavior = behavior;
249        self
250    }
251
252    /// Set the item index used to infer the list's cross-axis size.
253    pub fn with_item_to_measure_index(mut self, index: usize) -> Self {
254        self.item_to_measure_index = index;
255        self
256    }
257
258    /// Specify for table.
259    ///
260    /// Table is special, because the `scroll_handle` is based on Table head (That is not a virtual list).
261    ///
262    /// Such a list only follows the shared handle along its axis and never
263    /// scrolls across it: it fills the size its parent gives it, so the
264    /// cross-axis content size is not measured. That saves rendering and
265    /// laying out one extra item per list every frame, i.e. one per table row.
266    #[doc(hidden)]
267    pub fn with_scroll_handle(mut self, scroll_handle: &VirtualListScrollHandle) -> Self {
268        self.base = div().id(self.id.clone()).size_full();
269        self.scroll_handle = scroll_handle.clone();
270        self.measure_cross_axis = false;
271        self
272    }
273
274    fn scroll_to_deferred_item(
275        &self,
276        scroll_offset: Point<Pixels>,
277        size_layout: &ItemSizeLayout,
278        content_bounds: &Bounds<Pixels>,
279        scroll_to_item: DeferredScrollToItem,
280    ) -> Point<Pixels> {
281        let Some(bounds) = size_layout.item_bounds(
282            scroll_to_item.item_index + scroll_to_item.offset,
283            self.axis,
284            content_bounds,
285        ) else {
286            return scroll_offset;
287        };
288
289        let mut scroll_offset = scroll_offset;
290        match scroll_to_item.strategy {
291            ScrollStrategy::Center => {
292                if self.axis.is_vertical() {
293                    scroll_offset.y = content_bounds.top() + content_bounds.size.height.half()
294                        - bounds.top()
295                        - bounds.size.height.half()
296                } else {
297                    scroll_offset.x = content_bounds.left() + content_bounds.size.width.half()
298                        - bounds.left()
299                        - bounds.size.width.half()
300                }
301            }
302            _ => {
303                // Ref: https://github.com/zed-industries/zed/blob/0d145289e0867a8d5d63e5e1397a5ca69c9d49c3/crates/gpui/src/elements/div.rs#L3026
304                if self.axis.is_vertical() {
305                    if bounds.top() + scroll_offset.y < content_bounds.top() {
306                        scroll_offset.y = content_bounds.top() - bounds.top()
307                    } else if bounds.bottom() + scroll_offset.y > content_bounds.bottom() {
308                        scroll_offset.y = content_bounds.bottom() - bounds.bottom();
309                    }
310                } else {
311                    if bounds.left() + scroll_offset.x < content_bounds.left() {
312                        scroll_offset.x = content_bounds.left() - bounds.left();
313                    } else if bounds.right() + scroll_offset.x > content_bounds.right() {
314                        scroll_offset.x = content_bounds.right() - bounds.right();
315                    }
316                }
317            }
318        }
319        self.scroll_handle.set_offset(scroll_offset);
320        scroll_offset
321    }
322
323    /// Ref from: https://github.com/zed-industries/zed/blob/83f9f9d9e3f5914392cab9a09e3472711a1d7b38/crates/gpui/src/elements/uniform_list.rs#L660
324    fn measure_item(
325        &self,
326        list_width: Option<Pixels>,
327        window: &mut Window,
328        cx: &mut App,
329    ) -> Size<Pixels> {
330        if self.items_count == 0 || !self.measure_cross_axis {
331            return Size::default();
332        }
333
334        let item_ix = self.item_to_measure_index.min(self.items_count - 1);
335        let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
336        let Some(mut item_to_measure) = items.pop() else {
337            return Size::default();
338        };
339        let available_space = size(
340            list_width.map_or(AvailableSpace::MinContent, |width| {
341                AvailableSpace::Definite(width)
342            }),
343            AvailableSpace::MinContent,
344        );
345        item_to_measure.layout_as_root(available_space, window, cx)
346    }
347}
348
349/// Frame state used by the [VirtualItem].
350pub struct VirtualListFrameState {
351    /// Visible items to be painted.
352    items: SmallVec<[AnyElement; 32]>,
353    size_layout: ItemSizeLayout,
354}
355
356/// Per-item sizes along the list axis, gap included, and their prefix sums.
357///
358/// Shared between the element state and the frame state so that carrying
359/// them across a frame is a reference count, not a copy of every item.
360#[derive(Default, Clone)]
361pub struct ItemSizeLayout {
362    items_sizes: Rc<Vec<Size<Pixels>>>,
363    axis_and_gap: Option<(Axis, Pixels)>,
364    content_size: Size<Pixels>,
365    sizes: Rc<[Pixels]>,
366    origins: Rc<[Pixels]>,
367    last_layout_bounds: Bounds<Pixels>,
368}
369
370impl ItemSizeLayout {
371    /// The bounds of item `ix` in the list's content space: offset from the
372    /// content origin along the list axis, filling it on the other.
373    fn item_bounds(
374        &self,
375        ix: usize,
376        axis: Axis,
377        content_bounds: &Bounds<Pixels>,
378    ) -> Option<Bounds<Pixels>> {
379        let origin = *self.origins.get(ix)?;
380        let item_size = self.sizes[ix];
381        Some(match axis {
382            Axis::Horizontal => Bounds {
383                origin: point(content_bounds.left() + origin, px(0.)),
384                size: size(item_size, content_bounds.size.height),
385            },
386            Axis::Vertical => Bounds {
387                origin: point(px(0.), content_bounds.top() + origin),
388                size: size(content_bounds.size.width, item_size),
389            },
390        })
391    }
392}
393
394/// The items that intersect `viewport` along the list axis, plus one item of
395/// overdraw past its end, given each item's origin and size (gap included).
396///
397/// Both edges are binary searches.
398fn visible_range(origins: &[Pixels], sizes: &[Pixels], viewport: Range<Pixels>) -> Range<usize> {
399    let count = origins.len();
400    // Item ends grow with the index, so the first item ending past `edge` is
401    // a partition point over the indices.
402    let ends_before = |edge: Pixels| {
403        let mut low = 0;
404        let mut high = count;
405        while low < high {
406            let mid = low + (high - low) / 2;
407            if origins[mid] + sizes[mid] <= edge {
408                low = mid + 1;
409            } else {
410                high = mid;
411            }
412        }
413        low
414    };
415    let first = ends_before(viewport.start);
416    let past_end = ends_before(viewport.end);
417    let last = if past_end == count {
418        count
419    } else {
420        (past_end + 2).min(count)
421    };
422    first..last.max(first)
423}
424
425#[cfg(not(feature = "gpui-fast"))]
426impl IntoElement for VirtualList {
427    type Element = Self;
428
429    fn into_element(self) -> Self::Element {
430        self
431    }
432}
433
434impl Element for VirtualList {
435    type RequestLayoutState = VirtualListFrameState;
436    type PrepaintState = Option<Hitbox>;
437
438    fn id(&self) -> Option<ElementId> {
439        Some(self.id.clone())
440    }
441
442    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
443        None
444    }
445
446    fn request_layout(
447        &mut self,
448        global_id: Option<&GlobalElementId>,
449        inspector_id: Option<&gpui::InspectorElementId>,
450        window: &mut Window,
451        cx: &mut App,
452    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
453        let rem_size = window.rem_size();
454        let font_size = window.text_style().font_size.to_pixels(rem_size);
455        let mut size_layout = ItemSizeLayout::default();
456        // Measure vertical lists at the last known content width so relative
457        // widths and text truncation resolve like the visible rows; an
458        // unconstrained measure would turn one long non-wrapping text into a
459        // phantom horizontal scroll range.
460        let list_width = if self.axis.is_vertical() {
461            self.scroll_handle
462                .state
463                .borrow()
464                .last_content_size
465                .map(|size| size.width)
466                .filter(|width| !width.is_zero())
467        } else {
468            None
469        };
470        let longest_item_size = self.measure_item(list_width, window, cx);
471
472        let layout_id = self.base.interactivity().request_layout(
473            global_id,
474            inspector_id,
475            window,
476            cx,
477            |style, window, cx| {
478                size_layout = window.with_element_state(
479                    global_id.unwrap(),
480                    |state: Option<ItemSizeLayout>, _window| {
481                        let mut state = state.unwrap_or(ItemSizeLayout::default());
482
483                        // Including the gap between items for calculate the item size
484                        let gap = style
485                            .gap
486                            .along(self.axis)
487                            .to_pixels(font_size.into(), rem_size);
488
489                        if state.items_sizes != self.item_sizes
490                            || state.axis_and_gap != Some((self.axis, gap))
491                        {
492                            state.items_sizes = self.item_sizes.clone();
493                            state.axis_and_gap = Some((self.axis, gap));
494                            // Prepare each item's size by axis
495                            state.sizes = self
496                                .item_sizes
497                                .iter()
498                                .enumerate()
499                                .map(|(i, size)| {
500                                    let size = size.along(self.axis);
501                                    if i + 1 == self.items_count {
502                                        size
503                                    } else {
504                                        size + gap
505                                    }
506                                })
507                                .collect();
508
509                            // Prepare each item's origin by axis
510                            let mut cumulative = px(0.);
511                            state.origins = state
512                                .sizes
513                                .iter()
514                                .map(|size| {
515                                    let origin = cumulative;
516                                    cumulative += *size;
517                                    origin
518                                })
519                                .collect();
520
521                            if self.axis.is_horizontal() {
522                                state.content_size.width = cumulative;
523                            } else {
524                                state.content_size.height = cumulative;
525                            }
526                        }
527
528                        if self.axis.is_horizontal() {
529                            state.content_size.height = longest_item_size.height;
530                        } else {
531                            state.content_size.width = longest_item_size.width;
532                        }
533
534                        (state.clone(), state)
535                    },
536                );
537
538                let axis = self.axis;
539                let layout_id =
540                    match self.sizing_behavior {
541                        ListSizingBehavior::Infer => {
542                            window.with_text_style(style.text_style().cloned(), |window| {
543                                let size_layout = size_layout.clone();
544
545                                window.request_measured_layout(style, {
546                                    move |known_dimensions, available_space, _, _| {
547                                        let mut size = Size::default();
548                                        if axis.is_horizontal() {
549                                            size.width = known_dimensions.width.unwrap_or(
550                                                match available_space.width {
551                                                    AvailableSpace::Definite(x) => x,
552                                                    AvailableSpace::MinContent
553                                                    | AvailableSpace::MaxContent => {
554                                                        size_layout.content_size.width
555                                                    }
556                                                },
557                                            );
558                                            size.height = known_dimensions.height.unwrap_or(
559                                                match available_space.height {
560                                                    AvailableSpace::Definite(x) => x,
561                                                    AvailableSpace::MinContent
562                                                    | AvailableSpace::MaxContent => {
563                                                        size_layout.content_size.height
564                                                    }
565                                                },
566                                            );
567                                        } else {
568                                            size.width = known_dimensions.width.unwrap_or(
569                                                match available_space.width {
570                                                    AvailableSpace::Definite(x) => x,
571                                                    AvailableSpace::MinContent
572                                                    | AvailableSpace::MaxContent => {
573                                                        size_layout.content_size.width
574                                                    }
575                                                },
576                                            );
577                                            size.height = known_dimensions.height.unwrap_or(
578                                                match available_space.height {
579                                                    AvailableSpace::Definite(x) => x,
580                                                    AvailableSpace::MinContent
581                                                    | AvailableSpace::MaxContent => {
582                                                        size_layout.content_size.height
583                                                    }
584                                                },
585                                            );
586                                        }
587
588                                        size
589                                    }
590                                })
591                            })
592                        }
593                        ListSizingBehavior::Auto => window
594                            .with_text_style(style.text_style().cloned(), |window| {
595                                window.request_layout(style, None, cx)
596                            }),
597                    };
598
599                layout_id
600            },
601        );
602
603        (
604            layout_id,
605            VirtualListFrameState {
606                items: SmallVec::new(),
607                size_layout,
608            },
609        )
610    }
611
612    fn prepaint(
613        &mut self,
614        global_id: Option<&GlobalElementId>,
615        inspector_id: Option<&gpui::InspectorElementId>,
616        bounds: Bounds<Pixels>,
617        layout: &mut Self::RequestLayoutState,
618        window: &mut Window,
619        cx: &mut App,
620    ) -> Self::PrepaintState {
621        layout.size_layout.last_layout_bounds = bounds;
622
623        let style = self
624            .base
625            .interactivity()
626            .compute_style(global_id, None, window, cx);
627        let border_widths = style.border_widths.to_pixels(window.rem_size());
628        let paddings = style
629            .padding
630            .to_pixels(bounds.size.into(), window.rem_size());
631
632        let item_sizes = &layout.size_layout.sizes;
633        let item_origins = &layout.size_layout.origins;
634
635        let content_bounds = Bounds::from_corners(
636            bounds.origin
637                + point(
638                    border_widths.left + paddings.left,
639                    border_widths.top + paddings.top,
640                ),
641            bounds.bottom_right()
642                - point(
643                    border_widths.right + paddings.right,
644                    border_widths.bottom + paddings.bottom,
645                ),
646        );
647
648        let axis = self.axis;
649
650        let mut scroll_state = self.scroll_handle.state.borrow_mut();
651        scroll_state.axis = axis;
652        scroll_state.items_count = self.items_count;
653        scroll_state.last_content_size = Some(content_bounds.size);
654
655        let mut scroll_offset = self.scroll_handle.offset();
656        if let Some(scroll_to_item) = scroll_state.deferred_scroll_to_item.take() {
657            scroll_offset = self.scroll_to_deferred_item(
658                scroll_offset,
659                &layout.size_layout,
660                &content_bounds,
661                scroll_to_item,
662            );
663        }
664
665        scroll_offset = scroll_offset
666            .max(&point(
667                content_bounds.size.width - layout.size_layout.content_size.width,
668                content_bounds.size.height - layout.size_layout.content_size.height,
669            ))
670            .min(&point(px(0.), px(0.)));
671        if scroll_offset != self.scroll_handle.offset() {
672            self.scroll_handle.set_offset(scroll_offset);
673        }
674
675        self.base.interactivity().prepaint(
676            global_id,
677            inspector_id,
678            bounds,
679            layout.size_layout.content_size,
680            window,
681            cx,
682            |_style, _, hitbox, window, cx| {
683                if self.items_count > 0 {
684                    let min_scroll_offset = content_bounds.size.along(self.axis)
685                        - layout.size_layout.content_size.along(self.axis);
686
687                    let is_scrolled = !scroll_offset.along(self.axis).is_zero();
688                    if is_scrolled {
689                        match self.axis {
690                            Axis::Horizontal if scroll_offset.x < min_scroll_offset => {
691                                scroll_offset.x = min_scroll_offset;
692                                self.scroll_handle.set_offset(scroll_offset);
693                            }
694                            Axis::Vertical if scroll_offset.y < min_scroll_offset => {
695                                scroll_offset.y = min_scroll_offset;
696                                self.scroll_handle.set_offset(scroll_offset);
697                            }
698                            _ => {}
699                        }
700                    }
701
702                    // The viewport in content space: the scroll offset is
703                    // negative, and the leading padding is admitted at the
704                    // start so an item under it is still drawn.
705                    let viewport = match self.axis {
706                        Axis::Horizontal => {
707                            -(scroll_offset.x + paddings.left)
708                                ..-scroll_offset.x + content_bounds.size.width
709                        }
710                        Axis::Vertical => {
711                            -(scroll_offset.y + paddings.top)
712                                ..-scroll_offset.y + content_bounds.size.height
713                        }
714                    };
715                    let visible_range = visible_range(item_origins, item_sizes, viewport);
716
717                    let items = (self.render_items)(visible_range.clone(), window, cx);
718
719                    let content_mask = ContentMask { bounds };
720                    window.with_content_mask(Some(content_mask), |window| {
721                        for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
722                            let item_origin = match self.axis {
723                                Axis::Horizontal => {
724                                    content_bounds.origin
725                                        + point(item_origins[ix] + scroll_offset.x, scroll_offset.y)
726                                }
727                                Axis::Vertical => {
728                                    content_bounds.origin
729                                        + point(scroll_offset.x, item_origins[ix] + scroll_offset.y)
730                                }
731                            };
732
733                            let available_space = match self.axis {
734                                Axis::Horizontal => size(
735                                    AvailableSpace::Definite(item_sizes[ix]),
736                                    AvailableSpace::Definite(content_bounds.size.height),
737                                ),
738                                Axis::Vertical => size(
739                                    AvailableSpace::Definite(content_bounds.size.width),
740                                    AvailableSpace::Definite(item_sizes[ix]),
741                                ),
742                            };
743
744                            item.layout_as_root(available_space, window, cx);
745                            item.prepaint_at(item_origin, window, cx);
746                            layout.items.push(item);
747                        }
748                    });
749                }
750
751                hitbox
752            },
753        )
754    }
755
756    fn paint(
757        &mut self,
758        global_id: Option<&GlobalElementId>,
759        inspector_id: Option<&gpui::InspectorElementId>,
760        bounds: Bounds<Pixels>,
761        layout: &mut Self::RequestLayoutState,
762        hitbox: &mut Self::PrepaintState,
763        window: &mut Window,
764        cx: &mut App,
765    ) {
766        self.base.interactivity().paint(
767            global_id,
768            inspector_id,
769            bounds,
770            hitbox.as_ref(),
771            window,
772            cx,
773            |_, window, cx| {
774                for item in &mut layout.items {
775                    item.paint(window, cx);
776                }
777            },
778        )
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    use gpui::{Context, ParentElement as _, TestAppContext, VisualTestContext};
787
788    struct VirtualListHarness {
789        axis: Axis,
790        item_sizes: Rc<Vec<Size<Pixels>>>,
791        scroll_handle: VirtualListScrollHandle,
792        visible_ranges: Rc<RefCell<Vec<Range<usize>>>>,
793    }
794
795    impl Render for VirtualListHarness {
796        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
797            let item_sizes = self.item_sizes.clone();
798            let visible_ranges = self.visible_ranges.clone();
799            virtual_list(
800                cx.entity(),
801                "virtual-list-test",
802                self.axis,
803                self.item_sizes.clone(),
804                move |_, visible_range, _, _| {
805                    visible_ranges.borrow_mut().push(visible_range.clone());
806                    visible_range
807                        .map(|ix| div().w(item_sizes[ix].width).h(item_sizes[ix].height))
808                        .collect::<Vec<_>>()
809                },
810            )
811            .track_scroll(&self.scroll_handle)
812            .w(px(60.))
813            .h(px(60.))
814        }
815    }
816
817    fn exercise_axis(cx: &mut TestAppContext, axis: Axis) {
818        let item_size = match axis {
819            Axis::Horizontal => size(px(20.), px(10.)),
820            Axis::Vertical => size(px(10.), px(20.)),
821        };
822        let item_sizes = Rc::new(vec![item_size; 20]);
823        let scroll_handle = VirtualListScrollHandle::new();
824        let visible_ranges = Rc::new(RefCell::new(Vec::new()));
825        let (_, cx) = cx.add_window_view({
826            let item_sizes = item_sizes.clone();
827            let scroll_handle = scroll_handle.clone();
828            let visible_ranges = visible_ranges.clone();
829            move |_, _| VirtualListHarness {
830                axis,
831                item_sizes,
832                scroll_handle,
833                visible_ranges,
834            }
835        });
836
837        cx.update(|window, cx| window.draw(cx).clear(cx));
838        let initial_range = visible_ranges.borrow().last().cloned().unwrap();
839        assert_eq!(initial_range.start, 0);
840        assert!(initial_range.end < item_sizes.len());
841
842        scroll_handle.scroll_to_item(12, ScrollStrategy::Top);
843        cx.update(|window, cx| window.draw(cx).clear(cx));
844        let scrolled_range = visible_ranges.borrow().last().cloned().unwrap();
845        assert!(scrolled_range.contains(&12));
846        match axis {
847            Axis::Horizontal => assert!(scroll_handle.offset().x < px(0.)),
848            Axis::Vertical => assert!(scroll_handle.offset().y < px(0.)),
849        }
850    }
851
852    fn layout(sizes: &[f32]) -> (Vec<Pixels>, Vec<Pixels>) {
853        let sizes: Vec<Pixels> = sizes.iter().map(|size| px(*size)).collect();
854        let origins = sizes
855            .iter()
856            .scan(px(0.), |cumulative, size| {
857                let origin = *cumulative;
858                *cumulative += *size;
859                Some(origin)
860            })
861            .collect();
862        (origins, sizes)
863    }
864
865    #[test]
866    fn visible_range_starts_at_the_first_item_crossing_the_viewport() {
867        let (origins, sizes) = layout(&[20.; 10]);
868        assert_eq!(visible_range(&origins, &sizes, px(0.)..px(60.)), 0..5);
869        assert_eq!(visible_range(&origins, &sizes, px(50.)..px(110.)), 2..7);
870    }
871
872    #[test]
873    fn visible_range_overdraws_one_item_past_the_viewport_but_not_past_the_end() {
874        let (origins, sizes) = layout(&[20.; 10]);
875        assert_eq!(visible_range(&origins, &sizes, px(150.)..px(210.)), 7..10);
876        assert_eq!(visible_range(&origins, &sizes, px(0.)..px(500.)), 0..10);
877    }
878
879    #[test]
880    fn visible_range_handles_uneven_sizes() {
881        let (origins, sizes) = layout(&[10., 30., 5., 50.]);
882        assert_eq!(visible_range(&origins, &sizes, px(12.)..px(44.)), 1..4);
883        assert_eq!(visible_range(&origins, &sizes, px(45.)..px(50.)), 3..4);
884    }
885
886    #[test]
887    fn visible_range_is_empty_without_items_or_past_the_content() {
888        let (origins, sizes) = layout(&[]);
889        assert_eq!(visible_range(&origins, &sizes, px(0.)..px(60.)), 0..0);
890        let (origins, sizes) = layout(&[20.; 10]);
891        assert!(visible_range(&origins, &sizes, px(300.)..px(360.)).is_empty());
892    }
893
894    #[gpui::test]
895    fn vertical_visible_range_and_deferred_scroll_are_preserved(cx: &mut TestAppContext) {
896        exercise_axis(cx, Axis::Vertical);
897    }
898
899    #[gpui::test]
900    fn horizontal_visible_range_and_deferred_scroll_are_preserved(cx: &mut TestAppContext) {
901        exercise_axis(cx, Axis::Horizontal);
902    }
903
904    /// Three 30 by 10 items, laid out along `axis` with `gap` between them.
905    struct GeometryHarness {
906        axis: Axis,
907        gap: Pixels,
908    }
909
910    impl Render for GeometryHarness {
911        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
912            virtual_list(
913                cx.entity(),
914                "virtual-list-geometry",
915                self.axis,
916                Rc::new(vec![size(px(30.), px(10.)); 3]),
917                |_, visible_range, _, _| {
918                    visible_range
919                        .map(|ix| {
920                            div()
921                                .w(px(30.))
922                                .h(px(10.))
923                                .debug_selector(move || format!("geometry-item-{ix}"))
924                        })
925                        .collect::<Vec<_>>()
926                },
927            )
928            .gap(self.gap)
929            .w(px(120.))
930            .h(px(100.))
931        }
932    }
933
934    /// Where the second item sits relative to the first.
935    fn second_item_offset(cx: &mut VisualTestContext) -> Point<Pixels> {
936        let first = cx.debug_bounds("geometry-item-0").unwrap().origin;
937        let second = cx.debug_bounds("geometry-item-1").unwrap().origin;
938        second - first
939    }
940
941    #[gpui::test]
942    fn changing_the_gap_moves_the_items(cx: &mut TestAppContext) {
943        let (view, cx) = cx.add_window_view(|_, _| GeometryHarness {
944            axis: Axis::Vertical,
945            gap: px(0.),
946        });
947        cx.update(|window, cx| window.draw(cx).clear(cx));
948        assert_eq!(second_item_offset(cx), point(px(0.), px(10.)));
949
950        cx.update(|window, cx| {
951            view.update(cx, |harness, cx| {
952                harness.gap = px(20.);
953                cx.notify();
954            });
955            window.draw(cx).clear(cx);
956        });
957        assert_eq!(second_item_offset(cx), point(px(0.), px(30.)));
958    }
959
960    #[gpui::test]
961    fn changing_the_axis_moves_the_items(cx: &mut TestAppContext) {
962        let (view, cx) = cx.add_window_view(|_, _| GeometryHarness {
963            axis: Axis::Vertical,
964            gap: px(0.),
965        });
966        cx.update(|window, cx| window.draw(cx).clear(cx));
967        assert_eq!(second_item_offset(cx), point(px(0.), px(10.)));
968
969        cx.update(|window, cx| {
970            view.update(cx, |harness, cx| {
971                harness.axis = Axis::Horizontal;
972                cx.notify();
973            });
974            window.draw(cx).clear(cx);
975        });
976        assert_eq!(second_item_offset(cx), point(px(30.), px(0.)));
977    }
978
979    #[gpui::test]
980    fn a_horizontal_list_infers_its_height_from_its_items(cx: &mut TestAppContext) {
981        struct InferHarness;
982
983        impl Render for InferHarness {
984            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
985                div()
986                    .flex()
987                    .flex_col()
988                    .items_start()
989                    .w(px(120.))
990                    .child(
991                        virtual_list(
992                            cx.entity(),
993                            "virtual-list-infer",
994                            Axis::Horizontal,
995                            Rc::new(vec![size(px(30.), px(10.)); 3]),
996                            |_, visible_range, _, _| {
997                                visible_range
998                                    .map(|_| div().w(px(30.)).h(px(10.)))
999                                    .collect::<Vec<_>>()
1000                            },
1001                        )
1002                        .with_sizing_behavior(ListSizingBehavior::Infer)
1003                        .w(px(120.))
1004                        .h_auto()
1005                        .flex_none(),
1006                    )
1007                    .child(div().size(px(1.)).debug_selector(|| "after-list".into()))
1008            }
1009        }
1010
1011        let (_, cx) = cx.add_window_view(|_, _| InferHarness);
1012        cx.update(|window, cx| window.draw(cx).clear(cx));
1013        // The list is as tall as its items, not as wide as itself.
1014        assert_eq!(cx.debug_bounds("after-list").unwrap().top(), px(10.));
1015    }
1016
1017    #[gpui::test]
1018    fn empty_list_draws_without_requesting_items(cx: &mut TestAppContext) {
1019        let visible_ranges = Rc::new(RefCell::new(Vec::new()));
1020        let (_, cx) = cx.add_window_view({
1021            let visible_ranges = visible_ranges.clone();
1022            move |_, _| VirtualListHarness {
1023                axis: Axis::Vertical,
1024                item_sizes: Rc::new(Vec::new()),
1025                scroll_handle: VirtualListScrollHandle::new(),
1026                visible_ranges,
1027            }
1028        });
1029
1030        cx.update(|window, cx| window.draw(cx).clear(cx));
1031        assert!(visible_ranges.borrow().is_empty());
1032    }
1033}