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