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}
 96
 97#[derive(Clone, Copy, Debug)]
 98#[allow(missing_docs)]
 99pub struct DeferredScrollToItem {
100    /// The item index to scroll to
101    pub item_index: usize,
102    /// The scroll strategy to use
103    pub strategy: ScrollStrategy,
104    /// The offset in number of items
105    pub offset: usize,
106    pub scroll_strict: bool,
107}
108
109#[derive(Clone, Debug, Default)]
110#[allow(missing_docs)]
111pub struct UniformListScrollState {
112    pub base_handle: ScrollHandle,
113    pub deferred_scroll_to_item: Option<DeferredScrollToItem>,
114    /// Size of the item, captured during last layout.
115    pub last_item_size: Option<ItemSize>,
116    /// Whether the list was vertically flipped during last layout.
117    pub y_flipped: bool,
118}
119
120#[derive(Copy, Clone, Debug, Default)]
121/// The size of the item and its contents.
122pub struct ItemSize {
123    /// The size of the item.
124    pub item: Size<Pixels>,
125    /// The size of the item's contents, which may be larger than the item itself,
126    /// if the item was bounded by a parent element.
127    pub contents: Size<Pixels>,
128}
129
130impl UniformListScrollHandle {
131    /// Create a new scroll handle to bind to a uniform list.
132    pub fn new() -> Self {
133        Self(Rc::new(RefCell::new(UniformListScrollState {
134            base_handle: ScrollHandle::new(),
135            deferred_scroll_to_item: None,
136            last_item_size: None,
137            y_flipped: false,
138        })))
139    }
140
141    /// Scroll the list so that the given item index is visible.
142    ///
143    /// This uses non-strict scrolling: if the item is already fully visible, no scrolling occurs.
144    /// If the item is out of view, it scrolls the minimum amount to bring it into view according
145    /// to the strategy.
146    pub fn scroll_to_item(&self, ix: usize, strategy: ScrollStrategy) {
147        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
148            item_index: ix,
149            strategy,
150            offset: 0,
151            scroll_strict: false,
152        });
153    }
154
155    /// Scroll the list so that the given item index is at scroll strategy position.
156    ///
157    /// This uses strict scrolling: the item will always be scrolled to match the strategy position,
158    /// even if it's already visible. Use this when you need precise positioning.
159    pub fn scroll_to_item_strict(&self, ix: usize, strategy: ScrollStrategy) {
160        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
161            item_index: ix,
162            strategy,
163            offset: 0,
164            scroll_strict: true,
165        });
166    }
167
168    /// Scroll the list to the given item index with an offset in number of items.
169    ///
170    /// This uses non-strict scrolling: if the item is already visible within the offset region,
171    /// no scrolling occurs.
172    ///
173    /// The offset parameter shrinks the effective viewport by the specified number of items
174    /// from the corresponding edge, then applies the scroll strategy within that reduced viewport:
175    /// - `ScrollStrategy::Top`: Shrinks from top, positions item at the new top
176    /// - `ScrollStrategy::Center`: Shrinks from top, centers item in the reduced viewport
177    /// - `ScrollStrategy::Bottom`: Shrinks from bottom, positions item at the new bottom
178    pub fn scroll_to_item_with_offset(&self, ix: usize, strategy: ScrollStrategy, offset: usize) {
179        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
180            item_index: ix,
181            strategy,
182            offset,
183            scroll_strict: false,
184        });
185    }
186
187    /// Scroll the list so that the given item index is at the exact scroll strategy position with an offset.
188    ///
189    /// This uses strict scrolling: the item will always be scrolled to match the strategy position,
190    /// even if it's already visible.
191    ///
192    /// The offset parameter shrinks the effective viewport by the specified number of items
193    /// from the corresponding edge, then applies the scroll strategy within that reduced viewport:
194    /// - `ScrollStrategy::Top`: Shrinks from top, positions item at the new top
195    /// - `ScrollStrategy::Center`: Shrinks from top, centers item in the reduced viewport
196    /// - `ScrollStrategy::Bottom`: Shrinks from bottom, positions item at the new bottom
197    pub fn scroll_to_item_strict_with_offset(
198        &self,
199        ix: usize,
200        strategy: ScrollStrategy,
201        offset: usize,
202    ) {
203        self.0.borrow_mut().deferred_scroll_to_item = Some(DeferredScrollToItem {
204            item_index: ix,
205            strategy,
206            offset,
207            scroll_strict: true,
208        });
209    }
210
211    /// Check if the list is flipped vertically.
212    pub fn y_flipped(&self) -> bool {
213        self.0.borrow().y_flipped
214    }
215
216    /// Get the index of the topmost visible child.
217    #[cfg(any(test, feature = "test-support"))]
218    pub fn logical_scroll_top_index(&self) -> usize {
219        let this = self.0.borrow();
220        this.deferred_scroll_to_item
221            .as_ref()
222            .map(|deferred| deferred.item_index)
223            .unwrap_or_else(|| this.base_handle.logical_scroll_top().0)
224    }
225
226    /// Checks if the list can be scrolled vertically.
227    pub fn is_scrollable(&self) -> bool {
228        if let Some(size) = self.0.borrow().last_item_size {
229            size.contents.height > size.item.height
230        } else {
231            false
232        }
233    }
234}
235
236impl Styled for UniformList {
237    fn style(&mut self) -> &mut StyleRefinement {
238        &mut self.interactivity.base_style
239    }
240}
241
242impl Element for UniformList {
243    type RequestLayoutState = UniformListFrameState;
244    type PrepaintState = Option<Hitbox>;
245
246    fn id(&self) -> Option<ElementId> {
247        self.interactivity.element_id.clone()
248    }
249
250    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
251        None
252    }
253
254    fn request_layout(
255        &mut self,
256        global_id: Option<&GlobalElementId>,
257        inspector_id: Option<&InspectorElementId>,
258        window: &mut Window,
259        cx: &mut App,
260    ) -> (LayoutId, Self::RequestLayoutState) {
261        let max_items = self.item_count;
262        let item_size = self.measure_item(None, window, cx);
263        let layout_id = self.interactivity.request_layout(
264            global_id,
265            inspector_id,
266            window,
267            cx,
268            |style, window, cx| match self.sizing_behavior {
269                ListSizingBehavior::Infer => {
270                    window.with_text_style(style.text_style().cloned(), |window| {
271                        window.request_measured_layout(
272                            style,
273                            move |known_dimensions, available_space, _window, _cx| {
274                                let desired_height = item_size.height * max_items;
275                                let width = known_dimensions.width.unwrap_or(match available_space
276                                    .width
277                                {
278                                    AvailableSpace::Definite(x) => x,
279                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
280                                        item_size.width
281                                    }
282                                });
283                                let height = match available_space.height {
284                                    AvailableSpace::Definite(height) => desired_height.min(height),
285                                    AvailableSpace::MinContent | AvailableSpace::MaxContent => {
286                                        desired_height
287                                    }
288                                };
289                                size(width, height)
290                            },
291                        )
292                    })
293                }
294                ListSizingBehavior::Auto => window
295                    .with_text_style(style.text_style().cloned(), |window| {
296                        window.request_layout(style, None, cx)
297                    }),
298            },
299        );
300
301        (
302            layout_id,
303            UniformListFrameState {
304                items: SmallVec::new(),
305                decorations: SmallVec::new(),
306            },
307        )
308    }
309
310    fn prepaint(
311        &mut self,
312        global_id: Option<&GlobalElementId>,
313        inspector_id: Option<&InspectorElementId>,
314        bounds: Bounds<Pixels>,
315        frame_state: &mut Self::RequestLayoutState,
316        window: &mut Window,
317        cx: &mut App,
318    ) -> Option<Hitbox> {
319        let style = self
320            .interactivity
321            .compute_style(global_id, None, window, cx);
322        let border = style.border_widths.to_pixels(window.rem_size());
323        let padding = style
324            .padding
325            .to_pixels(bounds.size.into(), window.rem_size());
326
327        let padded_bounds = Bounds::from_corners(
328            bounds.origin + point(border.left + padding.left, border.top + padding.top),
329            bounds.bottom_right()
330                - point(border.right + padding.right, border.bottom + padding.bottom),
331        );
332
333        let can_scroll_horizontally = matches!(
334            self.horizontal_sizing_behavior,
335            ListHorizontalSizingBehavior::Unconstrained
336        );
337
338        let longest_item_size = self.measure_item(None, window, cx);
339        let content_width = if can_scroll_horizontally {
340            padded_bounds.size.width.max(longest_item_size.width)
341        } else {
342            padded_bounds.size.width
343        };
344        let content_size = Size {
345            width: content_width,
346            height: longest_item_size.height * self.item_count + padding.top + padding.bottom,
347        };
348
349        let shared_scroll_offset = self.interactivity.scroll_offset.clone().unwrap();
350        let item_height = longest_item_size.height;
351        let shared_scroll_to_item = self.scroll_handle.as_mut().and_then(|handle| {
352            let mut handle = handle.0.borrow_mut();
353            handle.last_item_size = Some(ItemSize {
354                item: padded_bounds.size,
355                contents: content_size,
356            });
357            handle.deferred_scroll_to_item.take()
358        });
359
360        self.interactivity.prepaint(
361            global_id,
362            inspector_id,
363            bounds,
364            content_size,
365            window,
366            cx,
367            |style, mut scroll_offset, hitbox, window, cx| {
368                let border = style.border_widths.to_pixels(window.rem_size());
369                let padding = style
370                    .padding
371                    .to_pixels(bounds.size.into(), window.rem_size());
372
373                let padded_bounds = Bounds::from_corners(
374                    bounds.origin + point(border.left + padding.left, border.top),
375                    bounds.bottom_right() - point(border.right + padding.right, border.bottom),
376                );
377
378                let y_flipped = if let Some(scroll_handle) = &self.scroll_handle {
379                    let scroll_state = scroll_handle.0.borrow();
380                    scroll_state.y_flipped
381                } else {
382                    false
383                };
384
385                if self.item_count > 0 {
386                    let content_height =
387                        item_height * self.item_count + padding.top + padding.bottom;
388                    let is_scrolled_vertically = !scroll_offset.y.is_zero();
389                    let min_vertical_scroll_offset = padded_bounds.size.height - content_height;
390                    if is_scrolled_vertically && scroll_offset.y < min_vertical_scroll_offset {
391                        shared_scroll_offset.borrow_mut().y = min_vertical_scroll_offset;
392                        scroll_offset.y = min_vertical_scroll_offset;
393                    }
394
395                    let content_width = content_size.width + padding.left + padding.right;
396                    let is_scrolled_horizontally =
397                        can_scroll_horizontally && !scroll_offset.x.is_zero();
398                    if is_scrolled_horizontally && content_width <= padded_bounds.size.width {
399                        shared_scroll_offset.borrow_mut().x = Pixels::ZERO;
400                        scroll_offset.x = Pixels::ZERO;
401                    }
402
403                    if let Some(deferred_scroll) = shared_scroll_to_item {
404                        let mut ix = deferred_scroll.item_index;
405                        if y_flipped {
406                            ix = self.item_count.saturating_sub(ix + 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 * ix + padding.top;
411                        let item_bottom = item_top + item_height;
412                        let scroll_top = -updated_scroll_offset.y;
413                        let offset_pixels = item_height * deferred_scroll.offset;
414                        let mut scrolled_to_top = false;
415
416                        if item_top < scroll_top + padding.top + offset_pixels {
417                            scrolled_to_top = true;
418                            updated_scroll_offset.y = -(item_top) + padding.top + offset_pixels;
419                        } else if item_bottom > scroll_top + list_height - padding.bottom {
420                            scrolled_to_top = true;
421                            updated_scroll_offset.y = -(item_bottom - list_height) - padding.bottom;
422                        }
423
424                        if deferred_scroll.scroll_strict
425                            || (scrolled_to_top
426                                && (item_top < scroll_top + offset_pixels
427                                    || item_bottom > scroll_top + list_height))
428                        {
429                            match deferred_scroll.strategy {
430                                ScrollStrategy::Top => {
431                                    updated_scroll_offset.y = -(item_top - offset_pixels)
432                                        .max(Pixels::ZERO)
433                                        .min(content_height - list_height)
434                                        .max(Pixels::ZERO);
435                                }
436                                ScrollStrategy::Center => {
437                                    let item_center = item_top + item_height / 2.0;
438
439                                    let viewport_height = list_height - offset_pixels;
440                                    let viewport_center = offset_pixels + viewport_height / 2.0;
441                                    let target_scroll_top = item_center - viewport_center;
442
443                                    updated_scroll_offset.y = -target_scroll_top
444                                        .max(Pixels::ZERO)
445                                        .min(content_height - list_height)
446                                        .max(Pixels::ZERO);
447                                }
448                                ScrollStrategy::Bottom => {
449                                    updated_scroll_offset.y = -(item_bottom - list_height
450                                        + offset_pixels)
451                                        .max(Pixels::ZERO)
452                                        .min(content_height - list_height)
453                                        .max(Pixels::ZERO);
454                                }
455                            }
456                        }
457                        scroll_offset = *updated_scroll_offset
458                    }
459
460                    let first_visible_element_ix =
461                        (-(scroll_offset.y + padding.top) / item_height).floor() as usize;
462                    let last_visible_element_ix = ((-scroll_offset.y + padded_bounds.size.height)
463                        / item_height)
464                        .ceil() as usize;
465
466                    let visible_range = first_visible_element_ix
467                        ..cmp::min(last_visible_element_ix, self.item_count);
468
469                    let items = if y_flipped {
470                        let flipped_range = self.item_count.saturating_sub(visible_range.end)
471                            ..self.item_count.saturating_sub(visible_range.start);
472                        let mut items = (self.render_items)(flipped_range, window, cx);
473                        items.reverse();
474                        items
475                    } else {
476                        (self.render_items)(visible_range.clone(), window, cx)
477                    };
478
479                    let content_mask = ContentMask { bounds };
480                    window.with_content_mask(Some(content_mask), |window| {
481                        for (mut item, ix) in items.into_iter().zip(visible_range.clone()) {
482                            let item_origin = padded_bounds.origin
483                                + point(
484                                    if can_scroll_horizontally {
485                                        scroll_offset.x + padding.left
486                                    } else {
487                                        scroll_offset.x
488                                    },
489                                    item_height * ix + scroll_offset.y + padding.top,
490                                );
491                            let available_width = if can_scroll_horizontally {
492                                padded_bounds.size.width + scroll_offset.x.abs()
493                            } else {
494                                padded_bounds.size.width
495                            };
496                            let available_space = size(
497                                AvailableSpace::Definite(available_width),
498                                AvailableSpace::Definite(item_height),
499                            );
500                            item.layout_as_root(available_space, window, cx);
501                            item.prepaint_at(item_origin, window, cx);
502                            frame_state.items.push(item);
503                        }
504
505                        let bounds = Bounds::new(
506                            padded_bounds.origin
507                                + point(
508                                    if can_scroll_horizontally {
509                                        scroll_offset.x + padding.left
510                                    } else {
511                                        scroll_offset.x
512                                    },
513                                    scroll_offset.y + padding.top,
514                                ),
515                            padded_bounds.size,
516                        );
517                        for decoration in &self.decorations {
518                            let mut decoration = decoration.as_ref().compute(
519                                visible_range.clone(),
520                                bounds,
521                                scroll_offset,
522                                item_height,
523                                self.item_count,
524                                window,
525                                cx,
526                            );
527                            let available_space = size(
528                                AvailableSpace::Definite(bounds.size.width),
529                                AvailableSpace::Definite(bounds.size.height),
530                            );
531                            decoration.layout_as_root(available_space, window, cx);
532                            decoration.prepaint_at(bounds.origin, window, cx);
533                            frame_state.decorations.push(decoration);
534                        }
535                    });
536                }
537
538                hitbox
539            },
540        )
541    }
542
543    fn paint(
544        &mut self,
545        global_id: Option<&GlobalElementId>,
546        inspector_id: Option<&InspectorElementId>,
547        bounds: Bounds<crate::Pixels>,
548        request_layout: &mut Self::RequestLayoutState,
549        hitbox: &mut Option<Hitbox>,
550        window: &mut Window,
551        cx: &mut App,
552    ) {
553        self.interactivity.paint(
554            global_id,
555            inspector_id,
556            bounds,
557            hitbox.as_ref(),
558            window,
559            cx,
560            |_, window, cx| {
561                for item in &mut request_layout.items {
562                    item.paint(window, cx);
563                }
564                for decoration in &mut request_layout.decorations {
565                    decoration.paint(window, cx);
566                }
567            },
568        )
569    }
570}
571
572impl IntoElement for UniformList {
573    type Element = Self;
574
575    fn into_element(self) -> Self::Element {
576        self
577    }
578}
579
580/// A decoration for a [`UniformList`]. This can be used for various things,
581/// such as rendering indent guides, or other visual effects.
582pub trait UniformListDecoration {
583    /// Compute the decoration element, given the visible range of list items,
584    /// the bounds of the list, and the height of each item.
585    fn compute(
586        &self,
587        visible_range: Range<usize>,
588        bounds: Bounds<Pixels>,
589        scroll_offset: Point<Pixels>,
590        item_height: Pixels,
591        item_count: usize,
592        window: &mut Window,
593        cx: &mut App,
594    ) -> AnyElement;
595}
596
597impl<T: UniformListDecoration + 'static> UniformListDecoration for Entity<T> {
598    fn compute(
599        &self,
600        visible_range: Range<usize>,
601        bounds: Bounds<Pixels>,
602        scroll_offset: Point<Pixels>,
603        item_height: Pixels,
604        item_count: usize,
605        window: &mut Window,
606        cx: &mut App,
607    ) -> AnyElement {
608        self.update(cx, |inner, cx| {
609            inner.compute(
610                visible_range,
611                bounds,
612                scroll_offset,
613                item_height,
614                item_count,
615                window,
616                cx,
617            )
618        })
619    }
620}
621
622impl UniformList {
623    /// Selects a specific list item for measurement.
624    pub fn with_width_from_item(mut self, item_index: Option<usize>) -> Self {
625        self.item_to_measure_index = item_index.unwrap_or(0);
626        self
627    }
628
629    /// Sets the sizing behavior, similar to the `List` element.
630    pub const fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
631        self.sizing_behavior = behavior;
632        self
633    }
634
635    /// Sets the horizontal sizing behavior, controlling the way list items laid out horizontally.
636    /// With [`ListHorizontalSizingBehavior::Unconstrained`] behavior, every item and the list itself will
637    /// have the size of the widest item and lay out pushing the `end_slot` to the right end.
638    pub fn with_horizontal_sizing_behavior(
639        mut self,
640        behavior: ListHorizontalSizingBehavior,
641    ) -> Self {
642        self.horizontal_sizing_behavior = behavior;
643        match behavior {
644            ListHorizontalSizingBehavior::FitList => {
645                self.interactivity.base_style.overflow.x = None;
646            }
647            ListHorizontalSizingBehavior::Unconstrained => {
648                self.interactivity.base_style.overflow.x = Some(Overflow::Scroll);
649            }
650        }
651        self
652    }
653
654    /// Adds a decoration element to the list.
655    pub fn with_decoration(mut self, decoration: impl UniformListDecoration + 'static) -> Self {
656        self.decorations.push(Box::new(decoration));
657        self
658    }
659
660    fn measure_item(
661        &self,
662        list_width: Option<Pixels>,
663        window: &mut Window,
664        cx: &mut App,
665    ) -> Size<Pixels> {
666        if self.item_count == 0 {
667            return Size::default();
668        }
669
670        let item_ix = cmp::min(self.item_to_measure_index, self.item_count - 1);
671        let mut items = (self.render_items)(item_ix..item_ix + 1, window, cx);
672        let Some(mut item_to_measure) = items.pop() else {
673            return Size::default();
674        };
675        let available_space = size(
676            list_width.map_or(AvailableSpace::MinContent, |width| {
677                AvailableSpace::Definite(width)
678            }),
679            AvailableSpace::MinContent,
680        );
681        item_to_measure.layout_as_root(available_space, window, cx)
682    }
683
684    /// Track and render scroll state of this list with reference to the given scroll handle.
685    pub fn track_scroll(mut self, handle: UniformListScrollHandle) -> Self {
686        self.interactivity.tracked_scroll_handle = Some(handle.0.borrow().base_handle.clone());
687        self.scroll_handle = Some(handle);
688        self
689    }
690
691    /// Sets whether the list is flipped vertically, such that item 0 appears at the bottom.
692    pub fn y_flipped(mut self, y_flipped: bool) -> Self {
693        if let Some(ref scroll_handle) = self.scroll_handle {
694            let mut scroll_state = scroll_handle.0.borrow_mut();
695            let mut base_handle = &scroll_state.base_handle;
696            let offset = base_handle.offset();
697            match scroll_state.last_item_size {
698                Some(last_size) if scroll_state.y_flipped != y_flipped => {
699                    let new_y_offset =
700                        -(offset.y + last_size.contents.height - last_size.item.height);
701                    base_handle.set_offset(point(offset.x, new_y_offset));
702                    scroll_state.y_flipped = y_flipped;
703                }
704                // Handle case where list is initially flipped.
705                None if y_flipped => {
706                    base_handle.set_offset(point(offset.x, Pixels::MIN));
707                    scroll_state.y_flipped = y_flipped;
708                }
709                _ => {}
710            }
711        }
712        self
713    }
714}
715
716impl InteractiveElement for UniformList {
717    fn interactivity(&mut self) -> &mut crate::Interactivity {
718        &mut self.interactivity
719    }
720}