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, 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
240impl Styled for UniformList {
241    fn style(&mut self) -> &mut StyleRefinement {
242        &mut self.interactivity.base_style
243    }
244}
245
246impl Element for UniformList {
247    type RequestLayoutState = UniformListFrameState;
248    type PrepaintState = Option<Hitbox>;
249
250    fn id(&self) -> Option<ElementId> {
251        self.interactivity.element_id.clone()
252    }
253
254    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
255        None
256    }
257
258    fn request_layout(
259        &mut self,
260        global_id: Option<&GlobalElementId>,
261        inspector_id: Option<&InspectorElementId>,
262        window: &mut Window,
263        cx: &mut App,
264    ) -> (LayoutId, Self::RequestLayoutState) {
265        let max_items = self.item_count;
266        let item_size = self.measure_item(None, window, cx);
267        let layout_id = self.interactivity.request_layout(
268            global_id,
269            inspector_id,
270            window,
271            cx,
272            |style, window, cx| match self.sizing_behavior {
273                ListSizingBehavior::Infer => {
274                    window.with_text_style(style.text_style().cloned(), |window| {
275                        window.request_measured_layout(
276                            style,
277                            move |known_dimensions, available_space, _window, _cx| {
278                                let desired_height = item_size.height * max_items;
279                                let width = known_dimensions.width.unwrap_or(match available_space
280                                    .width
281                                {
282                                    AvailableSpace::Definite(x) => x,
283                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
284                                        item_size.width
285                                    }
286                                });
287                                let height = match available_space.height {
288                                    AvailableSpace::Definite(height) => desired_height.min(height),
289                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
290                                        desired_height
291                                    }
292                                };
293                                size(width, height)
294                            },
295                        )
296                    })
297                }
298                ListSizingBehavior::Auto => window
299                    .with_text_style(style.text_style().cloned(), |window| {
300                        window.request_layout(style, None, cx)
301                    }),
302            },
303        );
304
305        (
306            layout_id,
307            UniformListFrameState {
308                items: SmallVec::new(),
309                decorations: SmallVec::new(),
310            },
311        )
312    }
313
314    fn prepaint(
315        &mut self,
316        global_id: Option<&GlobalElementId>,
317        inspector_id: Option<&InspectorElementId>,
318        bounds: Bounds<Pixels>,
319        frame_state: &mut Self::RequestLayoutState,
320        window: &mut Window,
321        cx: &mut App,
322    ) -> Option<Hitbox> {
323        let style = self
324            .interactivity
325            .compute_style(global_id, None, window, cx);
326        let border = style.border_widths.to_pixels(window.rem_size());
327        let padding = style
328            .padding
329            .to_pixels(bounds.size.into(), window.rem_size());
330
331        let padded_bounds = Bounds::from_corners(
332            bounds.origin + point(border.left + padding.left, border.top + padding.top),
333            bounds.bottom_right()
334                - point(border.right + padding.right, border.bottom + padding.bottom),
335        );
336
337        let can_scroll_horizontally = matches!(
338            self.horizontal_sizing_behavior,
339            ListHorizontalSizingBehavior::Unconstrained
340        );
341
342        let longest_item_size = self.measure_item(None, window, cx);
343        let content_width = if can_scroll_horizontally {
344            padded_bounds.size.width.max(longest_item_size.width)
345        } else {
346            padded_bounds.size.width
347        };
348        let content_size = Size {
349            width: content_width,
350            height: longest_item_size.height * self.item_count,
351        };
352
353        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
354        let item_height = longest_item_size.height;
355        let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
356            let mut handle = handle.0.borrow_mut();
357            handle.last_item_size = Some(ItemSize {
358                item: padded_bounds.size,
359                contents: content_size,
360            });
361            handle.deferred_scroll_to_item.take()
362        });
363
364        self.interactivity.prepaint(
365            global_id,
366            inspector_id,
367            bounds,
368            content_size,
369            window,
370            cx,
371            |_style, mut scroll_offset, hitbox, window, cx| {
372                let y_flipped = if let Some(scroll_handle) = &self.scroll_handle {
373                    let scroll_state = scroll_handle.0.borrow();
374                    scroll_state.y_flipped
375                } else {
376                    false
377                };
378
379                if self.item_count > 0 {
380                    let content_height = item_height * self.item_count;
381
382                    let is_scrolled_vertically = !scroll_offset.y.is_zero();
383                    let max_scroll_offset = padded_bounds.size.height - content_height;
384
385                    if is_scrolled_vertically && scroll_offset.y < max_scroll_offset {
386                        shared_scroll_offset.borrow_mut().y = max_scroll_offset;
387                        scroll_offset.y = max_scroll_offset;
388                    }
389
390                    let content_width = content_size.width + padding.left + padding.right;
391                    let is_scrolled_horizontally =
392                        can_scroll_horizontally && !scroll_offset.x.is_zero();
393                    if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
394                        shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
395                        scroll_offset.x = Pixels::ZERO;
396                    }
397
398                    if let Some(DeferredScrollToItem {
399                        mut item_index,
400                        mut strategy,
401                        offset,
402                        scroll_strict,
403                    }) = shared_scroll_to_item
404                    {
405                        if y_flipped {
406                            item_index = self.item_count.saturating_sub(item_index + 1);
407                        }
408                        let list_height = padded_bounds.size.height;
409                        let mut updated_scroll_offset = shared_scroll_offset.borrow_mut();
410                        let item_top = item_height * item_index;
411                        let item_bottom = item_top + item_height;
412                        let scroll_top = -updated_scroll_offset.y;
413                        let offset_pixels = item_height * offset;
414
415                        // is the selected item above/below currently visible items
416                        let is_above = item_top < scroll_top + offset_pixels;
417                        let is_below = item_bottom > scroll_top + list_height;
418
419                        if scroll_strict || is_above || is_below {
420                            if strategy == ScrollStrategy::Nearest {
421                                if is_above {
422                                    strategy = ScrollStrategy::Top;
423                                } else if is_below {
424                                    strategy = ScrollStrategy::Bottom;
425                                }
426                            }
427
428                            let max_scroll_offset =
429                                (content_height - list_height).max(Pixels::ZERO);
430                            match strategy {
431                                ScrollStrategy::Top => {
432                                    updated_scroll_offset.y = -(item_top - offset_pixels)
433                                        .clamp(Pixels::ZERO, max_scroll_offset);
434                                }
435                                ScrollStrategy::Center => {
436                                    let item_center = item_top + item_height / 2.0;
437
438                                    let viewport_height = list_height - offset_pixels;
439                                    let viewport_center = offset_pixels + viewport_height / 2.0;
440                                    let target_scroll_top = item_center - viewport_center;
441                                    updated_scroll_offset.y =
442                                        -target_scroll_top.clamp(Pixels::ZERO, max_scroll_offset);
443                                }
444                                ScrollStrategy::Bottom => {
445                                    updated_scroll_offset.y = -(item_bottom - list_height)
446                                        .clamp(Pixels::ZERO, max_scroll_offset);
447                                }
448                                ScrollStrategy::Nearest => {
449                                    // Nearest, but the item is visible -> no scroll is required
450                                }
451                            }
452                        }
453                        scroll_offset = *updated_scroll_offset
454                    }
455
456                    let first_visible_element_ix =
457                        (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
458                    let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
459                        / item_height)
460                        .ceil() as usize;
461
462                    let visible_range = first_visible_element_ix
463                        ..cmp::min(last_visible_element_ix, self.item_count);
464
465                    let items = if y_flipped {
466                        let flipped_range = self.item_count.saturating_sub(visible_range.end)
467                            ..self.item_count.saturating_sub(visible_range.start);
468                        let mut items = (self.render_items)(flipped_range, window, cx);
469                        items.reverse();
470                        items
471                    } else {
472                        (self.render_items)(visible_range.clone(), window, cx)
473                    };
474
475                    let content_mask = ContentMask { bounds };
476                    window.with_content_mask(Some(content_mask), |window| {
477                        for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
478                            let item_origin = padded_bounds.origin
479                                + scroll_offset
480                                + point(Pixels::ZERO, item_height * ix);
481
482                            let available_width = if can_scroll_horizontally {
483                                padded_bounds.size.width + scroll_offset.x.abs()
484                            } else {
485                                padded_bounds.size.width
486                            };
487                            let available_space = size(
488                                AvailableSpace::Definite(available_width),
489                                AvailableSpace::Definite(item_height),
490                            );
491                            item.layout_as_root(available_space, window, cx);
492                            item.prepaint_at(item_origin, window, cx);
493                            frame_state.items.push(item);
494                        }
495
496                        let bounds =
497                            Bounds::new(padded_bounds.origin + scroll_offset, padded_bounds.size);
498                        for decoration in &self.decorations {
499                            let mut decoration = decoration.as_ref().compute(
500                                visible_range.clone(),
501                                bounds,
502                                scroll_offset,
503                                item_height,
504                                self.item_count,
505                                window,
506                                cx,
507                            );
508                            let available_space = size(
509                                AvailableSpace::Definite(bounds.size.width),
510                                AvailableSpace::Definite(bounds.size.height),
511                            );
512                            decoration.layout_as_root(available_space, window, cx);
513                            decoration.prepaint_at(bounds.origin, window, cx);
514                            frame_state.decorations.push(decoration);
515                        }
516                    });
517                }
518
519                hitbox
520            },
521        )
522    }
523
524    fn paint(
525        &mut self,
526        global_id: Option<&GlobalElementId>,
527        inspector_id: Option<&InspectorElementId>,
528        bounds: Bounds<crate::Pixels>,
529        request_layout: &mut Self::RequestLayoutState,
530        hitbox: &mut Option<Hitbox>,
531        window: &mut Window,
532        cx: &mut App,
533    ) {
534        self.interactivity.paint(
535            global_id,
536            inspector_id,
537            bounds,
538            hitbox.as_ref(),
539            window,
540            cx,
541            |_, window, cx| {
542                for item in &mut request_layout.items {
543                    item.paint(window, cx);
544                }
545                for decoration in &mut request_layout.decorations {
546                    decoration.paint(window, cx);
547                }
548            },
549        )
550    }
551}
552
553impl IntoElement for UniformList {
554    type Element = Self;
555
556    fn into_element(self) -> Self::Element {
557        self
558    }
559}
560
561/// A decoration for a [`UniformList`]. This can be used for various things,
562/// such as rendering indent guides, or other visual effects.
563pub trait UniformListDecoration {
564    /// Compute the decoration element, given the visible range of list items,
565    /// the bounds of the list, and the height of each item.
566    fn compute(
567        &self,
568        visible_range: Range<usize>,
569        bounds: Bounds<Pixels>,
570        scroll_offset: Point<Pixels>,
571        item_height: Pixels,
572        item_count: usize,
573        window: &mut Window,
574        cx: &mut App,
575    ) -> AnyElement;
576}
577
578impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
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        self.update(cx, |inner, cx| {
590            inner.compute(
591                visible_range,
592                bounds,
593                scroll_offset,
594                item_height,
595                item_count,
596                window,
597                cx,
598            )
599        })
600    }
601}
602
603impl UniformList {
604    /// Selects a specific list item for measurement.
605    pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
606        self.item_to_measure_index = item_index.unwrap_or(0);
607        self
608    }
609
610    /// Sets the sizing behavior, similar to the `List` element.
611    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
612        self.sizing_behavior = behavior;
613        self
614    }
615
616    /// Sets the horizontal sizing behavior, controlling the way list items laid out horizontally.
617    /// With [`ListHorizontalSizingBehavior::Unconstrained`] behavior, every item and the list itself will
618    /// have the size of the widest item and lay out pushing the `end_slot` to the right end.
619    pub fn with_horizontal_sizing_behavior(
620        mut self,
621        behavior: ListHorizontalSizingBehavior,
622    ) -> Self {
623        self.horizontal_sizing_behavior = behavior;
624        match behavior {
625            ListHorizontalSizingBehavior::FitList => {
626                self.interactivity.base_style.overflow.x = None;
627            }
628            ListHorizontalSizingBehavior::Unconstrained => {
629                self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
630            }
631        }
632        self
633    }
634
635    /// Adds a decoration element to the list.
636    pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
637        self.decorations.push(Box::new(decoration));
638        self
639    }
640
641    fn measure_item(
642        &self,
643        list_width: Option<Pixels>,
644        window: &mut Window,
645        cx: &mut App,
646    ) -> Size<Pixels> {
647        if self.item_count == 0 {
648            return Size::default();
649        }
650
651        let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
652        let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
653        let Some(mut item_to_measure) = items.pop() else {
654            return Size::default();
655        };
656        let available_space = size(
657            list_width.map_or(AvailableSpace::MinContent, |width| {
658                AvailableSpace::Definite(width)
659            }),
660            AvailableSpace::MinContent,
661        );
662        item_to_measure.layout_as_root(available_space, window, cx)
663    }
664
665    /// Track and render scroll state of this list with reference to the given scroll handle.
666    pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
667        self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
668        self.scroll_handle = Some(handle);
669        self
670    }
671
672    /// Sets whether the list is flipped vertically, such that item 0 appears at the bottom.
673    pub fn y_flipped(mut self, y_flipped: bool) -> Self {
674        if let Some(ref scroll_handle) = self.scroll_handle {
675            let mut scroll_state = scroll_handle.0.borrow_mut();
676            let mut base_handle = &scroll_state.base_handle;
677            let offset = base_handle.offset();
678            match scroll_state.last_item_size {
679                Some(last_size) if scroll_state.y_flipped != y_flipped => {
680                    let new_y_offset =
681                        -(offset.y + last_size.contents.height - last_size.item.height);
682                    base_handle.set_offset(point(offset.x, new_y_offset));
683                    scroll_state.y_flipped = y_flipped;
684                }
685                // Handle case where list is initially flipped.
686                None if y_flipped => {
687                    base_handle.set_offset(point(offset.x, Pixels::MIN));
688                    scroll_state.y_flipped = y_flipped;
689                }
690                _ => {}
691            }
692        }
693        self
694    }
695}
696
697impl InteractiveElement for UniformList {
698    fn interactivity(&mut self) -> &mut crate::Interactivity {
699        &mut self.interactivity
700    }
701}
702
703#[cfg(test)]
704mod test {
705    use crate::TestAppContext;
706
707    #[gpui::test]
708    fn test_scroll_strategy_nearest(cx: &mut TestAppContext) {
709        use crate::{
710            Context, FocusHandle, ScrollStrategy, UniformListScrollHandle, Window, actions, div,
711            prelude::*, px, uniform_list,
712        };
713        use std::ops::Range;
714
715        actions!(example, [SelectNext, SelectPrev]);
716
717        struct TestView {
718            index: usize,
719            length: usize,
720            scroll_handle: UniformListScrollHandle,
721            focus_handle: FocusHandle,
722            visible_range: Range<usize>,
723        }
724
725        impl TestView {
726            pub fn select_next(
727                &mut self,
728                _: &SelectNext,
729                window: &mut Window,
730                _: &mut Context<Self>,
731            ) {
732                if self.index + 1 == self.length {
733                    self.index = 0
734                } else {
735                    self.index += 1;
736                }
737                self.scroll_handle
738                    .scroll_to_item(self.index, ScrollStrategy::Nearest);
739                window.refresh();
740            }
741
742            pub fn select_previous(
743                &mut self,
744                _: &SelectPrev,
745                window: &mut Window,
746                _: &mut Context<Self>,
747            ) {
748                if self.index == 0 {
749                    self.index = self.length - 1
750                } else {
751                    self.index -= 1;
752                }
753                self.scroll_handle
754                    .scroll_to_item(self.index, ScrollStrategy::Nearest);
755                window.refresh();
756            }
757        }
758
759        impl Render for TestView {
760            fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
761                div()
762                    .id("list-example")
763                    .track_focus(&self.focus_handle)
764                    .on_action(cx.listener(Self::select_next))
765                    .on_action(cx.listener(Self::select_previous))
766                    .size_full()
767                    .child(
768                        uniform_list(
769                            "entries",
770                            self.length,
771                            cx.processor(|this, range: Range<usize>, _window, _cx| {
772                                this.visible_range = range.clone();
773                                range
774                                    .map(|ix| div().id(ix).h(px(20.0)).child(format!("Item {ix}")))
775                                    .collect()
776                            }),
777                        )
778                        .track_scroll(self.scroll_handle.clone())
779                        .h(px(200.0)),
780                    )
781            }
782        }
783
784        let (view, cx) = cx.add_window_view(|window, cx| {
785            let focus_handle = cx.focus_handle();
786            window.focus(&focus_handle);
787            TestView {
788                scroll_handle: UniformListScrollHandle::new(),
789                index: 0,
790                focus_handle,
791                length: 47,
792                visible_range: 0..0,
793            }
794        });
795
796        // 10 out of 47 items are visible
797
798        // First 9 times selecting next item does not scroll
799        for ix in 1..10 {
800            cx.dispatch_action(SelectNext);
801            view.read_with(cx, |view, _| {
802                assert_eq!(view.index, ix);
803                assert_eq!(view.visible_range, 0..10);
804            })
805        }
806
807        // Now each time the list scrolls down by 1
808        for ix in 10..47 {
809            cx.dispatch_action(SelectNext);
810            view.read_with(cx, |view, _| {
811                assert_eq!(view.index, ix);
812                assert_eq!(view.visible_range, ix - 9..ix + 1);
813            })
814        }
815
816        // After the last item we move back to the start
817        cx.dispatch_action(SelectNext);
818        view.read_with(cx, |view, _| {
819            assert_eq!(view.index, 0);
820            assert_eq!(view.visible_range, 0..10);
821        });
822
823        // Return to the last element
824        cx.dispatch_action(SelectPrev);
825        view.read_with(cx, |view, _| {
826            assert_eq!(view.index, 46);
827            assert_eq!(view.visible_range, 37..47);
828        });
829
830        // First 9 times selecting previous does not scroll
831        for ix in (37..46).rev() {
832            cx.dispatch_action(SelectPrev);
833            view.read_with(cx, |view, _| {
834                assert_eq!(view.index, ix);
835                assert_eq!(view.visible_range, 37..47);
836            })
837        }
838
839        // Now each time the list scrolls up by 1
840        for ix in (0..37).rev() {
841            cx.dispatch_action(SelectPrev);
842            view.read_with(cx, |view, _| {
843                assert_eq!(view.index, ix);
844                assert_eq!(view.visible_range, ix..ix + 10);
845            })
846        }
847    }
848}