Skip to main content

gpui/elements/
uniform_list.rs

1//! A scrollable list of elements with uniform height, optimized for large lists.
2//! Rather than use the full taffy layout system, uniform_list simply measures
3//! the first element and then lays out all remaining elements in a line based on that
4//! measurement. This is much faster than the full layout system, but only works for
5//! elements with uniform height.
6
7use crate::{
8    AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId, Entity,
9    GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, Interactivity, IntoElement,
10    IsZero, LayoutId, ListSizingBehavior, Overflow, Pixels, Point, ScrollHandle, Size,
11    StyleRefinement, Styled, Window, point, px, size,
12};
13use smallvec::SmallVec;
14use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
15
16use super::ListHorizontalSizingBehavior;
17
18/// uniform_list provides lazy rendering for a set of items that are of uniform height.
19/// When rendered into a container with overflow-y: hidden and a fixed (or max) height,
20/// uniform_list will only render the visible subset of items.
21#[track_caller]
22pub fn uniform_list<R>(
23    id: impl Into<ElementId>,
24    item_count: usize,
25    f: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
26) -> UniformList
27where
28    R: IntoElement,
29{
30    let id = id.into();
31    let mut base_style = StyleRefinement::default();
32    base_style.overflow.y = Some(Overflow::Scroll);
33
34    let render_range = move |range: Range<usize>, window: &mut Window, cx: &mut App| {
35        f(range, window, cx)
36            .into_iter()
37            .map(|component| component.into_any_element())
38            .collect()
39    };
40
41    UniformList {
42        item_count,
43        item_to_measure_index: 0,
44        render_items: Box::new(render_range),
45        decorations: Vec::new(),
46        interactivity: Interactivity {
47            element_id: Some(id),
48            base_style: Box::new(base_style),
49            ..Interactivity::new()
50        },
51        scroll_handle: None,
52        sizing_behavior: ListSizingBehavior::default(),
53        horizontal_sizing_behavior: ListHorizontalSizingBehavior::default(),
54    }
55}
56
57/// A list element for efficiently laying out and displaying a list of uniform-height elements.
58pub struct UniformList {
59    item_count: usize,
60    item_to_measure_index: usize,
61    render_items: Box<
62        dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
63    >,
64    decorations: Vec<Box<dyn UniformListDecoration>>,
65    interactivity: Interactivity,
66    scroll_handle: Option<UniformListScrollHandle>,
67    sizing_behavior: ListSizingBehavior,
68    horizontal_sizing_behavior: ListHorizontalSizingBehavior,
69}
70
71/// Frame state used by the [UniformList].
72pub struct UniformListFrameState {
73    items: SmallVec<[AnyElement; 32]>,
74    decorations: SmallVec<[AnyElement; 2]>,
75}
76
77/// A handle for controlling the scroll position of a uniform list.
78/// This should be stored in your view and passed to the uniform_list on each frame.
79#[derive(Clone, Debug, Default)]
80pub struct UniformListScrollHandle(pub Rc<RefCell<UniformListScrollState>>);
81
82/// Where to place the element scrolled to.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum ScrollStrategy {
85    /// Place the element at the top of the list's viewport.
86    Top,
87    /// Attempt to place the element in the middle of the list's viewport.
88    /// May not be possible if there's not enough list items above the item scrolled to:
89    /// in this case, the element will be placed at the closest possible position.
90    Center,
91    /// Attempt to place the element at the bottom of the list's viewport.
92    /// May not be possible if there's not enough list items above the item scrolled to:
93    /// in this case, the element will be placed at the closest possible position.
94    Bottom,
95    /// If the element is not visible attempt to place it at:
96    /// - The top of the list's viewport if the target element is above currently visible elements.
97    /// - The bottom of the list's viewport if the target element is above currently visible elements.
98    Nearest,
99}
100
101#[derive(Clone, Copy, Debug)]
102#[allow(missing_docs)]
103pub struct DeferredScrollToItem {
104    /// The item index to scroll to
105    pub item_index: usize,
106    /// The scroll strategy to use
107    pub strategy: ScrollStrategy,
108    /// The offset in number of items
109    pub offset: usize,
110    pub scroll_strict: bool,
111}
112
113#[derive(Clone, Debug, Default)]
114#[allow(missing_docs)]
115pub struct UniformListScrollState {
116    pub base_handle: ScrollHandle,
117    pub deferred_scroll_to_item: Option<DeferredScrollToItem>,
118    /// Size of the item, captured during last layout.
119    pub last_item_size: Option<ItemSize>,
120    /// Whether the list was vertically flipped during last layout.
121    pub y_flipped: bool,
122}
123
124#[derive(Copy, Clone, Debug, Default)]
125/// The size of the item and its contents.
126pub struct ItemSize {
127    /// The size of the item.
128    pub item: Size<Pixels>,
129    /// The size of the item's contents, which may be larger than the item itself,
130    /// if the item was bounded by a parent element.
131    pub contents: Size<Pixels>,
132}
133
134impl UniformListScrollHandle {
135    /// Create a new scroll handle to bind to a uniform list.
136    pub fn new() -> Self {
137        Self(Rc::new(RefCell::new(UniformListScrollState {
138            base_handle: ScrollHandle::new(),
139            deferred_scroll_to_item: None,
140            last_item_size: None,
141            y_flipped: false,
142        })))
143    }
144
145    /// Scroll the list so that the given item index is visible.
146    ///
147    /// This uses non-strict scrolling: if the item is already fully visible, no scrolling occurs.
148    /// If the item is out of view, it scrolls the minimum amount to bring it into view according
149    /// to the strategy.
150    pub fn scroll_to_item(&self, ix: usize, strategy: ScrollStrategy) {
151        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
152            item_index: ix,
153            strategy,
154            offset: 0,
155            scroll_strict: false,
156        });
157    }
158
159    /// Scroll the list so that the given item index is at scroll strategy position.
160    ///
161    /// This uses strict scrolling: the item will always be scrolled to match the strategy position,
162    /// even if it's already visible. Use this when you need precise positioning.
163    pub fn scroll_to_item_strict(&self, ix: usize, strategy: ScrollStrategy) {
164        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
165            item_index: ix,
166            strategy,
167            offset: 0,
168            scroll_strict: true,
169        });
170    }
171
172    /// Scroll the list to the given item index with an offset in number of items.
173    ///
174    /// This uses non-strict scrolling: if the item is already visible within the offset region,
175    /// no scrolling occurs.
176    ///
177    /// The offset parameter shrinks the effective viewport by the specified number of items
178    /// from the corresponding edge, then applies the scroll strategy within that reduced viewport:
179    /// - `ScrollStrategy::Top`: Shrinks from top, positions item at the new top
180    /// - `ScrollStrategy::Center`: Shrinks from top, centers item in the reduced viewport
181    /// - `ScrollStrategy::Bottom`: Shrinks from bottom, positions item at the new bottom
182    pub fn scroll_to_item_with_offset(&self, ix: usize, strategy: ScrollStrategy, offset: usize) {
183        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
184            item_index: ix,
185            strategy,
186            offset,
187            scroll_strict: false,
188        });
189    }
190
191    /// Scroll the list so that the given item index is at the exact scroll strategy position with an offset.
192    ///
193    /// This uses strict scrolling: the item will always be scrolled to match the strategy position,
194    /// even if it's already visible.
195    ///
196    /// The offset parameter shrinks the effective viewport by the specified number of items
197    /// from the corresponding edge, then applies the scroll strategy within that reduced viewport:
198    /// - `ScrollStrategy::Top`: Shrinks from top, positions item at the new top
199    /// - `ScrollStrategy::Center`: Shrinks from top, centers item in the reduced viewport
200    /// - `ScrollStrategy::Bottom`: Shrinks from bottom, positions item at the new bottom
201    pub fn scroll_to_item_strict_with_offset(
202        &self,
203        ix: usize,
204        strategy: ScrollStrategy,
205        offset: usize,
206    ) {
207        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
208            item_index: ix,
209            strategy,
210            offset,
211            scroll_strict: true,
212        });
213    }
214
215    /// Check if the list is flipped vertically.
216    pub fn y_flipped(&self) -> bool {
217        self.0.borrow().y_flipped
218    }
219
220    /// Get the index of the topmost visible child.
221    #[cfg(any(test, feature = "test-support"))]
222    pub fn logical_scroll_top_index(&self) -> usize {
223        let this = self.0.borrow();
224        this.deferred_scroll_to_item
225            .as_ref()
226            .map(|deferred| deferred.item_index)
227            .unwrap_or_else(|| this.base_handle.logical_scroll_top().0)
228    }
229
230    /// Checks if the list can be scrolled vertically.
231    pub fn is_scrollable(&self) -> bool {
232        if let Some(size) = self.0.borrow().last_item_size {
233            size.contents.height > size.item.height
234        } else {
235            false
236        }
237    }
238
239    /// Whether the list is scrolled to the end, or `None` if the list is
240    /// not scrollable.
241    pub fn is_scrolled_to_end(&self) -> Option<bool> {
242        let state = self.0.borrow();
243        let max_offset = state.base_handle.max_offset();
244        if max_offset.y <= px(0.) {
245            return None;
246        }
247        let offset = state.base_handle.offset();
248        Some(-offset.y >= max_offset.y)
249    }
250
251    /// Scroll to the bottom of the list.
252    pub fn scroll_to_bottom(&self) {
253        self.scroll_to_item(usize::MAX, ScrollStrategy::Bottom);
254    }
255}
256
257impl Styled for UniformList {
258    fn style(&mut self) -> &mut StyleRefinement {
259        &mut self.interactivity.base_style
260    }
261}
262
263impl Element for UniformList {
264    type RequestLayoutState = UniformListFrameState;
265    type PrepaintState = Option<Hitbox>;
266
267    fn id(&self) -> Option<ElementId> {
268        self.interactivity.element_id.clone()
269    }
270
271    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
272        None
273    }
274
275    fn request_layout(
276        &mut self,
277        global_id: Option<&GlobalElementId>,
278        inspector_id: Option<&InspectorElementId>,
279        window: &mut Window,
280        cx: &mut App,
281    ) -> (LayoutId, Self::RequestLayoutState) {
282        let max_items = self.item_count;
283        let item_size = self.measure_item(None, window, cx);
284        let layout_id = self.interactivity.request_layout(
285            global_id,
286            inspector_id,
287            window,
288            cx,
289            |style, window, cx| match self.sizing_behavior {
290                ListSizingBehavior::Infer => {
291                    window.with_text_style(style.text_style().cloned(), |window| {
292                        window.request_keyed_measured_layout(
293                            style,
294                            (item_size, max_items),
295                            move |known_dimensions, available_space, _window, _cx| {
296                                let desired_height = item_size.height * max_items;
297                                let width = known_dimensions.width.unwrap_or(match available_space
298                                    .width
299                                {
300                                    AvailableSpace::Definite(x) => x,
301                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
302                                        item_size.width
303                                    }
304                                });
305                                let height = match available_space.height {
306                                    AvailableSpace::Definite(height) => desired_height.min(height),
307                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
308                                        desired_height
309                                    }
310                                };
311                                size(width, height)
312                            },
313                        )
314                    })
315                }
316                ListSizingBehavior::Auto => window
317                    .with_text_style(style.text_style().cloned(), |window| {
318                        window.request_layout(style, None, cx)
319                    }),
320            },
321        );
322
323        (
324            layout_id,
325            UniformListFrameState {
326                items: SmallVec::new(),
327                decorations: SmallVec::new(),
328            },
329        )
330    }
331
332    fn prepaint(
333        &mut self,
334        global_id: Option<&GlobalElementId>,
335        inspector_id: Option<&InspectorElementId>,
336        bounds: Bounds<Pixels>,
337        frame_state: &mut Self::RequestLayoutState,
338        window: &mut Window,
339        cx: &mut App,
340    ) -> Option<Hitbox> {
341        let style = self
342            .interactivity
343            .compute_style(global_id, None, window, cx);
344        let border = style.border_widths.to_pixels(window.rem_size());
345        let padding = style
346            .padding
347            .to_pixels(bounds.size.into(), window.rem_size());
348
349        let padded_bounds = Bounds::from_corners(
350            bounds.origin + point(border.left + padding.left, border.top + padding.top),
351            bounds.bottom_right()
352                - point(border.right + padding.right, border.bottom + padding.bottom),
353        );
354
355        let can_scroll_horizontally = matches!(
356            self.horizontal_sizing_behavior,
357            ListHorizontalSizingBehavior::Unconstrained
358        );
359
360        let longest_item_size = self.measure_item(None, window, cx);
361        let content_width = if can_scroll_horizontally {
362            padded_bounds.size.width.max(longest_item_size.width)
363        } else {
364            padded_bounds.size.width
365        };
366        let content_size = Size {
367            width: content_width,
368            height: longest_item_size.height * self.item_count,
369        };
370
371        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
372        let item_height = longest_item_size.height;
373        let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
374            let mut handle = handle.0.borrow_mut();
375            handle.last_item_size = Some(ItemSize {
376                item: padded_bounds.size,
377                contents: content_size,
378            });
379            handle.deferred_scroll_to_item.take()
380        });
381
382        self.interactivity.prepaint(
383            global_id,
384            inspector_id,
385            bounds,
386            content_size,
387            window,
388            cx,
389            |_style, mut scroll_offset, hitbox, window, cx| {
390                let y_flipped = if let Some(scroll_handle) = &self.scroll_handle {
391                    let scroll_state = scroll_handle.0.borrow();
392                    scroll_state.y_flipped
393                } else {
394                    false
395                };
396
397                if self.item_count > 0 {
398                    let content_height = item_height * self.item_count;
399
400                    let is_scrolled_vertically = !scroll_offset.y.is_zero();
401                    let max_scroll_offset = padded_bounds.size.height - content_height;
402
403                    if is_scrolled_vertically && scroll_offset.y < max_scroll_offset {
404                        shared_scroll_offset.borrow_mut().y = max_scroll_offset;
405                        scroll_offset.y = max_scroll_offset;
406                    }
407
408                    let content_width = content_size.width + padding.left + padding.right;
409                    let is_scrolled_horizontally =
410                        can_scroll_horizontally && !scroll_offset.x.is_zero();
411                    if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
412                        shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
413                        scroll_offset.x = Pixels::ZERO;
414                    }
415
416                    if let Some(DeferredScrollToItem {
417                        mut item_index,
418                        mut strategy,
419                        offset,
420                        scroll_strict,
421                    }) = shared_scroll_to_item
422                    {
423                        if y_flipped {
424                            item_index = self.item_count.saturating_sub(item_index + 1);
425                        }
426                        let list_height = padded_bounds.size.height;
427                        let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
428                        let item_top = item_height * item_index;
429                        let item_bottom = item_top + item_height;
430                        let scroll_top = -updated_scroll_offset.y;
431                        let offset_pixels = item_height * offset;
432
433                        // is the selected item above/below currently visible items
434                        let is_above = item_top < scroll_top + offset_pixels;
435                        let is_below = item_bottom > scroll_top + list_height;
436
437                        if scroll_strict || is_above || is_below {
438                            if strategy == ScrollStrategy::Nearest {
439                                if is_above {
440                                    strategy = ScrollStrategy::Top;
441                                } else if is_below {
442                                    strategy = ScrollStrategy::Bottom;
443                                }
444                            }
445
446                            let max_scroll_offset =
447                                (content_height - list_height).max(Pixels::ZERO);
448                            match strategy {
449                                ScrollStrategy::Top => {
450                                    updated_scroll_offset.y = -(item_top - offset_pixels)
451                                        .clamp(Pixels::ZERO, max_scroll_offset);
452                                }
453                                ScrollStrategy::Center => {
454                                    let item_center = item_top + item_height / 2.0;
455
456                                    let viewport_height = list_height - offset_pixels;
457                                    let viewport_center = offset_pixels + viewport_height / 2.0;
458                                    let target_scroll_top = item_center - viewport_center;
459                                    updated_scroll_offset.y =
460                                        -target_scroll_top.clamp(Pixels::ZERO, max_scroll_offset);
461                                }
462                                ScrollStrategy::Bottom => {
463                                    updated_scroll_offset.y = -(item_bottom - list_height)
464                                        .clamp(Pixels::ZERO, max_scroll_offset);
465                                }
466                                ScrollStrategy::Nearest => {
467                                    // Nearest, but the item is visible -> no scroll is required
468                                }
469                            }
470                        }
471                        scroll_offset = *updated_scroll_offset
472                    }
473
474                    let scroll_top = -scroll_offset.y.to_f64();
475                    let item_height_f64 = item_height.to_f64();
476                    let first_visible_element_ix =
477                        ((scroll_top - padding.top.to_f64()) / item_height_f64).floor() as usize;
478                    let last_visible_element_ix = ((scroll_top
479                        + padded_bounds.size.height.to_f64())
480                        / item_height_f64)
481                        .ceil() as usize;
482
483                    let visible_range = first_visible_element_ix
484                        ..cmp::min(last_visible_element_ix, self.item_count);
485
486                    let items = if y_flipped {
487                        let flipped_range = self.item_count.saturating_sub(visible_range.end)
488                            ..self.item_count.saturating_sub(visible_range.start);
489                        let mut items = (self.render_items)(flipped_range, window, cx);
490                        items.reverse();
491                        items
492                    } else {
493                        (self.render_items)(visible_range.clone(), window, cx)
494                    };
495
496                    let content_mask = ContentMask { bounds };
497                    window.with_content_mask(Some(content_mask), |window| {
498                        for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
499                            let item_top = item_height_f64 * ix as f64 - scroll_top;
500                            let item_origin = padded_bounds.origin
501                                + point(scroll_offset.x, Pixels::from(item_top));
502
503                            let available_width = if can_scroll_horizontally {
504                                padded_bounds.size.width + scroll_offset.x.abs()
505                            } else {
506                                padded_bounds.size.width
507                            };
508                            let available_space = size(
509                                AvailableSpace::Definite(available_width),
510                                AvailableSpace::Definite(item_height),
511                            );
512                            item.layout_as_root(available_space, window, cx);
513                            item.prepaint_at(item_origin, window, cx);
514                            frame_state.items.push(item);
515                        }
516
517                        let bounds =
518                            Bounds::new(padded_bounds.origin + scroll_offset, padded_bounds.size);
519                        for decoration in &self.decorations {
520                            let mut decoration = decoration.as_ref().compute(
521                                visible_range.clone(),
522                                bounds,
523                                scroll_offset,
524                                item_height,
525                                self.item_count,
526                                window,
527                                cx,
528                            );
529                            let available_space = size(
530                                AvailableSpace::Definite(bounds.size.width),
531                                AvailableSpace::Definite(bounds.size.height),
532                            );
533                            decoration.layout_as_root(available_space, window, cx);
534                            decoration.prepaint_at(bounds.origin, window, cx);
535                            frame_state.decorations.push(decoration);
536                        }
537                    });
538                }
539
540                hitbox
541            },
542        )
543    }
544
545    fn paint(
546        &mut self,
547        global_id: Option<&GlobalElementId>,
548        inspector_id: Option<&InspectorElementId>,
549        bounds: Bounds<crate::Pixels>,
550        request_layout: &mut Self::RequestLayoutState,
551        hitbox: &mut Option<Hitbox>,
552        window: &mut Window,
553        cx: &mut App,
554    ) {
555        self.interactivity.paint(
556            global_id,
557            inspector_id,
558            bounds,
559            hitbox.as_ref(),
560            window,
561            cx,
562            |_, window, cx| {
563                for item in &mut request_layout.items {
564                    item.paint(window, cx);
565                }
566                for decoration in &mut request_layout.decorations {
567                    decoration.paint(window, cx);
568                }
569            },
570        )
571    }
572}
573
574/// A decoration for a [`UniformList`]. This can be used for various things,
575/// such as rendering indent guides, or other visual effects.
576pub trait UniformListDecoration {
577    /// Compute the decoration element, given the visible range of list items,
578    /// the bounds of the list, and the height of each item.
579    fn compute(
580        &self,
581        visible_range: Range<usize>,
582        bounds: Bounds<Pixels>,
583        scroll_offset: Point<Pixels>,
584        item_height: Pixels,
585        item_count: usize,
586        window: &mut Window,
587        cx: &mut App,
588    ) -> AnyElement;
589}
590
591impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
592    fn compute(
593        &self,
594        visible_range: Range<usize>,
595        bounds: Bounds<Pixels>,
596        scroll_offset: Point<Pixels>,
597        item_height: Pixels,
598        item_count: usize,
599        window: &mut Window,
600        cx: &mut App,
601    ) -> AnyElement {
602        self.update(cx, |inner, cx| {
603            inner.compute(
604                visible_range,
605                bounds,
606                scroll_offset,
607                item_height,
608                item_count,
609                window,
610                cx,
611            )
612        })
613    }
614}
615
616impl UniformList {
617    /// Selects a specific list item for measurement.
618    pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
619        self.item_to_measure_index = item_index.unwrap_or(0);
620        self
621    }
622
623    /// Sets the sizing behavior, similar to the `List` element.
624    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
625        self.sizing_behavior = behavior;
626        self
627    }
628
629    /// Sets the horizontal sizing behavior, controlling the way list items laid out horizontally.
630    /// With [`ListHorizontalSizingBehavior::Unconstrained`] behavior, every item and the list itself will
631    /// have the size of the widest item and lay out pushing the `end_slot` to the right end.
632    pub fn with_horizontal_sizing_behavior(
633        mut self,
634        behavior: ListHorizontalSizingBehavior,
635    ) -> Self {
636        self.horizontal_sizing_behavior = behavior;
637        match behavior {
638            ListHorizontalSizingBehavior::FitList => {
639                self.interactivity.base_style.overflow.x = None;
640            }
641            ListHorizontalSizingBehavior::Unconstrained => {
642                self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
643            }
644        }
645        self
646    }
647
648    /// Adds a decoration element to the list.
649    pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
650        self.decorations.push(Box::new(decoration));
651        self
652    }
653
654    fn measure_item(
655        &self,
656        list_width: Option<Pixels>,
657        window: &mut Window,
658        cx: &mut App,
659    ) -> Size<Pixels> {
660        if self.item_count == 0 {
661            return Size::default();
662        }
663
664        let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
665        let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
666        let Some(mut item_to_measure) = items.pop() else {
667            return Size::default();
668        };
669        let available_space = size(
670            list_width.map_or(AvailableSpace::MaxContent, |width| {
671                AvailableSpace::Definite(width)
672            }),
673            AvailableSpace::MinContent,
674        );
675        item_to_measure.layout_as_root(available_space, window, cx)
676    }
677
678    /// Track and render scroll state of this list with reference to the given scroll handle.
679    pub fn track_scroll(mut self, handle: &UniformListScrollHandle) -> Self {
680        self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
681        self.scroll_handle = Some(handle.clone());
682        self
683    }
684
685    /// Sets whether the list is flipped vertically, such that item 0 appears at the bottom.
686    pub fn y_flipped(self, y_flipped: bool) -> Self {
687        if let Some(ref scroll_handle) = self.scroll_handle {
688            let mut scroll_state = scroll_handle.0.borrow_mut();
689            let base_handle = &scroll_state.base_handle;
690            let offset = base_handle.offset();
691            match scroll_state.last_item_size {
692                Some(last_size) if scroll_state.y_flipped != y_flipped => {
693                    let new_y_offset =
694                        -(offset.y + last_size.contents.height - last_size.item.height);
695                    base_handle.set_offset(point(offset.x, new_y_offset));
696                    scroll_state.y_flipped = y_flipped;
697                }
698                // Handle case where list is initially flipped.
699                None if y_flipped => {
700                    base_handle.set_offset(point(offset.x, Pixels::MIN));
701                    scroll_state.y_flipped = y_flipped;
702                }
703                _ => {}
704            }
705        }
706        self
707    }
708}
709
710impl InteractiveElement for UniformList {
711    fn interactivity(&mut self) -> &mut crate::Interactivity {
712        &mut self.interactivity
713    }
714}
715
716#[cfg(test)]
717mod test {
718    use crate::TestAppContext;
719
720    #[gpui::test]
721    fn test_scroll_strategy_nearest(cx: &mut TestAppContext) {
722        use crate::{
723            Context, FocusHandle, ScrollStrategy, UniformListScrollHandle, Window, div, prelude::*,
724            px, uniform_list,
725        };
726        use std::ops::Range;
727
728        actions!(example, [SelectNext, SelectPrev]);
729
730        struct TestView {
731            index: usize,
732            length: usize,
733            scroll_handle: UniformListScrollHandle,
734            focus_handle: FocusHandle,
735            visible_range: Range<usize>,
736        }
737
738        impl TestView {
739            pub fn select_next(
740                &mut self,
741                _: &SelectNext,
742                window: &mut Window,
743                _: &mut Context<Self>,
744            ) {
745                if self.index + 1 == self.length {
746                    self.index = 0
747                } else {
748                    self.index += 1;
749                }
750                self.scroll_handle
751                    .scroll_to_item(self.index, ScrollStrategy::Nearest);
752                window.refresh();
753            }
754
755            pub fn select_previous(
756                &mut self,
757                _: &SelectPrev,
758                window: &mut Window,
759                _: &mut Context<Self>,
760            ) {
761                if self.index == 0 {
762                    self.index = self.length - 1
763                } else {
764                    self.index -= 1;
765                }
766                self.scroll_handle
767                    .scroll_to_item(self.index, ScrollStrategy::Nearest);
768                window.refresh();
769            }
770        }
771
772        impl Render for TestView {
773            fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
774                div()
775                    .id("list-example")
776                    .track_focus(&self.focus_handle)
777                    .on_action(cx.listener(Self::select_next))
778                    .on_action(cx.listener(Self::select_previous))
779                    .size_full()
780                    .child(
781                        uniform_list(
782                            "entries",
783                            self.length,
784                            cx.processor(|this, range: Range<usize>, _window, _cx| {
785                                this.visible_range = range.clone();
786                                range
787                                    .map(|ix| div().id(ix).h(px(20.0)).child(format!("Item {ix}")))
788                                    .collect()
789                            }),
790                        )
791                        .track_scroll(&self.scroll_handle)
792                        .h(px(200.0)),
793                    )
794            }
795        }
796
797        let (view, cx) = cx.add_window_view(|window, cx| {
798            let focus_handle = cx.focus_handle();
799            window.focus(&focus_handle, cx);
800            TestView {
801                scroll_handle: UniformListScrollHandle::new(),
802                index: 0,
803                focus_handle,
804                length: 47,
805                visible_range: 0..0,
806            }
807        });
808
809        // 10 out of 47 items are visible
810
811        // First 9 times selecting next item does not scroll
812        for ix in 1..10 {
813            cx.dispatch_action(SelectNext);
814            view.read_with(cx, |view, _| {
815                assert_eq!(view.index, ix);
816                assert_eq!(view.visible_range, 0..10);
817            })
818        }
819
820        // Now each time the list scrolls down by 1
821        for ix in 10..47 {
822            cx.dispatch_action(SelectNext);
823            view.read_with(cx, |view, _| {
824                assert_eq!(view.index, ix);
825                assert_eq!(view.visible_range, ix - 9..ix + 1);
826            })
827        }
828
829        // After the last item we move back to the start
830        cx.dispatch_action(SelectNext);
831        view.read_with(cx, |view, _| {
832            assert_eq!(view.index, 0);
833            assert_eq!(view.visible_range, 0..10);
834        });
835
836        // Return to the last element
837        cx.dispatch_action(SelectPrev);
838        view.read_with(cx, |view, _| {
839            assert_eq!(view.index, 46);
840            assert_eq!(view.visible_range, 37..47);
841        });
842
843        // First 9 times selecting previous does not scroll
844        for ix in (37..46).rev() {
845            cx.dispatch_action(SelectPrev);
846            view.read_with(cx, |view, _| {
847                assert_eq!(view.index, ix);
848                assert_eq!(view.visible_range, 37..47);
849            })
850        }
851
852        // Now each time the list scrolls up by 1
853        for ix in (0..37).rev() {
854            cx.dispatch_action(SelectPrev);
855            view.read_with(cx, |view, _| {
856                assert_eq!(view.index, ix);
857                assert_eq!(view.visible_range, ix..ix + 10);
858            })
859        }
860    }
861
862    #[gpui::test]
863    fn test_item_positions_far_down_long_list(cx: &mut TestAppContext) {
864        use crate::{
865            Bounds, Context, Pixels, UniformListScrollHandle, Window, canvas, point, prelude::*,
866            px, uniform_list,
867        };
868        use std::{cell::RefCell, ops::Range, rc::Rc};
869
870        struct TestView {
871            scroll_handle: UniformListScrollHandle,
872            item_bounds: Rc<RefCell<Vec<(usize, Bounds<Pixels>)>>>,
873        }
874
875        impl Render for TestView {
876            fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
877                let item_bounds = self.item_bounds.clone();
878                uniform_list(
879                    "entries",
880                    10_000_000,
881                    cx.processor(move |_, range: Range<usize>, _window, _cx| {
882                        range
883                            .map(|ix| {
884                                let item_bounds = item_bounds.clone();
885                                canvas(
886                                    move |bounds, _, _| item_bounds.borrow_mut().push((ix, bounds)),
887                                    |_, _, _, _| {},
888                                )
889                                .w_full()
890                                .h(px(24.0))
891                            })
892                            .collect()
893                    }),
894                )
895                .track_scroll(&self.scroll_handle)
896                .h(px(200.0))
897            }
898        }
899
900        let item_bounds = Rc::new(RefCell::new(Vec::new()));
901        let (view, cx) = cx.add_window_view(|_, _| TestView {
902            scroll_handle: UniformListScrollHandle::new(),
903            item_bounds: item_bounds.clone(),
904        });
905
906        // Past 2^27px, f32 can only represent multiples of 16px. This offset is 16px into item
907        // 9_000_002, and the items must still be laid out 24px apart from that point.
908        item_bounds.borrow_mut().clear();
909        view.update(cx, |view, cx| {
910            view.scroll_handle
911                .0
912                .borrow()
913                .base_handle
914                .set_offset(point(px(0.0), px(-216_000_064.0)));
915            cx.notify();
916        });
917        cx.run_until_parked();
918
919        let item_tops = item_bounds
920            .borrow()
921            .iter()
922            .map(|(ix, bounds)| (*ix, bounds.origin.y))
923            .collect::<Vec<_>>();
924        let expected_tops = (9_000_002..9_000_011)
925            .map(|ix| (ix, px(-16.0 + 24.0 * (ix - 9_000_002) as f32)))
926            .collect::<Vec<_>>();
927        assert_eq!(item_tops, expected_tops);
928    }
929}