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
425impl Element for VirtualList {
426    type RequestLayoutState = VirtualListFrameState;
427    type PrepaintState = Option<Hitbox>;
428
429    fn id(&self) -> Option<ElementId> {
430        Some(self.id.clone())
431    }
432
433    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
434        None
435    }
436
437    fn request_layout(
438        &mut self,
439        global_id: Option<&GlobalElementId>,
440        inspector_id: Option<&gpui::InspectorElementId>,
441        window: &mut Window,
442        cx: &mut App,
443    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
444        let rem_size = window.rem_size();
445        let font_size = window.text_style().font_size.to_pixels(rem_size);
446        let mut size_layout = ItemSizeLayout::default();
447        // Measure vertical lists at the last known content width so relative
448        // widths and text truncation resolve like the visible rows; an
449        // unconstrained measure would turn one long non-wrapping text into a
450        // phantom horizontal scroll range.
451        let list_width = if self.axis.is_vertical() {
452            self.scroll_handle
453                .state
454                .borrow()
455                .last_content_size
456                .map(|size| size.width)
457                .filter(|width| !width.is_zero())
458        } else {
459            None
460        };
461        let longest_item_size = self.measure_item(list_width, window, cx);
462
463        let layout_id = self.base.interactivity().request_layout(
464            global_id,
465            inspector_id,
466            window,
467            cx,
468            |style, window, cx| {
469                size_layout = window.with_element_state(
470                    global_id.unwrap(),
471                    |state: Option<ItemSizeLayout>, _window| {
472                        let mut state = state.unwrap_or(ItemSizeLayout::default());
473
474                        // Including the gap between items for calculate the item size
475                        let gap = style
476                            .gap
477                            .along(self.axis)
478                            .to_pixels(font_size.into(), rem_size);
479
480                        if state.items_sizes != self.item_sizes
481                            || state.axis_and_gap != Some((self.axis, gap))
482                        {
483                            state.items_sizes = self.item_sizes.clone();
484                            state.axis_and_gap = Some((self.axis, gap));
485                            // Prepare each item's size by axis
486                            state.sizes = self
487                                .item_sizes
488                                .iter()
489                                .enumerate()
490                                .map(|(i, size)| {
491                                    let size = size.along(self.axis);
492                                    if i + 1 == self.items_count {
493                                        size
494                                    } else {
495                                        size + gap
496                                    }
497                                })
498                                .collect();
499
500                            // Prepare each item's origin by axis
501                            let mut cumulative = px(0.);
502                            state.origins = state
503                                .sizes
504                                .iter()
505                                .map(|size| {
506                                    let origin = cumulative;
507                                    cumulative += *size;
508                                    origin
509                                })
510                                .collect();
511
512                            if self.axis.is_horizontal() {
513                                state.content_size.width = cumulative;
514                            } else {
515                                state.content_size.height = cumulative;
516                            }
517                        }
518
519                        if self.axis.is_horizontal() {
520                            state.content_size.height = longest_item_size.height;
521                        } else {
522                            state.content_size.width = longest_item_size.width;
523                        }
524
525                        (state.clone(), state)
526                    },
527                );
528
529                let axis = self.axis;
530                let layout_id =
531                    match self.sizing_behavior {
532                        ListSizingBehavior::Infer => {
533                            window.with_text_style(style.text_style().cloned(), |window| {
534                                let size_layout = size_layout.clone();
535
536                                window.request_measured_layout(style, {
537                                    move |known_dimensions, available_space, _, _| {
538                                        let mut size = Size::default();
539                                        if axis.is_horizontal() {
540                                            size.width = known_dimensions.width.unwrap_or(
541                                                match available_space.width {
542                                                    AvailableSpace::Definite(x) => x,
543                                                    AvailableSpace::MinContent
544                                                    | AvailableSpace::MaxContent => {
545                                                        size_layout.content_size.width
546                                                    }
547                                                },
548                                            );
549                                            size.height = known_dimensions.height.unwrap_or(
550                                                match available_space.height {
551                                                    AvailableSpace::Definite(x) => x,
552                                                    AvailableSpace::MinContent
553                                                    | AvailableSpace::MaxContent => {
554                                                        size_layout.content_size.height
555                                                    }
556                                                },
557                                            );
558                                        } else {
559                                            size.width = known_dimensions.width.unwrap_or(
560                                                match available_space.width {
561                                                    AvailableSpace::Definite(x) => x,
562                                                    AvailableSpace::MinContent
563                                                    | AvailableSpace::MaxContent => {
564                                                        size_layout.content_size.width
565                                                    }
566                                                },
567                                            );
568                                            size.height = known_dimensions.height.unwrap_or(
569                                                match available_space.height {
570                                                    AvailableSpace::Definite(x) => x,
571                                                    AvailableSpace::MinContent
572                                                    | AvailableSpace::MaxContent => {
573                                                        size_layout.content_size.height
574                                                    }
575                                                },
576                                            );
577                                        }
578
579                                        size
580                                    }
581                                })
582                            })
583                        }
584                        ListSizingBehavior::Auto => window
585                            .with_text_style(style.text_style().cloned(), |window| {
586                                window.request_layout(style, None, cx)
587                            }),
588                    };
589
590                layout_id
591            },
592        );
593
594        (
595            layout_id,
596            VirtualListFrameState {
597                items: SmallVec::new(),
598                size_layout,
599            },
600        )
601    }
602
603    fn prepaint(
604        &mut self,
605        global_id: Option<&GlobalElementId>,
606        inspector_id: Option<&gpui::InspectorElementId>,
607        bounds: Bounds<Pixels>,
608        layout: &mut Self::RequestLayoutState,
609        window: &mut Window,
610        cx: &mut App,
611    ) -> Self::PrepaintState {
612        layout.size_layout.last_layout_bounds = bounds;
613
614        let style = self
615            .base
616            .interactivity()
617            .compute_style(global_id, None, window, cx);
618        let border_widths = style.border_widths.to_pixels(window.rem_size());
619        let paddings = style
620            .padding
621            .to_pixels(bounds.size.into(), window.rem_size());
622
623        let item_sizes = &layout.size_layout.sizes;
624        let item_origins = &layout.size_layout.origins;
625
626        let content_bounds = Bounds::from_corners(
627            bounds.origin
628                + point(
629                    border_widths.left + paddings.left,
630                    border_widths.top + paddings.top,
631                ),
632            bounds.bottom_right()
633                - point(
634                    border_widths.right + paddings.right,
635                    border_widths.bottom + paddings.bottom,
636                ),
637        );
638
639        let axis = self.axis;
640
641        let mut scroll_state = self.scroll_handle.state.borrow_mut();
642        scroll_state.axis = axis;
643        scroll_state.items_count = self.items_count;
644        scroll_state.last_content_size = Some(content_bounds.size);
645
646        let mut scroll_offset = self.scroll_handle.offset();
647        if let Some(scroll_to_item) = scroll_state.deferred_scroll_to_item.take() {
648            scroll_offset = self.scroll_to_deferred_item(
649                scroll_offset,
650                &layout.size_layout,
651                &content_bounds,
652                scroll_to_item,
653            );
654        }
655
656        scroll_offset = scroll_offset
657            .max(&point(
658                content_bounds.size.width - layout.size_layout.content_size.width,
659                content_bounds.size.height - layout.size_layout.content_size.height,
660            ))
661            .min(&point(px(0.), px(0.)));
662        if scroll_offset != self.scroll_handle.offset() {
663            self.scroll_handle.set_offset(scroll_offset);
664        }
665
666        self.base.interactivity().prepaint(
667            global_id,
668            inspector_id,
669            bounds,
670            layout.size_layout.content_size,
671            window,
672            cx,
673            |_style, _, hitbox, window, cx| {
674                if self.items_count > 0 {
675                    let min_scroll_offset = content_bounds.size.along(self.axis)
676                        - layout.size_layout.content_size.along(self.axis);
677
678                    let is_scrolled = !scroll_offset.along(self.axis).is_zero();
679                    if is_scrolled {
680                        match self.axis {
681                            Axis::Horizontal if scroll_offset.x < min_scroll_offset => {
682                                scroll_offset.x = min_scroll_offset;
683                                self.scroll_handle.set_offset(scroll_offset);
684                            }
685                            Axis::Vertical if scroll_offset.y < min_scroll_offset => {
686                                scroll_offset.y = min_scroll_offset;
687                                self.scroll_handle.set_offset(scroll_offset);
688                            }
689                            _ => {}
690                        }
691                    }
692
693                    // The viewport in content space: the scroll offset is
694                    // negative, and the leading padding is admitted at the
695                    // start so an item under it is still drawn.
696                    let viewport = match self.axis {
697                        Axis::Horizontal => {
698                            -(scroll_offset.x + paddings.left)
699                                ..-scroll_offset.x + content_bounds.size.width
700                        }
701                        Axis::Vertical => {
702                            -(scroll_offset.y + paddings.top)
703                                ..-scroll_offset.y + content_bounds.size.height
704                        }
705                    };
706                    let visible_range = visible_range(item_origins, item_sizes, viewport);
707
708                    let items = (self.render_items)(visible_range.clone(), window, cx);
709
710                    let content_mask = ContentMask { bounds };
711                    window.with_content_mask(Some(content_mask), |window| {
712                        for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
713                            let item_origin = match self.axis {
714                                Axis::Horizontal => {
715                                    content_bounds.origin
716                                        + point(item_origins[ix] + scroll_offset.x, scroll_offset.y)
717                                }
718                                Axis::Vertical => {
719                                    content_bounds.origin
720                                        + point(scroll_offset.x, item_origins[ix] + scroll_offset.y)
721                                }
722                            };
723
724                            let available_space = match self.axis {
725                                Axis::Horizontal => size(
726                                    AvailableSpace::Definite(item_sizes[ix]),
727                                    AvailableSpace::Definite(content_bounds.size.height),
728                                ),
729                                Axis::Vertical => size(
730                                    AvailableSpace::Definite(content_bounds.size.width),
731                                    AvailableSpace::Definite(item_sizes[ix]),
732                                ),
733                            };
734
735                            item.layout_as_root(available_space, window, cx);
736                            item.prepaint_at(item_origin, window, cx);
737                            layout.items.push(item);
738                        }
739                    });
740                }
741
742                hitbox
743            },
744        )
745    }
746
747    fn paint(
748        &mut self,
749        global_id: Option<&GlobalElementId>,
750        inspector_id: Option<&gpui::InspectorElementId>,
751        bounds: Bounds<Pixels>,
752        layout: &mut Self::RequestLayoutState,
753        hitbox: &mut Self::PrepaintState,
754        window: &mut Window,
755        cx: &mut App,
756    ) {
757        self.base.interactivity().paint(
758            global_id,
759            inspector_id,
760            bounds,
761            hitbox.as_ref(),
762            window,
763            cx,
764            |_, window, cx| {
765                for item in &mut layout.items {
766                    item.paint(window, cx);
767                }
768            },
769        )
770    }
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776
777    use gpui::{Context, ParentElement as _, TestAppContext, VisualTestContext};
778
779    struct VirtualListHarness {
780        axis: Axis,
781        item_sizes: Rc<Vec<Size<Pixels>>>,
782        scroll_handle: VirtualListScrollHandle,
783        visible_ranges: Rc<RefCell<Vec<Range<usize>>>>,
784    }
785
786    impl Render for VirtualListHarness {
787        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
788            let item_sizes = self.item_sizes.clone();
789            let visible_ranges = self.visible_ranges.clone();
790            virtual_list(
791                cx.entity(),
792                "virtual-list-test",
793                self.axis,
794                self.item_sizes.clone(),
795                move |_, visible_range, _, _| {
796                    visible_ranges.borrow_mut().push(visible_range.clone());
797                    visible_range
798                        .map(|ix| div().w(item_sizes[ix].width).h(item_sizes[ix].height))
799                        .collect::<Vec<_>>()
800                },
801            )
802            .track_scroll(&self.scroll_handle)
803            .w(px(60.))
804            .h(px(60.))
805        }
806    }
807
808    fn exercise_axis(cx: &mut TestAppContext, axis: Axis) {
809        let item_size = match axis {
810            Axis::Horizontal => size(px(20.), px(10.)),
811            Axis::Vertical => size(px(10.), px(20.)),
812        };
813        let item_sizes = Rc::new(vec![item_size; 20]);
814        let scroll_handle = VirtualListScrollHandle::new();
815        let visible_ranges = Rc::new(RefCell::new(Vec::new()));
816        let (_, cx) = cx.add_window_view({
817            let item_sizes = item_sizes.clone();
818            let scroll_handle = scroll_handle.clone();
819            let visible_ranges = visible_ranges.clone();
820            move |_, _| VirtualListHarness {
821                axis,
822                item_sizes,
823                scroll_handle,
824                visible_ranges,
825            }
826        });
827
828        cx.update(|window, cx| window.draw(cx).clear(cx));
829        let initial_range = visible_ranges.borrow().last().cloned().unwrap();
830        assert_eq!(initial_range.start, 0);
831        assert!(initial_range.end < item_sizes.len());
832
833        scroll_handle.scroll_to_item(12, ScrollStrategy::Top);
834        cx.update(|window, cx| window.draw(cx).clear(cx));
835        let scrolled_range = visible_ranges.borrow().last().cloned().unwrap();
836        assert!(scrolled_range.contains(&12));
837        match axis {
838            Axis::Horizontal => assert!(scroll_handle.offset().x < px(0.)),
839            Axis::Vertical => assert!(scroll_handle.offset().y < px(0.)),
840        }
841    }
842
843    fn layout(sizes: &[f32]) -> (Vec<Pixels>, Vec<Pixels>) {
844        let sizes: Vec<Pixels> = sizes.iter().map(|size| px(*size)).collect();
845        let origins = sizes
846            .iter()
847            .scan(px(0.), |cumulative, size| {
848                let origin = *cumulative;
849                *cumulative += *size;
850                Some(origin)
851            })
852            .collect();
853        (origins, sizes)
854    }
855
856    #[test]
857    fn visible_range_starts_at_the_first_item_crossing_the_viewport() {
858        let (origins, sizes) = layout(&[20.; 10]);
859        assert_eq!(visible_range(&origins, &sizes, px(0.)..px(60.)), 0..5);
860        assert_eq!(visible_range(&origins, &sizes, px(50.)..px(110.)), 2..7);
861    }
862
863    #[test]
864    fn visible_range_overdraws_one_item_past_the_viewport_but_not_past_the_end() {
865        let (origins, sizes) = layout(&[20.; 10]);
866        assert_eq!(visible_range(&origins, &sizes, px(150.)..px(210.)), 7..10);
867        assert_eq!(visible_range(&origins, &sizes, px(0.)..px(500.)), 0..10);
868    }
869
870    #[test]
871    fn visible_range_handles_uneven_sizes() {
872        let (origins, sizes) = layout(&[10., 30., 5., 50.]);
873        assert_eq!(visible_range(&origins, &sizes, px(12.)..px(44.)), 1..4);
874        assert_eq!(visible_range(&origins, &sizes, px(45.)..px(50.)), 3..4);
875    }
876
877    #[test]
878    fn visible_range_is_empty_without_items_or_past_the_content() {
879        let (origins, sizes) = layout(&[]);
880        assert_eq!(visible_range(&origins, &sizes, px(0.)..px(60.)), 0..0);
881        let (origins, sizes) = layout(&[20.; 10]);
882        assert!(visible_range(&origins, &sizes, px(300.)..px(360.)).is_empty());
883    }
884
885    #[gpui::test]
886    fn vertical_visible_range_and_deferred_scroll_are_preserved(cx: &mut TestAppContext) {
887        exercise_axis(cx, Axis::Vertical);
888    }
889
890    #[gpui::test]
891    fn horizontal_visible_range_and_deferred_scroll_are_preserved(cx: &mut TestAppContext) {
892        exercise_axis(cx, Axis::Horizontal);
893    }
894
895    /// Three 30 by 10 items, laid out along `axis` with `gap` between them.
896    struct GeometryHarness {
897        axis: Axis,
898        gap: Pixels,
899    }
900
901    impl Render for GeometryHarness {
902        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
903            virtual_list(
904                cx.entity(),
905                "virtual-list-geometry",
906                self.axis,
907                Rc::new(vec![size(px(30.), px(10.)); 3]),
908                |_, visible_range, _, _| {
909                    visible_range
910                        .map(|ix| {
911                            div()
912                                .w(px(30.))
913                                .h(px(10.))
914                                .debug_selector(move || format!("geometry-item-{ix}"))
915                        })
916                        .collect::<Vec<_>>()
917                },
918            )
919            .gap(self.gap)
920            .w(px(120.))
921            .h(px(100.))
922        }
923    }
924
925    /// Where the second item sits relative to the first.
926    fn second_item_offset(cx: &mut VisualTestContext) -> Point<Pixels> {
927        let first = cx.debug_bounds("geometry-item-0").unwrap().origin;
928        let second = cx.debug_bounds("geometry-item-1").unwrap().origin;
929        second - first
930    }
931
932    #[gpui::test]
933    fn changing_the_gap_moves_the_items(cx: &mut TestAppContext) {
934        let (view, cx) = cx.add_window_view(|_, _| GeometryHarness {
935            axis: Axis::Vertical,
936            gap: px(0.),
937        });
938        cx.update(|window, cx| window.draw(cx).clear(cx));
939        assert_eq!(second_item_offset(cx), point(px(0.), px(10.)));
940
941        cx.update(|window, cx| {
942            view.update(cx, |harness, cx| {
943                harness.gap = px(20.);
944                cx.notify();
945            });
946            window.draw(cx).clear(cx);
947        });
948        assert_eq!(second_item_offset(cx), point(px(0.), px(30.)));
949    }
950
951    #[gpui::test]
952    fn changing_the_axis_moves_the_items(cx: &mut TestAppContext) {
953        let (view, cx) = cx.add_window_view(|_, _| GeometryHarness {
954            axis: Axis::Vertical,
955            gap: px(0.),
956        });
957        cx.update(|window, cx| window.draw(cx).clear(cx));
958        assert_eq!(second_item_offset(cx), point(px(0.), px(10.)));
959
960        cx.update(|window, cx| {
961            view.update(cx, |harness, cx| {
962                harness.axis = Axis::Horizontal;
963                cx.notify();
964            });
965            window.draw(cx).clear(cx);
966        });
967        assert_eq!(second_item_offset(cx), point(px(30.), px(0.)));
968    }
969
970    #[gpui::test]
971    fn a_horizontal_list_infers_its_height_from_its_items(cx: &mut TestAppContext) {
972        struct InferHarness;
973
974        impl Render for InferHarness {
975            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
976                div()
977                    .flex()
978                    .flex_col()
979                    .items_start()
980                    .w(px(120.))
981                    .child(
982                        virtual_list(
983                            cx.entity(),
984                            "virtual-list-infer",
985                            Axis::Horizontal,
986                            Rc::new(vec![size(px(30.), px(10.)); 3]),
987                            |_, visible_range, _, _| {
988                                visible_range
989                                    .map(|_| div().w(px(30.)).h(px(10.)))
990                                    .collect::<Vec<_>>()
991                            },
992                        )
993                        .with_sizing_behavior(ListSizingBehavior::Infer)
994                        .w(px(120.))
995                        .h_auto()
996                        .flex_none(),
997                    )
998                    .child(div().size(px(1.)).debug_selector(|| "after-list".into()))
999            }
1000        }
1001
1002        let (_, cx) = cx.add_window_view(|_, _| InferHarness);
1003        cx.update(|window, cx| window.draw(cx).clear(cx));
1004        // The list is as tall as its items, not as wide as itself.
1005        assert_eq!(cx.debug_bounds("after-list").unwrap().top(), px(10.));
1006    }
1007
1008    #[gpui::test]
1009    fn empty_list_draws_without_requesting_items(cx: &mut TestAppContext) {
1010        let visible_ranges = Rc::new(RefCell::new(Vec::new()));
1011        let (_, cx) = cx.add_window_view({
1012            let visible_ranges = visible_ranges.clone();
1013            move |_, _| VirtualListHarness {
1014                axis: Axis::Vertical,
1015                item_sizes: Rc::new(Vec::new()),
1016                scroll_handle: VirtualListScrollHandle::new(),
1017                visible_ranges,
1018            }
1019        });
1020
1021        cx.update(|window, cx| window.draw(cx).clear(cx));
1022        assert!(visible_ranges.borrow().is_empty());
1023    }
1024}