Skip to main content

gpui/elements/
uniform_list.rs

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