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_measured_layout(
298                            style,
299                            move |known_dimensions, available_space, _window, _cx| {
300                                let desired_height = item_size.height * max_items;
301                                let width = known_dimensions.width.unwrap_or(match available_space
302                                    .width
303                                {
304                                    AvailableSpace::Definite(x) => x,
305                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
306                                        item_size.width
307                                    }
308                                });
309                                let height = match available_space.height {
310                                    AvailableSpace::Definite(height) => desired_height.min(height),
311                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
312                                        desired_height
313                                    }
314                                };
315                                size(width, height)
316                            },
317                        )
318                    })
319                }
320                ListSizingBehavior::Auto => window
321                    .with_text_style(style.text_style().cloned(), |window| {
322                        window.request_layout(style, None, cx)
323                    }),
324            },
325        );
326
327        (
328            layout_id,
329            UniformListFrameState {
330                items: SmallVec::new(),
331                decorations: SmallVec::new(),
332            },
333        )
334    }
335
336    fn prepaint(
337        &mut self,
338        global_id: Option<&GlobalElementId>,
339        inspector_id: Option<&InspectorElementId>,
340        bounds: Bounds<Pixels>,
341        frame_state: &mut Self::RequestLayoutState,
342        window: &mut Window,
343        cx: &mut App,
344    ) -> Option<Hitbox> {
345        let style = self
346            .interactivity
347            .compute_style(global_id, None, window, cx);
348        let border = style.border_widths.to_pixels(window.rem_size());
349        let padding = style
350            .padding
351            .to_pixels(bounds.size.into(), window.rem_size());
352
353        let padded_bounds = Bounds::from_corners(
354            bounds.origin + point(border.left + padding.left, border.top + padding.top),
355            bounds.bottom_right()
356                - point(border.right + padding.right, border.bottom + padding.bottom),
357        );
358
359        let can_scroll_horizontally = matches!(
360            self.horizontal_sizing_behavior,
361            ListHorizontalSizingBehavior::Unconstrained
362        );
363
364        let longest_item_size =
365            crate::fast::layers::lists::measure_item(window, cx, global_id, |window, cx| {
366                self.measure_item(None, window, cx)
367            });
368        let content_width = if can_scroll_horizontally {
369            padded_bounds.size.width.max(longest_item_size.width)
370        } else {
371            padded_bounds.size.width
372        };
373        let content_size = Size {
374            width: content_width,
375            height: longest_item_size.height * self.item_count,
376        };
377
378        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
379        let item_height = longest_item_size.height;
380        let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
381            let mut handle = handle.0.borrow_mut();
382            handle.last_item_size = Some(ItemSize {
383                item: padded_bounds.size,
384                contents: content_size,
385            });
386            handle.deferred_scroll_to_item.take()
387        });
388
389        self.interactivity.prepaint(
390            global_id,
391            inspector_id,
392            bounds,
393            content_size,
394            window,
395            cx,
396            |_style, mut scroll_offset, hitbox, window, cx| {
397                let y_flipped = if let Some(scroll_handle) = &self.scroll_handle {
398                    let scroll_state = scroll_handle.0.borrow();
399                    scroll_state.y_flipped
400                } else {
401                    false
402                };
403
404                if self.item_count > 0 {
405                    let content_height = item_height * self.item_count;
406
407                    let is_scrolled_vertically = !scroll_offset.y.is_zero();
408                    let max_scroll_offset = padded_bounds.size.height - content_height;
409
410                    if is_scrolled_vertically && scroll_offset.y < max_scroll_offset {
411                        shared_scroll_offset.borrow_mut().y = max_scroll_offset;
412                        scroll_offset.y = max_scroll_offset;
413                    }
414
415                    let content_width = content_size.width + padding.left + padding.right;
416                    let is_scrolled_horizontally =
417                        can_scroll_horizontally && !scroll_offset.x.is_zero();
418                    if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
419                        shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
420                        scroll_offset.x = Pixels::ZERO;
421                    }
422
423                    if let Some(DeferredScrollToItem {
424                        mut item_index,
425                        mut strategy,
426                        offset,
427                        scroll_strict,
428                    }) = shared_scroll_to_item
429                    {
430                        if y_flipped {
431                            item_index = self.item_count.saturating_sub(item_index + 1);
432                        }
433                        let list_height = padded_bounds.size.height;
434                        let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
435                        let item_top = item_height * item_index;
436                        let item_bottom = item_top + item_height;
437                        let scroll_top = -updated_scroll_offset.y;
438                        let offset_pixels = item_height * offset;
439
440                        // is the selected item above/below currently visible items
441                        let is_above = item_top < scroll_top + offset_pixels;
442                        let is_below = item_bottom > scroll_top + list_height;
443
444                        if scroll_strict || is_above || is_below {
445                            if strategy == ScrollStrategy::Nearest {
446                                if is_above {
447                                    strategy = ScrollStrategy::Top;
448                                } else if is_below {
449                                    strategy = ScrollStrategy::Bottom;
450                                }
451                            }
452
453                            let max_scroll_offset =
454                                (content_height - list_height).max(Pixels::ZERO);
455                            match strategy {
456                                ScrollStrategy::Top => {
457                                    updated_scroll_offset.y = -(item_top - offset_pixels)
458                                        .clamp(Pixels::ZERO, max_scroll_offset);
459                                }
460                                ScrollStrategy::Center => {
461                                    let item_center = item_top + item_height / 2.0;
462
463                                    let viewport_height = list_height - offset_pixels;
464                                    let viewport_center = offset_pixels + viewport_height / 2.0;
465                                    let target_scroll_top = item_center - viewport_center;
466                                    updated_scroll_offset.y =
467                                        -target_scroll_top.clamp(Pixels::ZERO, max_scroll_offset);
468                                }
469                                ScrollStrategy::Bottom => {
470                                    updated_scroll_offset.y = -(item_bottom - list_height)
471                                        .clamp(Pixels::ZERO, max_scroll_offset);
472                                }
473                                ScrollStrategy::Nearest => {
474                                    // Nearest, but the item is visible -> no scroll is required
475                                }
476                            }
477                        }
478                        scroll_offset = *updated_scroll_offset
479                    }
480
481                    let scroll_offset =
482                        crate::fast::layers::lists::snap_item_offset(window, scroll_offset);
483                    let scroll_top = -scroll_offset.y.to_f64();
484                    let item_height_f64 = item_height.to_f64();
485                    let first_visible_element_ix =
486                        ((scroll_top - padding.top.to_f64()) / item_height_f64).floor() as usize;
487                    let last_visible_element_ix = ((scroll_top
488                        + padded_bounds.size.height.to_f64())
489                        / item_height_f64)
490                        .ceil() as usize;
491
492                    let visible_range = first_visible_element_ix
493                        ..cmp::min(last_visible_element_ix, self.item_count);
494                    let fast_rows = crate::fast::layers::lists::begin_uniform_list(
495                        window,
496                        cx,
497                        global_id,
498                        padded_bounds,
499                        scroll_offset,
500                        item_height,
501                        self.item_count,
502                        &visible_range,
503                        y_flipped,
504                    );
505
506                    let items = if y_flipped {
507                        let flipped_range = self.item_count.saturating_sub(visible_range.end)
508                            ..self.item_count.saturating_sub(visible_range.start);
509                        let mut items = (self.render_items)(flipped_range, window, cx);
510                        items.reverse();
511                        items
512                    } else {
513                        crate::fast::layers::lists::render_rows(
514                            &fast_rows,
515                            visible_range.clone(),
516                            |range| (self.render_items)(range, window, cx),
517                        )
518                    };
519
520                    let fast_indices =
521                        crate::fast::layers::lists::row_indices(&fast_rows, visible_range.clone());
522                    let content_mask = ContentMask { bounds };
523                    window.with_content_mask(Some(content_mask), |window| {
524                        for (mut item, ix) in items.into_iter().zip(fast_indices) {
525                            let item_top = item_height_f64 * ix as f64 - scroll_top;
526                            let item_origin = padded_bounds.origin
527                                + point(scroll_offset.x, Pixels::from(item_top));
528
529                            let available_width = if can_scroll_horizontally {
530                                padded_bounds.size.width + scroll_offset.x.abs()
531                            } else {
532                                padded_bounds.size.width
533                            };
534                            let available_space = size(
535                                AvailableSpace::Definite(available_width),
536                                AvailableSpace::Definite(item_height),
537                            );
538                            crate::fast::layout_key::layout_as_list_item(
539                                &mut item,
540                                ix,
541                                available_space,
542                                window,
543                                cx,
544                            );
545                            crate::fast::layers::lists::prepaint_row(
546                                window,
547                                cx,
548                                ix,
549                                |window, cx| item.prepaint_at(item_origin, window, cx),
550                            );
551                            frame_state.items.push(item);
552                        }
553                        crate::fast::layers::lists::end_rows(window, cx, fast_rows);
554
555                        let bounds =
556                            Bounds::new(padded_bounds.origin + scroll_offset, padded_bounds.size);
557                        for decoration in &self.decorations {
558                            let mut decoration = decoration.as_ref().compute(
559                                visible_range.clone(),
560                                bounds,
561                                scroll_offset,
562                                item_height,
563                                self.item_count,
564                                window,
565                                cx,
566                            );
567                            let available_space = size(
568                                AvailableSpace::Definite(bounds.size.width),
569                                AvailableSpace::Definite(bounds.size.height),
570                            );
571                            decoration.layout_as_root(available_space, window, cx);
572                            decoration.prepaint_at(bounds.origin, window, cx);
573                            frame_state.decorations.push(decoration);
574                        }
575                    });
576                }
577
578                hitbox
579            },
580        )
581    }
582
583    fn paint(
584        &mut self,
585        global_id: Option<&GlobalElementId>,
586        inspector_id: Option<&InspectorElementId>,
587        bounds: Bounds<crate::Pixels>,
588        request_layout: &mut Self::RequestLayoutState,
589        hitbox: &mut Option<Hitbox>,
590        window: &mut Window,
591        cx: &mut App,
592    ) {
593        self.interactivity.paint(
594            global_id,
595            inspector_id,
596            bounds,
597            hitbox.as_ref(),
598            window,
599            cx,
600            |_, window, cx| {
601                crate::fast::layers::lists::begin_paint_rows(window, cx, global_id);
602                for item in &mut request_layout.items {
603                    crate::fast::layers::lists::paint_row(window, cx, None, |window, cx| {
604                        item.paint(window, cx)
605                    });
606                }
607                crate::fast::layers::lists::end_paint_rows(window, cx, global_id);
608                for decoration in &mut request_layout.decorations {
609                    decoration.paint(window, cx);
610                }
611            },
612        )
613    }
614}
615
616impl IntoElement for UniformList {
617    type Element = Self;
618
619    fn into_element(self) -> Self::Element {
620        self
621    }
622}
623
624/// A decoration for a [`UniformList`]. This can be used for various things,
625/// such as rendering indent guides, or other visual effects.
626pub trait UniformListDecoration {
627    /// Compute the decoration element, given the visible range of list items,
628    /// the bounds of the list, and the height of each item.
629    fn compute(
630        &self,
631        visible_range: Range<usize>,
632        bounds: Bounds<Pixels>,
633        scroll_offset: Point<Pixels>,
634        item_height: Pixels,
635        item_count: usize,
636        window: &mut Window,
637        cx: &mut App,
638    ) -> AnyElement;
639}
640
641impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
642    fn compute(
643        &self,
644        visible_range: Range<usize>,
645        bounds: Bounds<Pixels>,
646        scroll_offset: Point<Pixels>,
647        item_height: Pixels,
648        item_count: usize,
649        window: &mut Window,
650        cx: &mut App,
651    ) -> AnyElement {
652        self.update(cx, |inner, cx| {
653            inner.compute(
654                visible_range,
655                bounds,
656                scroll_offset,
657                item_height,
658                item_count,
659                window,
660                cx,
661            )
662        })
663    }
664}
665
666impl UniformList {
667    /// Selects a specific list item for measurement.
668    pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
669        self.item_to_measure_index = item_index.unwrap_or(0);
670        self
671    }
672
673    /// Sets the sizing behavior, similar to the `List` element.
674    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
675        self.sizing_behavior = behavior;
676        self
677    }
678
679    /// Sets the horizontal sizing behavior, controlling the way list items laid out horizontally.
680    /// With [`ListHorizontalSizingBehavior::Unconstrained`] behavior, every item and the list itself will
681    /// have the size of the widest item and lay out pushing the `end_slot` to the right end.
682    pub fn with_horizontal_sizing_behavior(
683        mut self,
684        behavior: ListHorizontalSizingBehavior,
685    ) -> Self {
686        self.horizontal_sizing_behavior = behavior;
687        match behavior {
688            ListHorizontalSizingBehavior::FitList => {
689                self.interactivity.base_style.overflow.x = None;
690            }
691            ListHorizontalSizingBehavior::Unconstrained => {
692                self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
693            }
694        }
695        self
696    }
697
698    /// Adds a decoration element to the list.
699    pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
700        self.decorations.push(Box::new(decoration));
701        self
702    }
703
704    fn measure_item(
705        &self,
706        list_width: Option<Pixels>,
707        window: &mut Window,
708        cx: &mut App,
709    ) -> Size<Pixels> {
710        if self.item_count == 0 {
711            return Size::default();
712        }
713
714        let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
715        let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
716        let Some(mut item_to_measure) = items.pop() else {
717            return Size::default();
718        };
719        let available_space = size(
720            list_width.map_or(AvailableSpace::MaxContent, |width| {
721                AvailableSpace::Definite(width)
722            }),
723            AvailableSpace::MinContent,
724        );
725        item_to_measure.layout_as_root(available_space, window, cx)
726    }
727
728    /// Track and render scroll state of this list with reference to the given scroll handle.
729    pub fn track_scroll(mut self, handle: &UniformListScrollHandle) -> Self {
730        self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
731        self.scroll_handle = Some(handle.clone());
732        self
733    }
734
735    /// Sets whether the list is flipped vertically, such that item 0 appears at the bottom.
736    pub fn y_flipped(self, y_flipped: bool) -> Self {
737        if let Some(ref scroll_handle) = self.scroll_handle {
738            let mut scroll_state = scroll_handle.0.borrow_mut();
739            let base_handle = &scroll_state.base_handle;
740            let offset = base_handle.offset();
741            match scroll_state.last_item_size {
742                Some(last_size) if scroll_state.y_flipped != y_flipped => {
743                    let new_y_offset =
744                        -(offset.y + last_size.contents.height - last_size.item.height);
745                    base_handle.set_offset(point(offset.x, new_y_offset));
746                    scroll_state.y_flipped = y_flipped;
747                }
748                // Handle case where list is initially flipped.
749                None if y_flipped => {
750                    base_handle.set_offset(point(offset.x, Pixels::MIN));
751                    scroll_state.y_flipped = y_flipped;
752                }
753                _ => {}
754            }
755        }
756        self
757    }
758}
759
760impl InteractiveElement for UniformList {
761    fn interactivity(&mut self) -> &mut crate::Interactivity {
762        &mut self.interactivity
763    }
764}
765
766#[cfg(test)]
767mod test {
768    use crate::TestAppContext;
769
770    #[gpui::test]
771    fn test_scroll_strategy_nearest(cx: &mut TestAppContext) {
772        use crate::{
773            Context, FocusHandle, ScrollStrategy, UniformListScrollHandle, Window, div, prelude::*,
774            px, uniform_list,
775        };
776        use std::ops::Range;
777
778        actions!(example, [SelectNext, SelectPrev]);
779
780        struct TestView {
781            index: usize,
782            length: usize,
783            scroll_handle: UniformListScrollHandle,
784            focus_handle: FocusHandle,
785            visible_range: Range<usize>,
786        }
787
788        impl TestView {
789            pub fn select_next(
790                &mut self,
791                _: &SelectNext,
792                window: &mut Window,
793                _: &mut Context<Self>,
794            ) {
795                if self.index + 1 == self.length {
796                    self.index = 0
797                } else {
798                    self.index += 1;
799                }
800                self.scroll_handle
801                    .scroll_to_item(self.index, ScrollStrategy::Nearest);
802                window.refresh();
803            }
804
805            pub fn select_previous(
806                &mut self,
807                _: &SelectPrev,
808                window: &mut Window,
809                _: &mut Context<Self>,
810            ) {
811                if self.index == 0 {
812                    self.index = self.length - 1
813                } else {
814                    self.index -= 1;
815                }
816                self.scroll_handle
817                    .scroll_to_item(self.index, ScrollStrategy::Nearest);
818                window.refresh();
819            }
820        }
821
822        impl Render for TestView {
823            fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
824                div()
825                    .id("list-example")
826                    .track_focus(&self.focus_handle)
827                    .on_action(cx.listener(Self::select_next))
828                    .on_action(cx.listener(Self::select_previous))
829                    .size_full()
830                    .child(
831                        uniform_list(
832                            "entries",
833                            self.length,
834                            cx.processor(|this, range: Range<usize>, _window, _cx| {
835                                this.visible_range = range.clone();
836                                range
837                                    .map(|ix| div().id(ix).h(px(20.0)).child(format!("Item {ix}")))
838                                    .collect()
839                            }),
840                        )
841                        .track_scroll(&self.scroll_handle)
842                        .h(px(200.0)),
843                    )
844            }
845        }
846
847        let (view, cx) = cx.add_window_view(|window, cx| {
848            let focus_handle = cx.focus_handle();
849            window.focus(&focus_handle, cx);
850            TestView {
851                scroll_handle: UniformListScrollHandle::new(),
852                index: 0,
853                focus_handle,
854                length: 47,
855                visible_range: 0..0,
856            }
857        });
858
859        // 10 out of 47 items are visible
860
861        // First 9 times selecting next item does not scroll
862        for ix in 1..10 {
863            cx.dispatch_action(SelectNext);
864            view.read_with(cx, |view, _| {
865                assert_eq!(view.index, ix);
866                assert_eq!(view.visible_range, 0..10);
867            })
868        }
869
870        // Now each time the list scrolls down by 1
871        for ix in 10..47 {
872            cx.dispatch_action(SelectNext);
873            view.read_with(cx, |view, _| {
874                assert_eq!(view.index, ix);
875                assert_eq!(view.visible_range, ix - 9..ix + 1);
876            })
877        }
878
879        // After the last item we move back to the start
880        cx.dispatch_action(SelectNext);
881        view.read_with(cx, |view, _| {
882            assert_eq!(view.index, 0);
883            assert_eq!(view.visible_range, 0..10);
884        });
885
886        // Return to the last element
887        cx.dispatch_action(SelectPrev);
888        view.read_with(cx, |view, _| {
889            assert_eq!(view.index, 46);
890            assert_eq!(view.visible_range, 37..47);
891        });
892
893        // First 9 times selecting previous does not scroll
894        for ix in (37..46).rev() {
895            cx.dispatch_action(SelectPrev);
896            view.read_with(cx, |view, _| {
897                assert_eq!(view.index, ix);
898                assert_eq!(view.visible_range, 37..47);
899            })
900        }
901
902        // Now each time the list scrolls up by 1
903        for ix in (0..37).rev() {
904            cx.dispatch_action(SelectPrev);
905            view.read_with(cx, |view, _| {
906                assert_eq!(view.index, ix);
907                assert_eq!(view.visible_range, ix..ix + 10);
908            })
909        }
910    }
911
912    #[gpui::test]
913    fn test_item_positions_far_down_long_list(cx: &mut TestAppContext) {
914        use crate::{
915            Bounds, Context, Pixels, UniformListScrollHandle, Window, canvas, point, prelude::*,
916            px, uniform_list,
917        };
918        use std::{cell::RefCell, ops::Range, rc::Rc};
919
920        struct TestView {
921            scroll_handle: UniformListScrollHandle,
922            item_bounds: Rc<RefCell<Vec<(usize, Bounds<Pixels>)>>>,
923        }
924
925        impl Render for TestView {
926            fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
927                let item_bounds = self.item_bounds.clone();
928                uniform_list(
929                    "entries",
930                    10_000_000,
931                    cx.processor(move |_, range: Range<usize>, _window, _cx| {
932                        range
933                            .map(|ix| {
934                                let item_bounds = item_bounds.clone();
935                                canvas(
936                                    move |bounds, _, _| item_bounds.borrow_mut().push((ix, bounds)),
937                                    |_, _, _, _| {},
938                                )
939                                .w_full()
940                                .h(px(24.0))
941                            })
942                            .collect()
943                    }),
944                )
945                .track_scroll(&self.scroll_handle)
946                .h(px(200.0))
947            }
948        }
949
950        let item_bounds = Rc::new(RefCell::new(Vec::new()));
951        let (view, cx) = cx.add_window_view(|_, _| TestView {
952            scroll_handle: UniformListScrollHandle::new(),
953            item_bounds: item_bounds.clone(),
954        });
955
956        // Past 2^27px, f32 can only represent multiples of 16px. This offset is 16px into item
957        // 9_000_002, and the items must still be laid out 24px apart from that point.
958        item_bounds.borrow_mut().clear();
959        view.update(cx, |view, cx| {
960            view.scroll_handle
961                .0
962                .borrow()
963                .base_handle
964                .set_offset(point(px(0.0), px(-216_000_064.0)));
965            cx.notify();
966        });
967        cx.run_until_parked();
968
969        let item_tops = item_bounds
970            .borrow()
971            .iter()
972            .map(|(ix, bounds)| (*ix, bounds.origin.y))
973            .collect::<Vec<_>>();
974        let expected_tops = (9_000_002..9_000_011)
975            .map(|ix| (ix, px(-16.0 + 24.0 * (ix - 9_000_002) as f32)))
976            .collect::<Vec<_>>();
977        assert_eq!(item_tops, expected_tops);
978    }
979}